section
stringlengths
2
30
filename
stringlengths
1
82
text
stringlengths
783
28M
feminout
importZ88Mesh
# *************************************************************************** # * Copyright (c) 2016 Bernd Hahnebach <bernd@bimstatik.org> * # * * # * This file is part of the FreeCAD CAx development system. * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** __title__ = "Mesh import and export for Z88 mesh file format" __author__ = "Bernd Hahnebach" __url__ = "https://www.freecad.org" ## @package importZ88Mesh # \ingroup FEM # \brief FreeCAD Z88 Mesh reader and writer for FEM workbench import os import FreeCAD from femmesh import meshtools from FreeCAD import Console # ************************************************************************************************ # ********* generic FreeCAD import and export methods ******************************************** # names are fix given from FreeCAD, these methods are called from FreeCAD # they are set in FEM modules Init.py pyopen = open def open(filename): """called when freecad opens a file a FEM mesh object is created in a new document""" docname = os.path.splitext(os.path.basename(filename))[0] return insert(filename, docname) def insert(filename, docname): """called when freecad wants to import a file a FEM mesh object is created in a existing document""" try: doc = FreeCAD.getDocument(docname) except NameError: doc = FreeCAD.newDocument(docname) FreeCAD.ActiveDocument = doc import_z88_mesh(filename, docname) return doc def export(objectslist, filename): "called when freecad exports a file" if len(objectslist) != 1: Console.PrintError("This exporter can only export one object.\n") return obj = objectslist[0] if not obj.isDerivedFrom("Fem::FemMeshObject"): Console.PrintError("No FEM mesh object selected.\n") return femnodes_mesh = obj.FemMesh.Nodes femelement_table = meshtools.get_femelement_table(obj.FemMesh) z88_element_type = get_z88_element_type(obj.FemMesh, femelement_table) f = pyopen(filename, "w") write_z88_mesh_to_file(femnodes_mesh, femelement_table, z88_element_type, f) f.close() # ************************************************************************************************ # ********* module specific methods ************************************************************** # reader: # - a method uses a FemMesh instance, creates the FreeCAD document object and returns this object # - a method creates and returns a FemMesh (no FreeCAD document object) out of the FEM mesh dict # - a method reads the data from the mesh file or converts data and returns FEM mesh dictionary # # writer: # - a method directly writes a FemMesh to the mesh file # - a method takes a file handle, mesh data and writes to the file handle # ********* reader ******************************************************************************* def import_z88_mesh(filename, analysis=None, docname=None): """read a FEM mesh from a Z88 mesh file and insert a FreeCAD FEM Mesh object in the ActiveDocument """ try: doc = FreeCAD.getDocument(docname) except NameError: try: doc = FreeCAD.ActiveDocument except NameError: doc = FreeCAD.newDocument() FreeCAD.ActiveDocument = doc mesh_name = os.path.basename(os.path.splitext(filename)[0]) femmesh = read(filename) if femmesh: mesh_object = doc.addObject("Fem::FemMeshObject", mesh_name) mesh_object.FemMesh = femmesh return mesh_object def read(filename): """read a FemMesh from a Z88 mesh file and return the FemMesh""" # no document object is created, just the FemMesh is returned mesh_data = read_z88_mesh(filename) from . import importToolsFem return importToolsFem.make_femmesh(mesh_data) def read_z88_mesh(z88_mesh_input): """reads a z88 mesh file z88i1.txt (Z88OSV14) or z88structure.txt (Z88AuroraV3) and extracts the nodes and elements """ nodes = {} elements_hexa8 = {} elements_penta6 = {} elements_tetra4 = {} elements_tetra10 = {} elements_penta15 = {} elements_hexa20 = {} elements_tria3 = {} elements_tria6 = {} elements_quad4 = {} elements_quad8 = {} elements_seg2 = {} elements_seg3 = {} input_continues = False # elem = -1 z88_element_type = 0 z88_mesh_file = pyopen(z88_mesh_input, "r") mesh_info = z88_mesh_file.readline().strip().split() nodes_dimension = int(mesh_info[0]) nodes_count = int(mesh_info[1]) elements_count = int(mesh_info[2]) kflag = int(mesh_info[4]) # for non rotational elements is --> kflag = 0 --> cartesian, kflag = 1 polar coordinates if kflag: Console.PrintError( "KFLAG = 1, Rotational coordinates not supported at the moment\n" ) return {} nodes_first_line = 2 # first line is mesh_info nodes_last_line = nodes_count + 1 elemts_first_line = nodes_last_line + 1 elements_last_line = elemts_first_line - 1 + elements_count * 2 Console.PrintLog("{}\n".format(nodes_count)) Console.PrintLog("{}\n".format(elements_count)) Console.PrintLog("{}\n".format(nodes_last_line)) Console.PrintLog("{}\n".format(elemts_first_line)) Console.PrintLog("{}\n".format(elements_last_line)) z88_mesh_file.seek(0) # go back to the beginning of the file for no, line in enumerate(z88_mesh_file): lno = no + 1 linecolumns = line.split() if lno >= nodes_first_line and lno <= nodes_last_line: # node line node_no = int(linecolumns[0]) node_x = float(linecolumns[2]) node_y = float(linecolumns[3]) if nodes_dimension == 2: node_z = 0.0 elif nodes_dimension == 3: node_z = float(linecolumns[4]) nodes[node_no] = FreeCAD.Vector(node_x, node_y, node_z) if lno >= elemts_first_line and lno <= elements_last_line: # first element line if not input_continues: elem_no = int(linecolumns[0]) z88_element_type = int(linecolumns[1]) input_continues = True # second element line elif input_continues: # not supported elements if z88_element_type == 8: # torus8 Console.PrintError("Z88 Element No. 8, torus8\n") Console.PrintError( "Rotational elements are not supported at the moment\n" ) return {} elif z88_element_type == 12: # torus12 Console.PrintError("Z88 Element No. 12, torus12\n") Console.PrintError( "Rotational elements are not supported at the moment\n" ) return {} elif z88_element_type == 15: # torus6 Console.PrintError("Z88 Element No. 15, torus6\n") Console.PrintError( "Rotational elements are not supported at the moment\n" ) return {} elif z88_element_type == 19: # platte16 Console.PrintError("Z88 Element No. 19, platte16\n") Console.PrintError("Not supported at the moment\n") return {} elif z88_element_type == 21: # schale16, mixture made from hexa8 and hexa20 (thickness is linear) Console.PrintError("Z88 Element No. 21, schale16\n") Console.PrintError("Not supported at the moment\n") return {} elif z88_element_type == 22: # schale12, mixtrue made from prism6 and prism15 (thickness is linear) Console.PrintError("Z88 Element No. 22, schale12\n") Console.PrintError("Not supported at the moment\n") return {} # supported elements elif ( z88_element_type == 2 or z88_element_type == 4 or z88_element_type == 5 or z88_element_type == 9 or z88_element_type == 13 or z88_element_type == 25 ): # stab4 or stab5 or welle5 or beam13 or beam25 Z88 --> seg2 FreeCAD # N1, N2 nd1 = int(linecolumns[0]) nd2 = int(linecolumns[1]) elements_seg2[elem_no] = (nd1, nd2) input_continues = False elif ( z88_element_type == 3 or z88_element_type == 14 or z88_element_type == 24 ): # scheibe3 or scheibe14 or schale24 Z88 --> tria6 FreeCAD # N1, N2, N3, N4, N5, N6 nd1 = int(linecolumns[0]) nd2 = int(linecolumns[1]) nd3 = int(linecolumns[2]) nd4 = int(linecolumns[3]) nd5 = int(linecolumns[4]) nd6 = int(linecolumns[5]) elements_tria6[elem_no] = (nd1, nd2, nd3, nd4, nd5, nd6) input_continues = False elif ( z88_element_type == 7 or z88_element_type == 20 or z88_element_type == 23 ): # scheibe7 or platte20 or schale23 Z88 --> quad8 FreeCAD # N1, N2, N3, N4, N5, N6, N7, N8 nd1 = int(linecolumns[0]) nd2 = int(linecolumns[1]) nd3 = int(linecolumns[2]) nd4 = int(linecolumns[3]) nd5 = int(linecolumns[4]) nd6 = int(linecolumns[5]) nd7 = int(linecolumns[6]) nd8 = int(linecolumns[7]) elements_quad8[elem_no] = (nd1, nd2, nd3, nd4, nd5, nd6, nd7, nd8) input_continues = False elif z88_element_type == 17: # volume17 Z88 --> tetra4 FreeCAD # N4, N2, N3, N1 nd1 = int(linecolumns[0]) nd2 = int(linecolumns[1]) nd3 = int(linecolumns[2]) nd4 = int(linecolumns[3]) elements_tetra4[elem_no] = (nd4, nd2, nd3, nd1) input_continues = False elif z88_element_type == 16: # volume16 Z88 --> tetra10 FreeCAD # N1, N2, N4, N3, N5, N8, N10, N7, N6, N9 # Z88 to FC is different as FC to Z88 nd1 = int(linecolumns[0]) nd2 = int(linecolumns[1]) nd3 = int(linecolumns[2]) nd4 = int(linecolumns[3]) nd5 = int(linecolumns[4]) nd6 = int(linecolumns[5]) nd7 = int(linecolumns[6]) nd8 = int(linecolumns[7]) nd9 = int(linecolumns[8]) nd10 = int(linecolumns[9]) elements_tetra10[elem_no] = ( nd1, nd2, nd4, nd3, nd5, nd8, nd10, nd7, nd6, nd9, ) input_continues = False elif z88_element_type == 1: # volume1 Z88 --> hexa8 FreeCAD # N1, N2, N3, N4, N5, N6, N7, N8 nd1 = int(linecolumns[0]) nd2 = int(linecolumns[1]) nd3 = int(linecolumns[2]) nd4 = int(linecolumns[3]) nd5 = int(linecolumns[4]) nd6 = int(linecolumns[5]) nd7 = int(linecolumns[6]) nd8 = int(linecolumns[7]) elements_hexa8[elem_no] = (nd1, nd2, nd3, nd4, nd5, nd6, nd7, nd8) input_continues = False elif z88_element_type == 10: # volume10 Z88 --> hexa20 FreeCAD # N2, N3, N4, N1, N6, N7, N8, N5, N10, N11 # N12, N9, N14, N15, N16, N13, N18, N19, N20, N17 # or turn by 90 degree and they match ! # N1, N2, N3, N4, N5, N6, N7, N8, N9, N10 # N11, N12, N13, N14, N15, N16, N17, N18, N19, N20 nd1 = int(linecolumns[0]) nd2 = int(linecolumns[1]) nd3 = int(linecolumns[2]) nd4 = int(linecolumns[3]) nd5 = int(linecolumns[4]) nd6 = int(linecolumns[5]) nd7 = int(linecolumns[6]) nd8 = int(linecolumns[7]) nd9 = int(linecolumns[8]) nd10 = int(linecolumns[9]) nd11 = int(linecolumns[10]) nd12 = int(linecolumns[11]) nd13 = int(linecolumns[12]) nd14 = int(linecolumns[13]) nd15 = int(linecolumns[14]) nd16 = int(linecolumns[15]) nd17 = int(linecolumns[16]) nd18 = int(linecolumns[17]) nd19 = int(linecolumns[18]) nd20 = int(linecolumns[19]) elements_hexa20[elem_no] = ( nd1, nd2, nd3, nd4, nd5, nd6, nd7, nd8, nd9, nd10, nd11, nd12, nd13, nd14, nd15, nd16, nd17, nd18, nd19, nd20, ) input_continues = False # unknown elements # some examples have -1 for some teaching reasons to show some other stuff else: Console.PrintError("Unknown element\n") return {} for n in nodes: Console.PrintLog(str(n) + " " + str(nodes[n]) + "\n") for e in elements_tria6: Console.PrintLog(str(e) + " " + str(elements_tria6[e]) + "\n") FreeCAD.Console.PrintLog("\n") z88_mesh_file.close() return { "Nodes": nodes, "Seg2Elem": elements_seg2, "Seg3Elem": elements_seg3, "Tria3Elem": elements_tria3, "Tria6Elem": elements_tria6, "Quad4Elem": elements_quad4, "Quad8Elem": elements_quad8, "Tetra4Elem": elements_tetra4, "Tetra10Elem": elements_tetra10, "Hexa8Elem": elements_hexa8, "Hexa20Elem": elements_hexa20, "Penta6Elem": elements_penta6, "Penta15Elem": elements_penta15, } # ********* writer ******************************************************************************* def write(fem_mesh, filename): """directly write a FemMesh to a Z88 mesh file format fem_mesh: a FemMesh""" if not fem_mesh.isDerivedFrom("Fem::FemMesh"): Console.PrintError("Not a FemMesh was given as parameter.\n") return femnodes_mesh = fem_mesh.Nodes femelement_table = meshtools.get_femelement_table(fem_mesh) z88_element_type = get_z88_element_type(fem_mesh, femelement_table) f = pyopen(filename, "w") write_z88_mesh_to_file(femnodes_mesh, femelement_table, z88_element_type, f) f.close() def write_z88_mesh_to_file(femnodes_mesh, femelement_table, z88_element_type, f): node_dimension = 3 # 2 for 2D not supported if ( z88_element_type == 4 or z88_element_type == 17 or z88_element_type == 16 or z88_element_type == 1 or z88_element_type == 10 ): node_dof = 3 elif z88_element_type == 23 or z88_element_type == 24: node_dof = 6 # schalenelemente else: Console.PrintError("Error: wrong z88_element_type.\n") return node_count = len(femnodes_mesh) element_count = len(femelement_table) dofs = node_dof * node_count unknown_flag = 0 written_by = "written by FreeCAD" # first line, some z88 specific stuff f.write( "{0} {1} {2} {3} {4} {5}\n".format( node_dimension, node_count, element_count, dofs, unknown_flag, written_by ) ) # nodes for node in femnodes_mesh: vec = femnodes_mesh[node] f.write( "{0} {1} {2:.6f} {3:.6f} {4:.6f}\n".format( node, node_dof, vec.x, vec.y, vec.z ) ) # elements for element in femelement_table: # z88_element_type is checked for every element # but mixed elements are not supported up to date n = femelement_table[element] if ( z88_element_type == 2 or z88_element_type == 4 or z88_element_type == 5 or z88_element_type == 9 or z88_element_type == 13 or z88_element_type == 25 ): # seg2 FreeCAD --> stab4 Z88 # N1, N2 f.write("{0} {1}\n".format(element, z88_element_type)) f.write("{0} {1}\n".format(n[0], n[1])) elif z88_element_type == 3 or z88_element_type == 14 or z88_element_type == 24: # tria6 FreeCAD --> schale24 Z88 # N1, N2, N3, N4, N5, N6 f.write("{0} {1}\n".format(element, z88_element_type)) f.write( "{0} {1} {2} {3} {4} {5}\n".format(n[0], n[1], n[2], n[3], n[4], n[5]) ) elif z88_element_type == 7 or z88_element_type == 20 or z88_element_type == 23: # quad8 FreeCAD --> schale23 Z88 # N1, N2, N3, N4, N5, N6, N7, N8 f.write("{0} {1}\n".format(element, z88_element_type)) f.write( "{0} {1} {2} {3} {4} {5} {6} {7}\n".format( n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7] ) ) elif z88_element_type == 17: # tetra4 FreeCAD --> volume17 Z88 # N4, N2, N3, N1 f.write("{0} {1}\n".format(element, z88_element_type)) f.write("{0} {1} {2} {3}\n".format(n[3], n[1], n[2], n[0])) elif z88_element_type == 16: # tetra10 FreeCAD --> volume16 Z88 # N1, N2, N4, N3, N5, N9, N8, N6, N10, N7, FC to Z88 is different as Z88 to FC f.write("{0} {1}\n".format(element, z88_element_type)) f.write( "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}\n".format( n[0], n[1], n[3], n[2], n[4], n[8], n[7], n[5], n[9], n[6] ) ) elif z88_element_type == 1: # hexa8 FreeCAD --> volume1 Z88 # N1, N2, N3, N4, N5, N6, N7, N8 f.write("{0} {1}\n".format(element, z88_element_type)) f.write( "{0} {1} {2} {3} {4} {5} {6} {7}\n".format( n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7] ) ) elif z88_element_type == 10: # hexa20 FreeCAD --> volume10 Z88 # N2, N3, N4, N1, N6, N7, N8, N5, N10, N11 # N12, N9, N14, N15, N16, N13, N18, N19, N20, N17 # or turn by 90 degree and they match ! # N1, N2, N3, N4, N5, N6, N7, N8, N9, N10 # N11, N12, N13, N14, N15, N16, N17, N18, N19, N20 f.write("{0} {1}\n".format(element, z88_element_type)) f.write( "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} " "{10} {11} {12} {13} {14} {15} {16} {17} {18} {19}\n".format( n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8], n[9], n[10], n[11], n[12], n[13], n[14], n[15], n[16], n[17], n[18], n[19], ) ) else: Console.PrintError( "Writing of Z88 elementtype {0} not supported.\n".format( z88_element_type ) ) # TODO support schale12 (made from prism15) and schale16 (made from hexa20) return # Helper def get_z88_element_type(femmesh, femelement_table=None): return z88_ele_types[meshtools.get_femmesh_eletype(femmesh, femelement_table)] z88_ele_types = { "tetra4": 17, "tetra10": 16, "hexa8": 1, "hexa20": 10, "tria3": 0, # no tria3 available in Z88 "tria6": 24, "quad4": 0, # no quad4 available in Z88 "quad8": 23, "seg2": 4, # 3D Truss element "seg3": 4, # 3D Truss element "None": 0, }
streamripper
srprefs
# Copyright (C) 2006 Adam Olsen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 1, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import os from xl.nls import gettext as _ from xlgui.preferences import widgets name = _("Streamripper") basedir = os.path.dirname(os.path.realpath(__file__)) ui = os.path.join(basedir, "streamripper.ui") class SavePreference(widgets.DirPreference): default = os.getenv("HOME") name = "plugin/streamripper/save_location" class PortPreference(widgets.Preference): default = "8888" name = "plugin/streamripper/relay_port" class FilePreference(widgets.CheckPreference): default = False name = "plugin/streamripper/single_file" class DeletePreference(widgets.CheckPreference): default = True name = "plugin/streamripper/delete_incomplete"
gui
quickchoice
# This file is part of MyPaint. # Copyright (C) 2013-2018 by the MyPaint Development Team. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. """Widgets and popup dialogs for making quick choices""" ## Imports from __future__ import division, print_function import abc import gui.colortools from lib.gibindings import Gtk from lib.observable import event from lib.pycompat import add_metaclass from . import brushmanager, brushselectionwindow, spinbox, widgets, windowing from .pixbuflist import PixbufList ## Module consts _DEFAULT_PREFS_ID = "default" ## Interfaces @add_metaclass(abc.ABCMeta) class Advanceable: """Interface for choosers which can be advanced by pressing keys. Advancing happens if the chooser is already visible and its key is pressed again. This can happen repeatedly. The actual action performed is up to the implementation: advancing some some choosers may move them forward through pages of alternatives, while other choosers may actually change a brush setting as they advance. """ @abc.abstractmethod def advance(self): """Advances the chooser to the next page or choice. Choosers should remain open when their advance() method is invoked. The actual action performed is up to the concrete implementation: see the class docs. """ ## Class defs class QuickBrushChooser(Gtk.VBox): """A quick chooser widget for brushes""" ## Class constants _PREFS_KEY_TEMPLATE = "brush_chooser.%s.selected_group" ICON_SIZE = 48 ## Method defs def __init__(self, app, prefs_id=_DEFAULT_PREFS_ID): """Initialize""" Gtk.VBox.__init__(self) self.app = app self.bm = app.brushmanager self._prefs_key = self._PREFS_KEY_TEMPLATE % (prefs_id,) active_group_name = app.preferences.get(self._prefs_key, None) model = self._make_groups_sb_model() self.groups_sb = spinbox.ItemSpinBox( model, self._groups_sb_changed_cb, active_group_name ) active_group_name = self.groups_sb.get_value() brushes = self.bm.get_group_brushes(active_group_name) self.brushlist = PixbufList( brushes, self.ICON_SIZE, self.ICON_SIZE, namefunc=brushselectionwindow.managedbrush_namefunc, pixbuffunc=brushselectionwindow.managedbrush_pixbuffunc, idfunc=brushselectionwindow.managedbrush_idfunc, ) self.brushlist.dragging_allowed = False self.bm.groups_changed += self._groups_changed_cb self.bm.brushes_changed += self._brushes_changed_cb self.brushlist.item_selected += self._item_selected_cb scrolledwin = Gtk.ScrolledWindow() scrolledwin.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.ALWAYS) scrolledwin.add(self.brushlist) w = int(self.ICON_SIZE * 4.5) h = int(self.ICON_SIZE * 5.0) scrolledwin.set_min_content_width(w) scrolledwin.set_min_content_height(h) scrolledwin.get_child().set_size_request(w, h) self.pack_start(self.groups_sb, False, False, 0) self.pack_start(scrolledwin, True, True, 0) self.set_spacing(widgets.SPACING_TIGHT) def _item_selected_cb(self, pixbuf_list, brush): """Internal: call brush_selected event when an item is chosen""" self.brush_selected(brush) @event def brush_selected(self, brush): """Event: a brush was selected :param brush: The newly chosen brush """ def _make_groups_sb_model(self): """Internal: create the model for the group choice spinbox""" group_names = sorted(self.bm.groups.keys()) model = [] for name in group_names: label_text = brushmanager.translate_group_name(name) model.append((name, label_text)) return model def _groups_changed_cb(self, bm): """Internal: update the spinbox model at the top of the widget""" model = self._make_groups_sb_model() self.groups_sb.set_model(model) # In case the group has been deleted and recreated, we do this: group_name = self.groups_sb.get_value() group_brushes = self.bm.groups.get(group_name, []) self.brushlist.itemlist = group_brushes self.brushlist.update() # See https://github.com/mypaint/mypaint/issues/654 def _brushes_changed_cb(self, bm, brushes): """Internal: update the PixbufList if its group was changed.""" # CARE: this might be called in response to the group being deleted. # Don't recreate it by accident. group_name = self.groups_sb.get_value() group_brushes = self.bm.groups.get(group_name) if brushes is group_brushes: self.brushlist.update() def _groups_sb_changed_cb(self, group_name): """Internal: update the list of brush icons when the group changes""" self.app.preferences[self._prefs_key] = group_name group_brushes = self.bm.groups.get(group_name, []) self.brushlist.itemlist = group_brushes self.brushlist.update() def advance(self): """Advances to the next page of brushes.""" self.groups_sb.next() class BrushChooserPopup(windowing.ChooserPopup): """Speedy brush chooser popup""" def __init__(self, app, prefs_id=_DEFAULT_PREFS_ID): """Initialize. :param gui.application.Application app: main app instance :param unicode prefs_id: prefs identifier for the chooser The prefs identifier forms part of preferences key which store layout and which page of the chooser is selected. It should follow the same syntax rules as Python simple identifiers. """ windowing.ChooserPopup.__init__( self, app=app, actions=[ "ColorChooserPopup", "ColorChooserPopupFastSubset", "BrushChooserPopup", ], config_name="brush_chooser.%s" % (prefs_id,), ) self._chosen_brush = None self._chooser = QuickBrushChooser(app, prefs_id=prefs_id) self._chooser.brush_selected += self._brush_selected_cb bl = self._chooser.brushlist bl.connect("button-release-event", self._brushlist_button_release_cb) self.add(self._chooser) def _brush_selected_cb(self, chooser, brush): """Internal: update the response brush when an icon is clicked""" self._chosen_brush = brush def _brushlist_button_release_cb(self, *junk): """Internal: send an accept response on a button release We only send the response (and close the dialog) on button release to avoid accidental dabs with the stylus. """ if self._chosen_brush is not None: bm = self.app.brushmanager bm.select_brush(self._chosen_brush) self.hide() self._chosen_brush = None def advance(self): """Advances to the next page of brushes.""" self._chooser.advance() class QuickColorChooser(Gtk.VBox): """A quick chooser widget for colors""" ## Class constants _PREFS_KEY_TEMPLATE = "color_chooser.%s.selected_adjuster" _ALL_ADJUSTER_CLASSES = [ gui.colortools.HCYWheelTool, gui.colortools.HSVWheelTool, gui.colortools.PaletteTool, gui.colortools.HSVCubeTool, gui.colortools.HSVSquareTool, gui.colortools.ComponentSlidersTool, gui.colortools.RingsColorChangerTool, gui.colortools.WashColorChangerTool, gui.colortools.CrossedBowlColorChangerTool, ] _SINGLE_CLICK_ADJUSTER_CLASSES = [ gui.colortools.PaletteTool, gui.colortools.WashColorChangerTool, gui.colortools.CrossedBowlColorChangerTool, ] def __init__(self, app, prefs_id=_DEFAULT_PREFS_ID, single_click=False): Gtk.VBox.__init__(self) self._app = app self._spinbox_model = [] self._adjs = {} self._pages = [] mgr = app.brush_color_manager if single_click: adjuster_classes = self._SINGLE_CLICK_ADJUSTER_CLASSES else: adjuster_classes = self._ALL_ADJUSTER_CLASSES for page_class in adjuster_classes: name = page_class.__name__ page = page_class() self._pages.append(page) self._spinbox_model.append((name, page.tool_widget_title)) self._adjs[name] = page page.set_color_manager(mgr) if page_class in self._SINGLE_CLICK_ADJUSTER_CLASSES: page.connect_after( "button-release-event", self._ccwidget_btn_release_cb, ) self._prefs_key = self._PREFS_KEY_TEMPLATE % (prefs_id,) active_page = app.preferences.get(self._prefs_key, None) sb = spinbox.ItemSpinBox( self._spinbox_model, self._spinbox_changed_cb, active_page ) active_page = sb.get_value() self._spinbox = sb self._active_adj = self._adjs[active_page] self.pack_start(sb, False, False, 0) self.pack_start(self._active_adj, True, True, 0) self.set_spacing(widgets.SPACING_TIGHT) def _spinbox_changed_cb(self, page_name): self._app.preferences[self._prefs_key] = page_name self.remove(self._active_adj) new_adj = self._adjs[page_name] self._active_adj = new_adj self.pack_start(self._active_adj, True, True, 0) self._active_adj.show_all() def _ccwidget_btn_release_cb(self, ccwidget, event): """Internal: fire "choice_completed" after clicking certain widgets""" self.choice_completed() return False @event def choice_completed(self): """Event: a complete selection was made This is emitted by button-release events on certain kinds of colour chooser page. Not every page in the chooser emits this event, because colour is a three-dimensional quantity: clicking on a two-dimensional popup can't make a complete choice of colour with most pages. The palette page does emit this event, and it's the default. """ def advance(self): """Advances to the next color selector.""" self._spinbox.next() class ColorChooserPopup(windowing.ChooserPopup): """Speedy color chooser dialog""" def __init__(self, app, prefs_id=_DEFAULT_PREFS_ID, single_click=False): """Initialize. :param gui.application.Application app: main app instance :param unicode prefs_id: prefs identifier for the chooser :param bool single_click: limit to just the single-click adjusters The prefs identifier forms part of preferences key which store layout and which page of the chooser is selected. It should follow the same syntax rules as Python simple identifiers. """ windowing.ChooserPopup.__init__( self, app=app, actions=[ "ColorChooserPopup", "ColorChooserPopupFastSubset", "BrushChooserPopup", ], config_name="color_chooser.%s" % (prefs_id,), ) self._chooser = QuickColorChooser( app, prefs_id=prefs_id, single_click=single_click, ) self._chooser.choice_completed += self._choice_completed_cb self.add(self._chooser) def _choice_completed_cb(self, chooser): """Internal: close when a choice is (fully) made Close the dialog on button release only to avoid accidental dabs with the stylus. """ self.hide() def advance(self): """Advances to the next color selector.""" self._chooser.advance() ## Classes: interface registration Advanceable.register(QuickBrushChooser) Advanceable.register(QuickColorChooser) Advanceable.register(BrushChooserPopup) Advanceable.register(ColorChooserPopup)
admin
pages
from CTFd.admin import admin from CTFd.models import Pages from CTFd.schemas.pages import PageSchema from CTFd.utils import markdown from CTFd.utils.decorators import admins_only from flask import render_template, request @admin.route("/admin/pages") @admins_only def pages_listing(): pages = Pages.query.all() return render_template("admin/pages.html", pages=pages) @admin.route("/admin/pages/new") @admins_only def pages_new(): return render_template("admin/editor.html") @admin.route("/admin/pages/preview", methods=["POST"]) @admins_only def pages_preview(): # We only care about content. # Loading other attributes improperly will cause Marshmallow to incorrectly return a dict data = { "content": request.form.get("content"), "format": request.form.get("format"), } schema = PageSchema() page = schema.load(data) return render_template("page.html", content=page.data.html) @admin.route("/admin/pages/<int:page_id>") @admins_only def pages_detail(page_id): page = Pages.query.filter_by(id=page_id).first_or_404() page_op = request.args.get("operation") if request.method == "GET" and page_op == "preview": return render_template("page.html", content=markdown(page.content)) if request.method == "GET" and page_op == "create": return render_template("admin/editor.html") return render_template("admin/editor.html", page=page)
saveddata
drone
# =============================================================================== # Copyright (C) 2010 Diego Duclos # # This file is part of eos. # # eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # eos is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with eos. If not, see <http://www.gnu.org/licenses/>. # =============================================================================== import math import eos.db from eos.effectHandlerHelpers import HandledCharge, HandledItem from eos.modifiedAttributeDict import ( ChargeAttrShortcut, ItemAttrShortcut, ModifiedAttributeDict, ) from eos.saveddata.mutatedMixin import MutaError, MutatedMixin from eos.saveddata.mutator import MutatorDrone from eos.utils.cycles import CycleInfo from eos.utils.default import DEFAULT from eos.utils.stats import DmgTypes, RRTypes from logbook import Logger from sqlalchemy.orm import reconstructor, validates pyfalog = Logger(__name__) class Drone( HandledItem, HandledCharge, ItemAttrShortcut, ChargeAttrShortcut, MutatedMixin ): MINING_ATTRIBUTES = ("miningAmount",) def __init__(self, item, baseItem=None, mutaplasmid=None): """Initialize a drone from the program""" self._item = item self._mutaInit(baseItem=baseItem, mutaplasmid=mutaplasmid) if self.isInvalid: raise ValueError("Passed item is not a Drone") self.itemID = item.ID if item is not None else None self.amount = 0 self.amountActive = 0 self.projected = False self.projectionRange = None self.build() @reconstructor def init(self): """Initialize a drone from the database and validate""" self._item = None if self.itemID: self._item = eos.db.getItem(self.itemID) if self._item is None: pyfalog.error("Item (id: {0}) does not exist", self.itemID) return try: self._mutaReconstruct() except MutaError: return if self.isInvalid: pyfalog.error("Item (id: {0}) is not a Drone", self.itemID) return self.build() def build(self): """Build object. Assumes proper and valid item already set""" self.__charge = None self.__baseVolley = None self.__baseRRAmount = None self.__miningYield = None self.__miningWaste = None self.__ehp = None self.__itemModifiedAttributes = ModifiedAttributeDict() self.__itemModifiedAttributes.original = self._item.attributes self.__itemModifiedAttributes.overrides = self._item.overrides self.__chargeModifiedAttributes = ModifiedAttributeDict() self._mutaLoadMutators(mutatorClass=MutatorDrone) self.__itemModifiedAttributes.mutators = self.mutators chargeID = self.getModifiedItemAttr("entityMissileTypeID", None) if chargeID: charge = eos.db.getItem(int(chargeID)) self.__charge = charge self.__chargeModifiedAttributes.original = charge.attributes self.__chargeModifiedAttributes.overrides = charge.overrides @property def itemModifiedAttributes(self): return self.__itemModifiedAttributes @property def chargeModifiedAttributes(self): return self.__chargeModifiedAttributes @property def isInvalid(self): if self._item is None: return True if self._item.category.name != "Drone": return True if self._mutaIsInvalid: return True return False @property def item(self): return self._item @property def charge(self): return self.__charge @property def cycleTime(self): if self.hasAmmo: cycleTime = self.getModifiedItemAttr("missileLaunchDuration", 0) else: for attr in ("speed", "duration", "durationHighisGood"): cycleTime = self.getModifiedItemAttr(attr) if cycleTime: break if cycleTime is None: return 0 return max(cycleTime, 0) @property def dealsDamage(self): for attr in ("emDamage", "kineticDamage", "explosiveDamage", "thermalDamage"): if ( attr in self.itemModifiedAttributes or attr in self.chargeModifiedAttributes ): return True @property def mines(self): if "miningAmount" in self.itemModifiedAttributes: return True @property def hasAmmo(self): return self.charge is not None def isDealingDamage(self): volleyParams = self.getVolleyParameters() for volley in volleyParams.values(): if volley.total > 0: return True return False def getVolleyParameters(self, targetProfile=None): if not self.dealsDamage or self.amountActive <= 0: return {0: DmgTypes(0, 0, 0, 0)} if self.__baseVolley is None: dmgGetter = ( self.getModifiedChargeAttr if self.hasAmmo else self.getModifiedItemAttr ) dmgMult = self.amountActive * ( self.getModifiedItemAttr("damageMultiplier", 1) ) self.__baseVolley = DmgTypes( em=(dmgGetter("emDamage", 0)) * dmgMult, thermal=(dmgGetter("thermalDamage", 0)) * dmgMult, kinetic=(dmgGetter("kineticDamage", 0)) * dmgMult, explosive=(dmgGetter("explosiveDamage", 0)) * dmgMult, ) volley = DmgTypes( em=self.__baseVolley.em * (1 - getattr(targetProfile, "emAmount", 0)), thermal=self.__baseVolley.thermal * (1 - getattr(targetProfile, "thermalAmount", 0)), kinetic=self.__baseVolley.kinetic * (1 - getattr(targetProfile, "kineticAmount", 0)), explosive=self.__baseVolley.explosive * (1 - getattr(targetProfile, "explosiveAmount", 0)), ) return {0: volley} def getVolley(self, targetProfile=None): return self.getVolleyParameters(targetProfile=targetProfile)[0] def getDps(self, targetProfile=None): volley = self.getVolley(targetProfile=targetProfile) if not volley: return DmgTypes(0, 0, 0, 0) cycleParams = self.getCycleParameters() if cycleParams is None: return DmgTypes(0, 0, 0, 0) dpsFactor = 1 / (cycleParams.averageTime / 1000) dps = DmgTypes( em=volley.em * dpsFactor, thermal=volley.thermal * dpsFactor, kinetic=volley.kinetic * dpsFactor, explosive=volley.explosive * dpsFactor, ) return dps def isRemoteRepping(self, ignoreState=False): repParams = self.getRepAmountParameters(ignoreState=ignoreState) for rrData in repParams.values(): if rrData: return True return False def getRepAmountParameters(self, ignoreState=False): amount = self.amount if ignoreState else self.amountActive if amount <= 0: return {} if self.__baseRRAmount is None: self.__baseRRAmount = {} hullAmount = self.getModifiedItemAttr("structureDamageAmount", 0) armorAmount = self.getModifiedItemAttr("armorDamageAmount", 0) shieldAmount = self.getModifiedItemAttr("shieldBonus", 0) if shieldAmount: self.__baseRRAmount[0] = RRTypes( shield=shieldAmount * amount, armor=0, hull=0, capacitor=0 ) if armorAmount or hullAmount: self.__baseRRAmount[self.cycleTime] = RRTypes( shield=0, armor=armorAmount * amount, hull=hullAmount * amount, capacitor=0, ) return self.__baseRRAmount def getRemoteReps(self, ignoreState=False): rrDuringCycle = RRTypes(0, 0, 0, 0) cycleParams = self.getCycleParameters() if cycleParams is None: return rrDuringCycle repAmountParams = self.getRepAmountParameters(ignoreState=ignoreState) avgCycleTime = cycleParams.averageTime if len(repAmountParams) == 0 or avgCycleTime == 0: return rrDuringCycle for rrAmount in repAmountParams.values(): rrDuringCycle += rrAmount rrFactor = 1 / (avgCycleTime / 1000) rrDuringCycle *= rrFactor return rrDuringCycle def getCycleParameters(self, reloadOverride=None): cycleTime = self.cycleTime if not cycleTime: return None return CycleInfo(self.cycleTime, 0, math.inf, False) def getMiningYPS(self, ignoreState=False): if not ignoreState and self.amountActive <= 0: return 0 if self.__miningYield is None: self.__miningYield, self.__miningWaste = self.__calculateMining() return self.__miningYield def getMiningWPS(self, ignoreState=False): if not ignoreState and self.amountActive <= 0: return 0 if self.__miningWaste is None: self.__miningYield, self.__miningWaste = self.__calculateMining() return self.__miningWaste def __calculateMining(self): if self.mines is True: getter = self.getModifiedItemAttr cycleParams = self.getCycleParameters() if cycleParams is None: yps = 0 else: cycleTime = cycleParams.averageTime yield_ = sum([getter(d) for d in self.MINING_ATTRIBUTES]) * self.amount yps = yield_ / (cycleTime / 1000.0) wasteChance = self.getModifiedItemAttr("miningWasteProbability") wasteMult = self.getModifiedItemAttr("miningWastedVolumeMultiplier") wps = yps * max(0, min(1, wasteChance / 100)) * wasteMult return yps, wps else: return 0, 0 @property def maxRange(self): attrs = ( "shieldTransferRange", "powerTransferRange", "energyDestabilizationRange", "empFieldRange", "ecmBurstRange", "maxRange", "ECMRangeOptimal", ) for attr in attrs: maxRange = self.getModifiedItemAttr(attr) if maxRange: return maxRange if self.charge is not None: delay = self.getModifiedChargeAttr("explosionDelay") speed = self.getModifiedChargeAttr("maxVelocity") if delay is not None and speed is not None: return delay / 1000.0 * speed @property def hp(self): hp = {} for type, attr in ( ("shield", "shieldCapacity"), ("armor", "armorHP"), ("hull", "hp"), ): hp[type] = self.getModifiedItemAttr(attr) return hp @property def ehp(self): if self.__ehp is None: if self.owner is None or self.owner.damagePattern is None: ehp = self.hp else: ehp = self.owner.damagePattern.calculateEhp(self) self.__ehp = ehp return self.__ehp def calculateShieldRecharge(self): capacity = self.getModifiedItemAttr("shieldCapacity") rechargeRate = self.getModifiedItemAttr("shieldRechargeRate") / 1000.0 return 10 / rechargeRate * math.sqrt(0.25) * (1 - math.sqrt(0.25)) * capacity # Had to add this to match the falloff property in modules.py # Fscking ship scanners. If you find any other falloff attributes, # Put them in the attrs tuple. @property def falloff(self): attrs = ("falloff", "falloffEffectiveness") for attr in attrs: falloff = self.getModifiedItemAttr(attr) if falloff: return falloff @validates("ID", "itemID", "chargeID", "amount", "amountActive") def validator(self, key, val): map = { "ID": lambda _val: isinstance(_val, int), "itemID": lambda _val: isinstance(_val, int), "chargeID": lambda _val: isinstance(_val, int), "amount": lambda _val: isinstance(_val, int) and _val >= 0, "amountActive": lambda _val: isinstance(_val, int) and self.amount >= _val >= 0, } if not map[key](val): raise ValueError(str(val) + " is not a valid value for " + key) else: return val def clear(self): self.__baseVolley = None self.__baseRRAmount = None self.__miningYield = None self.__miningWaste = None self.__ehp = None self.itemModifiedAttributes.clear() self.chargeModifiedAttributes.clear() def canBeApplied(self, projectedOnto): """Check if drone can engage specific fitting""" item = self.item # Do not allow to apply offensive modules on ship with offensive module immunite, with few exceptions # (all effects which apply instant modification are exception, generally speaking) if ( item.offensive and projectedOnto.ship.getModifiedItemAttr("disallowOffensiveModifiers") == 1 ): offensiveNonModifiers = { "energyDestabilizationNew", "leech", "energyNosferatuFalloff", "energyNeutralizerFalloff", } if not offensiveNonModifiers.intersection(set(item.effects)): return False # If assistive modules are not allowed, do not let to apply these altogether if ( item.assistive and projectedOnto.ship.getModifiedItemAttr("disallowAssistance") == 1 ): return False else: return True def calculateModifiedAttributes( self, fit, runTime, forceProjected=False, forcedProjRange=DEFAULT ): if self.projected or forceProjected: context = "projected", "drone" projected = True else: context = ("drone",) projected = False projectionRange = ( self.projectionRange if forcedProjRange is DEFAULT else forcedProjRange ) for effect in self.item.effects.values(): if ( effect.runTime == runTime and effect.activeByDefault and ( (projected is True and effect.isType("projected")) or projected is False and effect.isType("passive") ) ): # See GH issue #765 if effect.getattr("grouped"): effect.handler(fit, self, context, projectionRange, effect=effect) else: i = 0 while i != self.amountActive: effect.handler( fit, self, context, projectionRange, effect=effect ) i += 1 if self.charge: for effect in self.charge.effects.values(): if effect.runTime == runTime and effect.activeByDefault: effect.handler( fit, self, ("droneCharge",), projectionRange, effect=effect ) def __deepcopy__(self, memo): copy = Drone(self.item, self.baseItem, self.mutaplasmid) copy.amount = self.amount copy.amountActive = self.amountActive copy.projectionRange = self.projectionRange self._mutaApplyMutators(mutatorClass=MutatorDrone, targetInstance=copy) return copy def rebase(self, item): amount = self.amount amountActive = self.amountActive projectionRange = self.projectionRange Drone.__init__(self, item, self.baseItem, self.mutaplasmid) self.amount = amount self.amountActive = amountActive self.projectionRange = projectionRange self._mutaApplyMutators(mutatorClass=MutatorDrone) def fits(self, fit): fitDroneGroupLimits = set() for i in range(1, 3): groneGrp = fit.ship.getModifiedItemAttr("allowedDroneGroup%d" % i) if groneGrp: fitDroneGroupLimits.add(int(groneGrp)) if len(fitDroneGroupLimits) == 0: return True if self.item.groupID in fitDroneGroupLimits: return True return False def canDealDamage(self, ignoreState=False): if self.item is None: return False for effect in self.item.effects.values(): if effect.dealsDamage and (ignoreState or self.amountActive > 0): return True return False
core
torrentmanager
# # Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com> # # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with # the additional special exception to link portions of this program with the OpenSSL library. # See LICENSE for more details. # """TorrentManager handles Torrent objects""" import datetime import logging import operator import os import pickle import time from base64 import b64encode from tempfile import gettempdir from typing import Dict, List, NamedTuple, Tuple import deluge.component as component from deluge._libtorrent import LT_VERSION, lt from deluge.common import ( VersionSplit, archive_files, decode_bytes, get_magnet_info, is_magnet, ) from deluge.configmanager import ConfigManager, get_config_dir from deluge.core.authmanager import AUTH_LEVEL_ADMIN from deluge.core.torrent import Torrent, TorrentOptions, sanitize_filepath from deluge.decorators import maybe_coroutine from deluge.error import AddTorrentError, InvalidTorrentError from deluge.event import ( ExternalIPEvent, PreTorrentRemovedEvent, SessionStartedEvent, TorrentAddedEvent, TorrentFileCompletedEvent, TorrentFileRenamedEvent, TorrentFinishedEvent, TorrentRemovedEvent, TorrentResumedEvent, ) from twisted.internet import defer, reactor, threads from twisted.internet.defer import Deferred, DeferredList from twisted.internet.task import LoopingCall log = logging.getLogger(__name__) LT_DEFAULT_ADD_TORRENT_FLAGS = ( lt.torrent_flags.paused | lt.torrent_flags.auto_managed | lt.torrent_flags.update_subscribe | lt.torrent_flags.apply_ip_filter ) class PrefetchQueueItem(NamedTuple): alert_deferred: Deferred result_queue: List[Deferred] class TorrentState: # pylint: disable=old-style-class """Create a torrent state. Note: This must be old style class to avoid breaking torrent.state file. """ def __init__( self, torrent_id=None, filename=None, trackers=None, storage_mode="sparse", paused=False, save_path=None, max_connections=-1, max_upload_slots=-1, max_upload_speed=-1.0, max_download_speed=-1.0, prioritize_first_last=False, sequential_download=False, file_priorities=None, queue=None, auto_managed=True, is_finished=False, stop_ratio=2.00, stop_at_ratio=False, remove_at_ratio=False, move_completed=False, move_completed_path=None, magnet=None, owner=None, shared=False, super_seeding=False, name=None, ): # Build the class attribute list from args for key, value in locals().items(): if key == "self": continue setattr(self, key, value) def __eq__(self, other): return isinstance(other, TorrentState) and self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other class TorrentManagerState: # pylint: disable=old-style-class """TorrentManagerState holds a list of TorrentState objects. Note: This must be old style class to avoid breaking torrent.state file. """ def __init__(self): self.torrents = [] def __eq__(self, other): return ( isinstance(other, TorrentManagerState) and self.torrents == other.torrents ) def __ne__(self, other): return not self == other class TorrentManager(component.Component): """TorrentManager contains a list of torrents in the current libtorrent session. This object is also responsible for saving the state of the session for use on restart. """ # This is used in the test to mock out timeouts clock = reactor def __init__(self): component.Component.__init__( self, "TorrentManager", interval=5, depend=["CorePluginManager", "AlertManager"], ) log.debug("TorrentManager init...") # Set the libtorrent session self.session = component.get("Core").session # Set the alertmanager self.alerts = component.get("AlertManager") # Get the core config self.config = ConfigManager("core.conf") # Make sure the state folder has been created self.state_dir = os.path.join(get_config_dir(), "state") if not os.path.exists(self.state_dir): os.makedirs(self.state_dir) self.temp_file = os.path.join(self.state_dir, ".safe_state_check") # Create the torrents dict { torrent_id: Torrent } self.torrents = {} self.queued_torrents = set() self.is_saving_state = False self.save_resume_data_file_lock = defer.DeferredLock() self.torrents_loading = {} self.prefetching_metadata: Dict[str, PrefetchQueueItem] = {} # This is a map of torrent_ids to Deferreds used to track needed resume data. # The Deferreds will be completed when resume data has been saved. self.waiting_on_resume_data = {} # Keep track of torrents finished but moving storage self.waiting_on_finish_moving = [] # Keeps track of resume data self.resume_data = {} self.torrents_status_requests = [] self.status_dict = {} self.last_state_update_alert_ts = 0 # Keep the previous saved state self.prev_saved_state = None # Register set functions set_config_keys = [ "max_connections_per_torrent", "max_upload_slots_per_torrent", "max_upload_speed_per_torrent", "max_download_speed_per_torrent", ] for config_key in set_config_keys: on_set_func = getattr(self, "".join(["on_set_", config_key])) self.config.register_set_function(config_key, on_set_func) # Register alert functions alert_handles = [ "external_ip", "performance", "add_torrent", "metadata_received", "torrent_finished", "torrent_paused", "torrent_checked", "torrent_resumed", "tracker_reply", "tracker_announce", "tracker_warning", "tracker_error", "file_renamed", "file_error", "file_completed", "storage_moved", "storage_moved_failed", "state_update", "state_changed", "save_resume_data", "save_resume_data_failed", "fastresume_rejected", ] for alert_handle in alert_handles: on_alert_func = getattr(self, "".join(["on_alert_", alert_handle])) self.alerts.register_handler(alert_handle, on_alert_func) # Define timers self.save_state_timer = LoopingCall(self.save_state) self.save_resume_data_timer = LoopingCall(self.save_resume_data) self.prev_status_cleanup_loop = LoopingCall(self.cleanup_torrents_prev_status) def start(self): # Check for old temp file to verify safe shutdown if os.path.isfile(self.temp_file): self.archive_state("Bad shutdown detected so archiving state files") os.remove(self.temp_file) with open(self.temp_file, "a"): os.utime(self.temp_file, None) # Try to load the state from file self.load_state() # Save the state periodically self.save_state_timer.start(200, False) self.save_resume_data_timer.start(190, False) self.prev_status_cleanup_loop.start(10) @maybe_coroutine async def stop(self): # Stop timers if self.save_state_timer.running: self.save_state_timer.stop() if self.save_resume_data_timer.running: self.save_resume_data_timer.stop() if self.prev_status_cleanup_loop.running: self.prev_status_cleanup_loop.stop() # Save state on shutdown await self.save_state() self.session.pause() result = await self.save_resume_data(flush_disk_cache=True) # Remove the temp_file to signify successfully saved state if result and os.path.isfile(self.temp_file): os.remove(self.temp_file) def update(self): for torrent_id, torrent in self.torrents.items(): # XXX: Should the state check be those that _can_ be stopped at ratio if torrent.options["stop_at_ratio"] and torrent.state not in ( "Checking", "Allocating", "Paused", "Queued", ): if ( torrent.get_ratio() >= torrent.options["stop_ratio"] and torrent.is_finished ): if torrent.options["remove_at_ratio"]: self.remove(torrent_id) break if not torrent.status.paused: torrent.pause() def __getitem__(self, torrent_id): """Return the Torrent with torrent_id. Args: torrent_id (str): The torrent_id. Returns: Torrent: A torrent object. """ return self.torrents[torrent_id] def get_torrent_list(self): """Creates a list of torrent_ids, owned by current user and any marked shared. Returns: list: A list of torrent_ids. """ torrent_ids = list(self.torrents) if component.get("RPCServer").get_session_auth_level() == AUTH_LEVEL_ADMIN: return torrent_ids current_user = component.get("RPCServer").get_session_user() for torrent_id in torrent_ids[:]: torrent_status = self.torrents[torrent_id].get_status(["owner", "shared"]) if torrent_status["owner"] != current_user and not torrent_status["shared"]: torrent_ids.pop(torrent_ids.index(torrent_id)) return torrent_ids def get_torrent_info_from_file(self, filepath): """Retrieves torrent_info from the file specified. Args: filepath (str): The filepath to extract torrent info from. Returns: lt.torrent_info: A libtorrent torrent_info dict or None if invalid file or data. """ # Get the torrent data from the torrent file if log.isEnabledFor(logging.DEBUG): log.debug("Attempting to extract torrent_info from %s", filepath) try: torrent_info = lt.torrent_info(filepath) except RuntimeError as ex: log.warning("Unable to open torrent file %s: %s", filepath, ex) else: return torrent_info @maybe_coroutine async def prefetch_metadata(self, magnet: str, timeout: int) -> Tuple[str, bytes]: """Download the metadata for a magnet URI. Args: magnet: A magnet URI to download the metadata for. timeout: Number of seconds to wait before canceling. Returns: A tuple of (torrent_id, metadata) """ torrent_id = get_magnet_info(magnet)["info_hash"] if torrent_id in self.prefetching_metadata: d = Deferred() self.prefetching_metadata[torrent_id].result_queue.append(d) return await d add_torrent_params = lt.parse_magnet_uri(magnet) add_torrent_params.save_path = gettempdir() add_torrent_params.flags = ( ( LT_DEFAULT_ADD_TORRENT_FLAGS | lt.torrent_flags.duplicate_is_error | lt.torrent_flags.upload_mode ) ^ lt.torrent_flags.auto_managed ^ lt.torrent_flags.paused ) torrent_handle = self.session.add_torrent(add_torrent_params) d = Deferred() # Cancel the defer if timeout reached. d.addTimeout(timeout, self.clock) self.prefetching_metadata[torrent_id] = PrefetchQueueItem(d, []) try: torrent_info = await d except (defer.TimeoutError, defer.CancelledError): log.debug(f"Prefetching metadata for {torrent_id} timed out or cancelled.") metadata = b"" else: log.debug("prefetch metadata received") if VersionSplit(LT_VERSION) < VersionSplit("2.0.0.0"): metadata = torrent_info.metadata() else: metadata = torrent_info.info_section() log.debug("remove prefetch magnet from session") result_queue = self.prefetching_metadata.pop(torrent_id).result_queue self.session.remove_torrent(torrent_handle, 1) result = torrent_id, b64encode(metadata) for d in result_queue: d.callback(result) return result def _build_torrent_options(self, options): """Load default options and update if needed.""" _options = TorrentOptions() if options: _options.update(options) options = _options if not options["owner"]: options["owner"] = component.get("RPCServer").get_session_user() if not component.get("AuthManager").has_account(options["owner"]): options["owner"] = "localclient" return options def _build_torrent_params( self, torrent_info=None, magnet=None, options=None, resume_data=None ): """Create the add_torrent_params dict for adding torrent to libtorrent.""" add_torrent_params = {} if torrent_info: add_torrent_params["ti"] = torrent_info name = torrent_info.name() if not name: name = ( torrent_info.file_at(0).path.replace("\\", "/", 1).split("/", 1)[0] ) add_torrent_params["name"] = name torrent_id = str(torrent_info.info_hash()) elif magnet: magnet_info = get_magnet_info(magnet) if magnet_info: add_torrent_params["name"] = magnet_info["name"] add_torrent_params["trackers"] = list(magnet_info["trackers"]) torrent_id = magnet_info["info_hash"] add_torrent_params["info_hash"] = bytes(bytearray.fromhex(torrent_id)) else: raise AddTorrentError( "Unable to add magnet, invalid magnet info: %s" % magnet ) # Check for existing torrent in session. if torrent_id in self.get_torrent_list(): # Attempt merge trackers before returning. self.torrents[torrent_id].merge_trackers(torrent_info) raise AddTorrentError("Torrent already in session (%s)." % torrent_id) elif torrent_id in self.torrents_loading: raise AddTorrentError("Torrent already being added (%s)." % torrent_id) elif torrent_id in self.prefetching_metadata: # Cancel and remove metadata fetching torrent. self.prefetching_metadata[torrent_id].alert_deferred.cancel() # Check for renamed files and if so, rename them in the torrent_info before adding. if options["mapped_files"] and torrent_info: for index, fname in options["mapped_files"].items(): fname = sanitize_filepath(decode_bytes(fname)) if log.isEnabledFor(logging.DEBUG): log.debug("renaming file index %s to %s", index, fname) try: torrent_info.rename_file(index, fname.encode("utf8")) except TypeError: torrent_info.rename_file(index, fname) add_torrent_params["ti"] = torrent_info if log.isEnabledFor(logging.DEBUG): log.debug("options: %s", options) # Fill in the rest of the add_torrent_params dictionary. add_torrent_params["save_path"] = options["download_location"].encode("utf8") if options["name"]: add_torrent_params["name"] = options["name"] if options["pre_allocate_storage"]: add_torrent_params["storage_mode"] = lt.storage_mode_t.storage_mode_allocate if resume_data: add_torrent_params["resume_data"] = resume_data # Set flags: enable duplicate_is_error & override_resume_data, disable auto_managed. add_torrent_params["flags"] = ( LT_DEFAULT_ADD_TORRENT_FLAGS | lt.torrent_flags.duplicate_is_error ) ^ lt.torrent_flags.auto_managed if options["seed_mode"]: add_torrent_params["flags"] |= lt.torrent_flags.seed_mode if options["super_seeding"]: add_torrent_params["flags"] |= lt.torrent_flags.super_seeding return torrent_id, add_torrent_params def add( self, torrent_info=None, state=None, options=None, save_state=True, filedump=None, filename=None, magnet=None, resume_data=None, ): """Adds a torrent to the torrent manager. Args: torrent_info (lt.torrent_info, optional): A libtorrent torrent_info object. state (TorrentState, optional): The torrent state. options (dict, optional): The options to apply to the torrent on adding. save_state (bool, optional): If True save the session state after adding torrent, defaults to True. filedump (str, optional): bencoded filedump of a torrent file. filename (str, optional): The filename of the torrent file. magnet (str, optional): The magnet URI. resume_data (lt.entry, optional): libtorrent fast resume data. Returns: str: If successful the torrent_id of the added torrent, None if adding the torrent failed. Emits: TorrentAddedEvent: Torrent with torrent_id added to session. """ if not torrent_info and not filedump and not magnet: raise AddTorrentError( "You must specify a valid torrent_info, torrent state or magnet." ) if filedump: try: torrent_info = lt.torrent_info(lt.bdecode(filedump)) except RuntimeError as ex: raise AddTorrentError( "Unable to add torrent, decoding filedump failed: %s" % ex ) options = self._build_torrent_options(options) __, add_torrent_params = self._build_torrent_params( torrent_info, magnet, options, resume_data ) # We need to pause the AlertManager momentarily to prevent alerts # for this torrent being generated before a Torrent object is created. component.pause("AlertManager") try: handle = self.session.add_torrent(add_torrent_params) if not handle.is_valid(): raise InvalidTorrentError("Torrent handle is invalid!") except (RuntimeError, InvalidTorrentError) as ex: component.resume("AlertManager") raise AddTorrentError("Unable to add torrent to session: %s" % ex) torrent = self._add_torrent_obj( handle, options, state, filename, magnet, resume_data, filedump, save_state ) return torrent.torrent_id def add_async( self, torrent_info=None, state=None, options=None, save_state=True, filedump=None, filename=None, magnet=None, resume_data=None, ): """Adds a torrent to the torrent manager using libtorrent async add torrent method. Args: torrent_info (lt.torrent_info, optional): A libtorrent torrent_info object. state (TorrentState, optional): The torrent state. options (dict, optional): The options to apply to the torrent on adding. save_state (bool, optional): If True save the session state after adding torrent, defaults to True. filedump (str, optional): bencoded filedump of a torrent file. filename (str, optional): The filename of the torrent file. magnet (str, optional): The magnet URI. resume_data (lt.entry, optional): libtorrent fast resume data. Returns: Deferred: If successful the torrent_id of the added torrent, None if adding the torrent failed. Emits: TorrentAddedEvent: Torrent with torrent_id added to session. """ if not torrent_info and not filedump and not magnet: raise AddTorrentError( "You must specify a valid torrent_info, torrent state or magnet." ) if filedump: try: torrent_info = lt.torrent_info(lt.bdecode(filedump)) except RuntimeError as ex: raise AddTorrentError( "Unable to add torrent, decoding filedump failed: %s" % ex ) options = self._build_torrent_options(options) torrent_id, add_torrent_params = self._build_torrent_params( torrent_info, magnet, options, resume_data ) d = Deferred() self.torrents_loading[torrent_id] = ( d, options, state, filename, magnet, resume_data, filedump, save_state, ) try: self.session.async_add_torrent(add_torrent_params) except RuntimeError as ex: raise AddTorrentError("Unable to add torrent to session: %s" % ex) return d def _add_torrent_obj( self, handle, options, state, filename, magnet, resume_data, filedump, save_state, ): # For magnets added with metadata, filename is used so set as magnet. if not magnet and is_magnet(filename): magnet = filename filename = None # Create a Torrent object and add to the dictionary. torrent = Torrent(handle, options, state, filename, magnet) self.torrents[torrent.torrent_id] = torrent # Resume AlertManager if paused for adding torrent to libtorrent. component.resume("AlertManager") # Store the original resume_data, in case of errors. if resume_data: self.resume_data[torrent.torrent_id] = resume_data # Add to queued torrents set. self.queued_torrents.add(torrent.torrent_id) if self.config["queue_new_to_top"]: self.queue_top(torrent.torrent_id) # Resume the torrent if needed. if not options["add_paused"]: torrent.resume() # Emit torrent_added signal. from_state = state is not None component.get("EventManager").emit( TorrentAddedEvent(torrent.torrent_id, from_state) ) if log.isEnabledFor(logging.DEBUG): log.debug("Torrent added: %s", str(handle.info_hash())) if log.isEnabledFor(logging.INFO): name_and_owner = torrent.get_status(["name", "owner"]) log.info( 'Torrent %s from user "%s" %s', name_and_owner["name"], name_and_owner["owner"], from_state and "loaded" or "added", ) # Write the .torrent file to the state directory. if filedump: torrent.write_torrentfile(filedump) # Save the session state. if save_state: self.save_state() return torrent def add_async_callback( self, handle, d, options, state, filename, magnet, resume_data, filedump, save_state, ): torrent = self._add_torrent_obj( handle, options, state, filename, magnet, resume_data, filedump, save_state ) d.callback(torrent.torrent_id) def remove(self, torrent_id, remove_data=False, save_state=True): """Remove a torrent from the session. Args: torrent_id (str): The torrent ID to remove. remove_data (bool, optional): If True, remove the downloaded data, defaults to False. save_state (bool, optional): If True, save the session state after removal, defaults to True. Returns: bool: True if removed successfully, False if not. Emits: PreTorrentRemovedEvent: Torrent is about to be removed from session. TorrentRemovedEvent: Torrent with torrent_id removed from session. Raises: InvalidTorrentError: If the torrent_id is not in the session. """ try: torrent = self.torrents[torrent_id] except KeyError: raise InvalidTorrentError("torrent_id %s not in session." % torrent_id) torrent_name = torrent.get_status(["name"])["name"] # Emit the signal to the clients component.get("EventManager").emit(PreTorrentRemovedEvent(torrent_id)) try: self.session.remove_torrent(torrent.handle, 1 if remove_data else 0) except RuntimeError as ex: log.warning("Error removing torrent: %s", ex) return False # Remove fastresume data if it is exists self.resume_data.pop(torrent_id, None) # Remove the .torrent file in the state and copy location, if user requested. delete_copies = ( self.config["copy_torrent_file"] and self.config["del_copy_torrent_file"] ) torrent.delete_torrentfile(delete_copies) # Remove from set if it wasn't finished if not torrent.is_finished: try: self.queued_torrents.remove(torrent_id) except KeyError: log.debug("%s is not in queued torrents set.", torrent_id) raise InvalidTorrentError( "%s is not in queued torrents set." % torrent_id ) # Remove the torrent from deluge's session del self.torrents[torrent_id] if save_state: self.save_state() # Emit the signal to the clients component.get("EventManager").emit(TorrentRemovedEvent(torrent_id)) log.info( "Torrent %s removed by user: %s", torrent_name, component.get("RPCServer").get_session_user(), ) return True def fixup_state(self, state): """Fixup an old state by adding missing TorrentState options and assigning default values. Args: state (TorrentManagerState): A torrentmanager state containing torrent details. Returns: TorrentManagerState: A fixedup TorrentManager state. """ if state.torrents: t_state_tmp = TorrentState() if dir(state.torrents[0]) != dir(t_state_tmp): self.archive_state("Migration of TorrentState required.") try: for attr in set(dir(t_state_tmp)) - set(dir(state.torrents[0])): for t_state in state.torrents: setattr(t_state, attr, getattr(t_state_tmp, attr, None)) except AttributeError as ex: log.error( "Unable to update state file to a compatible version: %s", ex ) return state def open_state(self): """Open the torrents.state file containing a TorrentManager state with session torrents. Returns: TorrentManagerState: The TorrentManager state. """ torrents_state = os.path.join(self.state_dir, "torrents.state") state = None for filepath in (torrents_state, torrents_state + ".bak"): log.info("Loading torrent state: %s", filepath) if not os.path.isfile(filepath): continue try: with open(filepath, "rb") as _file: state = pickle.load(_file, encoding="utf8") except (OSError, EOFError, pickle.UnpicklingError) as ex: message = f"Unable to load {filepath}: {ex}" log.error(message) if not filepath.endswith(".bak"): self.archive_state(message) else: log.info("Successfully loaded %s", filepath) break return state if state else TorrentManagerState() def load_state(self): """Load all the torrents from TorrentManager state into session. Emits: SessionStartedEvent: Emitted after all torrents are added to the session. """ start = datetime.datetime.now() state = self.open_state() state = self.fixup_state(state) # Reorder the state.torrents list to add torrents in the correct queue order. state.torrents.sort( key=operator.attrgetter("queue"), reverse=self.config["queue_new_to_top"] ) resume_data = self.load_resume_data_file() deferreds = [] for t_state in state.torrents: # Populate the options dict from state options = TorrentOptions() for option in options: try: options[option] = getattr(t_state, option) except AttributeError: pass # Manually update unmatched attributes options["download_location"] = t_state.save_path options["pre_allocate_storage"] = t_state.storage_mode == "allocate" options["prioritize_first_last_pieces"] = t_state.prioritize_first_last options["add_paused"] = t_state.paused magnet = t_state.magnet torrent_info = self.get_torrent_info_from_file( os.path.join(self.state_dir, t_state.torrent_id + ".torrent") ) try: d = self.add_async( torrent_info=torrent_info, state=t_state, options=options, save_state=False, magnet=magnet, resume_data=resume_data.get(t_state.torrent_id), ) except AddTorrentError as ex: log.warning( 'Error when adding torrent "%s" to session: %s', t_state.torrent_id, ex, ) else: deferreds.append(d) deferred_list = DeferredList(deferreds, consumeErrors=False) def on_complete(result): log.info( "Finished loading %d torrents in %s", len(state.torrents), str(datetime.datetime.now() - start), ) component.get("EventManager").emit(SessionStartedEvent()) deferred_list.addCallback(on_complete) def create_state(self): """Create a state of all the torrents in TorrentManager. Returns: TorrentManagerState: The TorrentManager state. """ state = TorrentManagerState() # Create the state for each Torrent and append to the list for torrent in self.torrents.values(): if self.session.is_paused(): paused = torrent.handle.is_paused() elif torrent.forced_error: paused = torrent.forced_error.was_paused elif torrent.state == "Paused": paused = True else: paused = False torrent_state = TorrentState( torrent.torrent_id, torrent.filename, torrent.trackers, torrent.get_status(["storage_mode"])["storage_mode"], paused, torrent.options["download_location"], torrent.options["max_connections"], torrent.options["max_upload_slots"], torrent.options["max_upload_speed"], torrent.options["max_download_speed"], torrent.options["prioritize_first_last_pieces"], torrent.options["sequential_download"], torrent.options["file_priorities"], torrent.get_queue_position(), torrent.options["auto_managed"], torrent.is_finished, torrent.options["stop_ratio"], torrent.options["stop_at_ratio"], torrent.options["remove_at_ratio"], torrent.options["move_completed"], torrent.options["move_completed_path"], torrent.magnet, torrent.options["owner"], torrent.options["shared"], torrent.options["super_seeding"], torrent.options["name"], ) state.torrents.append(torrent_state) return state def save_state(self): """Run the save state task in a separate thread to avoid blocking main thread. Note: If a save task is already running, this call is ignored. """ if self.is_saving_state: return defer.succeed(None) self.is_saving_state = True d = threads.deferToThread(self._save_state) def on_state_saved(arg): self.is_saving_state = False if self.save_state_timer.running: self.save_state_timer.reset() d.addBoth(on_state_saved) return d def _save_state(self): """Save the state of the TorrentManager to the torrents.state file.""" state = self.create_state() # If the state hasn't changed, no need to save it if self.prev_saved_state == state: return filename = "torrents.state" filepath = os.path.join(self.state_dir, filename) filepath_bak = filepath + ".bak" filepath_tmp = filepath + ".tmp" try: log.debug("Creating the temporary file: %s", filepath_tmp) with open(filepath_tmp, "wb", 0) as _file: pickle.dump(state, _file, protocol=2) _file.flush() os.fsync(_file.fileno()) except (OSError, pickle.PicklingError) as ex: log.error("Unable to save %s: %s", filename, ex) return try: log.debug("Creating backup of %s at: %s", filename, filepath_bak) if os.path.isfile(filepath_bak): os.remove(filepath_bak) if os.path.isfile(filepath): os.rename(filepath, filepath_bak) except OSError as ex: log.error("Unable to backup %s to %s: %s", filepath, filepath_bak, ex) return try: log.debug("Saving %s to: %s", filename, filepath) os.rename(filepath_tmp, filepath) self.prev_saved_state = state except OSError as ex: log.error("Failed to set new state file %s: %s", filepath, ex) if os.path.isfile(filepath_bak): log.info("Restoring backup of state from: %s", filepath_bak) os.rename(filepath_bak, filepath) def save_resume_data(self, torrent_ids=None, flush_disk_cache=False): """Saves torrents resume data. Args: torrent_ids (list of str): A list of torrents to save the resume data for, defaults to None which saves all torrents resume data. flush_disk_cache (bool, optional): If True flushes the disk cache which avoids potential issue with file timestamps, defaults to False. This is only needed when stopping the session. Returns: t.i.d.DeferredList: A list of twisted Deferred callbacks to be invoked when save is complete. """ if torrent_ids is None: torrent_ids = ( tid for tid, t in self.torrents.items() if t.handle.need_save_resume_data() ) def on_torrent_resume_save(dummy_result, torrent_id): """Received torrent resume_data alert so remove from waiting list""" self.waiting_on_resume_data.pop(torrent_id, None) deferreds = [] for torrent_id in torrent_ids: d = self.waiting_on_resume_data.get(torrent_id) if not d: d = Deferred().addBoth(on_torrent_resume_save, torrent_id) self.waiting_on_resume_data[torrent_id] = d deferreds.append(d) self.torrents[torrent_id].save_resume_data(flush_disk_cache) def on_all_resume_data_finished(dummy_result): """Saves resume data file when no more torrents waiting for resume data. Returns: bool: True if fastresume file is saved. This return value determines removal of `self.temp_file` in `self.stop()`. """ # Use flush_disk_cache as a marker for shutdown so fastresume is # saved even if torrents are waiting. if not self.waiting_on_resume_data or flush_disk_cache: return self.save_resume_data_file(queue_task=flush_disk_cache) return DeferredList(deferreds).addBoth(on_all_resume_data_finished) def load_resume_data_file(self): """Load the resume data from file for all torrents. Returns: dict: A dict of torrents and their resume_data. """ filename = "torrents.fastresume" filepath = os.path.join(self.state_dir, filename) filepath_bak = filepath + ".bak" old_data_filepath = os.path.join(get_config_dir(), filename) for _filepath in (filepath, filepath_bak, old_data_filepath): log.info("Opening %s for load: %s", filename, _filepath) try: with open(_filepath, "rb") as _file: resume_data = lt.bdecode(_file.read()) except (OSError, EOFError, RuntimeError) as ex: if self.torrents: log.warning("Unable to load %s: %s", _filepath, ex) resume_data = None else: # lt.bdecode returns the dict keys as bytes so decode them. resume_data = {k.decode(): v for k, v in resume_data.items()} log.info("Successfully loaded %s: %s", filename, _filepath) break # If the libtorrent bdecode doesn't happen properly, it will return None # so we need to make sure we return a {} if resume_data is None: return {} else: return resume_data def save_resume_data_file(self, queue_task=False): """Save resume data to file in a separate thread to avoid blocking main thread. Args: queue_task (bool): If True and a save task is already running then queue this save task to run next. Default is to not queue save tasks. Returns: Deferred: Fires with arg, True if save task was successful, False if not and None if task was not performed. """ if not queue_task and self.save_resume_data_file_lock.locked: return defer.succeed(None) def on_lock_aquired(): d = threads.deferToThread(self._save_resume_data_file) def on_resume_data_file_saved(arg): if self.save_resume_data_timer.running: self.save_resume_data_timer.reset() return arg d.addBoth(on_resume_data_file_saved) return d return self.save_resume_data_file_lock.run(on_lock_aquired) def _save_resume_data_file(self): """Saves the resume data file with the contents of self.resume_data""" if not self.resume_data: return True filename = "torrents.fastresume" filepath = os.path.join(self.state_dir, filename) filepath_bak = filepath + ".bak" filepath_tmp = filepath + ".tmp" try: log.debug("Creating the temporary file: %s", filepath_tmp) with open(filepath_tmp, "wb", 0) as _file: _file.write(lt.bencode(self.resume_data)) _file.flush() os.fsync(_file.fileno()) except (OSError, EOFError) as ex: log.error("Unable to save %s: %s", filename, ex) return False try: log.debug("Creating backup of %s at: %s", filename, filepath_bak) if os.path.isfile(filepath_bak): os.remove(filepath_bak) if os.path.isfile(filepath): os.rename(filepath, filepath_bak) except OSError as ex: log.error("Unable to backup %s to %s: %s", filepath, filepath_bak, ex) return False try: log.debug("Saving %s to: %s", filename, filepath) os.rename(filepath_tmp, filepath) except OSError as ex: log.error("Failed to set new file %s: %s", filepath, ex) if os.path.isfile(filepath_bak): log.info("Restoring backup from: %s", filepath_bak) os.rename(filepath_bak, filepath) else: # Sync the rename operations for the directory if hasattr(os, "O_DIRECTORY"): dirfd = os.open(os.path.dirname(filepath), os.O_DIRECTORY) os.fsync(dirfd) os.close(dirfd) return True def archive_state(self, message): log.warning(message) arc_filepaths = [] for filename in ("torrents.fastresume", "torrents.state"): filepath = os.path.join(self.state_dir, filename) arc_filepaths.extend([filepath, filepath + ".bak"]) archive_files("state", arc_filepaths, message=message) def get_queue_position(self, torrent_id): """Get queue position of torrent""" return self.torrents[torrent_id].get_queue_position() def queue_top(self, torrent_id): """Queue torrent to top""" if self.torrents[torrent_id].get_queue_position() == 0: return False self.torrents[torrent_id].handle.queue_position_top() return True def queue_up(self, torrent_id): """Queue torrent up one position""" if self.torrents[torrent_id].get_queue_position() == 0: return False self.torrents[torrent_id].handle.queue_position_up() return True def queue_down(self, torrent_id): """Queue torrent down one position""" if self.torrents[torrent_id].get_queue_position() == ( len(self.queued_torrents) - 1 ): return False self.torrents[torrent_id].handle.queue_position_down() return True def queue_bottom(self, torrent_id): """Queue torrent to bottom""" if self.torrents[torrent_id].get_queue_position() == ( len(self.queued_torrents) - 1 ): return False self.torrents[torrent_id].handle.queue_position_bottom() return True def cleanup_torrents_prev_status(self): """Run cleanup_prev_status for each registered torrent""" for torrent in self.torrents.values(): torrent.cleanup_prev_status() def on_set_max_connections_per_torrent(self, key, value): """Sets the per-torrent connection limit""" log.debug("max_connections_per_torrent set to %s...", value) for key in self.torrents: self.torrents[key].set_max_connections(value) def on_set_max_upload_slots_per_torrent(self, key, value): """Sets the per-torrent upload slot limit""" log.debug("max_upload_slots_per_torrent set to %s...", value) for key in self.torrents: self.torrents[key].set_max_upload_slots(value) def on_set_max_upload_speed_per_torrent(self, key, value): """Sets the per-torrent upload speed limit""" log.debug("max_upload_speed_per_torrent set to %s...", value) for key in self.torrents: self.torrents[key].set_max_upload_speed(value) def on_set_max_download_speed_per_torrent(self, key, value): """Sets the per-torrent download speed limit""" log.debug("max_download_speed_per_torrent set to %s...", value) for key in self.torrents: self.torrents[key].set_max_download_speed(value) # --- Alert handlers --- def on_alert_add_torrent(self, alert): """Alert handler for libtorrent add_torrent_alert""" if not alert.handle.is_valid(): log.warning("Torrent handle is invalid: %s", alert.error.message()) return try: torrent_id = str(alert.handle.info_hash()) except RuntimeError as ex: log.warning("Failed to get torrent id from handle: %s", ex) return try: add_async_params = self.torrents_loading.pop(torrent_id) except KeyError as ex: log.warning("Torrent id not in torrents loading list: %s", ex) return self.add_async_callback(alert.handle, *add_async_params) def on_alert_torrent_finished(self, alert): """Alert handler for libtorrent torrent_finished_alert""" try: torrent_id = str(alert.handle.info_hash()) torrent = self.torrents[torrent_id] except (RuntimeError, KeyError): return # If total_download is 0, do not move, it's likely the torrent wasn't downloaded, but just added. # Get fresh data from libtorrent, the cache isn't always up to date total_download = torrent.get_status(["total_payload_download"], update=True)[ "total_payload_download" ] if log.isEnabledFor(logging.DEBUG): log.debug("Finished %s ", torrent_id) log.debug( "Torrent settings: is_finished: %s, total_download: %s, move_completed: %s, move_path: %s", torrent.is_finished, total_download, torrent.options["move_completed"], torrent.options["move_completed_path"], ) torrent.update_state() if not torrent.is_finished and total_download: # Move completed download to completed folder if needed if ( torrent.options["move_completed"] and torrent.options["download_location"] != torrent.options["move_completed_path"] ): self.waiting_on_finish_moving.append(torrent_id) torrent.move_storage(torrent.options["move_completed_path"]) else: torrent.is_finished = True component.get("EventManager").emit(TorrentFinishedEvent(torrent_id)) else: torrent.is_finished = True # Torrent is no longer part of the queue try: self.queued_torrents.remove(torrent_id) except KeyError: # Sometimes libtorrent fires a TorrentFinishedEvent twice if log.isEnabledFor(logging.DEBUG): log.debug("%s is not in queued torrents set.", torrent_id) # Only save resume data if it was actually downloaded something. Helps # on startup with big queues with lots of seeding torrents. Libtorrent # emits alert_torrent_finished for them, but there seems like nothing # worth really to save in resume data, we just read it up in # self.load_state(). if total_download: self.save_resume_data((torrent_id,)) def on_alert_torrent_paused(self, alert): """Alert handler for libtorrent torrent_paused_alert""" try: torrent_id = str(alert.handle.info_hash()) torrent = self.torrents[torrent_id] except (RuntimeError, KeyError): return torrent.update_state() # Write the fastresume file if we are not waiting on a bulk write if torrent_id not in self.waiting_on_resume_data: self.save_resume_data((torrent_id,)) def on_alert_torrent_checked(self, alert): """Alert handler for libtorrent torrent_checked_alert""" try: torrent = self.torrents[str(alert.handle.info_hash())] except (RuntimeError, KeyError): return # Check to see if we're forcing a recheck and set it back to paused if necessary. if torrent.forcing_recheck: torrent.forcing_recheck = False if torrent.forcing_recheck_paused: torrent.handle.pause() torrent.update_state() def on_alert_tracker_reply(self, alert): """Alert handler for libtorrent tracker_reply_alert""" try: torrent = self.torrents[str(alert.handle.info_hash())] except (RuntimeError, KeyError): return # Set the tracker status for the torrent torrent.set_tracker_status("Announce OK") # Check for peer information from the tracker, if none then send a scrape request. torrent.get_lt_status() if torrent.status.num_complete == -1 or torrent.status.num_incomplete == -1: torrent.scrape_tracker() def on_alert_tracker_announce(self, alert): """Alert handler for libtorrent tracker_announce_alert""" try: torrent = self.torrents[str(alert.handle.info_hash())] except (RuntimeError, KeyError): return # Set the tracker status for the torrent torrent.set_tracker_status("Announce Sent") def on_alert_tracker_warning(self, alert): """Alert handler for libtorrent tracker_warning_alert""" try: torrent = self.torrents[str(alert.handle.info_hash())] except (RuntimeError, KeyError): return # Set the tracker status for the torrent torrent.set_tracker_status("Warning: %s" % decode_bytes(alert.message())) def on_alert_tracker_error(self, alert): """Alert handler for libtorrent tracker_error_alert""" try: torrent = self.torrents[str(alert.handle.info_hash())] except (RuntimeError, KeyError): return error_message = decode_bytes(alert.error_message()) if not error_message: error_message = decode_bytes(alert.error.message()) log.debug( "Tracker Error Alert: %s [%s]", decode_bytes(alert.message()), error_message ) # libtorrent 1.2 added endpoint struct to each tracker. to prevent false updates # we will need to verify that at least one endpoint to the errored tracker is working for tracker in torrent.handle.trackers(): if tracker["url"] == alert.url: if any( endpoint["last_error"]["value"] == 0 for endpoint in tracker["endpoints"] ): torrent.set_tracker_status("Announce OK") else: torrent.set_tracker_status("Error: " + error_message) break def on_alert_storage_moved(self, alert): """Alert handler for libtorrent storage_moved_alert""" try: torrent_id = str(alert.handle.info_hash()) torrent = self.torrents[torrent_id] except (RuntimeError, KeyError): return torrent.set_download_location(os.path.normpath(alert.storage_path())) torrent.set_move_completed(False) torrent.update_state() if torrent_id in self.waiting_on_finish_moving: self.waiting_on_finish_moving.remove(torrent_id) torrent.is_finished = True component.get("EventManager").emit(TorrentFinishedEvent(torrent_id)) def on_alert_storage_moved_failed(self, alert): """Alert handler for libtorrent storage_moved_failed_alert""" try: torrent_id = str(alert.handle.info_hash()) torrent = self.torrents[torrent_id] except (RuntimeError, KeyError): return log.warning("on_alert_storage_moved_failed: %s", decode_bytes(alert.message())) # Set an Error message and pause the torrent alert_msg = decode_bytes(alert.message()).split(":", 1)[1].strip() torrent.force_error_state("Failed to move download folder: %s" % alert_msg) if torrent_id in self.waiting_on_finish_moving: self.waiting_on_finish_moving.remove(torrent_id) torrent.is_finished = True component.get("EventManager").emit(TorrentFinishedEvent(torrent_id)) def on_alert_torrent_resumed(self, alert): """Alert handler for libtorrent torrent_resumed_alert""" try: torrent_id = str(alert.handle.info_hash()) torrent = self.torrents[torrent_id] except (RuntimeError, KeyError): return torrent.update_state() component.get("EventManager").emit(TorrentResumedEvent(torrent_id)) def on_alert_state_changed(self, alert): """Alert handler for libtorrent state_changed_alert. Emits: TorrentStateChangedEvent: The state has changed. """ try: torrent_id = str(alert.handle.info_hash()) torrent = self.torrents[torrent_id] except (RuntimeError, KeyError): return torrent.update_state() # Torrent may need to download data after checking. if torrent.state in ("Checking", "Downloading"): torrent.is_finished = False self.queued_torrents.add(torrent_id) def on_alert_save_resume_data(self, alert): """Alert handler for libtorrent save_resume_data_alert""" try: torrent_id = str(alert.handle.info_hash()) except RuntimeError: return if torrent_id in self.torrents: # libtorrent add_torrent expects bencoded resume_data. self.resume_data[torrent_id] = lt.bencode( lt.write_resume_data(alert.params) ) if torrent_id in self.waiting_on_resume_data: self.waiting_on_resume_data[torrent_id].callback(None) def on_alert_save_resume_data_failed(self, alert): """Alert handler for libtorrent save_resume_data_failed_alert""" try: torrent_id = str(alert.handle.info_hash()) except RuntimeError: return if torrent_id in self.waiting_on_resume_data: self.waiting_on_resume_data[torrent_id].errback( Exception(decode_bytes(alert.message())) ) def on_alert_fastresume_rejected(self, alert): """Alert handler for libtorrent fastresume_rejected_alert""" try: torrent_id = str(alert.handle.info_hash()) torrent = self.torrents[torrent_id] except (RuntimeError, KeyError): return alert_msg = decode_bytes(alert.message()) log.error("on_alert_fastresume_rejected: %s", alert_msg) if alert.error.value() == 134: if not os.path.isdir(torrent.options["download_location"]): error_msg = "Unable to locate Download Folder!" else: error_msg = "Missing or invalid torrent data!" else: error_msg = ( "Problem with resume data: %s" % alert_msg.split(":", 1)[1].strip() ) torrent.force_error_state(error_msg, restart_to_resume=True) def on_alert_file_renamed(self, alert): """Alert handler for libtorrent file_renamed_alert. Emits: TorrentFileRenamedEvent: Files in the torrent have been renamed. """ try: torrent_id = str(alert.handle.info_hash()) torrent = self.torrents[torrent_id] except (RuntimeError, KeyError): return new_name = decode_bytes(alert.new_name()) log.debug("index: %s name: %s", alert.index, new_name) # We need to see if this file index is in a waiting_on_folder dict for wait_on_folder in torrent.waiting_on_folder_rename: if alert.index in wait_on_folder: wait_on_folder[alert.index].callback(None) break else: # This is just a regular file rename so send the signal component.get("EventManager").emit( TorrentFileRenamedEvent(torrent_id, alert.index, new_name) ) self.save_resume_data((torrent_id,)) def on_alert_metadata_received(self, alert): """Alert handler for libtorrent metadata_received_alert""" try: torrent_id = str(alert.handle.info_hash()) except RuntimeError: return try: torrent = self.torrents[torrent_id] except KeyError: pass else: return torrent.on_metadata_received() # Try callback to prefetch_metadata method. try: d = self.prefetching_metadata[torrent_id].alert_deferred except KeyError: pass else: torrent_info = alert.handle.get_torrent_info() return d.callback(torrent_info) def on_alert_file_error(self, alert): """Alert handler for libtorrent file_error_alert""" try: torrent = self.torrents[str(alert.handle.info_hash())] except (RuntimeError, KeyError): return torrent.update_state() def on_alert_file_completed(self, alert): """Alert handler for libtorrent file_completed_alert Emits: TorrentFileCompletedEvent: When an individual file completes downloading. """ try: torrent_id = str(alert.handle.info_hash()) except RuntimeError: return if torrent_id in self.torrents: component.get("EventManager").emit( TorrentFileCompletedEvent(torrent_id, alert.index) ) def on_alert_state_update(self, alert): """Alert handler for libtorrent state_update_alert Result of a session.post_torrent_updates() call and contains the torrent status of all torrents that changed since last time this was posted. """ self.last_state_update_alert_ts = time.time() for t_status in alert.status: try: torrent_id = str(t_status.info_hash) except RuntimeError: continue if torrent_id in self.torrents: self.torrents[torrent_id].status = t_status self.handle_torrents_status_callback(self.torrents_status_requests.pop()) def on_alert_external_ip(self, alert): """Alert handler for libtorrent external_ip_alert""" log.info("on_alert_external_ip: %s", alert.external_address) component.get("EventManager").emit(ExternalIPEvent(alert.external_address)) def on_alert_performance(self, alert): """Alert handler for libtorrent performance_alert""" log.warning( "on_alert_performance: %s, %s", decode_bytes(alert.message()), alert.warning_code, ) if alert.warning_code == lt.performance_warning_t.send_buffer_watermark_too_low: max_send_buffer_watermark = 3 * 1024 * 1024 # 3MiB settings = self.session.get_settings() send_buffer_watermark = settings["send_buffer_watermark"] # If send buffer is too small, try increasing its size by 512KiB (up to max_send_buffer_watermark) if send_buffer_watermark < max_send_buffer_watermark: value = send_buffer_watermark + (500 * 1024) log.info( "Increasing send_buffer_watermark from %s to %s Bytes", send_buffer_watermark, value, ) component.get("Core").apply_session_setting( "send_buffer_watermark", value ) else: log.warning( "send_buffer_watermark reached maximum value: %s Bytes", max_send_buffer_watermark, ) def separate_keys(self, keys, torrent_ids): """Separates the input keys into torrent class keys and plugins keys""" if self.torrents: for torrent_id in torrent_ids: if torrent_id in self.torrents: status_keys = list(self.torrents[torrent_id].status_funcs) leftover_keys = list(set(keys) - set(status_keys)) torrent_keys = list(set(keys) - set(leftover_keys)) return torrent_keys, leftover_keys return [], [] def handle_torrents_status_callback(self, status_request): """Build the status dictionary with torrent values""" d, torrent_ids, keys, diff = status_request status_dict = {}.fromkeys(torrent_ids) torrent_keys, plugin_keys = self.separate_keys(keys, torrent_ids) # Get the torrent status for each torrent_id for torrent_id in torrent_ids: if torrent_id not in self.torrents: # The torrent_id does not exist in the dict. # Could be the clients cache (sessionproxy) isn't up to speed. del status_dict[torrent_id] else: status_dict[torrent_id] = self.torrents[torrent_id].get_status( torrent_keys, diff, all_keys=not keys ) self.status_dict = status_dict d.callback((status_dict, plugin_keys)) def torrents_status_update(self, torrent_ids, keys, diff=False): """Returns status dict for the supplied torrent_ids async. Note: If torrent states was updated recently post_torrent_updates is not called and instead cached state is used. Args: torrent_ids (list of str): The torrent IDs to get the status of. keys (list of str): The keys to get the status on. diff (bool, optional): If True, will return a diff of the changes since the last call to get_status based on the session_id, defaults to False. Returns: dict: A status dictionary for the requested torrents. """ d = Deferred() now = time.time() # If last update was recent, use cached data instead of request updates from libtorrent if (now - self.last_state_update_alert_ts) < 1.5: reactor.callLater( 0, self.handle_torrents_status_callback, (d, torrent_ids, keys, diff) ) else: # Ask libtorrent for status update self.torrents_status_requests.insert(0, (d, torrent_ids, keys, diff)) self.session.post_torrent_updates() return d
migrations
0005_auto_20220312_1215
# Generated by Django 3.2.12 on 2022-03-12 12:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("accounts", "0004_alter_user_first_name"), ] operations = [ migrations.RenameField( model_name="user", old_name="has_config_persional_info", new_name="has_set_personal_info", ), migrations.AlterField( model_name="user", name="has_set_personal_info", field=models.BooleanField( default=False, help_text="User has set their personal info" ), ), migrations.AlterField( model_name="user", name="has_configured_image_analysis", field=models.BooleanField( default=False, help_text="User has configured image analysis" ), ), migrations.AlterField( model_name="user", name="has_configured_importing", field=models.BooleanField( default=False, help_text="User has configured photo importing" ), ), migrations.AlterField( model_name="user", name="has_created_library", field=models.BooleanField( default=False, help_text="User has created a library" ), ), ]
photos
admin
from django.contrib import admin from .models import ( Camera, Lens, Library, LibraryPath, LibraryUser, Photo, PhotoFile, PhotoTag, Tag, ) class VersionedAdmin(admin.ModelAdmin): fieldsets = ( ( "Created/Updated", {"classes": ("collapse",), "fields": ("created_at", "updated_at")}, ), ) readonly_fields = ["created_at", "updated_at"] class LibraryUserInline(admin.TabularInline): model = LibraryUser exclude = ["created_at", "updated_at"] class LibraryPathInline(admin.TabularInline): model = LibraryPath exclude = ["created_at", "updated_at"] class LibraryAdmin(VersionedAdmin): list_display = ( "name", "classification_color_enabled", "classification_location_enabled", "classification_style_enabled", "classification_object_enabled", "classification_face_enabled", "setup_stage_completed", "created_at", "updated_at", ) list_ordering = ("name",) list_filter = ( "classification_color_enabled", "classification_location_enabled", "classification_style_enabled", "classification_object_enabled", "classification_face_enabled", "setup_stage_completed", ) inlines = [LibraryUserInline, LibraryPathInline] fieldsets = ( ( None, { "fields": ( "name", "classification_color_enabled", "classification_location_enabled", "classification_style_enabled", "classification_object_enabled", "classification_face_enabled", "setup_stage_completed", ), }, ), ) + VersionedAdmin.fieldsets class CameraAdmin(VersionedAdmin): list_display = ("id", "library", "make", "model", "earliest_photo", "latest_photo") list_ordering = ("make", "model") search_fields = ("id", "library__id", "make", "model") fieldsets = ( ( None, { "fields": ( "library", "make", "model", "earliest_photo", "latest_photo", ), }, ), ) + VersionedAdmin.fieldsets readonly_fields = ["earliest_photo", "latest_photo"] class LensAdmin(VersionedAdmin): list_display = ("id", "library", "name", "earliest_photo", "latest_photo") list_ordering = ("make", "model") search_fields = ("id", "library__id", "name") fieldsets = ( ( None, { "fields": ("library", "name", "earliest_photo", "latest_photo"), }, ), ) + VersionedAdmin.fieldsets readonly_fields = ["earliest_photo", "latest_photo"] class PhotoFileInline(admin.TabularInline): model = PhotoFile exclude = [ "created_at", "updated_at", ] readonly_fields = [ "file_modified_at", ] class PhotoTagInline(admin.TabularInline): model = PhotoTag exclude = [ "created_at", "updated_at", ] class PhotoAdmin(VersionedAdmin): list_display = ("id", "library", "visible", "taken_at", "taken_by") list_ordering = ("taken_at",) search_fields = ("id", "library__id") inlines = [PhotoFileInline, PhotoTagInline] fieldsets = ( ( None, { "fields": ( "library", "visible", "taken_at", "taken_by", "aperture", "exposure", "iso_speed", "focal_length", "flash", "metering_mode", "drive_mode", "shooting_mode", "camera", "lens", "latitude", "longitude", "altitude", ), }, ), ) + VersionedAdmin.fieldsets class TagAdmin(VersionedAdmin): list_display = ("id", "name", "library", "parent", "type", "source") list_ordering = ("name",) list_filter = ("type", "source") search_fields = ("id", "name", "library__id") fieldsets = ( ( None, { "fields": ("library", "name", "parent", "type", "source"), }, ), ) + VersionedAdmin.fieldsets admin.site.register(Library, LibraryAdmin) admin.site.register(Camera, CameraAdmin) admin.site.register(Lens, LensAdmin) admin.site.register(Photo, PhotoAdmin) admin.site.register(Tag, TagAdmin)
task
task
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # Copyright (C) 2009 Thomas Vander Stichele # This file is part of whipper. # # whipper is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # whipper is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with whipper. If not, see <http://www.gnu.org/licenses/>. import asyncio import logging import sys logger = logging.getLogger(__name__) class TaskException(Exception): """Wrap an exception that happened during task execution.""" exception = None # original exception def __init__(self, exception, message=None): self.exception = exception self.exceptionMessage = message self.args = ( exception, message, ) # lifted from flumotion log module def _getExceptionMessage(exception, frame=-1, filename=None): """ Return a short message based on an exception, useful for debugging. Tries to find where the exception was triggered. """ import traceback stack = traceback.extract_tb(sys.exc_info()[2]) if filename: stack = [f for f in stack if f[0].find(filename) > -1] # badly raised exceptions can come without a stack if stack: (filename, line, func, text) = stack[frame] else: (filename, line, func, text) = ("no stack", 0, "none", "") exc = exception.__class__.__name__ msg = "" # a shortcut to extract a useful message out of most exceptions # for now if str(exception): msg = ": %s" % str(exception) return "exception %(exc)s at %(filename)s:%(line)s: %(func)s()%(msg)s" % locals() class LogStub: """Stub for a log interface.""" @staticmethod def log(message, *args): logger.info(message, *args) @staticmethod def debug(message, *args): logger.debug(message, *args) @staticmethod def warning(message, *args): logger.warning(message, *args) class Task(LogStub): """ Wrap a task in an asynchronous interface. Can be listened to for starting, stopping, description changes and progress updates. I communicate an error by setting self.exception to an exception and stopping myself from running. The listener can then handle the Task.exception. :cvar description: what am I doing :cvar exception: set if an exception happened during the task execution. Will be raised through ``run()`` at the end """ logCategory = "Task" description = "I am doing something." progress = 0.0 increment = 0.01 running = False runner = None exception = None exceptionMessage = None exceptionTraceback = None _listeners = None # subclass methods def start(self, runner): """ Start the task. Subclasses should chain up to me at the beginning. Subclass implementations should raise exceptions immediately in case of failure (using set(AndRaise)Exception) first, or do it later using those methods. If start doesn't raise an exception, the task should run until complete, or ``setException()`` and ``stop()``. """ self.debug("starting") self.setProgress(self.progress) self.running = True self.runner = runner self._notifyListeners("started") def stop(self): """ Stop the task. Also resets the runner on the task. Subclasses should chain up to me at the end. It is important that they do so in all cases, even when they ran into an exception of their own. Listeners will get notified that the task is stopped, whether successfully or with an exception. """ self.debug("stopping") self.running = False if not self.runner: print("ERROR: stopping task which is already stopped") import traceback traceback.print_stack() self.runner = None self.debug("reset runner to None") self._notifyListeners("stopped") # base class methods def setProgress(self, value): """ Notify about progress changes bigger than the increment. Called by subclass implementations as the task progresses. """ if value - self.progress > self.increment or value >= 1.0 or value == 0.0: self.progress = value self._notifyListeners("progressed", value) self.debug("notifying progress: %r on %r", value, self.description) def setDescription(self, description): if description != self.description: self._notifyListeners("described", description) self.description = description # FIXME: unify? def setExceptionAndTraceback(self, exception): """ Call this to set a synthetically created exception. Not one that was actually raised and caught. """ import traceback stack = traceback.extract_stack()[:-1] (filename, line, func, text) = stack[-1] exc = exception.__class__.__name__ msg = "" # a shortcut to extract a useful message out of most exceptions # for now if str(exception): msg = ": %s" % str(exception) line = ( "exception %(exc)s at %(filename)s:%(line)s: " "%(func)s()%(msg)s" % locals() ) self.exception = exception self.exceptionMessage = line self.exceptionTraceback = traceback.format_exc() self.debug("set exception, %r" % self.exceptionMessage) # FIXME: remove setAndRaiseException = setExceptionAndTraceback def setException(self, exception): """Call this to set a caught exception on the task.""" import traceback self.exception = exception self.exceptionMessage = _getExceptionMessage(exception) self.exceptionTraceback = traceback.format_exc() self.debug("set exception, %r, %r" % (exception, self.exceptionMessage)) def schedule(self, delta, callable_task, *args, **kwargs): if not self.runner: print("ERROR: scheduling on a task that's altready stopped") import traceback traceback.print_stack() return self.runner.schedule(self, delta, callable_task, *args, **kwargs) def addListener(self, listener): """ Add a listener for task status changes. Listeners should implement started, stopped, and progressed. """ self.debug("Adding listener %r", listener) if not self._listeners: self._listeners = [] self._listeners.append(listener) def _notifyListeners(self, methodName, *args, **kwargs): if self._listeners: for listener in self._listeners: method = getattr(listener, methodName) try: method(self, *args, **kwargs) # FIXME: catching too general exception (Exception) except Exception as e: self.setException(e) # FIXME: should this become a real interface, like in zope ? class ITaskListener: """An interface for objects listening to tasks.""" # listener callbacks def progressed(self, task, value): """ Implement me to be informed about progress. :param task: a task :type task: Task :param value: progress, from 0.0 to 1.0 :type value: float """ def described(self, task, description): """ Implement me to be informed about description changes. :param task: a task :type task: Task :param description: description :type description: str """ def started(self, task): """Implement me to be informed about the task starting.""" def stopped(self, task): """ Implement me to be informed about the task stopping. If the task had an error, task.exception will be set. """ # this is a Dummy task that can be used to test if this works at all class DummyTask(Task): def start(self, runner): Task.start(self, runner) self.schedule(1.0, self._wind) def _wind(self): self.setProgress(min(self.progress + 0.1, 1.0)) if self.progress >= 1.0: self.stop() return self.schedule(1.0, self._wind) class BaseMultiTask(Task, ITaskListener): """ I perform multiple tasks. :cvar tasks: the tasks to run :vartype tasks: list(Task) """ description = "Doing various tasks" tasks = None def __init__(self): self.tasks = [] self._task = 0 def addTask(self, task): """ Add a task. :type task: Task """ if self.tasks is None: self.tasks = [] self.tasks.append(task) def start(self, runner): """ Start tasks. Tasks can still be added while running. For example, a first task can determine how many additional tasks to run. """ Task.start(self, runner) # initialize task tracking if not self.tasks: self.warning("no tasks") self._generic = self.description self.next() def next(self): """Start the next task.""" try: # start next task task = self.tasks[self._task] self._task += 1 self.debug( "BaseMultiTask.next(): starting task %d of %d: %r", self._task, len(self.tasks), task, ) self.setDescription( "%s (%d of %d) ..." % (task.description, self._task, len(self.tasks)) ) task.addListener(self) task.start(self.runner) self.debug( "BaseMultiTask.next(): started task %d of %d: %r", self._task, len(self.tasks), task, ) # FIXME: catching too general exception (Exception) except Exception as e: self.setException(e) self.debug("Got exception during next: %r", self.exceptionMessage) self.stop() return # ITaskListener methods def started(self, task): pass def progressed(self, task, value): pass def stopped(self, task): # noqa: D401 """ Subclasses should chain up to me at the end of their implementation. They should fall through to chaining up if there is an exception. """ self.debug( "BaseMultiTask.stopped: task %r (%d of %d)", task, self.tasks.index(task) + 1, len(self.tasks), ) if task.exception: self.warning("BaseMultiTask.stopped: exception %r", task.exceptionMessage) self.exception = task.exception self.exceptionMessage = task.exceptionMessage self.stop() return if self._task == len(self.tasks): self.debug("BaseMultiTask.stopped: all tasks done") self.stop() return # pick another self.debug("BaseMultiTask.stopped: pick next task") self.schedule(0, self.next) class MultiSeparateTask(BaseMultiTask): """ Perform multiple tasks. Track progress of each individual task, going back to 0 for each task. """ description = "Doing various tasks separately" def start(self, runner): self.debug("MultiSeparateTask.start()") BaseMultiTask.start(self, runner) def next(self): self.debug("MultiSeparateTask.next()") # start next task self.progress = 0.0 # reset progress for each task BaseMultiTask.next(self) # ITaskListener methods def progressed(self, task, value): self.setProgress(value) def described(self, description): self.setDescription( "%s (%d of %d) ..." % (description, self._task, len(self.tasks)) ) class MultiCombinedTask(BaseMultiTask): """ Perform multiple tasks. Track progress as a combined progress on all tasks on task granularity. """ description = "Doing various tasks combined" _stopped = 0 # ITaskListener methods def progressed(self, task, value): self.setProgress(float(self._stopped + value) / len(self.tasks)) def stopped(self, task): self._stopped += 1 self.setProgress(float(self._stopped) / len(self.tasks)) BaseMultiTask.stopped(self, task) class TaskRunner(LogStub): """ Base class for task runners. Task runners should be reusable. """ logCategory = "TaskRunner" def run(self, task): """ Run the given task. :type task: Task """ raise NotImplementedError # methods for tasks to call def schedule(self, delta, callable_task, *args, **kwargs): """ Schedule a single future call. Subclasses should implement this. :param delta: time in the future to schedule call for, in seconds. :type delta: float :param callable_task: a task :type callable_task: Task """ raise NotImplementedError class SyncRunner(TaskRunner, ITaskListener): """Run the task synchronously in an asyncio event loop.""" def __init__(self, verbose=True): self._verbose = verbose self._longest = 0 # longest string shown; for clearing def run(self, task, verbose=None, skip=False): self.debug("run task %r", task) self._task = task self._verboseRun = self._verbose if verbose is not None: self._verboseRun = verbose self._skip = skip self._loop = asyncio.new_event_loop() self._task.addListener(self) # only start the task after going into the mainloop, # otherwise the task might complete before we are in it self._loop.call_soon(self._startWrap, self._task) self.debug("run loop") self._loop.run_forever() self.debug("done running task %r", task) if task.exception: # catch the exception message # FIXME: this gave a traceback in the logging module self.debug( "raising TaskException for %r, %r" % (task.exceptionMessage, task.exceptionTraceback) ) msg = task.exceptionMessage if task.exceptionTraceback: msg += "\n" + task.exceptionTraceback raise TaskException(task.exception, message=msg) def _startWrap(self, task): # wrap task start such that we can report any exceptions and # never hang try: self.debug("start task %r" % task) task.start(self) # FIXME: catching too general exception (Exception) except Exception as e: # getExceptionMessage uses global exception state that doesn't # hang around, so store the message task.setException(e) self.debug("exception during start: %r", task.exceptionMessage) self.stopped(task) def schedule(self, task, delta, callable_task, *args, **kwargs): def c(): try: callable_task(*args, **kwargs) return False except Exception as e: self.debug( "exception when calling scheduled callable %r", callable_task ) task.setException(e) self.stopped(task) raise self._loop.call_later(delta, c) # ITaskListener methods def progressed(self, task, value): if not self._verboseRun: return self._report() if value >= 1.0: if self._skip: self._output("%s %3d %%" % (self._task.description, 100.0)) else: # clear with whitespace print(("%s\r" % (" " * self._longest,)), end="") def _output(self, what, newline=False, ret=True): print(what, end="") print((" " * (self._longest - len(what))), end="") if ret: print("\r", end="") if newline: print("") sys.stdout.flush() if len(what) > self._longest: self._longest = len(what) def described(self, task, description): if self._verboseRun: self._report() def stopped(self, task): self.debug("stopped task %r", task) self.progressed(task, 1.0) self._loop.stop() def _report(self): self._output( "%s %3d %%" % (self._task.description, self._task.progress * 100.0) ) if __name__ == "__main__": task = DummyTask() runner = SyncRunner() runner.run(task)
webservice
ratecontrol
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2007 Lukáš Lalinský # Copyright (C) 2009 Carlin Mangar # Copyright (C) 2017 Sambhav Kothari # Copyright (C) 2018, 2020-2021 Laurent Monin # Copyright (C) 2019, 2022 Philipp Wolfer # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import math import sys import time from collections import defaultdict from picard import log from picard.webservice.utils import hostkey_from_url # ============================================================================ # Throttling/congestion avoidance # ============================================================================ # Throttles requests to a given hostkey by assigning a minimum delay between # requests in milliseconds. # # Plugins may assign limits to their associated service(s) like so: # # >>> from picard.webservice import ratecontrol # >>> ratecontrol.set_minimum_delay(('myservice.org', 80), 100) # 10 requests/second # Minimun delay for the given hostkey (in milliseconds), can be set using # set_minimum_delay() REQUEST_DELAY_MINIMUM = defaultdict(lambda: 1000) # Current delay (adaptive) between requests to a given hostkey. REQUEST_DELAY = defaultdict(lambda: 1000) # Conservative initial value. # Determines delay during exponential backoff phase. REQUEST_DELAY_EXPONENT = defaultdict(lambda: 0) # Unacknowledged request counter. # # Bump this when handing a request to QNetworkManager and trim when receiving # a response. CONGESTION_UNACK = defaultdict(lambda: 0) # Congestion window size in terms of unacked requests. # # We're allowed to send up to `int(this)` many requests at a time. CONGESTION_WINDOW_SIZE = defaultdict(lambda: 1.0) # Slow start threshold. # # After placing this many unacknowledged requests on the wire, switch from # slow start to congestion avoidance. (See `_adjust_throttle`.) Initialized # upon encountering a temporary error. CONGESTION_SSTHRESH = defaultdict(lambda: 0) # Storage of last request times per host key LAST_REQUEST_TIMES = defaultdict(lambda: 0) def set_minimum_delay(hostkey, delay_ms): """Set the minimun delay between requests hostkey is an unique key, for example (host, port) delay_ms is the delay in milliseconds """ REQUEST_DELAY_MINIMUM[hostkey] = delay_ms def set_minimum_delay_for_url(url, delay_ms): """Set the minimun delay between requests url will be converted to an unique key (host, port) delay_ms is the delay in milliseconds """ set_minimum_delay(hostkey_from_url(url), delay_ms) def current_delay(hostkey): """Returns the current delay (adaptive) between requests for this hostkey hostkey is an unique key, for example (host, port) """ return REQUEST_DELAY[hostkey] def get_delay_to_next_request(hostkey): """Calculate delay to next request to hostkey (host, port) returns a tuple (wait, delay) where: wait is True if a delay is needed delay is the delay in milliseconds to next request """ if CONGESTION_UNACK[hostkey] >= int(CONGESTION_WINDOW_SIZE[hostkey]): # We've maxed out the number of requests to `hostkey`, so wait # until responses begin to come back. (See `_timer_run_next_task` # strobe in `_handle_reply`.) return (True, sys.maxsize) interval = REQUEST_DELAY[hostkey] if not interval: log.debug("%s: Starting another request without delay", hostkey) return (False, 0) last_request = LAST_REQUEST_TIMES[hostkey] if not last_request: log.debug("%s: First request", hostkey) _remember_request_time(hostkey) # set it on first run return (False, interval) elapsed = (time.time() - last_request) * 1000 if elapsed >= interval: log.debug( "%s: Last request was %d ms ago, starting another one", hostkey, elapsed ) return (False, interval) delay = int(math.ceil(interval - elapsed)) log.debug( "%s: Last request was %d ms ago, waiting %d ms before starting another one", hostkey, elapsed, delay, ) return (True, delay) def _remember_request_time(hostkey): if REQUEST_DELAY[hostkey]: LAST_REQUEST_TIMES[hostkey] = time.time() def increment_requests(hostkey): """Store the request time for this hostkey, and increment counter It has to be called on each request """ _remember_request_time(hostkey) # Increment the number of unack'd requests on sending a new one CONGESTION_UNACK[hostkey] += 1 log.debug("%s: Incrementing requests to: %d", hostkey, CONGESTION_UNACK[hostkey]) def decrement_requests(hostkey): """Decrement counter, it has to be called on each reply""" assert CONGESTION_UNACK[hostkey] > 0 CONGESTION_UNACK[hostkey] -= 1 log.debug("%s: Decrementing requests to: %d", hostkey, CONGESTION_UNACK[hostkey]) def copy_minimal_delay(from_hostkey, to_hostkey): """Copy minimal delay from one hostkey to another Useful for redirections """ if ( from_hostkey in REQUEST_DELAY_MINIMUM and to_hostkey not in REQUEST_DELAY_MINIMUM ): REQUEST_DELAY_MINIMUM[to_hostkey] = REQUEST_DELAY_MINIMUM[from_hostkey] log.debug( "%s: Copy minimun delay from %s, setting it to %dms", to_hostkey, from_hostkey, REQUEST_DELAY_MINIMUM[to_hostkey], ) def adjust(hostkey, slow_down): """Adjust `REQUEST` and `CONGESTION` metrics when a HTTP request completes. Args: hostkey: `(host, port)`. slow_down: `True` if we encountered intermittent server trouble and need to slow down. """ if slow_down: _slow_down(hostkey) elif CONGESTION_UNACK[hostkey] <= CONGESTION_WINDOW_SIZE[hostkey]: # not in backoff phase anymore _out_of_backoff(hostkey) def _slow_down(hostkey): # Backoff exponentially until ~30 seconds between requests. delay = max( pow(2, REQUEST_DELAY_EXPONENT[hostkey]) * 1000, REQUEST_DELAY_MINIMUM[hostkey] ) REQUEST_DELAY_EXPONENT[hostkey] = min(REQUEST_DELAY_EXPONENT[hostkey] + 1, 5) # Slow start threshold is ~1/2 of the window size up until we saw # trouble. Shrink the new window size back to 1. CONGESTION_SSTHRESH[hostkey] = int(CONGESTION_WINDOW_SIZE[hostkey] / 2.0) CONGESTION_WINDOW_SIZE[hostkey] = 1.0 log.debug( "%s: slowdown; delay: %dms -> %dms; ssthresh: %d; cws: %.3f", hostkey, REQUEST_DELAY[hostkey], delay, CONGESTION_SSTHRESH[hostkey], CONGESTION_WINDOW_SIZE[hostkey], ) REQUEST_DELAY[hostkey] = delay def _out_of_backoff(hostkey): REQUEST_DELAY_EXPONENT[hostkey] = 0 # Coming out of backoff, so reset. # Shrink the delay between requests with each successive reply to # converge on maximum throughput. delay = max(int(REQUEST_DELAY[hostkey] / 2), REQUEST_DELAY_MINIMUM[hostkey]) cws = CONGESTION_WINDOW_SIZE[hostkey] sst = CONGESTION_SSTHRESH[hostkey] if sst and cws >= sst: # Analogous to TCP's congestion avoidance phase. Window growth is linear. phase = "congestion avoidance" cws = cws + (1.0 / cws) else: # Analogous to TCP's slow start phase. Window growth is exponential. phase = "slow start" cws += 1 if REQUEST_DELAY[hostkey] != delay or CONGESTION_WINDOW_SIZE[hostkey] != cws: log.debug( "%s: oobackoff; delay: %dms -> %dms; %s; window size %.3f -> %.3f", hostkey, REQUEST_DELAY[hostkey], delay, phase, CONGESTION_WINDOW_SIZE[hostkey], cws, ) CONGESTION_WINDOW_SIZE[hostkey] = cws REQUEST_DELAY[hostkey] = delay
BasicDrawing
FrameworkUtilities
import AppDrawing from Cocoa import * from Quartz import * def myCreatePDFDataFromPasteBoard(): # Obtain the pasteboard to examine. pboard = NSPasteboard.generalPasteboard() # Scan the types of data on the pasteboard and return the first type available that is # listed in the array supplied. Here the array of requested types contains only one type, # that of PDF data. If your application could handle more types, you would list them in # the creation of this array. type = pboard.availableTypeFromArray_([NSPDFPboardType]) # If the string is non-nil, there was data of one of our requested types # on the pasteboard that can be obtained. if type is not None: # Test that the type is the PDF data type. This code is not strictly necessary # for this example since we only said we could handle PDF data, but is appropriate # if you can handle more types than just PDF. if type == NSPDFPboardType: # Get the PDF data from the pasteboard. pdfData = pboard.dataForType_(type) if pdfData is not None: return pdfData else: NSLog("Couldn't get PDF data from pasteboard!") else: NSLog("Pasteboard doesn't contain PDF data!") return None def addPDFDataToPasteBoard(command): pdfData = cfDataCreatePDFDocumentFromCommand(command) if pdfData is not None: pboard = NSPasteboard.generalPasteboard() pboard.declareTypes_owner_(NSPDFPboardType, None) pboard.setData_forType_(pdfData, NSPDFPboardType)
slicing
exceptions
""" Slicing related exceptions. .. autoclass:: SlicingException .. autoclass:: SlicingCancelled :show-inheritance: .. autoclass:: SlicerException :show-inheritance: .. autoclass:: UnknownSlicer :show-inheritance: .. autoclass:: SlicerNotConfigured :show-inheritance: .. autoclass:: ProfileException .. autoclass:: UnknownProfile :show-inheritance: .. autoclass:: ProfileAlreadyExists :show-inheritance: """ __author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" class SlicingException(Exception): """ Base exception of all slicing related exceptions. """ pass class SlicingCancelled(SlicingException): """ Raised if a slicing job was cancelled. """ pass class SlicerException(SlicingException): """ Base exception of all slicer related exceptions. .. attribute:: slicer Identifier of the slicer for which the exception was raised. """ def __init__(self, slicer, *args, **kwargs): SlicingException.__init__(self, *args, **kwargs) self.slicer = slicer class SlicerNotConfigured(SlicerException): """ Raised if a slicer is not yet configured but must be configured to proceed. """ def __init__(self, slicer, *args, **kwargs): SlicerException.__init__(self, slicer, *args, **kwargs) self.message = f"Slicer not configured: {slicer}" class UnknownSlicer(SlicerException): """ Raised if a slicer is unknown. """ def __init__(self, slicer, *args, **kwargs): SlicerException.__init__(self, slicer, *args, **kwargs) self.message = f"No such slicer: {slicer}" class ProfileException(Exception): """ Base exception of all slicing profile related exceptions. .. attribute:: slicer Identifier of the slicer to which the profile belongs. .. attribute:: profile Identifier of the profile for which the exception was raised. """ def __init__(self, slicer, profile, *args, **kwargs): Exception.__init__(self, *args, **kwargs) self.slicer = slicer self.profile = profile class UnknownProfile(ProfileException): """ Raised if a slicing profile does not exist but must exist to proceed. """ def __init__(self, slicer, profile, *args, **kwargs): ProfileException.__init__(self, slicer, profile, *args, **kwargs) self.message = "Profile {profile} for slicer {slicer} does not exist".format( profile=profile, slicer=slicer ) class ProfileAlreadyExists(ProfileException): """ Raised if a slicing profile already exists and must not be overwritten. """ def __init__(self, slicer, profile, *args, **kwargs): ProfileException.__init__(self, slicer, profile, *args, **kwargs) self.message = "Profile {profile} for slicer {slicer} already exists".format( profile=profile, slicer=slicer ) class CouldNotDeleteProfile(ProfileException): """ Raised if there is an unexpected error trying to delete a known profile. """ def __init__(self, slicer, profile, cause=None, *args, **kwargs): ProfileException.__init__(self, slicer, profile, *args, **kwargs) self.cause = cause if cause: self.message = "Could not delete profile {profile} for slicer {slicer}: {cause}".format( profile=profile, slicer=slicer, cause=str(cause) ) else: self.message = ( "Could not delete profile {profile} for slicer {slicer}".format( profile=profile, slicer=slicer ) )
migrations
0212_alter_persondistinctid_team
# Generated by Django 3.2.5 on 2022-02-17 10:03 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): atomic = False # DROP INDEX CONCURRENTLY cannot be run in a transaction dependencies = [ ("posthog", "0211_async_migrations_errors_length"), ] operations = [ # Below is the original migration generated by running `./manage.py # makemigrations posthog`. We replace this migration which performs a # blocking DROP INDEX with one that does so using the postgresql # [CONCURRENTLY # keyword](https://www.postgresql.org/docs/9.3/sql-dropindex.html) # # To do so we need to make sure that Djangos state is update such that # it doesn't think that there is an index on the field (otherwise on # next run or ./manage.py makemigrations we'd end up generating another # migration), and also actually perform the database mutations. # # migrations.AlterField( # model_name='persondistinctid', # name='team', # field=models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, to='posthog.team'), # ), # # Which generates the sql, as seen by `./manage.py sqlmigrate posthog # 0212` # # BEGIN; # -- # -- Alter field team on persondistinctid # -- # SET CONSTRAINTS "posthog_persondistinctid_team_id_46330ec9_fk_posthog_team_id" IMMEDIATE; ALTER TABLE "posthog_persondistinctid" DROP CONSTRAINT "posthog_persondistinctid_team_id_46330ec9_fk_posthog_team_id"; # DROP INDEX IF EXISTS "posthog_persondistinctid_team_id_46330ec9"; # ALTER TABLE "posthog_persondistinctid" ADD CONSTRAINT "posthog_persondistinctid_team_id_46330ec9_fk_posthog_team_id" FOREIGN KEY ("team_id") REFERENCES "posthog_team" ("id") DEFERRABLE INITIALLY DEFERRED; # COMMIT; # # migrations.SeparateDatabaseAndState( state_operations=[ migrations.AlterField( model_name="persondistinctid", name="team", field=models.ForeignKey( db_index=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team", ), ) ], database_operations=[ # NOTE: there is a # `django.contrib.postgres.operations.RemoveIndexConcurrently` # but this appears to only work with explicit indices rather # than indicies from `ForeignKey` as far as I can tell. migrations.RunSQL( sql='DROP INDEX CONCURRENTLY IF EXISTS "posthog_persondistinctid_team_id_46330ec9";', reverse_sql="CREATE INDEX posthog_persondistinctid_team_id_46330ec9 ON public.posthog_persondistinctid USING btree (team_id);", ) ], ) ]
model
abstract_abbreviation
# Copyright (C) 2011 Chris Dekter # Copyright (C) 2019-2020 Thomas Hess <thomas.hess@udo.edu> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import re import typing from autokey.model.helpers import DEFAULT_WORDCHAR_REGEX, TriggerMode class AbstractAbbreviation: """ Abstract class encapsulating the common functionality of an abbreviation list """ def __init__(self): self.abbreviations = [] # type: typing.List[str] self.backspace = True self.ignoreCase = False self.immediate = False self.triggerInside = False self.set_word_chars(DEFAULT_WORDCHAR_REGEX) def get_serializable(self): d = { "abbreviations": self.abbreviations, "backspace": self.backspace, "ignoreCase": self.ignoreCase, "immediate": self.immediate, "triggerInside": self.triggerInside, "wordChars": self.get_word_chars(), } return d def load_from_serialized(self, data: dict): if "abbreviations" not in data: # check for pre v0.80.4 self.abbreviations = [data["abbreviation"]] # type: typing.List[str] else: self.abbreviations = data["abbreviations"] # type: typing.List[str] self.backspace = data["backspace"] self.ignoreCase = data["ignoreCase"] self.immediate = data["immediate"] self.triggerInside = data["triggerInside"] self.set_word_chars(data["wordChars"]) def copy_abbreviation(self, abbr): self.abbreviations = abbr.abbreviations self.backspace = abbr.backspace self.ignoreCase = abbr.ignoreCase self.immediate = abbr.immediate self.triggerInside = abbr.triggerInside self.set_word_chars(abbr.get_word_chars()) def set_word_chars(self, regex): self.wordChars = re.compile(regex, re.UNICODE) def get_word_chars(self): return self.wordChars.pattern def add_abbreviation(self, abbr): if not isinstance(abbr, str): raise ValueError( "Abbreviations must be strings. Cannot add abbreviation '{}', having type {}.".format( abbr, type(abbr) ) ) self.abbreviations.append(abbr) if TriggerMode.ABBREVIATION not in self.modes: self.modes.append(TriggerMode.ABBREVIATION) def add_abbreviations(self, abbreviation_list: typing.Iterable[str]): if not isinstance(abbreviation_list, list): abbreviation_list = list(abbreviation_list) if not all(isinstance(abbr, str) for abbr in abbreviation_list): raise ValueError("All added Abbreviations must be strings.") self.abbreviations += abbreviation_list if TriggerMode.ABBREVIATION not in self.modes: self.modes.append(TriggerMode.ABBREVIATION) def clear_abbreviations(self): self.abbreviations = [] def get_abbreviations(self): if TriggerMode.ABBREVIATION not in self.modes: return "" elif len(self.abbreviations) == 1: return self.abbreviations[0] else: return "[" + ",".join(self.abbreviations) + "]" def _should_trigger_abbreviation(self, buffer): """ Checks whether, based on the settings for the abbreviation and the given input, the abbreviation should trigger. @param buffer Input buffer to be checked (as string) """ return any(self.__checkInput(buffer, abbr) for abbr in self.abbreviations) def _get_trigger_abbreviation(self, buffer): for abbr in self.abbreviations: if self.__checkInput(buffer, abbr): return abbr return None def __checkInput(self, buffer, abbr): stringBefore, typedAbbr, stringAfter = self._partition_input(buffer, abbr) if len(typedAbbr) > 0: # Check trigger character condition if not self.immediate: # If not immediate expansion, check last character if len(stringAfter) == 1: # Have a character after abbr if self.wordChars.match(stringAfter): # last character(s) is a word char, can't send expansion return False elif len(stringAfter) > 1: # Abbr not at/near end of buffer any more, can't send return False else: # Nothing after abbr yet, can't expand yet return False else: # immediate option enabled, check abbr is at end of buffer if len(stringAfter) > 0: return False # Check chars ahead of abbr # length of stringBefore should always be > 0 if ( len(stringBefore) > 0 and not re.match("(^\s)", stringBefore[-1]) and not self.triggerInside ): # check if last char before the typed abbreviation is a word char # if triggerInside is not set, can't trigger when inside a word return False return True return False def _partition_input( self, current_string: str, abbr: typing.Optional[str] ) -> typing.Tuple[str, str, str]: """ Partition the input into text before, typed abbreviation (if it exists), and text after """ if abbr: if self.ignoreCase: ( string_before, typed_abbreviation, string_after, ) = self._case_insensitive_rpartition(current_string, abbr) abbr_start_index = len(string_before) abbr_end_index = abbr_start_index + len(typed_abbreviation) typed_abbreviation = current_string[abbr_start_index:abbr_end_index] else: ( string_before, typed_abbreviation, string_after, ) = current_string.rpartition(abbr) return string_before, typed_abbreviation, string_after else: # abbr is None. This happens if the phrase was typed/pasted using a hotkey and is about to be un-done. # In this case, there is no trigger character (thus empty before and after text). The complete string # should be undone. return "", current_string, "" @staticmethod def _case_insensitive_rpartition( input_string: str, separator: str ) -> typing.Tuple[str, str, str]: """Same as str.rpartition(), except that the partitioning is done case insensitive.""" lowered_input_string = input_string.lower() lowered_separator = separator.lower() try: split_index = lowered_input_string.rindex(lowered_separator) except ValueError: # Did not find the separator in the input_string. # Follow https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str # str.rpartition documentation and return the tuple ("", "", unmodified_input) in this case return "", "", input_string else: split_index_2 = split_index + len(separator) return ( input_string[:split_index], input_string[split_index:split_index_2], input_string[split_index_2:], )
logging
handlers
import concurrent.futures import logging.handlers import os import re import time class AsyncLogHandlerMixin(logging.Handler): def __init__(self, *args, **kwargs): self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) super().__init__(*args, **kwargs) def emit(self, record): if getattr(self._executor, "_shutdown", False): return try: self._executor.submit(self._emit, record) except Exception: self.handleError(record) def _emit(self, record): # noinspection PyUnresolvedReferences super().emit(record) def close(self): self._executor.shutdown(wait=True) super().close() class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler): def __init__(self, *args, **kwargs): kwargs["encoding"] = kwargs.get("encoding", "utf-8") super().__init__(*args, **kwargs) # clean up old files on handler start if self.backupCount > 0: for s in self.getFilesToDelete(): os.remove(s) class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler): rollover_callbacks = [] def __init__(self, *args, **kwargs): kwargs["encoding"] = kwargs.get("encoding", "utf-8") super().__init__(*args, **kwargs) @classmethod def registerRolloverCallback(cls, callback, *args, **kwargs): cls.rollover_callbacks.append((callback, args, kwargs)) def doRollover(self): super().doRollover() for rcb in self.rollover_callbacks: callback, args, kwargs = rcb callback(*args, **kwargs) class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler): pass class TriggeredRolloverLogHandler( AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler ): do_rollover = False suffix_template = "%Y-%m-%d_%H-%M-%S" file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$") @classmethod def arm_rollover(cls): cls.do_rollover = True def __init__(self, *args, **kwargs): kwargs["encoding"] = kwargs.get("encoding", "utf-8") super().__init__(*args, **kwargs) self.cleanupFiles() def shouldRollover(self, record): return self.do_rollover def getFilesToDelete(self): """ Determine the files to delete when rolling over. """ dirName, baseName = os.path.split(self.baseFilename) fileNames = os.listdir(dirName) result = [] prefix = baseName + "." plen = len(prefix) for fileName in fileNames: if fileName[:plen] == prefix: suffix = fileName[plen:] if type(self).file_pattern.match(suffix): result.append(os.path.join(dirName, fileName)) result.sort() if len(result) < self.backupCount: result = [] else: result = result[: len(result) - self.backupCount] return result def cleanupFiles(self): if self.backupCount > 0: for path in self.getFilesToDelete(): os.remove(path) def doRollover(self): self.do_rollover = False if self.stream: self.stream.close() self.stream = None if os.path.exists(self.baseFilename): # figure out creation date/time to use for file suffix t = time.localtime(os.stat(self.baseFilename).st_mtime) dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t) if os.path.exists(dfn): os.remove(dfn) os.rename(self.baseFilename, dfn) self.cleanupFiles() if not self.delay: self.stream = self._open() class SerialLogHandler(TriggeredRolloverLogHandler): pass class PluginTimingsLogHandler(TriggeredRolloverLogHandler): pass class TornadoLogHandler(CleaningTimedRotatingFileHandler): pass class AuthLogHandler(CleaningTimedRotatingFileHandler): pass class RecordingLogHandler(logging.Handler): def __init__(self, target=None, *args, **kwargs): super().__init__(*args, **kwargs) self._buffer = [] self._target = target def emit(self, record): self._buffer.append(record) def setTarget(self, target): self._target = target def flush(self): if not self._target: return self.acquire() try: for record in self._buffer: self._target.handle(record) self._buffer = [] finally: self.release() def close(self): self.flush() self.acquire() try: self._buffer = [] finally: self.release() def __len__(self): return len(self._buffer) # noinspection PyAbstractClass class CombinedLogHandler(logging.Handler): def __init__(self, *handlers): logging.Handler.__init__(self) self._handlers = handlers def setHandlers(self, *handlers): self._handlers = handlers def handle(self, record): self.acquire() try: if self._handlers: for handler in self._handlers: handler.handle(record) finally: self.release()
extractor
c56
# coding: utf-8 from __future__ import unicode_literals import re from ..utils import js_to_json from .common import InfoExtractor class C56IE(InfoExtractor): _VALID_URL = r"https?://(?:(?:www|player)\.)?56\.com/(?:.+?/)?(?:v_|(?:play_album.+-))(?P<textid>.+?)\.(?:html|swf)" IE_NAME = "56.com" _TESTS = [ { "url": "http://www.56.com/u39/v_OTM0NDA3MTY.html", "md5": "e59995ac63d0457783ea05f93f12a866", "info_dict": { "id": "93440716", "ext": "flv", "title": "网事知多少 第32期:车怒", "duration": 283.813, }, }, { "url": "http://www.56.com/u47/v_MTM5NjQ5ODc2.html", "md5": "", "info_dict": { "id": "82247482", "title": "爱的诅咒之杜鹃花开", }, "playlist_count": 7, "add_ie": ["Sohu"], }, ] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE) text_id = mobj.group("textid") webpage = self._download_webpage(url, text_id) sohu_video_info_str = self._search_regex( r"var\s+sohuVideoInfo\s*=\s*({[^}]+});", webpage, "Sohu video info", default=None, ) if sohu_video_info_str: sohu_video_info = self._parse_json( sohu_video_info_str, text_id, transform_source=js_to_json ) return self.url_result(sohu_video_info["url"], "Sohu") page = self._download_json( "http://vxml.56.com/json/%s/" % text_id, text_id, "Downloading video info" ) info = page["info"] formats = [ {"format_id": f["type"], "filesize": int(f["filesize"]), "url": f["url"]} for f in info["rfiles"] ] self._sort_formats(formats) return { "id": info["vid"], "title": info["Subject"], "duration": int(info["duration"]) / 1000.0, "formats": formats, "thumbnail": info.get("bimg") or info.get("img"), }
api
ee_event_definition
from django.utils import timezone from ee.models.event_definition import EnterpriseEventDefinition from posthog.api.shared import UserBasicSerializer from posthog.api.tagged_item import TaggedItemSerializerMixin from posthog.models.activity_logging.activity_log import ( Detail, dict_changes_between, log_activity, ) from rest_framework import serializers class EnterpriseEventDefinitionSerializer( TaggedItemSerializerMixin, serializers.ModelSerializer ): updated_by = UserBasicSerializer(read_only=True) verified_by = UserBasicSerializer(read_only=True) created_by = UserBasicSerializer(read_only=True) is_action = serializers.SerializerMethodField(read_only=True) action_id = serializers.IntegerField(read_only=True) is_calculating = serializers.BooleanField(read_only=True) last_calculated_at = serializers.DateTimeField(read_only=True) last_updated_at = serializers.DateTimeField(read_only=True) post_to_slack = serializers.BooleanField(default=False) class Meta: model = EnterpriseEventDefinition fields = ( "id", "name", "owner", "description", "tags", "created_at", "updated_at", "updated_by", "last_seen_at", "last_updated_at", "verified", "verified_at", "verified_by", # Action fields "is_action", "action_id", "is_calculating", "last_calculated_at", "created_by", "post_to_slack", ) read_only_fields = [ "id", "name", "created_at", "updated_at", "last_seen_at", "last_updated_at", "verified_at", "verified_by", # Action fields "is_action", "action_id", "is_calculating", "last_calculated_at", "created_by", ] def update(self, event_definition: EnterpriseEventDefinition, validated_data): validated_data["updated_by"] = self.context["request"].user if "verified" in validated_data: if validated_data["verified"] and not event_definition.verified: # Verify event only if previously unverified validated_data["verified_by"] = self.context["request"].user validated_data["verified_at"] = timezone.now() validated_data["verified"] = True elif not validated_data["verified"]: # Unverifying event nullifies verified properties validated_data["verified_by"] = None validated_data["verified_at"] = None validated_data["verified"] = False else: # Attempting to re-verify an already verified event, invalid action. Ignore attribute. validated_data.pop("verified") before_state = { k: event_definition.__dict__[k] for k in validated_data.keys() if k in event_definition.__dict__ } # KLUDGE: if we get a None value for tags, and we're not adding any # then we get an activity log that we went from null to the empty array ¯\_(ツ)_/¯ if "tags" not in before_state or before_state["tags"] is None: before_state["tags"] = [] changes = dict_changes_between( "EventDefinition", before_state, validated_data, True ) log_activity( organization_id=None, team_id=self.context["team_id"], user=self.context["request"].user, item_id=str(event_definition.id), scope="EventDefinition", activity="changed", detail=Detail(name=str(event_definition.name), changes=changes), ) return super().update(event_definition, validated_data) def to_representation(self, instance): representation = super().to_representation(instance) representation["owner"] = ( UserBasicSerializer(instance=instance.owner).data if hasattr(instance, "owner") and instance.owner else None ) return representation def get_is_action(self, obj): return hasattr(obj, "action_id") and obj.action_id is not None
blocks
msg_pair_to_var
#!/usr/bin/env python # # Copyright 2020 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # import pmt from gnuradio import gr class msg_pair_to_var(gr.sync_block): """ This block will take an input message pair and allow you to set a flowgraph variable via setter callback. If the second element the pair is a compound PMT object or not of the datatype expected by the flowgraph the behavior of the flowgraph may be unpredictable. """ def __init__(self, callback): gr.sync_block.__init__(self, name="msg_pair_to_var", in_sig=None, out_sig=None) self.callback = callback self.message_port_register_in(pmt.intern("inpair")) self.set_msg_handler(pmt.intern("inpair"), self.msg_handler) def msg_handler(self, msg): if not pmt.is_pair(msg) or pmt.is_dict(msg) or pmt.is_pdu(msg): gr.log.warn("Input message %s is not a simple pair, dropping" % repr(msg)) return new_val = pmt.to_python(pmt.cdr(msg)) try: self.callback(new_val) except Exception as e: gr.log.error( "Error when calling " + repr(self.callback) + " with " + repr(new_val) + " (reason: %s)" % repr(e) ) def stop(self): return True
src
class_addressGenerator
""" A thread for creating addresses """ import hashlib import time from binascii import hexlify import defaults import highlevelcrypto import queues import shared import state import tr from addresses import decodeAddress, encodeAddress, encodeVarint from bmconfigparser import config from fallback import RIPEMD160Hash from network import StoppableThread from pyelliptic import arithmetic from pyelliptic.openssl import OpenSSL from six.moves import configparser, queue class AddressGeneratorException(Exception): """Generic AddressGenerator exception""" pass class addressGenerator(StoppableThread): """A thread for creating addresses""" name = "addressGenerator" def stopThread(self): try: queues.addressGeneratorQueue.put(("stopThread", "data")) except queue.Full: self.logger.error("addressGeneratorQueue is Full") super(addressGenerator, self).stopThread() def run(self): """ Process the requests for addresses generation from `.queues.addressGeneratorQueue` """ # pylint: disable=too-many-locals, too-many-branches # pylint: disable=protected-access, too-many-statements # pylint: disable=too-many-nested-blocks while state.shutdown == 0: queueValue = queues.addressGeneratorQueue.get() nonceTrialsPerByte = 0 payloadLengthExtraBytes = 0 live = True if queueValue[0] == "createChan": ( command, addressVersionNumber, streamNumber, label, deterministicPassphrase, live, ) = queueValue eighteenByteRipe = False numberOfAddressesToMake = 1 numberOfNullBytesDemandedOnFrontOfRipeHash = 1 elif queueValue[0] == "joinChan": command, chanAddress, label, deterministicPassphrase, live = queueValue eighteenByteRipe = False addressVersionNumber = decodeAddress(chanAddress)[1] streamNumber = decodeAddress(chanAddress)[2] numberOfAddressesToMake = 1 numberOfNullBytesDemandedOnFrontOfRipeHash = 1 elif len(queueValue) == 7: ( command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, ) = queueValue numberOfNullBytesDemandedOnFrontOfRipeHash = config.safeGetInt( "bitmessagesettings", "numberofnullbytesonaddress", 2 if eighteenByteRipe else 1, ) elif len(queueValue) == 9: ( command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes, ) = queueValue numberOfNullBytesDemandedOnFrontOfRipeHash = config.safeGetInt( "bitmessagesettings", "numberofnullbytesonaddress", 2 if eighteenByteRipe else 1, ) elif queueValue[0] == "stopThread": break else: self.logger.error( "Programming error: A structure with the wrong number" " of values was passed into the addressGeneratorQueue." " Here is the queueValue: %r\n", queueValue, ) if addressVersionNumber < 3 or addressVersionNumber > 4: self.logger.error( "Program error: For some reason the address generator" " queue has been given a request to create at least" " one version %s address which it cannot do.\n", addressVersionNumber, ) if nonceTrialsPerByte == 0: nonceTrialsPerByte = config.getint( "bitmessagesettings", "defaultnoncetrialsperbyte" ) if ( nonceTrialsPerByte < defaults.networkDefaultProofOfWorkNonceTrialsPerByte ): nonceTrialsPerByte = ( defaults.networkDefaultProofOfWorkNonceTrialsPerByte ) if payloadLengthExtraBytes == 0: payloadLengthExtraBytes = config.getint( "bitmessagesettings", "defaultpayloadlengthextrabytes" ) if payloadLengthExtraBytes < defaults.networkDefaultPayloadLengthExtraBytes: payloadLengthExtraBytes = defaults.networkDefaultPayloadLengthExtraBytes if command == "createRandomAddress": queues.UISignalQueue.put( ( "updateStatusBar", tr._translate("MainWindow", "Generating one new address"), ) ) # This next section is a little bit strange. We're going # to generate keys over and over until we find one # that starts with either \x00 or \x00\x00. Then when # we pack them into a Bitmessage address, we won't store # the \x00 or \x00\x00 bytes thus making the address shorter. startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 potentialPrivSigningKey = OpenSSL.rand(32) potentialPubSigningKey = highlevelcrypto.pointMult( potentialPrivSigningKey ) while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivEncryptionKey = OpenSSL.rand(32) potentialPubEncryptionKey = highlevelcrypto.pointMult( potentialPrivEncryptionKey ) sha = hashlib.new("sha512") sha.update(potentialPubSigningKey + potentialPubEncryptionKey) ripe = RIPEMD160Hash(sha.digest()).digest() if ( ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == b"\x00" * numberOfNullBytesDemandedOnFrontOfRipeHash ): break self.logger.info( "Generated address with ripe digest: %s", hexlify(ripe) ) try: self.logger.info( "Address generator calculated %s addresses at %s" " addresses per second before finding one with" " the correct ripe-prefix.", numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), ) except ZeroDivisionError: # The user must have a pretty fast computer. # time.time() - startTime equaled zero. pass address = encodeAddress(addressVersionNumber, streamNumber, ripe) # An excellent way for us to store our keys # is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format privSigningKey = b"\x80" + potentialPrivSigningKey checksum = hashlib.sha256( hashlib.sha256(privSigningKey).digest() ).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58 ) privEncryptionKey = b"\x80" + potentialPrivEncryptionKey checksum = hashlib.sha256( hashlib.sha256(privEncryptionKey).digest() ).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58 ) config.add_section(address) config.set(address, "label", label) config.set(address, "enabled", "true") config.set(address, "decoy", "false") config.set(address, "noncetrialsperbyte", str(nonceTrialsPerByte)) config.set( address, "payloadlengthextrabytes", str(payloadLengthExtraBytes) ) config.set(address, "privsigningkey", privSigningKeyWIF) config.set(address, "privencryptionkey", privEncryptionKeyWIF) config.save() # The API and the join and create Chan functionality # both need information back from the address generator. queues.apiAddressGeneratorReturnQueue.put(address) queues.UISignalQueue.put( ( "updateStatusBar", tr._translate( "MainWindow", "Done generating address. Doing work necessary" " to broadcast it...", ), ) ) queues.UISignalQueue.put( ("writeNewAddressToTable", (label, address, streamNumber)) ) shared.reloadMyAddressHashes() if addressVersionNumber == 3: queues.workerQueue.put(("sendOutOrStoreMyV3Pubkey", ripe)) elif addressVersionNumber == 4: queues.workerQueue.put(("sendOutOrStoreMyV4Pubkey", address)) elif ( command == "createDeterministicAddresses" or command == "getDeterministicAddress" or command == "createChan" or command == "joinChan" ): if not deterministicPassphrase: self.logger.warning( "You are creating deterministic" " address(es) using a blank passphrase." " Bitmessage will do it but it is rather stupid." ) if command == "createDeterministicAddresses": queues.UISignalQueue.put( ( "updateStatusBar", tr._translate( "MainWindow", "Generating %1 new addresses." ).arg(str(numberOfAddressesToMake)), ) ) signingKeyNonce = 0 encryptionKeyNonce = 1 # We fill out this list no matter what although we only # need it if we end up passing the info to the API. listOfNewAddressesToSendOutThroughTheAPI = [] for _ in range(numberOfAddressesToMake): # This next section is a little bit strange. We're # going to generate keys over and over until we find # one that has a RIPEMD hash that starts with either # \x00 or \x00\x00. Then when we pack them into a # Bitmessage address, we won't store the \x00 or # \x00\x00 bytes thus making the address shorter. startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 while True: numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 potentialPrivSigningKey = hashlib.sha512( deterministicPassphrase + encodeVarint(signingKeyNonce) ).digest()[:32] potentialPrivEncryptionKey = hashlib.sha512( deterministicPassphrase + encodeVarint(encryptionKeyNonce) ).digest()[:32] potentialPubSigningKey = highlevelcrypto.pointMult( potentialPrivSigningKey ) potentialPubEncryptionKey = highlevelcrypto.pointMult( potentialPrivEncryptionKey ) signingKeyNonce += 2 encryptionKeyNonce += 2 sha = hashlib.new("sha512") sha.update(potentialPubSigningKey + potentialPubEncryptionKey) ripe = RIPEMD160Hash(sha.digest()).digest() if ( ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == b"\x00" * numberOfNullBytesDemandedOnFrontOfRipeHash ): break self.logger.info( "Generated address with ripe digest: %s", hexlify(ripe) ) try: self.logger.info( "Address generator calculated %s addresses" " at %s addresses per second before finding" " one with the correct ripe-prefix.", numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), ) except ZeroDivisionError: # The user must have a pretty fast computer. # time.time() - startTime equaled zero. pass address = encodeAddress(addressVersionNumber, streamNumber, ripe) saveAddressToDisk = True # If we are joining an existing chan, let us check # to make sure it matches the provided Bitmessage address if command == "joinChan": if address != chanAddress: listOfNewAddressesToSendOutThroughTheAPI.append( "chan name does not match address" ) saveAddressToDisk = False if command == "getDeterministicAddress": saveAddressToDisk = False if saveAddressToDisk and live: # An excellent way for us to store our keys is # in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format privSigningKey = b"\x80" + potentialPrivSigningKey checksum = hashlib.sha256( hashlib.sha256(privSigningKey).digest() ).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58 ) privEncryptionKey = b"\x80" + potentialPrivEncryptionKey checksum = hashlib.sha256( hashlib.sha256(privEncryptionKey).digest() ).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKey + checksum, 256, 58 ) try: config.add_section(address) addressAlreadyExists = False except configparser.DuplicateSectionError: addressAlreadyExists = True if addressAlreadyExists: self.logger.info( "%s already exists. Not adding it again.", address ) queues.UISignalQueue.put( ( "updateStatusBar", tr._translate( "MainWindow", "%1 is already in 'Your Identities'." " Not adding it again.", ).arg(address), ) ) else: self.logger.debug("label: %s", label) config.set(address, "label", label) config.set(address, "enabled", "true") config.set(address, "decoy", "false") if command == "joinChan" or command == "createChan": config.set(address, "chan", "true") config.set( address, "noncetrialsperbyte", str(nonceTrialsPerByte) ) config.set( address, "payloadlengthextrabytes", str(payloadLengthExtraBytes), ) config.set(address, "privSigningKey", privSigningKeyWIF) config.set( address, "privEncryptionKey", privEncryptionKeyWIF ) config.save() queues.UISignalQueue.put( ( "writeNewAddressToTable", (label, address, str(streamNumber)), ) ) listOfNewAddressesToSendOutThroughTheAPI.append(address) shared.myECCryptorObjects[ ripe ] = highlevelcrypto.makeCryptor( hexlify(potentialPrivEncryptionKey) ) shared.myAddressesByHash[ripe] = address tag = hashlib.sha512( hashlib.sha512( encodeVarint(addressVersionNumber) + encodeVarint(streamNumber) + ripe ).digest() ).digest()[32:] shared.myAddressesByTag[tag] = address if addressVersionNumber == 3: # If this is a chan address, # the worker thread won't send out # the pubkey over the network. queues.workerQueue.put( ("sendOutOrStoreMyV3Pubkey", ripe) ) elif addressVersionNumber == 4: queues.workerQueue.put( ("sendOutOrStoreMyV4Pubkey", address) ) queues.UISignalQueue.put( ( "updateStatusBar", tr._translate( "MainWindow", "Done generating address" ), ) ) elif ( saveAddressToDisk and not live and not config.has_section(address) ): listOfNewAddressesToSendOutThroughTheAPI.append(address) # Done generating addresses. if ( command == "createDeterministicAddresses" or command == "joinChan" or command == "createChan" ): queues.apiAddressGeneratorReturnQueue.put( listOfNewAddressesToSendOutThroughTheAPI ) elif command == "getDeterministicAddress": queues.apiAddressGeneratorReturnQueue.put(address) else: raise AddressGeneratorException( "Error in the addressGenerator thread. Thread was" + " given a command it could not understand: " + command ) queues.addressGeneratorQueue.task_done()
localFighter
changeAmount
import eos.db import gui.mainFrame import wx from gui import globalEvents as GE from gui.fitCommands.calc.fighter.changeAmount import CalcChangeFighterAmountCommand from gui.fitCommands.calc.fighter.localRemove import CalcRemoveLocalFighterCommand from gui.fitCommands.helpers import InternalCommandHistory from service.fit import Fit class GuiChangeLocalFighterAmountCommand(wx.Command): def __init__(self, fitID, position, amount): wx.Command.__init__(self, True, "Change Local Fighter Amount") self.internalHistory = InternalCommandHistory() self.fitID = fitID self.position = position self.amount = amount def Do(self): if self.amount > 0: cmd = CalcChangeFighterAmountCommand( fitID=self.fitID, projected=False, position=self.position, amount=self.amount, ) else: cmd = CalcRemoveLocalFighterCommand( fitID=self.fitID, position=self.position ) success = self.internalHistory.submit(cmd) eos.db.flush() sFit = Fit.getInstance() sFit.recalc(self.fitID) sFit.fill(self.fitID) eos.db.commit() wx.PostEvent( gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,)) ) return success def Undo(self): success = self.internalHistory.undoAll() eos.db.flush() sFit = Fit.getInstance() sFit.recalc(self.fitID) sFit.fill(self.fitID) eos.db.commit() wx.PostEvent( gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,)) ) return success
extractors
coub
#!/usr/bin/env python __all__ = ["coub_download"] from ..common import * from ..processor import ffmpeg from ..util.fs import legitimize def coub_download(url, output_dir=".", merge=True, info_only=False, **kwargs): html = get_content(url) try: json_data = get_coub_data(html) title, video_url, audio_url = get_title_and_urls(json_data) video_file_name, video_file_path = get_file_path( merge, output_dir, title, video_url ) audio_file_name, audio_file_path = get_file_path( merge, output_dir, title, audio_url ) download_url(audio_url, merge, output_dir, title, info_only) download_url(video_url, merge, output_dir, title, info_only) if not info_only: try: fix_coub_video_file(video_file_path) audio_duration = float( ffmpeg.ffprobe_get_media_duration(audio_file_path) ) video_duration = float( ffmpeg.ffprobe_get_media_duration(video_file_path) ) loop_file_path = get_loop_file_path(title, output_dir) single_file_path = audio_file_path if audio_duration > video_duration: write_loop_file( round(audio_duration / video_duration), loop_file_path, video_file_name, ) else: single_file_path = audio_file_path write_loop_file( round(video_duration / audio_duration), loop_file_path, audio_file_name, ) ffmpeg.ffmpeg_concat_audio_and_video( [loop_file_path, single_file_path], title + "_full", "mp4" ) cleanup_files([video_file_path, audio_file_path, loop_file_path]) except EnvironmentError as err: print("Error preparing full coub video. {}".format(err)) except Exception as err: print("Error while downloading files. {}".format(err)) def write_loop_file(records_number, loop_file_path, file_name): with open(loop_file_path, "a") as file: for i in range(records_number): file.write("file '{}'\n".format(file_name)) def download_url(url, merge, output_dir, title, info_only): mime, ext, size = url_info(url) print_info(site_info, title, mime, size) if not info_only: download_urls([url], title, ext, size, output_dir, merge=merge) def fix_coub_video_file(file_path): with open(file_path, "r+b") as file: file.seek(0) file.write(bytes(2)) def get_title_and_urls(json_data): title = legitimize(re.sub("[\s*]", "_", json_data["title"])) video_info = json_data["file_versions"]["html5"]["video"] if "high" not in video_info: if "med" not in video_info: video_url = video_info["low"]["url"] else: video_url = video_info["med"]["url"] else: video_url = video_info["high"]["url"] audio_info = json_data["file_versions"]["html5"]["audio"] if "high" not in audio_info: if "med" not in audio_info: audio_url = audio_info["low"]["url"] else: audio_url = audio_info["med"]["url"] else: audio_url = audio_info["high"]["url"] return title, video_url, audio_url def get_coub_data(html): coub_data = r1( r"<script id=\'coubPageCoubJson\' type=\'text/json\'>([\w\W]+?(?=</script>))</script>", html, ) json_data = json.loads(coub_data) return json_data def get_file_path(merge, output_dir, title, url): mime, ext, size = url_info(url) file_name = get_output_filename([], title, ext, output_dir, merge) file_path = os.path.join(output_dir, file_name) return file_name, file_path def get_loop_file_path(title, output_dir): return os.path.join(output_dir, get_output_filename([], title, "txt", None, False)) def cleanup_files(files): for file in files: os.remove(file) site_info = "coub.com" download = coub_download download_playlist = playlist_not_supported("coub")
Benchmark
BenchmarkPack
import io import os from collections import OrderedDict from Config import config from Plugin import PluginManager from util import Msgpack @PluginManager.registerTo("Actions") class ActionsPlugin: def createZipFile(self, path): import zipfile test_data = b"Test" * 1024 file_name = b"\xc3\x81rv\xc3\xadzt\xc5\xb1r\xc5\x91%s.txt".decode("utf8") with zipfile.ZipFile(path, "w") as archive: for y in range(100): zip_info = zipfile.ZipInfo(file_name % y, (1980, 1, 1, 0, 0, 0)) zip_info.compress_type = zipfile.ZIP_DEFLATED zip_info.create_system = 3 zip_info.flag_bits = 0 zip_info.external_attr = 25165824 archive.writestr(zip_info, test_data) def testPackZip(self, num_run=1): """ Test zip file creating """ yield "x 100 x 5KB " from Crypt import CryptHash zip_path = "%s/test.zip" % config.data_dir for i in range(num_run): self.createZipFile(zip_path) yield "." archive_size = os.path.getsize(zip_path) / 1024 yield "(Generated file size: %.2fkB)" % archive_size hash = CryptHash.sha512sum(open(zip_path, "rb")) valid = "cb32fb43783a1c06a2170a6bc5bb228a032b67ff7a1fd7a5efb9b467b400f553" assert hash == valid, "Invalid hash: %s != %s<br>" % (hash, valid) os.unlink(zip_path) def testUnpackZip(self, num_run=1): """ Test zip file reading """ yield "x 100 x 5KB " import zipfile zip_path = "%s/test.zip" % config.data_dir test_data = b"Test" * 1024 file_name = b"\xc3\x81rv\xc3\xadzt\xc5\xb1r\xc5\x91".decode("utf8") self.createZipFile(zip_path) for i in range(num_run): with zipfile.ZipFile(zip_path) as archive: for f in archive.filelist: assert f.filename.startswith(file_name), ( "Invalid filename: %s != %s" % (f.filename, file_name) ) data = archive.open(f.filename).read() assert archive.open(f.filename).read() == test_data, ( "Invalid data: %s..." % data[0:30] ) yield "." os.unlink(zip_path) def createArchiveFile(self, path, archive_type="gz"): import gzip import tarfile # Monkey patch _init_write_gz to use fixed date in order to keep the hash independent from datetime def nodate_write_gzip_header(self): self._write_mtime = 0 original_write_gzip_header(self) test_data_io = io.BytesIO(b"Test" * 1024) file_name = b"\xc3\x81rv\xc3\xadzt\xc5\xb1r\xc5\x91%s.txt".decode("utf8") original_write_gzip_header = gzip.GzipFile._write_gzip_header gzip.GzipFile._write_gzip_header = nodate_write_gzip_header with tarfile.open(path, "w:%s" % archive_type) as archive: for y in range(100): test_data_io.seek(0) tar_info = tarfile.TarInfo(file_name % y) tar_info.size = 4 * 1024 archive.addfile(tar_info, test_data_io) def testPackArchive(self, num_run=1, archive_type="gz"): """ Test creating tar archive files """ yield "x 100 x 5KB " from Crypt import CryptHash hash_valid_db = { "gz": "92caec5121a31709cbbc8c11b0939758e670b055bbbe84f9beb3e781dfde710f", "bz2": "b613f41e6ee947c8b9b589d3e8fa66f3e28f63be23f4faf015e2f01b5c0b032d", "xz": "ae43892581d770959c8d993daffab25fd74490b7cf9fafc7aaee746f69895bcb", } archive_path = "%s/test.tar.%s" % (config.data_dir, archive_type) for i in range(num_run): self.createArchiveFile(archive_path, archive_type=archive_type) yield "." archive_size = os.path.getsize(archive_path) / 1024 yield "(Generated file size: %.2fkB)" % archive_size hash = CryptHash.sha512sum( open("%s/test.tar.%s" % (config.data_dir, archive_type), "rb") ) valid = hash_valid_db[archive_type] assert hash == valid, "Invalid hash: %s != %s<br>" % (hash, valid) if os.path.isfile(archive_path): os.unlink(archive_path) def testUnpackArchive(self, num_run=1, archive_type="gz"): """ Test reading tar archive files """ yield "x 100 x 5KB " import tarfile test_data = b"Test" * 1024 file_name = b"\xc3\x81rv\xc3\xadzt\xc5\xb1r\xc5\x91%s.txt".decode("utf8") archive_path = "%s/test.tar.%s" % (config.data_dir, archive_type) self.createArchiveFile(archive_path, archive_type=archive_type) for i in range(num_run): with tarfile.open(archive_path, "r:%s" % archive_type) as archive: for y in range(100): assert archive.extractfile(file_name % y).read() == test_data yield "." if os.path.isfile(archive_path): os.unlink(archive_path) def testPackMsgpack(self, num_run=1): """ Test msgpack encoding """ yield "x 100 x 5KB " binary = b'fqv\xf0\x1a"e\x10,\xbe\x9cT\x9e(\xa5]u\x072C\x8c\x15\xa2\xa8\x93Sw)\x19\x02\xdd\t\xfb\xf67\x88\xd9\xee\x86\xa1\xe4\xb6,\xc6\x14\xbb\xd7$z\x1d\xb2\xda\x85\xf5\xa0\x97^\x01*\xaf\xd3\xb0!\xb7\x9d\xea\x89\xbbh8\xa1"\xa7]e(@\xa2\xa5g\xb7[\xae\x8eE\xc2\x9fL\xb6s\x19\x19\r\xc8\x04S\xd0N\xe4]?/\x01\xea\xf6\xec\xd1\xb3\xc2\x91\x86\xd7\xf4K\xdf\xc2lV\xf4\xe8\x80\xfc\x8ep\xbb\x82\xb3\x86\x98F\x1c\xecS\xc8\x15\xcf\xdc\xf1\xed\xfc\xd8\x18r\xf9\x80\x0f\xfa\x8cO\x97(\x0b]\xf1\xdd\r\xe7\xbf\xed\x06\xbd\x1b?\xc5\xa0\xd7a\x82\xf3\xa8\xe6@\xf3\ri\xa1\xb10\xf6\xd4W\xbc\x86\x1a\xbb\xfd\x94!bS\xdb\xaeM\x92\x00#\x0b\xf7\xad\xe9\xc2\x8e\x86\xbfi![%\xd31]\xc6\xfc2\xc9\xda\xc6v\x82P\xcc\xa9\xea\xb9\xff\xf6\xc8\x17iD\xcf\xf3\xeeI\x04\xe9\xa1\x19\xbb\x01\x92\xf5nn4K\xf8\xbb\xc6\x17e>\xa7 \xbbv' data = OrderedDict( sorted( { "int": 1024 * 1024 * 1024, "float": 12345.67890, "text": "hello" * 1024, "binary": binary, }.items() ) ) data_packed_valid = b'\x84\xa6binary\xc5\x01\x00fqv\xf0\x1a"e\x10,\xbe\x9cT\x9e(\xa5]u\x072C\x8c\x15\xa2\xa8\x93Sw)\x19\x02\xdd\t\xfb\xf67\x88\xd9\xee\x86\xa1\xe4\xb6,\xc6\x14\xbb\xd7$z\x1d\xb2\xda\x85\xf5\xa0\x97^\x01*\xaf\xd3\xb0!\xb7\x9d\xea\x89\xbbh8\xa1"\xa7]e(@\xa2\xa5g\xb7[\xae\x8eE\xc2\x9fL\xb6s\x19\x19\r\xc8\x04S\xd0N\xe4]?/\x01\xea\xf6\xec\xd1\xb3\xc2\x91\x86\xd7\xf4K\xdf\xc2lV\xf4\xe8\x80\xfc\x8ep\xbb\x82\xb3\x86\x98F\x1c\xecS\xc8\x15\xcf\xdc\xf1\xed\xfc\xd8\x18r\xf9\x80\x0f\xfa\x8cO\x97(\x0b]\xf1\xdd\r\xe7\xbf\xed\x06\xbd\x1b?\xc5\xa0\xd7a\x82\xf3\xa8\xe6@\xf3\ri\xa1\xb10\xf6\xd4W\xbc\x86\x1a\xbb\xfd\x94!bS\xdb\xaeM\x92\x00#\x0b\xf7\xad\xe9\xc2\x8e\x86\xbfi![%\xd31]\xc6\xfc2\xc9\xda\xc6v\x82P\xcc\xa9\xea\xb9\xff\xf6\xc8\x17iD\xcf\xf3\xeeI\x04\xe9\xa1\x19\xbb\x01\x92\xf5nn4K\xf8\xbb\xc6\x17e>\xa7 \xbbv\xa5float\xcb@\xc8\x1c\xd6\xe61\xf8\xa1\xa3int\xce@\x00\x00\x00\xa4text\xda\x14\x00' data_packed_valid += b"hello" * 1024 for y in range(num_run): for i in range(100): data_packed = Msgpack.pack(data) yield "." assert data_packed == data_packed_valid, "%s<br>!=<br>%s" % ( repr(data_packed), repr(data_packed_valid), ) def testUnpackMsgpack(self, num_run=1): """ Test msgpack decoding """ yield "x 5KB " binary = b'fqv\xf0\x1a"e\x10,\xbe\x9cT\x9e(\xa5]u\x072C\x8c\x15\xa2\xa8\x93Sw)\x19\x02\xdd\t\xfb\xf67\x88\xd9\xee\x86\xa1\xe4\xb6,\xc6\x14\xbb\xd7$z\x1d\xb2\xda\x85\xf5\xa0\x97^\x01*\xaf\xd3\xb0!\xb7\x9d\xea\x89\xbbh8\xa1"\xa7]e(@\xa2\xa5g\xb7[\xae\x8eE\xc2\x9fL\xb6s\x19\x19\r\xc8\x04S\xd0N\xe4]?/\x01\xea\xf6\xec\xd1\xb3\xc2\x91\x86\xd7\xf4K\xdf\xc2lV\xf4\xe8\x80\xfc\x8ep\xbb\x82\xb3\x86\x98F\x1c\xecS\xc8\x15\xcf\xdc\xf1\xed\xfc\xd8\x18r\xf9\x80\x0f\xfa\x8cO\x97(\x0b]\xf1\xdd\r\xe7\xbf\xed\x06\xbd\x1b?\xc5\xa0\xd7a\x82\xf3\xa8\xe6@\xf3\ri\xa1\xb10\xf6\xd4W\xbc\x86\x1a\xbb\xfd\x94!bS\xdb\xaeM\x92\x00#\x0b\xf7\xad\xe9\xc2\x8e\x86\xbfi![%\xd31]\xc6\xfc2\xc9\xda\xc6v\x82P\xcc\xa9\xea\xb9\xff\xf6\xc8\x17iD\xcf\xf3\xeeI\x04\xe9\xa1\x19\xbb\x01\x92\xf5nn4K\xf8\xbb\xc6\x17e>\xa7 \xbbv' data = OrderedDict( sorted( { "int": 1024 * 1024 * 1024, "float": 12345.67890, "text": "hello" * 1024, "binary": binary, }.items() ) ) data_packed = b'\x84\xa6binary\xc5\x01\x00fqv\xf0\x1a"e\x10,\xbe\x9cT\x9e(\xa5]u\x072C\x8c\x15\xa2\xa8\x93Sw)\x19\x02\xdd\t\xfb\xf67\x88\xd9\xee\x86\xa1\xe4\xb6,\xc6\x14\xbb\xd7$z\x1d\xb2\xda\x85\xf5\xa0\x97^\x01*\xaf\xd3\xb0!\xb7\x9d\xea\x89\xbbh8\xa1"\xa7]e(@\xa2\xa5g\xb7[\xae\x8eE\xc2\x9fL\xb6s\x19\x19\r\xc8\x04S\xd0N\xe4]?/\x01\xea\xf6\xec\xd1\xb3\xc2\x91\x86\xd7\xf4K\xdf\xc2lV\xf4\xe8\x80\xfc\x8ep\xbb\x82\xb3\x86\x98F\x1c\xecS\xc8\x15\xcf\xdc\xf1\xed\xfc\xd8\x18r\xf9\x80\x0f\xfa\x8cO\x97(\x0b]\xf1\xdd\r\xe7\xbf\xed\x06\xbd\x1b?\xc5\xa0\xd7a\x82\xf3\xa8\xe6@\xf3\ri\xa1\xb10\xf6\xd4W\xbc\x86\x1a\xbb\xfd\x94!bS\xdb\xaeM\x92\x00#\x0b\xf7\xad\xe9\xc2\x8e\x86\xbfi![%\xd31]\xc6\xfc2\xc9\xda\xc6v\x82P\xcc\xa9\xea\xb9\xff\xf6\xc8\x17iD\xcf\xf3\xeeI\x04\xe9\xa1\x19\xbb\x01\x92\xf5nn4K\xf8\xbb\xc6\x17e>\xa7 \xbbv\xa5float\xcb@\xc8\x1c\xd6\xe61\xf8\xa1\xa3int\xce@\x00\x00\x00\xa4text\xda\x14\x00' data_packed += b"hello" * 1024 for y in range(num_run): data_unpacked = Msgpack.unpack(data_packed, decode=False) yield "." assert data_unpacked == data, "%s<br>!=<br>%s" % (data_unpacked, data) def testUnpackMsgpackStreaming(self, num_run=1, fallback=False): """ Test streaming msgpack decoding """ yield "x 1000 x 5KB " binary = b'fqv\xf0\x1a"e\x10,\xbe\x9cT\x9e(\xa5]u\x072C\x8c\x15\xa2\xa8\x93Sw)\x19\x02\xdd\t\xfb\xf67\x88\xd9\xee\x86\xa1\xe4\xb6,\xc6\x14\xbb\xd7$z\x1d\xb2\xda\x85\xf5\xa0\x97^\x01*\xaf\xd3\xb0!\xb7\x9d\xea\x89\xbbh8\xa1"\xa7]e(@\xa2\xa5g\xb7[\xae\x8eE\xc2\x9fL\xb6s\x19\x19\r\xc8\x04S\xd0N\xe4]?/\x01\xea\xf6\xec\xd1\xb3\xc2\x91\x86\xd7\xf4K\xdf\xc2lV\xf4\xe8\x80\xfc\x8ep\xbb\x82\xb3\x86\x98F\x1c\xecS\xc8\x15\xcf\xdc\xf1\xed\xfc\xd8\x18r\xf9\x80\x0f\xfa\x8cO\x97(\x0b]\xf1\xdd\r\xe7\xbf\xed\x06\xbd\x1b?\xc5\xa0\xd7a\x82\xf3\xa8\xe6@\xf3\ri\xa1\xb10\xf6\xd4W\xbc\x86\x1a\xbb\xfd\x94!bS\xdb\xaeM\x92\x00#\x0b\xf7\xad\xe9\xc2\x8e\x86\xbfi![%\xd31]\xc6\xfc2\xc9\xda\xc6v\x82P\xcc\xa9\xea\xb9\xff\xf6\xc8\x17iD\xcf\xf3\xeeI\x04\xe9\xa1\x19\xbb\x01\x92\xf5nn4K\xf8\xbb\xc6\x17e>\xa7 \xbbv' data = OrderedDict( sorted( { "int": 1024 * 1024 * 1024, "float": 12345.67890, "text": "hello" * 1024, "binary": binary, }.items() ) ) data_packed = b'\x84\xa6binary\xc5\x01\x00fqv\xf0\x1a"e\x10,\xbe\x9cT\x9e(\xa5]u\x072C\x8c\x15\xa2\xa8\x93Sw)\x19\x02\xdd\t\xfb\xf67\x88\xd9\xee\x86\xa1\xe4\xb6,\xc6\x14\xbb\xd7$z\x1d\xb2\xda\x85\xf5\xa0\x97^\x01*\xaf\xd3\xb0!\xb7\x9d\xea\x89\xbbh8\xa1"\xa7]e(@\xa2\xa5g\xb7[\xae\x8eE\xc2\x9fL\xb6s\x19\x19\r\xc8\x04S\xd0N\xe4]?/\x01\xea\xf6\xec\xd1\xb3\xc2\x91\x86\xd7\xf4K\xdf\xc2lV\xf4\xe8\x80\xfc\x8ep\xbb\x82\xb3\x86\x98F\x1c\xecS\xc8\x15\xcf\xdc\xf1\xed\xfc\xd8\x18r\xf9\x80\x0f\xfa\x8cO\x97(\x0b]\xf1\xdd\r\xe7\xbf\xed\x06\xbd\x1b?\xc5\xa0\xd7a\x82\xf3\xa8\xe6@\xf3\ri\xa1\xb10\xf6\xd4W\xbc\x86\x1a\xbb\xfd\x94!bS\xdb\xaeM\x92\x00#\x0b\xf7\xad\xe9\xc2\x8e\x86\xbfi![%\xd31]\xc6\xfc2\xc9\xda\xc6v\x82P\xcc\xa9\xea\xb9\xff\xf6\xc8\x17iD\xcf\xf3\xeeI\x04\xe9\xa1\x19\xbb\x01\x92\xf5nn4K\xf8\xbb\xc6\x17e>\xa7 \xbbv\xa5float\xcb@\xc8\x1c\xd6\xe61\xf8\xa1\xa3int\xce@\x00\x00\x00\xa4text\xda\x14\x00' data_packed += b"hello" * 1024 for i in range(num_run): unpacker = Msgpack.getUnpacker(decode=False, fallback=fallback) for y in range(1000): unpacker.feed(data_packed) for data_unpacked in unpacker: pass yield "." assert data == data_unpacked, "%s != %s" % (data_unpacked, data)
intro-doc
svg
#!/usr/bin/env python3 """Generate a visual graph of transactions. """ __copyright__ = "Copyright (C) 2016-2017 Martin Blais" __license__ = "GNU GPLv2" import argparse import bisect import collections import csv import logging import math import random import re import textwrap from os import path from beancount.core import amount from beancount.core.number import D class Params: # Flags on whether to draw various pieces of text. draw_acctype = True draw_account = True draw_balance = True draw_before = True draw_clearing = False draw_opening = False draw_period = True draw_close = False draw_after = True # Min/max number of postings. min_postings, max_postings = 2, 6 # Vertically, we have # | above_line line y_margin = 5 # Vertical distance between elements. y_margin_group = 15 # Vertical distance between groups. y_margin_lines = 4 # Vertical gap between lines. y_aboveline = 10 # Occupied space above the timeline. y_interline = y_margin_lines + y_aboveline # Vertical distance between lines. # Sizing of posting and transaction nodes. post_radius = int(y_interline * 0.4) # Radius of posting node txn_radius = 16 # Radius of transaction node (match x_margin = 5 # Horizontal margin between all components. x_arrow_margin = 20 # Margin at the right of the timeline to leave space for an arrow x_txn_offset = int( post_radius * 2 * 1.2 ) # Offset of txn node to the right of the posting nodes x_section_margin = ( x_txn_offset + txn_radius + x_margin ) # Horizontal margin between sections # x_inter_distance = post_radius + x_txn_offset + txn_radius + x_margin # Horizontal distance between transactions. x_inter_distance = post_radius * 0.9 x_clear_distance = 2 # Horizontal distance between clearing transactions # Horizontally, we have # | acctype account | timeline | balances | x_acctype_width = 60 # Width of account type text. x_account_width = 150 # Width of account text. x_timeline_length = 900 # Length of timeline. x_timeline_before = 270 # Length of before zone. x_timeline_open = 43 # Length of open/clearing zone. x_timeline_period = 250 # Length of period zone. x_timeline_close = 45 # Length of closing zone. x_timeline_after = 100 # Length of closing zone. assert ( x_timeline_before + x_timeline_open + x_timeline_period + x_timeline_close + x_timeline_after ) < x_timeline_length x_balance_width = 110 # Width of balances rendering. x_timeline_start = x_margin + x_acctype_width + x_account_width + x_margin x_timeline_end = x_timeline_start + x_margin + x_timeline_length + x_margin x_width = x_timeline_end + x_margin + x_balance_width + x_margin # Max number of attempts fitting in a transaction. max_attempts = 1024 def groupby(sequence, key): groups = collections.defaultdict(list) for el in sequence: groups[key(el)].append(el) return dict(groups) def main(): parser = argparse.ArgumentParser(description=__doc__.strip()) parser.add_argument( "-b", "--balances-filename", action="store", default=path.join(path.dirname(__file__), "balances.csv"), help="A CSV file with balances in it", ) parser.add_argument("-s", "--seed", action="store", type=int) args = parser.parse_args() # Seed randomness for consistency. if args.seed is None: args.seed = random.randint(0, 2**20) print("seed = %s" % args.seed) random.seed(args.seed) # Read the balances. with open(args.balances_filename, "r") as balfile: balfile.readline() balances = sorted( [ (account, balance) for (account, balance) in csv.reader(balfile) if ( not re.search(r"201\d", account) and re.search(r"\bUSD\b", balance) and balance.strip() ) ] ) # balance_groups = [random.sample(balances, random.randint(5, 24)) for _ in range(2)] sbalances = [bal for bal in balances if not bal[0].startswith("Equity")] random.shuffle(sbalances) random.seed(args.seed) p = Params() p.draw_acctype = False p.y_interline += 2.5 draw_diagram(p, [sbalances], "svg3.html") random.seed(args.seed) p.draw_acctype = True draw_diagram(p, [sbalances], "svg4.html") random.seed(args.seed) p.draw_acctype = False p.x_timeline_end /= 2 p.x_width = p.x_timeline_end + p.x_margin + p.x_balance_width + p.x_margin p.draw_after = False p.draw_period = False draw_diagram(p, [sbalances[0 : len(sbalances) // 2]], "svg2.html") random.seed(args.seed) p.x_timeline_end *= 0.7 p.x_width = p.x_timeline_end + p.x_margin + p.x_balance_width + p.x_margin p.x_timeline_before = 100 draw_diagram(p, [sbalances[0 : len(sbalances) // 3]], "svg1.html") p = Params() random.seed(args.seed + 1) group_dict = groupby(balances, lambda item: item[0].split(":", 1)[0]) group_dict["Equity"].reverse() groups = [group_dict[x] for x in "Assets Liabilities Equity Income Expenses".split()] draw_diagram(p, groups, "svg5.html") random.seed(args.seed + 1) p.draw_clearing = True draw_diagram(p, groups, "svg6.html", scale_income=D("0.3")) random.seed(args.seed + 1) p.draw_opening = True draw_diagram(p, groups, "svg7.html") random.seed(args.seed + 1) p.draw_before = False draw_diagram(p, groups, "svg8.html") random.seed(args.seed + 1) p.draw_after = False draw_diagram(p, groups, "svg9.html") random.seed(args.seed + 1) p.draw_close = True draw_diagram(p, groups, "svgA.html") # random.seed(args.seed+1) # p.draw_close = True # draw_diagram(p, groups, 'svg6.html') # random.seed(args.seed+1) # p.draw_after = False # draw_diagram(p, groups, 'svg7.html') # random.seed(args.seed+1) # p.draw_before = False # draw_diagram(p, groups, 'svg8.html') # random.seed(args.seed+1) # p.draw_before = False # p.draw_after = True # draw_diagram(p, groups, 'svg9.html') # random.seed(args.seed+1) # p.draw_before = False # p.draw_after = True # p.draw_close = False # draw_diagram(p, groups, 'svg10.html') # random.seed(args.seed+1) # p.draw_before = False # p.draw_after = False # p.draw_close = False # draw_diagram(p, groups, 'svg11.html') def draw_diagram(p, balance_groups, filename, scale_income=None): y_height = ( p.y_margin + sum(map(len, balance_groups)) * p.y_interline + len(balance_groups) * p.y_margin_group ) # Total height of the entire thing with open(filename, "w") as outfile: pr = lambda *args: print(*args, file=outfile) pr_null = lambda *args: print(*args, file=open("/dev/null", "w")) pr("<html>") pr("<head>") pr('<style type="text/css">') pr( textwrap.dedent( """\ /* margin: 0px; */ /* padding: 0px; */ /* Defaults */ stroke-width: 2px; stroke: #000; /* div#top-level-svg { } */ /* svg { border: thin solid blue; }*/ """ ) ) pr("</style>") pr("</head>") pr("<body>") pr('<div id="top-level-svg">') # Make some definitions. pr( """ <svg width="{width}px" height="{height}px" font-size="12px" > <defs> <marker id="arrow" markerWidth="10" markerHeight="6" refX="0" refY="2" orient="auto" markerUnits="strokeWidth"> <path d="M0,0 L0,4 L9,2 Z" fill="#000" /> </marker> <g id="txn" transform="translate(-{r2},-{r2})"> <rect x="0" y="0" width="{r}" height="{r}" fill="#BBB" /> <text x="4" y="9" font-family="Courier" font-weight="bold" font-size="13px" alignment-baseline="central" > T </text> </g> </defs> """.format(width=p.x_width, height=y_height, r=p.txn_radius, r2=p.txn_radius / 2) ) # pr('<g transform="scale(1.0)">') y = 0 all_lines = [] all_line_pairs = [] for balance_group in balance_groups: # if p.draw_clearing: # balance_group = [(account, ('0.00 USD' # if re.match('Income|Expenses', account) # else balance)) # for account, balance in balance_group] if not p.draw_close: balance_group = [ (account, b) for (account, b) in balance_group if account.strip() != "Equity:Earnings:Current" ] y_lines = draw_type(p, y + p.y_margin_group, balance_group, pr, scale_income) y = y_lines[-1] assert len(balance_group) == len(y_lines) all_line_pairs.extend(zip(balance_group, y_lines)) # Skip rendering postings on the Equity lines. if balance_group[0][0].startswith("Equity"): continue all_lines.extend(y_lines) # Create and render all transactions. boxes = [] x = p.x_timeline_start + p.x_section_margin x_end = x + p.x_timeline_before # Before zone. if p.draw_before: pr('<g style="stroke: #000">') create_txns(p, x, x_end, all_lines, boxes, pr) pr("</g>") else: # To maintain random. create_txns(p, x, x_end, all_lines, boxes, pr_null) # Clearing zone. if p.draw_clearing or p.draw_opening: x = x_end + p.x_section_margin x_end = x + p.x_timeline_open if p.draw_clearing: pr('<g style="stroke: #040">') draw_summarizing_txns( p, x, "Equity:Earnings:Previous", "Income|Expenses", all_line_pairs, pr, ) pr("</g>") if p.draw_opening: pr('<g style="stroke: #006">') draw_summarizing_txns( p, x, "Equity:Opening-Balances", "Assets|Liabilities", list(reversed(all_line_pairs)), pr, ) pr("</g>") # Period zone. if p.draw_period: x = x_end + p.x_section_margin x_end = x + p.x_timeline_period pr('<g style="stroke: #000">') create_txns(p, x, x_end, all_lines, boxes, pr) pr("</g>") # Close zone. if p.draw_close: x = x_end + p.x_section_margin x_end = x + p.x_timeline_close pr('<g style="stroke: #040">') draw_summarizing_txns( p, x, "Equity:Earnings:Current", "Income|Expenses", all_line_pairs, pr ) pr("</g>") # After zone. if p.draw_after: x = x_end + p.x_section_margin x_end = x + p.x_timeline_after pr('<g style="stroke: #000">') create_txns(p, x, x_end, all_lines, boxes, pr) pr("</g>") # pr('</g>') pr("</svg>") pr("</div>") pr("</body>") pr("</html>") def create_txns(p, x, x_end, all_lines, boxes, pr): # Note: Side-effects on 'boxes'. while x <= x_end: x += p.x_inter_distance txn = create_txn(p, x, all_lines, boxes) if txn is None: continue # Skip it. y_selected, box = txn draw_txn(p, x, y_selected, all_lines, pr) boxes.append(box) def draw_summarizing_txns(p, x, equity_account, account_regexp, line_pairs, pr): all_y = sorted(p[1] for p in line_pairs) y_previous = None for (account, _), y in line_pairs: if re.match(equity_account, account): y_previous = y if y_previous: for (account, _), y in line_pairs: if re.match(account_regexp, account): y_selected = sorted([y_previous, y]) x += p.x_clear_distance draw_txn(p, x, y_selected, all_y, pr) def draw_type(p, y_start, balances, pr, scale_income): """Draw a set of lines with the given balances.""" # Draw the supporting lines. y_lines = [] for iy, (account, balance_amount) in enumerate(balances): y = y_start + p.y_interline * (iy + 1) y_lines.append(y) # Select some balance and draw it at the end of the timeline. acctype, account_name = account.strip().split(":", 1) acctype += ":" if scale_income is not None and acctype in ("Income:", "Expenses:"): amt = amount.from_string(balance_amount) amt = amount.Amount( (amt.number * scale_income).quantize(D("0.00")), amt.currency ) balance_amount = "{:>15}".format(amt.to_string().replace(" ", " ")) draw_line(p, y, acctype, account_name, balance_amount, pr) return y_lines def draw_line(p, y, acctype, account_name, balance_amount, pr): """Draw a single line with its account name and balance amount.""" pr("") pr( '<line x1="{x}" y1="{y}" x2="{x2}" y2="{y}" stroke="#000" marker-end="url(#arrow)" />'.format( x=p.x_timeline_start, x2=p.x_timeline_end, y=y ) ) if p.draw_acctype: pr( '<text x="{x}" y="{y}" text-anchor="end" alignment-baseline="central" font-family="Helvetica" font-weight="bold">'.format( x=p.x_margin + p.x_acctype_width, y=y ) ) pr(acctype) pr("</text>") if p.draw_account: pr( '<text x="{x}" y="{y}" text-anchor="start" alignment-baseline="central" font-family="Helvetica" font-weight="bold">'.format( x=p.x_margin + p.x_acctype_width, y=y ) ) pr(account_name) pr("</text>") if p.draw_balance: pr( '<text x="{x}" y="{y}" text-anchor="end" alignment-baseline="central" font-family="Courier">'.format( x=p.x_width - p.x_margin, y=y ) ) pr(balance_amount) pr("</text>") pr("") def iterpairs(seq): """Iterate over sequential pairs.""" seqiter = iter(seq) prev = next(seqiter) for el in seqiter: yield prev, el prev = el def intersects(minmax1, minmax2): min1, max1 = minmax1 min2, max2 = minmax2 return not (min1 >= max2 or max1 <= min2) def create_txn(p, x, y_lines, boxes): """Create a new transaction, avoiding existing ones.""" x_minmax = x - p.post_radius, x + p.x_txn_offset + p.txn_radius # Filter boxes to the list which might intersect ours on the x axis. blocker_boxes = [] for box in boxes: bx_minmax, _ = box if intersects(x_minmax, bx_minmax): blocker_boxes.append(box) y_selected = None i = 0 while y_selected is None: if i >= p.max_attempts: return None i += 1 # Select a number of postings. num_postings = 0 while not (p.min_postings <= num_postings <= min(p.max_postings, len(y_lines))): num_postings = int(random.lognormvariate(1.0, 0.4)) # Select some subset of lines. Try to keep the lines together. first_line = random.randint(0, len(y_lines) - num_postings) lines = [first_line] probab_select = 0.3 line = first_line while len(lines) < num_postings: for line in range(first_line + 1, len(y_lines)): if random.random() < probab_select: lines.append(line) if len(lines) >= num_postings: break y_selected = [y_lines[line] for line in sorted(lines)] y_minmax = y_selected[0] - p.post_radius, y_selected[-1] + p.post_radius for box in blocker_boxes: _, by_minmax = box if intersects(y_minmax, by_minmax): y_selected = None break box = (x_minmax, y_minmax) return y_selected, box def find_txn_location(y_selected, y_lines): # Select the y in the largest gap in the y lines. maxgap = 0 maxloc = -1 for i, (yp, yn) in enumerate(iterpairs(y_selected)): gap = yn - yp if gap > maxgap: maxgap = gap maxloc = i yt = (y_selected[maxloc + 1] + y_selected[maxloc]) / 2.0 # Shift the y location away from any existing line. i = bisect.bisect_left(y_lines, yt) yt = (y_lines[i - 1] + y_lines[i]) / 2 return yt def draw_txn(p, x, y_selected, y_lines, pr, debug=False): """Draw a single transaction.""" yt = find_txn_location(y_selected, y_lines) xt = x + p.x_txn_offset # Draw the joining lines between postings and transactions. for y in y_selected: pr( '<path d="M {} {} C {} {}, {} {}, {} {}" fill="transparent" />'.format( x, y, xt, y, xt, (yt + y) / 2, xt, yt ) ) # Draw the post icons (circles). for y in y_selected: pr( '<circle cx="{x}" cy="{y}" r="{r}" fill="#FFF" />'.format( x=x, y=y, r=p.post_radius ) ) # Draw the transaction icon. pr('<use xlink:href="#txn" x="{x}" y="{y}" />'.format(x=xt, y=yt)) if __name__ == "__main__": main()
macro
retrospective
from plover import system from plover.steno import Stroke from plover.translation import Translation def toggle_asterisk(translator, stroke, cmdline): assert not cmdline # Toggle asterisk of previous stroke translations = translator.get_state().translations if not translations: return t = translations[-1] translator.untranslate_translation(t) keys = set(t.strokes[-1].steno_keys) if "*" in keys: keys.remove("*") else: keys.add("*") translator.translate_stroke(Stroke(keys)) def delete_space(translator, stroke, cmdline): assert not cmdline # Retrospective delete space translations = translator.get_state().translations if len(translations) < 2: return replaced = translations[-2:] if replaced[1].is_retrospective_command: return english = [] for t in replaced: if t.english is not None: english.append(t.english) elif len(t.rtfcre) == 1 and t.rtfcre[0].isdigit(): english.append("{&%s}" % t.rtfcre[0]) if len(english) > 1: t = Translation([stroke], "{^~|^}".join(english)) t.replaced = replaced t.is_retrospective_command = True translator.translate_translation(t) def insert_space(translator, stroke, cmdline): assert not cmdline # Retrospective insert space translations = translator.get_state().translations if not translations: return replaced = translations[-1] if replaced.is_retrospective_command: return lookup_stroke = replaced.strokes[-1] english = [t.english or "/".join(t.rtfcre) for t in replaced.replaced] if english: english.append( translator.lookup([lookup_stroke], system.SUFFIX_KEYS) or lookup_stroke.rtfcre ) t = Translation([stroke], " ".join(english)) t.replaced = [replaced] t.is_retrospective_command = True translator.translate_translation(t)
misc
create_launcher
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2016 Christoph Reiter # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. """Creates simple Python .exe launchers for gui and cli apps ./create-launcher.py "3.8.0" <target-dir> """ import os import shlex import shutil import struct import subprocess import sys import tempfile def build_resource(rc_path, out_path): """Raises subprocess.CalledProcessError""" def is_64bit(): return struct.calcsize("P") == 8 subprocess.check_call( [ "windres", "-O", "coff", "-F", "pe-x86-64" if is_64bit() else "pe-i386", rc_path, "-o", out_path, ] ) def get_build_args(): python_name = os.path.splitext(os.path.basename(sys.executable))[0] python_config = os.path.join( os.path.dirname(sys.executable), python_name + "-config" ) cflags = subprocess.check_output(["sh", python_config, "--cflags"]).strip() libs = subprocess.check_output(["sh", python_config, "--libs"]).strip() cflags = os.fsdecode(cflags) libs = os.fsdecode(libs) return shlex.split(cflags) + shlex.split(libs) def build_exe(source_path, resource_path, is_gui, out_path): args = ["gcc", "-s"] if is_gui: args.append("-mwindows") args.append("-municode") args.extend(["-o", out_path, source_path, resource_path]) args.extend(get_build_args()) print("Compiling launcher: %r", args) subprocess.check_call(args) def get_launcher_code(entry_point): module, func = entry_point.split(":", 1) template = """\ #include "Python.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <tchar.h> #define BUFSIZE 32768 int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR lpCmdLine, int nCmdShow) { int result; DWORD retval = 0; BOOL success; WCHAR buffer[BUFSIZE] = {0}; WCHAR* lppPart[1] = {NULL}; retval = GetFullPathNameW(__wargv[0], BUFSIZE, buffer, lppPart); if (retval == 0) { // It's bad, but can be ignored printf ("GetFullPathName failed (%%d)\\n", GetLastError()); } else if (retval < BUFSIZE) { if (lppPart != NULL && *lppPart != 0) { lppPart[0][-1] = 0; printf("Calling SetDllDirectoryW(%%ls)\\n", buffer); success = SetDllDirectoryW(buffer); if (success) { printf("Successfully SetDllDirectoryW\\n"); } else { printf ("SetDllDirectoryW failed (%%d)\\n", GetLastError()); } } else { printf ("E: GetFullPathName didn't return filename\\n"); } } else { printf ("GetFullPathName buffer too small (required %%d)\\n", retval); return -1; // this shouldn't happen } Py_NoUserSiteDirectory = 1; Py_IgnoreEnvironmentFlag = 1; Py_DontWriteBytecodeFlag = 1; Py_Initialize(); PySys_SetArgvEx(__argc, __wargv, 0); result = PyRun_SimpleString("%s"); Py_Finalize(); return result; } """ launch_code = "import sys; from %s import %s; sys.exit(%s())" % (module, func, func) return template % launch_code def get_resource_code( filename, file_version, file_desc, icon_path, product_name, product_version, company_name, ): template = """\ 1 ICON "%(icon_path)s" 1 VERSIONINFO FILEVERSION %(file_version_list)s PRODUCTVERSION %(product_version_list)s FILEOS 0x4 FILETYPE 0x1 BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904E4" BEGIN VALUE "CompanyName", "%(company_name)s" VALUE "FileDescription", "%(file_desc)s" VALUE "FileVersion", "%(file_version)s" VALUE "InternalName", "%(internal_name)s" VALUE "OriginalFilename", "%(filename)s" VALUE "ProductName", "%(product_name)s" VALUE "ProductVersion", "%(product_version)s" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1252 END END """ def to_ver_list(v): return ",".join(map(str, (list(map(int, v.split("."))) + [0] * 4)[:4])) file_version_list = to_ver_list(file_version) product_version_list = to_ver_list(product_version) return template % { "icon_path": icon_path, "file_version_list": file_version_list, "product_version_list": product_version_list, "file_version": file_version, "product_version": product_version, "company_name": company_name, "filename": filename, "internal_name": os.path.splitext(filename)[0], "product_name": product_name, "file_desc": file_desc, } def build_launcher( out_path, icon_path, file_desc, product_name, product_version, company_name, entry_point, is_gui, ): src_ico = os.path.abspath(icon_path) target = os.path.abspath(out_path) file_version = product_version dir_ = os.getcwd() temp = tempfile.mkdtemp() try: os.chdir(temp) with open("launcher.c", "w") as h: h.write(get_launcher_code(entry_point)) shutil.copyfile(src_ico, "launcher.ico") with open("launcher.rc", "w") as h: h.write( get_resource_code( os.path.basename(target), file_version, file_desc, "launcher.ico", product_name, product_version, company_name, ) ) build_resource("launcher.rc", "launcher.res") build_exe("launcher.c", "launcher.res", is_gui, target) finally: os.chdir(dir_) shutil.rmtree(temp) def main(): argv = sys.argv version = argv[1] target = argv[2] company_name = "The gPodder Team" misc = os.path.dirname(os.path.realpath(__file__)) build_launcher( os.path.join(target, "gpodder.exe"), os.path.join(misc, "gpodder.ico"), "gPodder", "gPodder", version, company_name, "gpodder_launch.gpodder:main", True, ) build_launcher( os.path.join(target, "gpodder-cmd.exe"), os.path.join(misc, "gpodder.ico"), "gPodder", "gPodder", version, company_name, "gpodder_launch.gpodder:main", False, ) build_launcher( os.path.join(target, "gpo.exe"), os.path.join(misc, "gpo.ico"), "gPodder CLI", "gpo", version, company_name, "gpodder_launch.gpo:main", False, ) if __name__ == "__main__": main()
helpers
msgpack
""" wrapping msgpack ================ We wrap msgpack here the way we need it - to avoid having lots of clutter in the calling code. Packing ------- - use_bin_type = True (used by borg since borg 2.0) This is used to generate output according to new msgpack 2.0 spec. This cleanly keeps bytes and str types apart. - use_bin_type = False (used by borg < 1.3) This creates output according to the older msgpack spec. BAD: str and bytes were packed into same "raw" representation. - unicode_errors = 'surrogateescape' Guess backup applications are one of the rare cases when this needs to be used. It is needed because borg also needs to deal with data that does not cleanly encode/decode using utf-8. There's a lot of crap out there, e.g. in filenames and as a backup tool, we must keep them as good as possible. Unpacking --------- - raw = False (used by borg since borg 2.0) We already can use this with borg 2.0 due to the type conversion to the desired type in item.py update_internal methods. This type conversion code can be removed in future, when we do not have to deal with data any more that was packed the old way. It will then unpack according to the msgpack 2.0 spec format and directly output bytes or str. - raw = True (the old way, used by borg < 1.3) - unicode_errors = 'surrogateescape' -> see description above (will be used when raw is False). As of borg 2.0, we have fixed most of the msgpack str/bytes mess, #968. Borg now still needs to **read** old repos, archives, keys, ... so we can not yet fix it completely. But from now on, borg only **writes** new data according to the new msgpack 2.0 spec, thus we can remove some legacy support in a later borg release (some places are marked with "legacy"). current way in msgpack terms ---------------------------- - pack with use_bin_type=True (according to msgpack 2.0 spec) - packs str -> raw and bytes -> bin - unpack with raw=False (according to msgpack 2.0 spec, using unicode_errors='surrogateescape') - unpacks bin to bytes and raw to str (thus we need to convert to desired type if we want bytes from "raw") """ from msgpack import ExtType, OutOfData from msgpack import Packer as mp_Packer from msgpack import Timestamp from msgpack import Unpacker as mp_Unpacker from msgpack import pack as mp_pack from msgpack import packb as mp_packb from msgpack import unpack as mp_unpack from msgpack import unpackb as mp_unpackb from msgpack import version as mp_version from ..constants import * # NOQA from .datastruct import StableDict version = mp_version USE_BIN_TYPE = True RAW = False UNICODE_ERRORS = "surrogateescape" class PackException(Exception): """Exception while msgpack packing""" class UnpackException(Exception): """Exception while msgpack unpacking""" class Packer(mp_Packer): def __init__( self, *, default=None, unicode_errors=UNICODE_ERRORS, use_single_float=False, autoreset=True, use_bin_type=USE_BIN_TYPE, strict_types=False, ): assert unicode_errors == UNICODE_ERRORS super().__init__( default=default, unicode_errors=unicode_errors, use_single_float=use_single_float, autoreset=autoreset, use_bin_type=use_bin_type, strict_types=strict_types, ) def pack(self, obj): try: return super().pack(obj) except Exception as e: raise PackException(e) def packb(o, *, use_bin_type=USE_BIN_TYPE, unicode_errors=UNICODE_ERRORS, **kwargs): assert unicode_errors == UNICODE_ERRORS try: return mp_packb(o, use_bin_type=use_bin_type, unicode_errors=unicode_errors, **kwargs) except Exception as e: raise PackException(e) def pack(o, stream, *, use_bin_type=USE_BIN_TYPE, unicode_errors=UNICODE_ERRORS, **kwargs): assert unicode_errors == UNICODE_ERRORS try: return mp_pack( o, stream, use_bin_type=use_bin_type, unicode_errors=unicode_errors, **kwargs, ) except Exception as e: raise PackException(e) class Unpacker(mp_Unpacker): def __init__( self, file_like=None, *, read_size=0, use_list=True, raw=RAW, object_hook=None, object_pairs_hook=None, list_hook=None, unicode_errors=UNICODE_ERRORS, max_buffer_size=0, ext_hook=ExtType, strict_map_key=False, ): assert raw == RAW assert unicode_errors == UNICODE_ERRORS kw = dict( file_like=file_like, read_size=read_size, use_list=use_list, raw=raw, object_hook=object_hook, object_pairs_hook=object_pairs_hook, list_hook=list_hook, unicode_errors=unicode_errors, max_buffer_size=max_buffer_size, ext_hook=ext_hook, strict_map_key=strict_map_key, ) super().__init__(**kw) def unpack(self): try: return super().unpack() except OutOfData: raise except Exception as e: raise UnpackException(e) def __next__(self): try: return super().__next__() except StopIteration: raise except Exception as e: raise UnpackException(e) next = __next__ def unpackb(packed, *, raw=RAW, unicode_errors=UNICODE_ERRORS, strict_map_key=False, **kwargs): assert raw == RAW assert unicode_errors == UNICODE_ERRORS try: kw = dict(raw=raw, unicode_errors=unicode_errors, strict_map_key=strict_map_key) kw.update(kwargs) return mp_unpackb(packed, **kw) except Exception as e: raise UnpackException(e) def unpack(stream, *, raw=RAW, unicode_errors=UNICODE_ERRORS, strict_map_key=False, **kwargs): assert raw == RAW assert unicode_errors == UNICODE_ERRORS try: kw = dict(raw=raw, unicode_errors=unicode_errors, strict_map_key=strict_map_key) kw.update(kwargs) return mp_unpack(stream, **kw) except Exception as e: raise UnpackException(e) # msgpacking related utilities ----------------------------------------------- def is_slow_msgpack(): import msgpack import msgpack.fallback return msgpack.Packer is msgpack.fallback.Packer def is_supported_msgpack(): # DO NOT CHANGE OR REMOVE! See also requirements and comments in setup.cfg. import msgpack if msgpack.version in []: # < add bad releases here to deny list return False return (1, 0, 3) <= msgpack.version <= (1, 0, 7) def get_limited_unpacker(kind): """return a limited Unpacker because we should not trust msgpack data received from remote""" # Note: msgpack >= 0.6.1 auto-computes DoS-safe max values from len(data) for # unpack(data) or from max_buffer_size for Unpacker(max_buffer_size=N). args = dict(use_list=False, max_buffer_size=3 * max(BUFSIZE, MAX_OBJECT_SIZE)) # return tuples, not lists if kind in ("server", "client"): pass # nothing special elif kind in ("manifest", "archive", "key"): args.update(dict(use_list=True, object_hook=StableDict)) # default value else: raise ValueError('kind must be "server", "client", "manifest", "archive" or "key"') return Unpacker(**args) def int_to_timestamp(ns): assert isinstance(ns, int) return Timestamp.from_unix_nano(ns) def timestamp_to_int(ts): assert isinstance(ts, Timestamp) return ts.to_unix_nano()
utils
classification
import queue import threading import traceback from time import sleep from django.db import transaction from django.utils import timezone from photonix.photos.models import Photo, Task from photonix.photos.utils.tasks import requeue_stuck_tasks from photonix.web.utils import logger CLASSIFIERS = [ "color", "event", "location", "face", "style", "object", ] def process_classify_images_tasks(): for task in Task.objects.filter(type="classify_images", status="P").order_by( "created_at" ): photo_id = task.subject_id generate_classifier_tasks_for_photo(photo_id, task) def generate_classifier_tasks_for_photo(photo_id, task): task.start() started = timezone.now() # Add task for each classifier on current photo with transaction.atomic(): for classifier in CLASSIFIERS: Task( type="classify.{}".format(classifier), subject_id=photo_id, parent=task, library=Photo.objects.get(id=photo_id).library, ).save() task.complete_with_children = True task.save() class ThreadedQueueProcessor: def __init__( self, model=None, task_type=None, runner=None, num_workers=4, batch_size=64 ): self.model = model self.task_type = task_type self.runner = runner self.num_workers = num_workers self.batch_size = batch_size self.queue = queue.Queue() self.threads = [] def __worker(self): while True: task = self.queue.get() if task is None: break self.__process_task(task) self.queue.task_done() def __process_task(self, task): try: logger.info(f"Running task: {task.type} - {task.subject_id}") task.start() self.runner(task.subject_id) task.complete() except Exception: logger.error(f"Error processing task: {task.type} - {task.subject_id}") traceback.print_exc() task.failed() def __clean_up(self): # Shut down threads cleanly for i in range(self.num_workers): self.queue.put(None) for t in self.threads: t.join() def run(self, loop=True): logger.info("Starting {} {} workers".format(self.num_workers, self.task_type)) if self.num_workers > 1: for i in range(self.num_workers): t = threading.Thread(target=self.__worker) t.start() self.threads.append(t) try: while True: requeue_stuck_tasks(self.task_type) if self.task_type == "classify.color": task_queryset = Task.objects.filter( library__classification_color_enabled=True, type=self.task_type, status="P", ) elif self.task_type == "classify.location": task_queryset = Task.objects.filter( library__classification_location_enabled=True, type=self.task_type, status="P", ) elif self.task_type == "classify.face": task_queryset = Task.objects.filter( library__classification_face_enabled=True, type=self.task_type, status="P", ) elif self.task_type == "classify.style": task_queryset = Task.objects.filter( library__classification_style_enabled=True, type=self.task_type, status="P", ) elif self.task_type == "classify.object": task_queryset = Task.objects.filter( library__classification_object_enabled=True, type=self.task_type, status="P", ) else: task_queryset = Task.objects.filter(type=self.task_type, status="P") for task in task_queryset[:8]: if self.num_workers > 1: logger.debug("putting task") self.queue.put(task) else: self.__process_task(task) if self.num_workers > 1: self.queue.join() if not loop: self.__clean_up() return sleep(1) except KeyboardInterrupt: self.__clean_up()
migrations
0317_batch_export_models
# Generated by Django 3.2.18 on 2023-05-30 09:06 import django.db.models.deletion import posthog.models.utils from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("posthog", "0316_action_href_text_matching"), ] operations = [ migrations.CreateModel( name="BatchExportDestination", fields=[ ( "id", models.UUIDField( default=posthog.models.utils.UUIDT, editable=False, primary_key=True, serialize=False, ), ), ( "type", models.CharField( choices=[("S3", "S3")], help_text="A choice of supported BatchExportDestination types.", max_length=64, ), ), ( "config", models.JSONField( blank=True, default=dict, help_text="A JSON field to store all configuration parameters required to access a BatchExportDestination.", ), ), ( "created_at", models.DateTimeField( auto_now_add=True, help_text="The timestamp at which this BatchExportDestination was created.", ), ), ( "last_updated_at", models.DateTimeField( auto_now=True, help_text="The timestamp at which this BatchExportDestination was last updated.", ), ), ], options={ "abstract": False, }, ), migrations.CreateModel( name="BatchExport", fields=[ ( "id", models.UUIDField( default=posthog.models.utils.UUIDT, editable=False, primary_key=True, serialize=False, ), ), ( "team", models.ForeignKey( help_text="The team this belongs to.", on_delete=django.db.models.deletion.CASCADE, to="posthog.team", ), ), ( "name", models.TextField( help_text="A human-readable name for this BatchExport." ), ), ( "destination", models.ForeignKey( help_text="The destination to export data to.", on_delete=django.db.models.deletion.CASCADE, to="posthog.batchexportdestination", ), ), ( "interval", models.CharField( choices=[("hour", "hour"), ("day", "day"), ("week", "week")], default="hour", help_text="The interval at which to export data.", max_length=64, ), ), ( "paused", models.BooleanField( default=False, help_text="Whether this BatchExport is paused or not.", ), ), ( "deleted", models.BooleanField( default=False, help_text="Whether this BatchExport is deleted or not.", ), ), ( "created_at", models.DateTimeField( auto_now_add=True, help_text="The timestamp at which this BatchExport was created.", ), ), ( "last_updated_at", models.DateTimeField( auto_now=True, help_text="The timestamp at which this BatchExport was last updated.", ), ), ], options={ "abstract": False, }, ), migrations.CreateModel( name="BatchExportRun", fields=[ ( "id", models.UUIDField( default=posthog.models.utils.UUIDT, editable=False, primary_key=True, serialize=False, ), ), ( "status", models.CharField( choices=[ ("Cancelled", "Cancelled"), ("Completed", "Completed"), ("ContinuedAsNew", "Continuedasnew"), ("Failed", "Failed"), ("Terminated", "Terminated"), ("TimedOut", "Timedout"), ("Running", "Running"), ("Starting", "Starting"), ], help_text="The status of this run.", max_length=64, ), ), ( "records_completed", models.IntegerField( help_text="The number of records that have been exported.", null=True, ), ), ( "latest_error", models.TextField( help_text="The latest error that occurred during this run.", null=True, ), ), ( "data_interval_start", models.DateTimeField(help_text="The start of the data interval."), ), ( "data_interval_end", models.DateTimeField(help_text="The end of the data interval."), ), ( "cursor", models.TextField( help_text="An opaque cursor that may be used to resume.", null=True, ), ), ( "created_at", models.DateTimeField( auto_now_add=True, help_text="The timestamp at which this BatchExportRun was created.", ), ), ( "finished_at", models.DateTimeField( help_text="The timestamp at which this BatchExportRun finished, successfully or not.", null=True, ), ), ( "last_updated_at", models.DateTimeField( auto_now=True, help_text="The timestamp at which this BatchExportRun was last updated.", ), ), ( "batch_export", models.ForeignKey( help_text="The BatchExport this run belongs to.", on_delete=django.db.models.deletion.CASCADE, to="posthog.batchexport", ), ), ], options={ "abstract": False, }, ), ]
scripting
engine
# Copyright (C) 2011 Chris Dekter # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Engine backend for Autokey""" import pathlib from collections.abc import Iterable from typing import List, Optional, Tuple, Union import autokey.model.folder import autokey.model.helpers import autokey.model.phrase import autokey.model.script from autokey import configmanager from autokey.model.key import Key from autokey.scripting.system import System logger = __import__("autokey.logger").logger.get_logger(__name__) class Engine: """ Provides access to the internals of AutoKey. Note that any configuration changes made using this API while the configuration window is open will not appear until it is closed and re-opened. """ SendMode = autokey.model.phrase.SendMode Key = Key def __init__(self, config_manager, runner): """ """ self.configManager = config_manager self.runner = runner self.monitor = config_manager.app.monitor self._macro_args = [] self._script_args = [] self._script_kwargs = {} self._return_value = "" self._triggered_abbreviation = None # type: Optional[str] def get_folder(self, title: str): """ Retrieve a folder by its title Usage: C{engine.get_folder(title)} Note that if more than one folder has the same title, only the first match will be returned. """ validateType(title, "title", str) for folder in self.configManager.allFolders: if folder.title == title: return folder return None def create_folder(self, title: str, parent_folder=None, temporary=False): """ Create and return a new folder. Usage: C{engine.create_folder("new folder"), parent_folder=folder, temporary=True} Descriptions for the optional arguments: @param parentFolder: Folder to make this folder a subfolder of. If passed as a folder, it will be that folder within auotkey. If passed as pathlib.Path, it will be created or added at that path. Paths expand ~ to $HOME. @param temporary: Folders created with temporary=True are not persisted. Used for single-source rc-style scripts. Cannot be used if parent_folder is a Path. If a folder of that name already exists, this will return it unchanged. If the folder wasn't already added to autokey, it will be. The 'temporary' property is not touched to avoid deleting an existing folder. Note that if more than one folder has the same title, only the first match will be returned. """ validateType(title, "title", str) validateType( parent_folder, "parent_folder", [autokey.model.folder.Folder, pathlib.Path] ) validateType(temporary, "temporary", bool) # XXX Doesn't check if a folder already exists at this path in autokey. if isinstance(parent_folder, pathlib.Path): if temporary: raise ValueError( "Parameter 'temporary' is True, but a path \ was given as the parent folder. Temporary folders \ cannot use absolute paths." ) path = parent_folder.expanduser() / title path.mkdir(parents=True, exist_ok=True) new_folder = autokey.model.folder.Folder(title, path=str(path.resolve())) self.configManager.allFolders.append(new_folder) return new_folder # TODO: Convert this to use get_folder, when we change to specifying # the exact folder by more than just title. if parent_folder is None: parent_folders = self.configManager.allFolders elif isinstance(parent_folder, autokey.model.folder.Folder): parent_folders = parent_folder.folders else: # Input is previously validated, must match one of the above. pass for folder in parent_folders: if folder.title == title: return folder else: new_folder = autokey.model.folder.Folder(title) if parent_folder is None: self.configManager.allFolders.append(new_folder) else: parent_folder.add_folder(new_folder) if not temporary and parent_folder.temporary: raise ValueError( "Parameter 'temporary' is False, but parent folder is a temporary one. \ Folders created within temporary folders must themselves be set temporary" ) if not temporary: new_folder.persist() else: new_folder.temporary = True return new_folder def create_phrase( self, folder, name: str, contents: str, abbreviations: Union[str, List[str]] = None, hotkey: Tuple[List[Union[Key, str]], Union[Key, str]] = None, send_mode: autokey.model.phrase.SendMode = autokey.model.phrase.SendMode.CB_CTRL_V, window_filter: str = None, show_in_system_tray: bool = False, always_prompt: bool = False, temporary=False, replace_existing_hotkey=False, ): """ Create a new text phrase inside the given folder. Use C{engine.get_folder(folder_name)} to retrieve the folder you wish to create the Phrase in. If the folder is a temporary one, the phrase will be created as temporary. The first three arguments (folder, name and contents) are required. All further arguments are optional and considered to be keyword-argument only. Do not rely on the order of the optional arguments. The optional parameters can be used to configure the newly created Phrase. Usage (minimal example): C{engine.create_phrase(folder, name, contents)} Further concrete examples: C{ engine.create_phrase(folder, "My new Phrase", "This is the Phrase content", abbreviations=["abc", "def"], hotkey=([engine.Key.SHIFT], engine.Key.NP_DIVIDE), send_mode=engine.SendMode.CB_CTRL_SHIFT_V, window_filter="konsole\\.Konsole", show_in_system_tray=True) } Descriptions for the optional arguments: abbreviations may be a single string or a list of strings. Each given string is assigned as an abbreviation to the newly created phrase. hotkey parameter: The hotkey parameter accepts a 2-tuple, consisting of a list of modifier keys in the first element and an unshifted (lowercase) key as the second element. Modifier keys must be given as a list of strings (or Key enum instances), with the following values permitted: <ctrl> <alt> <super> <hyper> <meta> <shift> The key must be an unshifted character (i.e. lowercase) or a Key enum instance. Modifier keys from the list above are NOT allowed here. Example: (["<ctrl>", "<alt>"], "9") to assign "<Ctrl>+<Alt>+9" as a hotkey. The Key enum contains objects representing various special keys and is available as an attribute of the "engine" object, named "Key". So to access a function key, you can use the string "<f12>" or engine.Key.F12 See the AutoKey Wiki for an overview of all available keys in the enumeration. send_mode: This parameter configures how AutoKey sends the phrase content, for example by typing or by pasting using the clipboard. It accepts items from the SendMode enumeration, which is also available from the engine object as engine.SendMode. The parameter defaults to engine.SendMode.KEYBOARD. Available send modes are: KEYBOARD CB_CTRL_V CB_CTRL_SHIFT_V CB_SHIFT_INSERT SELECTION To paste the Phrase using "<shift>+<insert>, set send_mode=engine.SendMode.CB_SHIFT_INSERT window_filter: Accepts a string which will be used as a regular expression to match window titles or applications using the WM_CLASS attribute. @param folder: folder to place the abbreviation in, retrieved using C{engine.get_folder()} @param name: Name/description for the phrase. @param contents: the expansion text @param abbreviations: Can be a single string or a list (or other iterable) of strings. Assigned to the Phrase @param hotkey: A tuple containing a keyboard combination that will be assigned as a hotkey. First element is a list of modifiers, second element is the key. @param send_mode: The pasting mode that will be used to expand the Phrase. Used to configure, how the Phrase is expanded. Defaults to typing using the "CTRL+V" method. @param window_filter: A string containing a regular expression that will be used as the window filter. @param show_in_system_tray: A boolean defaulting to False. If set to True, the new Phrase will be shown in the tray icon context menu. @param always_prompt: A boolean defaulting to False. If set to True, the Phrase expansion has to be manually confirmed, each time it is triggered. @param temporary: Hotkeys created with temporary=True are not persisted as .jsons, and are replaced if the description is not unique within the folder. Used for single-source rc-style scripts. @param replace_existing_hotkey: If true, instead of warning if the hotkey is already in use by another phrase or folder, it removes the hotkey from those clashes and keeps this phrase's hotkey. @raise ValueError: If a given abbreviation or hotkey is already in use or parameters are otherwise invalid @return The created Phrase object. This object is NOT considered part of the public API and exposes the raw internals of AutoKey. Ignore it, if you don’t need it or don’t know what to do with it. It can be used for _really_ advanced use cases, where further customizations are desired. Use at your own risk. No guarantees are made about the object’s structure. Read the AutoKey source code for details. """ validateArguments( folder, name, contents, abbreviations, hotkey, send_mode, window_filter, show_in_system_tray, always_prompt, temporary, replace_existing_hotkey, ) if abbreviations and isinstance(abbreviations, str): abbreviations = [abbreviations] check_abbreviation_unique(self.configManager, abbreviations, window_filter) if not replace_existing_hotkey: check_hotkey_unique(self.configManager, hotkey, window_filter) else: # XXX If something causes the phrase creation to fail after this, # this will unset the hotkey without replacing it. self.__clear_existing_hotkey(hotkey, window_filter) self.monitor.suspend() try: p = autokey.model.phrase.Phrase(name, contents) if send_mode in autokey.model.phrase.SendMode: p.sendMode = send_mode if abbreviations: p.add_abbreviations(abbreviations) if hotkey: p.set_hotkey(*hotkey) if window_filter: p.set_window_titles(window_filter) p.show_in_tray_menu = show_in_system_tray p.prompt = always_prompt p.temporary = temporary folder.add_item(p) # Don't save a json if it is a temporary hotkey. Won't persist across # reloads. if not temporary: p.persist() return p finally: self.monitor.unsuspend() self.configManager.config_altered(False) def __clear_existing_hotkey(self, hotkey, window_filter): existing_item = self.get_item_with_hotkey(hotkey) if existing_item and not isinstance( existing_item, configmanager.configmanager.GlobalHotkey ): if existing_item.filter_matches(window_filter): existing_item.unset_hotkey() def create_abbreviation(self, folder, description, abbr, contents): """ DEPRECATED. Use engine.create_phrase() with appropriate keyword arguments instead. Create a new text phrase inside the given folder and assign the abbreviation given. Usage: C{engine.create_abbreviation(folder, description, abbr, contents)} When the given abbreviation is typed, it will be replaced with the given text. @param folder: folder to place the abbreviation in, retrieved using C{engine.get_folder()} @param description: description for the phrase @param abbr: the abbreviation that will trigger the expansion @param contents: the expansion text @raise Exception: if the specified abbreviation is not unique """ if not self.configManager.check_abbreviation_unique(abbr, None, None)[0]: raise Exception("The specified abbreviation is already in use") self.monitor.suspend() p = autokey.model.phrase.Phrase(description, contents) p.modes.append(autokey.model.helpers.TriggerMode.ABBREVIATION) p.abbreviations = [abbr] folder.add_item(p) p.persist() self.monitor.unsuspend() self.configManager.config_altered(False) def create_hotkey(self, folder, description, modifiers, key, contents): """ DEPRECATED. Use engine.create_phrase() with appropriate keyword arguments instead. Create a text hotkey Usage: C{engine.create_hotkey(folder, description, modifiers, key, contents)} When the given hotkey is pressed, it will be replaced with the given text. Modifiers must be given as a list of strings, with the following values permitted: <ctrl> <alt> <super> <hyper> <meta> <shift> The key must be an unshifted character (i.e. lowercase) @param folder: folder to place the abbreviation in, retrieved using C{engine.get_folder()} @param description: description for the phrase @param modifiers: modifiers to use with the hotkey (as a list) @param key: the hotkey @param contents: the expansion text @raise Exception: if the specified hotkey is not unique """ modifiers.sort() if not self.configManager.check_hotkey_unique(modifiers, key, None, None)[0]: raise Exception( "The specified hotkey and modifier combination is already in use" ) self.monitor.suspend() p = autokey.model.phrase.Phrase(description, contents) p.modes.append(autokey.model.helpers.TriggerMode.HOTKEY) p.set_hotkey(modifiers, key) folder.add_item(p) p.persist() self.monitor.unsuspend() self.configManager.config_altered(False) def run_script(self, description, *args, **kwargs): """ Run an existing script using its description or path to look it up Usage: C{engine.run_script(description, 'foo', 'bar', foobar='foobar')} @param description: description of the script to run. If parsable as an absolute path to an existing file, that will be run instead. @raise Exception: if the specified script does not exist """ self._script_args = args self._script_kwargs = kwargs path = pathlib.Path(description) path = path.expanduser() # Check if absolute path. if pathlib.PurePath(path).is_absolute() and path.exists(): self.runner.run_subscript(path) else: target_script = None for item in self.configManager.allItems: if item.description == description and isinstance( item, autokey.model.script.Script ): target_script = item if target_script is not None: self.runner.run_subscript(target_script) else: raise Exception("No script with description '%s' found" % description) return self._return_value def run_script_from_macro(self, args): """ Used internally by AutoKey for phrase macros """ self._macro_args = args["args"].split(",") try: self.run_script(args["name"]) except Exception as e: # TODO: Log more information here, instead of setting the return # value. self.set_return_value("{ERROR: %s}" % str(e)) def run_system_command_from_macro(self, args): """ Used internally by AutoKey for system macros """ try: self._return_value = System.exec_command(args["command"], getOutput=True) except Exception as e: self.set_return_value("{ERROR: %s}" % str(e)) def get_script_arguments(self): """ Get the arguments supplied to the current script via the scripting api Usage: C{engine.get_script_arguments()} @return: the arguments @rtype: C{list[Any]} """ return self._script_args def get_script_keyword_arguments(self): """ Get the arguments supplied to the current script via the scripting api as keyword args. Usage: C{engine.get_script_keyword_arguments()} @return: the arguments @rtype: C{Dict[str, Any]} """ return self._script_kwargs def get_macro_arguments(self): """ Get the arguments supplied to the current script via its macro Usage: C{engine.get_macro_arguments()} @return: the arguments @rtype: C{list(str())} """ return self._macro_args def set_return_value(self, val): """ Store a return value to be used by a phrase macro Usage: C{engine.set_return_value(val)} @param val: value to be stored """ self._return_value = val def _get_return_value(self): """ Used internally by AutoKey for phrase macros """ ret = self._return_value self._return_value = "" return ret def _set_triggered_abbreviation(self, abbreviation: str, trigger_character: str): """ Used internally by AutoKey to provide the abbreviation and trigger that caused the script to execute. @param abbreviation: Abbreviation that caused the script to execute @param trigger_character: Possibly empty "trigger character". As defined in the abbreviation configuration. """ self._triggered_abbreviation = abbreviation self._triggered_character = trigger_character def get_triggered_abbreviation(self) -> Tuple[Optional[str], Optional[str]]: """ This function can be queried by a script to get the abbreviation text that triggered it’s execution. If a script is triggered by an abbreviation, this function returns a tuple containing two strings. First element is the abbreviation text. The second element is the trigger character that finally caused the execution. It is typically some whitespace character, like ' ', '\t' or a newline character. It is empty, if the abbreviation was configured to "trigger immediately". If the script execution was triggered by a hotkey, a call to the DBus interface, the tray icon, the "Run" button in the main window or any other means, this function returns a tuple containing two None values. Usage: C{abbreviation, trigger_character = engine.get_triggered_abbreviation()} You can determine if the script was triggered by an abbreviation by simply testing the truth value of the first returned value. @return: Abbreviation that triggered the script execution, if any. @rtype: C{Tuple[Optional[str], Optional[str]]} """ return self._triggered_abbreviation, self._triggered_character def remove_all_temporary(self, folder=None, in_temp_parent=False): """ Removes all temporary folders and phrases, as well as any within temporary folders. Useful for rc-style scripts that want to change a set of keys. """ self.configManager.remove_all_temporary(folder, in_temp_parent) def get_item_with_hotkey(self, hotkey): if not hotkey: return modifiers = sorted(hotkey[0]) return self.configManager.get_item_with_hotkey(modifiers, hotkey[1]) def validateAbbreviations(abbreviations): """ Checks if the given abbreviations are a list/iterable of strings @param abbreviations: Abbreviations list to be validated @raise ValueError: Raises C{ValueError} if C{abbreviations} is anything other than C{str} or C{Iterable} """ if abbreviations is None: return fail = False if not isinstance(abbreviations, str): fail = True if isinstance(abbreviations, Iterable): fail = False for item in abbreviations: if not isinstance(item, str): fail = True if fail: raise ValueError( "Expected abbreviations to be a single string or a list/iterable of strings, not {}".format( type(abbreviations) ) ) def check_abbreviation_unique(configmanager, abbreviations, window_filter): """ Checks if the given abbreviations are unique @param configmanager: ConfigManager Instance to check abbrevations @param abbreviations: List of abbreviations to be checked @param window_filter: Window filter that the abbreviation will apply to. @raise ValueError: Raises C{ValueError} if an abbreviation is already in use. """ if not abbreviations: return for abbr in abbreviations: if not configmanager.check_abbreviation_unique(abbr, window_filter, None)[0]: raise ValueError( "The specified abbreviation '{}' is already in use.".format(abbr) ) def check_hotkey_unique(configmanager, hotkey, window_filter): """ Checks if the given hotkey is unique @param configmanager: ConfigManager Instance used to check hotkey @param hotkey: hotkey to be check if unique @param window_filter: Window filter to be applied to the hotkey """ if not hotkey: return modifiers = sorted(hotkey[0]) if not configmanager.check_hotkey_unique(modifiers, hotkey[1], window_filter, None)[ 0 ]: raise ValueError( "The specified hotkey and modifier combination is already in use: {}".format( hotkey ) ) def isValidHotkeyType(item): """ Checks if the hotkey is valid. @param item: Hotkey to be checked @return: Returns C{True} if hotkey is valid, C{False} otherwise """ fail = False if isinstance(item, Key): fail = False elif isinstance(item, str): if len(item) == 1: fail = False else: fail = not Key.is_key(item) else: fail = True return not fail def validateHotkey(hotkey): """ """ failmsg = "Expected hotkey to be a tuple of modifiers then keys, as lists of Key or str, not {}".format( type(hotkey) ) if hotkey is None: return fail = False if not isinstance(hotkey, tuple): fail = True else: if len(hotkey) != 2: fail = True else: # First check modifiers is list of valid hotkeys. if isinstance(hotkey[0], list): for item in hotkey[0]: if not isValidHotkeyType(item): fail = True failmsg = "Hotkey is not a valid modifier: {}".format(item) else: fail = True failmsg = "Hotkey modifiers is not a list" # Then check second element is a key or str if not isValidHotkeyType(hotkey[1]): fail = True failmsg = "Hotkey is not a valid key: {}".format(hotkey[1]) if fail: raise ValueError(failmsg) def validateArguments( folder, name, contents, abbreviations, hotkey, send_mode, window_filter, show_in_system_tray, always_prompt, temporary, replace_existing_hotkey, ): if folder is None: raise ValueError( "Parameter 'folder' is None. Check the folder is a valid autokey folder" ) validateType(folder, "folder", autokey.model.folder.Folder) # For when we allow pathlib.Path # validateType(folder, "folder", # [model.Folder, pathlib.Path]) validateType(name, "name", str) validateType(contents, "contents", str) validateAbbreviations(abbreviations) validateHotkey(hotkey) validateType(send_mode, "send_mode", autokey.model.phrase.SendMode) validateType(window_filter, "window_filter", str) validateType(show_in_system_tray, "show_in_system_tray", bool) validateType(always_prompt, "always_prompt", bool) validateType(temporary, "temporary", bool) validateType(replace_existing_hotkey, "replace_existing_hotkey", bool) # TODO: The validation should be done by some controller functions in the model base classes. if folder.temporary and not temporary: raise ValueError( "Parameter 'temporary' is False, but parent folder is a temporary one. \ Phrases created within temporary folders must themselves be explicitly set temporary" ) def validateType(item, name, type_): """type_ may be a list, in which case if item matches any type, no error is raised. """ if item is None: return if isinstance(type_, list): failed = True for type__ in type_: if isinstance(item, type__): failed = False if failed: raise ValueError( "Expected {} to be one of {}, not {}".format(name, type_, type(item)) ) else: if not isinstance(item, type_): raise ValueError( "Expected {} to be {}, not {}".format(name, type_, type(item)) )
models
user
""" database schema for user data """ import re from urllib.parse import urlparse import pytz from bookwyrm import activitypub from bookwyrm.connectors import ConnectorException, get_data from bookwyrm.models.shelf import Shelf from bookwyrm.models.status import Status from bookwyrm.preview_images import generate_user_preview_image_task from bookwyrm.settings import DOMAIN, ENABLE_PREVIEW_IMAGES, LANGUAGES, USE_HTTPS from bookwyrm.signatures import create_key_pair from bookwyrm.tasks import MISC, app from bookwyrm.utils import regex from django.apps import apps from django.contrib.auth.models import AbstractUser from django.contrib.postgres.fields import ArrayField, CICharField from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from django.db import models, transaction from django.dispatch import receiver from django.utils import timezone from django.utils.translation import gettext_lazy as _ from model_utils import FieldTracker from . import fields from .activitypub_mixin import ActivitypubMixin, OrderedCollectionPageMixin from .base_model import BookWyrmModel, DeactivationReason, new_access_code from .federated_server import FederatedServer FeedFilterChoices = [ ("review", _("Reviews")), ("comment", _("Comments")), ("quotation", _("Quotations")), ("everything", _("Everything else")), ] def get_feed_filter_choices(): """return a list of filter choice keys""" return [f[0] for f in FeedFilterChoices] def site_link(): """helper for generating links to the site""" protocol = "https" if USE_HTTPS else "http" return f"{protocol}://{DOMAIN}" # pylint: disable=too-many-public-methods class User(OrderedCollectionPageMixin, AbstractUser): """a user who wants to read books""" username = fields.UsernameField() email = models.EmailField(unique=True, null=True) key_pair = fields.OneToOneField( "KeyPair", on_delete=models.CASCADE, blank=True, null=True, activitypub_field="publicKey", related_name="owner", ) inbox = fields.RemoteIdField(unique=True) shared_inbox = fields.RemoteIdField( activitypub_field="sharedInbox", activitypub_wrapper="endpoints", deduplication_field=False, null=True, ) federated_server = models.ForeignKey( "FederatedServer", on_delete=models.PROTECT, null=True, blank=True, ) outbox = fields.RemoteIdField(unique=True, null=True) summary = fields.HtmlField(null=True, blank=True) local = models.BooleanField(default=False) bookwyrm_user = fields.BooleanField(default=True) localname = CICharField( max_length=255, null=True, unique=True, validators=[fields.validate_localname], ) # name is your display name, which you can change at will name = fields.CharField(max_length=100, null=True, blank=True) avatar = fields.ImageField( upload_to="avatars/", blank=True, null=True, activitypub_field="icon", alt_field="alt_text", ) preview_image = models.ImageField( upload_to="previews/avatars/", blank=True, null=True ) followers_url = fields.CharField(max_length=255, activitypub_field="followers") followers = models.ManyToManyField( "self", symmetrical=False, through="UserFollows", through_fields=("user_object", "user_subject"), related_name="following", ) follow_requests = models.ManyToManyField( "self", symmetrical=False, through="UserFollowRequest", through_fields=("user_subject", "user_object"), related_name="follower_requests", ) blocks = models.ManyToManyField( "self", symmetrical=False, through="UserBlocks", through_fields=("user_subject", "user_object"), related_name="blocked_by", ) saved_lists = models.ManyToManyField( "List", symmetrical=False, related_name="saved_lists", blank=True ) favorites = models.ManyToManyField( "Status", symmetrical=False, through="Favorite", through_fields=("user", "status"), related_name="favorite_statuses", ) default_post_privacy = models.CharField( max_length=255, default="public", choices=fields.PrivacyLevels ) remote_id = fields.RemoteIdField(null=True, unique=True, activitypub_field="id") created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) last_active_date = models.DateTimeField(default=timezone.now) manually_approves_followers = fields.BooleanField(default=False) theme = models.ForeignKey("Theme", null=True, blank=True, on_delete=models.SET_NULL) hide_follows = fields.BooleanField(default=False) # options to turn features on and off show_goal = models.BooleanField(default=True) show_suggested_users = models.BooleanField(default=True) discoverable = fields.BooleanField(default=False) show_guided_tour = models.BooleanField(default=True) # feed options feed_status_types = ArrayField( models.CharField(max_length=10, blank=False, choices=FeedFilterChoices), size=8, default=get_feed_filter_choices, ) # annual summary keys summary_keys = models.JSONField(null=True) preferred_timezone = models.CharField( choices=[(str(tz), str(tz)) for tz in pytz.all_timezones], default=str(pytz.utc), max_length=255, ) preferred_language = models.CharField( choices=LANGUAGES, null=True, blank=True, max_length=255, ) deactivation_reason = models.CharField( max_length=255, choices=DeactivationReason, null=True, blank=True ) deactivation_date = models.DateTimeField(null=True, blank=True) allow_reactivation = models.BooleanField(default=False) confirmation_code = models.CharField(max_length=32, default=new_access_code) name_field = "username" property_fields = [("following_link", "following")] field_tracker = FieldTracker(fields=["name", "avatar"]) # two factor authentication two_factor_auth = models.BooleanField(default=None, blank=True, null=True) otp_secret = models.CharField(max_length=32, default=None, blank=True, null=True) hotp_secret = models.CharField(max_length=32, default=None, blank=True, null=True) hotp_count = models.IntegerField(default=0, blank=True, null=True) @property def active_follower_requests(self): """Follow requests from active users""" return self.follower_requests.filter(is_active=True) @property def confirmation_link(self): """helper for generating confirmation links""" link = site_link() return f"{link}/confirm-email/{self.confirmation_code}" @property def following_link(self): """just how to find out the following info""" return f"{self.remote_id}/following" @property def alt_text(self): """alt text with username""" # pylint: disable=consider-using-f-string return "avatar for {:s}".format(self.localname or self.username) @property def display_name(self): """show the cleanest version of the user's name possible""" if self.name and self.name != "": return self.name return self.localname or self.username @property def deleted(self): """for consistent naming""" return not self.is_active @property def unread_notification_count(self): """count of notifications, for the templates""" return self.notification_set.filter(read=False).count() @property def has_unread_mentions(self): """whether any of the unread notifications are conversations""" return self.notification_set.filter( read=False, notification_type__in=["REPLY", "MENTION", "TAG", "REPORT"], ).exists() activity_serializer = activitypub.Person @classmethod def viewer_aware_objects(cls, viewer): """the user queryset filtered for the context of the logged in user""" queryset = cls.objects.filter(is_active=True) if viewer and viewer.is_authenticated: queryset = queryset.exclude(blocks=viewer) return queryset @classmethod def admins(cls): """Get a queryset of the admins for this instance""" return cls.objects.filter( models.Q(groups__name__in=["moderator", "admin"]) | models.Q(is_superuser=True), is_active=True, ).distinct() def update_active_date(self): """this user is here! they are doing things!""" self.last_active_date = timezone.now() self.save(broadcast=False, update_fields=["last_active_date"]) def to_outbox(self, filter_type=None, **kwargs): """an ordered collection of statuses""" if filter_type: filter_class = apps.get_model(f"bookwyrm.{filter_type}", require_ready=True) if not issubclass(filter_class, Status): raise TypeError( "filter_status_class must be a subclass of models.Status" ) queryset = filter_class.objects else: queryset = Status.objects queryset = ( queryset.filter( user=self, deleted=False, privacy__in=["public", "unlisted"], ) .select_subclasses() .order_by("-published_date") ) return self.to_ordered_collection( queryset, collection_only=True, remote_id=self.outbox, **kwargs ).serialize() def to_following_activity(self, **kwargs): """activitypub following list""" remote_id = f"{self.remote_id}/following" return self.to_ordered_collection( self.following.order_by("-updated_date").all(), remote_id=remote_id, id_only=True, **kwargs, ) def to_followers_activity(self, **kwargs): """activitypub followers list""" remote_id = self.followers_url return self.to_ordered_collection( self.followers.order_by("-updated_date").all(), remote_id=remote_id, id_only=True, **kwargs, ) def to_activity(self, **kwargs): """override default AP serializer to add context object idk if this is the best way to go about this""" if not self.is_active: return self.remote_id activity_object = super().to_activity(**kwargs) activity_object["@context"] = [ "https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1", { "manuallyApprovesFollowers": "as:manuallyApprovesFollowers", "schema": "http://schema.org#", "PropertyValue": "schema:PropertyValue", "value": "schema:value", }, ] return activity_object def save(self, *args, **kwargs): """populate fields for new local users""" created = not bool(self.id) if not self.local and not re.match(regex.FULL_USERNAME, self.username): # generate a username that uses the domain (webfinger format) actor_parts = urlparse(self.remote_id) self.username = f"{self.username}@{actor_parts.netloc}" # this user already exists, no need to populate fields if not created: if self.is_active: self.deactivation_date = None elif not self.deactivation_date: self.deactivation_date = timezone.now() super().save(*args, **kwargs) return # this is a new remote user, we need to set their remote server field if not self.local: super().save(*args, **kwargs) transaction.on_commit(lambda: set_remote_server(self.id)) return with transaction.atomic(): # populate fields for local users link = site_link() self.remote_id = f"{link}/user/{self.localname}" self.followers_url = f"{self.remote_id}/followers" self.inbox = f"{self.remote_id}/inbox" self.shared_inbox = f"{link}/inbox" self.outbox = f"{self.remote_id}/outbox" # an id needs to be set before we can proceed with related models super().save(*args, **kwargs) # make users editors by default try: group = ( apps.get_model("bookwyrm.SiteSettings") .objects.get() .default_user_auth_group ) if group: self.groups.add(group) except ObjectDoesNotExist: # this should only happen in tests pass # create keys and shelves for new local users self.key_pair = KeyPair.objects.create( remote_id=f"{self.remote_id}/#main-key" ) self.save(broadcast=False, update_fields=["key_pair"]) self.create_shelves() def delete(self, *args, **kwargs): """We don't actually delete the database entry""" # pylint: disable=attribute-defined-outside-init self.is_active = False self.avatar = "" # skip the logic in this class's save() super().save(*args, **kwargs) def deactivate(self): """Disable the user but allow them to reactivate""" # pylint: disable=attribute-defined-outside-init self.is_active = False self.deactivation_reason = "self_deactivation" self.allow_reactivation = True super().save(broadcast=False) def reactivate(self): """Now you want to come back, huh?""" # pylint: disable=attribute-defined-outside-init if not self.allow_reactivation: return self.is_active = True self.deactivation_reason = None self.allow_reactivation = False super().save( broadcast=False, update_fields=["deactivation_reason", "is_active", "allow_reactivation"], ) @property def local_path(self): """this model doesn't inherit bookwyrm model, so here we are""" # pylint: disable=consider-using-f-string return "/user/{:s}".format(self.localname or self.username) def create_shelves(self): """default shelves for a new user""" shelves = [ { "name": "To Read", "identifier": "to-read", }, { "name": "Currently Reading", "identifier": "reading", }, { "name": "Read", "identifier": "read", }, { "name": "Stopped Reading", "identifier": "stopped-reading", }, ] for shelf in shelves: Shelf( name=shelf["name"], identifier=shelf["identifier"], user=self, editable=False, ).save(broadcast=False) def raise_not_editable(self, viewer): """Who can edit the user object?""" if self == viewer or viewer.has_perm("bookwyrm.moderate_user"): return raise PermissionDenied() class KeyPair(ActivitypubMixin, BookWyrmModel): """public and private keys for a user""" private_key = models.TextField(blank=True, null=True) public_key = fields.TextField( blank=True, null=True, activitypub_field="publicKeyPem" ) activity_serializer = activitypub.PublicKey serialize_reverse_fields = [("owner", "owner", "id")] def get_remote_id(self): # self.owner is set by the OneToOneField on User return f"{self.owner.remote_id}/#main-key" def save(self, *args, **kwargs): """create a key pair""" # no broadcasting happening here if "broadcast" in kwargs: del kwargs["broadcast"] if not self.public_key: self.private_key, self.public_key = create_key_pair() return super().save(*args, **kwargs) @app.task(queue=MISC) def set_remote_server(user_id, allow_external_connections=False): """figure out the user's remote server in the background""" user = User.objects.get(id=user_id) actor_parts = urlparse(user.remote_id) federated_server = get_or_create_remote_server( actor_parts.netloc, allow_external_connections=allow_external_connections ) # if we were unable to find the server, we need to create a new entry for it if not federated_server: # and to do that, we will call this function asynchronously. if not allow_external_connections: set_remote_server.delay(user_id, allow_external_connections=True) return user.federated_server = federated_server user.save(broadcast=False, update_fields=["federated_server"]) if user.bookwyrm_user and user.outbox: get_remote_reviews.delay(user.outbox) def get_or_create_remote_server( domain, allow_external_connections=False, refresh=False ): """get info on a remote server""" server = FederatedServer() try: server = FederatedServer.objects.get(server_name=domain) if not refresh: return server except FederatedServer.DoesNotExist: pass if not allow_external_connections: return None try: data = get_data(f"https://{domain}/.well-known/nodeinfo") try: nodeinfo_url = data.get("links")[0].get("href") except (TypeError, KeyError): raise ConnectorException() data = get_data(nodeinfo_url) application_type = data.get("software", {}).get("name") application_version = data.get("software", {}).get("version") except ConnectorException: if server.id: return server application_type = application_version = None server.server_name = domain server.application_type = application_type server.application_version = application_version server.save() return server @app.task(queue=MISC) def get_remote_reviews(outbox): """ingest reviews by a new remote bookwyrm user""" outbox_page = outbox + "?page=true&type=Review" data = get_data(outbox_page) # TODO: pagination? for activity in data["orderedItems"]: if not activity["type"] == "Review": continue activitypub.Review(**activity).to_model() # pylint: disable=unused-argument @receiver(models.signals.post_save, sender=User) def preview_image(instance, *args, **kwargs): """create preview images when user is updated""" if not ENABLE_PREVIEW_IMAGES: return # don't call the task for remote users if not instance.local: return changed_fields = instance.field_tracker.changed() if len(changed_fields) > 0: generate_user_preview_image_task.delay(instance.id)
build
update_version
import logging import os from argparse import ArgumentParser from pathlib import Path from time import ctime logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def parse_arguments(): parser = ArgumentParser(description='Update Tribler Version') parser.add_argument('-r', '--repo', type=str, help='path to a repository folder', default='.') return parser.parse_args() if __name__ == '__main__': arguments = parse_arguments() logger.info(f'Arguments: {arguments}') ref_name = Path('.TriblerVersion').read_text().rstrip('\n') logger.info(f'Tribler tag: {ref_name}') commit = Path('.TriblerCommit').read_text().rstrip('\n') logger.info(f'Git Commit: {commit}') build_time = ctime() logger.info(f'Build time: {build_time}') sentry_url = os.environ.get('SENTRY_URL', None) logger.info(f'Sentry URL (hash): {hash(sentry_url)}') if sentry_url is None: logger.critical('Sentry url is not defined. To define sentry url use:' 'EXPORT SENTRY_URL=<sentry_url>\n' 'If you want to disable sentry, then define the following:' 'EXPORT SENTRY_URL=') exit(1) version_py = Path(arguments.repo) / 'src/tribler/core/version.py' logger.info(f'Write info to: {version_py}') version_py.write_text( f'version_id = "{ref_name}"\n' f'build_date = "{build_time}"\n' f'commit_id = "{commit}"\n' f'sentry_url = "{sentry_url}"\n' )
conversions
releaseDec2021
CONVERSIONS = { # Renamed items "Gas Cloud Harvester I": "Gas Cloud Scoop I", "Gas Cloud Harvester II": "Gas Cloud Scoop II", "'Crop' Gas Cloud Harvester": "'Crop' Gas Cloud Scoop", "'Plow' Gas Cloud Harvester": "'Plow' Gas Cloud Scoop", "Syndicate Gas Cloud Harvester": "Syndicate Gas Cloud Scoop", "Mercoxit Mining Crystal I": "Mercoxit Asteroid Mining Crystal Type A I", "Mercoxit Mining Crystal II": "Mercoxit Asteroid Mining Crystal Type A II", "Ubiquitous Moon Ore Mining Crystal I": "Ubiquitous Moon Mining Crystal Type A I", "Ubiquitous Moon Ore Mining Crystal II": "Ubiquitous Moon Mining Crystal Type A II", "Common Moon Ore Mining Crystal I": "Common Moon Mining Crystal Type A I", "Common Moon Ore Mining Crystal II": "Common Moon Mining Crystal Type A II", "Uncommon Moon Ore Mining Crystal I": "Uncommon Moon Mining Crystal Type A I", "Uncommon Moon Ore Mining Crystal II": "Uncommon Moon Mining Crystal Type A II", "Rare Moon Ore Mining Crystal I": "Rare Moon Mining Crystal Type A I", "Rare Moon Ore Mining Crystal II": "Rare Moon Mining Crystal Type A II", "Exceptional Moon Ore Mining Crystal I": "Exceptional Moon Mining Crystal Type A I", "Exceptional Moon Ore Mining Crystal II": "Exceptional Moon Mining Crystal Type A II", "Industrial Core I": "Capital Industrial Core I", "Industrial Core II": "Capital Industrial Core II", # Converted items "Veldspar Mining Crystal I": "Simple Asteroid Mining Crystal Type A I", "Scordite Mining Crystal I": "Simple Asteroid Mining Crystal Type A I", "Pyroxeres Mining Crystal I": "Simple Asteroid Mining Crystal Type A I", "Plagioclase Mining Crystal I": "Simple Asteroid Mining Crystal Type A I", "Veldspar Mining Crystal II": "Simple Asteroid Mining Crystal Type A II", "Scordite Mining Crystal II": "Simple Asteroid Mining Crystal Type A II", "Pyroxeres Mining Crystal II": "Simple Asteroid Mining Crystal Type A II", "Plagioclase Mining Crystal II": "Simple Asteroid Mining Crystal Type A II", "Omber Mining Crystal I": "Coherent Asteroid Mining Crystal Type A I", "Kernite Mining Crystal I": "Coherent Asteroid Mining Crystal Type A I", "Jaspet Mining Crystal I": "Coherent Asteroid Mining Crystal Type A I", "Hemorphite Mining Crystal I": "Coherent Asteroid Mining Crystal Type A I", "Hedbergite Mining Crystal I": "Coherent Asteroid Mining Crystal Type A I", "Omber Mining Crystal II": "Coherent Asteroid Mining Crystal Type A II", "Jaspet Mining Crystal II": "Coherent Asteroid Mining Crystal Type A II", "Kernite Mining Crystal II": "Coherent Asteroid Mining Crystal Type A II", "Hedbergite Mining Crystal II": "Coherent Asteroid Mining Crystal Type A II", "Hemorphite Mining Crystal II": "Coherent Asteroid Mining Crystal Type A II", "Gneiss Mining Crystal I": "Variegated Asteroid Mining Crystal Type A I", "Dark Ochre Mining Crystal I": "Variegated Asteroid Mining Crystal Type A I", "Crokite Mining Crystal I": "Variegated Asteroid Mining Crystal Type A I", "Gneiss Mining Crystal II": "Variegated Asteroid Mining Crystal Type A II", "Dark Ochre Mining Crystal II": "Variegated Asteroid Mining Crystal Type A II", "Crokite Mining Crystal II": "Variegated Asteroid Mining Crystal Type A II", "Bistot Mining Crystal I": "Complex Asteroid Mining Crystal Type A I", "Arkonor Mining Crystal I": "Complex Asteroid Mining Crystal Type A I", "Spodumain Mining Crystal I": "Complex Asteroid Mining Crystal Type A I", "Bistot Mining Crystal II": "Complex Asteroid Mining Crystal Type A II", "Arkonor Mining Crystal II": "Complex Asteroid Mining Crystal Type A II", "Spodumain Mining Crystal II": "Complex Asteroid Mining Crystal Type A II", }
model
follower
# encoding: utf-8 from __future__ import annotations import datetime as _datetime from typing import Generic, Optional, Type, TypeVar import ckan.model import ckan.model.core as core import ckan.model.domain_object as domain_object import ckan.model.meta as meta import sqlalchemy import sqlalchemy.orm from ckan.types import Query from typing_extensions import Self Follower = TypeVar("Follower", bound="ckan.model.User") Followed = TypeVar( "Followed", "ckan.model.User", "ckan.model.Package", "ckan.model.Group" ) class ModelFollowingModel(domain_object.DomainObject, Generic[Follower, Followed]): follower_id: str object_id: str datetime: _datetime.datetime def __init__(self, follower_id: str, object_id: str) -> None: self.follower_id = follower_id self.object_id = object_id self.datetime = _datetime.datetime.utcnow() @classmethod def _follower_class(cls) -> Type[Follower]: raise NotImplementedError() @classmethod def _object_class(cls) -> Type[Followed]: raise NotImplementedError() @classmethod def get( cls, follower_id: Optional[str], object_id: Optional[str] ) -> Optional[Self]: """Return a ModelFollowingModel object for the given follower_id and object_id, or None if no such follower exists. """ query = cls._get(follower_id, object_id) following = cls._filter_following_objects(query) if len(following) == 1: return following[0] return None @classmethod def is_following(cls, follower_id: Optional[str], object_id: Optional[str]) -> bool: """Return True if follower_id is currently following object_id, False otherwise. """ return cls.get(follower_id, object_id) is not None @classmethod def followee_count(cls, follower_id: str) -> int: """Return the number of objects followed by the follower.""" return cls._get_followees(follower_id).count() @classmethod def followee_list(cls, follower_id: Optional[str]) -> list[Self]: """Return a list of objects followed by the follower.""" query = cls._get_followees(follower_id) followees = cls._filter_following_objects(query) return followees @classmethod def follower_count(cls, object_id: str) -> int: """Return the number of followers of the object.""" return cls._get_followers(object_id).count() @classmethod def follower_list(cls, object_id: Optional[str]) -> list[Self]: """Return a list of followers of the object.""" query = cls._get_followers(object_id) followers = cls._filter_following_objects(query) return followers @classmethod def _filter_following_objects( cls, query: Query[tuple[Self, Follower, Followed]] ) -> list[Self]: return [q[0] for q in query] @classmethod def _get_followees( cls, follower_id: Optional[str] ) -> Query[tuple[Self, Follower, Followed]]: return cls._get(follower_id) @classmethod def _get_followers( cls, object_id: Optional[str] ) -> Query[tuple[Self, Follower, Followed]]: return cls._get(None, object_id) @classmethod def _get( cls, follower_id: Optional[str] = None, object_id: Optional[str] = None ) -> Query[tuple[Self, Follower, Followed]]: follower_alias = sqlalchemy.orm.aliased(cls._follower_class()) object_alias = sqlalchemy.orm.aliased(cls._object_class()) follower_id = follower_id or cls.follower_id object_id = object_id or cls.object_id query: Query[tuple[Self, Follower, Followed]] = meta.Session.query( cls, follower_alias, object_alias ).filter( sqlalchemy.and_( follower_alias.id == follower_id, cls.follower_id == follower_alias.id, cls.object_id == object_alias.id, follower_alias.state != core.State.DELETED, object_alias.state != core.State.DELETED, object_alias.id == object_id, ) ) return query class UserFollowingUser(ModelFollowingModel["ckan.model.User", "ckan.model.User"]): """A many-many relationship between users. A relationship between one user (the follower) and another (the object), that means that the follower is currently following the object. """ @classmethod def _follower_class(cls): return ckan.model.User @classmethod def _object_class(cls): return ckan.model.User user_following_user_table = sqlalchemy.Table( "user_following_user", meta.metadata, sqlalchemy.Column( "follower_id", sqlalchemy.types.UnicodeText, sqlalchemy.ForeignKey("user.id", onupdate="CASCADE", ondelete="CASCADE"), primary_key=True, nullable=False, ), sqlalchemy.Column( "object_id", sqlalchemy.types.UnicodeText, sqlalchemy.ForeignKey("user.id", onupdate="CASCADE", ondelete="CASCADE"), primary_key=True, nullable=False, ), sqlalchemy.Column("datetime", sqlalchemy.types.DateTime, nullable=False), ) meta.mapper(UserFollowingUser, user_following_user_table) class UserFollowingDataset( ModelFollowingModel["ckan.model.User", "ckan.model.Package"] ): """A many-many relationship between users and datasets (packages). A relationship between a user (the follower) and a dataset (the object), that means that the user is currently following the dataset. """ @classmethod def _follower_class(cls): return ckan.model.User @classmethod def _object_class(cls): return ckan.model.Package user_following_dataset_table = sqlalchemy.Table( "user_following_dataset", meta.metadata, sqlalchemy.Column( "follower_id", sqlalchemy.types.UnicodeText, sqlalchemy.ForeignKey("user.id", onupdate="CASCADE", ondelete="CASCADE"), primary_key=True, nullable=False, ), sqlalchemy.Column( "object_id", sqlalchemy.types.UnicodeText, sqlalchemy.ForeignKey("package.id", onupdate="CASCADE", ondelete="CASCADE"), primary_key=True, nullable=False, ), sqlalchemy.Column("datetime", sqlalchemy.types.DateTime, nullable=False), ) meta.mapper(UserFollowingDataset, user_following_dataset_table) class UserFollowingGroup(ModelFollowingModel["ckan.model.User", "ckan.model.Group"]): """A many-many relationship between users and groups. A relationship between a user (the follower) and a group (the object), that means that the user is currently following the group. """ @classmethod def _follower_class(cls): return ckan.model.User @classmethod def _object_class(cls): return ckan.model.Group user_following_group_table = sqlalchemy.Table( "user_following_group", meta.metadata, sqlalchemy.Column( "follower_id", sqlalchemy.types.UnicodeText, sqlalchemy.ForeignKey("user.id", onupdate="CASCADE", ondelete="CASCADE"), primary_key=True, nullable=False, ), sqlalchemy.Column( "object_id", sqlalchemy.types.UnicodeText, sqlalchemy.ForeignKey("group.id", onupdate="CASCADE", ondelete="CASCADE"), primary_key=True, nullable=False, ), sqlalchemy.Column("datetime", sqlalchemy.types.DateTime, nullable=False), ) meta.mapper(UserFollowingGroup, user_following_group_table)
daw
project
import copy import math import os import re import shutil from sglib import constants from sglib.lib import history, util from sglib.lib.translate import _ from sglib.lib.util import * from sglib.log import LOG from sglib.math import clip_min, clip_value from sglib.models.daw.playlist import Playlist from sglib.models.daw.routing import MIDIRoutes, RoutingGraph from sglib.models.project.abstract import AbstractProject from sglib.models.stargate import * from sglib.models.stargate import AudioInputTracks from sglib.models.track_plugin import track_plugin, track_plugins from . import _shared from .atm_sequence import DawAtmRegion from .audio_item import DawAudioItem from .item import item from .seq_item import sequencer_item from .sequencer import sequencer try: from sg_py_vendor.pymarshal.json import * except ImportError: from pymarshal.json import * folder_daw = os.path.join("projects", "daw") folder_items = os.path.join(folder_daw, "items") folder_tracks = os.path.join(folder_daw, "tracks") folder_automation = os.path.join(folder_daw, "automation") FOLDER_SONGS = os.path.join(folder_daw, "songs") FILE_PLAYLIST = os.path.join(folder_daw, "playlist.json") file_sequences_atm = os.path.join(folder_daw, "automation.txt") file_routing_graph = os.path.join(folder_daw, "routing.txt") file_midi_routing = os.path.join( folder_daw, "midi_routing.txt", ) file_pyitems = os.path.join(folder_daw, "items.txt") file_takes = os.path.join(folder_daw, "takes.txt") file_pytracks = os.path.join(folder_daw, "tracks.txt") file_pyinput = os.path.join(folder_daw, "input.txt") file_notes = os.path.join(folder_daw, "notes.txt") class DawProject(AbstractProject): def __init__(self, a_with_audio): self.undo_context = 0 self.TRACK_COUNT = _shared.TRACK_COUNT_ALL self.last_item_number = 1 self.clear_history() self.suppress_updates = False self._items_dict_cache = None self._sequence_cache = {} self._item_cache = {} def quirks(self): """Make modifications to the project folder format as needed, to bring old projects up to date on format changes """ # TODO Stargate v2: Remove all existing quirks self._quirk_per_song_automation() def _quirk_per_song_automation(self): """When the song list feature was implemented, this was overlooked, and automation was shared between all songs, which is never really ideal, and often just bad. So copy automation.txt for the automation folder for each song uid, as this will be equivalent to what already existed, and not delete somebody's automation """ if not os.path.isfile(self.automation_file): return LOG.info("Migrating project to per-song automation files") uids = [os.path.basename(x) for x in os.listdir(self.song_folder)] for uid in uids: path = os.path.join(self.automation_folder, uid) LOG.info(f"Copying {self.automation_file} to {path}") shutil.copy(self.automation_file, path) os.remove(self.automation_file) def ipc(self): return constants.DAW_IPC def save_file(self, a_folder, a_file, a_text, a_force_new=False): f_result = AbstractProject.save_file( self, a_folder, a_file, a_text, a_force_new ) if f_result: f_existed, f_old = f_result f_history_file = history.history_file( a_folder, a_file, a_text, f_old, f_existed ) self.history_files.append(f_history_file) def set_undo_context(self, a_context): self.undo_context = a_context def clear_undo_context(self, a_context): self.history_commits[a_context] = [] def commit(self, a_message, a_discard=False): """Commit the project history""" if self.undo_context not in self.history_commits: self.history_commits[self.undo_context] = [] if self.history_undo_cursor > 0: self.history_commits[self.undo_context] = self.history_commits[ self.undo_context ][: self.history_undo_cursor] self.history_undo_cursor = 0 if self.history_files and not a_discard: f_commit = history.history_commit(self.history_files, a_message) self.history_commits[self.undo_context].append(f_commit) self.history_files = [] def clear_history(self): self.history_undo_cursor = 0 self.history_files = [] self.history_commits = {} def undo(self): if ( self.undo_context not in self.history_commits or self.history_undo_cursor >= len(self.history_commits[self.undo_context]) ): return False self.history_undo_cursor += 1 self.history_commits[self.undo_context][-1 * self.history_undo_cursor].undo( self.project_folder ) return True def redo(self): if ( self.undo_context not in self.history_commits or self.history_undo_cursor == 0 ): return False self.history_commits[self.undo_context][-1 * self.history_undo_cursor].redo( self.project_folder ) self.history_undo_cursor -= 1 return True def get_files_dict(self, a_folder, a_ext=None): f_result = {} f_files = [] if a_ext is not None: for f_file in os.listdir(a_folder): if f_file.endswith(a_ext): f_files.append(f_file) else: f_files = os.listdir(a_folder) for f_file in f_files: f_result[f_file] = read_file_text(os.path.join(a_folder, f_file)) return f_result def set_project_folders(self, a_project_file): # folders self.project_folder = os.path.dirname(a_project_file) self.project_file = os.path.splitext(os.path.basename(a_project_file))[0] self.automation_folder = os.path.join( self.project_folder, folder_automation, ) self.items_folder = os.path.join( self.project_folder, folder_items, ) self.host_folder = os.path.join(self.project_folder, folder_daw) self.track_pool_folder = os.path.join(self.project_folder, folder_tracks) self.song_folder = os.path.join( self.project_folder, FOLDER_SONGS, ) # files self.pyitems_file = os.path.join(self.project_folder, file_pyitems) self.takes_file = os.path.join(self.project_folder, file_takes) self.pyscale_file = os.path.join(self.project_folder, "default.pyscale") self.pynotes_file = os.path.join(self.project_folder, file_notes) self.routing_graph_file = os.path.join(self.project_folder, file_routing_graph) self.midi_routing_file = os.path.join(self.project_folder, file_midi_routing) self.automation_file = os.path.join(self.project_folder, file_sequences_atm) self.playlist_file = os.path.join( self.project_folder, FILE_PLAYLIST, ) self.audio_inputs_file = os.path.join(self.project_folder, file_pyinput) self.project_folders = [ self.automation_folder, self.items_folder, self.project_folder, self.song_folder, self.track_pool_folder, ] # Do it here in case we add new folders later after a project # has already been created for project_dir in self.project_folders: if not os.path.isdir(project_dir): LOG.info(f"Creating directory: {project_dir}") os.makedirs(project_dir) def open_project(self, a_project_file, a_notify_osc=True): self.set_project_folders(a_project_file) self.quirks() if not os.path.exists(a_project_file): LOG.info( "project file {} does not exist, creating as " "new project".format( a_project_file ) ) self.new_project(a_project_file) if a_notify_osc: constants.DAW_IPC.open_song(self.project_folder) def new_project(self, a_project_file, a_notify_osc=True): self.set_project_folders(a_project_file) j = marshal_json(Playlist.new()) j = json.dumps(j, indent=2, sort_keys=True) self.save_file("", FILE_PLAYLIST, j) self.save_file( FOLDER_SONGS, "0", str(sequencer(name="default")), ) self.create_file("", file_pyitems, terminating_char) f_tracks = tracks() for i in range(_shared.TRACK_COUNT_ALL): f_tracks.add_track( i, track( a_track_uid=i, a_track_pos=i, a_name="Main" if i == 0 else "track{}".format(i), ), ) plugins = track_plugins() for i2 in range(constants.TOTAL_PLUGINS_PER_TRACK): plugins.plugins.append( track_plugin(i2, 0, -1), ) self.save_track_plugins(i, plugins) self.create_file("", file_pytracks, str(f_tracks)) self.commit("Created project") if a_notify_osc: constants.DAW_IPC.open_song(self.project_folder) def active_audio_pool_uids(self): playlist = self.get_playlist() result = set() for uid in (x.seq_uid for x in playlist.pool): f_sequence = self.get_sequence(uid=uid) f_item_uids = set(x.item_uid for x in f_sequence.items) f_items = [self.get_item_by_uid(x) for x in f_item_uids] result.update(set(y.uid for x in f_items for y in x.items.values())) for uid in self.get_plugin_audio_pool_uids(): result.add(uid) return result def get_notes(self): if os.path.isfile(self.pynotes_file): return read_file_text(self.pynotes_file) else: return "" def write_notes(self, a_text): write_file_text(self.pynotes_file, a_text) def set_midi_scale(self, a_key, a_scale): write_file_text(self.pyscale_file, "{}|{}".format(a_key, a_scale)) def get_midi_scale(self): if os.path.exists(self.pyscale_file): f_list = read_file_text(self.pyscale_file).split("|") return (int(f_list[0]), int(f_list[1])) else: return None def get_routing_graph(self) -> RoutingGraph: if os.path.isfile(self.routing_graph_file): content = read_file_text(self.routing_graph_file) return RoutingGraph.from_str(content) else: return RoutingGraph() def save_routing_graph(self, a_graph, a_notify=True): self.save_file("", file_routing_graph, str(a_graph)) if a_notify: constants.DAW_IPC.update_track_send() def check_output(self, a_track=None): """Ensure that any track with items or plugins is routed to main if it does not have any routings """ if a_track is not None and a_track <= 0: return graph = self.get_routing_graph() sequence = self.get_sequence() modified = False tracks = set(x.track_num for x in sequence.items) if 0 in tracks: tracks.remove(0) if a_track is not None: tracks.add(a_track) for i in tracks: if graph.set_default_output(i): modified = True if modified: self.save_routing_graph(graph) self.commit("Set default output") def get_midi_routing(self): if os.path.isfile(self.midi_routing_file): content = read_file_text(self.midi_routing_file) return MIDIRoutes.from_str(content) else: return MIDIRoutes() def save_midi_routing(self, a_routing, a_notify=True): self.save_file("", file_midi_routing, str(a_routing)) if a_notify: self.commit("Update MIDI routing") def get_takes(self): if os.path.isfile(self.takes_file): content = read_file_text(self.takes_file) return SgTakes.from_str(content) else: return SgTakes() def save_takes(self, a_takes): self.save_file("", file_takes, str(a_takes)) def get_items_dict(self): if self._items_dict_cache: return self._items_dict_cache try: content = read_file_text(self.pyitems_file) return name_uid_dict.from_str(content) except: return name_uid_dict() def save_items_dict(self, a_uid_dict): self._items_dict_cache = a_uid_dict self.save_file("", file_pyitems, str(a_uid_dict)) def create_sequence(self, name): """Create a new sequence with the next available uid @raises: IndexError if no more uids left """ uid = self.get_next_sequence_uid() sequence = self.get_sequence(uid, name) self.save_file( FOLDER_SONGS, uid, str(sequence), ) self.save_atm_sequence(DawAtmRegion(), uid) constants.DAW_IPC.new_sequence(uid) return uid, sequence def get_next_sequence_uid(self): """Get the next available sequence uid, or None if no uids are available @raises: IndexError if no more uids left """ for i in range(constants.DAW_MAX_SONG_COUNT): path = os.path.join( self.song_folder, str(i), ) if not os.path.exists(path): return i raise IndexError def sequence_uids_by_name(self): """Return a dict of {'sequence name': (uid, sequence)}""" result = {} for i in range(constants.DAW_MAX_SONG_COUNT): path = os.path.join( self.song_folder, str(i), ) if os.path.exists(path): sequence = self.get_sequence(i) result[sequence.name] = (i, sequence) return result def get_sequence( self, uid=None, name="default", ): """Get an existing sequence, or create a new empty sequence""" if uid is None: uid = constants.DAW_CURRENT_SEQUENCE_UID assert uid >= 0 and uid < constants.DAW_MAX_SONG_COUNT, uid if uid in self._sequence_cache: return self._sequence_cache[uid] sequencer_file = os.path.join( self.song_folder, str(uid), ) if os.path.isfile(sequencer_file): content = read_file_text(sequencer_file) return sequencer.from_str(content) else: return sequencer(name) def import_midi_file( self, a_midi_file, a_beat_offset, a_track_offset, item_name, ): """ @a_midi_file: An instance of DawMidiFile """ f_sequencer = self.get_sequence() f_active_tracks = [ x + a_track_offset for x in a_midi_file.result_dict if x + a_track_offset < _shared.TRACK_COUNT_ALL ] f_end_beat = math.ceil( max(clip_min(x.get_length(), 1.0) for x in a_midi_file.result_dict.values()) ) f_sequencer.clear_range(f_active_tracks, a_beat_offset, f_end_beat) for k, v in a_midi_file.result_dict.items(): f_track = a_track_offset + int(k) if f_track >= _shared.TRACK_COUNT_ALL: break f_item_ref = sequencer_item( f_track, a_beat_offset, math.ceil(clip_min(v.get_length(), 1.0)), v.uid, ) f_sequencer.add_item_ref_by_uid(f_item_ref) self.save_sequence(f_sequencer) def get_playlist(self): if os.path.isfile(self.playlist_file): j = read_file_json(self.playlist_file) return unmarshal_json(j, Playlist) else: return Playlist.new() def save_playlist(self, playlist): j = marshal_json(playlist) j = json.dumps(j, indent=2, sort_keys=True) self.save_file("", FILE_PLAYLIST, j) self.commit("Update playlist") def get_atm_sequence(self, song_uid=None): if song_uid is None: song_uid = constants.DAW_CURRENT_SEQUENCE_UID path = os.path.join(self.automation_folder, str(song_uid)) if os.path.isfile(path): content = read_file_text(path) return DawAtmRegion.from_str(content) else: return DawAtmRegion() def save_atm_sequence(self, a_sequence, song_uid=None): if song_uid is None: song_uid = constants.DAW_CURRENT_SEQUENCE_UID self.save_file(folder_automation, str(song_uid), str(a_sequence)) self.commit("Update automation") constants.DAW_IPC.save_atm_sequence() def all_items(self): """Generator function to open, modify and save all items""" for name in self.get_item_list(): item = self.get_item_by_name(name) yield item self.save_item_by_uid(item.uid, item) def replace_all_audio_file(self, old_uid, new_uid): """Replace all instances of an audio file with another in all sequencer items in the project @old_uid: The UID of the old audio file in the audio pool @new_uid: The UID of the new audio file in the audio pool """ for item in self.all_items(): item.replace_all_audio_file(old_uid, new_uid) def clone_sef(self, audio_item): """Clone start/end/fade for all instances of a file in the project""" for item in self.all_items(): item.clone_sef(audio_item) def rename_items(self, a_item_names, a_new_item_name): """@a_item_names: A list of str""" assert isinstance(a_item_names, list), a_item_names f_items_dict = self.get_items_dict() if len(a_item_names) > 1 or f_items_dict.name_exists(a_new_item_name): f_suffix = 1 f_new_item_name = f"{a_new_item_name}-" for f_item_name in a_item_names: while f_items_dict.name_exists( f"{f_new_item_name}{f_suffix}", ): f_suffix += 1 f_items_dict.rename_item( f_item_name, f_new_item_name + str(f_suffix), ) else: f_items_dict.rename_item(a_item_names[0], a_new_item_name) self.save_items_dict(f_items_dict) def get_item_string(self, a_item_uid): try: path = os.path.join(*(str(x) for x in (self.items_folder, a_item_uid))) return read_file_text(path) except: return "" def get_item_by_uid(self, a_item_uid, _copy=False): a_item_uid = int(a_item_uid) if a_item_uid in self._item_cache: _item = self._item_cache[a_item_uid] if _copy: _item = copy.deepcopy(_item) else: _item = item.from_str( self.get_item_string(a_item_uid), a_item_uid, ) assert _item.uid == a_item_uid, ( "UIDs do not match", _item.uid, a_item_uid, ) return _item def get_item_by_name(self, a_item_name, _copy=False): items_dict = self.get_items_dict() uid = items_dict.get_uid_by_name(a_item_name) return self.get_item_by_uid(uid, _copy=_copy) def save_audio_inputs(self, a_tracks): if not self.suppress_updates: self.save_file("", file_pyinput, str(a_tracks)) def get_audio_inputs(self): if os.path.isfile(self.audio_inputs_file): content = read_file_text(self.audio_inputs_file) return AudioInputTracks.from_str(content) else: return AudioInputTracks() def reorder_tracks(self, a_dict): constants.IPC.pause_engine() f_tracks = self.get_tracks() f_tracks.reorder(a_dict) f_audio_inputs = self.get_audio_inputs() f_audio_inputs.reorder(a_dict) f_midi_routings = self.get_midi_routing() f_midi_routings.reorder(a_dict) f_track_plugins = {k: self.get_track_plugins(k) for k in f_tracks.tracks} # Delete the existing track files for k in f_track_plugins: f_path = os.path.join(*(str(x) for x in (self.track_pool_folder, k))) if os.path.exists(f_path): os.remove(f_path) for k, v in f_track_plugins.items(): if v: self.save_track_plugins(a_dict[k], v) f_graph = self.get_routing_graph() f_graph.reorder(a_dict) sequences = self.sequence_uids_by_name() for name, tup in sequences.items(): uid = tup[0] sequence = self.get_sequence(uid) sequence.reorder(a_dict) self.save_sequence(sequence, a_notify=False, uid=uid) self.save_tracks(f_tracks) self.save_audio_inputs(f_audio_inputs) self.save_routing_graph(f_graph, a_notify=False) self.save_midi_routing(f_midi_routings, a_notify=False) constants.DAW_IPC.open_song(self.project_folder, False) constants.IPC.resume_engine() self.commit("Re-order tracks", a_discard=True) self.clear_history() def get_tracks_string(self): try: path = os.path.join(self.project_folder, file_pytracks) return read_file_text(path) except: return terminating_char def get_tracks(self): return tracks.from_str(self.get_tracks_string()) def get_track_plugin_uids(self, a_track_num): f_plugins = self.get_track_plugins(a_track_num) if f_plugins: return set(x.plugin_uid for x in f_plugins.plugins) else: return f_plugins def create_empty_item(self, a_item_name="item"): f_items_dict = self.get_items_dict() f_item_name = self.get_next_default_item_name( a_item_name, a_items_dict=f_items_dict, ) f_uid = f_items_dict.add_new_item(f_item_name) self.save_file(folder_items, str(f_uid), item(f_uid)) constants.DAW_IPC.save_item(f_uid) self.save_items_dict(f_items_dict) return f_uid def copy_item(self, a_old_item: str, a_new_item: str): f_items_dict = self.get_items_dict() f_uid = f_items_dict.add_new_item(a_new_item) f_old_uid = f_items_dict.get_uid_by_name(a_old_item) f_new_item = copy.deepcopy(self.get_item_by_uid(f_old_uid)) f_new_item.uid = f_uid self.save_file( folder_items, str(f_uid), str(f_new_item), ) constants.DAW_IPC.save_item(f_uid) self.save_items_dict(f_items_dict) return f_uid def save_item_by_uid(self, a_uid, a_item, a_new_item=False): a_uid = int(a_uid) a_item = copy.deepcopy(a_item) a_item.uid = a_uid self._item_cache[a_uid] = a_item if not self.suppress_updates: self.save_file( folder_items, str(a_uid), str(a_item), a_new_item, ) constants.DAW_IPC.save_item(a_uid) def save_sequence( self, a_sequence, a_notify=True, uid=None, ): if self.suppress_updates: return a_sequence.fix_overlaps() if uid is None: uid = str(constants.DAW_CURRENT_SEQUENCE_UID) self._sequence_cache[uid] = a_sequence self.save_file( FOLDER_SONGS, uid, str(a_sequence), ) if a_notify: constants.DAW_IPC.save_sequence(uid) self.check_output() def save_tracks(self, a_tracks): if not self.suppress_updates: self.save_file("", file_pytracks, str(a_tracks)) # Is there a need for a configure message here? def save_track_plugins(self, a_uid, a_track): """@a_uid: int, the track number @a_track: track_plugins """ int(a_uid) # Test that it can be cast to an int f_folder = folder_tracks if not self.suppress_updates: self.save_file(f_folder, str(a_uid), str(a_track)) def item_exists(self, a_item_name, a_name_dict=None): if a_name_dict is None: f_name_dict = self.get_items_dict() else: f_name_dict = a_name_dict if str(a_item_name) in f_name_dict.uid_lookup: return True else: return False def get_next_default_item_name( self, a_item_name="item", a_items_dict=None, ): f_item_name = str(a_item_name) f_end_number = re.search(r"[0-9]+$", f_item_name) if f_item_name == "item": f_start = self.last_item_number else: if f_end_number: f_num_str = f_end_number.group() f_start = int(f_num_str) f_item_name = f_item_name[: -len(f_num_str)] f_item_name = f_item_name.strip("-") else: f_start = 1 if a_items_dict: f_items_dict = a_items_dict else: f_items_dict = self.get_items_dict() for i in range(f_start, 10000): f_result = "{}-{}".format(f_item_name, i).strip("-") if not f_result in f_items_dict.uid_lookup: if f_item_name == "item": self.last_item_number = i return f_result def get_item_list(self): f_result = self.get_items_dict() return sorted(f_result.uid_lookup.keys()) def check_audio_files(self): """Verify that all audio files exist""" f_result = [] f_sequences = self.get_sequences_dict() f_audio_pool = constants.PROJECT.get_audio_pool() by_uid = f_audio_pool.by_uid() f_to_delete = [] f_commit = False for k, v in by_uid.items(): if not os.path.isfile(v): f_to_delete.append(k) if f_to_delete: f_commit = True f_audio_pool.remove_by_uid(f_to_delete) self.save_audio_pool(f_audio_pool) LOG.error("Removed missing audio item(s) from audio_pool") f_audio_pool = constants.PROJECT.get_audio_pool() by_uid = f_audio_pool.by_uid() for f_uid in list(f_sequences.uid_lookup.values()): f_to_delete = [] f_sequence = self.get_audio_sequence(f_uid) for k, v in list(f_sequence.items.items()): if v.uid not in by_uid: f_to_delete.append(k) if len(f_to_delete) > 0: f_commit = True for f_key in f_to_delete: f_sequence.remove_item(f_key) f_result += f_to_delete self.save_audio_sequence(f_uid, f_sequence) LOG.error( "Removed missing audio item(s) " "from sequence {}".format(f_uid) ) if f_commit: self.commit("check_audio_file") return f_result
VersionUpgrade22to24
VersionUpgrade
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. import configparser # To get version numbers from config files. import io import os import os.path from typing import Dict, List, Optional, Tuple import UM.VersionUpgrade from UM.Resources import Resources from UM.VersionUpgrade import VersionUpgrade # Superclass of the plugin. class VersionUpgrade22to24(VersionUpgrade): def upgradeMachineInstance( self, serialised: str, filename: str ) -> Optional[Tuple[List[str], List[str]]]: # All of this is needed to upgrade custom variant machines from old Cura to 2.4 where # `definition_changes` instance container has been introduced. Variant files which # look like the the handy work of the old machine settings plugin are converted directly # on disk. config = configparser.ConfigParser(interpolation=None) config.read_string(serialised) # Read the input string as config file. if config.get("metadata", "type") == "definition_changes": # This is not a container stack, don't upgrade it here return None config.set("general", "version", "3") container_list = [] # type: List[str] if config.has_section("containers"): for index, container_id in config.items("containers"): container_list.append(container_id) elif config.has_option("general", "containers"): containers = config.get("general", "containers") container_list = containers.split(",") user_variants = self.__getUserVariants() name_path_dict = {} for variant in user_variants: name_path_dict[variant["name"]] = variant["path"] user_variant_names = set(container_list).intersection(name_path_dict.keys()) if len(user_variant_names): # One of the user defined variants appears in the list of containers in the stack. for variant_name in ( user_variant_names ): # really there should just be one variant to convert. config_name = self.__convertVariant(name_path_dict[variant_name]) # Change the name of variant and insert empty_variant into the stack. new_container_list = [] for item in container_list: if not item: # the last item may be an empty string continue if item == variant_name: new_container_list.append("empty_variant") new_container_list.append(config_name) else: new_container_list.append(item) container_list = new_container_list if not config.has_section("containers"): config.add_section("containers") config.remove_option("general", "containers") for idx, _ in enumerate(container_list): config.set("containers", str(idx), container_list[idx]) output = io.StringIO() config.write(output) return [filename], [output.getvalue()] def __convertVariant(self, variant_path: str) -> str: # Copy the variant to the machine_instances/*_settings.inst.cfg variant_config = configparser.ConfigParser(interpolation=None) with open(variant_path, "r", encoding="utf-8") as fhandle: variant_config.read_file(fhandle) config_name = "Unknown Variant" if variant_config.has_section("general") and variant_config.has_option( "general", "name" ): config_name = variant_config.get("general", "name") if config_name.endswith("_variant"): config_name = config_name[: -len("_variant")] + "_settings" variant_config.set("general", "name", config_name) if not variant_config.has_section("metadata"): variant_config.add_section("metadata") variant_config.set("metadata", "type", "definition_changes") resource_path = Resources.getDataStoragePath() machine_instances_dir = os.path.join(resource_path, "machine_instances") if variant_path.endswith("_variant.inst.cfg"): variant_path = ( variant_path[: -len("_variant.inst.cfg")] + "_settings.inst.cfg" ) with open( os.path.join(machine_instances_dir, os.path.basename(variant_path)), "w", encoding="utf-8", ) as fp: variant_config.write(fp) return config_name def __getUserVariants(self) -> List[Dict[str, str]]: resource_path = Resources.getDataStoragePath() variants_dir = os.path.join(resource_path, "variants") result = [] for entry in os.scandir(variants_dir): if entry.name.endswith(".inst.cfg") and entry.is_file(): config = configparser.ConfigParser(interpolation=None) with open(entry.path, "r", encoding="utf-8") as fhandle: config.read_file(fhandle) if config.has_section("general") and config.has_option( "general", "name" ): result.append( {"path": entry.path, "name": config.get("general", "name")} ) return result def upgradeExtruderTrain( self, serialised: str, filename: str ) -> Tuple[List[str], List[str]]: config = configparser.ConfigParser(interpolation=None) config.read_string(serialised) # Read the input string as config file. config.set( "general", "version", "3" ) # Just bump the version number. That is all we need for now. output = io.StringIO() config.write(output) return [filename], [output.getvalue()] def upgradePreferences( self, serialised: str, filename: str ) -> Tuple[List[str], List[str]]: config = configparser.ConfigParser(interpolation=None) config.read_string(serialised) if not config.has_section("general"): raise UM.VersionUpgrade.FormatException('No "general" section.') # Make z_seam_x and z_seam_y options visible. In a clean 2.4 they are visible by default. if config.has_option("general", "visible_settings"): visible_settings = config.get("general", "visible_settings") visible_set = set(visible_settings.split(";")) visible_set.add("z_seam_x") visible_set.add("z_seam_y") config.set("general", "visible_settings", ";".join(visible_set)) config.set("general", "version", value="4") output = io.StringIO() config.write(output) return [filename], [output.getvalue()] def upgradeQuality( self, serialised: str, filename: str ) -> Tuple[List[str], List[str]]: config = configparser.ConfigParser(interpolation=None) config.read_string(serialised) # Read the input string as config file. config.set( "metadata", "type", "quality_changes" ) # Update metadata/type to quality_changes config.set( "general", "version", "2" ) # Just bump the version number. That is all we need for now. output = io.StringIO() config.write(output) return [filename], [output.getvalue()] def getCfgVersion(self, serialised: str) -> int: parser = configparser.ConfigParser(interpolation=None) parser.read_string(serialised) format_version = int( parser.get("general", "version") ) # Explicitly give an exception when this fails. That means that the file format is not recognised. setting_version = int(parser.get("metadata", "setting_version", fallback="0")) return format_version * 1000000 + setting_version
widgets
subscriptionswidget
from PyQt5.QtCore import Qt from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QLabel, QWidget from tribler.gui.sentry_mixin import AddBreadcrumbOnShowMixin from tribler.gui.utilities import ( connect, format_votes_rich_text, get_votes_rating_description, tr, ) from tribler.gui.widgets.tablecontentdelegate import DARWIN, WINDOWS class SubscriptionsWidget(AddBreadcrumbOnShowMixin, QWidget): """ This widget shows a favorite button and the number of subscriptions that a specific channel has. """ def __init__(self, parent): QWidget.__init__(self, parent) self.subscribe_button = None self.initialized = False self.contents_widget = None self.channel_rating_label = None def initialize(self, contents_widget): if not self.initialized: # We supply a link to the parent channelcontentswidget to use its property that # returns the current model in use (top of the stack) self.contents_widget = contents_widget self.subscribe_button = self.findChild(QWidget, "subscribe_button") self.channel_rating_label = self.findChild(QLabel, "channel_rating_label") self.channel_rating_label.setTextFormat(Qt.RichText) connect(self.subscribe_button.clicked, self.on_subscribe_button_click) self.subscribe_button.setToolTip(tr("Click to subscribe/unsubscribe")) connect(self.subscribe_button.toggled, self._adjust_tooltip) self.initialized = True def _adjust_tooltip(self, toggled): tooltip = (tr("Subscribed.") if toggled else tr("Not subscribed.")) + tr( "\n(Click to unsubscribe)" ) self.subscribe_button.setToolTip(tooltip) def update_subscribe_button_if_channel_matches(self, changed_channels_list): # TODO: the stuff requires MAJOR refactoring with properly implemented QT MVC model... if not ( self.contents_widget.model and self.contents_widget.model.channel_info.get("public_key") ): return for channel_info in changed_channels_list: if ( self.contents_widget.model.channel_info["public_key"] == channel_info["public_key"] and self.contents_widget.model.channel_info["id"] == channel_info["id"] ): self.update_subscribe_button(remote_response=channel_info) return def update_subscribe_button(self, remote_response=None): # A safeguard against race condition that happens when the user changed # the channel view before the response came in if self.isHidden(): return if remote_response and "subscribed" in remote_response: self.contents_widget.model.channel_info["subscribed"] = remote_response[ "subscribed" ] self.subscribe_button.setChecked(bool(remote_response["subscribed"])) self._adjust_tooltip(bool(remote_response["subscribed"])) # Update rating display votes = remote_response["votes"] self.channel_rating_label.setText(format_votes_rich_text(votes)) if DARWIN or WINDOWS: font = QFont() font.setLetterSpacing(QFont.PercentageSpacing, 60.0) self.channel_rating_label.setFont(font) self.channel_rating_label.setToolTip(get_votes_rating_description(votes)) def on_subscribe_button_click(self, checked): self.subscribe_button.setCheckedInstant( bool(self.contents_widget.model.channel_info["subscribed"]) ) channel_info = self.contents_widget.model.channel_info if channel_info["subscribed"]: # Show the global unsubscribe confirmation dialog self.window().on_channel_unsubscribe(channel_info) else: self.window().on_channel_subscribe(channel_info)
extractor
telecinco
# coding: utf-8 from __future__ import unicode_literals import json import re from ..utils import clean_html, int_or_none, str_or_none, try_get from .common import InfoExtractor class TelecincoIE(InfoExtractor): IE_DESC = "telecinco.es, cuatro.com and mediaset.es" _VALID_URL = r"https?://(?:www\.)?(?:telecinco\.es|cuatro\.com|mediaset\.es)/(?:[^/]+/)+(?P<id>.+?)\.html" _TESTS = [ { "url": "http://www.telecinco.es/robinfood/temporada-01/t01xp14/Bacalao-cocochas-pil-pil_0_1876350223.html", "info_dict": { "id": "1876350223", "title": "Bacalao con kokotxas al pil-pil", "description": "md5:716caf5601e25c3c5ab6605b1ae71529", }, "playlist": [ { "md5": "7ee56d665cfd241c0e6d80fd175068b0", "info_dict": { "id": "JEA5ijCnF6p5W08A1rNKn7", "ext": "mp4", "title": "Con Martín Berasategui, hacer un bacalao al pil-pil es fácil y divertido", "duration": 662, }, } ], }, { "url": "http://www.cuatro.com/deportes/futbol/barcelona/Leo_Messi-Champions-Roma_2_2052780128.html", "md5": "c86fe0d99e3bdb46b7950d38bf6ef12a", "info_dict": { "id": "jn24Od1zGLG4XUZcnUnZB6", "ext": "mp4", "title": "¿Quién es este ex futbolista con el que hablan Leo Messi y Luis Suárez?", "description": "md5:a62ecb5f1934fc787107d7b9a2262805", "duration": 79, }, }, { "url": "http://www.mediaset.es/12meses/campanas/doylacara/conlatratanohaytrato/Ayudame-dar-cara-trata-trato_2_1986630220.html", "md5": "eddb50291df704ce23c74821b995bcac", "info_dict": { "id": "aywerkD2Sv1vGNqq9b85Q2", "ext": "mp4", "title": "#DOYLACARA. Con la trata no hay trato", "description": "md5:2771356ff7bfad9179c5f5cd954f1477", "duration": 50, }, }, { # video in opening's content "url": "https://www.telecinco.es/vivalavida/fiorella-sobrina-edmundo-arrocet-entrevista_18_2907195140.html", "info_dict": { "id": "2907195140", "title": 'La surrealista entrevista a la sobrina de Edmundo Arrocet: "No puedes venir aquí y tomarnos por tontos"', "description": "md5:73f340a7320143d37ab895375b2bf13a", }, "playlist": [ { "md5": "adb28c37238b675dad0f042292f209a7", "info_dict": { "id": "TpI2EttSDAReWpJ1o0NVh2", "ext": "mp4", "title": 'La surrealista entrevista a la sobrina de Edmundo Arrocet: "No puedes venir aquí y tomarnos por tontos"', "duration": 1015, }, } ], "params": { "skip_download": True, }, }, { "url": "http://www.telecinco.es/informativos/nacional/Pablo_Iglesias-Informativos_Telecinco-entrevista-Pedro_Piqueras_2_1945155182.html", "only_matching": True, }, { "url": "http://www.telecinco.es/espanasinirmaslejos/Espana-gran-destino-turistico_2_1240605043.html", "only_matching": True, }, { # ooyala video "url": "http://www.cuatro.com/chesterinlove/a-carta/chester-chester_in_love-chester_edu_2_2331030022.html", "only_matching": True, }, ] def _parse_content(self, content, url): video_id = content["dataMediaId"] config = self._download_json( content["dataConfig"], video_id, "Downloading config JSON" ) title = config["info"]["title"] services = config["services"] caronte = self._download_json(services["caronte"], video_id) stream = caronte["dls"][0]["stream"] headers = self.geo_verification_headers() headers.update( { "Content-Type": "application/json;charset=UTF-8", "Origin": re.match(r"https?://[^/]+", url).group(0), } ) cdn = self._download_json( caronte["cerbero"], video_id, data=json.dumps( { "bbx": caronte["bbx"], "gbx": self._download_json(services["gbx"], video_id)["gbx"], } ).encode(), headers=headers, )["tokens"]["1"]["cdn"] formats = self._extract_m3u8_formats( stream + "?" + cdn, video_id, "mp4", "m3u8_native", m3u8_id="hls" ) self._sort_formats(formats) return { "id": video_id, "title": title, "formats": formats, "thumbnail": content.get("dataPoster") or config.get("poster", {}).get("imageUrl"), "duration": int_or_none(content.get("dataDuration")), } def _real_extract(self, url): display_id = self._match_id(url) webpage = self._download_webpage(url, display_id) article = self._parse_json( self._search_regex( r"window\.\$REACTBASE_STATE\.article(?:_multisite)?\s*=\s*({.+})", webpage, "article", ), display_id, )["article"] title = article.get("title") description = clean_html(article.get("leadParagraph")) or "" if article.get("editorialType") != "VID": entries = [] body = [article.get("opening")] body.extend(try_get(article, lambda x: x["body"], list) or []) for p in body: if not isinstance(p, dict): continue content = p.get("content") if not content: continue type_ = p.get("type") if type_ == "paragraph": content_str = str_or_none(content) if content_str: description += content_str continue if type_ == "video" and isinstance(content, dict): entries.append(self._parse_content(content, url)) return self.playlist_result( entries, str_or_none(article.get("id")), title, description ) content = article["opening"]["content"] info = self._parse_content(content, url) info.update( { "description": description, } ) return info
PyObjCTest
test_cvpixelformatdescription
from PyObjCTools.TestSupport import * from Quartz import * try: unicode except NameError: unicode = str try: long except NameError: long = int class TestCVPixelFormatDescription(TestCase): def testConstants(self): self.assertIsInstance(kCVPixelFormatName, unicode) self.assertIsInstance(kCVPixelFormatConstant, unicode) self.assertIsInstance(kCVPixelFormatCodecType, unicode) self.assertIsInstance(kCVPixelFormatFourCC, unicode) self.assertIsInstance(kCVPixelFormatPlanes, unicode) self.assertIsInstance(kCVPixelFormatBlockWidth, unicode) self.assertIsInstance(kCVPixelFormatBlockHeight, unicode) self.assertIsInstance(kCVPixelFormatBitsPerBlock, unicode) self.assertIsInstance(kCVPixelFormatBlockHorizontalAlignment, unicode) self.assertIsInstance(kCVPixelFormatBlockVerticalAlignment, unicode) self.assertIsInstance(kCVPixelFormatHorizontalSubsampling, unicode) self.assertIsInstance(kCVPixelFormatVerticalSubsampling, unicode) self.assertIsInstance(kCVPixelFormatOpenGLFormat, unicode) self.assertIsInstance(kCVPixelFormatOpenGLType, unicode) self.assertIsInstance(kCVPixelFormatOpenGLInternalFormat, unicode) self.assertIsInstance(kCVPixelFormatCGBitmapInfo, unicode) self.assertIsInstance(kCVPixelFormatQDCompatibility, unicode) self.assertIsInstance(kCVPixelFormatCGBitmapContextCompatibility, unicode) self.assertIsInstance(kCVPixelFormatCGImageCompatibility, unicode) self.assertIsInstance(kCVPixelFormatOpenGLCompatibility, unicode) self.assertIsInstance(kCVPixelFormatFillExtendedPixelsCallback, unicode) def testFunctions(self): self.assertResultIsCFRetained(CVPixelFormatDescriptionCreateWithPixelFormatType) v = CVPixelFormatDescriptionCreateWithPixelFormatType( None, kCVPixelFormatType_32ARGB ) self.assertIsInstance(v, CFDictionaryRef) self.assertResultIsCFRetained( CVPixelFormatDescriptionArrayCreateWithAllPixelFormatTypes ) v = CVPixelFormatDescriptionArrayCreateWithAllPixelFormatTypes(None) self.assertIsInstance(v, CFArrayRef) self.assertNotEqual(len(v), 0) self.assertIsInstance(v[0], (int, long)) tp = 42 while tp in v: tp += 1 CVPixelFormatDescriptionRegisterDescriptionWithPixelFormatType({}, tp) @min_os_level("10.6") def testConstants10_6(self): self.assertIsInstance(kCVPixelFormatBlackBlock, unicode) @min_os_level("10.7") def testConstants10_7(self): self.assertIsInstance(kCVPixelFormatContainsAlpha, unicode) if __name__ == "__main__": main()
widgets
trustpage
from typing import Dict from PyQt5.QtWidgets import QWidget from tribler.gui.defs import PB, TB from tribler.gui.dialogs.trustexplanationdialog import TrustExplanationDialog from tribler.gui.network.request_manager import request_manager from tribler.gui.sentry_mixin import AddBreadcrumbOnShowMixin from tribler.gui.utilities import connect from tribler.gui.widgets.graphs.dataplot import TimeSeriesDataPlot class TrustSeriesPlot(TimeSeriesDataPlot): def __init__(self, parent, **kargs): series = [ { "name": "Token balance", "pen": (224, 94, 0), "symbolBrush": (224, 94, 0), "symbolPen": "w", }, ] super().__init__(parent, "Token balance over time", series, **kargs) self.setLabel("left", "Data", units="B") self.setLimits(yMin=-TB, yMax=PB) class TrustPage(AddBreadcrumbOnShowMixin, QWidget): """ This page shows various trust statistics. """ def __init__(self): QWidget.__init__(self) self.trust_plot = None self.history = None self.byte_scale = 1024 * 1024 self.dialog = None def initialize_trust_page(self): vlayout = self.window().plot_widget.layout() if vlayout.isEmpty(): self.trust_plot = TrustSeriesPlot(self.window().plot_widget) vlayout.addWidget(self.trust_plot) connect(self.window().trust_explain_button.clicked, self.on_info_button_clicked) def on_info_button_clicked(self, checked): self.dialog = TrustExplanationDialog(self.window()) self.dialog.show() def received_bandwidth_statistics(self, statistics: Dict) -> None: """ We received bandwidth statistics from the Tribler core. Update the labels on the trust page with the received information. :param statistics: The received statistics, in JSON format. """ if not statistics or "statistics" not in statistics: return statistics = statistics["statistics"] total_up = statistics.get("total_given", 0) total_down = statistics.get("total_taken", 0) self.window().trust_contribution_amount_label.setText( f"{total_up // self.byte_scale} MBytes" ) self.window().trust_consumption_amount_label.setText( f"{total_down // self.byte_scale} MBytes" ) self.window().trust_people_helped_label.setText( "%d" % statistics["num_peers_helped"] ) self.window().trust_people_helped_you_label.setText( "%d" % statistics["num_peers_helped_by"] ) def load_history(self) -> None: """ Load the bandwidth balance history by initiating a request to the Tribler core. """ request_manager.get("bandwidth/history", self.received_history) def received_history(self, history: Dict): """ We received the bandwidth history from the Tribler core. Plot it in the trust chart. :param history: The received bandwidth history, in JSON format. """ if history: self.history = history["history"] self.plot_absolute_values() def plot_absolute_values(self) -> None: """ Plot the evolution of the token balance. """ if self.history: min_balance = min(item["balance"] for item in self.history) max_balance = max(item["balance"] for item in self.history) half = (max_balance - min_balance) / 2 min_limit = min(-TB, min_balance - half) max_limit = max(PB, max_balance + half) self.trust_plot.setLimits(yMin=min_limit, yMax=max_limit) self.trust_plot.setYRange(min_balance, max_balance) # Convert all dates to a datetime object for history_item in self.history: timestamp = history_item["timestamp"] // 1000 self.trust_plot.add_data(timestamp, [history_item["balance"]]) self.trust_plot.render_plot()
scripts
line_length_checker
import re import sys def getValue(line: str, key: str, default=None): """Convenience function that finds the value in a line of g-code. When requesting key = x from line "G1 X100" the value 100 is returned. """ if not key in line or (";" in line and line.find(key) > line.find(";")): return default sub_part = line[line.find(key) + 1 :] m = re.search("^-?[0-9]+\.?[0-9]*", sub_part) if m is None: return default try: return int(m.group(0)) except ValueError: # Not an integer. try: return float(m.group(0)) except ValueError: # Not a number at all. return default def analyse(gcode, distance_to_report, print_layers=False): lines_found = 0 previous_x = 0 previous_y = 0 dist_squared = distance_to_report * distance_to_report current_layer = 0 for line in gcode.split("\n"): if not line.startswith("G1"): if line.startswith(";LAYER:"): previous_x = 0 previous_y = 0 current_layer += 1 continue current_x = getValue(line, "X") current_y = getValue(line, "Y") if current_x is None or current_y is None: continue diff_x = current_x - previous_x diff_y = current_y - previous_y if diff_x * diff_x + diff_y * diff_y < dist_squared: lines_found += 1 if print_layers: print( "[!] ", distance_to_report, " layer ", current_layer, " ", previous_x, previous_y, ) previous_y = current_y previous_x = current_x return lines_found def loadAndPrettyPrint(file_name): print(file_name.replace(".gcode", "")) with open(file_name) as f: data = f.read() print("| Line length | Num segments |") print("| ------------- | ------------- |") print("| 1 |", analyse(data, 1), "|") print("| 0.5 |", analyse(data, 0.5), "|") print("| 0.1 |", analyse(data, 0.1), "|") print("| 0.05 |", analyse(data, 0.05), "|") print("| 0.01 |", analyse(data, 0.01), "|") print("| 0.005 |", analyse(data, 0.005), "|") print("| 0.001 |", analyse(data, 0.001), "|") if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: <input g-code>") sys.exit(1) in_filename = sys.argv[1] loadAndPrettyPrint(sys.argv[1])
scripts
fablin_post
# *************************************************************************** # * Copyright (c) 2017 imarin * # * * # * Heavily based on gbrl post-procesor by: * # * Copyright (c) 2014 sliptonic <shopinthewoods@gmail.com> * # * * # * This file is part of the FreeCAD CAx development system. * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * FreeCAD is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Lesser General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with FreeCAD; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** import datetime import Path.Post.Utils as PostUtils import PathScripts.PathUtils as PathUtils now = datetime.datetime.now() """ Generate g-code compatible with fablin from a Path. import fablin_post fablin_post.export(object,"/path/to/file.ncc") """ TOOLTIP_ARGS = """ Arguments for fablin: --rapids-feedrate ... feedrate to be used for rapids (e.g. --rapids-feedrate=300) --header,--no-header ... output headers (--header) --comments,--no-comments ... output comments (--comments) --line-numbers,--no-line-numbers ... prefix with line numbers (--no-lin-numbers) --show-editor, --no-show-editor ... pop up editor before writing output(--show-editor) """ # These globals set common customization preferences OUTPUT_COMMENTS = False # Fablin does not support parenthesis, it will echo the command complaining. As a side effect the spinner may turn at a very reduced speed (do not ask me why). OUTPUT_HEADER = False # Same as above. You can enable this by passing arguments to the post-processor in case you need them for example for debugging the gcode. OUTPUT_LINE_NUMBERS = False OUTPUT_TOOL_CHANGE = False SHOW_EDITOR = True MODAL = False # if true commands are suppressed if the same as previous line. COMMAND_SPACE = " " LINENR = 100 # line number starting value # These globals will be reflected in the Machine configuration of the project UNITS = "" # only metric, G20/G21 is ignored MACHINE_NAME = "FABLIN" CORNER_MIN = {"x": 0, "y": 0, "z": 0} CORNER_MAX = {"x": 500, "y": 300, "z": 300} RAPID_MOVES = ["G0", "G00"] RAPID_FEEDRATE = 10000 # Preamble text will appear at the beginning of the GCODE output file. PREAMBLE = """G90 """ # Postamble text will appear following the last operation. POSTAMBLE = """M5 G00 X-1.0 Y1.0 G90 """ # These commands are ignored by commenting them out SUPPRESS_COMMANDS = ["G98", "G80", "M6", "G17"] # Pre operation text will be inserted before every operation PRE_OPERATION = """""" # Post operation text will be inserted after every operation POST_OPERATION = """""" # Tool Change commands will be inserted before a tool change TOOL_CHANGE = """""" # to distinguish python built-in open function from the one declared below if open.__module__ in ["__builtin__", "io"]: pythonopen = open def processArguments(argstring): global OUTPUT_HEADER global OUTPUT_COMMENTS global OUTPUT_LINE_NUMBERS global SHOW_EDITOR global RAPID_FEEDRATE for arg in argstring.split(): if arg == "--header": OUTPUT_HEADER = True elif arg == "--no-header": OUTPUT_HEADER = False elif arg == "--comments": OUTPUT_COMMENTS = True elif arg == "--no-comments": OUTPUT_COMMENTS = False elif arg == "--line-numbers": OUTPUT_LINE_NUMBERS = True elif arg == "--no-line-numbers": OUTPUT_LINE_NUMBERS = False elif arg == "--show-editor": SHOW_EDITOR = True elif arg == "--no-show-editor": SHOW_EDITOR = False params = arg.split("=") if params[0] == "--rapids-feedrate": RAPID_FEEDRATE = params[1] def export(objectslist, filename, argstring): processArguments(argstring) global UNITS for obj in objectslist: if not hasattr(obj, "Path"): print( "the object " + obj.Name + " is not a path. Please select only path and Compounds." ) return print("postprocessing...") gcode = "" # Find the machine. # The user my have overridden post processor defaults in the GUI. # Make sure we're using the current values in the Machine Def. myMachine = None for pathobj in objectslist: if hasattr(pathobj, "Group"): # We have a compound or project. for p in pathobj.Group: if p.Name == "Machine": myMachine = p if myMachine is None: print("No machine found in this project") else: if myMachine.MachineUnits == "Metric": UNITS = "G21" else: UNITS = "G20" # write header if OUTPUT_HEADER: gcode += linenumber() + "(Exported by FreeCAD)\n" gcode += linenumber() + "(Post Processor: " + __name__ + ")\n" gcode += linenumber() + "(Output Time:" + str(now) + ")\n" # Write the preamble if OUTPUT_COMMENTS: gcode += linenumber() + "(begin preamble)\n" for line in PREAMBLE.splitlines(True): gcode += linenumber() + line for obj in objectslist: # do the pre_op if OUTPUT_COMMENTS: gcode += linenumber() + "(begin operation: " + obj.Label + ")\n" for line in PRE_OPERATION.splitlines(True): gcode += linenumber() + line gcode += parse(obj) # do the post_op if OUTPUT_COMMENTS: gcode += linenumber() + "(finish operation: " + obj.Label + ")\n" for line in POST_OPERATION.splitlines(True): gcode += linenumber() + line # do the post_amble if OUTPUT_COMMENTS: gcode += "(begin postamble)\n" for line in POSTAMBLE.splitlines(True): gcode += linenumber() + line if SHOW_EDITOR: dia = PostUtils.GCodeEditorDialog() dia.editor.setText(gcode) result = dia.exec_() if result: final = dia.editor.toPlainText() else: final = gcode else: final = gcode print("done postprocessing.") gfile = pythonopen(filename, "w") gfile.write(final) gfile.close() def linenumber(): global LINENR if OUTPUT_LINE_NUMBERS is True: LINENR += 10 return "N" + str(LINENR) + " " return "" def parse(pathobj): out = "" lastcommand = None params = [ "X", "Y", "Z", "A", "B", "I", "J", "F", "S", "T", "Q", "R", "L", ] # linuxcnc doesn't want K properties on XY plane Arcs need work. if hasattr(pathobj, "Group"): # We have a compound or project. if OUTPUT_COMMENTS: out += linenumber() + "(compound: " + pathobj.Label + ")\n" for p in pathobj.Group: out += parse(p) return out else: # parsing simple path if not hasattr( pathobj, "Path" ): # groups might contain non-path things like stock. return out if OUTPUT_COMMENTS: out += linenumber() + "(Path: " + pathobj.Label + ")\n" for c in PathUtils.getPathWithPlacement(pathobj).Commands: outstring = [] command = c.Name # fablin does not support parenthesis syntax, so removing that (pocket) in the agnostic gcode if command[0] == "(": if not OUTPUT_COMMENTS: pass else: outstring.append(command) # if modal: only print the command if it is not the same as the last one if MODAL is True: if command == lastcommand: outstring.pop(0) # Now add the remaining parameters in order for param in params: if param in c.Parameters: if param == "F": if command not in RAPID_MOVES: outstring.append(param + format(c.Parameters["F"], ".2f")) elif param == "T": outstring.append(param + str(c.Parameters["T"])) else: outstring.append(param + format(c.Parameters[param], ".4f")) if command in RAPID_MOVES and command != lastcommand: outstring.append("F" + format(RAPID_FEEDRATE)) # store the latest command lastcommand = command # Check for Tool Change: if command == "M6": if OUTPUT_COMMENTS: out += linenumber() + "(begin toolchange)\n" if not OUTPUT_TOOL_CHANGE: outstring.insert(0, ";") else: for line in TOOL_CHANGE.splitlines(True): out += linenumber() + line if command == "message": if OUTPUT_COMMENTS is False: out = [] else: outstring.pop(0) # remove the command if command in SUPPRESS_COMMANDS: outstring = [] # prepend a line number and append a newline if len(outstring) >= 1: if OUTPUT_LINE_NUMBERS: outstring.insert(0, (linenumber())) # append the line to the final output for w in outstring: out += w + COMMAND_SPACE out = out.strip() + "\n" return out # print(__name__ + " gcode postprocessor loaded.")
core
post_processing_test
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow_models.object_detection.core.post_processing.""" import numpy as np import tensorflow as tf from app.object_detection.core import post_processing from app.object_detection.core import standard_fields as fields class MulticlassNonMaxSuppressionTest(tf.test.TestCase): def test_with_invalid_scores_size(self): boxes = tf.constant( [ [[0, 0, 1, 1]], [[0, 0.1, 1, 1.1]], [[0, -0.1, 1, 0.9]], [[0, 10, 1, 11]], [[0, 10.1, 1, 11.1]], [[0, 100, 1, 101]], ], tf.float32, ) scores = tf.constant([[0.9], [0.75], [0.6], [0.95], [0.5]]) iou_thresh = 0.5 score_thresh = 0.6 max_output_size = 3 nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_output_size ) with self.test_session() as sess: with self.assertRaisesWithPredicateMatch( tf.errors.InvalidArgumentError, "Incorrect scores field length" ): sess.run(nms.get()) def test_multiclass_nms_select_with_shared_boxes(self): boxes = tf.constant( [ [[0, 0, 1, 1]], [[0, 0.1, 1, 1.1]], [[0, -0.1, 1, 0.9]], [[0, 10, 1, 11]], [[0, 10.1, 1, 11.1]], [[0, 100, 1, 101]], [[0, 1000, 1, 1002]], [[0, 1000, 1, 1002.1]], ], tf.float32, ) scores = tf.constant( [ [0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0], [0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5], ] ) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = [ [0, 10, 1, 11], [0, 0, 1, 1], [0, 1000, 1, 1002], [0, 100, 1, 101], ] exp_nms_scores = [0.95, 0.9, 0.85, 0.3] exp_nms_classes = [0, 0, 1, 0] nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_output_size ) with self.test_session() as sess: nms_corners_output, nms_scores_output, nms_classes_output = sess.run( [ nms.get(), nms.get_field(fields.BoxListFields.scores), nms.get_field(fields.BoxListFields.classes), ] ) self.assertAllClose(nms_corners_output, exp_nms_corners) self.assertAllClose(nms_scores_output, exp_nms_scores) self.assertAllClose(nms_classes_output, exp_nms_classes) def test_multiclass_nms_select_with_shared_boxes_given_keypoints(self): boxes = tf.constant( [ [[0, 0, 1, 1]], [[0, 0.1, 1, 1.1]], [[0, -0.1, 1, 0.9]], [[0, 10, 1, 11]], [[0, 10.1, 1, 11.1]], [[0, 100, 1, 101]], [[0, 1000, 1, 1002]], [[0, 1000, 1, 1002.1]], ], tf.float32, ) scores = tf.constant( [ [0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0], [0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5], ] ) num_keypoints = 6 keypoints = tf.tile(tf.reshape(tf.range(8), [8, 1, 1]), [1, num_keypoints, 2]) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = [ [0, 10, 1, 11], [0, 0, 1, 1], [0, 1000, 1, 1002], [0, 100, 1, 101], ] exp_nms_scores = [0.95, 0.9, 0.85, 0.3] exp_nms_classes = [0, 0, 1, 0] exp_nms_keypoints_tensor = tf.tile( tf.reshape(tf.constant([3, 0, 6, 5], dtype=tf.float32), [4, 1, 1]), [1, num_keypoints, 2], ) nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_output_size, additional_fields={fields.BoxListFields.keypoints: keypoints}, ) with self.test_session() as sess: ( nms_corners_output, nms_scores_output, nms_classes_output, nms_keypoints, exp_nms_keypoints, ) = sess.run( [ nms.get(), nms.get_field(fields.BoxListFields.scores), nms.get_field(fields.BoxListFields.classes), nms.get_field(fields.BoxListFields.keypoints), exp_nms_keypoints_tensor, ] ) self.assertAllClose(nms_corners_output, exp_nms_corners) self.assertAllClose(nms_scores_output, exp_nms_scores) self.assertAllClose(nms_classes_output, exp_nms_classes) self.assertAllEqual(nms_keypoints, exp_nms_keypoints) def test_multiclass_nms_with_shared_boxes_given_keypoint_heatmaps(self): boxes = tf.constant( [ [[0, 0, 1, 1]], [[0, 0.1, 1, 1.1]], [[0, -0.1, 1, 0.9]], [[0, 10, 1, 11]], [[0, 10.1, 1, 11.1]], [[0, 100, 1, 101]], [[0, 1000, 1, 1002]], [[0, 1000, 1, 1002.1]], ], tf.float32, ) scores = tf.constant( [ [0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0], [0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5], ] ) num_boxes = tf.shape(boxes)[0] heatmap_height = 5 heatmap_width = 5 num_keypoints = 17 keypoint_heatmaps = tf.ones( [num_boxes, heatmap_height, heatmap_width, num_keypoints], dtype=tf.float32 ) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = [ [0, 10, 1, 11], [0, 0, 1, 1], [0, 1000, 1, 1002], [0, 100, 1, 101], ] exp_nms_scores = [0.95, 0.9, 0.85, 0.3] exp_nms_classes = [0, 0, 1, 0] exp_nms_keypoint_heatmaps = np.ones( (4, heatmap_height, heatmap_width, num_keypoints), dtype=np.float32 ) nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_output_size, additional_fields={ fields.BoxListFields.keypoint_heatmaps: keypoint_heatmaps }, ) with self.test_session() as sess: ( nms_corners_output, nms_scores_output, nms_classes_output, nms_keypoint_heatmaps, ) = sess.run( [ nms.get(), nms.get_field(fields.BoxListFields.scores), nms.get_field(fields.BoxListFields.classes), nms.get_field(fields.BoxListFields.keypoint_heatmaps), ] ) self.assertAllClose(nms_corners_output, exp_nms_corners) self.assertAllClose(nms_scores_output, exp_nms_scores) self.assertAllClose(nms_classes_output, exp_nms_classes) self.assertAllEqual(nms_keypoint_heatmaps, exp_nms_keypoint_heatmaps) def test_multiclass_nms_with_additional_fields(self): boxes = tf.constant( [ [[0, 0, 1, 1]], [[0, 0.1, 1, 1.1]], [[0, -0.1, 1, 0.9]], [[0, 10, 1, 11]], [[0, 10.1, 1, 11.1]], [[0, 100, 1, 101]], [[0, 1000, 1, 1002]], [[0, 1000, 1, 1002.1]], ], tf.float32, ) scores = tf.constant( [ [0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0], [0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5], ] ) coarse_boxes_key = "coarse_boxes" coarse_boxes = tf.constant( [ [0.1, 0.1, 1.1, 1.1], [0.1, 0.2, 1.1, 1.2], [0.1, -0.2, 1.1, 1.0], [0.1, 10.1, 1.1, 11.1], [0.1, 10.2, 1.1, 11.2], [0.1, 100.1, 1.1, 101.1], [0.1, 1000.1, 1.1, 1002.1], [0.1, 1000.1, 1.1, 1002.2], ], tf.float32, ) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = np.array( [[0, 10, 1, 11], [0, 0, 1, 1], [0, 1000, 1, 1002], [0, 100, 1, 101]], dtype=np.float32, ) exp_nms_coarse_corners = np.array( [ [0.1, 10.1, 1.1, 11.1], [0.1, 0.1, 1.1, 1.1], [0.1, 1000.1, 1.1, 1002.1], [0.1, 100.1, 1.1, 101.1], ], dtype=np.float32, ) exp_nms_scores = [0.95, 0.9, 0.85, 0.3] exp_nms_classes = [0, 0, 1, 0] nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_output_size, additional_fields={coarse_boxes_key: coarse_boxes}, ) with self.test_session() as sess: ( nms_corners_output, nms_scores_output, nms_classes_output, nms_coarse_corners, ) = sess.run( [ nms.get(), nms.get_field(fields.BoxListFields.scores), nms.get_field(fields.BoxListFields.classes), nms.get_field(coarse_boxes_key), ] ) self.assertAllClose(nms_corners_output, exp_nms_corners) self.assertAllClose(nms_scores_output, exp_nms_scores) self.assertAllClose(nms_classes_output, exp_nms_classes) self.assertAllEqual(nms_coarse_corners, exp_nms_coarse_corners) def test_multiclass_nms_select_with_shared_boxes_given_masks(self): boxes = tf.constant( [ [[0, 0, 1, 1]], [[0, 0.1, 1, 1.1]], [[0, -0.1, 1, 0.9]], [[0, 10, 1, 11]], [[0, 10.1, 1, 11.1]], [[0, 100, 1, 101]], [[0, 1000, 1, 1002]], [[0, 1000, 1, 1002.1]], ], tf.float32, ) scores = tf.constant( [ [0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0], [0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5], ] ) num_classes = 2 mask_height = 3 mask_width = 3 masks = tf.tile( tf.reshape(tf.range(8), [8, 1, 1, 1]), [1, num_classes, mask_height, mask_width], ) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = [ [0, 10, 1, 11], [0, 0, 1, 1], [0, 1000, 1, 1002], [0, 100, 1, 101], ] exp_nms_scores = [0.95, 0.9, 0.85, 0.3] exp_nms_classes = [0, 0, 1, 0] exp_nms_masks_tensor = tf.tile( tf.reshape(tf.constant([3, 0, 6, 5], dtype=tf.float32), [4, 1, 1]), [1, mask_height, mask_width], ) nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_output_size, masks=masks ) with self.test_session() as sess: ( nms_corners_output, nms_scores_output, nms_classes_output, nms_masks, exp_nms_masks, ) = sess.run( [ nms.get(), nms.get_field(fields.BoxListFields.scores), nms.get_field(fields.BoxListFields.classes), nms.get_field(fields.BoxListFields.masks), exp_nms_masks_tensor, ] ) self.assertAllClose(nms_corners_output, exp_nms_corners) self.assertAllClose(nms_scores_output, exp_nms_scores) self.assertAllClose(nms_classes_output, exp_nms_classes) self.assertAllEqual(nms_masks, exp_nms_masks) def test_multiclass_nms_select_with_clip_window(self): boxes = tf.constant([[[0, 0, 10, 10]], [[1, 1, 11, 11]]], tf.float32) scores = tf.constant([[0.9], [0.75]]) clip_window = tf.constant([5, 4, 8, 7], tf.float32) score_thresh = 0.0 iou_thresh = 0.5 max_output_size = 100 exp_nms_corners = [[5, 4, 8, 7]] exp_nms_scores = [0.9] exp_nms_classes = [0] nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_output_size, clip_window=clip_window, ) with self.test_session() as sess: nms_corners_output, nms_scores_output, nms_classes_output = sess.run( [ nms.get(), nms.get_field(fields.BoxListFields.scores), nms.get_field(fields.BoxListFields.classes), ] ) self.assertAllClose(nms_corners_output, exp_nms_corners) self.assertAllClose(nms_scores_output, exp_nms_scores) self.assertAllClose(nms_classes_output, exp_nms_classes) def test_multiclass_nms_select_with_clip_window_change_coordinate_frame(self): boxes = tf.constant([[[0, 0, 10, 10]], [[1, 1, 11, 11]]], tf.float32) scores = tf.constant([[0.9], [0.75]]) clip_window = tf.constant([5, 4, 8, 7], tf.float32) score_thresh = 0.0 iou_thresh = 0.5 max_output_size = 100 exp_nms_corners = [[0, 0, 1, 1]] exp_nms_scores = [0.9] exp_nms_classes = [0] nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_output_size, clip_window=clip_window, change_coordinate_frame=True, ) with self.test_session() as sess: nms_corners_output, nms_scores_output, nms_classes_output = sess.run( [ nms.get(), nms.get_field(fields.BoxListFields.scores), nms.get_field(fields.BoxListFields.classes), ] ) self.assertAllClose(nms_corners_output, exp_nms_corners) self.assertAllClose(nms_scores_output, exp_nms_scores) self.assertAllClose(nms_classes_output, exp_nms_classes) def test_multiclass_nms_select_with_per_class_cap(self): boxes = tf.constant( [ [[0, 0, 1, 1]], [[0, 0.1, 1, 1.1]], [[0, -0.1, 1, 0.9]], [[0, 10, 1, 11]], [[0, 10.1, 1, 11.1]], [[0, 100, 1, 101]], [[0, 1000, 1, 1002]], [[0, 1000, 1, 1002.1]], ], tf.float32, ) scores = tf.constant( [ [0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0], [0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5], ] ) score_thresh = 0.1 iou_thresh = 0.5 max_size_per_class = 2 exp_nms_corners = [[0, 10, 1, 11], [0, 0, 1, 1], [0, 1000, 1, 1002]] exp_nms_scores = [0.95, 0.9, 0.85] exp_nms_classes = [0, 0, 1] nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_size_per_class ) with self.test_session() as sess: nms_corners_output, nms_scores_output, nms_classes_output = sess.run( [ nms.get(), nms.get_field(fields.BoxListFields.scores), nms.get_field(fields.BoxListFields.classes), ] ) self.assertAllClose(nms_corners_output, exp_nms_corners) self.assertAllClose(nms_scores_output, exp_nms_scores) self.assertAllClose(nms_classes_output, exp_nms_classes) def test_multiclass_nms_select_with_total_cap(self): boxes = tf.constant( [ [[0, 0, 1, 1]], [[0, 0.1, 1, 1.1]], [[0, -0.1, 1, 0.9]], [[0, 10, 1, 11]], [[0, 10.1, 1, 11.1]], [[0, 100, 1, 101]], [[0, 1000, 1, 1002]], [[0, 1000, 1, 1002.1]], ], tf.float32, ) scores = tf.constant( [ [0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0], [0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5], ] ) score_thresh = 0.1 iou_thresh = 0.5 max_size_per_class = 4 max_total_size = 2 exp_nms_corners = [[0, 10, 1, 11], [0, 0, 1, 1]] exp_nms_scores = [0.95, 0.9] exp_nms_classes = [0, 0] nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_size_per_class, max_total_size ) with self.test_session() as sess: nms_corners_output, nms_scores_output, nms_classes_output = sess.run( [ nms.get(), nms.get_field(fields.BoxListFields.scores), nms.get_field(fields.BoxListFields.classes), ] ) self.assertAllClose(nms_corners_output, exp_nms_corners) self.assertAllClose(nms_scores_output, exp_nms_scores) self.assertAllClose(nms_classes_output, exp_nms_classes) def test_multiclass_nms_threshold_then_select_with_shared_boxes(self): boxes = tf.constant( [ [[0, 0, 1, 1]], [[0, 0.1, 1, 1.1]], [[0, -0.1, 1, 0.9]], [[0, 10, 1, 11]], [[0, 10.1, 1, 11.1]], [[0, 100, 1, 101]], [[0, 1000, 1, 1002]], [[0, 1000, 1, 1002.1]], ], tf.float32, ) scores = tf.constant( [[0.9], [0.75], [0.6], [0.95], [0.5], [0.3], [0.01], [0.01]] ) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 3 exp_nms = [[0, 10, 1, 11], [0, 0, 1, 1], [0, 100, 1, 101]] nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_output_size ) with self.test_session() as sess: nms_output = sess.run(nms.get()) self.assertAllClose(nms_output, exp_nms) def test_multiclass_nms_select_with_separate_boxes(self): boxes = tf.constant( [ [[0, 0, 1, 1], [0, 0, 4, 5]], [[0, 0.1, 1, 1.1], [0, 0.1, 2, 1.1]], [[0, -0.1, 1, 0.9], [0, -0.1, 1, 0.9]], [[0, 10, 1, 11], [0, 10, 1, 11]], [[0, 10.1, 1, 11.1], [0, 10.1, 1, 11.1]], [[0, 100, 1, 101], [0, 100, 1, 101]], [[0, 1000, 1, 1002], [0, 999, 2, 1004]], [[0, 1000, 1, 1002.1], [0, 999, 2, 1002.7]], ], tf.float32, ) scores = tf.constant( [ [0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0], [0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5], ] ) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = [ [0, 10, 1, 11], [0, 0, 1, 1], [0, 999, 2, 1004], [0, 100, 1, 101], ] exp_nms_scores = [0.95, 0.9, 0.85, 0.3] exp_nms_classes = [0, 0, 1, 0] nms = post_processing.multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_output_size ) with self.test_session() as sess: nms_corners_output, nms_scores_output, nms_classes_output = sess.run( [ nms.get(), nms.get_field(fields.BoxListFields.scores), nms.get_field(fields.BoxListFields.classes), ] ) self.assertAllClose(nms_corners_output, exp_nms_corners) self.assertAllClose(nms_scores_output, exp_nms_scores) self.assertAllClose(nms_classes_output, exp_nms_classes) def test_batch_multiclass_nms_with_batch_size_1(self): boxes = tf.constant( [ [ [[0, 0, 1, 1], [0, 0, 4, 5]], [[0, 0.1, 1, 1.1], [0, 0.1, 2, 1.1]], [[0, -0.1, 1, 0.9], [0, -0.1, 1, 0.9]], [[0, 10, 1, 11], [0, 10, 1, 11]], [[0, 10.1, 1, 11.1], [0, 10.1, 1, 11.1]], [[0, 100, 1, 101], [0, 100, 1, 101]], [[0, 1000, 1, 1002], [0, 999, 2, 1004]], [[0, 1000, 1, 1002.1], [0, 999, 2, 1002.7]], ] ], tf.float32, ) scores = tf.constant( [ [ [0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0], [0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5], ] ] ) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = [ [[0, 10, 1, 11], [0, 0, 1, 1], [0, 999, 2, 1004], [0, 100, 1, 101]] ] exp_nms_scores = [[0.95, 0.9, 0.85, 0.3]] exp_nms_classes = [[0, 0, 1, 0]] ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, nmsed_additional_fields, num_detections, ) = post_processing.batch_multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_size_per_class=max_output_size, max_total_size=max_output_size, ) self.assertIsNone(nmsed_masks) self.assertIsNone(nmsed_additional_fields) with self.test_session() as sess: (nmsed_boxes, nmsed_scores, nmsed_classes, num_detections) = sess.run( [nmsed_boxes, nmsed_scores, nmsed_classes, num_detections] ) self.assertAllClose(nmsed_boxes, exp_nms_corners) self.assertAllClose(nmsed_scores, exp_nms_scores) self.assertAllClose(nmsed_classes, exp_nms_classes) self.assertEqual(num_detections, [4]) def test_batch_multiclass_nms_with_batch_size_2(self): boxes = tf.constant( [ [ [[0, 0, 1, 1], [0, 0, 4, 5]], [[0, 0.1, 1, 1.1], [0, 0.1, 2, 1.1]], [[0, -0.1, 1, 0.9], [0, -0.1, 1, 0.9]], [[0, 10, 1, 11], [0, 10, 1, 11]], ], [ [[0, 10.1, 1, 11.1], [0, 10.1, 1, 11.1]], [[0, 100, 1, 101], [0, 100, 1, 101]], [[0, 1000, 1, 1002], [0, 999, 2, 1004]], [[0, 1000, 1, 1002.1], [0, 999, 2, 1002.7]], ], ], tf.float32, ) scores = tf.constant( [ [[0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0]], [[0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5]], ] ) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = np.array( [ [[0, 10, 1, 11], [0, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 999, 2, 1004], [0, 10.1, 1, 11.1], [0, 100, 1, 101], [0, 0, 0, 0]], ] ) exp_nms_scores = np.array([[0.95, 0.9, 0, 0], [0.85, 0.5, 0.3, 0]]) exp_nms_classes = np.array([[0, 0, 0, 0], [1, 0, 0, 0]]) ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, nmsed_additional_fields, num_detections, ) = post_processing.batch_multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_size_per_class=max_output_size, max_total_size=max_output_size, ) self.assertIsNone(nmsed_masks) self.assertIsNone(nmsed_additional_fields) # Check static shapes self.assertAllEqual(nmsed_boxes.shape.as_list(), exp_nms_corners.shape) self.assertAllEqual(nmsed_scores.shape.as_list(), exp_nms_scores.shape) self.assertAllEqual(nmsed_classes.shape.as_list(), exp_nms_classes.shape) self.assertEqual(num_detections.shape.as_list(), [2]) with self.test_session() as sess: (nmsed_boxes, nmsed_scores, nmsed_classes, num_detections) = sess.run( [nmsed_boxes, nmsed_scores, nmsed_classes, num_detections] ) self.assertAllClose(nmsed_boxes, exp_nms_corners) self.assertAllClose(nmsed_scores, exp_nms_scores) self.assertAllClose(nmsed_classes, exp_nms_classes) self.assertAllClose(num_detections, [2, 3]) def test_batch_multiclass_nms_with_masks(self): boxes = tf.constant( [ [ [[0, 0, 1, 1], [0, 0, 4, 5]], [[0, 0.1, 1, 1.1], [0, 0.1, 2, 1.1]], [[0, -0.1, 1, 0.9], [0, -0.1, 1, 0.9]], [[0, 10, 1, 11], [0, 10, 1, 11]], ], [ [[0, 10.1, 1, 11.1], [0, 10.1, 1, 11.1]], [[0, 100, 1, 101], [0, 100, 1, 101]], [[0, 1000, 1, 1002], [0, 999, 2, 1004]], [[0, 1000, 1, 1002.1], [0, 999, 2, 1002.7]], ], ], tf.float32, ) scores = tf.constant( [ [[0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0]], [[0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5]], ] ) masks = tf.constant( [ [ [[[0, 1], [2, 3]], [[1, 2], [3, 4]]], [[[2, 3], [4, 5]], [[3, 4], [5, 6]]], [[[4, 5], [6, 7]], [[5, 6], [7, 8]]], [[[6, 7], [8, 9]], [[7, 8], [9, 10]]], ], [ [[[8, 9], [10, 11]], [[9, 10], [11, 12]]], [[[10, 11], [12, 13]], [[11, 12], [13, 14]]], [[[12, 13], [14, 15]], [[13, 14], [15, 16]]], [[[14, 15], [16, 17]], [[15, 16], [17, 18]]], ], ], tf.float32, ) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = np.array( [ [[0, 10, 1, 11], [0, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 999, 2, 1004], [0, 10.1, 1, 11.1], [0, 100, 1, 101], [0, 0, 0, 0]], ] ) exp_nms_scores = np.array([[0.95, 0.9, 0, 0], [0.85, 0.5, 0.3, 0]]) exp_nms_classes = np.array([[0, 0, 0, 0], [1, 0, 0, 0]]) exp_nms_masks = np.array( [ [ [[6, 7], [8, 9]], [[0, 1], [2, 3]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], ], [ [[13, 14], [15, 16]], [[8, 9], [10, 11]], [[10, 11], [12, 13]], [[0, 0], [0, 0]], ], ] ) ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, nmsed_additional_fields, num_detections, ) = post_processing.batch_multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_size_per_class=max_output_size, max_total_size=max_output_size, masks=masks, ) self.assertIsNone(nmsed_additional_fields) # Check static shapes self.assertAllEqual(nmsed_boxes.shape.as_list(), exp_nms_corners.shape) self.assertAllEqual(nmsed_scores.shape.as_list(), exp_nms_scores.shape) self.assertAllEqual(nmsed_classes.shape.as_list(), exp_nms_classes.shape) self.assertAllEqual(nmsed_masks.shape.as_list(), exp_nms_masks.shape) self.assertEqual(num_detections.shape.as_list(), [2]) with self.test_session() as sess: ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, num_detections, ) = sess.run( [nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, num_detections] ) self.assertAllClose(nmsed_boxes, exp_nms_corners) self.assertAllClose(nmsed_scores, exp_nms_scores) self.assertAllClose(nmsed_classes, exp_nms_classes) self.assertAllClose(num_detections, [2, 3]) self.assertAllClose(nmsed_masks, exp_nms_masks) def test_batch_multiclass_nms_with_additional_fields(self): boxes = tf.constant( [ [ [[0, 0, 1, 1], [0, 0, 4, 5]], [[0, 0.1, 1, 1.1], [0, 0.1, 2, 1.1]], [[0, -0.1, 1, 0.9], [0, -0.1, 1, 0.9]], [[0, 10, 1, 11], [0, 10, 1, 11]], ], [ [[0, 10.1, 1, 11.1], [0, 10.1, 1, 11.1]], [[0, 100, 1, 101], [0, 100, 1, 101]], [[0, 1000, 1, 1002], [0, 999, 2, 1004]], [[0, 1000, 1, 1002.1], [0, 999, 2, 1002.7]], ], ], tf.float32, ) scores = tf.constant( [ [[0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0]], [[0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5]], ] ) additional_fields = { "keypoints": tf.constant( [ [ [[6, 7], [8, 9]], [[0, 1], [2, 3]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], ], [ [[13, 14], [15, 16]], [[8, 9], [10, 11]], [[10, 11], [12, 13]], [[0, 0], [0, 0]], ], ], tf.float32, ) } score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = np.array( [ [[0, 10, 1, 11], [0, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 999, 2, 1004], [0, 10.1, 1, 11.1], [0, 100, 1, 101], [0, 0, 0, 0]], ] ) exp_nms_scores = np.array([[0.95, 0.9, 0, 0], [0.85, 0.5, 0.3, 0]]) exp_nms_classes = np.array([[0, 0, 0, 0], [1, 0, 0, 0]]) exp_nms_additional_fields = { "keypoints": np.array( [ [ [[0, 0], [0, 0]], [[6, 7], [8, 9]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], ], [ [[10, 11], [12, 13]], [[13, 14], [15, 16]], [[8, 9], [10, 11]], [[0, 0], [0, 0]], ], ] ) } ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, nmsed_additional_fields, num_detections, ) = post_processing.batch_multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_size_per_class=max_output_size, max_total_size=max_output_size, additional_fields=additional_fields, ) self.assertIsNone(nmsed_masks) # Check static shapes self.assertAllEqual(nmsed_boxes.shape.as_list(), exp_nms_corners.shape) self.assertAllEqual(nmsed_scores.shape.as_list(), exp_nms_scores.shape) self.assertAllEqual(nmsed_classes.shape.as_list(), exp_nms_classes.shape) self.assertEqual(len(nmsed_additional_fields), len(exp_nms_additional_fields)) for key in exp_nms_additional_fields: self.assertAllEqual( nmsed_additional_fields[key].shape.as_list(), exp_nms_additional_fields[key].shape, ) self.assertEqual(num_detections.shape.as_list(), [2]) with self.test_session() as sess: ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_additional_fields, num_detections, ) = sess.run( [ nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_additional_fields, num_detections, ] ) self.assertAllClose(nmsed_boxes, exp_nms_corners) self.assertAllClose(nmsed_scores, exp_nms_scores) self.assertAllClose(nmsed_classes, exp_nms_classes) for key in exp_nms_additional_fields: self.assertAllClose( nmsed_additional_fields[key], exp_nms_additional_fields[key] ) self.assertAllClose(num_detections, [2, 3]) def test_batch_multiclass_nms_with_dynamic_batch_size(self): boxes_placeholder = tf.placeholder(tf.float32, shape=(None, None, 2, 4)) scores_placeholder = tf.placeholder(tf.float32, shape=(None, None, 2)) masks_placeholder = tf.placeholder(tf.float32, shape=(None, None, 2, 2, 2)) boxes = np.array( [ [ [[0, 0, 1, 1], [0, 0, 4, 5]], [[0, 0.1, 1, 1.1], [0, 0.1, 2, 1.1]], [[0, -0.1, 1, 0.9], [0, -0.1, 1, 0.9]], [[0, 10, 1, 11], [0, 10, 1, 11]], ], [ [[0, 10.1, 1, 11.1], [0, 10.1, 1, 11.1]], [[0, 100, 1, 101], [0, 100, 1, 101]], [[0, 1000, 1, 1002], [0, 999, 2, 1004]], [[0, 1000, 1, 1002.1], [0, 999, 2, 1002.7]], ], ] ) scores = np.array( [ [[0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0]], [[0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5]], ] ) masks = np.array( [ [ [[[0, 1], [2, 3]], [[1, 2], [3, 4]]], [[[2, 3], [4, 5]], [[3, 4], [5, 6]]], [[[4, 5], [6, 7]], [[5, 6], [7, 8]]], [[[6, 7], [8, 9]], [[7, 8], [9, 10]]], ], [ [[[8, 9], [10, 11]], [[9, 10], [11, 12]]], [[[10, 11], [12, 13]], [[11, 12], [13, 14]]], [[[12, 13], [14, 15]], [[13, 14], [15, 16]]], [[[14, 15], [16, 17]], [[15, 16], [17, 18]]], ], ] ) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = np.array( [ [[0, 10, 1, 11], [0, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 999, 2, 1004], [0, 10.1, 1, 11.1], [0, 100, 1, 101], [0, 0, 0, 0]], ] ) exp_nms_scores = np.array([[0.95, 0.9, 0, 0], [0.85, 0.5, 0.3, 0]]) exp_nms_classes = np.array([[0, 0, 0, 0], [1, 0, 0, 0]]) exp_nms_masks = np.array( [ [ [[6, 7], [8, 9]], [[0, 1], [2, 3]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], ], [ [[13, 14], [15, 16]], [[8, 9], [10, 11]], [[10, 11], [12, 13]], [[0, 0], [0, 0]], ], ] ) ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, nmsed_additional_fields, num_detections, ) = post_processing.batch_multiclass_non_max_suppression( boxes_placeholder, scores_placeholder, score_thresh, iou_thresh, max_size_per_class=max_output_size, max_total_size=max_output_size, masks=masks_placeholder, ) self.assertIsNone(nmsed_additional_fields) # Check static shapes self.assertAllEqual(nmsed_boxes.shape.as_list(), [None, 4, 4]) self.assertAllEqual(nmsed_scores.shape.as_list(), [None, 4]) self.assertAllEqual(nmsed_classes.shape.as_list(), [None, 4]) self.assertAllEqual(nmsed_masks.shape.as_list(), [None, 4, 2, 2]) self.assertEqual(num_detections.shape.as_list(), [None]) with self.test_session() as sess: ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, num_detections, ) = sess.run( [nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, num_detections], feed_dict={ boxes_placeholder: boxes, scores_placeholder: scores, masks_placeholder: masks, }, ) self.assertAllClose(nmsed_boxes, exp_nms_corners) self.assertAllClose(nmsed_scores, exp_nms_scores) self.assertAllClose(nmsed_classes, exp_nms_classes) self.assertAllClose(num_detections, [2, 3]) self.assertAllClose(nmsed_masks, exp_nms_masks) def test_batch_multiclass_nms_with_masks_and_num_valid_boxes(self): boxes = tf.constant( [ [ [[0, 0, 1, 1], [0, 0, 4, 5]], [[0, 0.1, 1, 1.1], [0, 0.1, 2, 1.1]], [[0, -0.1, 1, 0.9], [0, -0.1, 1, 0.9]], [[0, 10, 1, 11], [0, 10, 1, 11]], ], [ [[0, 10.1, 1, 11.1], [0, 10.1, 1, 11.1]], [[0, 100, 1, 101], [0, 100, 1, 101]], [[0, 1000, 1, 1002], [0, 999, 2, 1004]], [[0, 1000, 1, 1002.1], [0, 999, 2, 1002.7]], ], ], tf.float32, ) scores = tf.constant( [ [[0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0]], [[0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5]], ] ) masks = tf.constant( [ [ [[[0, 1], [2, 3]], [[1, 2], [3, 4]]], [[[2, 3], [4, 5]], [[3, 4], [5, 6]]], [[[4, 5], [6, 7]], [[5, 6], [7, 8]]], [[[6, 7], [8, 9]], [[7, 8], [9, 10]]], ], [ [[[8, 9], [10, 11]], [[9, 10], [11, 12]]], [[[10, 11], [12, 13]], [[11, 12], [13, 14]]], [[[12, 13], [14, 15]], [[13, 14], [15, 16]]], [[[14, 15], [16, 17]], [[15, 16], [17, 18]]], ], ], tf.float32, ) num_valid_boxes = tf.constant([1, 1], tf.int32) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = [ [[0, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 10.1, 1, 11.1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], ] exp_nms_scores = [[0.9, 0, 0, 0], [0.5, 0, 0, 0]] exp_nms_classes = [[0, 0, 0, 0], [0, 0, 0, 0]] exp_nms_masks = [ [[[0, 1], [2, 3]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[8, 9], [10, 11]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], ] ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, nmsed_additional_fields, num_detections, ) = post_processing.batch_multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_size_per_class=max_output_size, max_total_size=max_output_size, num_valid_boxes=num_valid_boxes, masks=masks, ) self.assertIsNone(nmsed_additional_fields) with self.test_session() as sess: ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, num_detections, ) = sess.run( [nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, num_detections] ) self.assertAllClose(nmsed_boxes, exp_nms_corners) self.assertAllClose(nmsed_scores, exp_nms_scores) self.assertAllClose(nmsed_classes, exp_nms_classes) self.assertAllClose(num_detections, [1, 1]) self.assertAllClose(nmsed_masks, exp_nms_masks) def test_batch_multiclass_nms_with_additional_fields_and_num_valid_boxes(self): boxes = tf.constant( [ [ [[0, 0, 1, 1], [0, 0, 4, 5]], [[0, 0.1, 1, 1.1], [0, 0.1, 2, 1.1]], [[0, -0.1, 1, 0.9], [0, -0.1, 1, 0.9]], [[0, 10, 1, 11], [0, 10, 1, 11]], ], [ [[0, 10.1, 1, 11.1], [0, 10.1, 1, 11.1]], [[0, 100, 1, 101], [0, 100, 1, 101]], [[0, 1000, 1, 1002], [0, 999, 2, 1004]], [[0, 1000, 1, 1002.1], [0, 999, 2, 1002.7]], ], ], tf.float32, ) scores = tf.constant( [ [[0.9, 0.01], [0.75, 0.05], [0.6, 0.01], [0.95, 0]], [[0.5, 0.01], [0.3, 0.01], [0.01, 0.85], [0.01, 0.5]], ] ) additional_fields = { "keypoints": tf.constant( [ [ [[6, 7], [8, 9]], [[0, 1], [2, 3]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], ], [ [[13, 14], [15, 16]], [[8, 9], [10, 11]], [[10, 11], [12, 13]], [[0, 0], [0, 0]], ], ], tf.float32, ) } num_valid_boxes = tf.constant([1, 1], tf.int32) score_thresh = 0.1 iou_thresh = 0.5 max_output_size = 4 exp_nms_corners = [ [[0, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 10.1, 1, 11.1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], ] exp_nms_scores = [[0.9, 0, 0, 0], [0.5, 0, 0, 0]] exp_nms_classes = [[0, 0, 0, 0], [0, 0, 0, 0]] exp_nms_additional_fields = { "keypoints": np.array( [ [ [[6, 7], [8, 9]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], ], [ [[13, 14], [15, 16]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]], ], ] ) } ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_masks, nmsed_additional_fields, num_detections, ) = post_processing.batch_multiclass_non_max_suppression( boxes, scores, score_thresh, iou_thresh, max_size_per_class=max_output_size, max_total_size=max_output_size, num_valid_boxes=num_valid_boxes, additional_fields=additional_fields, ) self.assertIsNone(nmsed_masks) with self.test_session() as sess: ( nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_additional_fields, num_detections, ) = sess.run( [ nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_additional_fields, num_detections, ] ) self.assertAllClose(nmsed_boxes, exp_nms_corners) self.assertAllClose(nmsed_scores, exp_nms_scores) self.assertAllClose(nmsed_classes, exp_nms_classes) for key in exp_nms_additional_fields: self.assertAllClose( nmsed_additional_fields[key], exp_nms_additional_fields[key] ) self.assertAllClose(num_detections, [1, 1]) if __name__ == "__main__": tf.test.main()
mylar
librarysync
# -*- coding: utf-8 -*- # This file is part of Mylar. # # Mylar is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Mylar is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Mylar. If not, see <http://www.gnu.org/licenses/>. from __future__ import with_statement import glob import os import random import re import shutil import mylar from mylar import db, filechecker, helpers, importer, logger, updater # You can scan a single directory and append it to the current library by specifying append=True def libraryScan( dir=None, append=False, ComicID=None, ComicName=None, cron=None, queue=None ): if cron and not mylar.LIBRARYSCAN: return if not dir: dir = mylar.CONFIG.COMIC_DIR # If we're appending a dir, it's coming from the post processor which is # already bytestring if not append: dir = dir.encode(mylar.SYS_ENCODING) if not os.path.isdir(dir): logger.warn( "Cannot find directory: %s. Not scanning" % dir.decode(mylar.SYS_ENCODING, "replace") ) return "Fail" logger.info( "Scanning comic directory: %s" % dir.decode(mylar.SYS_ENCODING, "replace") ) basedir = dir comic_list = [] failure_list = [] utter_failure_list = [] comiccnt = 0 extensions = ("cbr", "cbz") cv_location = [] cbz_retry = 0 mylar.IMPORT_STATUS = "Now attempting to parse files for additional information" myDB = db.DBConnection() # mylar.IMPORT_PARSED_COUNT #used to count what #/totalfiles the filename parser is currently on for r, d, f in os.walk(dir): for files in f: mylar.IMPORT_FILES += 1 if any(files.lower().endswith("." + x.lower()) for x in extensions): comicpath = os.path.join(r, files) if mylar.CONFIG.IMP_PATHS is True: if myDB.select( 'SELECT * FROM comics JOIN issues WHERE issues.Status="Downloaded" AND ComicLocation=? AND issues.Location=?', [ r.decode(mylar.SYS_ENCODING, "replace"), files.decode(mylar.SYS_ENCODING, "replace"), ], ): logger.info("Skipped known issue path: %s" % comicpath) continue comic = files comicsize = os.path.getsize(comicpath) logger.fdebug( "Comic: " + comic + " [" + comicpath + "] - " + str(comicsize) + " bytes" ) try: t = filechecker.FileChecker(dir=r, file=comic) results = t.listFiles() # logger.info(results) #'type': re.sub('\.','', filetype).strip(), #'sub': path_list, #'volume': volume, #'match_type': match_type, #'comicfilename': filename, #'comiclocation': clocation, #'series_name': series_name, #'series_volume': issue_volume, #'series_year': issue_year, #'justthedigits': issue_number, #'annualcomicid': annual_comicid, #'scangroup': scangroup} if results: resultline = "[PARSE-" + results["parse_status"].upper() + "]" resultline += "[SERIES: " + results["series_name"] + "]" if results["series_volume"] is not None: resultline += "[VOLUME: " + results["series_volume"] + "]" if results["issue_year"] is not None: resultline += ( "[ISSUE YEAR: " + str(results["issue_year"]) + "]" ) if results["issue_number"] is not None: resultline += "[ISSUE #: " + results["issue_number"] + "]" logger.fdebug(resultline) else: logger.fdebug("[PARSED] FAILURE.") continue # We need the unicode path to use for logging, inserting into database unicode_comic_path = comicpath.decode(mylar.SYS_ENCODING, "replace") if results["parse_status"] == "success": comic_list.append( { "ComicFilename": comic, "ComicLocation": comicpath, "ComicSize": comicsize, "Unicode_ComicLocation": unicode_comic_path, "parsedinfo": { "series_name": results["series_name"], "series_volume": results["series_volume"], "issue_year": results["issue_year"], "issue_number": results["issue_number"], }, } ) comiccnt += 1 mylar.IMPORT_PARSED_COUNT += 1 else: failure_list.append( { "ComicFilename": comic, "ComicLocation": comicpath, "ComicSize": comicsize, "Unicode_ComicLocation": unicode_comic_path, "parsedinfo": { "series_name": results["series_name"], "series_volume": results["series_volume"], "issue_year": results["issue_year"], "issue_number": results["issue_number"], }, } ) mylar.IMPORT_FAILURE_COUNT += 1 if comic.endswith(".cbz"): cbz_retry += 1 except Exception, e: logger.info("bang") utter_failure_list.append( { "ComicFilename": comic, "ComicLocation": comicpath, "ComicSize": comicsize, "Unicode_ComicLocation": unicode_comic_path, "parsedinfo": None, "error": e, } ) logger.info( "[" + str(e) + "] FAILURE encountered. Logging the error for " + comic + " and continuing..." ) mylar.IMPORT_FAILURE_COUNT += 1 if comic.endswith(".cbz"): cbz_retry += 1 continue if "cvinfo" in files: cv_location.append(r) logger.fdebug("CVINFO found: " + os.path.join(r)) mylar.IMPORT_TOTALFILES = comiccnt logger.info( "I have successfully discovered & parsed a total of " + str(comiccnt) + " files....analyzing now" ) logger.info( "I have not been able to determine what " + str(len(failure_list)) + " files are" ) logger.info( "However, " + str(cbz_retry) + " out of the " + str(len(failure_list)) + " files are in a cbz format, which may contain metadata." ) logger.info( "[ERRORS] I have encountered " + str(len(utter_failure_list)) + " file-scanning errors during the scan, but have recorded the necessary information." ) mylar.IMPORT_STATUS = "Successfully parsed " + str(comiccnt) + " files" # return queue.put(valreturn) if len(utter_failure_list) > 0: logger.fdebug("Failure list: %s" % utter_failure_list) # let's load in the watchlist to see if we have any matches. logger.info( "loading in the watchlist to see if a series is being watched already..." ) watchlist = myDB.select("SELECT * from comics") ComicName = [] DisplayName = [] ComicYear = [] ComicPublisher = [] ComicTotal = [] ComicID = [] ComicLocation = [] AltName = [] watchcnt = 0 watch_kchoice = [] watchchoice = {} import_by_comicids = [] import_comicids = {} for watch in watchlist: # use the comicname_filesafe to start watchdisplaycomic = ( watch["ComicName"].encode("utf-8").strip() ) # re.sub('[\_\#\,\/\:\;\!\$\%\&\+\'\?\@]', ' ', watch['ComicName']).encode('utf-8').strip() # let's clean up the name, just in case for comparison purposes... watchcomic = ( re.sub("[\_\#\,\/\:\;\.\-\!\$\%\&\+'\?\@]", "", watch["ComicName_Filesafe"]) .encode("utf-8") .strip() ) # watchcomic = re.sub('\s+', ' ', str(watchcomic)).strip() if " the " in watchcomic.lower(): # drop the 'the' from the watchcomic title for proper comparisons. watchcomic = watchcomic[-4:] alt_chk = "no" # alt-checker flag (default to no) # account for alternate names as well if ( watch["AlternateSearch"] is not None and watch["AlternateSearch"] is not "None" ): altcomic = ( re.sub( "[\_\#\,\/\:\;\.\-\!\$\%\&\+'\?\@]", "", watch["AlternateSearch"] ) .encode("utf-8") .strip() ) # altcomic = re.sub('\s+', ' ', str(altcomic)).strip() AltName.append(altcomic) alt_chk = "yes" # alt-checker flag ComicName.append(watchcomic) DisplayName.append(watchdisplaycomic) ComicYear.append(watch["ComicYear"]) ComicPublisher.append(watch["ComicPublisher"]) ComicTotal.append(watch["Total"]) ComicID.append(watch["ComicID"]) ComicLocation.append(watch["ComicLocation"]) watchcnt += 1 logger.info("Successfully loaded " + str(watchcnt) + " series from your watchlist.") ripperlist = ["digital-", "empire", "dcp"] watchfound = 0 datelist = [ "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", ] # datemonth = {'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'eleven':$ # #search for number as text, and change to numeric # for numbs in basnumbs: # #logger.fdebug("numbs:" + str(numbs)) # if numbs in ComicName.lower(): # numconv = basnumbs[numbs] # #logger.fdebug("numconv: " + str(numconv)) issueid_list = [] cvscanned_loc = None cvinfo_CID = None cnt = 0 mylar.IMPORT_STATUS = ( "[0%] Now parsing individual filenames for metadata if available" ) for i in comic_list: mylar.IMPORT_STATUS = ( "[" + str(cnt) + "/" + str(comiccnt) + "] Now parsing individual filenames for metadata if available" ) logger.fdebug("Analyzing : " + i["ComicFilename"]) comfilename = i["ComicFilename"] comlocation = i["ComicLocation"] issueinfo = None # probably need to zero these issue-related metadata to None so we can pick the best option issuevolume = None # Make sure cvinfo is checked for FIRST (so that CID can be attached to all files properly thereafter as they're scanned in) if ( os.path.dirname(comlocation) in cv_location and os.path.dirname(comlocation) != cvscanned_loc ): # if comfilename == 'cvinfo': logger.info("comfilename: " + comfilename) logger.info("cvscanned_loc: " + str(cv_location)) logger.info("comlocation: " + os.path.dirname(comlocation)) # if cvscanned_loc != comlocation: try: with open(os.path.join(os.path.dirname(comlocation), "cvinfo")) as f: urllink = f.readline() if urllink: cid = urllink.strip() pattern = re.compile(r"^.*?\b(49|4050)-(?P<num>\d{2,})\b.*$", re.I) match = pattern.match(cid) if match: cvinfo_CID = match.group("num") logger.info( "CVINFO file located within directory. Attaching everything in directory that is valid to ComicID: " + str(cvinfo_CID) ) # store the location of the cvinfo so it's applied to the correct directory (since we're scanning multile direcorties usually) cvscanned_loc = os.path.dirname(comlocation) else: logger.error( "Could not read cvinfo file properly (or it does not contain any data)" ) except (OSError, IOError): logger.error( "Could not read cvinfo file properly (or it does not contain any data)" ) # else: # don't scan in it again if it's already been done initially # continue if mylar.CONFIG.IMP_METADATA: # if read tags is enabled during import, check here. if i["ComicLocation"].endswith(".cbz"): logger.fdebug("[IMPORT-CBZ] Metatagging checking enabled.") logger.info( "[IMPORT-CBZ} Attempting to read tags present in filename: " + i["ComicLocation"] ) try: issueinfo = helpers.IssueDetails(i["ComicLocation"], justinfo=True) except: logger.fdebug( "[IMPORT-CBZ] Unable to retrieve metadata - possibly doesn't exist. Ignoring meta-retrieval" ) pass else: logger.info("issueinfo: " + str(issueinfo)) if issueinfo is None: logger.fdebug( "[IMPORT-CBZ] No valid metadata contained within filename. Dropping down to parsing the filename itself." ) pass else: issuenotes_id = None logger.info( "[IMPORT-CBZ] Successfully retrieved some tags. Lets see what I can figure out." ) comicname = issueinfo[0]["series"] if comicname is not None: logger.fdebug("[IMPORT-CBZ] Series Name: " + comicname) as_d = filechecker.FileChecker() as_dyninfo = as_d.dynamic_replace(comicname) logger.fdebug( "Dynamic-ComicName: " + as_dyninfo["mod_seriesname"] ) else: logger.fdebug( "[IMPORT-CBZ] No series name found within metadata. This is bunk - dropping down to file parsing for usable information." ) issueinfo = None issue_number = None if issueinfo is not None: try: issueyear = issueinfo[0]["year"] except: issueyear = None # if the issue number is a non-numeric unicode string, this will screw up along with impID issue_number = issueinfo[0]["issue_number"] if issue_number is not None: logger.fdebug( "[IMPORT-CBZ] Issue Number: " + issue_number ) else: issue_number = i["parsed"]["issue_number"] if ( "annual" in comicname.lower() or "annual" in comfilename.lower() ): if issue_number is None or issue_number == "None": logger.info( "Annual detected with no issue number present within metadata. Assuming year as issue." ) try: issue_number = "Annual " + str(issueyear) except: issue_number = ( "Annual " + i["parsed"]["issue_year"] ) else: logger.info( "Annual detected with issue number present within metadata." ) if "annual" not in issue_number.lower(): issue_number = "Annual " + issue_number mod_series = re.sub( "annual", "", comicname, flags=re.I ).strip() else: mod_series = comicname logger.fdebug("issue number SHOULD Be: " + issue_number) try: issuetitle = issueinfo[0]["title"] except: issuetitle = None try: issueyear = issueinfo[0]["year"] except: issueyear = None try: issuevolume = str(issueinfo[0]["volume"]) if all( [ issuevolume is not None, issuevolume != "None", not issuevolume.lower().startswith("v"), ] ): issuevolume = "v" + str(issuevolume) if any([issuevolume is None, issuevolume == "None"]): logger.info("EXCEPT] issue volume is NONE") issuevolume = None else: logger.fdebug( "[TRY]issue volume is: " + str(issuevolume) ) except: logger.fdebug( "[EXCEPT]issue volume is: " + str(issuevolume) ) issuevolume = None if any( [ comicname is None, comicname == "None", issue_number is None, issue_number == "None", ] ): logger.fdebug( "[IMPORT-CBZ] Improperly tagged file as the metatagging is invalid. Ignoring meta and just parsing the filename." ) issueinfo = None pass else: # if used by ComicTagger, Notes field will have the IssueID. issuenotes = issueinfo[0]["notes"] logger.fdebug("[IMPORT-CBZ] Notes: " + issuenotes) if issuenotes is not None and issuenotes != "None": if "Issue ID" in issuenotes: st_find = issuenotes.find("Issue ID") tmp_issuenotes_id = re.sub( "[^0-9]", " ", issuenotes[st_find:] ).strip() if tmp_issuenotes_id.isdigit(): issuenotes_id = tmp_issuenotes_id logger.fdebug( "[IMPORT-CBZ] Successfully retrieved CV IssueID for " + comicname + " #" + issue_number + " [" + str(issuenotes_id) + "]" ) elif "CVDB" in issuenotes: st_find = issuenotes.find("CVDB") tmp_issuenotes_id = re.sub( "[^0-9]", " ", issuenotes[st_find:] ).strip() if tmp_issuenotes_id.isdigit(): issuenotes_id = tmp_issuenotes_id logger.fdebug( "[IMPORT-CBZ] Successfully retrieved CV IssueID for " + comicname + " #" + issue_number + " [" + str(issuenotes_id) + "]" ) else: logger.fdebug( "[IMPORT-CBZ] Unable to retrieve IssueID from meta-tagging. If there is other metadata present I will use that." ) logger.fdebug( "[IMPORT-CBZ] Adding " + comicname + " to the import-queue!" ) # impid = comicname + '-' + str(issueyear) + '-' + str(issue_number) #com_NAME + "-" + str(result_comyear) + "-" + str(comiss) impid = str(random.randint(1000000, 99999999)) logger.fdebug("[IMPORT-CBZ] impid: " + str(impid)) # make sure we only add in those issueid's which don't already have a comicid attached via the cvinfo scan above (this is for reverse-lookup of issueids) issuepopulated = False if cvinfo_CID is None: if issuenotes_id is None: logger.info( "[IMPORT-CBZ] No ComicID detected where it should be. Bypassing this metadata entry and going the parsing route [" + comfilename + "]" ) else: # we need to store the impid here as well so we can look it up. issueid_list.append( { "issueid": issuenotes_id, "importinfo": { "impid": impid, "comicid": None, "comicname": comicname, "dynamicname": as_dyninfo[ "mod_seriesname" ], "comicyear": issueyear, "issuenumber": issue_number, "volume": issuevolume, "comfilename": comfilename, "comlocation": comlocation.decode( mylar.SYS_ENCODING ), }, } ) mylar.IMPORT_CID_COUNT += 1 issuepopulated = True if issuepopulated == False: if cvscanned_loc == os.path.dirname(comlocation): cv_cid = cvinfo_CID logger.fdebug( "[IMPORT-CBZ] CVINFO_COMICID attached : " + str(cv_cid) ) else: cv_cid = None import_by_comicids.append( { "impid": impid, "comicid": cv_cid, "watchmatch": None, "displayname": mod_series, "comicname": comicname, "dynamicname": as_dyninfo["mod_seriesname"], "comicyear": issueyear, "issuenumber": issue_number, "volume": issuevolume, "issueid": issuenotes_id, "comfilename": comfilename, "comlocation": comlocation.decode( mylar.SYS_ENCODING ), } ) mylar.IMPORT_CID_COUNT += 1 else: pass # logger.fdebug(i['ComicFilename'] + ' is not in a metatagged format (cbz). Bypassing reading of the metatags') if issueinfo is None: if i["parsedinfo"]["issue_number"] is None: if "annual" in i["parsedinfo"]["series_name"].lower(): logger.fdebug( "Annual detected with no issue number present. Assuming year as issue." ) ##1 issue') if i["parsedinfo"]["issue_year"] is not None: issuenumber = "Annual " + str(i["parsedinfo"]["issue_year"]) else: issuenumber = "Annual 1" else: issuenumber = i["parsedinfo"]["issue_number"] if "annual" in i["parsedinfo"]["series_name"].lower(): mod_series = re.sub( "annual", "", i["parsedinfo"]["series_name"], flags=re.I ).strip() logger.fdebug( "Annual detected with no issue number present. Assuming year as issue." ) ##1 issue') if i["parsedinfo"]["issue_number"] is not None: issuenumber = "Annual " + str(i["parsedinfo"]["issue_number"]) else: if i["parsedinfo"]["issue_year"] is not None: issuenumber = "Annual " + str(i["parsedinfo"]["issue_year"]) else: issuenumber = "Annual 1" else: mod_series = i["parsedinfo"]["series_name"] issuenumber = i["parsedinfo"]["issue_number"] logger.fdebug("[" + mod_series + "] Adding to the import-queue!") isd = filechecker.FileChecker() is_dyninfo = isd.dynamic_replace(helpers.conversion(mod_series)) logger.fdebug("Dynamic-ComicName: " + is_dyninfo["mod_seriesname"]) # impid = dispname + '-' + str(result_comyear) + '-' + str(comiss) #com_NAME + "-" + str(result_comyear) + "-" + str(comiss) impid = str(random.randint(1000000, 99999999)) logger.fdebug("impid: " + str(impid)) if cvscanned_loc == os.path.dirname(comlocation): cv_cid = cvinfo_CID logger.fdebug("CVINFO_COMICID attached : " + str(cv_cid)) else: cv_cid = None if issuevolume is None: logger.fdebug("issue volume is : " + str(issuevolume)) if i["parsedinfo"]["series_volume"] is None: issuevolume = None else: if str(i["parsedinfo"]["series_volume"].lower()).startswith("v"): issuevolume = i["parsedinfo"]["series_volume"] else: issuevolume = "v" + str(i["parsedinfo"]["series_volume"]) else: logger.fdebug("issue volume not none : " + str(issuevolume)) if issuevolume.lower().startswith("v"): issuevolume = issuevolume else: issuevolume = "v" + str(issuevolume) logger.fdebug("IssueVolume is : " + str(issuevolume)) import_by_comicids.append( { "impid": impid, "comicid": cv_cid, "issueid": None, "watchmatch": None, # watchmatch (should be true/false if it already exists on watchlist) "displayname": mod_series, "comicname": i["parsedinfo"]["series_name"], "dynamicname": is_dyninfo["mod_seriesname"].lower(), "comicyear": i["parsedinfo"]["issue_year"], "issuenumber": issuenumber, # issuenumber, "volume": issuevolume, "comfilename": comfilename, "comlocation": helpers.conversion(comlocation), } ) cnt += 1 # logger.fdebug('import_by_ids: ' + str(import_by_comicids)) # reverse lookup all of the gathered IssueID's in order to get the related ComicID reverse_issueids = [] for x in issueid_list: reverse_issueids.append(x["issueid"]) vals = [] if len(reverse_issueids) > 0: mylar.IMPORT_STATUS = ( "Now Reverse looking up " + str(len(reverse_issueids)) + " IssueIDs to get the ComicIDs" ) vals = mylar.cv.getComic(None, "import", comicidlist=reverse_issueids) # logger.fdebug('vals returned:' + str(vals)) if len(watch_kchoice) > 0: watchchoice["watchlist"] = watch_kchoice # logger.fdebug("watchchoice: " + str(watchchoice)) logger.info( "I have found " + str(watchfound) + " out of " + str(comiccnt) + " comics for series that are being watched." ) wat = 0 comicids = [] if watchfound > 0: if mylar.CONFIG.IMP_MOVE: logger.info( "You checked off Move Files...so that's what I am going to do" ) # check to see if Move Files is enabled. # if not being moved, set the archive bit. logger.fdebug("Moving files into appropriate directory") while wat < watchfound: watch_the_list = watchchoice["watchlist"][wat] watch_comlocation = watch_the_list["ComicLocation"] watch_comicid = watch_the_list["ComicID"] watch_comicname = watch_the_list["ComicName"] watch_comicyear = watch_the_list["ComicYear"] watch_comiciss = watch_the_list["ComicIssue"] logger.fdebug("ComicLocation: " + watch_comlocation) orig_comlocation = watch_the_list["OriginalLocation"] orig_filename = watch_the_list["OriginalFilename"] logger.fdebug("Orig. Location: " + orig_comlocation) logger.fdebug("Orig. Filename: " + orig_filename) # before moving check to see if Rename to Mylar structure is enabled. if mylar.CONFIG.IMP_RENAME: logger.fdebug( "Renaming files according to configuration details : " + str(mylar.CONFIG.FILE_FORMAT) ) renameit = helpers.rename_param( watch_comicid, watch_comicname, watch_comicyear, watch_comiciss, ) nfilename = renameit["nfilename"] dst_path = os.path.join(watch_comlocation, nfilename) if str(watch_comicid) not in comicids: comicids.append(watch_comicid) else: logger.fdebug( "Renaming files not enabled, keeping original filename(s)" ) dst_path = os.path.join(watch_comlocation, orig_filename) # os.rename(os.path.join(self.nzb_folder, str(ofilename)), os.path.join(self.nzb_folder,str(nfilename + ext))) # src = os.path.join(, str(nfilename + ext)) logger.fdebug( "I am going to move " + orig_comlocation + " to " + dst_path ) try: shutil.move(orig_comlocation, dst_path) except (OSError, IOError): logger.info( "Failed to move directory - check directories and manually re-run." ) wat += 1 else: # if move files isn't enabled, let's set all found comics to Archive status :) while wat < watchfound: watch_the_list = watchchoice["watchlist"][wat] watch_comicid = watch_the_list["ComicID"] watch_issue = watch_the_list["ComicIssue"] logger.fdebug("ComicID: " + str(watch_comicid)) logger.fdebug("Issue#: " + str(watch_issue)) issuechk = myDB.selectone( "SELECT * from issues where ComicID=? AND INT_IssueNumber=?", [watch_comicid, watch_issue], ).fetchone() if issuechk is None: logger.fdebug("No matching issues for this comic#") else: logger.fdebug("...Existing status: " + str(issuechk["Status"])) control = {"IssueID": issuechk["IssueID"]} values = {"Status": "Archived"} logger.fdebug( "...changing status of " + str(issuechk["Issue_Number"]) + " to Archived " ) myDB.upsert("issues", values, control) if str(watch_comicid) not in comicids: comicids.append(watch_comicid) wat += 1 if comicids is None: pass else: c_upd = len(comicids) c = 0 while c < c_upd: logger.fdebug("Rescanning.. " + str(c)) updater.forceRescan(c) if not len(import_by_comicids): return "Completed" if len(import_by_comicids) > 0 or len(vals) > 0: # import_comicids['comic_info'] = import_by_comicids # if vals: # import_comicids['issueid_info'] = vals # else: # import_comicids['issueid_info'] = None if vals: cvimport_comicids = vals import_cv_ids = len(vals) else: cvimport_comicids = None import_cv_ids = 0 else: import_cv_ids = 0 cvimport_comicids = None return { "import_by_comicids": import_by_comicids, "import_count": len(import_by_comicids), "CV_import_comicids": cvimport_comicids, "import_cv_ids": import_cv_ids, "issueid_list": issueid_list, "failure_list": failure_list, "utter_failure_list": utter_failure_list, } def scanLibrary(scan=None, queue=None): mylar.IMPORT_FILES = 0 mylar.IMPORT_PARSED_COUNT = 0 valreturn = [] if scan: try: soma = libraryScan(queue=queue) except Exception, e: logger.error("[IMPORT] Unable to complete the scan: %s" % e) mylar.IMPORT_STATUS = None valreturn.append({"somevalue": "self.ie", "result": "error"}) return queue.put(valreturn) if soma == "Completed": logger.info("[IMPORT] Sucessfully completed import.") elif soma == "Fail": mylar.IMPORT_STATUS = "Failure" valreturn.append({"somevalue": "self.ie", "result": "error"}) return queue.put(valreturn) else: mylar.IMPORT_STATUS = "Now adding the completed results to the DB." logger.info("[IMPORT] Parsing/Reading of files completed!") logger.info( "[IMPORT] Attempting to import " + str(int(soma["import_cv_ids"] + soma["import_count"])) + " files into your watchlist." ) logger.info( "[IMPORT-BREAKDOWN] Files with ComicIDs successfully extracted: " + str(soma["import_cv_ids"]) ) logger.info( "[IMPORT-BREAKDOWN] Files that had to be parsed: " + str(soma["import_count"]) ) logger.info( "[IMPORT-BREAKDOWN] Files that were unable to be parsed: " + str(len(soma["failure_list"])) ) logger.info( "[IMPORT-BREAKDOWN] Files that caused errors during the import: " + str(len(soma["utter_failure_list"])) ) # logger.info('[IMPORT-BREAKDOWN] Failure Files: ' + str(soma['failure_list'])) myDB = db.DBConnection() # first we do the CV ones. if int(soma["import_cv_ids"]) > 0: for i in soma["CV_import_comicids"]: # we need to find the impid in the issueid_list as that holds the impid + other info abc = [ x for x in soma["issueid_list"] if x["issueid"] == i["IssueID"] ] ghi = abc[0]["importinfo"] nspace_dynamicname = re.sub( "[\|\s]", "", ghi["dynamicname"].lower() ).strip() # these all have related ComicID/IssueID's...just add them as is. controlValue = {"impID": ghi["impid"]} newValue = { "Status": "Not Imported", "ComicName": helpers.conversion(i["ComicName"]), "DisplayName": helpers.conversion(i["ComicName"]), "DynamicName": helpers.conversion(nspace_dynamicname), "ComicID": i["ComicID"], "IssueID": i["IssueID"], "IssueNumber": helpers.conversion(i["Issue_Number"]), "Volume": ghi["volume"], "ComicYear": ghi["comicyear"], "ComicFilename": helpers.conversion(ghi["comfilename"]), "ComicLocation": helpers.conversion(ghi["comlocation"]), "ImportDate": helpers.today(), "WatchMatch": None, } # i['watchmatch']} myDB.upsert("importresults", newValue, controlValue) if int(soma["import_count"]) > 0: for ss in soma["import_by_comicids"]: nspace_dynamicname = re.sub( "[\|\s]", "", ss["dynamicname"].lower() ).strip() controlValue = {"impID": ss["impid"]} newValue = { "ComicYear": ss["comicyear"], "Status": "Not Imported", "ComicName": helpers.conversion(ss["comicname"]), "DisplayName": helpers.conversion(ss["displayname"]), "DynamicName": helpers.conversion(nspace_dynamicname), "ComicID": ss[ "comicid" ], # if it's been scanned in for cvinfo, this will be the CID - otherwise it's None "IssueID": None, "Volume": ss["volume"], "IssueNumber": helpers.conversion(ss["issuenumber"]), "ComicFilename": helpers.conversion(ss["comfilename"]), "ComicLocation": helpers.conversion(ss["comlocation"]), "ImportDate": helpers.today(), "WatchMatch": ss["watchmatch"], } myDB.upsert("importresults", newValue, controlValue) # because we could be adding volumes/series that span years, we need to account for this # add the year to the db under the term, valid-years # add the issue to the db under the term, min-issue # locate metadata here. # unzip -z filename.cbz will show the comment field of the zip which contains the metadata. # self.importResults() mylar.IMPORT_STATUS = "Import completed." valreturn.append({"somevalue": "self.ie", "result": "success"}) return queue.put(valreturn)
sword
protocol
import copy import logging from datetime import datetime from io import BytesIO from itertools import chain from zipfile import ZipFile import langdetect import requests from deposit.models import DepositRecord from deposit.protocol import DepositError, DepositResult, RepositoryProtocol from deposit.registry import protocol_registry from deposit.sword.forms import SWORDMETSForm from deposit.utils import MetadataConverter, get_email from django.utils.functional import cached_property from django.utils.translation import ugettext as _ from lxml import etree from papers.models import Institution, OaiRecord, Researcher from papers.utils import kill_html from website.utils import get_users_idp logger = logging.getLogger("dissemin." + __name__) # Namespaces ATOM_NAMESPACE = "http://www.w3.org/2005/Atom" DISSEMIN_NAMESPACE = "https://dissem.in/deposit/terms/" METS_NAMESPACE = "http://www.loc.gov/METS/" MODS_NAMESPACE = "http://www.loc.gov/mods/v3" XLINK_NAMESPACE = "http://www.w3.org/1999/xlink" XSI_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance" ATOM = "{%s}" % ATOM_NAMESPACE DS = "{%s}" % DISSEMIN_NAMESPACE METS = "{%s}" % METS_NAMESPACE MODS = "{%s}" % MODS_NAMESPACE XLINK = "{%s}" % XLINK_NAMESPACE NSMAP = { "atom": ATOM_NAMESPACE, "ds": DISSEMIN_NAMESPACE, "mets": METS_NAMESPACE, "xlink": XLINK_NAMESPACE, "xsi": XSI_NAMESPACE, } class SWORDMETSProtocol(RepositoryProtocol): """ A protocol that performs a deposito via SWORDv2 using a METS Container. """ # The class of the form for the deposit form_class = SWORDMETSForm @cached_property def paper_metadata(self): """ Gives access to a dict of the metadata from the paper and its OaiRecords. """ prefered_records = self._get_prefered_records() mc = MetadataConverter(self.paper, prefered_records) return mc.metadata() def _get_deposit_result(self, response): """ Processes the deposit result as presented by sword. We try to set the splash url. We set deposit_status to pending. We do not set a pdf_url because we expect moderation, so a pdf_url would be a dead link (for samoe time). """ try: sword_statement = etree.fromstring(bytes(response, encoding="utf-8")) except etree.XMLSyntaxError: self.log("Invalid XML response from {}".format(self.repository.name)) raise DepositError( _("The repository {} returned invalid XML").format(self.repository.name) ) # We assume one element for the splash url, so we take the first one link_alternate = sword_statement.find( "atom:link[@rel='alternate']", namespaces=NSMAP ) print(link_alternate) if link_alternate is not None: splash_url = link_alternate.get("href", None) else: splash_url = None if splash_url: identifier = splash_url.split("/")[-1] else: identifier = None msg = "Found no splash url in XML reposonse from repository {}. Either no link[@ref='alternate'] was present or the href was missing.".format( self.repository.name ) self.log(msg) logger.warning(msg) # We expect that SWORD Repos usually have moderation. If this is at some point not the case, we can make this more flexible status = "pending" deposit_result = DepositResult( identifier=identifier, splash_url=splash_url, status=status ) return deposit_result @property def filename(self): """ Returns a filename that is paper slug and has at most 35+4 characters. """ return "{:.35}.pdf".format(self.paper.slug) def _get_mets(self, metadata, dissemin_metadata): """ Creates a mets xml from metadata Policy for creation is: One-time-usage, so keep the document as small as possible. This means * Attributes and elements are omitted if not needed * There is one and only one dmdSec * MDTYPE in dmdSec/mdWrap is always `OTHER` * One and only file that is named `document.pdf` :params metadata: Bibliographic metadata as lxml etree :params dissemin_metadata: Dissemin metadata as lxml etree :returns: complete mets as string """ # Creation of document root mets_xml = etree.Element(METS + "mets", nsmap=self.NSMAP) # Creation of metsHdr # We use this to make the mets itself distingushable from e.g. DeppGreen mets_hdr = etree.SubElement(mets_xml, METS + "metsHdr") mets_agent = etree.SubElement( mets_hdr, METS + "agent", ROLE="CREATOR", TYPE="ORGANIZATION" ) mets_name = etree.SubElement(mets_agent, METS + "name") mets_name.text = "Dissemin" # Creation of dmdSec and insertion of metadata mets_dmdSec = etree.SubElement(mets_xml, METS + "dmdSec", ID="d_dmd_1") mets_mdWrap = etree.SubElement( mets_dmdSec, METS + "mdWrap", MDTYPE="OTHER", OTHERMDTYPE="DSMODS" ) mets_xmlData = etree.SubElement(mets_mdWrap, METS + "xmlData") mets_xmlData.insert(0, metadata) # Creation of amdSec and insertion of dissemin metada mets_amdSec = etree.SubElement(mets_xml, METS + "amdSec", ID="d_amd_1") mets_rightsMD = etree.SubElement( mets_amdSec, METS + "rightsMD", ID="d_rightsmd_1" ) mets_mdWrap = etree.SubElement(mets_rightsMD, METS + "mdWrap", MDTYPE="OTHER") mets_xmlData = etree.SubElement(mets_mdWrap, METS + "xmlData") mets_xmlData.insert(0, dissemin_metadata) # Creation of fileSec mets_fileSec = etree.SubElement(mets_xml, METS + "fileSec") mets_fileGrp = etree.SubElement(mets_fileSec, METS + "fileGrp", USE="CONTENT") mets_file = etree.SubElement(mets_fileGrp, METS + "file", ID="d_file_1") mets_FLocat = etree.SubElement(mets_file, METS + "FLocat") mets_FLocat.set(XLINK + "href", self.filename) # TODO self.get:filename implementieren mets_FLocat.set("LOCTYPE", "URL") # Creation of structMap mets_structMap = etree.SubElement(mets_xml, METS + "structMap") mets_div_dmd = etree.SubElement(mets_structMap, METS + "div", DMDID="d_dmd_1") mets_div_file = etree.SubElement(mets_div_dmd, METS + "div") etree.SubElement(mets_div_file, METS + "fptr", FILEID="d_file_1") return etree.tostring( mets_xml, pretty_print=True, encoding="utf-8", xml_declaration=True ).decode() def _get_mets_container(self, pdf, mets): """ Creates a mets package, i.e. zip for a given file and given schema. The filename in the package is taken from mets. :params pdf: A pdf file :params mets: A mets as lxml etree :returns: a zip object """ s = BytesIO() with ZipFile(s, "w") as zip_file: zip_file.write(pdf, self.filename) zip_file.writestr("mets.xml", mets) return s def _get_xml_dissemin_metadata(self, form): """ This returns the special dissemin metadata as lxml. Currently not all features are supported. :param form: form with user given data :returns: lxml object ready to inserted """ ds = etree.Element(DS + "dissemin") ds.set("version", "1.0") # Information about the depositor ds_depositor = etree.SubElement(ds, DS + "depositor") ds_authentication = etree.SubElement(ds_depositor, DS + "authentication") # We have currently two uthentication methods if self.user.shib.get("username"): ds_authentication.text = "shibboleth" else: ds_authentication.text = "orcid" ds_first_name = etree.SubElement(ds_depositor, DS + "firstName") ds_first_name.text = self.user.first_name ds_last_name = etree.SubElement(ds_depositor, DS + "lastName") ds_last_name.text = self.user.last_name ds_email = etree.SubElement(ds_depositor, DS + "email") ds_email.text = form.cleaned_data["email"] r = Researcher.objects.get(user=self.user) if r.orcid: ds_orcid = etree.SubElement(ds_depositor, DS + "orcid") ds_orcid.text = r.orcid ds_is_contributor = etree.SubElement(ds_depositor, DS + "isContributor") if self.paper.is_owned_by(self.user, flexible=True): ds_is_contributor.text = "true" else: ds_is_contributor.text = "false" # If the user is authenticated via shibboleth, we can find out if the user is a member of the repository's institution ds_identical_institution = etree.SubElement( ds_depositor, DS + "identicalInstitution" ) idp_identifier = get_users_idp(self.user) if ( Institution.objects.get_repository_by_identifier(idp_identifier) == self.repository ): ds_identical_institution.text = "true" else: ds_identical_institution.text = "false" # Information about the publication ds_publication = etree.SubElement(ds, DS + "publication") license = form.cleaned_data.get("license", None) if license is not None: ds_license = etree.SubElement(ds_publication, DS + "license") ds_license_name = etree.SubElement(ds_license, DS + "licenseName") ds_license_name.text = license.license.name ds_license_uri = etree.SubElement(ds_license, DS + "licenseURI") ds_license_uri.text = license.license.uri ds_license_transmit = etree.SubElement(ds_license, DS + "licenseTransmitId") ds_license_transmit.text = license.transmit_id ds_dissemin = etree.SubElement(ds_publication, DS + "disseminId") ds_dissemin.text = str(self.paper.pk) embargo = form.cleaned_data.get("embargo", None) if embargo is not None: ds_embargo = etree.SubElement(ds_publication, DS + "embargoDate") ds_embargo.text = embargo.isoformat() if self.paper_metadata.get("romeo_id") is not None: ds_romeo = etree.SubElement(ds_publication, DS + "romeoId") ds_romeo.text = self.paper_metadata.get("romeo_id") return ds @staticmethod def _get_xml_metadata(form): """ This function returns metadata as lxml etree object, that is ready to inserted into a mets.xml. Override this function in your subclassed protocol. """ raise NotImplementedError("Function not implemented") def get_form_initial_data(self, **kwargs): """ Calls super and returns form's initial values. """ data = super().get_form_initial_data(**kwargs) if self.paper.abstract: data["abstract"] = kill_html(self.paper.abstract) else: self.paper.consolidate_metadata(wait=False) # We try to find an email, if we do not succed, that's ok data["email"] = get_email(self.user) return data def _get_prefered_records(self): """ Returns the prefered records, that is CrossRef, then BASE """ crossref = OaiRecord.objects.filter( about=self.paper, source__identifier="crossref", ) base = OaiRecord.objects.filter(about=self.paper, source__identifier="base") return list(chain(crossref, base)) def refresh_deposit_status(self): """ We refresh all DepositRecords that have the status 'pending' """ if self.repository.update_status_url: s = requests.Session() for deposit_record in DepositRecord.objects.filter( status="pending", repository=self.repository ).select_related("oairecord", "oairecord__about"): logger.info( "Refresh deposit status of {}".format(deposit_record.identifier) ) url = self.repository.update_status_url.format( deposit_record.identifier ) try: r = s.get(url, timeout=10) if r.status_code == 404: logger.info("Received 404, treating as refused") data = {"status": "refused"} else: r.raise_for_status() data = r.json() except Exception as e: logger.exception(e) else: try: status, pub_date, pdf_url = self._validate_deposit_status_data( data ) except Exception: logger.error( "Invalid deposit data when updating record {} with {}".format( deposit_record.pk, data ) ) else: self._update_deposit_record_status( deposit_record, status, pub_date, pdf_url ) def submit_deposit(self, pdf, form): """ Submit paper to the repository. This is a wrapper for the subclasses and calls some protocol specific functions. It creates the METS container and deposits. :param pdf: Filename to the PDF file to submit :param form: The form returned by get_form and completed by the user :returns: DepositResult object """ # Raise error if login credentials are missing. These are not mandatory in Admin UI, since alternatively an API Key can be used, but not for SWORD if not (self.repository.username and self.repository.password): raise DepositError( _( "Username or password not provided for this repository. Please contact the Dissemin team." ) ) metadata = self._get_xml_metadata(form) dissemin_metadata = self._get_xml_dissemin_metadata(form) mets = self._get_mets(metadata, dissemin_metadata) # Logging Metadata self.log("Metadata looks like:") self.log(mets) zipfile = self._get_mets_container(pdf, mets) # Send request to repository self.log("### Preparing request to repository") auth = (self.repository.username, self.repository.password) headers = { "Content-Type": "application/zip", "Content-Disposition": "filename=mets.zip", "Packaging": "http://purl.org/net/sword/package/METSMODS", } self.log("### Sending request") r = requests.post( self.repository.endpoint, auth=auth, headers=headers, data=zipfile.getvalue(), timeout=20, ) self.log_request( r, 201, _("Unable to deposit to repository") + self.repository.name ) # Deposit was successful self.log("This is what the repository yelled back:") self.log(r.text) deposit_result = self._get_deposit_result(r.text) # Set the license for the deposit result if delivered deposit_result = self._add_license_to_deposit_result(deposit_result, form) # Set the embargo_date for the deposit result if delivered deposit_result = self._add_embargo_date_to_deposit_result(deposit_result, form) return deposit_result @staticmethod def _update_deposit_record_status(deposit_record, status, pub_date, pdf_url): """ Updates the status of a deposit record unless it is :param deposit_record: DepositRecord to update :param status: new status, must be in ['refused', 'embargoed', 'published'] :param pub_date: date object, pub_date, only set if status not 'refused' :param pdf_url: string, only set if status not 'refused' """ if status == "refused": deposit_record.status = status deposit_record.save( update_fields=[ "status", ] ) elif status in ["embargoed", "published"]: deposit_record.status = status deposit_record.pub_date = pub_date deposit_record.save(update_fields=["pub_date", "status"]) deposit_record.oairecord.pdf_url = pdf_url deposit_record.oairecord.save(update_fields=["pdf_url"]) deposit_record.oairecord.about.update_availability() deposit_record.oairecord.about.update_index() @staticmethod def _validate_deposit_status_data(data): """ Validates the data and raises Exception if data not valid :param data: Dictonary :returns status, pub_date, pdf_url """ status = data.get("status") pdf_url = data.get("pdf_url", "") if status not in ["pending", "embargoed", "published", "refused"]: raise if status in ["embargoed", "published"]: try: pub_date = datetime.strptime( data.get("publication_date"), "%Y-%m-%d" ).date() except Exception: raise if pdf_url == "": raise else: pub_date = None pdf_url = "" return status, pub_date, pdf_url class SWORDMETSMODSProtocol(SWORDMETSProtocol): """ Protocol that implements MODS metadata with SWORDMETSProtocol """ # We copy the namespace and add MODS namespace, to have all namespaces in METS root element NSMAP = copy.copy(NSMAP) NSMAP["mods"] = MODS_NAMESPACE def __str__(self): """ Return human readable class name """ return "SWORD Protocol (MODS)" def _get_xml_metadata(self, form): """ Creates metadata as lxml etree in MODS """ self.log("### Creating MODS metadata from publication and form") # Creation of root mods_xml = etree.Element(MODS + "mods") mods_xml.set("version", "3.7") # Abstract if form.cleaned_data["abstract"]: mods_abstract = etree.SubElement(mods_xml, MODS + "abstract") mods_abstract.text = form.cleaned_data["abstract"] # Date mods_origin_info = etree.SubElement(mods_xml, MODS + "originInfo") mods_date_issued = etree.SubElement(mods_origin_info, MODS + "dateIssued") mods_date_issued.set("encoding", "w3cdtf") mods_date_issued.text = str(self.paper.pubdate) # DOI if self.paper_metadata.get("doi"): mods_doi = etree.SubElement(mods_xml, MODS + "identifier") mods_doi.set("type", "doi") mods_doi.text = self.paper_metadata.get("doi") # Publisher if self.paper_metadata.get("publisher"): mods_publisher = etree.SubElement(mods_origin_info, MODS + "publisher") mods_publisher.text = self.paper_metadata.get("publisher") # relatedItem related_item = self._get_xml_metadata_relatedItem() if related_item is not None: mods_xml.insert(0, related_item) # Language if len(form.cleaned_data["abstract"]) >= 256: language = langdetect.detect_langs(form.cleaned_data["abstract"])[0] if language.prob >= 0.5: mods_language = etree.SubElement(mods_xml, MODS + "language") mods_language_term = etree.SubElement( mods_language, MODS + "languageTerm" ) mods_language_term.set("type", "code") mods_language_term.set("authority", "rfc3066") mods_language_term.text = language.lang # DDC ddcs = form.cleaned_data.get("ddc", None) if ddcs is not None: for ddc in ddcs: mods_classification_ddc = etree.SubElement( mods_xml, MODS + "classification" ) mods_classification_ddc.set("authority", "ddc") mods_classification_ddc.text = ddc.number_as_string # Name / Authors list for author in self.paper.authors: mods_name = etree.SubElement(mods_xml, MODS + "name") mods_name.set("type", "personal") mods_last_name = etree.SubElement(mods_name, MODS + "namePart") mods_last_name.set("type", "family") mods_last_name.text = author.name.last mods_first_name = etree.SubElement(mods_name, MODS + "namePart") mods_first_name.set("type", "given") mods_first_name.text = author.name.first if author.orcid is not None: mods_orcid = etree.SubElement(mods_name, MODS + "nameIdentifier") mods_orcid.set("type", "orcid") mods_orcid.text = author.orcid # Title mods_title_info = etree.SubElement(mods_xml, MODS + "titleInfo") mods_title = etree.SubElement(mods_title_info, MODS + "title") mods_title.text = self.paper.title # Document type mods_type = etree.SubElement(mods_xml, MODS + "genre") mods_type.text = self.paper.doctype return mods_xml def _get_xml_metadata_relatedItem(self): """ Creates the mods item ``relatedItem`` if available :returns: lxml object or ``None`` """ related_item = None related_item_data = dict() # Set the journal title if self.paper_metadata.get("journal"): related_item_title_info = etree.Element(MODS + "titleInfo") related_item_title = etree.SubElement( related_item_title_info, MODS + "title" ) related_item_title.text = self.paper_metadata.get("journal") related_item_data["title"] = related_item_title_info # Set issn if self.paper_metadata.get("issn"): related_item_issn = etree.Element(MODS + "identifier") related_item_issn.set("type", "issn") related_item_issn.text = self.paper_metadata.get("issn") related_item_data["issn"] = related_item_issn # Set essn if self.paper_metadata.get("essn"): related_item_eissn = etree.Element(MODS + "identifier") related_item_eissn.set("type", "eissn") related_item_eissn.text = self.paper_metadata.get("essn") related_item_data["eissn"] = related_item_eissn # relatedItem - part part = dict() # Set pages if self.paper_metadata.get("pages"): pages = self.paper_metadata.get("pages").split("-", 1) related_item_pages = etree.Element(MODS + "extent") related_item_pages.set("unit", "pages") if len(pages) == 1: related_item_pages_total = etree.SubElement( related_item_pages, MODS + "total" ) related_item_pages_total.text = pages[0] part["pages"] = related_item_pages else: start = pages[0] end = pages[1] related_item_pages_start = etree.SubElement( related_item_pages, MODS + "start" ) related_item_pages_start.text = start related_item_pages_start = etree.SubElement( related_item_pages, MODS + "end" ) related_item_pages_start.text = end part["pages"] = related_item_pages # Set issue if self.paper_metadata.get("issue"): related_item_issue = etree.Element(MODS + "detail") related_item_issue.set("type", "issue") related_item_issue_number = etree.SubElement( related_item_issue, MODS + "number" ) related_item_issue_number.text = self.paper_metadata.get("issue") part["issue"] = related_item_issue # Set volume if self.paper_metadata.get("volume"): related_item_volume = etree.Element(MODS + "detail") related_item_volume.set("type", "volume") related_item_volume_number = etree.SubElement( related_item_volume, MODS + "number" ) related_item_volume_number.text = self.paper_metadata.get("volume") part["volume"] = related_item_volume # Make parts if existing if len(part) >= 1: related_item_part = etree.Element(MODS + "part") for item in part.values(): related_item_part.insert(0, item) related_item_data["part"] = related_item_part # Make relatedItem if existing if len(related_item_data) >= 1: related_item = etree.Element(MODS + "relatedItem") for item in related_item_data.values(): related_item.insert(0, item) return related_item protocol_registry.register(SWORDMETSMODSProtocol)
formats
mp4
# Copyright 2005 Alexey Bobyakov <claymore.ws@gmail.com>, Joe Wreschnig # Copyright 2006 Lukas Lalinsky # 2020 Nick Boultbee # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. from mutagen.mp4 import MP4, MP4Cover from quodlibet.util.path import get_temp_cover_file from quodlibet.util.string import decode from ._audio import AudioFile from ._image import EmbeddedImage from ._misc import AudioFileError, translate_errors class MP4File(AudioFile): format = "MPEG-4" mimes = ["audio/mp4", "audio/x-m4a", "audio/mpeg4", "audio/aac"] __translate = { "\xa9nam": "title", "\xa9alb": "album", "\xa9ART": "artist", "aART": "albumartist", "\xa9wrt": "composer", "\xa9day": "date", "\xa9cmt": "comment", "\xa9grp": "grouping", "\xa9gen": "genre", "tmpo": "bpm", "\xa9too": "encodedby", # FIXME: \xa9enc should be encodedby "desc": "description", # (usually used in podcasts) "cprt": "copyright", "soal": "albumsort", "soaa": "albumartistsort", "soar": "artistsort", "sonm": "titlesort", "soco": "composersort", "----:com.apple.iTunes:CONDUCTOR": "conductor", "----:com.apple.iTunes:DISCSUBTITLE": "discsubtitle", "----:com.apple.iTunes:LANGUAGE": "language", "----:com.apple.iTunes:MOOD": "mood", "----:com.apple.iTunes:MusicBrainz Artist Id": "musicbrainz_artistid", "----:com.apple.iTunes:MusicBrainz Track Id": "musicbrainz_trackid", "----:com.apple.iTunes:MusicBrainz Release Track Id": "musicbrainz_releasetrackid", "----:com.apple.iTunes:MusicBrainz Album Id": "musicbrainz_albumid", "----:com.apple.iTunes:MusicBrainz Album Artist Id": "musicbrainz_albumartistid", "----:com.apple.iTunes:MusicIP PUID": "musicip_puid", "----:com.apple.iTunes:MusicBrainz Album Status": "musicbrainz_albumstatus", "----:com.apple.iTunes:MusicBrainz Album Type": "musicbrainz_albumtype", "----:com.apple.iTunes:MusicBrainz Album Release Country": "releasecountry", "----:com.apple.iTunes:MusicBrainz Release Group Id": "musicbrainz_releasegroupid", "----:com.apple.iTunes:replaygain_album_gain": "replaygain_album_gain", "----:com.apple.iTunes:replaygain_album_peak": "replaygain_album_peak", "----:com.apple.iTunes:replaygain_track_gain": "replaygain_track_gain", "----:com.apple.iTunes:replaygain_track_peak": "replaygain_track_peak", "----:com.apple.iTunes:replaygain_reference_loudness": "replaygain_reference_loudness", } __rtranslate = dict((v, k) for k, v in __translate.items()) __tupletranslate = { "disk": "discnumber", "trkn": "tracknumber", } __rtupletranslate = dict((v, k) for k, v in __tupletranslate.items()) def __init__(self, filename): with translate_errors(): audio = MP4(filename) self["~codec"] = audio.info.codec_description self["~#length"] = audio.info.length self["~#bitrate"] = int(audio.info.bitrate / 1000) if audio.info.channels: self["~#channels"] = audio.info.channels self["~#samplerate"] = audio.info.sample_rate self["~#bitdepth"] = audio.info.bits_per_sample for key, values in audio.items(): if key in self.__tupletranslate: if values: name = self.__tupletranslate[key] cur, total = values[0] if total: self[name] = "%d/%d" % (cur, total) else: self[name] = str(cur) elif key in self.__translate: name = self.__translate[key] if key == "tmpo": self[name] = "\n".join(map(str, values)) elif key.startswith("----"): self[name] = "\n".join( map(lambda v: decode(v).strip("\x00"), values) ) else: self[name] = "\n".join(values) elif key == "covr": self.has_images = True self.sanitize(filename) def write(self): with translate_errors(): audio = MP4(self["~filename"]) for key in list(self.__translate.keys()) + list(self.__tupletranslate.keys()): try: del audio[key] except KeyError: pass for key in self.realkeys(): try: name = self.__rtranslate[key] except KeyError: continue values = self.list(key) if name == "tmpo": values = list(map(lambda v: int(round(float(v))), values)) elif name.startswith("----"): values = list(map(lambda v: v.encode("utf-8"), values)) audio[name] = values track, tracks = self("~#track"), self("~#tracks", 0) if track: audio["trkn"] = [(track, tracks)] disc, discs = self("~#disc"), self("~#discs", 0) if disc: audio["disk"] = [(disc, discs)] with translate_errors(): audio.save() self.sanitize() def can_multiple_values(self, key=None): if key is None: return [] return False def can_change(self, key=None): OK = list(self.__rtranslate.keys()) + list(self.__rtupletranslate.keys()) if key is None: return OK else: return super().can_change(key) and (key in OK) def get_images(self): images = [] try: tag = MP4(self["~filename"]) except Exception: return [] for cover in tag.get("covr", []): if cover.imageformat == MP4Cover.FORMAT_JPEG: mime = "image/jpeg" elif cover.imageformat == MP4Cover.FORMAT_PNG: mime = "image/png" else: mime = "image/" f = get_temp_cover_file(cover) images.append(EmbeddedImage(f, mime)) return images def get_primary_image(self): try: tag = MP4(self["~filename"]) except Exception: return for cover in tag.get("covr", []): if cover.imageformat == MP4Cover.FORMAT_JPEG: mime = "image/jpeg" elif cover.imageformat == MP4Cover.FORMAT_PNG: mime = "image/png" else: mime = "image/" f = get_temp_cover_file(cover) return EmbeddedImage(f, mime) can_change_images = True def clear_images(self): """Delete all embedded images""" with translate_errors(): tag = MP4(self["~filename"]) tag.pop("covr", None) tag.save() self.has_images = False def set_image(self, image): """Replaces all embedded images by the passed image""" if image.mime_type == "image/jpeg": image_format = MP4Cover.FORMAT_JPEG elif image.mime_type == "image/png": image_format = MP4Cover.FORMAT_PNG else: raise AudioFileError("mp4: Unsupported image format %r" % image.mime_type) with translate_errors(): tag = MP4(self["~filename"]) try: data = image.read() except EnvironmentError: return cover = MP4Cover(data, image_format) tag["covr"] = [cover] with translate_errors(): tag.save() self.has_images = True loader = MP4File types = [MP4File] extensions = [".mp4", ".m4a", ".m4b", ".m4v", ".3gp", ".3g2", ".3gp2"]
fcbt
CreateModule
# FreeCAD MakeNewBuildNbr script # (c) 2003 Werner Mayer # # Creates a new application # *************************************************************************** # * (c) Werner Mayer (werner.wm.mayer@gmx.de) 2003 * # * * # * This file is part of the FreeCAD CAx development system. * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * FreeCAD is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Lesser General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with FreeCAD; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # * Werner Mayer 2003 * # *************************************************************************** import os import re import sys import MakeAppTools FilFilter = [ "^.*\\.o$", "^.*Makefile$", "^.*\\.la$", "^.*\\.lo$", "^.*\\.positions$", "^.*\\.aux$", "^.*\\.bsc$", "^.*\\.exp$", "^.*\\.ilg$", "^.*\\.ilk$", "^.*\\.in$", "^.*\\.mak$", "^.*\\.ncb$", "^.*\\.opt$", "^.*\\.pyc$", "^.*\\.pyd$", "^.*\\.pdb$", "^.*\\.plg$", ] DirFilter = [ "^.*\\.o$", "^Debug$", "^DebugCmd$", "^DebugPy$", "^Release$", "^ReleaseCmd$", "^ReleasePy$", "^Attic$", "^CVS$", "^\\.svn$", "^\\.deps$", "^\\.libs$", ] def SetupFilter(MatchList): RegList = [] for regexp in MatchList: a = re.compile(regexp) RegList.append(a) return RegList def createApp(Application): """ Create a new application by copying the template """ # create directory ../Mod/<Application> if not os.path.isdir("../Mod/" + Application): os.mkdir("../Mod/" + Application) else: sys.stdout.write(Application + " already exists. Please enter another name.\n") sys.exit() # copying files from _TEMPLATE_ to ../Mod/<Application> sys.stdout.write("Copying files...") MakeAppTools.copyTemplate( "_TEMPLATE_", "../Mod/" + Application, "_TEMPLATE_", Application, SetupFilter(FilFilter), SetupFilter(DirFilter), ) sys.stdout.write("Ok\n") # replace the _TEMPLATE_ string by <Application> sys.stdout.write("Modifying files...\n") MakeAppTools.replaceTemplate("../Mod/" + Application, "_TEMPLATE_", Application) MakeAppTools.replaceTemplate( "../Mod/" + Application, "${CMAKE_SOURCE_DIR}/src/Tools/", "${CMAKE_SOURCE_DIR}/src/Mod/", ) # make the configure script executable # os.chmod("../Mod/" + Application + "/configure", 0777); sys.stdout.write("Modifying files done.\n") sys.stdout.write(Application + " module created successfully.\n") def validateApp(AppName): """ Validates the class name """ if len(AppName) < 2: sys.stdout.write("Too short name: '" + AppName + "'\n") sys.exit() # name is long enough clName = "class " + AppName + ": self=0" try: exec(clName) except Exception: # Invalid class name sys.stdout.write("Invalid name: '" + AppName + "'\n") sys.exit() sys.stdout.write("Please enter a name for your application:") sys.stdout.flush() AppName = sys.stdin.readline()[:-1] validateApp(AppName) createApp(AppName)
sgui
transport
import time from sglib import constants from sglib.lib import strings as sg_strings from sglib.lib import util from sglib.lib.translate import _ from sglib.log import LOG from sglib.math import db_to_lin from sglib.models.theme import get_asset_path from sgui import shared, widgets from sgui.sgqt import * class TransportWidget: def __init__(self, scaler): self.suppress_osc = True self.last_clock_text = None self.last_open_dir = util.HOME self.toolbar = QToolBar() self.toolbar.setIconSize(QtCore.QSize(36, 36)) self.toolbar.setObjectName("transport_panel") self.group_box = self.toolbar self.menu_button = QToolButton(self.toolbar) self.menu_button.setIcon( QIcon( get_asset_path("menu.svg"), ), ) self.menu_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) self.toolbar.addWidget(self.menu_button) self.toolbar.addSeparator() self.play_group = QActionGroup(self.toolbar) icon = QIcon() icon.addPixmap( QPixmap( get_asset_path("play-on.svg"), ), QIcon.Mode.Normal, QIcon.State.On, ) icon.addPixmap( QPixmap( get_asset_path("play-off.svg"), ), QIcon.Mode.Normal, QIcon.State.Off, ) self.play_button = QAction(icon, "", self.play_group) self.play_button.setToolTip( "Begin playback. Press spacebar to toggle", ) self.play_button.setCheckable(True) self.play_button.triggered.connect(self.on_play) self.toolbar.addAction(self.play_button) icon = QIcon() icon.addPixmap( QPixmap( get_asset_path("stop-on.svg"), ), QIcon.Mode.Normal, QIcon.State.On, ) icon.addPixmap( QPixmap( get_asset_path("stop-off.svg"), ), QIcon.Mode.Normal, QIcon.State.Off, ) self.stop_button = QAction(icon, "", self.play_group) self.stop_button.setToolTip( "Stop playback or recording. Press spacebar to toggle", ) self.stop_button.setCheckable(True) self.stop_button.setChecked(True) self.stop_button.triggered.connect(self.on_stop) self.toolbar.addAction(self.stop_button) icon = QIcon() icon.addPixmap( QPixmap( get_asset_path("rec-on.svg"), ), QIcon.Mode.Normal, QIcon.State.On, ) icon.addPixmap( QPixmap( get_asset_path("rec-off.svg"), ), QIcon.Mode.Normal, QIcon.State.Off, ) self.rec_button = QAction(icon, "", self.play_group) self.rec_button.setToolTip( "Stop playback or recording. Press spacebar to toggle", ) self.rec_button.setCheckable(True) self.rec_button.triggered.connect(self.on_rec) self.toolbar.addAction(self.rec_button) self.clock = QLCDNumber() self.clock.setToolTip( "The real time of the project, in minutes:seconds.1/10s. " "For musical time, see the sequencer timeline" ) self.clock.setObjectName("transport_clock") self.clock.setDigitCount(7) self.clock.setFixedHeight(42) self.clock.setFixedWidth(180) self.clock.display("0:00.0") self.toolbar.addWidget(self.clock) self.panic_button = QToolButton(self.toolbar) self.panic_button.setIcon( QIcon( get_asset_path("panic.svg"), ), ) self.panic_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) self.panic_menu = QMenu() self.panic_button.setMenu(self.panic_menu) self.all_notes_off_action = QAction("All notes off") self.all_notes_off_action.setToolTip( "Send a note off MIDI event on every note, to every plugin. " "Use this if you have hung notes" ) self.panic_menu.addAction(self.all_notes_off_action) self.all_notes_off_action.triggered.connect(self.on_panic) self.panic_menu.addSeparator() self.stop_engine_action = QAction(_("Stop Audio Engine")) self.stop_engine_action.setToolTip( "Stop the audio engine. You will need to restart the " "application. Use this in the event of loud unexpected noises " "coming out of the audio engine" ) self.panic_menu.addAction(self.stop_engine_action) self.stop_engine_action.triggered.connect(self.on_stop_engine) self.toolbar.addWidget(self.panic_button) self.host_widget = QWidget(self.toolbar) self.host_widget.setObjectName("transport_widget") self.host_layout = QVBoxLayout(self.host_widget) self.host_layout.setContentsMargins(1, 1, 1, 1) self.host_layout.setSpacing(1) host_label = QLabel("Host") host_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) host_label.setObjectName("transport_widget") self.host_layout.addWidget(host_label) self.toolbar.addWidget( self.host_widget, ) self.host_combobox = QComboBox() self.host_layout.addWidget(self.host_combobox) self.host_combobox.setMinimumWidth(85) self.host_combobox.addItems(["DAW", "Wave Editor"]) self.host_combobox.currentIndexChanged.connect( shared.MAIN_WINDOW.set_host, ) self.host_combobox.setToolTip( "The host to use. DAW is a full digital audio workstation " "optimized for producing electronic music. Wave Editor " "is a basic wave editor for simple editing tasks" ) knob_size = 40 self.main_vol_knob = widgets.PixmapKnob( knob_size, -480, 0, arc_width_pct=0.0, arc_space=0.0, fg_svg="default", bg_svg="default_bg", ) self.load_main_vol() self.toolbar.addWidget(self.main_vol_knob) self.main_vol_knob.valueChanged.connect(self.main_vol_changed) self.main_vol_knob.sliderReleased.connect(self.main_vol_released) self.main_vol_knob.setToolTip( "Master volume. Only affects your monitor speakers, not renders." ) self.suppress_osc = False self.controls_to_disable = (self.menu_button, self.host_combobox) def current_host(self) -> int: return self.host_combobox.currentIndex() def enable_controls(self, a_enabled): for f_control in self.controls_to_disable: f_control.setEnabled(a_enabled) def on_stop_engine(self): constants.IPC.kill_engine() QMessageBox.warning( None, None, ( "Audio engine has been requested to stop immediately. " "You will need to close and re-open Stargate DAW to " "continue using" ), ) if shared.IS_PLAYING: self.stop_button.trigger() def main_vol_released(self): util.set_file_setting("main_vol", self.main_vol_knob.value()) def load_main_vol(self): self.main_vol_knob.setValue( util.get_file_setting( "main_vol", int, 0, ), ) def main_vol_changed(self, a_val): if a_val == 0: f_result = 1.0 else: f_result = db_to_lin(float(a_val) * 0.1) constants.IPC.main_vol(f_result) def set_time(self, a_text): if a_text == self.last_clock_text: return self.last_clock_text = a_text self.clock.display(a_text) def on_spacebar(self): if shared.IS_PLAYING: self.stop_button.trigger() else: self.play_button.trigger() def on_play(self): if not self.play_button.isChecked(): return if shared.IS_PLAYING: self.play_button.setChecked(True) return if shared.IS_RECORDING: self.rec_button.setChecked(True) return if shared.MAIN_WINDOW.current_module.TRANSPORT.on_play(): shared.IS_PLAYING = True self.enable_controls(False) else: self.stop_button.setChecked(True) def on_stop(self): if not self.stop_button.isChecked(): return if not shared.IS_PLAYING and not shared.IS_RECORDING: return shared.MAIN_WINDOW.current_module.TRANSPORT.on_stop() shared.IS_PLAYING = False shared.IS_RECORDING = False self.enable_controls(True) time.sleep(0.1) def on_rec(self): if not self.rec_button.isChecked(): return if shared.IS_RECORDING: return if shared.IS_PLAYING: self.play_button.setChecked(True) return if shared.MAIN_WINDOW.current_module.TRANSPORT.on_rec(): shared.IS_PLAYING = True shared.IS_RECORDING = True self.enable_controls(False) else: self.stop_button.setChecked(True) def on_panic(self): LOG.info("Sending panic message to engine") shared.MAIN_WINDOW.current_module.TRANSPORT.on_panic()
migrations
0061_featureflag
# Generated by Django 3.0.6 on 2020-06-18 08:59 import django.contrib.postgres.fields.jsonb import django.db.models.deletion import django.utils.timezone from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("posthog", "0060_auto_20200616_0746"), ] operations = [ migrations.CreateModel( name="FeatureFlag", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(max_length=400)), ("key", models.CharField(max_length=400)), ( "filters", django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), ("rollout_percentage", models.IntegerField(blank=True, null=True)), ("created_at", models.DateTimeField(default=django.utils.timezone.now)), ("deleted", models.BooleanField(default=False)), ("active", models.BooleanField(default=True)), ( "created_by", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, ), ), ( "team", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="posthog.Team" ), ), ], ), migrations.AddConstraint( model_name="featureflag", constraint=models.UniqueConstraint( fields=("team", "key"), name="unique key for team" ), ), ]
session
gnome
# Copyright 2018 Christoph Reiter # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. from gi.repository import Gio, GLib from quodlibet import print_d, print_w from ._base import SessionClient, SessionError class GnomeSessionClient(SessionClient): DBUS_NAME = "org.gnome.SessionManager" DBUS_OBJECT_PATH = "/org/gnome/SessionManager" DBUS_MAIN_INTERFACE = "org.gnome.SessionManager" DBUS_CLIENT_INTERFACE = "org.gnome.SessionManager.ClientPrivate" def __init__(self): super().__init__() self._client_priv = None self._client_path = None self._sig_id = None def open(self, app): print_d("Connecting with gnome session manager") try: bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) session_mgr = Gio.DBusProxy.new_sync( bus, Gio.DBusProxyFlags.NONE, None, self.DBUS_NAME, self.DBUS_OBJECT_PATH, self.DBUS_MAIN_INTERFACE, None, ) if session_mgr.get_name_owner() is None: raise SessionError("%s unowned" % self.DBUS_NAME) client_path = session_mgr.RegisterClient("(ss)", app.id, "") if client_path is None: # https://github.com/quodlibet/quodlibet/issues/2435 raise SessionError("Broken session manager implementation, likely LXDE") client_priv = Gio.DBusProxy.new_sync( bus, Gio.DBusProxyFlags.NONE, None, self.DBUS_NAME, client_path, self.DBUS_CLIENT_INTERFACE, None, ) def g_signal_cb(proxy, sender, signal, args): if signal == "EndSession": print_d("GSM sent EndSession: going down") proxy.EndSessionResponse("(bs)", True, "") app.quit() elif signal == "Stop": print_d("GSM sent Stop: going down") app.quit() elif signal == "QueryEndSession": print_d("GSM sent QueryEndSession") proxy.EndSessionResponse("(bs)", True, "") self._sig_id = client_priv.connect("g-signal", g_signal_cb) self._client_priv = client_priv self._client_path = client_path print_d("Connected with gnome session manager: %s" % client_path) except GLib.Error as e: raise SessionError(e) def close(self): if self._client_priv is None: return self._client_priv.disconnect(self._sig_id) self._sig_id = None try: bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) session_mgr = Gio.DBusProxy.new_sync( bus, Gio.DBusProxyFlags.NONE, None, self.DBUS_NAME, self.DBUS_OBJECT_PATH, self.DBUS_MAIN_INTERFACE, None, ) session_mgr.UnregisterClient("(o)", self._client_path) except GLib.Error as e: print_w(str(e)) print_d("Disconnected from gnome session manager: %s" % self._client_path) self._client_path = None
accounts
SmoozedCom
# -*- coding: utf-8 -*- import hashlib import json import time from ..base.multi_account import MultiAccount class SmoozedCom(MultiAccount): __name__ = "SmoozedCom" __type__ = "account" __version__ = "0.14" __status__ = "testing" __config__ = [ ("mh_mode", "all;listed;unlisted", "Filter downloaders to use", "all"), ("mh_list", "str", "Downloader list (comma separated)", ""), ("mh_interval", "int", "Reload interval in hours", 12), ] __description__ = """Smoozed.com account plugin""" __license__ = "GPLv3" __authors__ = [(None, None)] def grab_hosters(self, user, password, data): return self.get_data("hosters") def grab_info(self, user, password, data): status = self.get_account_status(user, password) self.log_debug(status) if status["state"] != "ok": info = {"validuntil": None, "trafficleft": None, "premium": False} else: #: Parse account info info = { "validuntil": float(status["data"]["user"]["user_premium"]), "trafficleft": max( 0, status["data"]["traffic"][1] - status["data"]["traffic"][0] ) << 10, "session": status["data"]["session_key"], "hosters": [hoster["name"] for hoster in status["data"]["hoster"]], } if info["validuntil"] < time.time(): if float(status["data"]["user"].get("user_trial", 0)) > time.time(): info["premium"] = True else: info["premium"] = False else: info["premium"] = True return info def signin(self, user, password, data): #: Get user data from premiumize.me status = self.get_account_status(user, password) #: Check if user and password are valid if status["state"] != "ok": self.fail_login() def get_account_status(self, user, password): b_password = password.encode() encrypted = hashlib.pbkdf2_hmac("sha256", b_password, b_password, 1000).hex()[ 32 ] html = self.load( "http://www2.smoozed.com/api/login", get={"auth": user, "password": encrypted}, ) return json.loads(html)
extras
cairoextras
import ctypes import cairo # from: http://cairographics.org/freetypepython/ class PycairoContext(ctypes.Structure): _fields_ = [ ("PyObject_HEAD", ctypes.c_byte * object.__basicsize__), ("ctx", ctypes.c_void_p), ("base", ctypes.c_void_p), ] _initialized = False def create_cairo_font_face_for_file(filename, faceindex=0, loadoptions=0): global _initialized global _freetype_so global _cairo_so global _ft_lib global _surface CAIRO_STATUS_SUCCESS = 0 FT_Err_Ok = 0 if not _initialized: # find shared objects _freetype_so = ctypes.CDLL("libfreetype.so.6") _cairo_so = ctypes.CDLL("libcairo.so.2") # initialize freetype _ft_lib = ctypes.c_void_p() if FT_Err_Ok != _freetype_so.FT_Init_FreeType(ctypes.byref(_ft_lib)): raise OSError("Error initialising FreeType library.") _surface = cairo.ImageSurface(cairo.FORMAT_A8, 0, 0) _initialized = True # create freetype face ft_face = ctypes.c_void_p() cairo_ctx = cairo.Context(_surface) cairo_t = PycairoContext.from_address(id(cairo_ctx)).ctx _cairo_so.cairo_ft_font_face_create_for_ft_face.restype = ctypes.c_void_p if FT_Err_Ok != _freetype_so.FT_New_Face( _ft_lib, filename, faceindex, ctypes.byref(ft_face) ): raise Exception("Error creating FreeType font face for " + filename) # create cairo font face for freetype face cr_face = _cairo_so.cairo_ft_font_face_create_for_ft_face(ft_face, loadoptions) if CAIRO_STATUS_SUCCESS != _cairo_so.cairo_font_face_status(cr_face): raise Exception("Error creating cairo font face for " + filename) _cairo_so.cairo_set_font_face(cairo_t, cr_face) if CAIRO_STATUS_SUCCESS != _cairo_so.cairo_status(cairo_t): raise Exception("Error creating cairo font face for " + filename) face = cairo_ctx.get_font_face() return face if __name__ == "__main__": face = create_cairo_font_face_for_file( "/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-B.ttf", 0 ) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 128, 128) ctx = cairo.Context(surface) ctx.set_font_face(face) ctx.set_font_size(30) ctx.move_to(0, 44) ctx.show_text("Hello,") ctx.move_to(30, 74) ctx.show_text("world!") del ctx surface.write_to_png("hello.png")
Gui
PocketBase
# -*- coding: utf-8 -*- # *************************************************************************** # * Copyright (c) 2017 sliptonic <shopinthewoods@gmail.com> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** import FreeCAD import FreeCADGui import Path import Path.Base.Gui.Util as PathGuiUtil import Path.Op.Gui.Base as PathOpGui import Path.Op.Pocket as PathPocket import PathGui __title__ = "Path Pocket Base Operation UI" __author__ = "sliptonic (Brad Collette)" __url__ = "https://www.freecad.org" __doc__ = "Base page controller and command implementation for path pocket operations." if False: Path.Log.setLevel(Path.Log.Level.DEBUG, Path.Log.thisModule()) Path.Log.trackModule(Path.Log.thisModule()) else: Path.Log.setLevel(Path.Log.Level.INFO, Path.Log.thisModule()) translate = FreeCAD.Qt.translate FeaturePocket = 0x01 FeatureFacing = 0x02 FeatureOutline = 0x04 FeatureRestMachining = 0x08 class TaskPanelOpPage(PathOpGui.TaskPanelPage): """Page controller class for pocket operations, supports: FeaturePocket ... used for pocketing operation FeatureFacing ... used for face milling operation FeatureOutline ... used for pocket-shape operation """ def pocketFeatures(self): """pocketFeatures() ... return which features of the UI are supported by the operation. FeaturePocket ... used for pocketing operation FeatureFacing ... used for face milling operation FeatureOutline ... used for pocket-shape operation Must be overwritten by subclasses""" pass def getForm(self): """getForm() ... returns UI, adapted to the results from pocketFeatures()""" form = FreeCADGui.PySideUic.loadUi(":/panels/PageOpPocketFullEdit.ui") comboToPropertyMap = [ ("cutMode", "CutMode"), ("offsetPattern", "OffsetPattern"), ] enumTups = PathPocket.ObjectPocket.pocketPropertyEnumerations(dataType="raw") self.populateCombobox(form, enumTups, comboToPropertyMap) if not FeatureFacing & self.pocketFeatures(): form.facingWidget.hide() form.clearEdges.hide() if FeaturePocket & self.pocketFeatures(): form.extraOffset_label.setText(translate("PathPocket", "Pass Extension")) form.extraOffset.setToolTip( translate( "PathPocket", "The distance the facing operation will extend beyond the boundary shape.", ) ) if not (FeatureOutline & self.pocketFeatures()): form.useOutline.hide() if not (FeatureRestMachining & self.pocketFeatures()): form.useRestMachining.hide() # if True: # # currently doesn't have an effect or is experimental # form.minTravel.hide() return form def updateMinTravel(self, obj, setModel=True): if obj.UseStartPoint: self.form.minTravel.setEnabled(True) else: self.form.minTravel.setChecked(False) self.form.minTravel.setEnabled(False) if setModel and obj.MinTravel != self.form.minTravel.isChecked(): obj.MinTravel = self.form.minTravel.isChecked() def updateZigZagAngle(self, obj, setModel=True): if obj.OffsetPattern in ["Offset"]: self.form.zigZagAngle.setEnabled(False) else: self.form.zigZagAngle.setEnabled(True) if setModel: PathGuiUtil.updateInputField(obj, "ZigZagAngle", self.form.zigZagAngle) def getFields(self, obj): """getFields(obj) ... transfers values from UI to obj's properties""" if obj.CutMode != str(self.form.cutMode.currentData()): obj.CutMode = str(self.form.cutMode.currentData()) if obj.StepOver != self.form.stepOverPercent.value(): obj.StepOver = self.form.stepOverPercent.value() if obj.OffsetPattern != str(self.form.offsetPattern.currentData()): obj.OffsetPattern = str(self.form.offsetPattern.currentData()) PathGuiUtil.updateInputField(obj, "ExtraOffset", self.form.extraOffset) self.updateToolController(obj, self.form.toolController) self.updateCoolant(obj, self.form.coolantController) self.updateZigZagAngle(obj) if obj.UseStartPoint != self.form.useStartPoint.isChecked(): obj.UseStartPoint = self.form.useStartPoint.isChecked() if obj.UseRestMachining != self.form.useRestMachining.isChecked(): obj.UseRestMachining = self.form.useRestMachining.isChecked() if FeatureOutline & self.pocketFeatures(): if obj.UseOutline != self.form.useOutline.isChecked(): obj.UseOutline = self.form.useOutline.isChecked() self.updateMinTravel(obj) if FeatureFacing & self.pocketFeatures(): print(obj.BoundaryShape) print(self.form.boundaryShape.currentText()) print(self.form.boundaryShape.currentData()) if obj.BoundaryShape != str(self.form.boundaryShape.currentData()): obj.BoundaryShape = str(self.form.boundaryShape.currentData()) if obj.ClearEdges != self.form.clearEdges.isChecked(): obj.ClearEdges = self.form.clearEdges.isChecked() def setFields(self, obj): """setFields(obj) ... transfers obj's property values to UI""" self.form.stepOverPercent.setValue(obj.StepOver) self.form.extraOffset.setText( FreeCAD.Units.Quantity( obj.ExtraOffset.Value, FreeCAD.Units.Length ).UserString ) self.form.useStartPoint.setChecked(obj.UseStartPoint) self.form.useRestMachining.setChecked(obj.UseRestMachining) if FeatureOutline & self.pocketFeatures(): self.form.useOutline.setChecked(obj.UseOutline) self.form.zigZagAngle.setText( FreeCAD.Units.Quantity(obj.ZigZagAngle, FreeCAD.Units.Angle).UserString ) self.updateZigZagAngle(obj, False) self.form.minTravel.setChecked(obj.MinTravel) self.updateMinTravel(obj, False) self.selectInComboBox(obj.OffsetPattern, self.form.offsetPattern) self.selectInComboBox(obj.CutMode, self.form.cutMode) self.setupToolController(obj, self.form.toolController) self.setupCoolant(obj, self.form.coolantController) if FeatureFacing & self.pocketFeatures(): self.selectInComboBox(obj.BoundaryShape, self.form.boundaryShape) self.form.clearEdges.setChecked(obj.ClearEdges) def getSignalsForUpdate(self, obj): """getSignalsForUpdate(obj) ... return list of signals for updating obj""" signals = [] signals.append(self.form.cutMode.currentIndexChanged) signals.append(self.form.offsetPattern.currentIndexChanged) signals.append(self.form.stepOverPercent.editingFinished) signals.append(self.form.zigZagAngle.editingFinished) signals.append(self.form.toolController.currentIndexChanged) signals.append(self.form.extraOffset.editingFinished) signals.append(self.form.useStartPoint.clicked) signals.append(self.form.useRestMachining.clicked) signals.append(self.form.useOutline.clicked) signals.append(self.form.minTravel.clicked) signals.append(self.form.coolantController.currentIndexChanged) if FeatureFacing & self.pocketFeatures(): signals.append(self.form.boundaryShape.currentIndexChanged) signals.append(self.form.clearEdges.clicked) return signals
data
serial_port_connection
# -------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer # Homepage: http://www.softwarepublico.gov.br # Contact: invesalius@cti.gov.br # License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt) # -------------------------------------------------------------------------- # Este programa e software livre; voce pode redistribui-lo e/ou # modifica-lo sob os termos da Licenca Publica Geral GNU, conforme # publicada pela Free Software Foundation; de acordo com a versao 2 # da Licenca. # # Este programa eh distribuido na expectativa de ser util, mas SEM # QUALQUER GARANTIA; sem mesmo a garantia implicita de # COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM # PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais # detalhes. # -------------------------------------------------------------------------- import queue import threading import time from invesalius import constants from invesalius.pubsub import pub as Publisher class SerialPortConnection(threading.Thread): def __init__(self, com_port, baud_rate, serial_port_queue, event, sleep_nav): """ Thread created to communicate using the serial port to interact with software during neuronavigation. """ threading.Thread.__init__(self, name="Serial port") self.connection = None self.stylusplh = False self.com_port = com_port self.baud_rate = baud_rate self.serial_port_queue = serial_port_queue self.event = event self.sleep_nav = sleep_nav def Connect(self): if self.com_port is None: print("Serial port init error: COM port is unset.") return try: import serial self.connection = serial.Serial( self.com_port, baudrate=self.baud_rate, timeout=0 ) print("Connection to port {} opened.".format(self.com_port)) Publisher.sendMessage("Serial port connection", state=True) except: print( "Serial port init error: Connecting to port {} failed.".format( self.com_port ) ) def Disconnect(self): if self.connection: self.connection.close() print("Connection to port {} closed.".format(self.com_port)) Publisher.sendMessage("Serial port connection", state=False) def SendPulse(self): try: self.connection.send_break(constants.PULSE_DURATION_IN_MILLISECONDS / 1000) Publisher.sendMessage("Serial port pulse triggered") except: print("Error: Serial port could not be written into.") def run(self): while not self.event.is_set(): trigger_on = False try: lines = self.connection.readlines() if lines: trigger_on = True except: print("Error: Serial port could not be read.") if self.stylusplh: trigger_on = True self.stylusplh = False try: self.serial_port_queue.put_nowait(trigger_on) except queue.Full: print("Error: Serial port queue full.") time.sleep(self.sleep_nav) # XXX: This is needed here because the serial port queue has to be read # at least as fast as it is written into, otherwise it will eventually # become full. Reading is done in another thread, which has the same # sleeping parameter sleep_nav between consecutive runs as this thread. # However, a single run of that thread takes longer to finish than a # single run of this thread, causing that thread to lag behind. Hence, # the additional sleeping here to ensure that this thread lags behind the # other thread and not the other way around. However, it would be nice to # handle the timing dependencies between the threads in a more robust way. # time.sleep(0.3) else: self.Disconnect()
mystran
add_con_force
# *************************************************************************** # * Copyright (c) 2021 Bernd Hahnebach <bernd@bimstatik.org> * # * * # * This file is part of the FreeCAD CAx development system. * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** __title__ = "Mystran add force constraint" __author__ = "Bernd Hahnebach" __url__ = "http://www.freecad.org" ## \addtogroup FEM # @{ def add_con_force(f, model, mystran_writer): # generate pyNastran code # force card scale_factors = [] load_ids = [] force_code = "# force cards, mesh node loads\n" for i, femobj in enumerate(mystran_writer.member.cons_force): sid = i + 2 # 1 will be the id of the load card scale_factors.append(1.0) load_ids.append(sid) force_obj = femobj["Object"] # print(force_obj.Name) force_code += "# {}\n".format(force_obj.Name) dirvec = femobj["Object"].DirectionVector print(femobj["NodeLoadTable"]) for ref_shape in femobj["NodeLoadTable"]: force_code += "# {}\n".format(ref_shape[0]) for n in sorted(ref_shape[1]): node_load = ref_shape[1][n] force_code += "model.add_force(sid={}, node={}, mag={}, xyz=({}, {}, {}))\n".format( sid, n, node_load, dirvec.x, dirvec.y, dirvec.z ) force_code += "\n" # generate calce factors lists # load card, static load combinations load_code = ( "model.add_load(sid=1, scale=1.0, scale_factors={}, load_ids={})\n\n\n".format( scale_factors, load_ids ) ) pynas_code = "{}\n{}".format(force_code, load_code) # print(pynas_code) # write the pyNastran code f.write(pynas_code) # execute pyNastran code to add data to the model # print(model.get_bdf_stats()) exec(pynas_code) # print(model.get_bdf_stats()) return model ## @}
draftviewproviders
view_base
# *************************************************************************** # * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> * # * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> * # * Copyright (c) 2019 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** """Provides the viewprovider code for the base Draft object. Many viewprovider classes may inherit this class in order to have the same basic behavior.""" ## @package view_base # \ingroup draftviewproviders # \brief Provides the viewprovider code for the base Draft object. import draftutils.gui_utils as gui_utils import draftutils.utils as utils import FreeCAD as App ## \addtogroup draftviewproviders # @{ import PySide.QtCore as QtCore import PySide.QtGui as QtGui from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP if App.GuiUp: import Draft_rc import FreeCADGui as Gui from pivy import coin # The module is used to prevent complaints from code checkers (flake8) bool(Draft_rc.__name__) class ViewProviderDraft(object): """The base class for Draft view providers. Parameters ---------- vobj : a base C++ view provider The view provider of the scripted object (`obj.ViewObject`), which commonly may be of types `PartGui::ViewProvider2DObjectPython`, `PartGui::ViewProviderPython`, or `Gui::ViewProviderPythonFeature`. A basic view provider is instantiated during the creation of the base C++ object, for example, `Part::Part2DObjectPython`, `Part::FeaturePython`, or `App::FeaturePython`. >>> obj = App.ActiveDocument.addObject('Part::Part2DObjectPython') >>> vobj = obj.ViewObject >>> ViewProviderDraft(vobj) This view provider class instance is stored in the `Proxy` attribute of the base view provider. :: vobj.Proxy = self Attributes ---------- Object : the base C++ object The scripted document object that is associated with this view provider, which commonly may be of types `Part::Part2DObjectPython`, `Part::FeaturePython`, or `App::FeaturePython`. texture : coin.SoTexture2 A texture that could be added to this object. texcoords : coin.SoTextureCoordinatePlane The coordinates defining a plane to use for aligning the texture. These class attributes are accessible through the `Proxy` object: `vobj.Proxy.Object`, `vobj.Proxy.texture`, etc. """ def __init__(self, vobj): self.Object = vobj.Object self.texture = None self.texcoords = None self._set_properties(vobj) # This class is assigned to the Proxy attribute vobj.Proxy = self def _set_properties(self, vobj): """Set the properties of objects if they don't exist.""" if not hasattr(vobj, "Pattern"): vobj.addProperty( "App::PropertyEnumeration", "Pattern", "Draft", QT_TRANSLATE_NOOP("App::Property", "Defines an SVG pattern."), ) patterns = list(utils.svg_patterns()) patterns.sort() vobj.Pattern = ["None"] + patterns if not hasattr(vobj, "PatternSize"): vobj.addProperty( "App::PropertyFloat", "PatternSize", "Draft", QT_TRANSLATE_NOOP( "App::Property", "Defines the size of the SVG pattern." ), ) vobj.PatternSize = utils.get_param("HatchPatternSize", 1) def dumps(self): """Return a tuple of all serializable objects or None. When saving the document this view provider object gets stored using Python's `json` module. Since we have some un-serializable objects (Coin objects) in here we must define this method to return a tuple of all serializable objects or `None`. Override this method to define the serializable objects to return. By default it returns `None`. Returns ------- None """ return None def loads(self, state): """Set some internal properties for all restored objects. When a document is restored this method is used to set some properties for the objects stored with `json`. Override this method to define the properties to change for the restored serialized objects. By default no objects were serialized with `dumps`, so nothing needs to be done here, and it returns `None`. Parameters ---------- state : state A serialized object. Returns ------- None """ return None def attach(self, vobj): """Set up the scene sub-graph of the view provider. This method should always be defined, even if it does nothing. Override this method to set up a custom scene. Parameters ---------- vobj : the view provider of the scripted object. This is `obj.ViewObject`. """ self.texture = None self.texcoords = None self.Object = vobj.Object self.onChanged(vobj, "Pattern") return def updateData(self, obj, prop): """Run when an object property is changed. Override this method to handle the behavior of the view provider depending on changes that occur to the real object's properties. By default, no property is tested, and it does nothing. Parameters ---------- obj : the base C++ object The scripted document object that is associated with this view provider, which commonly may be of types `Part::Part2DObjectPython`, `Part::FeaturePython`, or `App::FeaturePython`. prop : str Name of the property that was modified. """ return def getDisplayModes(self, vobj): """Return a list of display modes. Override this method to return a list of strings with display mode styles, such as `'Flat Lines'`, `'Shaded'`, `'Wireframe'`, `'Points'`. By default it returns an empty list. Parameters ---------- vobj : the view provider of the scripted object. This is `obj.ViewObject`. Returns ------- list Empty list `[ ]` """ modes = [] return modes def getDefaultDisplayMode(self): """Return the default mode defined in getDisplayModes. Override this method to return a string with the default display mode. By default it returns `'Flat Lines'`. Returns ------- str `'Flat Lines'` """ return "Flat Lines" def setDisplayMode(self, mode): """Map the modes defined in attach with those in getDisplayModes. This method is optional. By default since they have the same names nothing needs to be done, and it just returns the input `mode`. Parameters ---------- str A string defining a display mode such as `'Flat Lines'`, `'Shaded'`, `'Wireframe'`, `'Points'`. """ return mode def onChanged(self, vobj, prop): """Run when a view property is changed. Override this method to handle the behavior of the view provider depending on changes that occur to its properties such as line color, line width, point color, point size, draw style, shape color, transparency, and others. This method updates the texture and pattern if the properties `TextureImage`, `Pattern`, `DiffuseColor`, and `PatternSize` change. Parameters ---------- vobj : the view provider of the scripted object. This is `obj.ViewObject`. prop : str Name of the property that was modified. """ # treatment of patterns and image textures if prop in ("TextureImage", "Pattern", "DiffuseColor"): if hasattr(self.Object, "Shape"): if self.Object.Shape.Faces: path = None if hasattr(vobj, "TextureImage"): if vobj.TextureImage: path = vobj.TextureImage if not path: if hasattr(vobj, "Pattern"): if str(vobj.Pattern) in utils.svg_patterns(): path = utils.svg_patterns()[vobj.Pattern][1] else: path = "None" if path and vobj.RootNode: if vobj.RootNode.getChildren().getLength() > 2: if vobj.RootNode.getChild(2).getChildren().getLength() > 0: innodes = ( vobj.RootNode.getChild(2) .getChild(0) .getChildren() .getLength() ) if innodes > 2: r = ( vobj.RootNode.getChild(2) .getChild(0) .getChild(innodes - 1) ) i = QtCore.QFileInfo(path) if self.texture: r.removeChild(self.texture) self.texture = None if self.texcoords: r.removeChild(self.texcoords) self.texcoords = None if i.exists(): size = None if ".SVG" in path.upper(): size = utils.get_param( "HatchPatternResolution", 128 ) if not size: size = 128 im = gui_utils.load_texture(path, size) if im: self.texture = coin.SoTexture2() self.texture.image = im r.insertChild(self.texture, 1) if size: s = 1 if hasattr(vobj, "PatternSize"): if vobj.PatternSize: s = vobj.PatternSize self.texcoords = ( coin.SoTextureCoordinatePlane() ) self.texcoords.directionS.setValue( s, 0, 0 ) self.texcoords.directionT.setValue( 0, s, 0 ) r.insertChild(self.texcoords, 2) elif prop == "PatternSize": if hasattr(self, "texcoords"): if self.texcoords: s = 1 if vobj.PatternSize: s = vobj.PatternSize vS = App.Vector(self.texcoords.directionS.getValue().getValue()) vT = App.Vector(self.texcoords.directionT.getValue().getValue()) vS.Length = s vT.Length = s self.texcoords.directionS.setValue(vS.x, vS.y, vS.z) self.texcoords.directionT.setValue(vT.x, vT.y, vT.z) return def _update_pattern_size(self, vobj): """Update the pattern size. Helper method in onChanged.""" if hasattr(self, "texcoords") and self.texcoords: s = 1 if vobj.PatternSize: s = vobj.PatternSize vS = App.Vector(self.texcoords.directionS.getValue().getValue()) vT = App.Vector(self.texcoords.directionT.getValue().getValue()) vS.Length = s vT.Length = s self.texcoords.directionS.setValue(vS.x, vS.y, vS.z) self.texcoords.directionT.setValue(vT.x, vT.y, vT.z) def execute(self, vobj): """Run when the object is created or recomputed. Override this method to produce effects when the object is newly created, and whenever the document is recomputed. By default it does nothing. Parameters ---------- vobj : the view provider of the scripted object. This is `obj.ViewObject`. """ return def setEdit(self, vobj, mode): """Enter the edit mode of the object. Parameters ---------- vobj : the view provider of the scripted object. This is `obj.ViewObject`. mode : int 0, 1, 2 or 3. See the `Std_UserEditMode` command. Returns ------- bool or None `False`: NOT USED HERE. Do not enter edit mode (unsetEdit is not called). `True` : Handled edit mode. Handled modes are 0 and 3, and only for certain objects. The unsetEdit function should then also return `True`. `None` : Unhandled edit mode. Handling is left to Part::FeaturePython code. The unsetEdit function should then also return `None`. """ if mode == 1 or mode == 2: return None # Fillet, Point, Shape2DView and PanelCut objects rely on a doubleClicked # function which takes precedence over all double-click edit modes. This # is a workaround as calling Gui.runCommand("Std_TransformManip") from # setEdit does not work properly. The object then seems to be put into # edit mode twice (?) and Esc will not cancel the command. # Facebinder, ShapeString, PanelSheet and Profile objects have their own # setEdit and unsetEdit. if utils.get_type(vobj.Object) in ( "Wire", "Circle", "Ellipse", "Rectangle", "Polygon", "BSpline", "BezCurve", ): if not "Draft_Edit" in Gui.listCommands(): self.wb_before_edit = Gui.activeWorkbench() Gui.activateWorkbench("DraftWorkbench") Gui.runCommand("Draft_Edit") return True return None def unsetEdit(self, vobj, mode): """Terminate the edit mode of the object. See setEdit. """ if mode == 1 or mode == 2: return None if utils.get_type(vobj.Object) in ( "Wire", "Circle", "Ellipse", "Rectangle", "Polygon", "BSpline", "BezCurve", ): if hasattr(App, "activeDraftCommand") and App.activeDraftCommand: App.activeDraftCommand.finish() Gui.Control.closeDialog() if hasattr(self, "wb_before_edit"): Gui.activateWorkbench(self.wb_before_edit.name()) delattr(self, "wb_before_edit") return True return None def setupContextMenu(self, vobj, menu): tp = utils.get_type(self.Object) if tp in ( "Wire", "Circle", "Ellipse", "Rectangle", "Polygon", "BSpline", "BezCurve", "Facebinder", "ShapeString", "PanelSheet", "Profile", ): action_edit = QtGui.QAction(translate("draft", "Edit"), menu) QtCore.QObject.connect(action_edit, QtCore.SIGNAL("triggered()"), self.edit) menu.addAction(action_edit) if tp == "Wire": action_flatten = QtGui.QAction(translate("draft", "Flatten"), menu) QtCore.QObject.connect( action_flatten, QtCore.SIGNAL("triggered()"), self.flatten ) # The flatten function is defined in view_wire.py. menu.addAction(action_flatten) # The default Part::FeaturePython context menu contains a `Set colors` # option. This option makes no sense for objects without a face or that # can only have a single face. In those cases we override this menu and # have to add our own `Transform` item. # To override the default menu this function must return `True`. if tp in ( "Wire", "Circle", "Ellipse", "Rectangle", "Polygon", "BSpline", "BezCurve", "Fillet", "Point", "Shape2DView", "PanelCut", "PanelSheet", "Profile", ): action_transform = QtGui.QAction( Gui.getIcon("Std_TransformManip.svg"), translate( "Command", "Transform" ), # Context `Command` instead of `draft`. menu, ) QtCore.QObject.connect( action_transform, QtCore.SIGNAL("triggered()"), self.transform ) menu.addAction(action_transform) return True def edit(self): Gui.ActiveDocument.setEdit(self.Object, 0) def transform(self): Gui.ActiveDocument.setEdit(self.Object, 1) def getIcon(self): """Return the path to the icon used by the view provider. The path can be a full path in the system, or a relative path inside the compiled resource file. It can also be a string that defines the icon in XPM format. Override this method to provide a specific icon for the object in the tree view. By default it returns the path to the `Draft_Draft.svg` icon. Returns ------- str `':/icons/Draft_Draft.svg'` """ tp = utils.get_type(self.Object) if tp in ("Line", "Wire", "Polyline"): return ":/icons/Draft_N-Linear.svg" if tp in ("Rectangle", "Polygon"): return ":/icons/Draft_N-Polygon.svg" if tp in ("Circle", "Ellipse", "BSpline", "BezCurve", "Fillet"): return ":/icons/Draft_N-Curve.svg" if tp in ("ShapeString"): return ":/icons/Draft_ShapeString_tree.svg" if hasattr(self.Object, "AutoUpdate") and not self.Object.AutoUpdate: import TechDrawGui return ":/icons/TechDraw_TreePageUnsync.svg" return ":/icons/Draft_Draft.svg" def claimChildren(self): """Return objects that will be placed under it in the tree view. Override this method to return a list with objects that will appear under this object in the tree view. That is, this object becomes the `parent`, and all those under it are the `children`. By default the returned list is composed of objects from `Object.Base`, `Object.Objects`, `Object.Components`, and `Object.Group`, if they exist. Returns ------- list List of objects. """ objs = [] if hasattr(self.Object, "Base"): objs.append(self.Object.Base) if hasattr(self.Object, "Objects"): objs.extend(self.Object.Objects) if hasattr(self.Object, "Components"): objs.extend(self.Object.Components) if hasattr(self.Object, "Group"): objs.extend(self.Object.Group) return objs # Alias for compatibility with v0.18 and earlier _ViewProviderDraft = ViewProviderDraft class ViewProviderDraftAlt(ViewProviderDraft): """A view provider that doesn't absorb its base object in the tree view. The `claimChildren` method is overridden to return an empty list. The `doubleClicked` method is defined. Only used by the `Shape2DView` object. """ def __init__(self, vobj): super(ViewProviderDraftAlt, self).__init__(vobj) def doubleClicked(self, vobj): # See setEdit in ViewProviderDraft. Gui.runCommand("Std_TransformManip") return True def claimChildren(self): return [] # Alias for compatibility with v0.18 and earlier _ViewProviderDraftAlt = ViewProviderDraftAlt class ViewProviderDraftPart(ViewProviderDraftAlt): """A view provider that displays a Part icon instead of a Draft icon. The `getIcon` method is overridden to provide `Part_3D_object.svg`. Only used by the `Block` object. """ def __init__(self, vobj): super(ViewProviderDraftPart, self).__init__(vobj) def getIcon(self): return ":/icons/Part_3D_object.svg" def setEdit(self, vobj, mode): return None def unsetEdit(self, vobj, mode): return None # Alias for compatibility with v0.18 and earlier _ViewProviderDraftPart = ViewProviderDraftPart ## @}
compat
py23
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import functools import sys # These functions are used to make the doctests compatible between # python2 and python3, and also provide uniform functionality between # the two versions. This code is pretty much lifted from the iPython # project's py3compat.py file. Credit to the iPython devs. # Numeric form of version PY_VERSION = float(sys.version[:3]) NEWPY = PY_VERSION >= 3.3 # Assume all strings are Unicode in Python 2 py23_str = str if sys.version[0] == "3" else unicode # Use the range iterator always py23_range = range if sys.version[0] == "3" else xrange # Uniform base string type py23_basestring = str if sys.version[0] == "3" else basestring # unichr function py23_unichr = chr if sys.version[0] == "3" else unichr def _py23_cmp(a, b): return (a > b) - (a < b) py23_cmp = _py23_cmp if sys.version[0] == "3" else cmp # zip as an iterator if sys.version[0] == "3": py23_zip = zip py23_map = map py23_filter = filter else: import itertools py23_zip = itertools.izip py23_map = itertools.imap py23_filter = itertools.ifilter # cmp_to_key was not created till 2.7, so require this for 2.6 try: from functools import cmp_to_key except ImportError: # pragma: no cover def cmp_to_key(mycmp): """Convert a cmp= function into a key= function""" class K(object): __slots__ = ["obj"] def __init__(self, obj): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 def __hash__(self): raise TypeError("hash not implemented") return K # This function is intended to decorate other functions that will modify # either a string directly, or a function's docstring. def _modify_str_or_docstring(str_change_func): @functools.wraps(str_change_func) def wrapper(func_or_str): if isinstance(func_or_str, py23_basestring): func = None doc = func_or_str else: func = func_or_str doc = func.__doc__ if doc is not None: doc = str_change_func(doc) if func: func.__doc__ = doc return func return doc return wrapper # Properly modify a doctstring to either have the unicode literal or not. if sys.version[0] == "3": # Abstract u'abc' syntax: @_modify_str_or_docstring def u_format(s): """ "{u}'abc'" --> "'abc'" (Python 3) Accepts a string or a function, so it can be used as a decorator.""" return s.format(u="") else: # Abstract u'abc' syntax: @_modify_str_or_docstring def u_format(s): """ "{u}'abc'" --> "u'abc'" (Python 2) Accepts a string or a function, so it can be used as a decorator.""" return s.format(u="u")
api
app_metrics
from typing import Any from posthog.api.routing import StructuredViewSetMixin from posthog.models.plugin import PluginConfig from posthog.queries.app_metrics.app_metrics import ( AppMetricsErrorDetailsQuery, AppMetricsErrorsQuery, AppMetricsQuery, ) from posthog.queries.app_metrics.historical_exports import ( historical_export_metrics, historical_exports_activity, ) from posthog.queries.app_metrics.serializers import ( AppMetricsErrorsRequestSerializer, AppMetricsRequestSerializer, ) from rest_framework import mixins, request, response, viewsets from rest_framework.decorators import action class AppMetricsViewSet( StructuredViewSetMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): queryset = PluginConfig.objects.all() def retrieve( self, request: request.Request, *args: Any, **kwargs: Any ) -> response.Response: plugin_config = self.get_object() filter = AppMetricsRequestSerializer(data=request.query_params) filter.is_valid(raise_exception=True) metric_results = AppMetricsQuery(self.team, plugin_config.pk, filter).run() errors = AppMetricsErrorsQuery(self.team, plugin_config.pk, filter).run() return response.Response({"metrics": metric_results, "errors": errors}) @action(methods=["GET"], detail=True) def error_details( self, request: request.Request, *args: Any, **kwargs: Any ) -> response.Response: plugin_config = self.get_object() filter = AppMetricsErrorsRequestSerializer(data=request.query_params) filter.is_valid(raise_exception=True) error_details = AppMetricsErrorDetailsQuery( self.team, plugin_config.pk, filter ).run() return response.Response({"result": error_details}) class HistoricalExportsAppMetricsViewSet( StructuredViewSetMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.ViewSet, ): def list( self, request: request.Request, *args: Any, **kwargs: Any ) -> response.Response: return response.Response( { "results": historical_exports_activity( team_id=self.parents_query_dict["team_id"], plugin_config_id=self.parents_query_dict["plugin_config_id"], ) } ) def retrieve( self, request: request.Request, *args: Any, **kwargs: Any ) -> response.Response: job_id = kwargs["pk"] plugin_config_id = self.parents_query_dict["plugin_config_id"] return response.Response( historical_export_metrics(self.team, plugin_config_id, job_id) )
blocks
qa_file_source
#!/usr/bin/env python # # Copyright 2018 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # import array import os import tempfile import pmt from gnuradio import blocks, gr, gr_unittest class test_file_source(gr_unittest.TestCase): @classmethod def setUpClass(cls): os.environ["GR_CONF_CONTROLPORT_ON"] = "False" with tempfile.NamedTemporaryFile(delete=False) as temp: cls._datafilename = temp.name cls._vector = list(range(1000)) array.array("f", cls._vector).tofile(temp) @classmethod def tearDownClass(cls): os.unlink(cls._datafilename) def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_file_source(self): src = blocks.file_source(gr.sizeof_float, self._datafilename) snk = blocks.vector_sink_f() self.tb.connect(src, snk) self.tb.run() result_data = snk.data() self.assertFloatTuplesAlmostEqual(self._vector, result_data) self.assertEqual(len(snk.tags()), 0) def test_file_source_no_such_file(self): """ Try to open a non-existent file and verify exception is thrown. """ with self.assertRaises(RuntimeError): blocks.file_source(gr.sizeof_float, "___no_such_file___") def test_file_source_with_offset(self): expected_result = self._vector[100:] src = blocks.file_source(gr.sizeof_float, self._datafilename, offset=100) snk = blocks.vector_sink_f() self.tb.connect(src, snk) self.tb.run() result_data = snk.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) self.assertEqual(len(snk.tags()), 0) def test_source_with_offset_and_len(self): expected_result = self._vector[100 : 100 + 600] src = blocks.file_source( gr.sizeof_float, self._datafilename, offset=100, len=600 ) snk = blocks.vector_sink_f() self.tb.connect(src, snk) self.tb.run() result_data = snk.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) self.assertEqual(len(snk.tags()), 0) def test_file_source_can_seek_after_open(self): src = blocks.file_source(gr.sizeof_float, self._datafilename) self.assertTrue(src.seek(0, os.SEEK_SET)) self.assertTrue(src.seek(len(self._vector) - 1, os.SEEK_SET)) # Seek past end of file - this will also log a warning self.assertFalse(src.seek(len(self._vector), os.SEEK_SET)) # Negative seek - this will also log a warning self.assertFalse(src.seek(-1, os.SEEK_SET)) self.assertTrue(src.seek(1, os.SEEK_END)) self.assertTrue(src.seek(len(self._vector), os.SEEK_END)) # Seek past end of file - this will also log a warning self.assertFalse(src.seek(0, os.SEEK_END)) self.assertTrue(src.seek(0, os.SEEK_SET)) self.assertTrue(src.seek(1, os.SEEK_CUR)) # Seek past end of file - this will also log a warning self.assertFalse(src.seek(len(self._vector), os.SEEK_CUR)) def test_begin_tag(self): expected_result = self._vector src = blocks.file_source(gr.sizeof_float, self._datafilename) src.set_begin_tag(pmt.string_to_symbol("file_begin")) snk = blocks.vector_sink_f() self.tb.connect(src, snk) self.tb.run() result_data = snk.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) self.assertEqual(len(snk.tags()), 1) def test_begin_tag_repeat(self): expected_result = self._vector + self._vector src = blocks.file_source(gr.sizeof_float, self._datafilename, True) src.set_begin_tag(pmt.string_to_symbol("file_begin")) head = blocks.head(gr.sizeof_float, 2 * len(self._vector)) snk = blocks.vector_sink_f() self.tb.connect(src, head, snk) self.tb.run() result_data = snk.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) tags = snk.tags() self.assertEqual(len(tags), 2) self.assertEqual(str(tags[0].key), "file_begin") self.assertEqual(str(tags[0].value), "0") self.assertEqual(tags[0].offset, 0) self.assertEqual(str(tags[1].key), "file_begin") self.assertEqual(str(tags[1].value), "1") self.assertEqual(tags[1].offset, 1000) if __name__ == "__main__": gr_unittest.run(test_file_source)
neubot
backend_neubot
# neubot/backend_neubot.py # # Copyright (c) 2012-2013 # Nexa Center for Internet & Society, Politecnico di Torino (DAUIN), # and Simone Basso <bassosimone@gmail.com> # # This file is part of Neubot <http://www.neubot.org/>. # # Neubot is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Neubot is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Neubot. If not, see <http://www.gnu.org/licenses/>. # """ Neubot backend """ # # The traditional Neubot backend, which saves results into # an sqlite3 database. Codesigned with Alessio Palmero Aprosio # and with comments and feedback from Roberto D'Auria. # import logging import os try: import cPickle as pickle except ImportError: import pickle from neubot import utils_path from neubot.backend_null import BackendNull from neubot.database import DATABASE, table_bittorrent, table_raw, table_speedtest SPLIT_INTERVAL = 1024 SPLIT_NUM_FILES = 15 class BackendNeubot(BackendNull): """Neubot backend""" def __init__(self, proxy): BackendNull.__init__(self, proxy) self.generic = {} def bittorrent_store(self, message): """Saves the results of a bittorrent test""" DATABASE.connect() if DATABASE.readonly: logging.warning("backend_neubot: readonly database") return table_bittorrent.insert(DATABASE.connection(), message) def store_raw(self, message): """Saves the results of a raw test""" DATABASE.connect() if DATABASE.readonly: logging.warning("backend_neubot: readonly database") return table_raw.insert(DATABASE.connection(), message) def speedtest_store(self, message): """Saves the results of a speedtest test""" DATABASE.connect() if DATABASE.readonly: logging.warning("backend_neubot: readonly database") return table_speedtest.insert(DATABASE.connection(), message) # # 'Generic' load/store functions. We append test results into a vector, # which is also serialized to disk using pickle. When the number of # items in the vector exceeds a threshold, we rotate the logfiles created # using pickle, and we start over with an empty vector. # # Also we access results by index, as the Twitter API does. Each index # is the number of a logfile. When there is no index, we serve the logfile # that is currently being written. # # Dash Elhauge had the original idea behind this implementation, my # fault if it took too much to implement it. # def store_generic(self, test, results): """Store the results of a generic test""" components = ["%s.pickle" % test] fullpath = self.proxy.datadir_touch(components) # Load if not test in self.generic: filep = open(fullpath, "rb") content = filep.read() filep.close() if content: self.generic[test] = pickle.loads(content) else: self.generic[test] = [] # Rotate if len(self.generic[test]) >= SPLIT_INTERVAL: tmppath = fullpath + "." + str(SPLIT_NUM_FILES) if os.path.isfile(tmppath): os.unlink(tmppath) for index in range(SPLIT_NUM_FILES, 0, -1): srcpath = fullpath + "." + str(index - 1) if not os.path.isfile(srcpath): continue destpath = fullpath + "." + str(index) os.rename(srcpath, destpath) tmppath = fullpath + ".0" filep = open(tmppath, "wb") pickle.dump(self.generic[test], filep) filep.close() self.generic[test] = [] # Write self.generic[test].append(results) filep = open(fullpath, "wb") pickle.dump(self.generic[test], filep) filep.close() def walk_generic(self, test, index): """Walk over the results of a generic test""" filename = "%s.pickle" % test if index != None: filename += "." + str(int(index)) fullpath = utils_path.append(self.proxy.datadir, filename, False) if not fullpath: return [] if not os.path.isfile(fullpath): return [] filep = open(fullpath, "rb") content = filep.read() filep.close() if not content: return [] return pickle.loads(content) def datadir_init(self, uname=None, datadir=None): """Initialize datadir (if needed)""" self.proxy.really_init_datadir(uname, datadir)
zeromq
probe_manager
# # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio. # # SPDX-License-Identifier: GPL-3.0-or-later # import time import numpy import zmq class probe_manager(object): def __init__(self): self.zmq_context = zmq.Context() self.poller = zmq.Poller() self.interfaces = [] def add_socket(self, address, data_type, callback_func): socket = self.zmq_context.socket(zmq.SUB) socket.setsockopt(zmq.SUBSCRIBE, b"") # Do not wait more than 5 seconds for a message socket.setsockopt(zmq.RCVTIMEO, 100) socket.connect(address) # use a tuple to store interface elements self.interfaces.append((socket, data_type, callback_func)) self.poller.register(socket, zmq.POLLIN) # Give it time for the socket to be ready time.sleep(0.5) def watcher(self): poll = dict(self.poller.poll(1000)) for i in self.interfaces: # i = (socket, data_type, callback_func) if poll.get(i[0]) == zmq.POLLIN: # receive data msg_packed = i[0].recv() # use numpy to unpack the data msg_unpacked = numpy.frombuffer(msg_packed, numpy.dtype(i[1])) # invoke callback function i[2](msg_unpacked)
core
constants
##################################################################### # Frets on Fire X (FoFiX) # # Copyright (C) 2011 FoFiX Team # # # # This program is free software; you can redistribute it and/or # # modify it under the terms of the GNU General Public License # # as published by the Free Software Foundation; either version 2 # # of the License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # # MA 02110-1301, USA. # ##################################################################### # Horizontal alignments LEFT = 0 CENTER = 1 RIGHT = 2 # Vertical alignments TOP = 0 MIDDLE = 1 BOTTOM = 2 # Stretching constants FIT_WIDTH = 1 FIT_HEIGHT = 2 FULL_SCREEN = 3 KEEP_ASPECT = 4 # Screen sizing scalers SCREEN_WIDTH = 640.0 SCREEN_HEIGHT = 480.0 def isTrue(value): """Check if the value looks like True""" return value in ["1", "true", "yes", "on"]
digital
qa_constellation_decoder_cb
#!/usr/bin/env python # # Copyright 2004,2007,2010-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from gnuradio import blocks, digital, gr, gr_unittest class test_constellation_decoder(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_constellation_decoder_cb_bpsk(self): cnst = digital.constellation_bpsk() src_data = ( 0.5 + 0.5j, 0.1 - 1.2j, -0.8 - 0.1j, -0.45 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 - 1.2j, ) expected_result = (1, 1, 0, 0, 1, 0, 1) src = blocks.vector_source_c(src_data) op = digital.constellation_decoder_cb(cnst.base()) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink # print "actual result", actual_result # print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result) def _test_constellation_decoder_cb_qpsk(self): cnst = digital.constellation_qpsk() src_data = ( 0.5 + 0.5j, 0.1 - 1.2j, -0.8 - 0.1j, -0.45 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 - 1.2j, ) expected_result = (3, 1, 0, 2, 3, 2, 1) src = blocks.vector_source_c(src_data) op = digital.constellation_decoder_cb(cnst.base()) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink # print "actual result", actual_result # print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result) def test_constellation_decoder_cb_bpsk_to_qpsk(self): cnst = digital.constellation_bpsk() src_data = ( 0.5 + 0.5j, 0.1 - 1.2j, -0.8 - 0.1j, -0.45 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 - 1.2j, ) src = blocks.vector_source_c(src_data) op = digital.constellation_decoder_cb(cnst.base()) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() # run the graph and wait for it to finish cnst = digital.constellation_qpsk() src_data = ( 0.5 + 0.5j, 0.1 - 1.2j, -0.8 - 0.1j, -0.45 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 - 1.2j, ) expected_result = ( 1, 1, 0, 0, # BPSK section 1, 0, 1, 3, 1, 0, 2, # QPSK section 3, 2, 1, ) src.set_data(src_data) op.set_constellation(cnst.base()) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink # print("actual result", actual_result) # print("expected result", expected_result) self.assertFloatTuplesAlmostEqual(expected_result, actual_result) if __name__ == "__main__": gr_unittest.run(test_constellation_decoder)
PathTests
TestPathPost
# -*- coding: utf-8 -*- # *************************************************************************** # * Copyright (c) 2016 sliptonic <shopinthewoods@gmail.com> * # * Copyright (c) 2022 Larry Woestman <LarryWoestman2@gmail.com> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** import difflib import os import unittest import FreeCAD import Path import Path.Post.Command as PathPost import Path.Post.Utils as PostUtils from Path.Post.Processor import PostProcessor # If KEEP_DEBUG_OUTPUT is False, remove the gcode file after the test succeeds. # If KEEP_DEBUG_OUTPUT is True or the test fails leave the gcode file behind # so it can be looked at easily. KEEP_DEBUG_OUTPUT = False PathPost.LOG_MODULE = Path.Log.thisModule() Path.Log.setLevel(Path.Log.Level.INFO, PathPost.LOG_MODULE) class TestPathPost(unittest.TestCase): """Test some of the output of the postprocessors. So far there are three tests each for the linuxcnc and centroid postprocessors. """ def setUp(self): """Set up the postprocessor tests.""" pass def tearDown(self): """Tear down after the postprocessor tests.""" pass # # You can run just this test using: # ./FreeCAD -c -t PathTests.TestPathPost.TestPathPost.test_postprocessors # def test_postprocessors(self): """Test the postprocessors.""" # # The tests are performed in the order they are listed: # one test performed on all of the postprocessors # then the next test on all of the postprocessors, etc. # You can comment out the tuples for tests that you don't want # to use. # tests_to_perform = ( # (output_file_id, freecad_document, job_name, postprocessor_arguments, # postprocessor_list) # # test with all of the defaults (metric mode, etc.) ("default", "boxtest1", "Job", "--no-show-editor", ()), # test in Imperial mode ("imperial", "boxtest1", "Job", "--no-show-editor --inches", ()), # test in metric, G55, M4, the other way around the part ("other_way", "boxtest1", "Job001", "--no-show-editor", ()), # test in metric, split by fixtures, G54, G55, G56 ("split", "boxtest1", "Job002", "--no-show-editor", ()), # test in metric mode without the header ("no_header", "boxtest1", "Job", "--no-header --no-show-editor", ()), # test translating G81, G82, and G83 to G00 and G01 commands ( "drill_translate", "drill_test1", "Job", "--no-show-editor --translate_drill", ("grbl", "refactored_grbl"), ), ) # # The postprocessors to test. # You can comment out any postprocessors that you don't want # to test. # postprocessors_to_test = ( "centroid", # "fanuc", "grbl", "linuxcnc", "mach3_mach4", "refactored_centroid", # "refactored_fanuc", "refactored_grbl", "refactored_linuxcnc", "refactored_mach3_mach4", "refactored_test", ) # # Enough of the path to where the tests are stored so that # they can be found by the python interpreter. # PATHTESTS_LOCATION = "Mod/Path/PathTests" # # The following code tries to re-use an open FreeCAD document # as much as possible. It compares the current document with # the document for the next test. If the names are different # then the current document is closed and the new document is # opened. The final document is closed at the end of the code. # current_document = "" for ( output_file_id, freecad_document, job_name, postprocessor_arguments, postprocessor_list, ) in tests_to_perform: if current_document != freecad_document: if current_document != "": FreeCAD.closeDocument(current_document) current_document = freecad_document current_document_path = ( FreeCAD.getHomePath() + PATHTESTS_LOCATION + os.path.sep + current_document + ".fcstd" ) FreeCAD.open(current_document_path) job = FreeCAD.ActiveDocument.getObject(job_name) # Create the objects to be written by the postprocessor. postlist = PathPost.buildPostList(job) for postprocessor_id in postprocessors_to_test: if postprocessor_list == () or postprocessor_id in postprocessor_list: print( "\nRunning %s test on %s postprocessor:\n" % (output_file_id, postprocessor_id) ) processor = PostProcessor.load(postprocessor_id) output_file_path = FreeCAD.getHomePath() + PATHTESTS_LOCATION output_file_pattern = "test_%s_%s" % ( postprocessor_id, output_file_id, ) output_file_extension = ".ngc" for idx, section in enumerate(postlist): partname = section[0] sublist = section[1] output_filename = PathPost.processFileNameSubstitutions( job, partname, idx, output_file_path, output_file_pattern, output_file_extension, ) # print("output file: " + output_filename) file_path, extension = os.path.splitext(output_filename) reference_file_name = "%s%s%s" % (file_path, "_ref", extension) # print("reference file: " + reference_file_name) gcode = processor.export( sublist, output_filename, postprocessor_arguments ) if not gcode: print("no gcode") with open(reference_file_name, "r") as fp: reference_gcode = fp.read() if not reference_gcode: print("no reference gcode") # Remove the "Output Time:" line in the header from the # comparison if it is present because it changes with # every test. gcode_lines = [ i for i in gcode.splitlines(True) if "Output Time:" not in i ] reference_gcode_lines = [ i for i in reference_gcode.splitlines(True) if "Output Time:" not in i ] if gcode_lines != reference_gcode_lines: msg = "".join( difflib.ndiff(gcode_lines, reference_gcode_lines) ) self.fail( os.path.basename(output_filename) + " output doesn't match:\n" + msg ) if not KEEP_DEBUG_OUTPUT: os.remove(output_filename) if current_document != "": FreeCAD.closeDocument(current_document) class TestPathPostUtils(unittest.TestCase): def test010(self): """Test the utility functions in the PostUtils.py file.""" commands = [ Path.Command("G1 X-7.5 Y5.0 Z0.0"), Path.Command("G2 I2.5 J0.0 K0.0 X-5.0 Y7.5 Z0.0"), Path.Command("G1 X5.0 Y7.5 Z0.0"), Path.Command("G2 I0.0 J-2.5 K0.0 X7.5 Y5.0 Z0.0"), Path.Command("G1 X7.5 Y-5.0 Z0.0"), Path.Command("G2 I-2.5 J0.0 K0.0 X5.0 Y-7.5 Z0.0"), Path.Command("G1 X-5.0 Y-7.5 Z0.0"), Path.Command("G2 I0.0 J2.5 K0.0 X-7.5 Y-5.0 Z0.0"), Path.Command("G1 X-7.5 Y0.0 Z0.0"), ] testpath = Path.Path(commands) self.assertTrue(len(testpath.Commands) == 9) self.assertTrue( len([c for c in testpath.Commands if c.Name in ["G2", "G3"]]) == 4 ) results = PostUtils.splitArcs(testpath) # self.assertTrue(len(results.Commands) == 117) self.assertTrue( len([c for c in results.Commands if c.Name in ["G2", "G3"]]) == 0 ) def dumpgroup(group): print("====Dump Group======") for i in group: print(i[0]) for j in i[1]: print(f"--->{j.Name}") print("====================") class TestBuildPostList(unittest.TestCase): """ The postlist is the list of postprocessable elements from the job. The list varies depending on -The operations -The tool controllers -The work coordinate systems (WCS) or 'fixtures' -How the job is ordering the output (WCS, tool, operation) -Whether or not the output is being split to multiple files This test case ensures that the correct sequence of postable objects is created. The list will be comprised of a list of tuples. Each tuple consists of (subobject string, [list of objects]) The subobject string can be used in output name generation if splitting output the list of objects is all postable elements to be written to that file """ def setUp(self): self.testfile = ( FreeCAD.getHomePath() + "Mod/Path/PathTests/test_filenaming.fcstd" ) self.doc = FreeCAD.open(self.testfile) self.job = self.doc.getObjectsByLabel("MainJob")[0] def tearDown(self): FreeCAD.closeDocument(self.doc.Name) def test000(self): # check that the test file is structured correctly self.assertTrue(len(self.job.Tools.Group) == 2) self.assertTrue(len(self.job.Fixtures) == 2) self.assertTrue(len(self.job.Operations.Group) == 3) self.job.SplitOutput = False self.job.OrderOutputBy = "Operation" def test010(self): postlist = PathPost.buildPostList(self.job) self.assertTrue(type(postlist) is list) firstoutputitem = postlist[0] self.assertTrue(type(firstoutputitem) is tuple) self.assertTrue(type(firstoutputitem[0]) is str) self.assertTrue(type(firstoutputitem[1]) is list) def test020(self): # Without splitting, result should be list of one item self.job.SplitOutput = False self.job.OrderOutputBy = "Operation" postlist = PathPost.buildPostList(self.job) self.assertTrue(len(postlist) == 1) def test030(self): # No splitting should include all ops, tools, and fixtures self.job.SplitOutput = False self.job.OrderOutputBy = "Operation" postlist = PathPost.buildPostList(self.job) firstoutputitem = postlist[0] firstoplist = firstoutputitem[1] self.assertTrue(len(firstoplist) == 14) def test040(self): # Test splitting by tool # ordering by tool with toolnumber for string teststring = "%T.nc" self.job.SplitOutput = True self.job.PostProcessorOutputFile = teststring self.job.OrderOutputBy = "Tool" postlist = PathPost.buildPostList(self.job) firstoutputitem = postlist[0] self.assertTrue(firstoutputitem[0] == str(5)) # check length of output firstoplist = firstoutputitem[1] self.assertTrue(len(firstoplist) == 5) def test050(self): # ordering by tool with tool description for string teststring = "%t.nc" self.job.SplitOutput = True self.job.PostProcessorOutputFile = teststring self.job.OrderOutputBy = "Tool" postlist = PathPost.buildPostList(self.job) firstoutputitem = postlist[0] self.assertTrue(firstoutputitem[0] == "TC__7_16__two_flute") def test060(self): # Ordering by fixture and splitting teststring = "%W.nc" self.job.SplitOutput = True self.job.PostProcessorOutputFile = teststring self.job.OrderOutputBy = "Fixture" postlist = PathPost.buildPostList(self.job) firstoutputitem = postlist[0] firstoplist = firstoutputitem[1] self.assertTrue(len(firstoplist) == 6) self.assertTrue(firstoutputitem[0] == "G54") class TestOutputNameSubstitution(unittest.TestCase): """ String substitution allows the following: %D ... directory of the active document %d ... name of the active document (with extension) %M ... user macro directory %j ... name of the active Job object The Following can be used if output is being split. If Output is not split these will be ignored. %S ... Sequence Number (default) %T ... Tool Number %t ... Tool Controller label %W ... Work Coordinate System %O ... Operation Label self.job.Fixtures = ["G54"] self.job.SplitOutput = False self.job.OrderOutputBy = "Fixture" Assume: active document: self.assertTrue(filename, f"{home}/testdoc.fcstd user macro: ~/.local/share/FreeCAD/Macro Job: MainJob Operations: OutsideProfile DrillAllHoles TC: 7/16" two flute (5) TC: Drill (2) Fixtures: (G54, G55) Strings should be sanitized like this to ensure valid filenames # import re # filename="TC: 7/16" two flute" # >>> re.sub(r"[^\w\d-]","_",filename) # "TC__7_16__two_flute" """ def setUp(self): self.testfile = ( FreeCAD.getHomePath() + "Mod/Path/PathTests/test_filenaming.fcstd" ) self.testfilepath, self.testfilename = os.path.split(self.testfile) self.testfilename, self.ext = os.path.splitext(self.testfilename) self.doc = FreeCAD.open(self.testfile) self.job = self.doc.getObjectsByLabel("MainJob")[0] self.macro = FreeCAD.getUserMacroDir() self.job.SplitOutput = False def tearDown(self): FreeCAD.closeDocument(self.doc.Name) def test000(self): # Test basic name generation with empty string FreeCAD.setActiveDocument(self.doc.Label) teststring = "" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) outlist = PathPost.buildPostList(self.job) self.assertTrue(len(outlist) == 1) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, f"{self.testfilename}.nc") def test015(self): # Test basic string substitution without splitting teststring = "~/Desktop/%j.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) outlist = PathPost.buildPostList(self.job) self.assertTrue(len(outlist) == 1) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual( os.path.normpath(filename), os.path.normpath("~/Desktop/MainJob.nc") ) def test010(self): # Substitute current file path teststring = "%D/testfile.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual( os.path.normpath(filename), os.path.normpath(f"{self.testfilepath}/testfile.nc"), ) def test020(self): teststring = "%d.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, f"{self.testfilename}.nc") def test030(self): teststring = "%M/outfile.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual( os.path.normpath(filename), os.path.normpath(f"{self.macro}outfile.nc") ) def test040(self): # unused substitution strings should be ignored teststring = "%d%T%t%W%O/testdoc.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual( os.path.normpath(filename), os.path.normpath(f"{self.testfilename}/testdoc.nc"), ) def test050(self): # explicitly using the sequence number should include it where indicated. teststring = "%S-%d.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "0-test_filenaming.nc") def test060(self): # # Split by Tool self.job.SplitOutput = True self.job.OrderOutputBy = "Tool" outlist = PathPost.buildPostList(self.job) # substitute jobname and use default sequence numbers teststring = "%j.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "MainJob-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "MainJob-1.nc") # Use Toolnumbers and default sequence numbers teststring = "%T.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "5-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "2-1.nc") # Use Tooldescriptions and default sequence numbers teststring = "%t.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) outlist = PathPost.buildPostList(self.job) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "TC__7_16__two_flute-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "TC__Drill-1.nc") def test070(self): # Split by WCS self.job.SplitOutput = True self.job.OrderOutputBy = "Fixture" outlist = PathPost.buildPostList(self.job) teststring = "%j.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "MainJob-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "MainJob-1.nc") teststring = "%W-%j.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "G54-MainJob-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "G55-MainJob-1.nc") def test080(self): # Split by Operation self.job.SplitOutput = True self.job.OrderOutputBy = "Operation" outlist = PathPost.buildPostList(self.job) teststring = "%j.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "MainJob-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "MainJob-1.nc") teststring = "%O-%j.nc" self.job.PostProcessorOutputFile = teststring Path.Preferences.setOutputFileDefaults( teststring, "Append Unique ID on conflict" ) subpart, objs = outlist[0] filename = PathPost.resolveFileName(self.job, subpart, 0) self.assertEqual(filename, "OutsideProfile-MainJob-0.nc") subpart, objs = outlist[1] filename = PathPost.resolveFileName(self.job, subpart, 1) self.assertEqual(filename, "DrillAllHoles-MainJob-1.nc")
extractor
vvvvid
# coding: utf-8 from __future__ import unicode_literals import re from ..utils import ExtractorError, int_or_none, str_or_none from .common import InfoExtractor from .youtube import YoutubeIE class VVVVIDIE(InfoExtractor): _VALID_URL_BASE = ( r"https?://(?:www\.)?vvvvid\.it/(?:#!)?(?:show|anime|film|series)/" ) _VALID_URL = ( r"%s(?P<show_id>\d+)/[^/]+/(?P<season_id>\d+)/(?P<id>[0-9]+)" % _VALID_URL_BASE ) _TESTS = [ { # video_type == 'video/vvvvid' "url": "https://www.vvvvid.it/#!show/434/perche-dovrei-guardarlo-di-dario-moccia/437/489048/ping-pong", "md5": "b8d3cecc2e981adc3835adf07f6df91b", "info_dict": { "id": "489048", "ext": "mp4", "title": "Ping Pong", "duration": 239, "series": '"Perché dovrei guardarlo?" di Dario Moccia', "season_id": "437", "episode": "Ping Pong", "episode_number": 1, "episode_id": "3334", "view_count": int, "like_count": int, "repost_count": int, }, "params": { "skip_download": True, }, }, { # video_type == 'video/rcs' "url": "https://www.vvvvid.it/#!show/376/death-note-live-action/377/482493/episodio-01", "md5": "33e0edfba720ad73a8782157fdebc648", "info_dict": { "id": "482493", "ext": "mp4", "title": "Episodio 01", }, "params": { "skip_download": True, }, }, { # video_type == 'video/youtube' "url": "https://www.vvvvid.it/show/404/one-punch-man/406/486683/trailer", "md5": "33e0edfba720ad73a8782157fdebc648", "info_dict": { "id": "RzmFKUDOUgw", "ext": "mp4", "title": "Trailer", "upload_date": "20150906", "description": "md5:a5e802558d35247fee285875328c0b80", "uploader_id": "BandaiVisual", "uploader": "BANDAI NAMCO Arts Channel", }, "params": { "skip_download": True, }, }, { # video_type == 'video/dash' "url": "https://www.vvvvid.it/show/683/made-in-abyss/1542/693786/nanachi", "info_dict": { "id": "693786", "ext": "mp4", "title": "Nanachi", }, "params": { "skip_download": True, "format": "mp4", }, }, { "url": "https://www.vvvvid.it/show/434/perche-dovrei-guardarlo-di-dario-moccia/437/489048", "only_matching": True, }, ] _conn_id = None def _real_initialize(self): self._conn_id = self._download_json( "https://www.vvvvid.it/user/login", None, headers=self.geo_verification_headers(), )["data"]["conn_id"] def _download_info(self, show_id, path, video_id, fatal=True, query=None): q = { "conn_id": self._conn_id, } if query: q.update(query) response = self._download_json( "https://www.vvvvid.it/vvvvid/ondemand/%s/%s" % (show_id, path), video_id, headers=self.geo_verification_headers(), query=q, fatal=fatal, ) if not (response or fatal): return if response.get("result") == "error": raise ExtractorError( "%s said: %s" % (self.IE_NAME, response["message"]), expected=True ) return response["data"] def _extract_common_video_info(self, video_data): return { "thumbnail": video_data.get("thumbnail"), "episode_id": str_or_none(video_data.get("id")), } def _real_extract(self, url): show_id, season_id, video_id = re.match(self._VALID_URL, url).groups() response = self._download_info( show_id, "season/%s" % season_id, video_id, query={"video_id": video_id} ) vid = int(video_id) video_data = list( filter(lambda episode: episode.get("video_id") == vid, response) )[0] title = video_data["title"] formats = [] # vvvvid embed_info decryption algorithm is reverse engineered from function $ds(h) at vvvvid.js def ds(h): g = "MNOPIJKL89+/4567UVWXQRSTEFGHABCDcdefYZabstuvopqr0123wxyzklmnghij" def f(m): l = [] o = 0 b = False m_len = len(m) while (not b) and o < m_len: n = m[o] << 2 o += 1 k = -1 j = -1 if o < m_len: n += m[o] >> 4 o += 1 if o < m_len: k = (m[o - 1] << 4) & 255 k += m[o] >> 2 o += 1 if o < m_len: j = (m[o - 1] << 6) & 255 j += m[o] o += 1 else: b = True else: b = True else: b = True l.append(n) if k != -1: l.append(k) if j != -1: l.append(j) return l c = [] for e in h: c.append(g.index(e)) c_len = len(c) for e in range(c_len * 2 - 1, -1, -1): a = c[e % c_len] ^ c[(e + 1) % c_len] c[e % c_len] = a c = f(c) d = "" for e in c: d += chr(e) return d info = {} def metadata_from_url(r_url): if not info and r_url: mobj = re.search(r"_(?:S(\d+))?Ep(\d+)", r_url) if mobj: info["episode_number"] = int(mobj.group(2)) season_number = mobj.group(1) if season_number: info["season_number"] = int(season_number) video_type = video_data.get("video_type") is_youtube = False for quality in ("", "_sd"): embed_code = video_data.get("embed_info" + quality) if not embed_code: continue embed_code = ds(embed_code) if video_type == "video/kenc": embed_code = re.sub( r"https?(://[^/]+)/z/", r"https\1/i/", embed_code ).replace("/manifest.f4m", "/master.m3u8") kenc = ( self._download_json( "https://www.vvvvid.it/kenc", video_id, query={ "action": "kt", "conn_id": self._conn_id, "url": embed_code, }, fatal=False, ) or {} ) kenc_message = kenc.get("message") if kenc_message: embed_code += "?" + ds(kenc_message) formats.extend( self._extract_m3u8_formats( embed_code, video_id, "mp4", m3u8_id="hls", fatal=False ) ) elif video_type == "video/rcs": formats.extend(self._extract_akamai_formats(embed_code, video_id)) elif video_type == "video/youtube": info.update( { "_type": "url_transparent", "ie_key": YoutubeIE.ie_key(), "url": embed_code, } ) is_youtube = True break elif video_type == "video/dash": formats.extend( self._extract_m3u8_formats( embed_code, video_id, "mp4", m3u8_id="hls", fatal=False ) ) else: formats.extend( self._extract_wowza_formats( "http://sb.top-ix.org/videomg/_definst_/mp4:%s/playlist.m3u8" % embed_code, video_id, ) ) metadata_from_url(embed_code) if not is_youtube: self._sort_formats(formats) info["formats"] = formats metadata_from_url(video_data.get("thumbnail")) info.update(self._extract_common_video_info(video_data)) info.update( { "id": video_id, "title": title, "duration": int_or_none(video_data.get("length")), "series": video_data.get("show_title"), "season_id": season_id, "episode": title, "view_count": int_or_none(video_data.get("views")), "like_count": int_or_none(video_data.get("video_likes")), "repost_count": int_or_none(video_data.get("video_shares")), } ) return info class VVVVIDShowIE(VVVVIDIE): _VALID_URL = ( r"(?P<base_url>%s(?P<id>\d+)(?:/(?P<show_title>[^/?&#]+))?)/?(?:[?#&]|$)" % VVVVIDIE._VALID_URL_BASE ) _TESTS = [ { "url": "https://www.vvvvid.it/show/156/psyco-pass", "info_dict": { "id": "156", "title": "Psycho-Pass", "description": "md5:94d572c0bd85894b193b8aebc9a3a806", }, "playlist_count": 46, }, { "url": "https://www.vvvvid.it/show/156", "only_matching": True, }, ] def _real_extract(self, url): base_url, show_id, show_title = re.match(self._VALID_URL, url).groups() seasons = self._download_info(show_id, "seasons/", show_title) show_info = self._download_info(show_id, "info/", show_title, fatal=False) if not show_title: base_url += "/title" entries = [] for season in seasons or []: episodes = season.get("episodes") or [] playlist_title = season.get("name") or show_info.get("title") for episode in episodes: if episode.get("playable") is False: continue season_id = str_or_none(episode.get("season_id")) video_id = str_or_none(episode.get("video_id")) if not (season_id and video_id): continue info = self._extract_common_video_info(episode) info.update( { "_type": "url_transparent", "ie_key": VVVVIDIE.ie_key(), "url": "/".join([base_url, season_id, video_id]), "title": episode.get("title"), "description": episode.get("description"), "season_id": season_id, "playlist_title": playlist_title, } ) entries.append(info) return self.playlist_result( entries, show_id, show_info.get("title"), show_info.get("description") )
api
urls
# -*- coding: utf-8 -*- from collections import OrderedDict from typing import Any, List, NamedTuple from django.urls import include, path from rest_framework import routers from rest_framework.schemas import get_schema_view from . import views class ExtraPath(NamedTuple): path: str reverese_name: str route: Any class CustomRouterWithExtraPaths(routers.DefaultRouter): extra_api_urls: List[ExtraPath] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.extra_api_urls = [] def add_detail_path(self, url_path, reverese_name, *args, **kwargs): self.extra_api_urls = self.extra_api_urls or [] kwargs["name"] = reverese_name self.extra_api_urls.append( ExtraPath(url_path, reverese_name, path(url_path, *args, **kwargs)) ) def get_api_root_view(self, api_urls=None): api_root_dict = OrderedDict() list_name = self.routes[0].name for prefix, viewset, basename in self.registry: api_root_dict[prefix] = list_name.format(basename=basename) for extra_path in self.extra_api_urls: api_root_dict[extra_path.path] = extra_path.reverese_name return self.APIRootView.as_view(api_root_dict=api_root_dict) @property def urls(self): return super().urls + [e.route for e in self.extra_api_urls] router = CustomRouterWithExtraPaths() router.register(r"bmi", views.BMIViewSet) router.register(r"changes", views.DiaperChangeViewSet) router.register(r"children", views.ChildViewSet) router.register(r"feedings", views.FeedingViewSet) router.register(r"head-circumference", views.HeadCircumferenceViewSet) router.register(r"height", views.HeightViewSet) router.register(r"notes", views.NoteViewSet) router.register(r"pumping", views.PumpingViewSet) router.register(r"sleep", views.SleepViewSet) router.register(r"tags", views.TagViewSet) router.register(r"temperature", views.TemperatureViewSet) router.register(r"timers", views.TimerViewSet) router.register(r"tummy-times", views.TummyTimeViewSet) router.register(r"weight", views.WeightViewSet) router.add_detail_path("profile", "profile", views.ProfileView.as_view()) router.add_detail_path( "schema", "openapi-schema", get_schema_view( title="Baby Buddy API", version=1, description="API documentation for the Baby Buddy application", ), ) app_name = "api" urlpatterns = [ path("api/", include(router.urls)), path("api/auth/", include("rest_framework.urls", namespace="rest_framework")), ]
engines
yggtorrent
# SPDX-License-Identifier: AGPL-3.0-or-later """ Yggtorrent (Videos, Music, Files) """ from datetime import datetime from operator import itemgetter from urllib.parse import quote from lxml import html from searx.poolrequests import get as http_get from searx.utils import extract_text, get_torrent_size # about about = { "website": "https://www4.yggtorrent.li/", "wikidata_id": None, "official_api_documentation": None, "use_official_api": False, "require_api_key": False, "results": "HTML", } # engine dependent config categories = ["videos", "music", "files"] paging = True # search-url url = "https://www4.yggtorrent.li/" search_url = ( url + "engine/search?name={search_term}&do=search&page={pageno}&category={search_type}" ) # yggtorrent specific type-definitions search_types = {"files": "all", "music": "2139", "videos": "2145"} cookies = dict() def init(engine_settings=None): global cookies # pylint: disable=global-variable-not-assigned # initial cookies resp = http_get(url) if resp.ok: for r in resp.history: cookies.update(r.cookies) cookies.update(resp.cookies) # do search-request def request(query, params): search_type = search_types.get(params["category"], "all") pageno = (params["pageno"] - 1) * 50 params["url"] = search_url.format( search_term=quote(query), search_type=search_type, pageno=pageno ) params["cookies"] = cookies return params # get response from search-request def response(resp): results = [] dom = html.fromstring(resp.text) search_res = dom.xpath('//section[@id="#torrents"]/div/table/tbody/tr') # return empty array if nothing is found if not search_res: return [] # parse results for result in search_res: link = result.xpath('.//a[@id="torrent_name"]')[0] href = link.attrib.get("href") title = extract_text(link) seed = result.xpath(".//td[8]/text()")[0] leech = result.xpath(".//td[9]/text()")[0] # convert seed to int if possible if seed.isdigit(): seed = int(seed) else: seed = 0 # convert leech to int if possible if leech.isdigit(): leech = int(leech) else: leech = 0 params = { "url": href, "title": title, "seed": seed, "leech": leech, "template": "torrent.html", } # let's try to calculate the torrent size try: filesize_info = result.xpath(".//td[6]/text()")[0] filesize = filesize_info[:-2] filesize_multiplier = filesize_info[-2:].lower() multiplier_french_to_english = { "to": "TiB", "go": "GiB", "mo": "MiB", "ko": "KiB", } filesize = get_torrent_size( filesize, multiplier_french_to_english[filesize_multiplier] ) params["filesize"] = filesize except: pass # extract and convert creation date try: date_ts = result.xpath(".//td[5]/div/text()")[0] date = datetime.fromtimestamp(float(date_ts)) params["publishedDate"] = date except: pass # append result results.append(params) # return results sorted by seeder return sorted(results, key=itemgetter("seed"), reverse=True)
mackup
appsdb
""" The applications database. The Applications Database provides an easy to use interface to load application data from the Mackup Database (files). """ import os try: import configparser except ImportError: import ConfigParser as configparser from .constants import APPS_DIR, CUSTOM_APPS_DIR class ApplicationsDatabase(object): """Database containing all the configured applications.""" def __init__(self): """Create a ApplicationsDatabase instance.""" # Build the dict that will contain the properties of each application self.apps = dict() for config_file in ApplicationsDatabase.get_config_files(): config = configparser.SafeConfigParser(allow_no_value=True) # Needed to not lowercase the configuration_files in the ini files config.optionxform = str if config.read(config_file): # Get the filename without the directory name filename = os.path.basename(config_file) # The app name is the cfg filename with the extension app_name = filename[: -len(".cfg")] # Start building a dict for this app self.apps[app_name] = dict() # Add the fancy name for the app, for display purpose app_pretty_name = config.get("application", "name") self.apps[app_name]["name"] = app_pretty_name # Add the configuration files to sync self.apps[app_name]["configuration_files"] = set() if config.has_section("configuration_files"): for path in config.options("configuration_files"): if path.startswith("/"): raise ValueError( "Unsupported absolute path: {}".format(path) ) self.apps[app_name]["configuration_files"].add(path) # Add the XDG configuration files to sync home = os.path.expanduser("~/") failobj = "{}.config".format(home) xdg_config_home = os.environ.get("XDG_CONFIG_HOME", failobj) if not xdg_config_home.startswith(home): raise ValueError( "$XDG_CONFIG_HOME: {} must be " "somewhere within your home " "directory: {}".format(xdg_config_home, home) ) if config.has_section("xdg_configuration_files"): for path in config.options("xdg_configuration_files"): if path.startswith("/"): raise ValueError( "Unsupported absolute path: " "{}".format(path) ) path = os.path.join(xdg_config_home, path) path = path.replace(home, "") (self.apps[app_name]["configuration_files"].add(path)) @staticmethod def get_config_files(): """ Return the application configuration files. Return a list of configuration files describing the apps supported by Mackup. The files returned are absolute full path to those files. e.g. /usr/lib/mackup/applications/bash.cfg Only one config file per application should be returned, custom config having a priority over stock config. Returns: set of strings. """ # Configure the config parser apps_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), APPS_DIR) custom_apps_dir = os.path.join(os.environ["HOME"], CUSTOM_APPS_DIR) # List of stock application config files config_files = set() # Temp list of user added app config file names custom_files = set() # Get the list of custom application config files first if os.path.isdir(custom_apps_dir): for filename in os.listdir(custom_apps_dir): if filename.endswith(".cfg"): config_files.add(os.path.join(custom_apps_dir, filename)) # Also add it to the set of custom apps, so that we don't # add the stock config for the same app too custom_files.add(filename) # Add the default provided app config files, but only if those are not # customized, as we don't want to overwrite custom app config. for filename in os.listdir(apps_dir): if filename.endswith(".cfg") and filename not in custom_files: config_files.add(os.path.join(apps_dir, filename)) return config_files def get_name(self, name): """ Return the fancy name of an application. Args: name (str) Returns: str """ return self.apps[name]["name"] def get_files(self, name): """ Return the list of config files of an application. Args: name (str) Returns: set of str. """ return self.apps[name]["configuration_files"] def get_app_names(self): """ Return application names. Return the list of application names that are available in the database. Returns: set of str. """ app_names = set() for name in self.apps: app_names.add(name) return app_names def get_pretty_app_names(self): """ Return the list of pretty app names that are available in the database. Returns: set of str. """ pretty_app_names = set() for app_name in self.get_app_names(): pretty_app_names.add(self.get_name(app_name)) return pretty_app_names
plugins
tvrby
""" $description Live TV channels from BTRC, a Belarusian public, state-owned broadcaster. $url tvr.by $type live $region Belarus """ import logging import re from streamlink.plugin import Plugin, pluginmatcher from streamlink.plugin.api import validate from streamlink.stream.hls import HLSStream log = logging.getLogger(__name__) @pluginmatcher( re.compile( r"https?://(?:www\.)?tvr\.by/televidenie/belarus", ) ) class TVRBy(Plugin): file_re = re.compile(r"""(?P<url>https://stream\.hoster\.by[^"',]+\.m3u8[^"',]*)""") player_re = re.compile(r"""["'](?P<url>[^"']+tvr\.by/plugines/online-tv-main\.php[^"']+)["']""") stream_schema = validate.Schema( validate.all( validate.transform(file_re.finditer), validate.transform(list), [validate.get("url")], # remove duplicates validate.transform(set), validate.transform(list), ), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # ensure the URL ends with a / if not self.url.endswith("/"): self.url += "/" def _get_streams(self): res = self.session.http.get(self.url) m = self.player_re.search(res.text) if not m: return player_url = m.group("url") res = self.session.http.get(player_url) stream_urls = self.stream_schema.validate(res.text) log.debug("Found {0} stream URL{1}".format(len(stream_urls), "" if len(stream_urls) == 1 else "s")) for stream_url in stream_urls: yield from HLSStream.parse_variant_playlist(self.session, stream_url).items() __plugin__ = TVRBy
PyObjCTest
test_synthesize
""" Tests for objc.synthesize """ import objc from PyObjCTest.fnd import NSObject from PyObjCTools.TestSupport import * class TestSynthesizeCopier(NSObject): def copy(self): return 42 class TestSynthesizeHelper(NSObject): objc.synthesize("someTitle", copy=True) objc.synthesize("stringValue", copy=False) objc.synthesize("read", readwrite=False) class TestSynthesize(TestCase): def testNames(self): self.assertHasAttr(TestSynthesizeHelper, "someTitle") self.assertHasAttr(TestSynthesizeHelper, "setSomeTitle_") self.assertHasAttr(TestSynthesizeHelper, "stringValue") self.assertHasAttr(TestSynthesizeHelper, "setStringValue_") self.assertHasAttr(TestSynthesizeHelper, "read") self.assertNotHasAttr(TestSynthesizeHelper, "setRead_") def testCopying(self): obj = TestSynthesizeHelper.alloc().init() v = TestSynthesizeCopier.alloc().init() obj.setStringValue_(v) self.assertIs(obj.stringValue(), v) obj.setSomeTitle_(v) self.assertEqual(obj.someTitle(), 42) def testFailures(self): self.assertRaises(ValueError, objc.synthesize, "") self.assertRaises(ValueError, objc.synthesize, None) if __name__ == "__main__": main()
hogql-queries
trends_query_runner
from datetime import timedelta from itertools import groupby from math import ceil from operator import itemgetter from typing import Any, Dict, List, Optional from django.utils.timezone import datetime from posthog.caching.insights_api import ( BASE_MINIMUM_INSIGHT_REFRESH_INTERVAL, REDUCED_MINIMUM_INSIGHT_REFRESH_INTERVAL, ) from posthog.caching.utils import is_stale from posthog.hogql import ast from posthog.hogql.parser import parse_expr, parse_select from posthog.hogql.property import property_to_expr from posthog.hogql.query import execute_hogql_query from posthog.hogql.timings import HogQLTimings from posthog.hogql_queries.query_runner import QueryRunner from posthog.hogql_queries.utils.formula_ast import FormulaAST from posthog.hogql_queries.utils.query_date_range import QueryDateRange from posthog.hogql_queries.utils.query_previous_period_date_range import ( QueryPreviousPeriodDateRange, ) from posthog.models import Team from posthog.models.filters.mixins.utils import cached_property from posthog.schema import ( ActionsNode, EventsNode, HogQLQueryResponse, TrendsQuery, TrendsQueryResponse, ) class SeriesWithExtras: series: EventsNode | ActionsNode is_previous_period_series: Optional[bool] def __init__( self, series: EventsNode | ActionsNode, is_previous_period_series: Optional[bool], ): self.series = series self.is_previous_period_series = is_previous_period_series class TrendsQueryRunner(QueryRunner): query: TrendsQuery query_type = TrendsQuery series: List[SeriesWithExtras] def __init__( self, query: TrendsQuery | Dict[str, Any], team: Team, timings: Optional[HogQLTimings] = None, ): super().__init__(query, team, timings) self.series = self.setup_series() def to_query(self) -> List[ast.SelectQuery]: queries = [] with self.timings.measure("trends_query"): for series in self.series: if not series.is_previous_period_series: date_placeholders = self.query_date_range.to_placeholders() else: date_placeholders = self.query_previous_date_range.to_placeholders() queries.append( parse_select( """ SELECT groupArray(day_start) AS date, groupArray(count) AS total FROM ( SELECT sum(total) AS count, day_start FROM ( SELECT 0 AS total, dateTrunc({interval}, {date_to}) - {number_interval_period} AS day_start FROM numbers( coalesce(dateDiff({interval}, {date_from}, {date_to}), 0) ) UNION ALL SELECT 0 AS total, {date_from} UNION ALL SELECT {aggregation_operation} AS total, dateTrunc({interval}, toTimeZone(toDateTime(timestamp), 'UTC')) AS date FROM events AS e %s WHERE {events_filter} GROUP BY date ) GROUP BY day_start ORDER BY day_start ASC ) """ % (self.sample_value()), placeholders={ **date_placeholders, "events_filter": self.events_filter(series), "aggregation_operation": self.aggregation_operation( series.series ), }, timings=self.timings, ) ) return queries def _is_stale(self, cached_result_package): date_to = self.query_date_range.date_to() interval = self.query_date_range.interval_name return is_stale(self.team, date_to, interval, cached_result_package) def _refresh_frequency(self): date_to = self.query_date_range.date_to() date_from = self.query_date_range.date_from() interval = self.query_date_range.interval_name delta_days: Optional[int] = None if date_from and date_to: delta = date_to - date_from delta_days = ceil(delta.total_seconds() / timedelta(days=1).total_seconds()) refresh_frequency = BASE_MINIMUM_INSIGHT_REFRESH_INTERVAL if interval == "hour" or (delta_days is not None and delta_days <= 7): # The interval is shorter for short-term insights refresh_frequency = REDUCED_MINIMUM_INSIGHT_REFRESH_INTERVAL return refresh_frequency def to_persons_query(self) -> str: # TODO: add support for selecting and filtering by breakdowns raise NotImplementedError() def calculate(self): queries = self.to_query() res = [] timings = [] for index, query in enumerate(queries): series_with_extra = self.series[index] response = execute_hogql_query( query_type="TrendsQuery", query=query, team=self.team, timings=self.timings, ) timings.extend(response.timings) res.extend(self.build_series_response(response, series_with_extra)) if ( self.query.trendsFilter is not None and self.query.trendsFilter.formula is not None ): res = self.apply_formula(self.query.trendsFilter.formula, res) return TrendsQueryResponse(result=res, timings=timings) def build_series_response( self, response: HogQLQueryResponse, series: SeriesWithExtras ): if response.results is None: return [] res = [] for val in response.results: series_object = { "data": val[1], "labels": [ item.strftime("%-d-%b-%Y") for item in val[0] ], # Add back in hour formatting "days": [ item.strftime("%Y-%m-%d") for item in val[0] ], # Add back in hour formatting "count": float(sum(val[1])), "label": "All events" if self.series_event(series.series) is None else self.series_event(series.series), } # Modifications for when comparing to previous period if self.query.trendsFilter is not None and self.query.trendsFilter.compare: labels = [ "{} {}".format( self.query.interval if self.query.interval is not None else "day", i, ) for i in range(len(series_object["labels"])) ] series_object["compare"] = True series_object["compare_label"] = ( "previous" if series.is_previous_period_series else "current" ) series_object["labels"] = labels res.append(series_object) return res @cached_property def query_date_range(self): return QueryDateRange( date_range=self.query.dateRange, team=self.team, interval=self.query.interval, now=datetime.now(), ) @cached_property def query_previous_date_range(self): return QueryPreviousPeriodDateRange( date_range=self.query.dateRange, team=self.team, interval=self.query.interval, now=datetime.now(), ) def aggregation_operation(self, series: EventsNode | ActionsNode) -> ast.Expr: if series.math == "hogql": return parse_expr(series.math_hogql) return parse_expr("count(*)") def events_filter(self, series_with_extra: SeriesWithExtras) -> ast.Expr: series = series_with_extra.series filters: List[ast.Expr] = [] # Team ID filters.append( parse_expr( "team_id = {team_id}", placeholders={"team_id": ast.Constant(value=self.team.pk)}, ) ) if not series_with_extra.is_previous_period_series: # Dates (current period) filters.extend( [ parse_expr( "(toTimeZone(timestamp, 'UTC') >= {date_from})", placeholders=self.query_date_range.to_placeholders(), ), parse_expr( "(toTimeZone(timestamp, 'UTC') <= {date_to})", placeholders=self.query_date_range.to_placeholders(), ), ] ) else: # Date (previous period) filters.extend( [ parse_expr( "(toTimeZone(timestamp, 'UTC') >= {date_from})", placeholders=self.query_previous_date_range.to_placeholders(), ), parse_expr( "(toTimeZone(timestamp, 'UTC') <= {date_to})", placeholders=self.query_previous_date_range.to_placeholders(), ), ] ) # Series if self.series_event(series) is not None: filters.append( parse_expr( "event = {event}", placeholders={ "event": ast.Constant(value=self.series_event(series)) }, ) ) # Filter Test Accounts if ( self.query.filterTestAccounts and isinstance(self.team.test_account_filters, list) and len(self.team.test_account_filters) > 0 ): for property in self.team.test_account_filters: filters.append(property_to_expr(property, self.team)) # Properties if self.query.properties is not None and self.query.properties != []: filters.append(property_to_expr(self.query.properties, self.team)) # Series Filters if series.properties is not None and series.properties != []: filters.append(property_to_expr(series.properties, self.team)) if len(filters) == 0: return ast.Constant(value=True) elif len(filters) == 1: return filters[0] else: return ast.And(exprs=filters) # Using string interpolation for SAMPLE due to HogQL limitations with `UNION ALL` and `SAMPLE` AST nodes def sample_value(self) -> str: if self.query.samplingFactor is None: return "" return f"SAMPLE {self.query.samplingFactor}" def series_event(self, series: EventsNode | ActionsNode) -> str | None: if isinstance(series, EventsNode): return series.event return None def setup_series(self) -> List[SeriesWithExtras]: if self.query.trendsFilter is not None and self.query.trendsFilter.compare: updated_series = [] for series in self.query.series: updated_series.append( SeriesWithExtras(series, is_previous_period_series=False) ) updated_series.append( SeriesWithExtras(series, is_previous_period_series=True) ) return updated_series return [ SeriesWithExtras(series, is_previous_period_series=False) for series in self.query.series ] def apply_formula( self, formula: str, results: List[Dict[str, Any]] ) -> List[Dict[str, Any]]: if self.query.trendsFilter is not None and self.query.trendsFilter.compare: sorted_results = sorted(results, key=itemgetter("compare_label")) res = [] for _, group in groupby(sorted_results, key=itemgetter("compare_label")): group_list = list(group) series_data = map(lambda s: s["data"], group_list) new_series_data = FormulaAST(series_data).call(formula) new_result = group_list[0] new_result["data"] = new_series_data new_result["count"] = float(sum(new_series_data)) new_result["label"] = f"Formula ({formula})" res.append(new_result) return res series_data = map(lambda s: s["data"], results) new_series_data = FormulaAST(series_data).call(formula) new_result = results[0] new_result["data"] = new_series_data new_result["count"] = float(sum(new_series_data)) new_result["label"] = f"Formula ({formula})" return [new_result]
file-import
abc
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/ # # Copyright (c) 2008 - 2014 by Wilbert Berendsen # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # See http://www.gnu.org/licenses/ for more information. """ Import ABC dialog. Uses abc2ly to create ly file from abc. In the dialog the options of abc2ly can be set. """ import os import app import qutil import util from PyQt5.QtCore import QSettings, QSize from PyQt5.QtWidgets import QCheckBox, QComboBox, QDialogButtonBox, QLabel from . import toly_dialog class Dialog(toly_dialog.ToLyDialog): def __init__(self, parent=None): self.nobeamCheck = QCheckBox() self.impChecks = [self.nobeamCheck] self.nobeamCheck.setObjectName("import-beaming") self.impExtra = [] super().__init__(parent, imp_prgm="abc2ly", userg="abc_import") app.translateUI(self) qutil.saveDialogSize(self, "abc_import/dialog/size", QSize(480, 160)) self.loadSettings() def translateUI(self): self.nobeamCheck.setText(_("Import beaming")) self.buttons.button(QDialogButtonBox.Ok).setText(_("Run abc2ly")) super().translateUI() def configure_job(self): super().configure_job() if self.nobeamCheck.isChecked(): self._job.add_argument("-b") def loadSettings(self): """Get users previous settings.""" self.imp_default = [True] self.settings = QSettings() self.settings.beginGroup("abc_import") super().loadSettings() def saveSettings(self): """Save users last settings.""" self.settings = QSettings() self.settings.beginGroup("abc_import") super().saveSettings()
builders
hyperparams_builder
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Builder function to construct tf-slim arg_scope for convolution, fc ops.""" import tensorflow as tf from app.object_detection.protos import hyperparams_pb2 slim = tf.contrib.slim def build(hyperparams_config, is_training): """Builds tf-slim arg_scope for convolution ops based on the config. Returns an arg_scope to use for convolution ops containing weights initializer, weights regularizer, activation function, batch norm function and batch norm parameters based on the configuration. Note that if the batch_norm parameteres are not specified in the config (i.e. left to default) then batch norm is excluded from the arg_scope. The batch norm parameters are set for updates based on `is_training` argument and conv_hyperparams_config.batch_norm.train parameter. During training, they are updated only if batch_norm.train parameter is true. However, during eval, no updates are made to the batch norm variables. In both cases, their current values are used during forward pass. Args: hyperparams_config: hyperparams.proto object containing hyperparameters. is_training: Whether the network is in training mode. Returns: arg_scope: tf-slim arg_scope containing hyperparameters for ops. Raises: ValueError: if hyperparams_config is not of type hyperparams.Hyperparams. """ if not isinstance(hyperparams_config, hyperparams_pb2.Hyperparams): raise ValueError( "hyperparams_config not of type " "hyperparams_pb.Hyperparams." ) batch_norm = None batch_norm_params = None if hyperparams_config.HasField("batch_norm"): batch_norm = slim.batch_norm batch_norm_params = _build_batch_norm_params( hyperparams_config.batch_norm, is_training ) affected_ops = [slim.conv2d, slim.separable_conv2d, slim.conv2d_transpose] if hyperparams_config.HasField("op") and ( hyperparams_config.op == hyperparams_pb2.Hyperparams.FC ): affected_ops = [slim.fully_connected] with slim.arg_scope( affected_ops, weights_regularizer=_build_regularizer(hyperparams_config.regularizer), weights_initializer=_build_initializer(hyperparams_config.initializer), activation_fn=_build_activation_fn(hyperparams_config.activation), normalizer_fn=batch_norm, normalizer_params=batch_norm_params, ) as sc: return sc def _build_activation_fn(activation_fn): """Builds a callable activation from config. Args: activation_fn: hyperparams_pb2.Hyperparams.activation Returns: Callable activation function. Raises: ValueError: On unknown activation function. """ if activation_fn == hyperparams_pb2.Hyperparams.NONE: return None if activation_fn == hyperparams_pb2.Hyperparams.RELU: return tf.nn.relu if activation_fn == hyperparams_pb2.Hyperparams.RELU_6: return tf.nn.relu6 raise ValueError("Unknown activation function: {}".format(activation_fn)) def _build_regularizer(regularizer): """Builds a tf-slim regularizer from config. Args: regularizer: hyperparams_pb2.Hyperparams.regularizer proto. Returns: tf-slim regularizer. Raises: ValueError: On unknown regularizer. """ regularizer_oneof = regularizer.WhichOneof("regularizer_oneof") if regularizer_oneof == "l1_regularizer": return slim.l1_regularizer(scale=float(regularizer.l1_regularizer.weight)) if regularizer_oneof == "l2_regularizer": return slim.l2_regularizer(scale=float(regularizer.l2_regularizer.weight)) raise ValueError("Unknown regularizer function: {}".format(regularizer_oneof)) def _build_initializer(initializer): """Build a tf initializer from config. Args: initializer: hyperparams_pb2.Hyperparams.regularizer proto. Returns: tf initializer. Raises: ValueError: On unknown initializer. """ initializer_oneof = initializer.WhichOneof("initializer_oneof") if initializer_oneof == "truncated_normal_initializer": return tf.truncated_normal_initializer( mean=initializer.truncated_normal_initializer.mean, stddev=initializer.truncated_normal_initializer.stddev, ) if initializer_oneof == "variance_scaling_initializer": enum_descriptor = ( hyperparams_pb2.VarianceScalingInitializer.DESCRIPTOR.enum_types_by_name[ "Mode" ] ) mode = enum_descriptor.values_by_number[ initializer.variance_scaling_initializer.mode ].name return slim.variance_scaling_initializer( factor=initializer.variance_scaling_initializer.factor, mode=mode, uniform=initializer.variance_scaling_initializer.uniform, ) raise ValueError("Unknown initializer function: {}".format(initializer_oneof)) def _build_batch_norm_params(batch_norm, is_training): """Build a dictionary of batch_norm params from config. Args: batch_norm: hyperparams_pb2.ConvHyperparams.batch_norm proto. is_training: Whether the models is in training mode. Returns: A dictionary containing batch_norm parameters. """ batch_norm_params = { "decay": batch_norm.decay, "center": batch_norm.center, "scale": batch_norm.scale, "epsilon": batch_norm.epsilon, "is_training": is_training and batch_norm.train, } return batch_norm_params
utils
html
# -*- encoding: utf-8 -*- import html import bleach import misaka class Sanitizer(object): def __init__(self, elements, attributes): # attributes found in Sundown's HTML serializer [1] # - except for <img> tag, because images are not generated anyways. # - sub and sup added # # [1] https://github.com/vmg/sundown/blob/master/html/html.c self.elements = [ "a", "p", "hr", "br", "ol", "ul", "li", "pre", "code", "blockquote", "del", "ins", "strong", "em", "h1", "h2", "h3", "h4", "h5", "h6", "sub", "sup", "table", "thead", "tbody", "th", "td", ] + elements # href for <a> and align for <table> self.attributes = ["align", "href"] + attributes def sanitize(self, text): clean_html = bleach.clean( text, tags=self.elements, attributes=self.attributes, strip=True ) def set_links(attrs, new=False): href_key = (None, "href") if href_key not in attrs: return attrs if attrs[href_key].startswith("mailto:"): return attrs rel_key = (None, "rel") rel_values = [val for val in attrs.get(rel_key, "").split(" ") if val] for value in ["nofollow", "noopener"]: if value not in [rel_val.lower() for rel_val in rel_values]: rel_values.append(value) attrs[rel_key] = " ".join(rel_values) return attrs linker = bleach.linkifier.Linker(callbacks=[set_links]) return linker.linkify(clean_html) def Markdown( extensions=( "autolink", "fenced-code", "no-intra-emphasis", "strikethrough", "superscript", ), flags=[], ): renderer = Unofficial(flags=flags) md = misaka.Markdown(renderer, extensions=extensions) def inner(text): rv = md(text).rstrip("\n") if rv.startswith("<p>") or rv.endswith("</p>"): return rv return "<p>" + rv + "</p>" return inner class Unofficial(misaka.HtmlRenderer): """A few modifications to process "common" Markdown. For instance, fenced code blocks (~~~ or ```) are just wrapped in <code> which does not preserve line breaks. If a language is given, it is added to <code class="$lang">, compatible with Highlight.js. """ def blockcode(self, text, lang): lang = ' class="{0}"'.format(html.escape(lang)) if lang else "" return "<pre><code{1}>{0}</code></pre>\n".format(html.escape(text, False), lang) class Markup(object): def __init__(self, conf): self.flags = conf.getlist("flags") self.extensions = conf.getlist("options") # Normalize render flags and extensions for misaka 2.0, which uses # `dashed-case` instead of `snake_case` (misaka 1.x) for options. self.flags = [x.replace("_", "-") for x in self.flags] self.extensions = [x.replace("_", "-") for x in self.extensions] parser = Markdown(extensions=self.extensions, flags=self.flags) # Filter out empty strings: allowed_elements = [x for x in conf.getlist("allowed-elements") if x] allowed_attributes = [x for x in conf.getlist("allowed-attributes") if x] # If images are allowed, source element should be allowed as well if "img" in allowed_elements and "src" not in allowed_attributes: allowed_attributes.append("src") sanitizer = Sanitizer(allowed_elements, allowed_attributes) self._render = lambda text: sanitizer.sanitize(parser(text)) def render(self, text): return self._render(text)
sabnzbd
misc
#!/usr/bin/python3 -OO # Copyright 2007-2023 The SABnzbd-Team (sabnzbd.org) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ sabnzbd.misc - misc classes """ import ctypes import datetime import html import inspect import ipaddress import logging import os import re import socket import ssl import subprocess import sys import time import urllib.parse import urllib.request from threading import Thread from typing import Any, AnyStr, Dict, List, Optional, Tuple, Union import sabnzbd import sabnzbd.cfg as cfg import sabnzbd.config as config import sabnzbd.getipaddress import socks from sabnzbd.constants import ( DEF_ARTICLE_CACHE_DEFAULT, DEF_ARTICLE_CACHE_MAX, DEFAULT_PRIORITY, GUESSIT_SORT_TYPES, MEBI, REPAIR_REQUEST, ) from sabnzbd.encoding import ubtou from sabnzbd.filesystem import is_valid_script, make_script_path, remove_file, userxbit if sabnzbd.WIN32: try: import win32con import win32process # Define scheduling priorities WIN_SCHED_PRIOS = { 1: win32process.IDLE_PRIORITY_CLASS, 2: win32process.BELOW_NORMAL_PRIORITY_CLASS, 3: win32process.NORMAL_PRIORITY_CLASS, 4: win32process.ABOVE_NORMAL_PRIORITY_CLASS, } except ImportError: pass if sabnzbd.MACOS: from sabnzbd.utils import sleepless TAB_UNITS = ("", "K", "M", "G", "T", "P") RE_UNITS = re.compile(r"(\d+\.*\d*)\s*([KMGTP]?)", re.I) RE_VERSION = re.compile(r"(\d+)\.(\d+)\.(\d+)([a-zA-Z]*)(\d*)") RE_SAMPLE = re.compile( r"((^|[\W_])(sample|proof))", re.I ) # something-sample or something-proof RE_IP4 = re.compile(r"inet\s+(addr:\s*)?(\d+\.\d+\.\d+\.\d+)") RE_IP6 = re.compile(r"inet6\s+(addr:\s*)?([0-9a-f:]+)", re.I) # Check if strings are defined for AM and PM HAVE_AMPM = bool(time.strftime("%p")) def helpful_warning(*args, **kwargs): """Wrapper to ignore helpful warnings if desired""" if sabnzbd.cfg.helpful_warnings(): return logging.warning(*args, **kwargs) return logging.info(*args, **kwargs) def time_format(fmt): """Return time-format string adjusted for 12/24 hour clock setting""" if cfg.ampm() and HAVE_AMPM: return fmt.replace("%H:%M:%S", "%I:%M:%S %p").replace("%H:%M", "%I:%M %p") else: return fmt def format_time_left(totalseconds: int, short_format: bool = False) -> str: """Calculate the time left in the format [DD:]HH:MM:SS or [DD:][HH:]MM:SS (short_format)""" if totalseconds > 0: try: minutes, seconds = divmod(totalseconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) if seconds < 10: seconds = "0%s" % seconds if hours > 0 or not short_format: if minutes < 10: minutes = "0%s" % minutes if days > 0: if hours < 10: hours = "0%s" % hours return "%s:%s:%s:%s" % (days, hours, minutes, seconds) else: return "%s:%s:%s" % (hours, minutes, seconds) else: return "%s:%s" % (minutes, seconds) except: pass if short_format: return "0:00" return "0:00:00" def calc_age(date: datetime.datetime, trans: bool = False) -> str: """Calculate the age difference between now and date. Value is returned as either days, hours, or minutes. When 'trans' is True, time symbols will be translated. """ if trans: d = T("d") # : Single letter abbreviation of day h = T("h") # : Single letter abbreviation of hour m = T("m") # : Single letter abbreviation of minute else: d = "d" h = "h" m = "m" try: # Return time difference in human-readable format date_diff = datetime.datetime.now() - date if date_diff.days: return "%d%s" % (date_diff.days, d) elif int(date_diff.seconds / 3600): return "%d%s" % (date_diff.seconds / 3600, h) else: return "%d%s" % (date_diff.seconds / 60, m) except: return "-" def safe_lower(txt: Any) -> str: """Return lowercased string. Return '' for None""" if txt: return txt.lower() else: return "" def cmp(x, y): """ Replacement for built-in function cmp that was removed in Python 3 Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. """ return (x > y) - (x < y) def name_to_cat(fname, cat=None): """Retrieve category from file name, but only if "cat" is None.""" if cat is None and fname.startswith("{{"): n = fname.find("}}") if n > 2: cat = fname[2:n].strip() fname = fname[n + 2 :].strip() logging.debug("Job %s has category %s", fname, cat) return fname, cat def cat_to_opts(cat, pp=None, script=None, priority=None) -> Tuple[str, int, str, int]: """Derive options from category, if options not already defined. Specified options have priority over category-options. If no valid category is given, special category '*' will supply default values """ def_cat = config.get_category() cat = safe_lower(cat) if cat in ("", "none", "default"): cat = "*" my_cat = config.get_category(cat) # Ignore the input category if we don't know it if my_cat == def_cat: cat = "*" if pp is None: pp = my_cat.pp() if pp == "": pp = def_cat.pp() if not script: script = my_cat.script() if safe_lower(script) in ("", "default"): script = def_cat.script() if priority is None or priority == "" or priority == DEFAULT_PRIORITY: priority = my_cat.priority() if priority == DEFAULT_PRIORITY: priority = def_cat.priority() logging.debug( "Parsing category %s to attributes: pp=%s script=%s prio=%s", cat, pp, script, priority, ) return cat, pp, script, priority def pp_to_opts(pp: int) -> Tuple[bool, bool, bool]: """Convert numeric processing options to (repair, unpack, delete)""" # Convert the pp to an int pp = sabnzbd.interface.int_conv(pp) if pp == 0: return False, False, False if pp == 1: return True, False, False if pp == 2: return True, True, False return True, True, True def opts_to_pp(repair: bool, unpack: bool, delete: bool) -> int: """Convert (repair, unpack, delete) to numeric process options""" if delete: return 3 if unpack: return 2 if repair: return 1 return 0 def sort_to_opts(sort_type: str) -> int: """Convert a guessed sort_type to its integer equivalent""" for k, v in GUESSIT_SORT_TYPES.items(): if v == sort_type: return k else: logging.debug( "Invalid sort_type %s, pretending a match to 0 ('all')", sort_type ) return 0 _wildcard_to_regex = { "\\": r"\\", "^": r"\^", "$": r"\$", ".": r"\.", "[": r"\[", "]": r"\]", "(": r"\(", ")": r"\)", "+": r"\+", "?": r".", "|": r"\|", "{": r"\{", "}": r"\}", "*": r".*", } def wildcard_to_re(text): """Convert plain wildcard string (with '*' and '?') to regex.""" return "".join([_wildcard_to_regex.get(ch, ch) for ch in text]) def convert_filter(text): """Return compiled regex. If string starts with re: it's a real regex else quote all regex specials, replace '*' by '.*' """ text = text.strip().lower() if text.startswith("re:"): txt = text[3:].strip() else: txt = wildcard_to_re(text) try: return re.compile(txt, re.I) except: logging.debug("Could not compile regex: %s", text) return None def cat_convert(cat): """Convert indexer's category/group-name to user categories. If no match found, but indexer-cat equals user-cat, then return user-cat If no match found, but the indexer-cat starts with the user-cat, return user-cat If no match found, return None """ if cat and cat.lower() != "none": cats = config.get_ordered_categories() raw_cats = config.get_categories() for ucat in cats: try: # Ordered cat-list has tags only as string indexer = raw_cats[ucat["name"]].newzbin() if not isinstance(indexer, list): indexer = [indexer] except: indexer = [] for name in indexer: if re.search("^%s$" % wildcard_to_re(name), cat, re.I): if "." in name: logging.debug( 'Convert group "%s" to user-cat "%s"', cat, ucat["name"] ) else: logging.debug( 'Convert index site category "%s" to user-cat "%s"', cat, ucat["name"], ) return ucat["name"] # Try to find full match between user category and indexer category for ucat in cats: if cat.lower() == ucat["name"].lower(): logging.debug( 'Convert index site category "%s" to user-cat "%s"', cat, ucat["name"], ) return ucat["name"] # Try to find partial match between user category and indexer category for ucat in cats: if cat.lower().startswith(ucat["name"].lower()): logging.debug( 'Convert index site category "%s" to user-cat "%s"', cat, ucat["name"], ) return ucat["name"] return None _SERVICE_KEY = "SYSTEM\\CurrentControlSet\\services\\" _SERVICE_PARM = "CommandLine" def get_serv_parms(service): """Get the service command line parameters from Registry""" import winreg service_parms = [] try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _SERVICE_KEY + service) for n in range(winreg.QueryInfoKey(key)[1]): name, service_parms, _val_type = winreg.EnumValue(key, n) if name == _SERVICE_PARM: break winreg.CloseKey(key) except OSError: pass # Always add the base program service_parms.insert(0, os.path.normpath(os.path.abspath(sys.argv[0]))) return service_parms def set_serv_parms(service, args): """Set the service command line parameters in Registry""" import winreg serv = [] for arg in args: serv.append(arg[0]) if arg[1]: serv.append(arg[1]) try: key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, _SERVICE_KEY + service) winreg.SetValueEx(key, _SERVICE_PARM, None, winreg.REG_MULTI_SZ, serv) winreg.CloseKey(key) except OSError: return False return True def get_from_url(url: str) -> Optional[str]: """Retrieve URL and return content""" try: req = urllib.request.Request(url) req.add_header("User-Agent", "SABnzbd/%s" % sabnzbd.__version__) with urllib.request.urlopen(req) as response: return ubtou(response.read()) except: return None def convert_version(text): """Convert version string to numerical value and a testversion indicator""" version = 0 test = True if m := RE_VERSION.search(ubtou(text)): version = ( int(m.group(1)) * 1000000 + int(m.group(2)) * 10000 + int(m.group(3)) * 100 ) try: if m.group(4).lower() == "rc": version = version + 80 elif m.group(4).lower() == "beta": version = version + 40 version = version + int(m.group(5)) except: version = version + 99 test = False return version, test def check_latest_version(): """Do an online check for the latest version Perform an online version check Syntax of online version file: <current-final-release> <url-of-current-final-release> <latest-alpha/beta-or-rc> <url-of-latest-alpha/beta/rc-release> The latter two lines are only present when an alpha/beta/rc is available. Formula for the version numbers (line 1 and 3). <major>.<minor>.<bugfix>[rc|beta|alpha]<cand> The <cand> value for a final version is assumed to be 99. The <cand> value for the beta/rc version is 1..98, with RC getting a boost of 80 and Beta of 40. This is done to signal alpha/beta/rc users of availability of the final version (which is implicitly 99). People will only be informed to upgrade to a higher alpha/beta/rc version, if they are already using an alpha/beta/rc. RC's are valued higher than Beta's, which are valued higher than Alpha's. """ if not cfg.version_check(): return current, testver = convert_version(sabnzbd.__version__) if not current: logging.debug( "Unsupported release number (%s), will not check", sabnzbd.__version__ ) return # Fetch version info data = get_from_url("https://sabnzbd.org/latest.txt") if not data: logging.info("Cannot retrieve version information from GitHub.com") logging.debug("Traceback: ", exc_info=True) return version_data = data.split() try: latest_label = version_data[0] url = version_data[1] except: latest_label = "" url = "" try: latest_testlabel = version_data[2] url_beta = version_data[3] except: latest_testlabel = "" url_beta = "" latest = convert_version(latest_label)[0] latest_test = convert_version(latest_testlabel)[0] logging.debug( "Checked for a new release, cur=%s, latest=%s (on %s), latest_test=%s (on %s)", current, latest, url, latest_test, url_beta, ) if latest_test and cfg.version_check() > 1: # User always wants to see the latest test release latest = latest_test latest_label = latest_testlabel url = url_beta notify_version = None if current < latest: # This is a test version, but user hasn't seen the # "Final" of this one yet, so show the Final # Or this one is behind, show latest final sabnzbd.NEW_VERSION = (latest_label, url) notify_version = latest_label elif testver and current < latest_test: # This is a test version beyond the latest Final, so show latest Alpha/Beta/RC sabnzbd.NEW_VERSION = (latest_testlabel, url_beta) notify_version = latest_testlabel if notify_version: sabnzbd.notifier.send_notification( T("Update Available!"), "SABnzbd %s" % notify_version, "other" ) def upload_file_to_sabnzbd(url, fp): """Function for uploading nzbs to a running SABnzbd instance""" try: fp = urllib.parse.quote_plus(fp) url = "%s&mode=addlocalfile&name=%s" % (url, fp) # Add local API-key if it wasn't already in the registered URL apikey = cfg.api_key() if apikey and "apikey" not in url: url = "%s&apikey=%s" % (url, apikey) if "apikey" not in url: # Use alternative login method username = cfg.username() password = cfg.password() if username and password: url = "%s&ma_username=%s&ma_password=%s" % (url, username, password) get_from_url(url) except: logging.error(T("Failed to upload file: %s"), fp) logging.info("Traceback: ", exc_info=True) def from_units(val: str) -> float: """Convert K/M/G/T/P notation to float Does not support negative numbers""" val = str(val).strip().upper() if val == "-1": return float(val) if m := RE_UNITS.search(val): if m.group(2): val = float(m.group(1)) unit = m.group(2) n = 0 while unit != TAB_UNITS[n]: val = val * 1024.0 n = n + 1 else: val = m.group(1) try: return float(val) except: return 0.0 else: return 0.0 def to_units(val: Union[int, float], postfix="") -> str: """Convert number to K/M/G/T/P notation Show single decimal for M and higher Also supports negative numbers """ if not isinstance(val, (int, float)): return "" if val < 0: sign = "-" else: sign = "" # Determine what form we are at val = abs(val) n = 0 while (val > 1023) and (n < 5): val = val / 1024 n = n + 1 if n > 1: decimals = 1 else: decimals = 0 return ("%%s%%.%sf %%s%%s" % decimals) % (sign, val, TAB_UNITS[n], postfix) def caller_name(skip=2): """Get a name of a caller in the format module.method Originally used: https://gist.github.com/techtonik/2151727 Adapted for speed by using sys calls directly """ # Only do the tracing on Debug (function is always called) if cfg.log_level() != 2: return "N/A" parentframe = sys._getframe(skip) function_name = parentframe.f_code.co_name # Module name is not available in the binaries, we can use the filename instead if hasattr(sys, "frozen"): module_name = inspect.getfile(parentframe) else: module_name = inspect.getmodule(parentframe).__name__ # For decorated functions we have to go deeper if function_name in ("call_func", "wrap") and skip == 2: return caller_name(4) return ".".join([module_name, function_name]) def exit_sab(value: int): """Leave the program after flushing stderr/stdout""" try: sys.stderr.flush() sys.stdout.flush() except AttributeError: # Not supported on Windows binaries pass # Cannot use sys.exit as it will not work inside the macOS-runner-thread os._exit(value) def split_host(srv): """Split host:port notation, allowing for IPV6""" if not srv: return None, None # IPV6 literal (with no port) if srv[-1] == "]": return srv, None out = srv.rsplit(":", 1) if len(out) == 1: # No port port = None else: try: port = int(out[1]) except ValueError: return srv, None return out[0], port def get_cache_limit(): """Depending on OS, calculate cache limits. In ArticleCache it will make sure we stay within system limits for 32/64 bit """ # Calculate, if possible try: if sabnzbd.WIN32: # Windows mem_bytes = get_windows_memory() elif sabnzbd.MACOS: # macOS mem_bytes = get_macos_memory() else: # Linux mem_bytes = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") # Use 1/4th of available memory mem_bytes = mem_bytes / 4 # We don't want to set a value that's too high if mem_bytes > from_units(DEF_ARTICLE_CACHE_MAX): return DEF_ARTICLE_CACHE_MAX # We make sure it's at least a valid value if mem_bytes > from_units("32M"): return to_units(mem_bytes) except: pass # Always at least minimum on Windows/macOS if sabnzbd.WIN32 and sabnzbd.MACOS: return DEF_ARTICLE_CACHE_DEFAULT # If failed, leave empty for Linux so user needs to decide return "" def get_windows_memory(): """Use ctypes to extract available memory""" class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("sullAvailExtendedVirtual", ctypes.c_ulonglong), ] def __init__(self): # have to initialize this to the size of MEMORYSTATUSEX self.dwLength = ctypes.sizeof(self) super(MEMORYSTATUSEX, self).__init__() stat = MEMORYSTATUSEX() ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) return stat.ullTotalPhys def get_macos_memory(): """Use system-call to extract total memory on macOS""" system_output = run_command(["sysctl", "hw.memsize"]) return float(system_output.split()[1]) def on_cleanup_list(filename: str, skip_nzb: bool = False) -> bool: """Return True if a filename matches the clean-up list""" cleanup_list = cfg.cleanup_list() if cleanup_list: name, ext = os.path.splitext(filename) ext = ext.strip().lower() name = name.strip() for cleanup_ext in cleanup_list: cleanup_ext = "." + cleanup_ext if (cleanup_ext == ext or (ext == "" and cleanup_ext == name)) and not ( skip_nzb and cleanup_ext == ".nzb" ): return True return False def memory_usage(): try: # Probably only works on Linux because it uses /proc/<pid>/statm with open("/proc/%d/statm" % os.getpid()) as t: v = t.read().split() virt = int(_PAGE_SIZE * int(v[0]) / MEBI) res = int(_PAGE_SIZE * int(v[1]) / MEBI) return "V=%sM R=%sM" % (virt, res) except IOError: pass except: logging.debug("Error retrieving memory usage") logging.info("Traceback: ", exc_info=True) try: _PAGE_SIZE = os.sysconf("SC_PAGE_SIZE") except: _PAGE_SIZE = 0 _HAVE_STATM = _PAGE_SIZE and memory_usage() def loadavg(): """Return 1, 5 and 15 minute load average of host or "" if not supported""" p = "" if not sabnzbd.WIN32 and not sabnzbd.MACOS: try: p = "%.2f | %.2f | %.2f" % os.getloadavg() except: pass if _HAVE_STATM: p = "%s | %s" % (p, memory_usage()) return p def format_time_string(seconds: float) -> str: """Return a formatted and translated time string""" def unit(single, n): # Seconds and minutes are special due to historical reasons if single == "minute" or (single == "second" and n == 1): single = single[:3] if n == 1: return T(single) return T(single + "s") # Format the string, size by size seconds = int_conv(seconds) completestr = [] days = seconds // 86400 if days >= 1: completestr.append("%s %s" % (days, unit("day", days))) seconds -= days * 86400 hours = seconds // 3600 if hours >= 1: completestr.append("%s %s" % (hours, unit("hour", hours))) seconds -= hours * 3600 minutes = seconds // 60 if minutes >= 1: completestr.append("%s %s" % (minutes, unit("minute", minutes))) seconds -= minutes * 60 if seconds > 0: completestr.append("%s %s" % (seconds, unit("second", seconds))) # Zero or invalid integer if not completestr: completestr.append("0 %s" % unit("second", 0)) return " ".join(completestr) def int_conv(value: Any) -> int: """Safe conversion to int (can handle None)""" try: return int(value) except: return 0 def create_https_certificates(ssl_cert, ssl_key): """Create self-signed HTTPS certificates and store in paths 'ssl_cert' and 'ssl_key'""" try: from sabnzbd.utils.certgen import generate_key, generate_local_cert private_key = generate_key(key_size=2048, output_file=ssl_key) generate_local_cert( private_key, days_valid=3560, output_file=ssl_cert, LN="SABnzbd", ON="SABnzbd", ) logging.info("Self-signed certificates generated successfully") except: logging.error(T("Error creating SSL key and certificate")) logging.info("Traceback: ", exc_info=True) return False return True def get_all_passwords(nzo) -> List[str]: """Get all passwords, from the NZB, meta and password file. In case a working password is already known, try it first.""" passwords = [] if nzo.correct_password: passwords.append(nzo.correct_password) if nzo.password: logging.info("Found a password that was set by the user: %s", nzo.password) passwords.append(nzo.password.strip()) # Note that we get a reference to the list, so adding to it updates the original list! meta_passwords = nzo.meta.get("password", []) pw = nzo.nzo_info.get("password") if pw and pw not in meta_passwords: meta_passwords.append(pw) if meta_passwords: passwords.extend(meta_passwords) logging.info( "Read %s passwords from meta data in NZB: %s", len(meta_passwords), meta_passwords, ) pw_file = cfg.password_file.get_path() if pw_file: try: with open(pw_file, "r") as pwf: lines = pwf.read().split("\n") # Remove empty lines and space-only passwords and remove surrounding spaces pws = [pw.strip("\r\n ") for pw in lines if pw.strip("\r\n ")] logging.debug("Read these passwords from file: %s", pws) passwords.extend(pws) logging.info("Read %s passwords from file %s", len(pws), pw_file) # Check size if len(pws) > 30: helpful_warning( T( "Your password file contains more than 30 passwords, testing all these passwords takes a lot of time. Try to only list useful passwords." ) ) except: logging.warning(T("Failed to read the password file %s"), pw_file) logging.info("Traceback: ", exc_info=True) if nzo.password: # If an explicit password was set, add a retry without password, just in case. passwords.append("") elif not passwords or nzo.encrypted < 1: # If we're not sure about encryption, start with empty password # and make sure we have at least the empty password passwords.insert(0, "") unique_passwords = [] for password in passwords: if password not in unique_passwords: unique_passwords.append(password) return unique_passwords def is_sample(filename: str) -> bool: """Try to determine if filename is (most likely) a sample""" return bool(re.search(RE_SAMPLE, filename)) def find_on_path(targets): """Search the PATH for a program and return full path""" if sabnzbd.WIN32: paths = os.getenv("PATH").split(";") else: paths = os.getenv("PATH").split(":") if isinstance(targets, str): targets = (targets,) for path in paths: for target in targets: target_path = os.path.abspath(os.path.join(path, target)) if os.path.isfile(target_path) and os.access(target_path, os.X_OK): return target_path return None def strip_ipv4_mapped_notation(ip: str) -> str: """Convert an IP address in IPv4-mapped IPv6 notation (e.g. ::ffff:192.168.0.10) to its regular IPv4 form. Any value of ip that doesn't use the relevant notation is returned unchanged. CherryPy may report remote IP addresses in this notation. While the ipaddress module should be able to handle that, the latter has issues with the is_private/is_loopback properties for these addresses. See https://bugs.python.org/issue33433""" try: # Keep the original if ipv4_mapped is None ip = ipaddress.ip_address(ip).ipv4_mapped or ip except (AttributeError, ValueError): pass return str(ip) def ip_in_subnet(ip: str, subnet: str) -> bool: """Determine whether ip is part of subnet. For the latter, the standard form with a prefix or netmask (e.g. "192.168.1.0/24" or "10.42.0.0/255.255.0.0") is expected. Input in SABnzbd's old cfg.local_ranges() settings style (e.g. "192.168.1."), intended for use with str.startswith(), is also accepted and internally converted to address/prefix form.""" if not ip or not subnet: return False try: if subnet.find("/") < 0 and subnet.find("::") < 0: # The subnet doesn't include a prefix or netmask, or represent a single (compressed) # IPv6 address; try converting from the older local_ranges settings style. # Take the IP version of the subnet into account IP_LEN, IP_BITS, IP_SEP = ( (8, 16, ":") if subnet.find(":") >= 0 else (4, 8, ".") ) subnet = subnet.rstrip(IP_SEP).split(IP_SEP) prefix = IP_BITS * len(subnet) # Append as many zeros as needed subnet.extend(["0"] * (IP_LEN - len(subnet))) # Store in address/prefix form subnet = "%s/%s" % (IP_SEP.join(subnet), prefix) ip = strip_ipv4_mapped_notation(ip) return ipaddress.ip_address(ip) in ipaddress.ip_network(subnet, strict=True) except Exception: # Probably an invalid range return False def is_ipv4_addr(ip: str) -> bool: """Determine if the ip is an IPv4 address""" try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6_addr(ip: str) -> bool: """Determine if the ip is an IPv6 address; square brackets ([2001::1]) are OK""" try: return ipaddress.ip_address(ip.strip("[]")).version == 6 except (ValueError, AttributeError): return False def is_loopback_addr(ip: str) -> bool: """Determine if the ip is an IPv4 or IPv6 local loopback address""" try: if ip.find(".") < 0: ip = ip.strip("[]") ip = strip_ipv4_mapped_notation(ip) return ipaddress.ip_address(ip).is_loopback except (ValueError, AttributeError): return False def is_localhost(value: str) -> bool: """Determine if the input is some variety of 'localhost'""" return (value == "localhost") or is_loopback_addr(value) def is_lan_addr(ip: str) -> bool: """Determine if the ip is a local area network address""" try: ip = strip_ipv4_mapped_notation(ip) return ( # The ipaddress module considers these private, see https://bugs.python.org/issue38655 not ip in ("0.0.0.0", "255.255.255.255") and not ip_in_subnet( ip, "::/128" ) # Also catch (partially) exploded forms of "::" and ipaddress.ip_address(ip).is_private and not is_loopback_addr(ip) ) except ValueError: return False def is_local_addr(ip: str) -> bool: """Determine if an IP address is to be considered local, i.e. it's part of a subnet in local_ranges, if defined, or in private address space reserved for local area networks.""" if local_ranges := cfg.local_ranges(): return any(ip_in_subnet(ip, local_range) for local_range in local_ranges) else: return is_lan_addr(ip) def ip_extract() -> List[str]: """Return list of IP addresses of this system""" ips = [] program = find_on_path("ip") if program: program = [program, "a"] else: program = find_on_path("ifconfig") if program: program = [program] if sabnzbd.WIN32 or not program: try: info = socket.getaddrinfo(socket.gethostname(), None) except: # Hostname does not resolve, use localhost info = socket.getaddrinfo("localhost", None) for item in info: ips.append(item[4][0]) else: output = run_command(program) for line in output.split("\n"): m = RE_IP4.search(line) if not (m and m.group(2)): m = RE_IP6.search(line) if m and m.group(2): ips.append(m.group(2)) return ips def get_server_addrinfo(host: str, port: int) -> socket.getaddrinfo: """Return getaddrinfo() based on user settings""" try: if cfg.ipv6_servers(): # Standard IPV4 or IPV6 return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) else: # Only IPv4 return socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM) except: return [] def get_base_url(url: str) -> str: """Return only the true root domain for the favicon, so api.oznzb.com -> oznzb.com But also api.althub.co.za -> althub.co.za """ url_host = urllib.parse.urlparse(url).hostname if url_host: url_split = url_host.split(".") # Exception for localhost and IPv6 addresses if len(url_split) < 3: return url_host return ".".join(len(url_split[-2]) < 4 and url_split[-3:] or url_split[-2:]) else: return "" def match_str(text: AnyStr, matches: Tuple[AnyStr, ...]) -> Optional[AnyStr]: """Return first matching element of list 'matches' in 'text', otherwise None""" text = text.lower() for match in matches: if match.lower() in text: return match return None def recursive_html_escape( input_dict_or_list: Union[Dict[str, Any], List], exclude_items: Tuple[str, ...] = () ): """Recursively update the input_dict in-place with html-safe values""" if isinstance(input_dict_or_list, (dict, list)): if isinstance(input_dict_or_list, dict): iterator = input_dict_or_list.items() else: # For lists we use enumerate iterator = enumerate(input_dict_or_list) for key, value in iterator: # Ignore any keys that are not safe to convert if key not in exclude_items: # We ignore any other than str if isinstance(value, str): input_dict_or_list[key] = html.escape(value, quote=True) if isinstance(value, (dict, list)): recursive_html_escape(value, exclude_items=exclude_items) else: raise ValueError("Expected dict or str, got %s" % type(input_dict_or_list)) def list2cmdline_unrar(lst: List[str]) -> str: """convert list to a unrar.exe-compatible command string Unrar uses "" instead of \" to escape the double quote""" nlst = [] for arg in lst: if not arg: nlst.append('""') else: if isinstance(arg, str): arg = arg.replace('"', '""') nlst.append('"%s"' % arg) return " ".join(nlst) def build_and_run_command( command: List[str], windows_unrar_command: bool = False, text_mode: bool = True, **kwargs, ): """Builds and then runs command with necessary flags and optional IONice and Nice commands. Optional Popen arguments can be supplied. On Windows we need to run our own list2cmdline for Unrar. Returns the Popen-instance. """ # command[0] should be set, and thus not None if not command[0]: logging.error( T("[%s] The command in build_command is undefined."), caller_name() ) raise IOError if not sabnzbd.WIN32: if command[0].endswith(".py"): with open(command[0], "r") as script_file: if not userxbit(command[0]): # Inform user that Python scripts need x-bit and then stop logging.error( T( 'Python script "%s" does not have execute (+x) permission set' ), command[0], ) raise IOError elif script_file.read(2) != "#!": # No shebang (#!) defined, add default python command.insert(0, sys.executable if sys.executable else "python") if sabnzbd.newsunpack.IONICE_COMMAND and cfg.ionice(): ionice = cfg.ionice().split() command = ionice + command command.insert(0, sabnzbd.newsunpack.IONICE_COMMAND) if sabnzbd.newsunpack.NICE_COMMAND and cfg.nice(): nice = cfg.nice().split() command = nice + command command.insert(0, sabnzbd.newsunpack.NICE_COMMAND) creationflags = 0 startupinfo = None else: # For Windows we always need to add python interpreter if command[0].endswith(".py"): command.insert(0, "python.exe") if windows_unrar_command: command = list2cmdline_unrar(command) # On some Windows platforms we need to suppress a quick pop-up of the command window startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags = win32process.STARTF_USESHOWWINDOW startupinfo.wShowWindow = win32con.SW_HIDE creationflags = WIN_SCHED_PRIOS[cfg.win_process_prio()] # Set the basic Popen arguments popen_kwargs = { "stdout": subprocess.PIPE, "stderr": subprocess.STDOUT, "bufsize": 0, "startupinfo": startupinfo, "creationflags": creationflags, } # In text mode we ignore errors if text_mode: # We default to utf8, and hope for the best popen_kwargs.update({"text": True, "encoding": "utf8", "errors": "replace"}) # Update with the supplied ones popen_kwargs.update(kwargs) # Run the command logging.info("[%s] Running external command: %s", caller_name(), command) logging.debug("Popen arguments: %s", popen_kwargs) return subprocess.Popen(command, **popen_kwargs) def run_command(cmd: List[str], **kwargs): """Run simple external command and return output as a string.""" with build_and_run_command(cmd, **kwargs) as p: txt = p.stdout.read() p.wait() return txt def run_script(script): """Run a user script (queue complete only)""" script_path = make_script_path(script) if script_path: try: script_output = run_command([script_path]) logging.info( "Output of queue-complete script %s: \n%s", script, script_output ) except: logging.info( "Failed queue-complete script %s, Traceback: ", script, exc_info=True ) def set_socks5_proxy(): if cfg.socks5_proxy_url(): proxy = urllib.parse.urlparse(cfg.socks5_proxy_url()) logging.info("Using Socks5 proxy %s:%s", proxy.hostname, proxy.port) socks.set_default_proxy( socks.SOCKS5, proxy.hostname, proxy.port, True, # use remote DNS, default proxy.username, proxy.password, ) socket.socket = socks.socksocket def set_https_verification(value): """Set HTTPS-verification state while returning current setting False = disable verification """ prev = ssl._create_default_https_context == ssl.create_default_context if value: ssl._create_default_https_context = ssl.create_default_context else: ssl._create_default_https_context = ssl._create_unverified_context return prev def test_cert_checking(): """Test quality of certificate validation""" # User disabled the test, assume proper SSL certificates if not cfg.selftest_host(): return True # Try a connection to our test-host try: ctx = ssl.create_default_context() base_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = ctx.wrap_socket(base_sock, server_hostname=cfg.selftest_host()) ssl_sock.settimeout(2.0) ssl_sock.connect((cfg.selftest_host(), 443)) ssl_sock.close() return True except (socket.gaierror, socket.timeout): # Non-SSL related error. # We now assume that certificates work instead of forcing # lower quality just because some (temporary) internet problem logging.info( "Could not determine system certificate validation quality due to connection problems" ) return True except: # Seems something is still wrong set_https_verification(False) return False def request_repair(): """Request a full repair on next restart""" path = os.path.join(cfg.admin_dir.get_path(), REPAIR_REQUEST) try: with open(path, "w") as f: f.write("\n") except: pass def check_repair_request(): """Return True if repair request found, remove afterwards""" path = os.path.join(cfg.admin_dir.get_path(), REPAIR_REQUEST) if os.path.exists(path): try: remove_file(path) except: pass return True return False def system_shutdown(): """Shutdown system after halting download and saving bookkeeping""" logging.info("Performing system shutdown") # Do not use regular shutdown, as we should be able to still send system-shutdown Thread(target=sabnzbd.halt).start() while sabnzbd.__INITIALIZED__: time.sleep(1.0) if sabnzbd.WIN32: sabnzbd.powersup.win_shutdown() elif sabnzbd.MACOS: sabnzbd.powersup.osx_shutdown() else: sabnzbd.powersup.linux_shutdown() def system_hibernate(): """Hibernate system""" logging.info("Performing system hybernation") if sabnzbd.WIN32: sabnzbd.powersup.win_hibernate() elif sabnzbd.MACOS: sabnzbd.powersup.osx_hibernate() else: sabnzbd.powersup.linux_hibernate() def system_standby(): """Standby system""" logging.info("Performing system standby") if sabnzbd.WIN32: sabnzbd.powersup.win_standby() elif sabnzbd.MACOS: sabnzbd.powersup.osx_standby() else: sabnzbd.powersup.linux_standby() def change_queue_complete_action(action: str, new: bool = True): """Action or script to be performed once the queue has been completed Scripts are prefixed with 'script_' """ _action = None _argument = None if new or cfg.queue_complete_pers(): if action.startswith("script_") and is_valid_script( action.replace("script_", "", 1) ): # all scripts are labeled script_xxx _action = sabnzbd.misc.run_script _argument = action.replace("script_", "", 1) elif action == "shutdown_pc": _action = system_shutdown elif action == "hibernate_pc": _action = system_hibernate elif action == "standby_pc": _action = system_standby elif action == "shutdown_program": _action = sabnzbd.shutdown_program else: action = None else: action = None if new: cfg.queue_complete.set(action or "") config.save_config() sabnzbd.QUEUECOMPLETE = action sabnzbd.QUEUECOMPLETEACTION = _action sabnzbd.QUEUECOMPLETEARG = _argument def keep_awake(): """If we still have work to do, keep Windows/macOS system awake""" if sabnzbd.KERNEL32 or sabnzbd.FOUNDATION: if sabnzbd.cfg.keep_awake(): ES_CONTINUOUS = 0x80000000 ES_SYSTEM_REQUIRED = 0x00000001 if ( not sabnzbd.Downloader.no_active_jobs() and not sabnzbd.NzbQueue.is_empty() ) or ( not sabnzbd.PostProcessor.paused and not sabnzbd.PostProcessor.empty() ): if sabnzbd.KERNEL32: # Set ES_SYSTEM_REQUIRED until the next call sabnzbd.KERNEL32.SetThreadExecutionState( ES_CONTINUOUS | ES_SYSTEM_REQUIRED ) else: sleepless.keep_awake( "SABnzbd is busy downloading and/or post-processing" ) else: if sabnzbd.KERNEL32: # Allow the regular state again sabnzbd.KERNEL32.SetThreadExecutionState(ES_CONTINUOUS) else: sleepless.allow_sleep() def history_updated(): """To make sure we always have a fresh history""" sabnzbd.LAST_HISTORY_UPDATE += 1 # Never go over the limit if sabnzbd.LAST_HISTORY_UPDATE + 1 >= sys.maxsize: sabnzbd.LAST_HISTORY_UPDATE = 1 def convert_sorter_settings(): """Convert older tv/movie/date sorter settings to the new universal sorter The old settings used: -enable_tv_sorting = OptionBool("misc", "enable_tv_sorting", False) -tv_sort_string = OptionStr("misc", "tv_sort_string") -tv_categories = OptionList("misc", "tv_categories", ["tv"]) -enable_movie_sorting = OptionBool("misc", "enable_movie_sorting", False) -movie_sort_string = OptionStr("misc", "movie_sort_string") -movie_sort_extra = OptionStr("misc", "movie_sort_extra", "-cd%1", strip=False) -movie_categories = OptionList("misc", "movie_categories", ["movies"]) -enable_date_sorting = OptionBool("misc", "enable_date_sorting", False) -date_sort_string = OptionStr("misc", "date_sort_string") -date_categories = OptionList("misc", "date_categories", ["tv"]) -movie_rename_limit = OptionStr("misc", "movie_rename_limit", "100M") -episode_rename_limit = OptionStr("misc", "episode_rename_limit", "20M") The new settings define a sorter as follows (cf. class config.ConfigSorter): name: str { name: str order: int min_size: Union[str|int] = "50M" multipart_label: Optional[str] = "" sort_string: str sort_cats: List[str] sort_type: List[int] is_active: bool = 1 } With the old settings, sorting was tried in a fixed order (series first, movies last); that order is retained by the conversion code. We only convert enabled sorters.""" # Keep track of order order = 0 if cfg.enable_tv_sorting() and cfg.tv_sort_string() and cfg.tv_categories(): # Define a new sorter based on the old configuration tv_sorter = {} tv_sorter["order"] = order tv_sorter["min_size"] = cfg.episode_rename_limit() tv_sorter["multipart_label"] = "" # Previously only available for movie sorting tv_sorter["sort_string"] = cfg.tv_sort_string() tv_sorter["sort_cats"] = cfg.tv_categories() tv_sorter["sort_type"] = [sort_to_opts("tv")] tv_sorter["is_active"] = int(cfg.enable_tv_sorting()) # Configure the new sorter logging.debug( "Converted old series sorter config to '%s': %s", T("Series Sorting"), tv_sorter, ) config.ConfigSorter(T("Series Sorting"), tv_sorter) order += 1 if cfg.enable_date_sorting() and cfg.date_sort_string() and cfg.date_categories(): date_sorter = {} date_sorter["order"] = order date_sorter["min_size"] = cfg.episode_rename_limit() date_sorter[ "multipart_label" ] = "" # Previously only available for movie sorting date_sorter["sort_string"] = cfg.date_sort_string() date_sorter["sort_cats"] = cfg.date_categories() date_sorter["sort_type"] = [sort_to_opts("date")] date_sorter["is_active"] = int(cfg.enable_date_sorting()) # Configure the new sorter logging.debug( "Converted old date sorter config to '%s': %s", T("Date Sorting"), date_sorter, ) config.ConfigSorter(T("Date Sorting"), date_sorter) order += 1 if ( cfg.enable_movie_sorting() and cfg.movie_sort_string() and cfg.movie_categories() ): movie_sorter = {} movie_sorter["order"] = order movie_sorter["min_size"] = cfg.movie_rename_limit() movie_sorter["multipart_label"] = cfg.movie_sort_extra() movie_sorter["sort_string"] = cfg.movie_sort_string() movie_sorter["sort_cats"] = cfg.movie_categories() movie_sorter["sort_type"] = [sort_to_opts("movie")] movie_sorter["is_active"] = int(cfg.enable_movie_sorting()) # Configure the new sorter logging.debug( "Converted old movie sorter config to '%s': %s", T("Movie Sorting"), movie_sorter, ) config.ConfigSorter(T("Movie Sorting"), movie_sorter)
plugins
dist_plugin
# Copyright (C) 2008-2010 Adam Olsen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # # The developers of the Exaile media player hereby grant permission # for non-GPL compatible GStreamer and Exaile plugins to be used and # distributed together with GStreamer and Exaile. This permission is # above and beyond the permissions granted by the GPL license by which # Exaile is covered. If you modify this code, you may extend this # exception to your version of the code, but you are not obligated to # do so. If you do not wish to do so, delete this exception statement # from your version. # script to turn a plugin dir into a .exz file suitable for distribution # takes one commandline parameter: the name of the plugin to build, which must # be a subdirectory of the current directory # outputs the built plugin to the current directory, overwriting any current # build of that plugin import os import tarfile from optparse import OptionParser p = OptionParser() p.add_option( "-c", "--compression", dest="compression", action="store", choices=("", "gz", "bz2"), default="bz2", ) p.add_option( "-e", "--ignore-extension", dest="extensions", action="append", default=(".pyc", ".pyo"), ) p.add_option("-f", "--ignore-file", dest="files", action="append", default=("test.py")) p.add_option("-O", "--output", dest="output", action="store", default="") options, args = p.parse_args() # allowed values: "", "gz", "bz2" COMPRESSION = options.compression # don't add files with these extensions to the archive IGNORED_EXTENSIONS = options.extensions # don't add files with this exact name to the archive IGNORED_FILES = options.files _ = lambda x: x for dir in args: if not os.path.exists(dir): print("No such folder %s" % dir) break print("Making plugin %s..." % dir) if not os.path.exists(os.path.join(dir, "PLUGININFO")): print("ERROR: no valid info for %s, skipping..." % dir) continue f = open(os.path.join(dir, "PLUGININFO")) info = {} for line in f: try: key, val = line.split("=", 1) except ValueError: continue key = key.strip() val = eval(val) info[key] = val f.close() if "Version" not in info: print("ERROR: couldn't get version for %s, skipping..." % dir) continue tfile = tarfile.open( options.output + dir + "-%s.exz" % info["Version"], "w:%s" % COMPRESSION, format=tarfile.USTAR_FORMAT, ) for fold, subdirs, files in os.walk(dir): for file in files: stop = False for ext in IGNORED_EXTENSIONS: if file.endswith(ext): stop = True break if stop: continue for name in IGNORED_FILES: if file == name: stop = True break if stop: continue path = os.path.join(fold, file) tfile.add(path) tfile.close() print("Done.")
comictaggerlib
settingswindow
"""A PyQT4 dialog to enter app settings""" # Copyright 2012-2014 Anthony Beville # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import platform import utils from comicvinecacher import ComicVineCacher from comicvinetalker import ComicVineTalker from imagefetcher import ImageFetcher from PyQt4 import QtCore, QtGui, uic from settings import ComicTaggerSettings windowsRarHelp = """ <html><head/><body><p>In order to write to CBR/RAR archives, you will need to have the tools from <a href="http://www.win-rar.com/download.html"> <span style=" text-decoration: underline; color:#0000ff;">WinRAR</span> </a> installed. </p></body></html> """ linuxRarHelp = """ <html><head/><body><p>In order to read/write to CBR/RAR archives, you will need to have the shareware tools from WinRar installed. Your package manager should have unrar, and probably rar. If not, download them <a href="http://www.win-rar.com/download.html"> <span style=" text-decoration: underline; color:#0000ff;">here</span> </a>, and install in your path. </p></body></html> """ macRarHelp = """ <html><head/><body><p>In order to read/write to CBR/RAR archives, you will need the shareware tools from <a href="http://www.win-rar.com/download.html"> <span style=" text-decoration: underline; color:#0000ff;">WinRAR</span> </a>. </p></body></html> """ class SettingsWindow(QtGui.QDialog): def __init__(self, parent, settings): super(SettingsWindow, self).__init__(parent) uic.loadUi(ComicTaggerSettings.getUIFile("settingswindow.ui"), self) self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint) self.settings = settings self.name = "Settings" if platform.system() == "Windows": self.lblUnrar.hide() self.leUnrarExePath.hide() self.btnBrowseUnrar.hide() self.lblRarHelp.setText(windowsRarHelp) elif platform.system() == "Linux": self.lblRarHelp.setText(linuxRarHelp) elif platform.system() == "Darwin": self.lblRarHelp.setText(macRarHelp) self.name = "Preferences" self.setWindowTitle("ComicTagger " + self.name) self.lblDefaultSettings.setText("Revert to default " + self.name.lower()) self.btnResetSettings.setText("Default " + self.name) nldtTip = """<html>The <b>Default Name Length Match Tolerance</b> is for eliminating automatic search matches that are too long compared to your series name search. The higher it is, the more likely to have a good match, but each search will take longer and use more bandwidth. Too low, and only the very closest lexical matches will be explored.</html>""" self.leNameLengthDeltaThresh.setToolTip(nldtTip) pblTip = """<html> The <b>Publisher Blacklist</b> is for eliminating automatic matches to certain publishers that you know are incorrect. Useful for avoiding international re-prints with same covers or series names. Enter publisher names separated by commas. </html>""" self.tePublisherBlacklist.setToolTip(pblTip) validator = QtGui.QIntValidator(1, 4, self) self.leIssueNumPadding.setValidator(validator) validator = QtGui.QIntValidator(0, 99, self) self.leNameLengthDeltaThresh.setValidator(validator) self.settingsToForm() self.btnBrowseRar.clicked.connect(self.selectRar) self.btnBrowseUnrar.clicked.connect(self.selectUnrar) self.btnClearCache.clicked.connect(self.clearCache) self.btnResetSettings.clicked.connect(self.resetSettings) self.btnTestKey.clicked.connect(self.testAPIKey) def settingsToForm(self): # Copy values from settings to form self.leRarExePath.setText(self.settings.rar_exe_path) self.leUnrarExePath.setText(self.settings.unrar_exe_path) self.leNameLengthDeltaThresh.setText(str(self.settings.id_length_delta_thresh)) self.tePublisherBlacklist.setPlainText(self.settings.id_publisher_blacklist) if self.settings.check_for_new_version: self.cbxCheckForNewVersion.setCheckState(QtCore.Qt.Checked) if self.settings.parse_scan_info: self.cbxParseScanInfo.setCheckState(QtCore.Qt.Checked) if self.settings.use_series_start_as_volume: self.cbxUseSeriesStartAsVolume.setCheckState(QtCore.Qt.Checked) if self.settings.clear_form_before_populating_from_cv: self.cbxClearFormBeforePopulating.setCheckState(QtCore.Qt.Checked) if self.settings.remove_html_tables: self.cbxRemoveHtmlTables.setCheckState(QtCore.Qt.Checked) self.leKey.setText(str(self.settings.cv_api_key)) if self.settings.assume_lone_credit_is_primary: self.cbxAssumeLoneCreditIsPrimary.setCheckState(QtCore.Qt.Checked) if self.settings.copy_characters_to_tags: self.cbxCopyCharactersToTags.setCheckState(QtCore.Qt.Checked) if self.settings.copy_teams_to_tags: self.cbxCopyTeamsToTags.setCheckState(QtCore.Qt.Checked) if self.settings.copy_locations_to_tags: self.cbxCopyLocationsToTags.setCheckState(QtCore.Qt.Checked) if self.settings.copy_storyarcs_to_tags: self.cbxCopyStoryArcsToTags.setCheckState(QtCore.Qt.Checked) if self.settings.copy_notes_to_comments: self.cbxCopyNotesToComments.setCheckState(QtCore.Qt.Checked) if self.settings.copy_weblink_to_comments: self.cbxCopyWebLinkToComments.setCheckState(QtCore.Qt.Checked) if self.settings.apply_cbl_transform_on_cv_import: self.cbxApplyCBLTransformOnCVIMport.setCheckState(QtCore.Qt.Checked) if self.settings.apply_cbl_transform_on_bulk_operation: self.cbxApplyCBLTransformOnBatchOperation.setCheckState(QtCore.Qt.Checked) self.leRenameTemplate.setText(self.settings.rename_template) self.leIssueNumPadding.setText(str(self.settings.rename_issue_number_padding)) if self.settings.rename_use_smart_string_cleanup: self.cbxSmartCleanup.setCheckState(QtCore.Qt.Checked) if self.settings.rename_extension_based_on_archive: self.cbxChangeExtension.setCheckState(QtCore.Qt.Checked) def accept(self): # Copy values from form to settings and save self.settings.rar_exe_path = str(self.leRarExePath.text()) self.settings.unrar_exe_path = str(self.leUnrarExePath.text()) # make sure unrar/rar program is now in the path for the UnRAR class utils.addtopath(os.path.dirname(self.settings.unrar_exe_path)) utils.addtopath(os.path.dirname(self.settings.rar_exe_path)) if not str(self.leNameLengthDeltaThresh.text()).isdigit(): self.leNameLengthDeltaThresh.setText("0") if not str(self.leIssueNumPadding.text()).isdigit(): self.leIssueNumPadding.setText("0") self.settings.check_for_new_version = self.cbxCheckForNewVersion.isChecked() self.settings.id_length_delta_thresh = int(self.leNameLengthDeltaThresh.text()) self.settings.id_publisher_blacklist = str( self.tePublisherBlacklist.toPlainText() ) self.settings.parse_scan_info = self.cbxParseScanInfo.isChecked() self.settings.use_series_start_as_volume = ( self.cbxUseSeriesStartAsVolume.isChecked() ) self.settings.clear_form_before_populating_from_cv = ( self.cbxClearFormBeforePopulating.isChecked() ) self.settings.remove_html_tables = self.cbxRemoveHtmlTables.isChecked() self.settings.cv_api_key = unicode(self.leKey.text()) ComicVineTalker.api_key = self.settings.cv_api_key self.settings.assume_lone_credit_is_primary = ( self.cbxAssumeLoneCreditIsPrimary.isChecked() ) self.settings.copy_characters_to_tags = self.cbxCopyCharactersToTags.isChecked() self.settings.copy_teams_to_tags = self.cbxCopyTeamsToTags.isChecked() self.settings.copy_locations_to_tags = self.cbxCopyLocationsToTags.isChecked() self.settings.copy_storyarcs_to_tags = self.cbxCopyStoryArcsToTags.isChecked() self.settings.copy_notes_to_comments = self.cbxCopyNotesToComments.isChecked() self.settings.copy_weblink_to_comments = ( self.cbxCopyWebLinkToComments.isChecked() ) self.settings.apply_cbl_transform_on_cv_import = ( self.cbxApplyCBLTransformOnCVIMport.isChecked() ) self.settings.apply_cbl_transform_on_bulk_operation = ( self.cbxApplyCBLTransformOnBatchOperation.isChecked() ) self.settings.rename_template = str(self.leRenameTemplate.text()) self.settings.rename_issue_number_padding = int(self.leIssueNumPadding.text()) self.settings.rename_use_smart_string_cleanup = self.cbxSmartCleanup.isChecked() self.settings.rename_extension_based_on_archive = ( self.cbxChangeExtension.isChecked() ) self.settings.save() QtGui.QDialog.accept(self) def selectRar(self): self.selectFile(self.leRarExePath, "RAR") def selectUnrar(self): self.selectFile(self.leUnrarExePath, "UnRAR") def clearCache(self): ImageFetcher().clearCache() ComicVineCacher().clearCache() QtGui.QMessageBox.information(self, self.name, "Cache has been cleared.") def testAPIKey(self): if ComicVineTalker().testKey(unicode(self.leKey.text())): QtGui.QMessageBox.information(self, "API Key Test", "Key is valid!") else: QtGui.QMessageBox.warning(self, "API Key Test", "Key is NOT valid.") def resetSettings(self): self.settings.reset() self.settingsToForm() QtGui.QMessageBox.information( self, self.name, self.name + " have been returned to default values." ) def selectFile(self, control, name): dialog = QtGui.QFileDialog(self) dialog.setFileMode(QtGui.QFileDialog.ExistingFile) if platform.system() == "Windows": if name == "RAR": filter = self.tr("Rar Program (Rar.exe)") else: filter = self.tr("Programs (*.exe)") dialog.setNameFilter(filter) else: # QtCore.QDir.Executable | QtCore.QDir.Files) dialog.setFilter(QtCore.QDir.Files) pass dialog.setDirectory(os.path.dirname(str(control.text()))) dialog.setWindowTitle("Find " + name + " program") if dialog.exec_(): fileList = dialog.selectedFiles() control.setText(str(fileList[0])) def showRenameTab(self): self.tabWidget.setCurrentIndex(5)
api
files
__author__ = "Gina Häußge <osd@foosel.net>" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import hashlib import logging import os import threading from urllib.parse import quote as urlquote import octoprint.filemanager import octoprint.filemanager.storage import octoprint.filemanager.util import octoprint.slicing import psutil from flask import abort, jsonify, make_response, request, url_for from octoprint.access.permissions import Permissions from octoprint.events import Events from octoprint.filemanager.destinations import FileDestinations from octoprint.filemanager.storage import StorageError from octoprint.server import ( NO_CONTENT, current_user, eventManager, fileManager, printer, slicingManager, ) from octoprint.server.api import api from octoprint.server.util.flask import ( get_json_command_from_request, no_firstrun_access, with_revalidation_checking, ) from octoprint.settings import settings, valid_boolean_trues from octoprint.util import sv, time_this # ~~ GCODE file handling _file_cache = {} _file_cache_mutex = threading.RLock() _DATA_FORMAT_VERSION = "v2" def _clear_file_cache(): with _file_cache_mutex: _file_cache.clear() def _create_lastmodified(path, recursive): path = path[len("/api/files") :] if path.startswith("/"): path = path[1:] if path == "": # all storages involved lms = [0] for storage in fileManager.registered_storages: try: lms.append(fileManager.last_modified(storage, recursive=recursive)) except Exception: logging.getLogger(__name__).exception( "There was an error retrieving the last modified data from storage {}".format( storage ) ) lms.append(None) if any(filter(lambda x: x is None, lms)): # we return None if ANY of the involved storages returned None return None # if we reach this point, we return the maximum of all dates return max(lms) else: if "/" in path: storage, path_in_storage = path.split("/", 1) else: storage = path path_in_storage = None try: return fileManager.last_modified( storage, path=path_in_storage, recursive=recursive ) except Exception: logging.getLogger(__name__).exception( "There was an error retrieving the last modified data from storage {} and path {}".format( storage, path_in_storage ) ) return None def _create_etag(path, filter, recursive, lm=None): if lm is None: lm = _create_lastmodified(path, recursive) if lm is None: return None hash = hashlib.sha1() def hash_update(value): value = value.encode("utf-8") hash.update(value) hash_update(str(lm)) hash_update(str(filter)) hash_update(str(recursive)) path = path[len("/api/files") :] if path.startswith("/"): path = path[1:] if "/" in path: storage, _ = path.split("/", 1) else: storage = path if path == "" or storage == FileDestinations.SDCARD: # include sd data in etag hash_update(repr(sorted(printer.get_sd_files(), key=lambda x: sv(x["name"])))) hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format return hash.hexdigest() @api.route("/files", methods=["GET"]) @Permissions.FILES_LIST.require(403) @with_revalidation_checking( etag_factory=lambda lm=None: _create_etag( request.path, request.values.get("filter", False), request.values.get("recursive", False), lm=lm, ), lastmodified_factory=lambda: _create_lastmodified( request.path, request.values.get("recursive", False) ), unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False), ) def readGcodeFiles(): filter = request.values.get("filter", False) recursive = request.values.get("recursive", "false") in valid_boolean_trues force = request.values.get("force", "false") in valid_boolean_trues files = _getFileList( FileDestinations.LOCAL, filter=filter, recursive=recursive, allow_from_cache=not force, ) files.extend(_getFileList(FileDestinations.SDCARD, allow_from_cache=not force)) usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False)) return jsonify(files=files, free=usage.free, total=usage.total) @api.route("/files/test", methods=["POST"]) @Permissions.FILES_LIST.require(403) def runFilesTest(): valid_commands = { "sanitize": ["storage", "path", "filename"], "exists": ["storage", "path", "filename"], } command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response def sanitize(storage, path, filename): sanitized_path = fileManager.sanitize_path(storage, path) sanitized_name = fileManager.sanitize_name(storage, filename) joined = fileManager.join_path(storage, sanitized_path, sanitized_name) return sanitized_path, sanitized_name, joined if command == "sanitize": _, _, sanitized = sanitize(data["storage"], data["path"], data["filename"]) return jsonify(sanitized=sanitized) elif command == "exists": storage = data["storage"] path = data["path"] filename = data["filename"] sanitized_path, _, sanitized = sanitize(storage, path, filename) exists = fileManager.file_exists(storage, sanitized) if exists: suggestion = filename name, ext = os.path.splitext(filename) counter = 0 while fileManager.file_exists( storage, fileManager.join_path( storage, sanitized_path, fileManager.sanitize_name(storage, suggestion), ), ): counter += 1 suggestion = f"{name}_{counter}{ext}" return jsonify(exists=True, suggestion=suggestion) else: return jsonify(exists=False) @api.route("/files/<string:origin>", methods=["GET"]) @Permissions.FILES_LIST.require(403) @with_revalidation_checking( etag_factory=lambda lm=None: _create_etag( request.path, request.values.get("filter", False), request.values.get("recursive", False), lm=lm, ), lastmodified_factory=lambda: _create_lastmodified( request.path, request.values.get("recursive", False) ), unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False), ) def readGcodeFilesForOrigin(origin): if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) filter = request.values.get("filter", False) recursive = request.values.get("recursive", "false") in valid_boolean_trues force = request.values.get("force", "false") in valid_boolean_trues files = _getFileList( origin, filter=filter, recursive=recursive, allow_from_cache=not force ) if origin == FileDestinations.LOCAL: usage = psutil.disk_usage( settings().getBaseFolder("uploads", check_writable=False) ) return jsonify(files=files, free=usage.free, total=usage.total) else: return jsonify(files=files) @api.route("/files/<string:target>/<path:filename>", methods=["GET"]) @Permissions.FILES_LIST.require(403) @with_revalidation_checking( etag_factory=lambda lm=None: _create_etag( request.path, request.values.get("filter", False), request.values.get("recursive", False), lm=lm, ), lastmodified_factory=lambda: _create_lastmodified( request.path, request.values.get("recursive", False) ), unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False), ) def readGcodeFile(target, filename): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) if not _validate(target, filename): abort(404) recursive = False if "recursive" in request.values: recursive = request.values["recursive"] in valid_boolean_trues file = _getFileDetails(target, filename, recursive=recursive) if not file: abort(404) return jsonify(file) def _getFileDetails(origin, path, recursive=True): parent, path = os.path.split(path) files = _getFileList(origin, path=parent, recursive=recursive, level=1) for f in files: if f["name"] == path: return f else: return None @time_this( logtarget=__name__ + ".timings", message="{func}({func_args},{func_kwargs}) took {timing:.2f}ms", incl_func_args=True, log_enter=True, message_enter="Entering {func}({func_args},{func_kwargs})...", ) def _getFileList( origin, path=None, filter=None, recursive=False, level=0, allow_from_cache=True ): if origin == FileDestinations.SDCARD: sdFileList = printer.get_sd_files(refresh=not allow_from_cache) files = [] if sdFileList is not None: for f in sdFileList: type_path = octoprint.filemanager.get_file_type(f["name"]) if not type_path: # only supported extensions continue else: file_type = type_path[0] file = { "type": file_type, "typePath": type_path, "name": f["name"], "display": f["display"] if f["display"] else f["name"], "path": f["name"], "origin": FileDestinations.SDCARD, "refs": { "resource": url_for( ".readGcodeFile", target=FileDestinations.SDCARD, filename=f["name"], _external=True, ) }, } if f["size"] is not None: file.update({"size": f["size"]}) if f["date"] is not None: file.update({"date": f["date"]}) files.append(file) else: # PERF: Only retrieve the extension tree once extension_tree = octoprint.filemanager.full_extension_tree() filter_func = None if filter: filter_func = ( lambda entry, entry_data: octoprint.filemanager.valid_file_type( entry, type=filter, tree=extension_tree ) ) with _file_cache_mutex: cache_key = f"{origin}:{path}:{recursive}:{filter}" files, lastmodified = _file_cache.get(cache_key, ([], None)) # recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422 if ( not allow_from_cache or lastmodified is None or lastmodified < fileManager.last_modified(origin, path=path, recursive=True) ): files = list( fileManager.list_files( origin, path=path, filter=filter_func, recursive=recursive, level=level, force_refresh=not allow_from_cache, )[origin].values() ) lastmodified = fileManager.last_modified( origin, path=path, recursive=True ) _file_cache[cache_key] = (files, lastmodified) def analyse_recursively(files, path=None): if path is None: path = "" result = [] for file_or_folder in files: # make a shallow copy in order to not accidentally modify the cached data file_or_folder = dict(file_or_folder) file_or_folder["origin"] = FileDestinations.LOCAL if file_or_folder["type"] == "folder": if "children" in file_or_folder: file_or_folder["children"] = analyse_recursively( file_or_folder["children"].values(), path + file_or_folder["name"] + "/", ) file_or_folder["refs"] = { "resource": url_for( ".readGcodeFile", target=FileDestinations.LOCAL, filename=path + file_or_folder["name"], _external=True, ) } else: if ( "analysis" in file_or_folder and octoprint.filemanager.valid_file_type( file_or_folder["name"], type="gcode", tree=extension_tree ) ): file_or_folder["gcodeAnalysis"] = file_or_folder["analysis"] del file_or_folder["analysis"] if ( "history" in file_or_folder and octoprint.filemanager.valid_file_type( file_or_folder["name"], type="gcode", tree=extension_tree ) ): # convert print log history = file_or_folder["history"] del file_or_folder["history"] success = 0 failure = 0 last = None for entry in history: success += ( 1 if "success" in entry and entry["success"] else 0 ) failure += ( 1 if "success" in entry and not entry["success"] else 0 ) if not last or ( "timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"] ): last = entry if last: prints = { "success": success, "failure": failure, "last": { "success": last["success"], "date": last["timestamp"], }, } if "printTime" in last: prints["last"]["printTime"] = last["printTime"] file_or_folder["prints"] = prints file_or_folder["refs"] = { "resource": url_for( ".readGcodeFile", target=FileDestinations.LOCAL, filename=file_or_folder["path"], _external=True, ), "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + urlquote(file_or_folder["path"]), } result.append(file_or_folder) return result files = analyse_recursively(files) return files def _verifyFileExists(origin, filename): if origin == FileDestinations.SDCARD: return filename in (x["name"] for x in printer.get_sd_files()) else: return fileManager.file_exists(origin, filename) def _verifyFolderExists(origin, foldername): if origin == FileDestinations.SDCARD: return False else: return fileManager.folder_exists(origin, foldername) def _isBusy(target, path): currentOrigin, currentPath = _getCurrentFile() if ( currentPath is not None and currentOrigin == target and fileManager.file_in_path(FileDestinations.LOCAL, path, currentPath) and (printer.is_printing() or printer.is_paused()) ): return True return any( target == x[0] and fileManager.file_in_path(FileDestinations.LOCAL, path, x[1]) for x in fileManager.get_busy_files() ) @api.route("/files/<string:target>", methods=["POST"]) @no_firstrun_access @Permissions.FILES_UPLOAD.require(403) def uploadGcodeFile(target): input_name = "file" input_upload_name = ( input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) ) input_upload_path = ( input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) ) if input_upload_name in request.values and input_upload_path in request.values: if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) upload = octoprint.filemanager.util.DiskFileWrapper( request.values[input_upload_name], request.values[input_upload_path] ) # Store any additional user data the caller may have passed. userdata = None if "userdata" in request.values: import json try: userdata = json.loads(request.values["userdata"]) except Exception: abort(400, description="userdata contains invalid JSON") # check preconditions for SD upload if target == FileDestinations.SDCARD and not settings().getBoolean( ["feature", "sdSupport"] ): abort(404) sd = target == FileDestinations.SDCARD if sd: # validate that all preconditions for SD upload are met before attempting it if not ( printer.is_operational() and not (printer.is_printing() or printer.is_paused()) ): abort( 409, description="Can not upload to SD card, printer is either not operational or already busy", ) if not printer.is_sd_ready(): abort(409, description="Can not upload to SD card, not yet initialized") # evaluate select and print parameter and if set check permissions & preconditions # and adjust as necessary # # we do NOT abort(409) here since this would be a backwards incompatible behaviour change # on the API, but instead return the actually effective select and print flags in the response # # note that this behaviour might change in a future API version select_request = ( "select" in request.values and request.values["select"] in valid_boolean_trues and Permissions.FILES_SELECT.can() ) print_request = ( "print" in request.values and request.values["print"] in valid_boolean_trues and Permissions.PRINT.can() ) to_select = select_request to_print = print_request if (to_select or to_print) and not ( printer.is_operational() and not (printer.is_printing() or printer.is_paused()) ): # can't select or print files if not operational or ready to_select = to_print = False # determine future filename of file to be uploaded, abort if it can't be uploaded try: # FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet canonPath, canonFilename = fileManager.canonicalize( FileDestinations.LOCAL, upload.filename ) if request.values.get("path"): canonPath = request.values.get("path") if request.values.get("filename"): canonFilename = request.values.get("filename") futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath) futureFilename = fileManager.sanitize_name( FileDestinations.LOCAL, canonFilename ) except Exception: canonFilename = None futurePath = None futureFilename = None if futureFilename is None: abort(400, description="Can not upload file, invalid file name") # prohibit overwriting currently selected file while it's being printed futureFullPath = fileManager.join_path( FileDestinations.LOCAL, futurePath, futureFilename ) futureFullPathInStorage = fileManager.path_in_storage( FileDestinations.LOCAL, futureFullPath ) if not printer.can_modify_file(futureFullPathInStorage, sd): abort( 409, description="Trying to overwrite file that is currently being printed", ) if ( fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage) and request.values.get("noOverwrite") in valid_boolean_trues ): abort(409, description="File already exists and noOverwrite was set") if ( fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage) and not Permissions.FILES_DELETE.can() ): abort( 403, description="File already exists, cannot overwrite due to a lack of permissions", ) reselect = printer.is_current_file(futureFullPathInStorage, sd) user = current_user.get_name() def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls to_select. """ if ( destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "machinecode") ): return filename, printer.add_sd_file( filename, absFilename, on_success=selectAndOrPrint, tags={"source:api", "api:files.sd"}, ) else: selectAndOrPrint(filename, absFilename, destination) return filename def selectAndOrPrint(filename, absFilename, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either to_select or to_print are True, or if the exact file is already selected, such reloading it. """ if octoprint.filemanager.valid_file_type(added_file, "gcode") and ( to_select or to_print or reselect ): printer.select_file( absFilename, destination == FileDestinations.SDCARD, to_print, user, ) try: added_file = fileManager.add_file( FileDestinations.LOCAL, futureFullPathInStorage, upload, allow_overwrite=True, display=canonFilename, ) except (OSError, StorageError) as e: _abortWithException(e) else: filename = fileProcessingFinished( added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target, ) done = not sd if userdata is not None: # upload included userdata, add this now to the metadata fileManager.set_additional_metadata( FileDestinations.LOCAL, added_file, "userdata", userdata ) sdFilename = None if isinstance(filename, tuple): filename, sdFilename = filename payload = { "name": futureFilename, "path": filename, "target": target, "select": select_request, "print": print_request, "effective_select": to_select, "effective_print": to_print, } if userdata is not None: payload["userdata"] = userdata eventManager.fire(Events.UPLOAD, payload) files = {} location = url_for( ".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True, ) files.update( { FileDestinations.LOCAL: { "name": futureFilename, "path": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + urlquote(filename), }, } } ) if sd and sdFilename: location = url_for( ".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True, ) files.update( { FileDestinations.SDCARD: { "name": sdFilename, "path": sdFilename, "origin": FileDestinations.SDCARD, "refs": {"resource": location}, } } ) r = make_response( jsonify( files=files, done=done, effectiveSelect=to_select, effectivePrint=to_print, ), 201, ) r.headers["Location"] = location return r elif "foldername" in request.values: foldername = request.values["foldername"] if target not in [FileDestinations.LOCAL]: abort(400, description="target is invalid") canonPath, canonName = fileManager.canonicalize(target, foldername) futurePath = fileManager.sanitize_path(target, canonPath) futureName = fileManager.sanitize_name(target, canonName) if not futureName or not futurePath: abort(400, description="folder name is empty") if "path" in request.values and request.values["path"]: futurePath = fileManager.sanitize_path( FileDestinations.LOCAL, request.values["path"] ) futureFullPath = fileManager.join_path(target, futurePath, futureName) if octoprint.filemanager.valid_file_type(futureName): abort(409, description="Can't create folder, please try another name") try: added_folder = fileManager.add_folder( target, futureFullPath, display=canonName ) except (OSError, StorageError) as e: _abortWithException(e) location = url_for( ".readGcodeFile", target=FileDestinations.LOCAL, filename=added_folder, _external=True, ) folder = { "name": futureName, "path": added_folder, "origin": target, "refs": {"resource": location}, } r = make_response(jsonify(folder=folder, done=True), 201) r.headers["Location"] = location return r else: abort(400, description="No file to upload and no folder to create") @api.route("/files/<string:target>/<path:filename>", methods=["POST"]) @no_firstrun_access def gcodeFileCommand(filename, target): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) if not _validate(target, filename): abort(404) # valid file commands, dict mapping command name to mandatory parameters valid_commands = { "select": [], "unselect": [], "slice": [], "analyse": [], "copy": ["destination"], "move": ["destination"], } command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response user = current_user.get_name() if command == "select": with Permissions.FILES_SELECT.require(403): if not _verifyFileExists(target, filename): abort(404) # selects/loads a file if not octoprint.filemanager.valid_file_type(filename, type="machinecode"): abort( 415, description="Cannot select file for printing, not a machinecode file", ) if not printer.is_ready(): abort( 409, description="Printer is already printing, cannot select a new file", ) printAfterLoading = False if "print" in data and data["print"] in valid_boolean_trues: with Permissions.PRINT.require(403): if not printer.is_operational(): abort( 409, description="Printer is not operational, cannot directly start printing", ) printAfterLoading = True sd = False if target == FileDestinations.SDCARD: filenameToSelect = filename sd = True else: filenameToSelect = fileManager.path_on_disk(target, filename) printer.select_file(filenameToSelect, sd, printAfterLoading, user) elif command == "unselect": with Permissions.FILES_SELECT.require(403): if not printer.is_ready(): return make_response( "Printer is already printing, cannot unselect current file", 409 ) _, currentFilename = _getCurrentFile() if currentFilename is None: return make_response( "Cannot unselect current file when there is no file selected", 409 ) if filename != currentFilename and filename != "current": return make_response( "Only the currently selected file can be unselected", 400 ) printer.unselect_file() elif command == "slice": with Permissions.SLICE.require(403): if not _verifyFileExists(target, filename): abort(404) try: if "slicer" in data: slicer = data["slicer"] del data["slicer"] slicer_instance = slicingManager.get_slicer(slicer) elif "cura" in slicingManager.registered_slicers: slicer = "cura" slicer_instance = slicingManager.get_slicer("cura") else: abort(415, description="Cannot slice file, no slicer available") except octoprint.slicing.UnknownSlicer: abort(404) if not any( [ octoprint.filemanager.valid_file_type( filename, type=source_file_type ) for source_file_type in slicer_instance.get_slicer_properties().get( "source_file_types", ["model"] ) ] ): abort(415, description="Cannot slice file, not a model file") cores = psutil.cpu_count() if ( slicer_instance.get_slicer_properties().get("same_device", True) and (printer.is_printing() or printer.is_paused()) and (cores is None or cores < 2) ): # slicer runs on same device as OctoPrint, slicing while printing is hence disabled abort( 409, description="Cannot slice on this slicer while printing on single core systems or systems of unknown core count due to performance reasons", ) if "destination" in data and data["destination"]: destination = data["destination"] del data["destination"] elif "gcode" in data and data["gcode"]: destination = data["gcode"] del data["gcode"] else: import os name, _ = os.path.splitext(filename) destination = ( name + "." + slicer_instance.get_slicer_properties().get( "destination_extensions", ["gco", "gcode", "g"] )[0] ) full_path = destination if "path" in data and data["path"]: full_path = fileManager.join_path(target, data["path"], destination) else: path, _ = fileManager.split_path(target, filename) if path: full_path = fileManager.join_path(target, path, destination) canon_path, canon_name = fileManager.canonicalize(target, full_path) sanitized_name = fileManager.sanitize_name(target, canon_name) if canon_path: full_path = fileManager.join_path(target, canon_path, sanitized_name) else: full_path = sanitized_name # prohibit overwriting the file that is currently being printed currentOrigin, currentFilename = _getCurrentFile() if ( currentFilename == full_path and currentOrigin == target and (printer.is_printing() or printer.is_paused()) ): abort( 409, description="Trying to slice into file that is currently being printed", ) if "profile" in data and data["profile"]: profile = data["profile"] del data["profile"] else: profile = None if "printerProfile" in data and data["printerProfile"]: printerProfile = data["printerProfile"] del data["printerProfile"] else: printerProfile = None if ( "position" in data and data["position"] and isinstance(data["position"], dict) and "x" in data["position"] and "y" in data["position"] ): position = data["position"] del data["position"] else: position = None select_after_slicing = False if "select" in data and data["select"] in valid_boolean_trues: if not printer.is_operational(): abort( 409, description="Printer is not operational, cannot directly select for printing", ) select_after_slicing = True print_after_slicing = False if "print" in data and data["print"] in valid_boolean_trues: if not printer.is_operational(): abort( 409, description="Printer is not operational, cannot directly start printing", ) select_after_slicing = print_after_slicing = True override_keys = [ k for k in data if k.startswith("profile.") and data[k] is not None ] overrides = {} for key in override_keys: overrides[key[len("profile.") :]] = data[key] def slicing_done(target, path, select_after_slicing, print_after_slicing): if select_after_slicing or print_after_slicing: sd = False if target == FileDestinations.SDCARD: filenameToSelect = path sd = True else: filenameToSelect = fileManager.path_on_disk(target, path) printer.select_file(filenameToSelect, sd, print_after_slicing, user) try: fileManager.slice( slicer, target, filename, target, full_path, profile=profile, printer_profile_id=printerProfile, position=position, overrides=overrides, display=canon_name, callback=slicing_done, callback_args=( target, full_path, select_after_slicing, print_after_slicing, ), ) except octoprint.slicing.UnknownProfile: abort(404, description="Unknown profile") location = url_for( ".readGcodeFile", target=target, filename=full_path, _external=True, ) result = { "name": destination, "path": full_path, "display": canon_name, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + target + "/" + urlquote(full_path), }, } r = make_response(jsonify(result), 202) r.headers["Location"] = location return r elif command == "analyse": with Permissions.FILES_UPLOAD.require(403): if not _verifyFileExists(target, filename): abort(404) printer_profile = None if "printerProfile" in data and data["printerProfile"]: printer_profile = data["printerProfile"] if not fileManager.analyse( target, filename, printer_profile_id=printer_profile ): abort(400, description="No analysis possible") elif command == "copy" or command == "move": with Permissions.FILES_UPLOAD.require(403): # Copy and move are only possible on local storage if target not in [FileDestinations.LOCAL]: abort(400, description=f"Unsupported target for {command}") if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): abort(404) path, name = fileManager.split_path(target, filename) destination = data["destination"] dst_path, dst_name = fileManager.split_path(target, destination) sanitized_destination = fileManager.join_path( target, dst_path, fileManager.sanitize_name(target, dst_name) ) # Check for exception thrown by _verifyFolderExists, if outside the root directory try: if ( _verifyFolderExists(target, destination) and sanitized_destination != filename ): # destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed # to move filename to this folder under the same name destination = fileManager.join_path(target, destination, name) if _verifyFileExists(target, destination) or _verifyFolderExists( target, destination ): abort(409, description="File or folder does already exist") except Exception: abort( 409, description="Exception thrown by storage, bad folder/file name?", ) is_file = fileManager.file_exists(target, filename) is_folder = fileManager.folder_exists(target, filename) if not (is_file or is_folder): abort(400, description=f"Neither file nor folder, can't {command}") try: if command == "copy": # destination already there? error... if _verifyFileExists(target, destination) or _verifyFolderExists( target, destination ): abort(409, description="File or folder does already exist") if is_file: fileManager.copy_file(target, filename, destination) else: fileManager.copy_folder(target, filename, destination) elif command == "move": with Permissions.FILES_DELETE.require(403): if _isBusy(target, filename): abort( 409, description="Trying to move a file or folder that is currently in use", ) # destination already there AND not ourselves (= display rename)? error... if ( _verifyFileExists(target, destination) or _verifyFolderExists(target, destination) ) and sanitized_destination != filename: abort(409, description="File or folder does already exist") # deselect the file if it's currently selected currentOrigin, currentFilename = _getCurrentFile() if currentFilename is not None and filename == currentFilename: printer.unselect_file() if is_file: fileManager.move_file(target, filename, destination) else: fileManager.move_folder(target, filename, destination) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE: abort( 415, description=f"Could not {command} {filename} to {destination}, invalid type", ) else: abort( 500, description=f"Could not {command} {filename} to {destination}", ) location = url_for( ".readGcodeFile", target=target, filename=destination, _external=True, ) result = { "name": name, "path": destination, "origin": FileDestinations.LOCAL, "refs": {"resource": location}, } if is_file: result["refs"]["download"] = ( url_for("index", _external=True) + "downloads/files/" + target + "/" + urlquote(destination) ) r = make_response(jsonify(result), 201) r.headers["Location"] = location return r return NO_CONTENT @api.route("/files/<string:target>/<path:filename>", methods=["DELETE"]) @no_firstrun_access @Permissions.FILES_DELETE.require(403) def deleteGcodeFile(filename, target): if not _validate(target, filename): abort(404) if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): abort(404) if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) if _verifyFileExists(target, filename): if _isBusy(target, filename): abort(409, description="Trying to delete a file that is currently in use") # deselect the file if it's currently selected currentOrigin, currentPath = _getCurrentFile() if ( currentPath is not None and currentOrigin == target and filename == currentPath ): printer.unselect_file() # delete it if target == FileDestinations.SDCARD: printer.delete_sd_file(filename, tags={"source:api", "api:files.sd"}) else: try: fileManager.remove_file(target, filename) except (OSError, StorageError) as e: _abortWithException(e) elif _verifyFolderExists(target, filename): if _isBusy(target, filename): abort( 409, description="Trying to delete a folder that contains a file that is currently in use", ) # deselect the file if it's currently selected currentOrigin, currentPath = _getCurrentFile() if ( currentPath is not None and currentOrigin == target and fileManager.file_in_path(target, filename, currentPath) ): printer.unselect_file() # delete it try: fileManager.remove_folder(target, filename, recursive=True) except (OSError, StorageError) as e: _abortWithException(e) return NO_CONTENT def _abortWithException(error): if type(error) is StorageError: logging.getLogger(__name__).error( f"{error}: {error.code}", exc_info=error.cause ) if error.code == StorageError.INVALID_DIRECTORY: abort(400, description="Could not create folder, invalid directory") elif error.code == StorageError.INVALID_FILE: abort(415, description="Could not upload file, invalid type") elif error.code == StorageError.INVALID_SOURCE: abort(404, description="Source path does not exist, invalid source") elif error.code == StorageError.INVALID_DESTINATION: abort(400, description="Destination is invalid") elif error.code == StorageError.DOES_NOT_EXIST: abort(404, description="Does not exit") elif error.code == StorageError.ALREADY_EXISTS: abort(409, description="File or folder already exists") elif error.code == StorageError.SOURCE_EQUALS_DESTINATION: abort(400, description="Source and destination are the same folder") elif error.code == StorageError.NOT_EMPTY: abort(409, description="Folder is not empty") elif error.code == StorageError.UNKNOWN: abort(500, description=str(error.cause).split(":")[0]) else: abort(500, description=error) else: logging.getLogger(__name__).exception(error) abort(500, description=str(error).split(":")[0]) def _getCurrentFile(): currentJob = printer.get_current_job() if ( currentJob is not None and "file" in currentJob and "path" in currentJob["file"] and "origin" in currentJob["file"] ): return currentJob["file"]["origin"], currentJob["file"]["path"] else: return None, None def _validate(target, filename): if target == FileDestinations.SDCARD: # we make no assumptions about the shape of valid SDCard file names return True else: return filename == "/".join( map(lambda x: fileManager.sanitize_name(target, x), filename.split("/")) ) class WerkzeugFileWrapper(octoprint.filemanager.util.AbstractFileWrapper): """ A wrapper around a Werkzeug ``FileStorage`` object. Arguments: file_obj (werkzeug.datastructures.FileStorage): The Werkzeug ``FileStorage`` instance to wrap. .. seealso:: `werkzeug.datastructures.FileStorage <http://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.FileStorage>`_ The documentation of Werkzeug's ``FileStorage`` class. """ def __init__(self, file_obj): octoprint.filemanager.util.AbstractFileWrapper.__init__(self, file_obj.filename) self.file_obj = file_obj def save(self, path): """ Delegates to ``werkzeug.datastructures.FileStorage.save`` """ self.file_obj.save(path) def stream(self): """ Returns ``werkzeug.datastructures.FileStorage.stream`` """ return self.file_obj.stream
filter
qa_rational_resampler
#!/usr/bin/env python # # Copyright 2005-2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # import math import random import sys from gnuradio import blocks, filter, gr, gr_unittest def random_floats(n): r = [] for x in range(n): # r.append(float(random.randint(-32768, 32768))) r.append(float(random.random())) return tuple(r) def reference_dec_filter(src_data, decim, taps): tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.fir_filter_fff(decim, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() result_data = dst.data() tb = None return result_data def reference_interp_filter(src_data, interp, taps): tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.interp_fir_filter_fff(interp, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() result_data = dst.data() tb = None return result_data def reference_interp_dec_filter(src_data, interp, decim, taps): tb = gr.top_block() src = blocks.vector_source_f(src_data) up = filter.interp_fir_filter_fff(interp, (1,)) dn = filter.fir_filter_fff(decim, taps) dst = blocks.vector_sink_f() tb.connect(src, up, dn, dst) tb.run() result_data = dst.data() tb = None return result_data class test_rational_resampler(gr_unittest.TestCase): def setUp(self): random.seed(0) def tearDown(self): pass def test_000_1_to_1(self): taps = (-4, 5) src_data = (234, -4, 23, -56, 45, 98, -23, -7) xr = (1186, -112, 339, -460, -167, 582) expected_result = [float(x) for x in xr] tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_fff(1, 1, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def test_001_interp(self): taps = [1, 10, 100, 1000, 10000] src_data = (0, 2, 3, 5, 7, 11, 13, 17) interpolation = 3 xr = ( 2, 20, 200, 2003, 20030, 300, 3005, 30050, 500, 5007, 50070, 700, 7011, 70110, 1100, 11013, 110130, 1300, 13017, 130170, 1700.0, 17000.0, 170000.0, 0.0, ) expected_result = [float(x) for x in xr] tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_fff(interpolation, 1, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def test_002_interp(self): taps = random_floats(31) src_data = random_floats(10000) interpolation = 3 expected_result = reference_interp_filter(src_data, interpolation, taps) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_fff(interpolation, 1, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() N = 1000 offset = len(taps) - 1 self.assertEqual(expected_result[offset : offset + N], result_data[0:N]) def xtest_003_interp(self): taps = random_floats(9) src_data = random_floats(10000) decimation = 3 expected_result = reference_dec_filter(src_data, decimation, taps) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_fff(1, decimation, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() N = 10 offset = 10 # len(taps)-1 print(expected_result[100 + offset : 100 + offset + N]) print(result_data[100 : 100 + N]) # self.assertEqual(expected_result[offset:offset+N], result_data[0:N]) # FIXME disabled. Triggers hang on SuSE 10.0 def xtest_004_decim_random_vals(self): MAX_TAPS = 9 MAX_DECIM = 7 OUTPUT_LEN = 9 random.seed(0) # we want reproducibility for ntaps in range(1, MAX_TAPS + 1): for decim in range(1, MAX_DECIM + 1): for ilen in range(ntaps + decim, ntaps + OUTPUT_LEN * decim): src_data = random_floats(ilen) taps = random_floats(ntaps) expected_result = reference_dec_filter(src_data, decim, taps) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_fff(1, decim, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() tb = None result_data = dst.data() L1 = len(result_data) L2 = len(expected_result) L = min(L1, L2) if False: sys.stderr.write( "delta = %2d: ntaps = %d decim = %d ilen = %d\n" % (L2 - L1, ntaps, decim, ilen) ) sys.stderr.write( " len(result_data) = %d len(expected_result) = %d\n" % (len(result_data), len(expected_result)) ) self.assertEqual(expected_result[0:L], result_data[0:L]) # FIXME disabled. Triggers hang on SuSE 10.0 def xtest_005_interp_random_vals(self): MAX_TAPS = 9 MAX_INTERP = 7 INPUT_LEN = 9 random.seed(0) # we want reproducibility for ntaps in range(1, MAX_TAPS + 1): for interp in range(1, MAX_INTERP + 1): for ilen in range(ntaps, ntaps + INPUT_LEN): src_data = random_floats(ilen) taps = random_floats(ntaps) expected_result = reference_interp_filter(src_data, interp, taps) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_fff(interp, 1, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() tb = None result_data = dst.data() L1 = len(result_data) L2 = len(expected_result) L = min(L1, L2) # if True or abs(L1-L2) > 1: if False: sys.stderr.write( "delta = %2d: ntaps = %d interp = %d ilen = %d\n" % (L2 - L1, ntaps, interp, ilen) ) # sys.stderr.write(' len(result_data) = %d len(expected_result) = %d\n' % # (len(result_data), len(expected_result))) # self.assertEqual(expected_result[0:L], result_data[0:L]) # FIXME check first ntaps+1 answers self.assertEqual( expected_result[ntaps + 1 : L], result_data[ntaps + 1 : L] ) def test_006_interp_decim(self): taps = random_floats(31) src_data = random_floats(10000) interp = 3 decimation = 2 expected_result = reference_interp_dec_filter( src_data, interp, decimation, taps ) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_fff(interp, decimation, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() N = 1000 offset = len(taps) // 2 self.assertFloatTuplesAlmostEqual( expected_result[offset : offset + N], result_data[0:N], 5 ) def test_007_interp_decim_common_factor(self): taps = random_floats(31) src_data = random_floats(10000) interp = 6 decimation = 2 expected_result = reference_interp_dec_filter( src_data, interp, decimation, taps ) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_fff(interp, decimation, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() N = 1000 offset = len(taps) // 2 self.assertFloatTuplesAlmostEqual( expected_result[offset : offset + N], result_data[0:N], 5 ) if __name__ == "__main__": # FIXME: Disabled, see ticket:210 gr_unittest.run(test_rational_resampler)
drone
localToggleStates
import eos.db import wx from logbook import Logger from service.fit import Fit pyfalog = Logger(__name__) class CalcToggleLocalDroneStatesCommand(wx.Command): def __init__(self, fitID, mainPosition, positions, forceActiveAmounts=None): wx.Command.__init__(self, True, "Toggle Local Drone States") self.fitID = fitID self.mainPosition = mainPosition self.positions = positions self.forceActiveAmounts = forceActiveAmounts self.savedActiveAmounts = None def Do(self): pyfalog.debug( "Doing toggling of local drone state at position {}/{} for fit {}".format( self.mainPosition, self.positions, self.fitID ) ) fit = Fit.getInstance().getFit(self.fitID) positions = self.positions[:] if self.mainPosition not in positions: positions.append(self.mainPosition) self.savedActiveAmounts = {p: fit.drones[p].amountActive for p in positions} if self.forceActiveAmounts is not None: for position, amountActive in self.forceActiveAmounts.items(): drone = fit.drones[position] drone.amountActive = amountActive elif fit.drones[self.mainPosition].amountActive > 0: for position in positions: drone = fit.drones[position] if drone.amountActive > 0: drone.amountActive = 0 else: for position in positions: drone = fit.drones[position] if drone.amountActive == 0: drone.amountActive = drone.amount return True def Undo(self): pyfalog.debug( "Undoing toggling of local drone state at position {}/{} for fit {}".format( self.mainPosition, self.positions, self.fitID ) ) cmd = CalcToggleLocalDroneStatesCommand( fitID=self.fitID, mainPosition=self.mainPosition, positions=self.positions, forceActiveAmounts=self.savedActiveAmounts, ) return cmd.Do()
linters
meshes
from pathlib import Path from typing import Iterator from ..diagnostic import Diagnostic from .linter import Linter MAX_MESH_FILE_SIZE = 1 * 1024 * 1024 # 1MB class Meshes(Linter): def __init__(self, file: Path, settings: dict) -> None: """Finds issues in model files, such as incorrect file format or too large size""" super().__init__(file, settings) self._max_file_size = self._settings.get( "diagnostic-mesh-file-size", MAX_MESH_FILE_SIZE ) def check(self) -> Iterator[Diagnostic]: if self._settings["checks"].get("diagnostic-mesh-file-extension", False): for check in self.checkFileFormat(): yield check if self._settings["checks"].get("diagnostic-mesh-file-size", False): for check in self.checkFileSize(): yield check yield def checkFileFormat(self) -> Iterator[Diagnostic]: """Check if mesh is in supported format""" if self._file.suffix.lower() not in (".3mf", ".obj", ".stl"): yield Diagnostic( file=self._file, diagnostic_name="diagnostic-mesh-file-extension", message=f"Extension {self._file.suffix} not supported, use 3mf, obj or stl", level="Error", offset=1, ) yield def checkFileSize(self) -> Iterator[Diagnostic]: """Check if file is within size limits for Cura""" if self._file.stat().st_size > self._max_file_size: yield Diagnostic( file=self._file, diagnostic_name="diagnostic-mesh-file-size", message=f"Mesh file with a size {self._file.stat().st_size} is bigger then allowed maximum of {self._max_file_size}", level="Error", offset=1, ) yield
queries
foss_cohort_query
from typing import Any, Dict, List, Optional, Tuple, Union, cast from posthog.clickhouse.materialized_columns import ColumnName from posthog.constants import PropertyOperatorType from posthog.models import Filter, Team from posthog.models.action import Action from posthog.models.cohort import Cohort from posthog.models.cohort.util import ( format_static_cohort_query, get_count_operator, get_entity_query, ) from posthog.models.filters.mixins.utils import cached_property from posthog.models.property import ( BehavioralPropertyType, OperatorInterval, Property, PropertyGroup, PropertyName, ) from posthog.models.property.util import prop_filter_json_extract from posthog.queries.event_query import EventQuery from posthog.queries.util import PersonPropertiesMode from posthog.utils import PersonOnEventsMode Relative_Date = Tuple[int, OperatorInterval] Event = Tuple[str, Union[str, int]] INTERVAL_TO_SECONDS = { "minute": 60, "hour": 3600, "day": 86400, "week": 604800, "month": 2592000, "year": 31536000, } def relative_date_to_seconds(date: Tuple[Optional[int], Union[OperatorInterval, None]]): if date[0] is None or date[1] is None: raise ValueError("Time value and time interval must be specified") return date[0] * INTERVAL_TO_SECONDS[date[1]] def validate_interval(interval: Optional[OperatorInterval]) -> OperatorInterval: if interval is None or interval not in INTERVAL_TO_SECONDS.keys(): raise ValueError(f"Invalid interval: {interval}") else: return interval def parse_and_validate_positive_integer(value: Optional[int], value_name: str) -> int: if value is None: raise ValueError(f"{value_name} cannot be None") try: parsed_value = int(value) except ValueError: raise ValueError(f"{value_name} must be an integer, got {value}") if parsed_value <= 0: raise ValueError(f"{value_name} must be greater than 0, got {value}") return parsed_value def validate_entity( possible_event: Tuple[Optional[str], Optional[Union[int, str]]] ) -> Event: event_type = possible_event[0] event_val = possible_event[1] if event_type is None or event_val is None: raise ValueError("Entity name and entity id must be specified") return (event_type, event_val) def validate_seq_date_more_recent_than_date( seq_date: Relative_Date, date: Relative_Date ): if relative_date_is_greater(seq_date, date): raise ValueError("seq_date must be more recent than date") def relative_date_is_greater(date_1: Relative_Date, date_2: Relative_Date) -> bool: return relative_date_to_seconds(date_1) > relative_date_to_seconds(date_2) def convert_to_entity_params(events: List[Event]) -> Tuple[List, List]: res_events = [] res_actions = [] for idx, event in enumerate(events): event_type = event[0] event_val = event[1] if event_type == "events": res_events.append( {"id": event_val, "name": event_val, "order": idx, "type": event_type} ) elif event_type == "actions": action = Action.objects.get(id=event_val) res_actions.append( {"id": event_val, "name": action.name, "order": idx, "type": event_type} ) return res_events, res_actions def get_relative_date_arg(relative_date: Relative_Date) -> str: return f"-{relative_date[0]}{relative_date[1][0].lower()}" def full_outer_join_query( q: str, alias: str, left_operand: str, right_operand: str ) -> str: return join_query(q, "FULL OUTER JOIN", alias, left_operand, right_operand) def inner_join_query(q: str, alias: str, left_operand: str, right_operand: str) -> str: return join_query(q, "INNER JOIN", alias, left_operand, right_operand) def join_query( q: str, join: str, alias: str, left_operand: str, right_operand: str ) -> str: return f"{join} ({q}) {alias} ON {left_operand} = {right_operand}" def if_condition(condition: str, true_res: str, false_res: str) -> str: return f"if({condition}, {true_res}, {false_res})" class FOSSCohortQuery(EventQuery): BEHAVIOR_QUERY_ALIAS = "behavior_query" FUNNEL_QUERY_ALIAS = "funnel_query" SEQUENCE_FIELD_ALIAS = "steps" _fields: List[str] _events: List[str] _earliest_time_for_event_query: Optional[Relative_Date] _restrict_event_query_by_time: bool def __init__( self, filter: Filter, team: Team, *, cohort_pk: Optional[int] = None, round_interval=False, should_join_distinct_ids=False, should_join_persons=False, # Extra events/person table columns to fetch since parent query needs them extra_fields: List[ColumnName] = [], extra_event_properties: List[PropertyName] = [], extra_person_fields: List[ColumnName] = [], override_aggregate_users_by_distinct_id: Optional[bool] = None, **kwargs, ) -> None: self._fields = [] self._events = [] self._earliest_time_for_event_query = None self._restrict_event_query_by_time = True self._cohort_pk = cohort_pk super().__init__( filter=FOSSCohortQuery.unwrap_cohort(filter, team.pk), team=team, round_interval=round_interval, should_join_distinct_ids=should_join_distinct_ids, should_join_persons=should_join_persons, extra_fields=extra_fields, extra_event_properties=extra_event_properties, extra_person_fields=extra_person_fields, override_aggregate_users_by_distinct_id=override_aggregate_users_by_distinct_id, person_on_events_mode=team.person_on_events_mode, **kwargs, ) self._validate_negations() property_groups = ( self._column_optimizer.property_optimizer.parse_property_groups( self._filter.property_groups ) ) self._inner_property_groups = property_groups.inner self._outer_property_groups = property_groups.outer @staticmethod def unwrap_cohort(filter: Filter, team_id: int) -> Filter: def _unwrap( property_group: PropertyGroup, negate_group: bool = False ) -> PropertyGroup: if len(property_group.values): if isinstance(property_group.values[0], PropertyGroup): # dealing with a list of property groups, so unwrap each one # Propogate the negation to the children and handle as necessary with respect to deMorgan's law if not negate_group: return PropertyGroup( type=property_group.type, values=[ _unwrap(v) for v in cast( List[PropertyGroup], property_group.values ) ], ) else: return PropertyGroup( type=PropertyOperatorType.AND if property_group.type == PropertyOperatorType.OR else PropertyOperatorType.OR, values=[ _unwrap(v, True) for v in cast( List[PropertyGroup], property_group.values ) ], ) elif isinstance(property_group.values[0], Property): # dealing with a list of properties # if any single one is a cohort property, unwrap it into a property group # which implies converting everything else in the list into a property group too new_property_group_list: List[PropertyGroup] = [] for prop in property_group.values: prop = cast(Property, prop) current_negation = prop.negation or False negation_value = ( not current_negation if negate_group else current_negation ) if prop.type in ["cohort", "precalculated-cohort"]: try: prop_cohort: Cohort = Cohort.objects.get( pk=prop.value, team_id=team_id ) if prop_cohort.is_static: new_property_group_list.append( PropertyGroup( type=PropertyOperatorType.AND, values=[ Property( type="static-cohort", key="id", value=prop_cohort.pk, negation=negation_value, ) ], ) ) else: new_property_group_list.append( _unwrap(prop_cohort.properties, negation_value) ) except Cohort.DoesNotExist: new_property_group_list.append( PropertyGroup( type=PropertyOperatorType.AND, values=[ Property( key="fake_key_01r2ho", value=0, type="person", ) ], ) ) else: prop.negation = negation_value new_property_group_list.append( PropertyGroup( type=PropertyOperatorType.AND, values=[prop] ) ) if not negate_group: return PropertyGroup( type=property_group.type, values=new_property_group_list ) else: return PropertyGroup( type=PropertyOperatorType.AND if property_group.type == PropertyOperatorType.OR else PropertyOperatorType.OR, values=new_property_group_list, ) return property_group new_props = _unwrap(filter.property_groups) return filter.shallow_clone({"properties": new_props.to_dict()}) # Implemented in /ee def get_query(self) -> Tuple[str, Dict[str, Any]]: if not self._outer_property_groups: # everything is pushed down, no behavioral stuff to do # thus, use personQuery directly return self._person_query.get_query(prepend=self._cohort_pk) # TODO: clean up this kludge. Right now, get_conditions has to run first so that _fields is populated for _get_behavioral_subquery() conditions, condition_params = self._get_conditions() self.params.update(condition_params) subq = [] ( behavior_subquery, behavior_subquery_params, behavior_query_alias, ) = self._get_behavior_subquery() subq.append((behavior_subquery, behavior_query_alias)) self.params.update(behavior_subquery_params) person_query, person_params, person_query_alias = self._get_persons_query( prepend=str(self._cohort_pk) ) subq.append((person_query, person_query_alias)) self.params.update(person_params) # Since we can FULL OUTER JOIN, we may end up with pairs of uuids where one side is blank. Always try to choose the non blank ID q, fields = self._build_sources(subq) final_query = f""" SELECT {fields} AS id FROM {q} WHERE 1 = 1 {conditions} """ return final_query, self.params def _build_sources(self, subq: List[Tuple[str, str]]) -> Tuple[str, str]: q = "" filtered_queries = [(q, alias) for (q, alias) in subq if q and len(q)] prev_alias: Optional[str] = None fields = "" for idx, (subq_query, subq_alias) in enumerate(filtered_queries): if idx == 0: q += f"({subq_query}) {subq_alias}" fields = f"{subq_alias}.person_id" elif prev_alias: # can't join without a previous alias if ( subq_alias == self.PERSON_TABLE_ALIAS and self.should_pushdown_persons ): if self._person_on_events_mode == PersonOnEventsMode.V1_ENABLED: # when using person-on-events, instead of inner join, we filter inside # the event query itself continue q = f"{q} {inner_join_query(subq_query, subq_alias, f'{subq_alias}.person_id', f'{prev_alias}.person_id')}" fields = f"{subq_alias}.person_id" else: q = f"{q} {full_outer_join_query(subq_query, subq_alias, f'{subq_alias}.person_id', f'{prev_alias}.person_id')}" fields = if_condition( f"{prev_alias}.person_id = '00000000-0000-0000-0000-000000000000'", f"{subq_alias}.person_id", f"{fields}", ) prev_alias = subq_alias return q, fields def _get_behavior_subquery(self) -> Tuple[str, Dict[str, Any], str]: # # Get the subquery for the cohort query. # event_param_name = f"{self._cohort_pk}_event_ids" person_prop_query = "" person_prop_params: dict = {} query, params = "", {} if self._should_join_behavioral_query: _fields = [ f"{self.DISTINCT_ID_TABLE_ALIAS if self._person_on_events_mode == PersonOnEventsMode.DISABLED else self.EVENT_TABLE_ALIAS}.person_id AS person_id" ] _fields.extend(self._fields) if ( self.should_pushdown_persons and self._person_on_events_mode != PersonOnEventsMode.DISABLED ): person_prop_query, person_prop_params = self._get_prop_groups( self._inner_property_groups, person_properties_mode=PersonPropertiesMode.DIRECT_ON_EVENTS, person_id_joined_alias=self._person_id_alias, ) date_condition, date_params = self._get_date_condition() query = f""" SELECT {", ".join(_fields)} FROM events {self.EVENT_TABLE_ALIAS} {self._get_person_ids_query()} WHERE team_id = %(team_id)s AND event IN %({event_param_name})s {date_condition} {person_prop_query} GROUP BY person_id """ query, params = ( query, { "team_id": self._team_id, event_param_name: self._events, **date_params, **person_prop_params, }, ) return query, params, self.BEHAVIOR_QUERY_ALIAS def _get_persons_query(self, prepend: str = "") -> Tuple[str, Dict[str, Any], str]: query, params = "", {} if self._should_join_persons: person_query, person_params = self._person_query.get_query(prepend=prepend) person_query = f"SELECT *, id AS person_id FROM ({person_query})" query, params = person_query, person_params return query, params, self.PERSON_TABLE_ALIAS @cached_property def should_pushdown_persons(self) -> bool: return "person" not in [ prop.type for prop in getattr(self._outer_property_groups, "flat", []) ] and "static-cohort" not in [ prop.type for prop in getattr(self._outer_property_groups, "flat", []) ] def _get_date_condition(self) -> Tuple[str, Dict[str, Any]]: date_query = "" date_params: Dict[str, Any] = {} earliest_time_param = f"earliest_time_{self._cohort_pk}" if self._earliest_time_for_event_query and self._restrict_event_query_by_time: date_params = {earliest_time_param: self._earliest_time_for_event_query[0]} date_query = f"AND timestamp <= now() AND timestamp >= now() - INTERVAL %({earliest_time_param})s {self._earliest_time_for_event_query[1]}" return date_query, date_params def _check_earliest_date(self, relative_date: Relative_Date) -> None: if self._earliest_time_for_event_query is None: self._earliest_time_for_event_query = relative_date elif relative_date_is_greater( relative_date, self._earliest_time_for_event_query ): self._earliest_time_for_event_query = relative_date def _get_conditions(self) -> Tuple[str, Dict[str, Any]]: def build_conditions( prop: Optional[Union[PropertyGroup, Property]], prepend="level", num=0 ): if not prop: return "", {} if isinstance(prop, PropertyGroup): params = {} conditions = [] for idx, p in enumerate(prop.values): q, q_params = build_conditions(p, f"{prepend}_level_{num}", idx) # type: ignore if q != "": conditions.append(q) params.update(q_params) return f"({f' {prop.type} '.join(conditions)})", params else: return self._get_condition_for_property(prop, prepend, num) conditions, params = build_conditions( self._outer_property_groups, prepend=f"{self._cohort_pk}_level", num=0 ) return f"AND ({conditions})" if conditions else "", params # Implemented in /ee def _get_condition_for_property( self, prop: Property, prepend: str, idx: int ) -> Tuple[str, Dict[str, Any]]: res: str = "" params: Dict[str, Any] = {} if prop.type == "behavioral": if prop.value == "performed_event": res, params = self.get_performed_event_condition(prop, prepend, idx) elif prop.value == "performed_event_multiple": res, params = self.get_performed_event_multiple(prop, prepend, idx) elif prop.type == "person": res, params = self.get_person_condition(prop, prepend, idx) elif ( prop.type == "static-cohort" ): # "cohort" and "precalculated-cohort" are handled by flattening during initialization res, params = self.get_static_cohort_condition(prop, prepend, idx) else: raise ValueError(f"Invalid property type for Cohort queries: {prop.type}") return res, params def get_person_condition( self, prop: Property, prepend: str, idx: int ) -> Tuple[str, Dict[str, Any]]: if self._outer_property_groups and len(self._outer_property_groups.flat): return prop_filter_json_extract( prop, idx, prepend, prop_var="person_props", allow_denormalized_props=True, property_operator="", ) else: return "", {} def get_static_cohort_condition( self, prop: Property, prepend: str, idx: int ) -> Tuple[str, Dict[str, Any]]: # If we reach this stage, it means there are no cyclic dependencies # They should've been caught by API update validation # and if not there, `simplifyFilter` would've failed cohort = Cohort.objects.get(pk=cast(int, prop.value)) query, params = format_static_cohort_query(cohort, idx, prepend) return f"id {'NOT' if prop.negation else ''} IN ({query})", params def get_performed_event_condition( self, prop: Property, prepend: str, idx: int ) -> Tuple[str, Dict[str, Any]]: event = (prop.event_type, prop.key) column_name = f"performed_event_condition_{prepend}_{idx}" entity_query, entity_params = self._get_entity(event, prepend, idx) date_value = parse_and_validate_positive_integer(prop.time_value, "time_value") date_interval = validate_interval(prop.time_interval) date_param = f"{prepend}_date_{idx}" self._check_earliest_date((date_value, date_interval)) field = f"countIf(timestamp > now() - INTERVAL %({date_param})s {date_interval} AND timestamp < now() AND {entity_query}) > 0 AS {column_name}" self._fields.append(field) # Negation is handled in the where clause to ensure the right result if a full join occurs where the joined person did not perform the event return f"{'NOT' if prop.negation else ''} {column_name}", { f"{date_param}": date_value, **entity_params, } def get_performed_event_multiple( self, prop: Property, prepend: str, idx: int ) -> Tuple[str, Dict[str, Any]]: event = (prop.event_type, prop.key) column_name = f"performed_event_multiple_condition_{prepend}_{idx}" entity_query, entity_params = self._get_entity(event, prepend, idx) count = parse_and_validate_positive_integer( prop.operator_value, "operator_value" ) date_value = parse_and_validate_positive_integer(prop.time_value, "time_value") date_interval = validate_interval(prop.time_interval) date_param = f"{prepend}_date_{idx}" operator_value_param = f"{prepend}_operator_value_{idx}" self._check_earliest_date((date_value, date_interval)) field = f"countIf(timestamp > now() - INTERVAL %({date_param})s {date_interval} AND timestamp < now() AND {entity_query}) {get_count_operator(prop.operator)} %({operator_value_param})s AS {column_name}" self._fields.append(field) # Negation is handled in the where clause to ensure the right result if a full join occurs where the joined person did not perform the event return ( f"{'NOT' if prop.negation else ''} {column_name}", { f"{operator_value_param}": count, f"{date_param}": date_value, **entity_params, }, ) def _determine_should_join_distinct_ids(self) -> None: self._should_join_distinct_ids = ( self._person_on_events_mode != PersonOnEventsMode.V1_ENABLED ) def _determine_should_join_persons(self) -> None: # :TRICKY: This doesn't apply to joining inside events query, but to the # overall query, while `should_join_distinct_ids` applies only to # event subqueries self._should_join_persons = ( self._column_optimizer.is_using_person_properties or len(self._column_optimizer.used_properties_with_type("static-cohort")) > 0 ) @cached_property def _should_join_behavioral_query(self) -> bool: for prop in self._filter.property_groups.flat: if prop.value in [ BehavioralPropertyType.PERFORMED_EVENT, BehavioralPropertyType.PERFORMED_EVENT_FIRST_TIME, BehavioralPropertyType.PERFORMED_EVENT_MULTIPLE, BehavioralPropertyType.PERFORMED_EVENT_REGULARLY, BehavioralPropertyType.RESTARTED_PERFORMING_EVENT, BehavioralPropertyType.STOPPED_PERFORMING_EVENT, ]: return True return False # Check if negations are always paired with a positive filter # raise a value error warning that this is an invalid cohort # implemented in /ee def _validate_negations(self) -> None: pass def _get_entity( self, event: Tuple[Optional[str], Optional[Union[int, str]]], prepend: str, idx: int, ) -> Tuple[str, Dict[str, Any]]: res: str = "" params: Dict[str, Any] = {} if event[0] is None or event[1] is None: raise ValueError("Event type and key must be specified") if event[0] == "actions": self._add_action(int(event[1])) res, params = get_entity_query( None, int(event[1]), self._team_id, f"{prepend}_entity_{idx}", self._filter.hogql_context, ) elif event[0] == "events": self._add_event(str(event[1])) res, params = get_entity_query( str(event[1]), None, self._team_id, f"{prepend}_entity_{idx}", self._filter.hogql_context, ) else: raise ValueError(f"Event type must be 'events' or 'actions'") return res, params def _add_action(self, action_id: int) -> None: action = Action.objects.get(id=action_id) for step in action.steps.all(): self._events.append(step.event) def _add_event(self, event_id: str) -> None: self._events.append(event_id)
access
views
import json import logging import os import uuid from functools import wraps import archivematicaFunctions import components.filesystem_ajax.views as filesystem_views import django.http from agentarchives.archivesspace import ArchivesSpaceError, AuthenticationError from components import helpers from components.ingest.views_as import get_as_system_client from django.shortcuts import redirect from django.utils import timezone from main.models import ( SIP, ArchivesSpaceDigitalObject, DublinCore, SIPArrange, SIPArrangeAccessMapping, ) logger = logging.getLogger("archivematica.dashboard") """ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Access @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ """ def _authenticate_to_archivesspace(func): @wraps(func) def wrapper(*args, **kwargs): try: client = get_as_system_client() except AuthenticationError: response = { "success": False, "message": "Unable to authenticate to ArchivesSpace server using the default user! Check administrative settings.", } return django.http.HttpResponseServerError( json.dumps(response), content_type="application/json" ) except ArchivesSpaceError: response = { "success": False, "message": "Unable to connect to ArchivesSpace server at the default location! Check administrative settings.", } return django.http.HttpResponseServerError( json.dumps(response), content_type="application/json" ) return func(client, *args, **kwargs) return wrapper def _normalize_record_id(record_id): """ Normalizes a record ID that has been mangled for a URL. ArchivesSpace record IDs are URL fragments, in the format /repository/n/type/n. The slashes are replaced by dashes so that they can be conveniently passed in URLs within this module; this function transforms them back into the original format. """ return record_id.replace("-", "/") def _get_arrange_path(func): @wraps(func) def wrapper(request, record_id=""): try: mapping = SIPArrangeAccessMapping.objects.get( system=SIPArrangeAccessMapping.ARCHIVESSPACE, identifier=_normalize_record_id(record_id), ) return func(request, mapping) except SIPArrangeAccessMapping.DoesNotExist: response = { "success": False, "message": "No SIP Arrange mapping exists for record {}".format( record_id ), } return helpers.json_response(response, status_code=404) return wrapper def _get_or_create_arrange_path(func): @wraps(func) def wrapper(request, record_id=""): mapping = create_arranged_directory(record_id) return func(request, mapping) return wrapper def _get_sip(func): @wraps(func) def wrapper(request, mapping): arrange = SIPArrange.objects.get( arrange_path=os.path.join(mapping.arrange_path, "") ) if arrange.sip is None: arrange.sip = SIP.objects.create(uuid=(uuid.uuid4()), currentpath=None) arrange.save() return func(request, arrange.sip) return wrapper @_authenticate_to_archivesspace def all_records(client, request): page = request.GET.get("page", 1) page_size = request.GET.get("page_size", 30) search_pattern = request.GET.get("title", "") identifier = request.GET.get("identifier", "") records = client.find_collections( search_pattern=search_pattern, identifier=identifier, page=page, page_size=page_size, ) for i, r in enumerate(records): records[i] = _get_sip_arrange_children(r) return helpers.json_response(records) @_authenticate_to_archivesspace def record(client, request, record_id=""): if request.method == "PUT": try: new_record = json.load(request) except ValueError: response = { "success": False, "message": "No JSON object could be decoded from request body.", } return helpers.json_response(response, status_code=400) try: client.edit_record(new_record) except ArchivesSpaceError as e: return helpers.json_response( {"sucess": False, "message": str(e)}, status_code=500 ) return helpers.json_response({"success": True, "message": "Record updated."}) elif request.method == "GET": record_id = _normalize_record_id(record_id) try: records = client.get_resource_component_and_children( record_id, recurse_max_level=3 ) return helpers.json_response(records) except ArchivesSpaceError as e: return helpers.json_response( {"success": False, "message": str(e)}, status_code=400 ) elif request.method == "DELETE": # Delete associated SIPArrange entries try: mapping = SIPArrangeAccessMapping.objects.get( system=SIPArrangeAccessMapping.ARCHIVESSPACE, identifier=_normalize_record_id(record_id), ) except SIPArrangeAccessMapping.DoesNotExist: logger.debug("No access mapping for %s", record_id) else: filesystem_views.delete_arrange( request, filepath=mapping.arrange_path + "/" ) # Delete in Aspace return helpers.json_response( client.delete_record(_normalize_record_id(record_id)) ) @_authenticate_to_archivesspace def record_children(client, request, record_id=""): record_id = _normalize_record_id(record_id) if request.method == "POST": new_record_data = json.load(request) try: notes = new_record_data.get("notes", []) new_id = client.add_child( record_id, title=new_record_data.get("title", ""), level=new_record_data.get("level", ""), start_date=new_record_data.get("start_date", ""), end_date=new_record_data.get("end_date", ""), date_expression=new_record_data.get("date_expression", ""), notes=notes, ) except ArchivesSpaceError as e: response = {"success": False, "message": str(e)} return helpers.json_response(response, status_code=400) response = { "success": True, "id": new_id, "message": "New record successfully created", } return helpers.json_response(response) elif request.method == "GET": records = client.get_resource_component_and_children( record_id, recurse_max_level=3 ) records = _get_sip_arrange_children(records) return helpers.json_response(records["children"]) def get_digital_object_component_path(record_id, component_id, create=True): mapping = create_arranged_directory(record_id) component_path = os.path.join( mapping.arrange_path, f"digital_object_component_{component_id}", "" ) if create: filesystem_views.create_arrange_directories([component_path]) return component_path @_authenticate_to_archivesspace def digital_object_components(client, request, record_id=""): """ List, modify or view the digital object components associated with the record `record_id`. GET: Returns a list of all digital object components in the database associated with `record_id`. These are returned as dictionaries containing the keys `id`, `label`, and `title`. POST: Creates a new digital object component associated with `record_id`. The `label` and `title` of the new object, and the `uuid` of a SIP with which the component should be associated, can be specified by including a JSON document in the request body with values in those keys. PUT: Updates an existing digital object component, using `title` and `label` values in a JSON document in the request body. The `component_id` to the component to edit must be specified in the request body. """ if request.method == "POST": record = json.load(request) component = ArchivesSpaceDigitalObject.objects.create( resourceid=_normalize_record_id(record_id), sip_id=record.get("uuid"), label=record.get("label", ""), title=record.get("title", ""), ) try: access_path = get_digital_object_component_path( record_id, component.id, create=True ) except ValueError as e: component.delete() response = {"success": False, "message": str(e)} return helpers.json_response(response, status_code=400) response = { "success": True, "message": "Digital object component successfully created", "component_id": component.id, "component_path": access_path, } return helpers.json_response(response) elif request.method == "GET": components = list( ArchivesSpaceDigitalObject.objects.filter( resourceid=_normalize_record_id(record_id), started=False ).values("id", "resourceid", "label", "title") ) for component in components: access_path = get_digital_object_component_path(record_id, component["id"]) component["path"] = access_path component["type"] = "digital_object" return helpers.json_response(components) elif request.method == "PUT": record = json.load(request) try: component_id = record["component_id"] except KeyError: response = {"success": False, "message": "No component_id was specified!"} return helpers.json_response(response, status_code=400) try: component = ArchivesSpaceDigitalObject.objects.get(id=component_id) except ArchivesSpaceDigitalObject.DoesNotExist: response = { "success": False, "message": "No digital object component exists with the specified ID: {}".format( component_id ), } return helpers.json_response(response, status_code=404) else: component.label = record.get("label", "") component.title = record.get("title", "") component.save() return django.http.HttpResponse(status=204) def _get_sip_arrange_children(record): """Recursively check for SIPArrange associations.""" try: mapping = SIPArrangeAccessMapping.objects.get( system=SIPArrangeAccessMapping.ARCHIVESSPACE, identifier=record["id"] ) record["path"] = mapping.arrange_path record["children"] = record["children"] or [] record["has_children"] = True except ( SIPArrangeAccessMapping.MultipleObjectsReturned, SIPArrangeAccessMapping.DoesNotExist, ): pass if record["children"]: # record['children'] may be False for i, r in enumerate(record["children"]): record["children"][i] = _get_sip_arrange_children(r) record["has_children"] = ( record["has_children"] or ArchivesSpaceDigitalObject.objects.filter(resourceid=record["id"]).exists() ) return record @_authenticate_to_archivesspace def get_levels_of_description(client, request): levels = client.get_levels_of_description() return helpers.json_response(levels) def create_arranged_directory(record_id): """ Creates a directory to house an arranged SIP associated with `record_id`. If a mapping already exists, returns the existing mapping. Otherwise, creates one along with a directory in the arranged directory tree. """ identifier = _normalize_record_id(record_id) mapping, created = SIPArrangeAccessMapping.objects.get_or_create( system=SIPArrangeAccessMapping.ARCHIVESSPACE, identifier=identifier ) if created: try: filepath = ( "/arrange/" + record_id + str(uuid.uuid4()) ) # TODO: get this from the title? filesystem_views.create_arrange_directories([filepath]) except ValueError: mapping.delete() return else: mapping.arrange_path = filepath mapping.save() return mapping def access_create_directory(request, record_id=""): """ Creates an arranged SIP directory for record `record_id`. """ mapping = create_arranged_directory(record_id) if mapping is not None: response = { "success": True, "message": "Creation successful.", "path": mapping.arrange_path, } status_code = 201 else: response = {"success": False, "message": "Could not create arrange directory."} status_code = 400 return helpers.json_response(response, status_code=status_code) @_get_or_create_arrange_path @_get_sip def access_sip_rights(request, sip): return redirect("rights_ingest:index", uuid=sip.uuid) @_get_or_create_arrange_path @_get_sip def access_sip_metadata(request, sip): return redirect("ingest:ingest_metadata_list", uuid=sip.uuid) def access_copy_to_arrange(request, record_id=""): """ Copies a record from POST parameter `filepath` into the SIP arrange directory for the specified record, creating a directory if necessary. This should be used to copy files into the root of the SIP, while filesystem_ajax's version of this API should be used to copy deeper into the record. """ mapping = create_arranged_directory(record_id) if mapping is None: response = {"success": False, "message": "Unable to create directory."} return helpers.json_response(response, status_code=400) sourcepath = archivematicaFunctions.b64decode_string( request.POST.get("filepath", "") ).lstrip("/") return filesystem_views.copy_to_arrange( request, sourcepath=sourcepath, destination=mapping.arrange_path + "/" ) @_get_arrange_path def access_arrange_contents(request, mapping): """ Lists the files in the root of the SIP arrange directory associated with this record. """ return filesystem_views.arrange_contents(request, path=mapping.arrange_path + "/") @_get_arrange_path @_authenticate_to_archivesspace def access_arrange_start_sip(client, request, mapping): """ Starts the SIP associated with this record. """ try: arrange = SIPArrange.objects.get( arrange_path=os.path.join(mapping.arrange_path, "") ) except SIPArrange.DoesNotExist: response = { "success": False, "message": "No SIP Arrange object exists for record {}".format( mapping.identifier ), } return helpers.json_response(response, status_code=404) # Get metadata from ArchivesSpace archival_object = client.get_record(mapping.identifier) logger.debug("archival object %s", archival_object) # dc.creator is sort_name of the resource's linked_agent with role: creator resource = client.get_record(archival_object["resource"]["ref"]) logger.debug("resource %s", resource) creators = [ agent for agent in resource["linked_agents"] if agent["role"] == "creator" ] if creators: creator = client.get_record(creators[0]["ref"]) logger.debug("creator %s", creator) creator = creator["display_name"]["sort_name"] else: response = { "success": False, "message": "Unable to fetch ArchivesSpace creator", } return helpers.json_response(response, status_code=502) # dc.description is general note's content notes = [n for n in archival_object["notes"] if n["type"] == "odd"] description = notes[0]["subnotes"][0]["content"] if notes else "" # dc.relation is parent archival object's display names relation = [] parent = archival_object.get("parent", {}).get("ref") while parent: parent_obj = client.get_record(parent) parent_title = ( parent_obj["title"] if parent_obj.get("title") else parent_obj["display_string"] ) relation = [parent_title] + relation parent = parent_obj.get("parent", {}).get("ref") relation = " - ".join(relation) # Create digital objects in ASpace related to the resource instead of digital object components for do in ArchivesSpaceDigitalObject.objects.filter( resourceid=mapping.identifier, started=False ): new_do = client.add_digital_object(mapping.identifier, str(uuid.uuid4())) do.remoteid = new_do["id"] do.save() sip_uuid = arrange.sip_id sip_name = json.load(request).get("sip_name", "") status_code, response = filesystem_views.copy_from_arrange_to_completed_common( filepath=mapping.arrange_path + "/", sip_uuid=sip_uuid, sip_name=sip_name ) if not response.get("error"): sip_uuid = response["sip_uuid"] logger.debug("New SIP UUID %s", sip_uuid) # Update ArchivesSpaceDigitalObject with new SIP UUID ArchivesSpaceDigitalObject.objects.filter( resourceid=mapping.identifier, started=False ).update(started=True, sip_id=response["sip_uuid"]) # Create new SIP-level DC with ArchivesSpace metadata DublinCore.objects.create( metadataappliestotype_id="3e48343d-e2d2-4956-aaa3-b54d26eb9761", # SIP metadataappliestoidentifier=sip_uuid, title=archival_object["display_string"], creator=creator, date=str(timezone.now().year), description=description, rights="This content may be under copyright. Researchers are responsible for determining the appropriate use or reuse of materials.", relation=relation, ) return helpers.json_response(response, status_code=status_code)
downloader
f4m
from __future__ import division, unicode_literals import io import itertools import time from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_struct_pack, compat_struct_unpack, compat_urllib_error, compat_urllib_parse_urlparse, compat_urlparse, ) from ..utils import fix_xml_ampersands, xpath_text from .fragment import FragmentFD class DataTruncatedError(Exception): pass class FlvReader(io.BytesIO): """ Reader for Flv files The file format is documented in https://www.adobe.com/devnet/f4v.html """ def read_bytes(self, n): data = self.read(n) if len(data) < n: raise DataTruncatedError( "FlvReader error: need %d bytes while only %d bytes got" % (n, len(data)) ) return data # Utility functions for reading numbers and strings def read_unsigned_long_long(self): return compat_struct_unpack("!Q", self.read_bytes(8))[0] def read_unsigned_int(self): return compat_struct_unpack("!I", self.read_bytes(4))[0] def read_unsigned_char(self): return compat_struct_unpack("!B", self.read_bytes(1))[0] def read_string(self): res = b"" while True: char = self.read_bytes(1) if char == b"\x00": break res += char return res def read_box_info(self): """ Read a box and return the info as a tuple: (box_size, box_type, box_data) """ real_size = size = self.read_unsigned_int() box_type = self.read_bytes(4) header_end = 8 if size == 1: real_size = self.read_unsigned_long_long() header_end = 16 return real_size, box_type, self.read_bytes(real_size - header_end) def read_asrt(self): # version self.read_unsigned_char() # flags self.read_bytes(3) quality_entry_count = self.read_unsigned_char() # QualityEntryCount for i in range(quality_entry_count): self.read_string() segment_run_count = self.read_unsigned_int() segments = [] for i in range(segment_run_count): first_segment = self.read_unsigned_int() fragments_per_segment = self.read_unsigned_int() segments.append((first_segment, fragments_per_segment)) return { "segment_run": segments, } def read_afrt(self): # version self.read_unsigned_char() # flags self.read_bytes(3) # time scale self.read_unsigned_int() quality_entry_count = self.read_unsigned_char() # QualitySegmentUrlModifiers for i in range(quality_entry_count): self.read_string() fragments_count = self.read_unsigned_int() fragments = [] for i in range(fragments_count): first = self.read_unsigned_int() first_ts = self.read_unsigned_long_long() duration = self.read_unsigned_int() if duration == 0: discontinuity_indicator = self.read_unsigned_char() else: discontinuity_indicator = None fragments.append( { "first": first, "ts": first_ts, "duration": duration, "discontinuity_indicator": discontinuity_indicator, } ) return { "fragments": fragments, } def read_abst(self): # version self.read_unsigned_char() # flags self.read_bytes(3) self.read_unsigned_int() # BootstrapinfoVersion # Profile,Live,Update,Reserved flags = self.read_unsigned_char() live = flags & 0x20 != 0 # time scale self.read_unsigned_int() # CurrentMediaTime self.read_unsigned_long_long() # SmpteTimeCodeOffset self.read_unsigned_long_long() self.read_string() # MovieIdentifier server_count = self.read_unsigned_char() # ServerEntryTable for i in range(server_count): self.read_string() quality_count = self.read_unsigned_char() # QualityEntryTable for i in range(quality_count): self.read_string() # DrmData self.read_string() # MetaData self.read_string() segments_count = self.read_unsigned_char() segments = [] for i in range(segments_count): box_size, box_type, box_data = self.read_box_info() assert box_type == b"asrt" segment = FlvReader(box_data).read_asrt() segments.append(segment) fragments_run_count = self.read_unsigned_char() fragments = [] for i in range(fragments_run_count): box_size, box_type, box_data = self.read_box_info() assert box_type == b"afrt" fragments.append(FlvReader(box_data).read_afrt()) return { "segments": segments, "fragments": fragments, "live": live, } def read_bootstrap_info(self): total_size, box_type, box_data = self.read_box_info() assert box_type == b"abst" return FlvReader(box_data).read_abst() def read_bootstrap_info(bootstrap_bytes): return FlvReader(bootstrap_bytes).read_bootstrap_info() def build_fragments_list(boot_info): """Return a list of (segment, fragment) for each fragment in the video""" res = [] segment_run_table = boot_info["segments"][0] fragment_run_entry_table = boot_info["fragments"][0]["fragments"] first_frag_number = fragment_run_entry_table[0]["first"] fragments_counter = itertools.count(first_frag_number) for segment, fragments_count in segment_run_table["segment_run"]: # In some live HDS streams (for example Rai), `fragments_count` is # abnormal and causing out-of-memory errors. It's OK to change the # number of fragments for live streams as they are updated periodically if fragments_count == 4294967295 and boot_info["live"]: fragments_count = 2 for _ in range(fragments_count): res.append((segment, next(fragments_counter))) if boot_info["live"]: res = res[-2:] return res def write_unsigned_int(stream, val): stream.write(compat_struct_pack("!I", val)) def write_unsigned_int_24(stream, val): stream.write(compat_struct_pack("!I", val)[1:]) def write_flv_header(stream): """Writes the FLV header to stream""" # FLV header stream.write(b"FLV\x01") stream.write(b"\x05") stream.write(b"\x00\x00\x00\x09") stream.write(b"\x00\x00\x00\x00") def write_metadata_tag(stream, metadata): """Writes optional metadata tag to stream""" SCRIPT_TAG = b"\x12" FLV_TAG_HEADER_LEN = 11 if metadata: stream.write(SCRIPT_TAG) write_unsigned_int_24(stream, len(metadata)) stream.write(b"\x00\x00\x00\x00\x00\x00\x00") stream.write(metadata) write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata)) def remove_encrypted_media(media): return list( filter( lambda e: "drmAdditionalHeaderId" not in e.attrib and "drmAdditionalHeaderSetId" not in e.attrib, media, ) ) def _add_ns(prop, ver=1): return "{http://ns.adobe.com/f4m/%d.0}%s" % (ver, prop) def get_base_url(manifest): base_url = xpath_text( manifest, [_add_ns("baseURL"), _add_ns("baseURL", 2)], "base URL", default=None ) if base_url: base_url = base_url.strip() return base_url class F4mFD(FragmentFD): """ A downloader for f4m manifests or AdobeHDS. """ FD_NAME = "f4m" def _get_unencrypted_media(self, doc): media = doc.findall(_add_ns("media")) if not media: self.report_error("No media found") for e in doc.findall(_add_ns("drmAdditionalHeader")) + doc.findall( _add_ns("drmAdditionalHeaderSet") ): # If id attribute is missing it's valid for all media nodes # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute if "id" not in e.attrib: self.report_error("Missing ID in f4m DRM") media = remove_encrypted_media(media) if not media: self.report_error("Unsupported DRM") return media def _get_bootstrap_from_url(self, bootstrap_url): bootstrap = self.ydl.urlopen(bootstrap_url).read() return read_bootstrap_info(bootstrap) def _update_live_fragments(self, bootstrap_url, latest_fragment): fragments_list = [] retries = 30 while (not fragments_list) and (retries > 0): boot_info = self._get_bootstrap_from_url(bootstrap_url) fragments_list = build_fragments_list(boot_info) fragments_list = [f for f in fragments_list if f[1] > latest_fragment] if not fragments_list: # Retry after a while time.sleep(5.0) retries -= 1 if not fragments_list: self.report_error("Failed to update fragments") return fragments_list def _parse_bootstrap_node(self, node, base_url): # Sometimes non empty inline bootstrap info can be specified along # with bootstrap url attribute (e.g. dummy inline bootstrap info # contains whitespace characters in [1]). We will prefer bootstrap # url over inline bootstrap info when present. # 1. http://live-1-1.rutube.ru/stream/1024/HDS/SD/C2NKsS85HQNckgn5HdEmOQ/1454167650/S-s604419906/move/four/dirs/upper/1024-576p.f4m bootstrap_url = node.get("url") if bootstrap_url: bootstrap_url = compat_urlparse.urljoin(base_url, bootstrap_url) boot_info = self._get_bootstrap_from_url(bootstrap_url) else: bootstrap_url = None bootstrap = compat_b64decode(node.text) boot_info = read_bootstrap_info(bootstrap) return boot_info, bootstrap_url def real_download(self, filename, info_dict): man_url = info_dict["url"] requested_bitrate = info_dict.get("tbr") self.to_screen("[%s] Downloading f4m manifest" % self.FD_NAME) urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url)) man_url = urlh.geturl() # Some manifests may be malformed, e.g. prosiebensat1 generated manifests # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244 # and https://github.com/ytdl-org/youtube-dl/issues/7823) manifest = fix_xml_ampersands(urlh.read().decode("utf-8", "ignore")).strip() doc = compat_etree_fromstring(manifest) formats = [ (int(f.attrib.get("bitrate", -1)), f) for f in self._get_unencrypted_media(doc) ] if requested_bitrate is None or len(formats) == 1: # get the best format formats = sorted(formats, key=lambda f: f[0]) rate, media = formats[-1] else: rate, media = list( filter(lambda f: int(f[0]) == requested_bitrate, formats) )[0] # Prefer baseURL for relative URLs as per 11.2 of F4M 3.0 spec. man_base_url = get_base_url(doc) or man_url base_url = compat_urlparse.urljoin(man_base_url, media.attrib["url"]) bootstrap_node = doc.find(_add_ns("bootstrapInfo")) boot_info, bootstrap_url = self._parse_bootstrap_node( bootstrap_node, man_base_url ) live = boot_info["live"] metadata_node = media.find(_add_ns("metadata")) if metadata_node is not None: metadata = compat_b64decode(metadata_node.text) else: metadata = None fragments_list = build_fragments_list(boot_info) test = self.params.get("test", False) if test: # We only download the first fragment fragments_list = fragments_list[:1] total_frags = len(fragments_list) # For some akamai manifests we'll need to add a query to the fragment url akamai_pv = xpath_text(doc, _add_ns("pv-2.0")) ctx = { "filename": filename, "total_frags": total_frags, "live": live, } self._prepare_frag_download(ctx) dest_stream = ctx["dest_stream"] if ctx["complete_frags_downloaded_bytes"] == 0: write_flv_header(dest_stream) if not live: write_metadata_tag(dest_stream, metadata) base_url_parsed = compat_urllib_parse_urlparse(base_url) self._start_frag_download(ctx) frag_index = 0 while fragments_list: seg_i, frag_i = fragments_list.pop(0) frag_index += 1 if frag_index <= ctx["fragment_index"]: continue name = "Seg%d-Frag%d" % (seg_i, frag_i) query = [] if base_url_parsed.query: query.append(base_url_parsed.query) if akamai_pv: query.append(akamai_pv.strip(";")) if info_dict.get("extra_param_to_segment_url"): query.append(info_dict["extra_param_to_segment_url"]) url_parsed = base_url_parsed._replace( path=base_url_parsed.path + name, query="&".join(query) ) try: success, down_data = self._download_fragment( ctx, url_parsed.geturl(), info_dict ) if not success: return False reader = FlvReader(down_data) while True: try: _, box_type, box_data = reader.read_box_info() except DataTruncatedError: if test: # In tests, segments may be truncated, and thus # FlvReader may not be able to parse the whole # chunk. If so, write the segment as is # See https://github.com/ytdl-org/youtube-dl/issues/9214 dest_stream.write(down_data) break raise if box_type == b"mdat": self._append_fragment(ctx, box_data) break except (compat_urllib_error.HTTPError,) as err: if live and (err.code == 404 or err.code == 410): # We didn't keep up with the live window. Continue # with the next available fragment. msg = "Fragment %d unavailable" % frag_i self.report_warning(msg) fragments_list = [] else: raise if not fragments_list and not test and live and bootstrap_url: fragments_list = self._update_live_fragments(bootstrap_url, frag_i) total_frags += len(fragments_list) if fragments_list and (fragments_list[0][1] > frag_i + 1): msg = "Missed %d fragments" % (fragments_list[0][1] - (frag_i + 1)) self.report_warning(msg) self._finish_frag_download(ctx) return True
deluge-extractor
core
# # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # # Basic plugin template created by: # Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com> # Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com> # # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with # the additional special exception to link portions of this program with the OpenSSL library. # See LICENSE for more details. # import errno import logging import os import deluge.component as component import deluge.configmanager from deluge.common import windows_check from deluge.core.rpcserver import export from deluge.plugins.pluginbase import CorePluginBase from twisted.internet.utils import getProcessOutputAndValue from twisted.python.procutils import which log = logging.getLogger(__name__) DEFAULT_PREFS = {"extract_path": "", "use_name_folder": True} if windows_check(): win_7z_exes = [ "7z.exe", "C:\\Program Files\\7-Zip\\7z.exe", "C:\\Program Files (x86)\\7-Zip\\7z.exe", ] import winreg try: hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\7-Zip") except OSError: pass else: win_7z_path = os.path.join(winreg.QueryValueEx(hkey, "Path")[0], "7z.exe") winreg.CloseKey(hkey) win_7z_exes.insert(1, win_7z_path) switch_7z = "x -y" # Future suport: # 7-zip cannot extract tar.* with single command. # ".tar.gz", ".tgz", # ".tar.bz2", ".tbz", # ".tar.lzma", ".tlz", # ".tar.xz", ".txz", exts_7z = [".rar", ".zip", ".tar", ".7z", ".xz", ".lzma"] for win_7z_exe in win_7z_exes: if which(win_7z_exe): EXTRACT_COMMANDS = dict.fromkeys(exts_7z, [win_7z_exe, switch_7z]) break else: required_cmds = ["unrar", "unzip", "tar", "unxz", "unlzma", "7zr", "bunzip2"] # Possible future suport: # gunzip: gz (cmd will delete original archive) # the following do not extract to dest dir # ".xz": ["xz", "-d --keep"], # ".lzma": ["xz", "-d --format=lzma --keep"], # ".bz2": ["bzip2", "-d --keep"], EXTRACT_COMMANDS = { ".rar": ["unrar", "x -o+ -y"], ".tar": ["tar", "-xf"], ".zip": ["unzip", ""], ".tar.gz": ["tar", "-xzf"], ".tgz": ["tar", "-xzf"], ".tar.bz2": ["tar", "-xjf"], ".tbz": ["tar", "-xjf"], ".tar.lzma": ["tar", "--lzma -xf"], ".tlz": ["tar", "--lzma -xf"], ".tar.xz": ["tar", "--xz -xf"], ".txz": ["tar", "--xz -xf"], ".7z": ["7zr", "x"], } # Test command exists and if not, remove. for command in required_cmds: if not which(command): for k, v in list(EXTRACT_COMMANDS.items()): if command in v[0]: log.warning("%s not found, disabling support for %s", command, k) del EXTRACT_COMMANDS[k] if not EXTRACT_COMMANDS: raise Exception("No archive extracting programs found, plugin will be disabled") class Core(CorePluginBase): def enable(self): self.config = deluge.configmanager.ConfigManager( "extractor.conf", DEFAULT_PREFS ) if not self.config["extract_path"]: self.config["extract_path"] = deluge.configmanager.ConfigManager( "core.conf" )["download_location"] component.get("EventManager").register_event_handler( "TorrentFinishedEvent", self._on_torrent_finished ) def disable(self): component.get("EventManager").deregister_event_handler( "TorrentFinishedEvent", self._on_torrent_finished ) def update(self): pass def _on_torrent_finished(self, torrent_id): """ This is called when a torrent finishes and checks if any files to extract. """ tid = component.get("TorrentManager").torrents[torrent_id] tid_status = tid.get_status(["download_location", "name"]) files = tid.get_files() for f in files: file_root, file_ext = os.path.splitext(f["path"]) file_ext_sec = os.path.splitext(file_root)[1] if file_ext_sec and file_ext_sec + file_ext in EXTRACT_COMMANDS: file_ext = file_ext_sec + file_ext elif file_ext not in EXTRACT_COMMANDS or file_ext_sec == ".tar": log.debug("Cannot extract file with unknown file type: %s", f["path"]) continue elif file_ext == ".rar" and "part" in file_ext_sec: part_num = file_ext_sec.split("part")[1] if part_num.isdigit() and int(part_num) != 1: log.debug("Skipping remaining multi-part rar files: %s", f["path"]) continue cmd = EXTRACT_COMMANDS[file_ext] fpath = os.path.join( tid_status["download_location"], os.path.normpath(f["path"]) ) dest = os.path.normpath(self.config["extract_path"]) if self.config["use_name_folder"]: dest = os.path.join(dest, tid_status["name"]) try: os.makedirs(dest) except OSError as ex: if not (ex.errno == errno.EEXIST and os.path.isdir(dest)): log.error("Error creating destination folder: %s", ex) break def on_extract(result, torrent_id, fpath): # Check command exit code. if not result[2]: log.info("Extract successful: %s (%s)", fpath, torrent_id) else: log.error( "Extract failed: %s (%s) %s", fpath, torrent_id, result[1] ) # Run the command and add callback. log.debug( "Extracting %s from %s with %s %s to %s", fpath, torrent_id, cmd[0], cmd[1], dest, ) d = getProcessOutputAndValue( cmd[0], cmd[1].split() + [str(fpath)], os.environ, str(dest) ) d.addCallback(on_extract, torrent_id, fpath) @export def set_config(self, config): """Sets the config dictionary.""" for key in config: self.config[key] = config[key] self.config.save() @export def get_config(self): """Returns the config dictionary.""" return self.config.config
engines
imdb
# SPDX-License-Identifier: AGPL-3.0-or-later """ IMDB - Internet Movie Database Retrieves results from a basic search Advanced search options are not supported """ import json about = { "website": "https://imdb.com/", "wikidata_id": "Q37312", "official_api_documentation": None, "use_official_api": False, "require_api_key": False, "results": "HTML", } categories = ["general"] paging = False base_url = "https://imdb.com/{category}/{id}" suggestion_url = "https://v2.sg.media-imdb.com/suggestion/{letter}/{query}.json" search_categories = { "nm": "name", "tt": "title", "kw": "keyword", "co": "company", "ep": "episode", } def request(query, params): query = query.replace(" ", "_").lower() params["url"] = suggestion_url.format(letter=query[0], query=query) return params def response(resp): suggestions = json.loads(resp.text) results = [] for entry in suggestions["d"]: content = "" if entry["id"][:2] in search_categories: href = base_url.format( category=search_categories[entry["id"][:2]], id=entry["id"] ) if "y" in entry: content += str(entry["y"]) + " - " if "s" in entry: content += entry["s"] results.append({"title": entry["l"], "url": href, "content": content}) return results
gui
history_list
from __future__ import absolute_import import os from gi.repository import Gdk, GObject, Gtk from sunflower.parameters import Parameters class Column: NAME = 0 PATH = 1 TIMESTAMP = 2 class HistoryList(Gtk.Window): """History list is used to display complete browsing history.""" def __init__(self, parent, application): # create main window GObject.GObject.__init__(self) # store parameters locally, we'll need them later self._parent = parent self._application = application # configure dialog self.set_title(_("History")) self.set_size_request(500, 300) self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT) self.set_resizable(True) self.set_skip_taskbar_hint(True) self.set_modal(True) self.set_transient_for(application) self.set_wmclass("Sunflower", "Sunflower") self.set_border_width(7) # create UI vbox = Gtk.VBox(False, 7) list_container = Gtk.ScrolledWindow() list_container.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) list_container.set_shadow_type(Gtk.ShadowType.IN) self._history = Gtk.ListStore(str, str) cell_name = Gtk.CellRendererText() cell_path = Gtk.CellRendererText() col_name = Gtk.TreeViewColumn(_("Name"), cell_name, text=Column.NAME) col_path = Gtk.TreeViewColumn(_("Path"), cell_path, text=Column.PATH) self._history_list = Gtk.TreeView(self._history) self._history_list.connect("key-press-event", self._handle_key_press) self._history_list.append_column(col_name) self._history_list.append_column(col_path) # create controls hbox_controls = Gtk.HBox(False, 5) button_close = Gtk.Button(stock=Gtk.STOCK_CLOSE) button_close.connect("clicked", self._close) image_jump = Gtk.Image() image_jump.set_from_stock(Gtk.STOCK_OPEN, Gtk.IconSize.BUTTON) button_jump = Gtk.Button() button_jump.set_image(image_jump) button_jump.set_label(_("Open")) button_jump.set_can_default(True) button_jump.connect("clicked", self._change_path, False) image_new_tab = Gtk.Image() image_new_tab.set_from_icon_name("tab-new", Gtk.IconSize.BUTTON) button_new_tab = Gtk.Button() button_new_tab.set_image(image_new_tab) button_new_tab.set_label(_("Open in tab")) button_new_tab.set_tooltip_text(_("Open selected path in new tab")) button_new_tab.connect("clicked", self._change_path, True) button_opposite = Gtk.Button(label=_("Open in opposite list")) button_opposite.set_tooltip_text(_("Open selected path in opposite list")) button_opposite.connect("clicked", self._open_in_opposite_list) # pack UI list_container.add(self._history_list) hbox_controls.pack_end(button_close, False, False, 0) hbox_controls.pack_end(button_jump, False, False, 0) hbox_controls.pack_end(button_new_tab, False, False, 0) hbox_controls.pack_end(button_opposite, False, False, 0) vbox.pack_start(list_container, True, True, 0) vbox.pack_start(hbox_controls, False, False, 0) self.add(vbox) # populate history list self._populate_list() # show all elements self.show_all() def _close(self, widget=None, data=None): """Handle clicking on close button""" self.destroy() def _change_path(self, widget=None, new_tab=False): """Change to selected path""" selection = self._history_list.get_selection() item_list, selected_iter = selection.get_selected() # if selection is valid, change to selected path if selected_iter is not None: path = item_list.get_value(selected_iter, Column.PATH) if not new_tab: # change path self._parent._handle_history_click(path=path) else: # create a new tab options = Parameters() options.set("path", path) self._application.create_tab( self._parent._notebook, self._parent.__class__, options ) # close dialog self._close() def _open_in_opposite_list(self, widget=None, data=None): """Open selected item in opposite list""" selection = self._history_list.get_selection() item_list, selected_iter = selection.get_selected() # if selection is valid, change to selected path if selected_iter is not None: path = item_list.get_value(selected_iter, Column.PATH) # open in opposite list opposite_object = self._application.get_opposite_object( self._application.get_active_object() ) if hasattr(opposite_object, "change_path"): opposite_object.change_path(path) # close dialog self._close() def _handle_key_press(self, widget, event, data=None): """Handle pressing keys in history list""" result = False if event.keyval == Gdk.KEY_Return: if event.get_state() & Gdk.ModifierType.CONTROL_MASK: # open path in new tab self._change_path(new_tab=True) else: # open path in existing tab self._change_path(new_tab=False) result = True elif event.keyval == Gdk.KEY_Escape: # close window on escape self._close() result = True return result def _populate_list(self): """Populate history list""" target_iter = None current_path = self._parent._options.get("path") # add all entries to the list for path in self._parent.history: name = os.path.basename(path) if name == "": name = path new_iter = self._history.append((name, path)) # assign row to be selected if target_iter is None or path == current_path: target_iter = new_iter # select row path = self._history.get_path(target_iter) self._history_list.set_cursor(path)
lector
logger
# This file is a part of Lector, a Qt based ebook reader # Copyright (C) 2017-2019 BasioMeusPuga # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. VERSION = "0.5.GittyGittyBangBang" import logging import os from PyQt5 import QtCore location_prefix = os.path.join( QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.AppDataLocation), "Lector", ) logger_filename = os.path.join(location_prefix, "Lector.log") def init_logging(cli_arguments): # This needs a separate 'Lector' in the os.path.join because # application name isn't explicitly set in this module os.makedirs(location_prefix, exist_ok=True) log_level = 30 # Warning and above # Set log level according to command line arguments try: if cli_arguments[1] == "debug": log_level = 10 # Debug and above print("Debug logging enabled") try: os.remove(logger_filename) # Remove old log for clarity except FileNotFoundError: pass except IndexError: pass # Create logging object logging.basicConfig( filename=logger_filename, filemode="a", format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s", datefmt="%Y/%m/%d %H:%M:%S", level=log_level, ) logging.addLevelName(60, "HAMMERTIME") ## Messages that MUST be logged return logging.getLogger("lector.main")
deluge
config
# # Copyright (C) 2008 Andrew Resch <andrewresch@gmail.com> # # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with # the additional special exception to link portions of this program with the OpenSSL library. # See LICENSE for more details. # """ Deluge Config Module This module is used for loading and saving of configuration files.. or anything really. The format of the config file is two json encoded dicts: <version dict> <content dict> The version dict contains two keys: file and format. The format version is controlled by the Config class. It should only be changed when anything below it is changed directly by the Config class. An example of this would be if we changed the serializer for the content to something different. The config file version is changed by the 'owner' of the config file. This is to signify that there is a change in the naming of some config keys or something similar along those lines. The content is simply the dict to be saved and will be serialized before being written. Converting Since the format of the config could change, there needs to be a way to have the Config object convert to newer formats. To do this, you will need to register conversion functions for various versions of the config file. Note that this can only be done for the 'config file version' and not for the 'format' version as this will be done internally. """ import json import logging import os import pickle import shutil from codecs import getwriter from tempfile import NamedTemporaryFile from deluge.common import JSON_FORMAT, get_default_config_dir log = logging.getLogger(__name__) def find_json_objects(text, decoder=json.JSONDecoder()): """Find json objects in text. Args: text (str): The text to find json objects within. Returns: list: A list of tuples containing start and end locations of json objects in the text. e.g. [(start, end), ...] """ objects = [] offset = 0 while True: try: start = text.index("{", offset) except ValueError: break try: __, index = decoder.raw_decode(text[start:]) except json.decoder.JSONDecodeError: offset = start + 1 else: offset = start + index objects.append((start, offset)) return objects def cast_to_existing_type(value, old_value): """Attempt to convert new value type to match old value type""" types_match = isinstance(old_value, (type(None), type(value))) if value is not None and not types_match: old_type = type(old_value) # Skip convert to bytes since requires knowledge of encoding and value should # be unicode anyway. if old_type is bytes: return value return old_type(value) return value class Config: """This class is used to access/create/modify config files. Args: filename (str): The config filename. defaults (dict): The default config values to insert before loading the config file. config_dir (str): the path to the config directory. file_version (int): The file format for the default config values when creating a fresh config. This value should be increased whenever a new migration function is setup to convert old config files. (default: 1) log_mask_funcs (dict): A dict of key:function, used to mask sensitive key values (e.g. passwords) when logging is enabled. """ def __init__( self, filename, defaults=None, config_dir=None, file_version=1, log_mask_funcs=None, ): self.__config = {} self.__set_functions = {} self.__change_callbacks = [] self.__log_mask_funcs = log_mask_funcs if log_mask_funcs else {} # These hold the version numbers and they will be set when loaded self.__version = {"format": 1, "file": file_version} # This will get set with a reactor.callLater whenever a config option # is set. self._save_timer = None if defaults: for key, value in defaults.items(): self.set_item(key, value, default=True) # Load the config from file in the config_dir if config_dir: self.__config_file = os.path.join(config_dir, filename) else: self.__config_file = get_default_config_dir(filename) self.load() def callLater(self, period, func, *args, **kwargs): # noqa: N802 ignore camelCase """Wrapper around reactor.callLater for test purpose.""" from twisted.internet import reactor return reactor.callLater(period, func, *args, **kwargs) def __contains__(self, item): return item in self.__config def __setitem__(self, key, value): """See set_item""" return self.set_item(key, value) def set_item(self, key, value, default=False): """Sets item 'key' to 'value' in the config dictionary. Does not allow changing the item's type unless it is None. If the types do not match, it will attempt to convert it to the set type before raising a ValueError. Args: key (str): Item to change to change. value (any): The value to change item to, must be same type as what is currently in the config. default (optional, bool): When setting a default value skip func or save callbacks. Raises: ValueError: Raised when the type of value is not the same as what is currently in the config and it could not convert the value. Examples: >>> config = Config('test.conf') >>> config['test'] = 5 >>> config['test'] 5 """ if isinstance(value, bytes): value = value.decode() if key in self.__config: try: value = cast_to_existing_type(value, self.__config[key]) except ValueError: log.warning('Value Type "%s" invalid for key: %s', type(value), key) raise else: if self.__config[key] == value: return if log.isEnabledFor(logging.DEBUG): if key in self.__log_mask_funcs: value = self.__log_mask_funcs[key](value) log.debug( 'Setting key "%s" to: %s (of type: %s)', key, value, type(value), ) self.__config[key] = value # Skip save or func callbacks if setting default value for keys if default: return # Run the set_function for this key if any for func in self.__set_functions.get(key, []): self.callLater(0, func, key, value) try: def do_change_callbacks(key, value): for func in self.__change_callbacks: func(key, value) self.callLater(0, do_change_callbacks, key, value) except Exception: pass # We set the save_timer for 5 seconds if not already set if not self._save_timer or not self._save_timer.active(): self._save_timer = self.callLater(5, self.save) def __getitem__(self, key): """See get_item""" return self.get_item(key) def get_item(self, key): """Gets the value of item 'key'. Args: key (str): The item for which you want it's value. Returns: any: The value of item 'key'. Raises: ValueError: If 'key' is not in the config dictionary. Examples: >>> config = Config('test.conf', defaults={'test': 5}) >>> config['test'] 5 """ return self.__config[key] def get(self, key, default=None): """Gets the value of item 'key' if key is in the config, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. Args: key (str): the item for which you want it's value default (any): the default value if key is missing Returns: any: The value of item 'key' or default. Examples: >>> config = Config('test.conf', defaults={'test': 5}) >>> config.get('test', 10) 5 >>> config.get('bad_key', 10) 10 """ try: return self.get_item(key) except KeyError: return default def __delitem__(self, key): """ See :meth:`del_item` """ self.del_item(key) def del_item(self, key): """Deletes item with a specific key from the configuration. Args: key (str): The item which you wish to delete. Raises: ValueError: If 'key' is not in the config dictionary. Examples: >>> config = Config('test.conf', defaults={'test': 5}) >>> del config['test'] """ del self.__config[key] # We set the save_timer for 5 seconds if not already set if not self._save_timer or not self._save_timer.active(): self._save_timer = self.callLater(5, self.save) def register_change_callback(self, callback): """Registers a callback function for any changed value. Will be called when any value is changed in the config dictionary. Args: callback (func): The function to call with parameters: f(key, value). Examples: >>> config = Config('test.conf', defaults={'test': 5}) >>> def cb(key, value): ... print key, value ... >>> config.register_change_callback(cb) """ self.__change_callbacks.append(callback) def register_set_function(self, key, function, apply_now=True): """Register a function to be called when a config value changes. Args: key (str): The item to monitor for change. function (func): The function to call when the value changes, f(key, value). apply_now (bool): If True, the function will be called immediately after it's registered. Examples: >>> config = Config('test.conf', defaults={'test': 5}) >>> def cb(key, value): ... print key, value ... >>> config.register_set_function('test', cb, apply_now=True) test 5 """ log.debug("Registering function for %s key..", key) if key not in self.__set_functions: self.__set_functions[key] = [] self.__set_functions[key].append(function) # Run the function now if apply_now is set if apply_now: function(key, self.__config[key]) def apply_all(self): """Calls all set functions. Examples: >>> config = Config('test.conf', defaults={'test': 5}) >>> def cb(key, value): ... print key, value ... >>> config.register_set_function('test', cb, apply_now=False) >>> config.apply_all() test 5 """ log.debug("Calling all set functions..") for key, value in self.__set_functions.items(): for func in value: func(key, self.__config[key]) def apply_set_functions(self, key): """Calls set functions for `:param:key`. Args: key (str): the config key """ log.debug("Calling set functions for key %s..", key) if key in self.__set_functions: for func in self.__set_functions[key]: func(key, self.__config[key]) def load(self, filename=None): """Load a config file. Args: filename (str): If None, uses filename set in object initialization """ if not filename: filename = self.__config_file try: with open(filename, encoding="utf8") as _file: data = _file.read() except OSError as ex: log.warning("Unable to open config file %s: %s", filename, ex) return objects = find_json_objects(data) if not len(objects): # No json objects found, try depickling it try: self.__config.update(pickle.loads(data)) except Exception as ex: log.exception(ex) log.warning("Unable to load config file: %s", filename) elif len(objects) == 1: start, end = objects[0] try: self.__config.update(json.loads(data[start:end])) except Exception as ex: log.exception(ex) log.warning("Unable to load config file: %s", filename) elif len(objects) == 2: try: start, end = objects[0] self.__version.update(json.loads(data[start:end])) start, end = objects[1] self.__config.update(json.loads(data[start:end])) except Exception as ex: log.exception(ex) log.warning("Unable to load config file: %s", filename) if not log.isEnabledFor(logging.DEBUG): return config = self.__config if self.__log_mask_funcs: config = { key: self.__log_mask_funcs[key](config[key]) if key in self.__log_mask_funcs else config[key] for key in config } log.debug( "Config %s version: %s.%s loaded: %s", filename, self.__version["format"], self.__version["file"], config, ) def save(self, filename=None): """Save configuration to disk. Args: filename (str): If None, uses filename set in object initialization Returns: bool: Whether or not the save succeeded. """ if not filename: filename = self.__config_file # Check to see if the current config differs from the one on disk # We will only write a new config file if there is a difference try: with open(filename, encoding="utf8") as _file: data = _file.read() objects = find_json_objects(data) start, end = objects[0] version = json.loads(data[start:end]) start, end = objects[1] loaded_data = json.loads(data[start:end]) if self.__config == loaded_data and self.__version == version: # The config has not changed so lets just return if self._save_timer and self._save_timer.active(): self._save_timer.cancel() return True except (OSError, IndexError) as ex: log.warning("Unable to open config file: %s because: %s", filename, ex) # Save the new config and make sure it's written to disk try: with NamedTemporaryFile( prefix=os.path.basename(filename) + ".", delete=False ) as _file: filename_tmp = _file.name log.debug("Saving new config file %s", filename_tmp) json.dump(self.__version, getwriter("utf8")(_file), **JSON_FORMAT) json.dump(self.__config, getwriter("utf8")(_file), **JSON_FORMAT) _file.flush() os.fsync(_file.fileno()) except OSError as ex: log.error("Error writing new config file: %s", ex) return False # Resolve symlinked config files before backing up and saving. filename = os.path.realpath(filename) # Make a backup of the old config try: log.debug("Backing up old config file to %s.bak", filename) shutil.move(filename, filename + ".bak") except OSError as ex: log.warning("Unable to backup old config: %s", ex) # The new config file has been written successfully, so let's move it over # the existing one. try: log.debug("Moving new config file %s to %s", filename_tmp, filename) shutil.move(filename_tmp, filename) except OSError as ex: log.error("Error moving new config file: %s", ex) return False else: return True finally: if self._save_timer and self._save_timer.active(): self._save_timer.cancel() def run_converter(self, input_range, output_version, func): """Runs a function that will convert file versions. Args: input_range (tuple): (int, int) The range of input versions this function will accept. output_version (int): The version this function will convert to. func (func): The function that will do the conversion, it will take the config dict as an argument and return the augmented dict. Raises: ValueError: If output_version is less than the input_range. """ if output_version in input_range or output_version <= max(input_range): raise ValueError("output_version needs to be greater than input_range") if self.__version["file"] not in input_range: log.debug( "File version %s is not in input_range %s, ignoring converter function..", self.__version["file"], input_range, ) return try: self.__config = func(self.__config) except Exception as ex: log.exception(ex) log.error( "There was an exception try to convert config file %s %s to %s", self.__config_file, self.__version["file"], output_version, ) raise ex else: self.__version["file"] = output_version self.save() @property def config_file(self): return self.__config_file @property def config(self): """The config dictionary""" return self.__config @config.deleter def config(self): return self.save()
Tools
WinVersion
#! python # -*- coding: utf-8 -*- # (c) 2012 Juergen Riegel LGPL # # Script to create files used in Windows build # uses SubWCRev.py for version detection# import getopt import string import sys import SubWCRev def main(): input = "" output = "." try: opts, args = getopt.getopt(sys.argv[1:], "dso:", ["dir=", "src=", "out="]) except getopt.GetoptError: pass for o, a in opts: if o in ("-d", "--dir"): print("The %s option is deprecated. Ignoring." % (o)) if o in ("-s", "--src"): input = a if o in ("-o", "--out"): output = a git = SubWCRev.GitControl() if git.extractInfo(input, ""): print(git.hash) print(git.branch) print(git.rev[0:4]) print(git.date) print(git.url) print(input) print(output) f = open(input, "r") o = open(output, "w") for line in f.readlines(): line = string.replace(line, "$WCREV$", git.rev[0:4]) line = string.replace(line, "$WCDATE$", git.date) line = string.replace(line, "$WCURL$", git.url) o.write(line) if __name__ == "__main__": main()
extractor
rtl2
# coding: utf-8 from __future__ import unicode_literals import re from ..aes import aes_cbc_decrypt from ..compat import compat_b64decode, compat_ord, compat_str from ..utils import ( ExtractorError, bytes_to_intlist, int_or_none, intlist_to_bytes, strip_or_none, ) from .common import InfoExtractor class RTL2IE(InfoExtractor): IE_NAME = "rtl2" _VALID_URL = r"https?://(?:www\.)?rtl2\.de/sendung/[^/]+/(?:video/(?P<vico_id>\d+)[^/]+/(?P<vivi_id>\d+)-|folge/)(?P<id>[^/?#]+)" _TESTS = [ { "url": "http://www.rtl2.de/sendung/grip-das-motormagazin/folge/folge-203-0", "info_dict": { "id": "folge-203-0", "ext": "f4v", "title": "GRIP sucht den Sommerkönig", "description": "md5:e3adbb940fd3c6e76fa341b8748b562f", }, "params": { # rtmp download "skip_download": True, }, "expected_warnings": [ "Unable to download f4m manifest", "Failed to download m3u8 information", ], }, { "url": "http://www.rtl2.de/sendung/koeln-50667/video/5512-anna/21040-anna-erwischt-alex/", "info_dict": { "id": "anna-erwischt-alex", "ext": "mp4", "title": "Anna erwischt Alex!", "description": "Anna nimmt ihrem Vater nicht ab, dass er nicht spielt. Und tatsächlich erwischt sie ihn auf frischer Tat.", }, "params": { # rtmp download "skip_download": True, }, "expected_warnings": [ "Unable to download f4m manifest", "Failed to download m3u8 information", ], }, ] def _real_extract(self, url): vico_id, vivi_id, display_id = re.match(self._VALID_URL, url).groups() if not vico_id: webpage = self._download_webpage(url, display_id) mobj = re.search( r'data-collection="(?P<vico_id>\d+)"[^>]+data-video="(?P<vivi_id>\d+)"', webpage, ) if mobj: vico_id = mobj.group("vico_id") vivi_id = mobj.group("vivi_id") else: vico_id = self._html_search_regex( r"vico_id\s*:\s*([0-9]+)", webpage, "vico_id" ) vivi_id = self._html_search_regex( r"vivi_id\s*:\s*([0-9]+)", webpage, "vivi_id" ) info = self._download_json( "https://service.rtl2.de/api-player-vipo/video.php", display_id, query={ "vico_id": vico_id, "vivi_id": vivi_id, }, ) video_info = info["video"] title = video_info["titel"] formats = [] rtmp_url = video_info.get("streamurl") if rtmp_url: rtmp_url = rtmp_url.replace("\\", "") stream_url = "mp4:" + self._html_search_regex( r"/ondemand/(.+)", rtmp_url, "stream URL" ) rtmp_conn = [ "S:connect", "O:1", "NS:pageUrl:" + url, "NB:fpad:0", "NN:videoFunction:1", "O:0", ] formats.append( { "format_id": "rtmp", "url": rtmp_url, "play_path": stream_url, "player_url": "https://www.rtl2.de/sites/default/modules/rtl2/jwplayer/jwplayer-7.6.0/jwplayer.flash.swf", "page_url": url, "flash_version": "LNX 11,2,202,429", "rtmp_conn": rtmp_conn, "no_resume": True, "preference": 1, } ) m3u8_url = video_info.get("streamurl_hls") if m3u8_url: formats.extend(self._extract_akamai_formats(m3u8_url, display_id)) self._sort_formats(formats) return { "id": display_id, "title": title, "thumbnail": video_info.get("image"), "description": video_info.get("beschreibung"), "duration": int_or_none(video_info.get("duration")), "formats": formats, } class RTL2YouBaseIE(InfoExtractor): _BACKWERK_BASE_URL = "https://p-you-backwerk.rtl2apps.de/" class RTL2YouIE(RTL2YouBaseIE): IE_NAME = "rtl2:you" _VALID_URL = r"http?://you\.rtl2\.de/(?:video/\d+/|youplayer/index\.html\?.*?\bvid=)(?P<id>\d+)" _TESTS = [ { "url": "http://you.rtl2.de/video/3002/15740/MJUNIK%20%E2%80%93%20Home%20of%20YOU/307-hirn-wo-bist-du", "info_dict": { "id": "15740", "ext": "mp4", "title": "MJUNIK – Home of YOU - #307 Hirn, wo bist du?!", "description": "md5:ddaa95c61b372b12b66e115b2772fe01", "age_limit": 12, }, }, { "url": "http://you.rtl2.de/youplayer/index.html?vid=15712", "only_matching": True, }, ] _AES_KEY = b"\xe9W\xe4.<*\xb8\x1a\xd2\xb6\x92\xf3C\xd3\xefL\x1b\x03*\xbbbH\xc0\x03\xffo\xc2\xf2(\xaa\xaa!" _GEO_COUNTRIES = ["DE"] def _real_extract(self, url): video_id = self._match_id(url) stream_data = self._download_json( self._BACKWERK_BASE_URL + "stream/video/" + video_id, video_id ) data, iv = compat_b64decode(stream_data["streamUrl"]).decode().split(":") stream_url = intlist_to_bytes( aes_cbc_decrypt( bytes_to_intlist(compat_b64decode(data)), bytes_to_intlist(self._AES_KEY), bytes_to_intlist(compat_b64decode(iv)), ) ) if b"rtl2_you_video_not_found" in stream_url: raise ExtractorError("video not found", expected=True) formats = self._extract_m3u8_formats( stream_url[: -compat_ord(stream_url[-1])].decode(), video_id, "mp4", "m3u8_native", ) self._sort_formats(formats) video_data = self._download_json( self._BACKWERK_BASE_URL + "video/" + video_id, video_id ) series = video_data.get("formatTitle") title = episode = video_data.get("title") or series if series and series != title: title = "%s - %s" % (series, title) return { "id": video_id, "title": title, "formats": formats, "description": strip_or_none(video_data.get("description")), "thumbnail": video_data.get("image"), "duration": int_or_none( stream_data.get("duration") or video_data.get("duration"), 1000 ), "series": series, "episode": episode, "age_limit": int_or_none(video_data.get("minimumAge")), } class RTL2YouSeriesIE(RTL2YouBaseIE): IE_NAME = "rtl2:you:series" _VALID_URL = r"http?://you\.rtl2\.de/videos/(?P<id>\d+)" _TEST = { "url": "http://you.rtl2.de/videos/115/dragon-ball", "info_dict": { "id": "115", }, "playlist_mincount": 5, } def _real_extract(self, url): series_id = self._match_id(url) stream_data = self._download_json( self._BACKWERK_BASE_URL + "videos", series_id, query={ "formatId": series_id, "limit": 1000000000, }, ) entries = [] for video in stream_data.get("videos", []): video_id = compat_str(video["videoId"]) if not video_id: continue entries.append( self.url_result( "http://you.rtl2.de/video/%s/%s" % (series_id, video_id), "RTL2You", video_id, ) ) return self.playlist_result(entries, series_id)
covergrid
models
# Copyright 2022 Thomas Leberbauer # 2022 Nick Boultbee # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. from typing import Callable, Optional from gi.repository import Gio, GObject from quodlibet import _, app, util from quodlibet.library.song import SongLibrary from quodlibet.qltk.models import ObjectModelFilter, ObjectModelSort, ObjectStore from quodlibet.util.collection import Album from quodlibet.util.i18n import numeric_phrase from quodlibet.util.library import background_filter class AlbumListItem(GObject.Object): """This model represents an entry for a specific album. It will load the album cover and generate the album label on demand. """ def __init__(self, album: Optional[Album] = None): super().__init__() self._album = album self._cover = None self._label = None self.connect("notify::album", self._album_changed) def load_cover(self, size: int, cancelable: Optional[Gio.Cancellable] = None): def callback(cover): self._cover = cover self.notify("cover") manager = app.cover_manager # Skip this during testing if manager: manager.get_pixbuf_many_async( self._album.songs, size, size, cancelable, callback ) def format_label(self, pattern): self._label = pattern % self._album self.notify("label") def _album_changed(self, model, prop): self._label = None @GObject.Property def album(self): return self._album @GObject.Property def cover(self): return self._cover @GObject.Property def label(self): return self._label class AlbumListCountItem(AlbumListItem): """This model represents an entry for a set of albums. It will generate a label containing the number of albums on demand. """ def load_cover(self, *args, **kwargs): self.notify("cover") def format_label(self, pattern=None): n = self.__n_albums title = util.bold(_("All Albums")) number_phrase = numeric_phrase("%d album", "%d albums", n) self._label = f"{title}\n{number_phrase}" self.notify("label") @GObject.Property def n_albums(self): return self.__n_albums @n_albums.setter # type: ignore def n_albums(self, value): self.__n_albums = value self.format_label() class AlbumListModel(ObjectStore): """This model creates entries for albums from a library. The first entry represents the whole set of albums in the library. """ def __init__(self, library: SongLibrary): super().__init__() self.__library = library albums = library.albums self.__sigs = [ albums.connect("added", self._add_albums), albums.connect("removed", self._remove_albums), albums.connect("changed", self._change_albums), ] self.append(row=[AlbumListCountItem()]) self.append_many(AlbumListItem(a) for a in albums.values()) def destroy(self): albums = self.__library.albums for sig in self.__sigs: albums.disconnect(sig) self.__library = None self.clear() def _add_albums(self, library, added): self.append_many(AlbumListItem(a) for a in added) def _remove_albums(self, library, removed): removed_albums = removed.copy() iters_remove = [] for iter_, item in self.iterrows(): album = item.album if album is not None and album in removed_albums: removed_albums.remove(album) iters_remove.append(iter_) if not removed_albums: break for iter_ in iters_remove: self.remove(iter_) def _change_albums(self, library, changed): changed_albums = changed.copy() for iter_, item in self.iterrows(): album = item.album if album is not None and album in changed_albums: changed_albums.remove(album) self.iter_changed(iter_) if not changed_albums: break class AlbumListFilterModel(GObject.Object, Gio.ListModel): """This model filters entries in a child model. The property "include_item_all" toggles visibility of the first entry of the child model. The property "filter" is a function which defines visibility for all remaining entries of the child model. If "filter" is set to None, all entries are visible. """ __item_all: AlbumListItem __include_item_all: bool __filter: Optional[Callable[[AlbumListItem], bool]] = None def __init__(self, child_model=None, include_item_all=True, **kwargs): super().__init__(**kwargs) self.__include_item_all = include_item_all self._model = model = ObjectModelFilter(child_model=child_model) self.__item_all = self._get_item(0) self._update_n_albums() # Tell the tree model that all nodes are visible, otherwise it does not # emit the "row-changed" signal. for row in model: model.ref_node(row.iter) model.set_visible_func(self._apply_filter) self.__sigs = [ model.connect("row-changed", self._row_changed), model.connect("row-inserted", self._row_inserted), model.connect("row-deleted", self._row_deleted), model.connect("rows-reordered", self._rows_reordered), ] def destroy(self): model = self._model for sig in self.__sigs: model.disconnect(sig) self._model = None @GObject.Property def include_item_all(self): return self.__include_item_all @include_item_all.setter # type: ignore def include_item_all(self, value): if self.__include_item_all == value: return self.__include_item_all = value removed, added = (0, 1) if value else (1, 0) self.items_changed(0, removed, added) @GObject.Property def filter(self): return self.__filter @filter.setter # type: ignore def filter(self, value): b = background_filter() if b is None and value is None: f = None elif b is None: f = lambda item: value(item.album) else: f = lambda item: b(item.album) and value(item.album) if f or self.__filter: self.__filter = f self._model.refilter() def do_get_n_items(self): return len(self) def do_get_item(self, index): return self[index] def do_get_item_type(self): return AlbumListItem def __len__(self): n = len(self._model) if self.__include_item_all or n < 1: return n return n - 1 def __getitem__(self, index): if not self.__include_item_all: index += 1 return self._get_item(index) def _get_item(self, index: int) -> Optional[AlbumListItem]: model = self._model iter = model.iter_nth_child(None, index) return model.get_value(iter) if iter else None def _update_n_albums(self): self.__item_all.props.n_albums = len(self._model) - 1 def _apply_filter(self, model, iter, _): filter = self.__filter if filter is None: return True item = model.get_value(iter) if item is self.__item_all: return True return filter(item) def _row_changed(self, model, path, iter): item = model.get_value(iter) item.notify("album") def _row_inserted(self, model, path, iter): # Ensure that the tree model will emit the "row-changed" signal model.ref_node(iter) index = path.get_indices()[0] if not self.__include_item_all: index -= 1 if index >= 0: self.items_changed(index, 0, 1) self._update_n_albums() def _row_deleted(self, model, path): index = path.get_indices()[0] if not self.__include_item_all: index -= 1 if index >= 0: self.items_changed(index, 1, 0) self._update_n_albums() def _rows_reordered(self, model, path, iter, new_order): n = len(self) self.items_changed(0, n, n) class AlbumListSortModel(ObjectModelSort): """This model sorts entries of a child model""" pass
femobjects
constraint_electrostaticpotential
# *************************************************************************** # * Copyright (c) 2017 Markus Hovorka <m.hovorka@live.de> * # * Copyright (c) 2020 Bernd Hahnebach <bernd@bimstatik.org> * # * Copyright (c) 2023 Uwe Stöhr <uwestoehr@lyx.org> * # * * # * This file is part of the FreeCAD CAx development system. * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** __title__ = "FreeCAD FEM constraint electrostatic potential document object" __author__ = "Markus Hovorka, Bernd Hahnebach, Uwe Stöhr" __url__ = "https://www.freecad.org" ## @package constraint_electrostaticpotential # \ingroup FEM # \brief constraint electrostatic potential object from . import base_fempythonobject class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject): Type = "Fem::ConstraintElectrostaticPotential" def __init__(self, obj): super(ConstraintElectrostaticPotential, self).__init__(obj) self.add_properties(obj) def onDocumentRestored(self, obj): self.add_properties(obj) def add_properties(self, obj): if not hasattr(obj, "Potential"): obj.addProperty( "App::PropertyElectricPotential", "Potential", "Parameter", "Electric Potential", ) # setting 1 V assures that the unit does not switch to mV # and the constraint holds usually Volts obj.Potential = "1 V" if not hasattr(obj, "AV_re_1"): obj.addProperty( "App::PropertyElectricPotential", "AV_re_1", "Vector Potential", "Real part of potential x-component", ) obj.AV_re_1 = "0 V" if not hasattr(obj, "AV_re_2"): obj.addProperty( "App::PropertyElectricPotential", "AV_re_2", "Vector Potential", "Real part of potential y-component", ) obj.AV_re_2 = "0 V" if not hasattr(obj, "AV_re_3"): obj.addProperty( "App::PropertyElectricPotential", "AV_re_3", "Vector Potential", "Real part of potential z-component", ) obj.AV_re_3 = "0 V" if not hasattr(obj, "AV_im"): obj.addProperty( "App::PropertyElectricPotential", "AV_im", "Vector Potential", "Imaginary part of scalar potential", ) obj.AV_im = "0 V" if not hasattr(obj, "AV_im_1"): obj.addProperty( "App::PropertyElectricPotential", "AV_im_1", "Vector Potential", "Imaginary part of potential x-component", ) obj.AV_im_1 = "0 V" if not hasattr(obj, "AV_im_2"): obj.addProperty( "App::PropertyElectricPotential", "AV_im_2", "Vector Potential", "Imaginary part of potential y-component", ) obj.AV_im_2 = "0 V" if not hasattr(obj, "AV_im_3"): obj.addProperty( "App::PropertyElectricPotential", "AV_im_3", "Vector Potential", "Imaginary part of potential z-component", ) obj.AV_im_3 = "0 V" # now the enable bools if not hasattr(obj, "PotentialEnabled"): obj.addProperty( "App::PropertyBool", "PotentialEnabled", "Parameter", "Potential Enabled", ) obj.PotentialEnabled = True if not hasattr(obj, "AV_re_1_Disabled"): obj.addProperty( "App::PropertyBool", "AV_re_1_Disabled", "Vector Potential", "" ) obj.AV_re_1_Disabled = True if not hasattr(obj, "AV_re_2_Disabled"): obj.addProperty( "App::PropertyBool", "AV_re_2_Disabled", "Vector Potential", "" ) obj.AV_re_2_Disabled = True if not hasattr(obj, "AV_re_3_Disabled"): obj.addProperty( "App::PropertyBool", "AV_re_3_Disabled", "Vector Potential", "" ) obj.AV_re_3_Disabled = True if not hasattr(obj, "AV_im_Disabled"): obj.addProperty( "App::PropertyBool", "AV_im_Disabled", "Vector Potential", "" ) obj.AV_im_Disabled = True if not hasattr(obj, "AV_im_1_Disabled"): obj.addProperty( "App::PropertyBool", "AV_im_1_Disabled", "Vector Potential", "" ) obj.AV_im_1_Disabled = True if not hasattr(obj, "AV_im_2_Disabled"): obj.addProperty( "App::PropertyBool", "AV_im_2_Disabled", "Vector Potential", "" ) obj.AV_im_2_Disabled = True if not hasattr(obj, "AV_im_3_Disabled"): obj.addProperty( "App::PropertyBool", "AV_im_3_Disabled", "Vector Potential", "" ) obj.AV_im_3_Disabled = True if not hasattr(obj, "PotentialConstant"): obj.addProperty( "App::PropertyBool", "PotentialConstant", "Parameter", "Potential Constant", ) obj.PotentialConstant = False if not hasattr(obj, "ElectricInfinity"): obj.addProperty( "App::PropertyBool", "ElectricInfinity", "Parameter", "Electric Infinity", ) obj.ElectricInfinity = False if not hasattr(obj, "ElectricForcecalculation"): obj.addProperty( "App::PropertyBool", "ElectricForcecalculation", "Parameter", "Electric Force Calculation", ) obj.ElectricForcecalculation = False if not hasattr(obj, "CapacitanceBody"): obj.addProperty( "App::PropertyInteger", "CapacitanceBody", "Parameter", "Capacitance Body", ) obj.CapacitanceBody = 0 if not hasattr(obj, "CapacitanceBodyEnabled"): obj.addProperty( "App::PropertyBool", "CapacitanceBodyEnabled", "Parameter", "Capacitance Body Enabled", ) obj.CapacitanceBodyEnabled = False
beetsplug
keyfinder
# This file is part of beets. # Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. """Uses the `KeyFinder` program to add the `initial_key` field. """ import os.path import subprocess from beets import ui, util from beets.plugins import BeetsPlugin class KeyFinderPlugin(BeetsPlugin): def __init__(self): super().__init__() self.config.add( { "bin": "KeyFinder", "auto": True, "overwrite": False, } ) if self.config["auto"].get(bool): self.import_stages = [self.imported] def commands(self): cmd = ui.Subcommand("keyfinder", help="detect and add initial key from audio") cmd.func = self.command return [cmd] def command(self, lib, opts, args): self.find_key(lib.items(ui.decargs(args)), write=ui.should_write()) def imported(self, session, task): self.find_key(task.imported_items()) def find_key(self, items, write=False): overwrite = self.config["overwrite"].get(bool) command = [self.config["bin"].as_str()] # The KeyFinder GUI program needs the -f flag before the path. # keyfinder-cli is similar, but just wants the path with no flag. if "keyfinder-cli" not in os.path.basename(command[0]).lower(): command.append("-f") for item in items: if item["initial_key"] and not overwrite: continue try: output = util.command_output(command + [util.syspath(item.path)]).stdout except (subprocess.CalledProcessError, OSError) as exc: self._log.error("execution failed: {0}", exc) continue try: key_raw = output.rsplit(None, 1)[-1] except IndexError: # Sometimes keyfinder-cli returns 0 but with no key, usually # when the file is silent or corrupt, so we log and skip. self._log.error("no key returned for path: {0}", item.path) continue try: key = key_raw.decode("utf-8") except UnicodeDecodeError: self._log.error("output is invalid UTF-8") continue item["initial_key"] = key self._log.info( "added computed initial key {0} for {1}", key, util.displayable_path(item.path), ) if write: item.try_write() item.store()
neubot
config
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2011 Simone Basso <bassosimone@gmail.com>, # NEXA Center for Internet & Society at Politecnico di Torino # # This file is part of Neubot <http://www.neubot.org/>. # # Neubot is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Neubot is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Neubot. If not, see <http://www.gnu.org/licenses/>. # """ Regression tests for neubot/config.py """ import sys import unittest if __name__ == "__main__": sys.path.insert(0, ".") from neubot import config # # pylint: disable=R0904 # class TestStringToKv(unittest.TestCase): """Test string_to_kv behavior""" def test_string_to_kv(self): """Check string_to_kv behavior""" self.assertEquals(config.string_to_kv(" "), ()) self.assertEquals(config.string_to_kv("# a"), ()) self.assertEquals(config.string_to_kv("\r\n"), ()) self.assertEquals(config.string_to_kv("foo"), ("foo", "True")) self.assertEquals(config.string_to_kv("foo=bar"), ("foo", "bar")) class TestKvToString(unittest.TestCase): """Test kv_to_string behavior""" def test_kv_to_string(self): """Check kv_to_string behavior""" self.assertEquals(config.kv_to_string(("a", "b")), "a=b\n") self.assertEquals(config.kv_to_string((3, 7)), "3=7\n") self.assertEquals(config.kv_to_string(("èèè", "a")), "èèè=a\n") self.assertEquals(config.kv_to_string((3, 7.333)), "3=7.333\n") class TestConfigDict(unittest.TestCase): """Tests ConfigDict behavior""" def test_basics(self): """Test some basic properties of ConfigDict""" dictionary = config.ConfigDict() self.assertTrue(isinstance(dictionary, dict)) self.assertTrue(hasattr(dictionary, "__setitem__")) self.assertTrue(hasattr(dictionary, "update")) def test_assignment(self): """Make sure all ways to assign to ConfigDict are equivalent""" dict1 = config.ConfigDict() for key, value in [("a", 1), ("b", 2), ("c", 3)]: dict1[key] = value dict2 = config.ConfigDict({"a": 1, "b": 2, "c": 3}) dict3 = config.ConfigDict() dict3.update([("a", 1), ("b", 2), ("c", 3)]) dict4 = config.ConfigDict() dict4.update(a=1, b=2, c=3) self.assertTrue(dict1 == dict2 == dict3 == dict4) class TestCONFIG(unittest.TestCase): """Test the behavior of the CONFIG global object""" def test_config_global_object(self): """Check CONFIG global object behavior""" config.CONFIG.register_defaults( { "default_value": "default", "from_database": False, "from_cmdline": False, "from_environ": False, } ) self.assertEquals(config.CONFIG.get("XO", 7), 7) self.assertFalse(config.CONFIG.get("from_database", True)) if __name__ == "__main__": unittest.main()
graphs
feeding_amounts
# -*- coding: utf-8 -*- import plotly.graph_objs as go import plotly.offline as plotly from core import models from django.utils import timezone from django.utils.translation import gettext as _ from reports import utils def feeding_amounts(instances): """ Create a graph showing daily feeding amounts over time. :param instances: a QuerySet of Feeding instances. :returns: a tuple of the the graph's html and javascript. """ feeding_types, feeding_types_desc = map( list, zip(*models.Feeding._meta.get_field("type").choices) ) total_idx = len(feeding_types) + 1 # +1 for aggregate total totals_list = list() for i in range(total_idx): totals_list.append({}) for instance in instances: end = timezone.localtime(instance.end) date = end.date() if date not in totals_list[total_idx - 1].keys(): for item in totals_list: item[date] = 0 feeding_idx = feeding_types.index(instance.type) totals_list[feeding_idx][date] += instance.amount or 0 totals_list[total_idx - 1][date] += instance.amount or 0 zeros = [0 for a in totals_list[total_idx - 1].values()] # sum each feeding type for graph amounts_array = [] for i in range(total_idx): amounts_array.append([round(a, 2) for a in totals_list[i].values()]) traces = [] for i in range(total_idx - 1): for x in amounts_array[i]: if x != 0: # Only include if it has non zero values traces.append( go.Bar( name=str(feeding_types_desc[i]), x=list(totals_list[total_idx - 1].keys()), y=amounts_array[i], text=amounts_array[i], hovertemplate=str(feeding_types_desc[i]), ) ) break traces.append( go.Bar( name=_("Total"), x=list(totals_list[total_idx - 1].keys()), y=zeros, hoverinfo="text", textposition="outside", text=amounts_array[total_idx - 1], showlegend=False, ) ) layout_args = utils.default_graph_layout_options() layout_args["title"] = _("<b>Total Feeding Amount by Type</b>") layout_args["xaxis"]["title"] = _("Date") layout_args["xaxis"]["rangeselector"] = utils.rangeselector_date() layout_args["yaxis"]["title"] = _("Feeding amount") fig = go.Figure({"data": traces, "layout": go.Layout(**layout_args)}) fig.update_layout(barmode="stack") output = plotly.plot(fig, output_type="div", include_plotlyjs=False) return utils.split_graph_output(output)
femtools
checksanalysis
# *************************************************************************** # * Copyright (c) 2020 Przemo Firszt <przemo@firszt.eu> * # * Copyright (c) 2020 Bernd Hahnebach <bernd@bimstatik.org> * # * * # * This file is part of the FreeCAD CAx development system. * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** __title__ = "Analysis Checks" __author__ = "Przemo Firszt, Bernd Hahnebach" __url__ = "https://www.freecad.org" ## \addtogroup FEM # @{ import FreeCAD from femsolver.calculix.solver import ANALYSIS_TYPES from FreeCAD import Units from . import femutils def check_member_for_solver_calculix(analysis, solver, mesh, member): message = "" # solver if solver.AnalysisType not in ANALYSIS_TYPES: message += "Unknown analysis type: {}\n".format(solver.AnalysisType) if solver.AnalysisType == "frequency": if not hasattr(solver, "EigenmodeHighLimit"): message += "Frequency analysis: Solver has no EigenmodeHighLimit.\n" elif not hasattr(solver, "EigenmodeLowLimit"): message += "Frequency analysis: Solver has no EigenmodeLowLimit.\n" elif not hasattr(solver, "EigenmodesCount"): message += "Frequency analysis: Solver has no EigenmodesCount.\n" if ( hasattr(solver, "MaterialNonlinearity") and solver.MaterialNonlinearity == "nonlinear" ): if not member.mats_nonlinear: message += ( "Solver is set to nonlinear materials, " "but there is no nonlinear material in the analysis.\n" ) if ( solver.Proxy.Type == "Fem::SolverCcxTools" and solver.GeometricalNonlinearity != "nonlinear" ): # nonlinear geometry --> should be set # https://forum.freecad.org/viewtopic.php?f=18&t=23101&p=180489#p180489 message += ( "Solver CalculiX triggers nonlinear geometry for nonlinear material, " "thus it should to be set too.\n" ) # mesh if not mesh: message += "No mesh object defined in the analysis.\n" if mesh: if ( mesh.FemMesh.VolumeCount == 0 and mesh.FemMesh.FaceCount > 0 and not member.geos_shellthickness ): message += ( "FEM mesh has no volume elements, " "either define a shell thicknesses or " "provide a FEM mesh with volume elements.\n" ) if ( mesh.FemMesh.VolumeCount == 0 and mesh.FemMesh.FaceCount == 0 and mesh.FemMesh.EdgeCount > 0 and not member.geos_beamsection and not member.geos_fluidsection ): message += ( "FEM mesh has no volume and no shell elements, " "either define a beam/fluid section or provide " "a FEM mesh with volume elements.\n" ) if ( mesh.FemMesh.VolumeCount == 0 and mesh.FemMesh.FaceCount == 0 and mesh.FemMesh.EdgeCount == 0 ): message += ( "FEM mesh has neither volume nor shell or edge elements. " "Provide a FEM mesh with elements.\n" ) # material linear and nonlinear if not member.mats_linear: message += "No material object defined in the analysis.\n" has_no_references = False for m in member.mats_linear: if len(m["Object"].References) == 0: if has_no_references is True: message += ( "More than one material has an empty references list " "(Only one empty references list is allowed!).\n" ) has_no_references = True mat_ref_shty = "" for m in member.mats_linear: ref_shty = femutils.get_refshape_type(m["Object"]) if not mat_ref_shty: mat_ref_shty = ref_shty if mat_ref_shty and ref_shty and ref_shty != mat_ref_shty: # mat_ref_shty could be empty in one material # only the not empty ones should have the same shape type message += ( "Some material objects do not have the same reference shape type " "(all material objects must have the same reference shape type, " "at the moment).\n" ) for m in member.mats_linear: mat_map = m["Object"].Material mat_obj = m["Object"] if mat_obj.Category == "Solid": if "YoungsModulus" in mat_map: # print(Units.Quantity(mat_map["YoungsModulus"]).Value) if not Units.Quantity(mat_map["YoungsModulus"]).Value: message += "Value of YoungsModulus is set to 0.0.\n" else: message += "No YoungsModulus defined for at least one material.\n" if "PoissonRatio" not in mat_map: # PoissonRatio is allowed to be 0.0 (in ccx), but it should be set anyway. message += "No PoissonRatio defined for at least one material.\n" if solver.AnalysisType == "frequency" or member.cons_selfweight: if "Density" not in mat_map: message += "No Density defined for at least one material.\n" if solver.AnalysisType == "thermomech": if "ThermalConductivity" in mat_map: if not Units.Quantity(mat_map["ThermalConductivity"]).Value: message += "Value of ThermalConductivity is set to 0.0.\n" else: message += ( "Thermomechanical analysis: No ThermalConductivity defined " "for at least one material.\n" ) if ( "ThermalExpansionCoefficient" not in mat_map and mat_obj.Category == "Solid" ): message += ( "Thermomechanical analysis: No ThermalExpansionCoefficient defined " "for at least one material.\n" # allowed to be 0.0 (in ccx) ) if "SpecificHeat" not in mat_map: message += ( "Thermomechanical analysis: No SpecificHeat " "defined for at least one material.\n" # allowed to be 0.0 (in ccx) ) if femutils.is_of_type(mat_obj, "Fem::MaterialReinforced"): # additional tests for reinforced materials, # they are needed for result calculation not for ccx analysis mat_map_m = mat_obj.Material if "AngleOfFriction" in mat_map_m: # print(Units.Quantity(mat_map_m["AngleOfFriction"]).Value) if not Units.Quantity(mat_map_m["AngleOfFriction"]).Value: message += ( "Value of AngleOfFriction is set to 0.0 " "for the matrix of a reinforced material.\n" ) else: message += ( "No AngleOfFriction defined for the matrix " "of at least one reinforced material.\n" ) if "CompressiveStrength" in mat_map_m: # print(Units.Quantity(mat_map_m["CompressiveStrength"]).Value) if not Units.Quantity(mat_map_m["CompressiveStrength"]).Value: message += ( "Value of CompressiveStrength is set to 0.0 " "for the matrix of a reinforced material.\n" ) else: message += ( "No CompressiveStrength defined for the matrinx " "of at least one reinforced material.\n" ) mat_map_r = mat_obj.Reinforcement if "YieldStrength" in mat_map_r: # print(Units.Quantity(mat_map_r["YieldStrength"]).Value) if not Units.Quantity(mat_map_r["YieldStrength"]).Value: message += ( "Value of YieldStrength is set to 0.0 " "for the reinforcement of a reinforced material.\n" ) else: message += ( "No YieldStrength defined for the reinforcement " "of at least one reinforced material.\n" ) if len(member.mats_linear) == 1: mobj = member.mats_linear[0]["Object"] if hasattr(mobj, "References") and mobj.References: FreeCAD.Console.PrintError( "Only one material object, but this one has a reference shape. " "The reference shape will be ignored.\n" ) for m in member.mats_linear: has_nonlinear_material = False for nlm in member.mats_nonlinear: if nlm["Object"].LinearBaseMaterial == m["Object"]: if has_nonlinear_material is False: has_nonlinear_material = True else: message += ( "At least two nonlinear materials use the same linear base material. " "Only one nonlinear material for each linear material allowed.\n" ) # which analysis needs which constraints # no check in the regard of loads existence (constraint force, pressure, self weight) # is done, because an analysis without loads at all is an valid analysis too if solver.AnalysisType == "static": if not (member.cons_fixed or member.cons_displacement): message += ( "Static analysis: Neither constraint fixed nor " "constraint displacement defined.\n" ) if solver.AnalysisType == "thermomech": if not member.cons_initialtemperature: if not member.geos_fluidsection: message += ( "Thermomechanical analysis: No initial temperature defined.\n" ) if len(member.cons_initialtemperature) > 1: message += ( "Thermomechanical analysis: Only one initial temperature is allowed.\n" ) # constraints # fixed if member.cons_fixed: for c in member.cons_fixed: if len(c["Object"].References) == 0: message += "{} has empty references.".format(c["Object"].Name) # displacement if member.cons_displacement: for di in member.cons_displacement: if len(di["Object"].References) == 0: message += "{} has empty references.".format(c["Object"].Name) # plane rotation if member.cons_planerotation: for c in member.cons_planerotation: if len(c["Object"].References) == 0: message += "{} has empty references.".format(c["Object"].Name) # contact if member.cons_contact: for c in member.cons_contact: if len(c["Object"].References) == 0: message += "{} has empty references.".format(c["Object"].Name) # tie if member.cons_tie: for c in member.cons_tie: items = 0 for reference in c["Object"].References: items += len(reference[1]) if items != 2: message += "{} doesn't references exactly two needed faces.\n".format( c["Object"].Name ) # sectionprint if member.cons_sectionprint: for c in member.cons_sectionprint: items = 0 for reference in c["Object"].References: items += len(reference[1]) if items != 1: message += "{} doesn't reference exactly one needed face.\n".format( c["Object"].Name ) # transform if member.cons_transform: for c in member.cons_transform: if len(c["Object"].References) == 0: message += "{} has empty references.".format(c["Object"].Name) # pressure if member.cons_pressure: for c in member.cons_pressure: if len(c["Object"].References) == 0: message += "{} has empty references.".format(c["Object"].Name) # force if member.cons_force: for c in member.cons_force: if len(c["Object"].References) == 0: message += "{} has empty references.".format(c["Object"].Name) # temperature if member.cons_temperature: for c in member.cons_temperature: if len(c["Object"].References) == 0: message += "{} has empty references.".format(c["Object"].Name) # heat flux if member.cons_heatflux: for c in member.cons_heatflux: if len(c["Object"].References) == 0: message += "{} has empty references.".format(c["Object"].Name) # geometries # beam section if member.geos_beamsection: if member.geos_shellthickness: # this needs to be checked only once either here or in shell_thicknesses message += ( "Beam sections and shell thicknesses in one analysis " "is not supported at the moment.\n" ) if member.geos_fluidsection: # this needs to be checked only once either here or in shell_thicknesses message += ( "Beam sections and fluid sections in one analysis " "is not supported at the moment.\n" ) has_no_references = False for b in member.geos_beamsection: if len(b["Object"].References) == 0: if has_no_references is True: message += ( "More than one beam section has an empty references " "list (Only one empty references list is allowed!).\n" ) has_no_references = True if mesh: if mesh.FemMesh.FaceCount > 0 or mesh.FemMesh.VolumeCount > 0: message += ( "Beam sections defined but FEM mesh has volume or shell elements.\n" ) if mesh.FemMesh.EdgeCount == 0: message += "Beam sections defined but FEM mesh has no edge elements.\n" if not (hasattr(mesh, "Shape") or hasattr(mesh, "Part")): message += ( "Mesh without geometry link. " "The mesh needs to know its geometry for the beam rotations.\n" ) if len(member.geos_beamrotation) > 1: message += "Multiple beam rotations in one analysis are not supported at the moment.\n" # beam rotations if member.geos_beamrotation and not member.geos_beamsection: message += "Beam rotations in the analysis but no beam sections defined.\n" # shell thickness if member.geos_shellthickness: has_no_references = False for s in member.geos_shellthickness: if len(s["Object"].References) == 0: if has_no_references is True: message += ( "More than one shell thickness has an empty references " "list (Only one empty references list is allowed!).\n" ) has_no_references = True if mesh: if mesh.FemMesh.VolumeCount > 0: message += ( "Shell thicknesses defined but FEM mesh has volume elements.\n" ) if mesh.FemMesh.FaceCount == 0: message += ( "Shell thicknesses defined but FEM mesh has no shell elements.\n" ) # fluid section if member.geos_fluidsection: if not member.cons_selfweight: message += "A fluid network analysis requires self weight constraint to be applied\n" if solver.AnalysisType != "thermomech": message += ( "A fluid network analysis can only be done in a thermomech analysis\n" ) has_no_references = False for f in member.geos_fluidsection: if len(f["Object"].References) == 0: if has_no_references is True: message += ( "More than one fluid section has an empty references list " "(Only one empty references list is allowed!).\n" ) has_no_references = True if mesh: if mesh.FemMesh.FaceCount > 0 or mesh.FemMesh.VolumeCount > 0: message += "Fluid sections defined but FEM mesh has volume or shell elements.\n" if mesh.FemMesh.EdgeCount == 0: message += "Fluid sections defined but FEM mesh has no edge elements.\n" return message ## @}
draftmake
make_pointarray
# *************************************************************************** # * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> * # * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> * # * Copyright (c) 2018 Benjamin Alterauge (ageeye) * # * Copyright (c) 2020 Carlo Pavan <carlopav@gmail.com> * # * Copyright (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> * # * * # * This file is part of the FreeCAD CAx development system. * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** """Provides functions to create PointArray objects. The copies will be created at the points of a point object. """ ## @package make_pointarray # \ingroup draftmake # \brief Provides functions to create PointArray objects. import draftutils.gui_utils as gui_utils import draftutils.utils as utils ## \addtogroup draftmake # @{ import FreeCAD as App from draftobjects.pointarray import PointArray from draftutils.messages import _err, _msg from draftutils.translate import translate if App.GuiUp: from draftutils.todo import ToDo from draftviewproviders.view_array import ViewProviderDraftArray from draftviewproviders.view_draftlink import ViewProviderDraftLink def make_point_array(base_object, point_object, extra=None, use_link=True): """Make a Draft PointArray object. Create copies of a `base_object` at the points defined by a `point_object`. Parameters ---------- base_object: Part::Feature or str Any of object that has a `Part::TopoShape` that can be duplicated. This means most 2D and 3D objects produced with any workbench. If it is a string, it must be the `Label` of that object. Since a label is not guaranteed to be unique in a document, it will use the first object found with this label. point_object: Part::Feature, Sketcher::SketchObject, Mesh::Feature, Points::FeatureCustom or str The object must have vertices and/or points. extra: Base::Placement, Base::Vector3, or Base::Rotation, optional It defaults to `None`. If it is provided, it is an additional placement that is applied to each copy of the array. The input could be a full placement, just a vector indicating the additional translation, or just a rotation. Returns ------- Part::FeaturePython A scripted object of type `'PointArray'`. Its `Shape` is a compound of the copies of the original object. None If there is a problem it will return `None`. """ _name = "make_point_array" utils.print_header(_name, "Point array") found, doc = utils.find_doc(App.activeDocument()) if not found: _err(translate("draft", "No active document. Aborting.")) return None if isinstance(base_object, str): base_object_str = base_object found, base_object = utils.find_object(base_object, doc) if not found: _msg("base_object: {}".format(base_object_str)) _err(translate("draft", "Wrong input: object not in document.")) return None _msg("base_object: {}".format(base_object.Label)) if isinstance(point_object, str): point_object_str = point_object found, point_object = utils.find_object(point_object, doc) if not found: _msg("point_object: {}".format(point_object_str)) _err(translate("draft", "Wrong input: object not in document.")) return None _msg("point_object: {}".format(point_object.Label)) if not ( (hasattr(point_object, "Shape") and hasattr(point_object.Shape, "Vertexes")) or hasattr(point_object, "Mesh") or hasattr(point_object, "Points") ): _err(translate("draft", "Wrong input: object has the wrong type.")) return None _msg("extra: {}".format(extra)) if not extra: extra = App.Placement() try: utils.type_check( [(extra, (App.Placement, App.Vector, App.Rotation))], name=_name ) except TypeError: _err( translate( "draft", "Wrong input: must be a placement, a vector, or a rotation." ) ) return None # Convert the vector or rotation to a full placement if isinstance(extra, App.Vector): extra = App.Placement(extra, App.Rotation()) elif isinstance(extra, App.Rotation): extra = App.Placement(App.Vector(), extra) if use_link: # The PointArray class must be called in this special way # to make it a LinkArray new_obj = doc.addObject( "Part::FeaturePython", "PointArray", PointArray(None), None, True ) else: new_obj = doc.addObject("Part::FeaturePython", "PointArray") PointArray(new_obj) new_obj.Base = base_object new_obj.PointObject = point_object new_obj.ExtraPlacement = extra if App.GuiUp: if use_link: ViewProviderDraftLink(new_obj.ViewObject) else: new_obj.Proxy.execute( new_obj ) # Updates Count which is required for correct DiffuseColor. ViewProviderDraftArray(new_obj.ViewObject) gui_utils.format_object(new_obj, new_obj.Base) new_obj.ViewObject.Proxy.resetColors(new_obj.ViewObject) # Workaround to trigger update of DiffuseColor: ToDo.delay(reapply_diffuse_color, new_obj.ViewObject) new_obj.Base.ViewObject.hide() gui_utils.select(new_obj) return new_obj def makePointArray(base, ptlst): """Create PointArray. DEPRECATED. Use 'make_point_array'.""" utils.use_instead("make_point_array") return make_point_array(base, ptlst) def reapply_diffuse_color(vobj): try: vobj.DiffuseColor = vobj.DiffuseColor except: pass ## @}
LegacyProfileReader
LegacyProfileReader
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. import configparser # For reading the legacy profile INI files. import io import json # For reading the Dictionary of Doom. import math # For mathematical operations included in the Dictionary of Doom. import os.path # For concatenating the path to the plugin and the relative path to the Dictionary of Doom. from typing import Dict from cura.ReaderWriters.ProfileReader import ( ProfileReader, ) # The plug-in type to implement. from UM.Application import ( Application, ) # To get the machine manager to create the new profile in. from UM.Logger import Logger # Logging errors. from UM.PluginRegistry import ( PluginRegistry, ) # For getting the path to this plugin's directory. from UM.Settings.ContainerRegistry import ( ContainerRegistry, ) # To create unique profile IDs. from UM.Settings.InstanceContainer import InstanceContainer # The new profile to make. class LegacyProfileReader(ProfileReader): """A plugin that reads profile data from legacy Cura versions. It reads a profile from an .ini file, and performs some translations on it. Not all translations are correct, mind you, but it is a best effort. """ def __init__(self): """Initialises the legacy profile reader. This does nothing since the only other function is basically stateless. """ super().__init__() def prepareDefaults(self, json: Dict[str, Dict[str, str]]) -> Dict[str, str]: """Prepares the default values of all legacy settings. These are loaded from the Dictionary of Doom. :param json: The JSON file to load the default setting values from. This should not be a URL but a pre-loaded JSON handle. :return: A dictionary of the default values of the legacy Cura version. """ defaults = {} if "defaults" in json: for key in json[ "defaults" ]: # We have to copy over all defaults from the JSON handle to a normal dict. defaults[key] = json["defaults"][key] return defaults def prepareLocals(self, config_parser, config_section, defaults): """Prepares the local variables that can be used in evaluation of computing new setting values from the old ones. This fills a dictionary with all settings from the legacy Cura version and their values, so that they can be used in evaluating the new setting values as Python code. :param config_parser: The ConfigParser that finds the settings in the legacy profile. :param config_section: The section in the profile where the settings should be found. :param defaults: The default values for all settings in the legacy Cura. :return: A set of local variables, one for each setting in the legacy profile. """ copied_locals = defaults.copy() # Don't edit the original! for option in config_parser.options(config_section): copied_locals[option] = config_parser.get(config_section, option) return copied_locals def read(self, file_name): """Reads a legacy Cura profile from a file and returns it. :param file_name: The file to read the legacy Cura profile from. :return: The legacy Cura profile that was in the file, if any. If the file could not be read or didn't contain a valid profile, None is returned. """ if file_name.split(".")[-1] != "ini": return None global_container_stack = Application.getInstance().getGlobalContainerStack() if not global_container_stack: return None multi_extrusion = ( global_container_stack.getProperty("machine_extruder_count", "value") > 1 ) if multi_extrusion: Logger.log( "e", "Unable to import legacy profile %s. Multi extrusion is not supported", file_name, ) raise Exception( "Unable to import legacy profile. Multi extrusion is not supported" ) Logger.log("i", "Importing legacy profile from file " + file_name + ".") container_registry = ContainerRegistry.getInstance() profile_id = container_registry.uniqueName("Imported Legacy Profile") input_parser = configparser.ConfigParser(interpolation=None) try: input_parser.read([file_name]) # Parse the INI file. except Exception as e: Logger.log("e", "Unable to open legacy profile %s: %s", file_name, str(e)) return None # Legacy Cura saved the profile under the section "profile_N" where N is the ID of a machine, except when you export in which case it saves it in the section "profile". # Since importing multiple machine profiles is out of scope, just import the first section we find. section = "" for found_section in input_parser.sections(): if found_section.startswith("profile"): section = found_section break if not section: # No section starting with "profile" was found. Probably not a proper INI file. return None try: with open( os.path.join( PluginRegistry.getInstance().getPluginPath("LegacyProfileReader"), "DictionaryOfDoom.json", ), "r", encoding="utf-8", ) as f: dict_of_doom = json.load(f) # Parse the Dictionary of Doom. except IOError as e: Logger.log( "e", "Could not open DictionaryOfDoom.json for reading: %s", str(e) ) return None except Exception as e: Logger.log("e", "Could not parse DictionaryOfDoom.json: %s", str(e)) return None defaults = self.prepareDefaults(dict_of_doom) legacy_settings = self.prepareLocals( input_parser, section, defaults ) # Gets the settings from the legacy profile. # Serialised format into version 4.5. Do NOT upgrade this, let the version upgrader handle it. output_parser = configparser.ConfigParser(interpolation=None) output_parser.add_section("general") output_parser.add_section("metadata") output_parser.add_section("values") if "translation" not in dict_of_doom: Logger.log( "e", "Dictionary of Doom has no translation. Is it the correct JSON file?", ) return None current_printer_definition = global_container_stack.definition quality_definition = current_printer_definition.getMetaDataEntry( "quality_definition" ) if not quality_definition: quality_definition = current_printer_definition.getId() output_parser["general"]["definition"] = quality_definition for new_setting in dict_of_doom[ "translation" ]: # Evaluate all new settings that would get a value from the translations. old_setting_expression = dict_of_doom["translation"][new_setting] compiled = compile(old_setting_expression, new_setting, "eval") try: new_value = eval( compiled, {"math": math}, legacy_settings ) # Pass the legacy settings as local variables to allow access to in the evaluation. value_using_defaults = eval( compiled, {"math": math}, defaults ) # Evaluate again using only the default values to try to see if they are default. except Exception: # Probably some setting name that was missing or something else that went wrong in the ini file. Logger.log( "w", "Setting " + new_setting + " could not be set because the evaluation failed. Something is probably missing from the imported legacy profile.", ) continue definitions = current_printer_definition.findDefinitions(key=new_setting) if definitions: if ( new_value != value_using_defaults and definitions[0].default_value != new_value ): # Not equal to the default in the new Cura OR the default in the legacy Cura. output_parser["values"][new_setting] = str( new_value ) # Store the setting in the profile! if len(output_parser["values"]) == 0: Logger.log( "i", "A legacy profile was imported but everything evaluates to the defaults, creating an empty profile.", ) output_parser["general"]["version"] = "4" output_parser["general"]["name"] = profile_id output_parser["metadata"]["type"] = "quality_changes" output_parser["metadata"][ "quality_type" ] = "normal" # Don't know what quality_type it is based on, so use "normal" by default. output_parser["metadata"]["position"] = "0" # We only support single extrusion. output_parser["metadata"][ "setting_version" ] = "5" # What the dictionary of doom is made for. # Serialise in order to perform the version upgrade. stream = io.StringIO() output_parser.write(stream) data = stream.getvalue() profile = InstanceContainer(profile_id) profile.deserialize(data, file_name) # Also performs the version upgrade. profile.setDirty(True) # We need to return one extruder stack and one global stack. global_container_id = container_registry.uniqueName( "Global Imported Legacy Profile" ) # We duplicate the extruder profile into the global stack. # This may introduce some settings that are global in the extruder stack and some settings that are per-extruder in the global stack. # We don't care about that. The engine will ignore them anyway. global_profile = profile.duplicate( new_id=global_container_id, new_name=profile_id ) # Needs to have the same name as the extruder profile. del global_profile.getMetaData()[ "position" ] # Has no position because it's global. global_profile.setDirty(True) profile_definition = "fdmprinter" from UM.Util import parseBool if parseBool( global_container_stack.getMetaDataEntry("has_machine_quality", "False") ): profile_definition = global_container_stack.getMetaDataEntry( "quality_definition" ) if not profile_definition: profile_definition = global_container_stack.definition.getId() global_profile.setDefinition(profile_definition) return [global_profile]
comicapi
filenameparser
"""Functions for parsing comic info from filename This should probably be re-written, but, well, it mostly works! """ # Copyright 2012-2014 Anthony Beville # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Some portions of this code were modified from pyComicMetaThis project # http://code.google.com/p/pycomicmetathis/ import os import re from urllib import unquote class FileNameParser: def repl(self, m): return " " * len(m.group()) def fixSpaces(self, string, remove_dashes=True): if remove_dashes: placeholders = ["[-_]", " +"] else: placeholders = ["[_]", " +"] for ph in placeholders: string = re.sub(ph, self.repl, string) return string # .strip() def getIssueCount(self, filename, issue_end): count = "" filename = filename[issue_end:] # replace any name separators with spaces tmpstr = self.fixSpaces(filename) found = False match = re.search("(?<=\sof\s)\d+(?=\s)", tmpstr, re.IGNORECASE) if match: count = match.group() found = True if not found: match = re.search("(?<=\(of\s)\d+(?=\))", tmpstr, re.IGNORECASE) if match: count = match.group() found = True count = count.lstrip("0") return count def getIssueNumber(self, filename): """Returns a tuple of issue number string, and start and end indexes in the filename (The indexes will be used to split the string up for further parsing) """ found = False issue = "" start = 0 end = 0 # first, look for multiple "--", this means it's formatted differently # from most: if "--" in filename: # the pattern seems to be that anything to left of the first "--" # is the series name followed by issue filename = re.sub("--.*", self.repl, filename) elif "__" in filename: # the pattern seems to be that anything to left of the first "__" # is the series name followed by issue filename = re.sub("__.*", self.repl, filename) filename = filename.replace("+", " ") # replace parenthetical phrases with spaces filename = re.sub("\(.*?\)", self.repl, filename) filename = re.sub("\[.*?\]", self.repl, filename) # replace any name separators with spaces filename = self.fixSpaces(filename) # remove any "of NN" phrase with spaces (problem: this could break on # some titles) filename = re.sub("of [\d]+", self.repl, filename) # print u"[{0}]".format(filename) # we should now have a cleaned up filename version with all the words in # the same positions as original filename # make a list of each word and its position word_list = list() for m in re.finditer("\S+", filename): word_list.append((m.group(0), m.start(), m.end())) # remove the first word, since it can't be the issue number if len(word_list) > 1: word_list = word_list[1:] else: # only one word?? just bail. return issue, start, end # Now try to search for the likely issue number word in the list # first look for a word with "#" followed by digits with optional suffix # this is almost certainly the issue number for w in reversed(word_list): if re.match("#[-]?(([0-9]*\.[0-9]+|[0-9]+)(\w*))", w[0]): found = True break # same as above but w/o a '#', and only look at the last word in the # list if not found: w = word_list[-1] if re.match("[-]?(([0-9]*\.[0-9]+|[0-9]+)(\w*))", w[0]): found = True # now try to look for a # followed by any characters if not found: for w in reversed(word_list): if re.match("#\S+", w[0]): found = True break if found: issue = w[0] start = w[1] end = w[2] if issue[0] == "#": issue = issue[1:] return issue, start, end def getSeriesName(self, filename, issue_start): """Use the issue number string index to split the filename string""" if issue_start != 0: filename = filename[:issue_start] # in case there is no issue number, remove some obvious stuff if "--" in filename: # the pattern seems to be that anything to left of the first "--" # is the series name followed by issue filename = re.sub("--.*", self.repl, filename) elif "__" in filename: # the pattern seems to be that anything to left of the first "__" # is the series name followed by issue filename = re.sub("__.*", self.repl, filename) filename = filename.replace("+", " ") tmpstr = self.fixSpaces(filename, remove_dashes=False) series = tmpstr volume = "" # save the last word try: last_word = series.split()[-1] except: last_word = "" # remove any parenthetical phrases series = re.sub("\(.*?\)", "", series) # search for volume number match = re.search("(.+)([vV]|[Vv][oO][Ll]\.?\s?)(\d+)\s*$", series) if match: series = match.group(1) volume = match.group(3) # if a volume wasn't found, see if the last word is a year in parentheses # since that's a common way to designate the volume if volume == "": # match either (YEAR), (YEAR-), or (YEAR-YEAR2) match = re.search("(\()(\d{4})(-(\d{4}|)|)(\))", last_word) if match: volume = match.group(2) series = series.strip() # if we don't have an issue number (issue_start==0), look # for hints i.e. "TPB", "one-shot", "OS", "OGN", etc that might # be removed to help search online if issue_start == 0: one_shot_words = ["tpb", "os", "one-shot", "ogn", "gn"] try: last_word = series.split()[-1] if last_word.lower() in one_shot_words: series = series.rsplit(" ", 1)[0] except: pass return series, volume.strip() def getYear(self, filename, issue_end): filename = filename[issue_end:] year = "" # look for four digit number with "(" ")" or "--" around it match = re.search("(\(\d\d\d\d\))|(--\d\d\d\d--)", filename) if match: year = match.group() # remove non-digits year = re.sub("[^0-9]", "", year) return year def getRemainder(self, filename, year, count, volume, issue_end): """Make a guess at where the the non-interesting stuff begins""" remainder = "" if "--" in filename: remainder = filename.split("--", 1)[1] elif "__" in filename: remainder = filename.split("__", 1)[1] elif issue_end != 0: remainder = filename[issue_end:] remainder = self.fixSpaces(remainder, remove_dashes=False) if volume != "": remainder = remainder.replace("Vol." + volume, "", 1) if year != "": remainder = remainder.replace(year, "", 1) if count != "": remainder = remainder.replace("of " + count, "", 1) remainder = remainder.replace("()", "") remainder = remainder.replace(" ", " ") # cleans some whitespace mess return remainder.strip() def parseFilename(self, filename): # remove the path filename = os.path.basename(filename) # remove the extension filename = os.path.splitext(filename)[0] # url decode, just in case filename = unquote(filename) # sometimes archives get messed up names from too many decodes # often url encodings will break and leave "_28" and "_29" in place # of "(" and ")" see if there are a number of these, and replace them if filename.count("_28") > 1 and filename.count("_29") > 1: filename = filename.replace("_28", "(") filename = filename.replace("_29", ")") self.issue, issue_start, issue_end = self.getIssueNumber(filename) self.series, self.volume = self.getSeriesName(filename, issue_start) # provides proper value when the filename doesn't have a issue number if issue_end == 0: issue_end = len(self.series) self.year = self.getYear(filename, issue_end) self.issue_count = self.getIssueCount(filename, issue_end) self.remainder = self.getRemainder( filename, self.year, self.issue_count, self.volume, issue_end ) if self.issue != "": # strip off leading zeros self.issue = self.issue.lstrip("0") if self.issue == "": self.issue = "0" if self.issue[0] == ".": self.issue = "0" + self.issue
lib
plugin
# The contents of this file are subject to the Common Public Attribution # License Version 1.0. (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, but Sections 14 and 15 have been added to cover use of # software over a computer network and provide for limited attribution for the # Original Developer. In addition, Exhibit A has been modified to be consistent # with Exhibit B. # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for # the specific language governing rights and limitations under the License. # # The Original Code is reddit. # # The Original Developer is the Initial Developer. The Initial Developer of # the Original Code is reddit Inc. # # All portions of the code written by reddit are Copyright (c) 2006-2015 reddit # Inc. All Rights Reserved. ############################################################################### import os.path import sys from collections import OrderedDict import pkg_resources class Plugin(object): js = {} config = {} live_config = {} needs_static_build = False needs_translation = True errors = {} source_root_url = None def __init__(self, entry_point): self.entry_point = entry_point @property def name(self): return self.entry_point.name @property def path(self): module = sys.modules[type(self).__module__] return os.path.dirname(module.__file__) @property def template_dir(self): """Add module/templates/ as a template directory.""" return os.path.join(self.path, "templates") @property def static_dir(self): return os.path.join(self.path, "public") def on_load(self, g): pass def add_js(self, module_registry=None): if not module_registry: from r2.lib import js module_registry = js.module for name, module in self.js.iteritems(): if name not in module_registry: module_registry[name] = module else: module_registry[name].extend(module) def declare_queues(self, queues): pass def add_routes(self, mc): pass def load_controllers(self): pass def get_documented_controllers(self): return [] class PluginLoader(object): def __init__(self, working_set=None, plugin_names=None): self.working_set = working_set or pkg_resources.WorkingSet() if plugin_names is None: entry_points = self.available_plugins() else: entry_points = [] for name in plugin_names: try: entry_point = self.available_plugins(name).next() except StopIteration: ( print >> sys.stderr, ("Unable to locate plugin " "%s. Skipping." % name), ) continue else: entry_points.append(entry_point) self.plugins = OrderedDict() for entry_point in entry_points: try: plugin_cls = entry_point.load() except Exception as e: if plugin_names: # if this plugin was specifically requested, fail. raise e else: ( print >> sys.stderr, ( "Error loading plugin %s (%s)." " Skipping." % (entry_point.name, e) ), ) continue self.plugins[entry_point.name] = plugin_cls(entry_point) def __len__(self): return len(self.plugins) def __iter__(self): return self.plugins.itervalues() def __reversed__(self): return reversed(self.plugins.values()) def __getitem__(self, key): return self.plugins[key] def available_plugins(self, name=None): return self.working_set.iter_entry_points("r2.plugin", name) def declare_queues(self, queues): for plugin in self: plugin.declare_queues(queues) def load_plugins(self, config): g = config["pylons.app_globals"] for plugin in self: # Record plugin version entry = plugin.entry_point git_dir = os.path.join(entry.dist.location, ".git") g.record_repo_version(entry.name, git_dir) # Load plugin g.config.add_spec(plugin.config) config["pylons.paths"]["templates"].insert(0, plugin.template_dir) plugin.add_js() plugin.on_load(g) def load_controllers(self): # this module relies on pylons.i18n._ at import time (for translating # messages) which isn't available 'til we're in request context. from r2.lib import errors for plugin in self: errors.add_error_codes(plugin.errors) plugin.load_controllers() def get_documented_controllers(self): for plugin in self: for controller, url_prefix in plugin.get_documented_controllers(): yield controller, url_prefix