Exemple #1
0
    def run(self, argv):
        broker = self.communicator()
        adapter = broker.createObjectAdapter("PlayerAdapter")
        adapter2 = broker.createObjectAdapter("ContainerAdapter")
        sirviente = Container.Container()
        conRobotos = Container.Container()
        servant = Player(adapter, sirviente, conRobotos)
        adapter2.add(sirviente, broker.stringToIdentity("Container"))
        adapter2.add(conRobotos, broker.stringToIdentity("Robots"))

        proxyServer = adapter.add(servant,
                                  broker.stringToIdentity("Barbassss"))
        prx_id = proxyServer.ice_getIdentity()
        direct_prx = adapter.createDirectProxy(prx_id)
        player = drobots.PlayerPrx.uncheckedCast(direct_prx)

        adapter.activate()
        adapter2.activate()
        proxyClient = self.communicator().propertyToProxy("Game")
        game = drobots.GamePrx.checkedCast(proxyClient)

        name = random.randint(1000, 9999)
        game.login(player, str(name))

        self.shutdownOnInterrupt()
        broker.waitForShutdown()
    def __init__(self, imageDir, imageName, blockDimension, targetResult):
        """
        Fungsi konstruktor untuk mempersiapkan citra dan parameter algoritma
        :param imageDir: direktori file citra
        :param imageName: nama file citra
        :param blockDimension: ukuran blok dimensi (ex:32, 64, 128)
        :param targetResult: direktori untuk hasil deteksi
        :return: None
        """

        print imageName
        print "Step 1/4: Inisialisasi objek dan variable",

        # parameter gambar
        self.targetResult = targetResult
        self.imagePath = imageName
        self.image = Image.open(imageDir + imageName)
        self.imageWidth, self.imageHeight = self.image.size  # height = vertikal atas bawah, width = horizontal lebar kanan kiri

        if self.image.mode != 'L':
            self.isRGB = True

            self.image = self.image.convert('RGB')
            imagePixels = self.image.load()
            self.imageGrayscale = self.image.convert(
                'L')  # membuat kanvas grayscale baru dari gambar lama
            imageGrayscalePixels = self.imageGrayscale.load()

            for y in range(0, self.imageHeight):
                for x in range(0, self.imageWidth):
                    tmpR, tmpG, tmpB = imagePixels[x, y]
                    imageGrayscalePixels[x, y] = int(0.299 * tmpR) + int(
                        0.587 * tmpG) + int(0.114 * tmpB)
        else:
            self.isRGB = False
            self.image = self.image.convert('L')

        # parameter algoritma paper 1
        self.N = self.imageWidth * self.imageHeight
        self.blockDimension = blockDimension
        self.b = self.blockDimension * self.blockDimension
        self.Nb = (self.imageWidth - self.blockDimension +
                   1) * (self.imageHeight - self.blockDimension + 1)
        self.Nn = 2  # jumlah blok tetangga yang diperiksa
        # self.Nf = 750    # jumlah minimal frekuensi sebuah offset
        self.Nf = 188  # jumlah minimal frekuensi sebuah offset
        self.Nd = 50  # jumlah minimal offset magnitude

        # parameter algoritma paper 2
        self.P = (1.80, 1.80, 1.80, 0.0125, 0.0125, 0.0125, 0.0125)
        self.t1 = 2.80
        self.t2 = 0.02

        print self.Nb, self.isRGB

        # inisialisasi kontainer untuk menampung data
        self.featureContainer = Container.Container()
        self.pairContainer = Container.Container()
        self.offsetDict = {}
Exemple #3
0
    def __init__(self, imageDirectory, imageName, blockDimension,
                 outputDirectory):
        """
        Constructor to initialize the algorithm's parameters
        :return: None
        """

        print imageName
        print "Step 1 of 4: Object and variable initialization",

        # image parameter
        self.imageOutputDirectory = outputDirectory
        self.imagePath = imageName
        self.imageData = Image.open(imageDirectory + imageName)
        self.imageWidth, self.imageHeight = self.imageData.size  # height = vertikal, width = horizontal

        if self.imageData.mode != 'L':  # L means grayscale
            self.isThisRGBImage = True
            self.imageData = self.imageData.convert('RGB')
            RGBImagePixels = self.imageData.load()
            self.imageGrayscale = self.imageData.convert(
                'L'
            )  # creates a grayscale version of current image to be used later
            GrayscaleImagePixels = self.imageGrayscale.load()

            for yCoordinate in range(0, self.imageHeight):
                for xCoordinate in range(0, self.imageWidth):
                    redPixelValue, greenPixelValue, bluePixelValue = RGBImagePixels[
                        xCoordinate, yCoordinate]
                    GrayscaleImagePixels[xCoordinate, yCoordinate] = int(
                        0.299 * redPixelValue) + int(
                            0.587 * greenPixelValue) + int(
                                0.114 * bluePixelValue)
        else:
            self.isThisRGBImage = False
            self.imageData = self.imageData.convert('L')

        # algorithm's parameters from the first paper
        self.N = self.imageWidth * self.imageHeight
        self.blockDimension = blockDimension
        self.b = self.blockDimension * self.blockDimension
        self.Nb = (self.imageWidth - self.blockDimension +
                   1) * (self.imageHeight - self.blockDimension + 1)
        self.Nn = 2  # amount of neighboring block to be evaluated
        self.Nf = 188  # minimum treshold of the offset's frequency
        self.Nd = 50  # minimum treshold of the offset's magnitude

        # algorithm's parameters from the second paper
        self.P = (1.80, 1.80, 1.80, 0.0125, 0.0125, 0.0125, 0.0125)
        self.t1 = 2.80
        self.t2 = 0.02

        print self.Nb, self.isThisRGBImage

        # container initialization to later contains several data
        self.featuresContainer = Container.Container()
        self.blockPairContainer = Container.Container()
        self.offsetDictionary = {}
Exemple #4
0
 def get_nfa(self, postfix_regex):
     stack = []
     unary = ("*", "+", "?")
     binary = ("|", ".")
     while len(postfix_regex) > 0:
         char = postfix_regex[0]
         postfix_regex = postfix_regex[1:]
         if self.is_char(char):
             stack.append(Container(char))
         elif char in unary:
             op = stack.pop()
             if char == "*":
                 stack.append(ZeroOrMore(op))
             elif char == "+":
                 stack.append(OneOrMore(op))
             elif char == "?":
                 stack.append(ZeroOrOne(op))
         elif char in binary:
             op2 = stack.pop()
             op1 = stack.pop()
             if char == ".":
                 stack.append(Concat(op1, op2))
             elif char == "|":
                 stack.append(Or(op1, op2))
     #print("Stack!")
     return stack.pop()
    def __init__(self):
        QMainWindow.__init__(self)
        
        # Loading and setting up style sheet
        self.setupUi(self)
        
        # Initializing attributes
        self.zoom_count = 0
        self.thrd = None

        # Creating instances of classes for the main app
        self.container = Container(self.textBrowser, self.graphicsView)        
        self.comp = ComponentSelector(self)

        # Setting up interactive canvas        
        self.scene = self.container.graphics.get_scene()
        self.graphicsView.setScene(self.scene)
        self.graphicsView.setMouseTracking(True)
        self.graphicsView.keyPressEvent=self.delete_call
        
        self.setDockNestingEnabled(True)
        self.setCorner(Qt.BottomRightCorner, Qt.RightDockWidgetArea)
        self.setCorner(Qt.BottomLeftCorner, Qt.LeftDockWidgetArea)
        self.addDockWidget(Qt.BottomDockWidgetArea,self.dockWidget_2)
        
        # Calling initialisation 
        self.menu_bar()
        self.button_handler()
        self.comp.show()
Exemple #6
0
    def __init__(self, imageDirectory, imageName, blockDimension,
                 outputDirectory):
        """
        Constructor to initialize the algorithm's parameters
        :return: None
        """

        print(imageName)
        print("Step 1 of 4: Object and variable initialization")

        # image parameter
        self.imageOutputDirectory = outputDirectory
        self.imagePath = imageName
        self.imageData = Image.open(imageDirectory + imageName)
        self.imageWidth, self.imageHeight = self.imageData.size  # height = vertikal, width = horizontal

        if self.imageData.mode != 'L':  # L means grayscale
            self.isThisRGBImage = True
            self.imageData = self.imageData.convert('RGB')
            self.imageGrayscale = self.imageData.convert(
                'L'
            )  # creates a grayscale version of current image to be used later

        else:
            self.isThisRGBImage = False
            self.imageData = self.imageData.convert('L')

        self.blockDimension = blockDimension
        self.Max_Count = 15

        # container initialization to later contains several data
        self.featuresContainerKeypoints = Container.Container()
        self.featuresContainerDescriptors = Container.Container()
        self.blockPairContainer = Container.Container()
        self.matched_coordinate = Container.Container()
        self.offsetDictionary = {}
        FLANN_INDEX_KDTREE = 1
        index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
        search_params = dict(checks=50)  # or pass empty dictionary
        self.flann = cv2.FlannBasedMatcher(index_params, search_params)
 def PreWarmContainers(self):
     """Warm containers before incoming activation to mimic it happening at the actual time """
     if self.eviction_policy != "HIST":
         return
     to_warm = [
         kind for kind, prewarm in self.histPrewarm.items()
         if prewarm != 0 and prewarm +
         self.last_seen[kind] >= self.wall_time
     ]
     for kind in to_warm:
         c = Container(self.rep[kind])
         at = self.histPrewarm[kind] + self.last_seen[kind]
         at = min(at, self.wall_time)
         self.AddToPool(c=c, prewarm=True, at_time=at)
Exemple #8
0
 def __init__(self, _modelRunTitle, run_codes, _db):
     # add run title.
     self.modelRunTitle = self._addTitle(_modelRunTitle)
     # add run codes.
     self.run_codes = run_codes
     # container to pass info around.
     self.cont = Container.Container()
     self.cont.set('modelRunTitle', self._addTitle(_modelRunTitle))
     self.cont.set('run_codes', run_codes)
     self.cont.set('path', 'C:/Nonroad/%s/' % (_modelRunTitle))
     self.cont.set('db', _db)
     self.cont.set('qr', qr.QueryRecorder(self.cont.get('path')))
     # create Batch runner.
     self.batch = Batch.Batch(self.cont)
Exemple #9
0
    def Get(self):
        result = []

        allnumbers = self.GetShuffledNumbers()

        for i in range(0, 30, 6):
            posY = 540-(10*i)
            block = []
            for j in range(i, i+6):
                posX = 0+(60 * (j % 6))
                newContainer = Container(allnumbers[j], posX, posY)
                block.append(newContainer)
            result.append(block)

        return result
    def undo_redo_helper(self):
        for i in self.container.unit_operations:
            type(i).counter = 1
        self.container = None
        for i in dock_widget_lst:
            i.hide()
            del i
        lst.clear()
        self.container = Container(self.textBrowser, self.graphicsView)

        compound_selected.clear()
        self.scene = self.container.graphics.get_scene()
        self.graphicsView.setScene(self.scene)
        self.graphicsView.setMouseTracking(True)
        self.graphicsView.keyPressEvent=self.delete_call
    def cache_miss(self, d: LambdaData):
        c = Container(d)
        if not self.checkfree(c):  #due to space constraints
            #print("Eviction needed ", d.mem_size, self.mem_used)
            evicted = self.Eviction(
                d)  #Is a list. also terminates the containers?

        added = self.AddToPool(c)
        if not added:
            # print("Could not add even after evicting. FATAL ERROR")
            # print("actual in-use memory", sum([k.metadata.mem_size for k in self.ContainerPool]))
            # print("pool size", len(self.ContainerPool))
            return None

        heapq.heapify(self.ContainerPool)
        return c
Exemple #12
0
    def __init__(self,
                 name,
                 id,
                 mass,
                 sideLength,
                 length,
                 _from,
                 start_points,
                 end_points,
                 health=100):
        self.name = name
        self.id = id
        self.mass = mass
        self.sideLength = sideLength
        self.length = length
        self.start_points = start_points
        self.end_points = end_points
        self.parents = []
        self.health = health
        self.bacteriaClusters = []
        self.immuneCellClusters = []
        self._from = _from
        self._sideLengthBoxes = round(0.5 + (float(sideLength) /
                                             parameters.organ_grid_resolution))
        self._lengthBoxes = round(0.5 + (float(length) /
                                         parameters.organ_grid_resolution))
        self._grid = np.empty(
            (self._sideLengthBoxes, self._sideLengthBoxes, self._lengthBoxes),
            dtype=Container)
        for i in range(self._sideLengthBoxes):
            for j in range(self._sideLengthBoxes):
                for k in range(self._lengthBoxes):
                    self._grid[i][j][k] = Container()
        xs = np.random.uniform(0, self._sideLengthBoxes, 2)
        ys = np.random.uniform(0, self._sideLengthBoxes, 2)
        zs = np.random.uniform(0, self._lengthBoxes, 2)
        self._grid_entrance = Point(int(xs[0]), int(ys[0]), int(zs[0]))

        self._grid_exit = Point(int(xs[1]), int(ys[1]), int(zs[1]))
        self.volume = sideLength**2 * length
        self.residualVolume = 0
        self._flowEvent = []
        self.bacteriaCountHistory = []
        self.flowHistory = []
Exemple #13
0
    def run(self, argv):

        broker = self.communicator()
        adapter = broker.createObjectAdapter("PlayerAdapter")
        adapter2 = broker.createObjectAdapter("ContainerAdapter")

        containerRobots = Container.Container()

        # Factorias para controladores de robot
        factorias_robot_identity = ["RobotFactory1", "RobotFactory2", "RobotFactory3"]
        factorias_robot = []

        for factorias_identity in factorias_robot_identity:
            factory_proxy = broker.stringToProxy(factorias_identity)
            factorias_robot.append(drobots.RobotFactoryPrx.checkedCast(factory_proxy))

        # Factoria para controlador de detector
        detector_proxy = broker.stringToProxy("RobotFactory4")
        factoria_detector = drobots.DetectorFactoryPrx.checkedCast(detector_proxy)

        sirviente = Player(adapter, factorias_robot, factoria_detector, containerRobots)
        adapter2.add(containerRobots, broker.stringToIdentity("Robots"))

        proxyPlayer = adapter.add(sirviente, broker.stringToIdentity("Player"))
        proxyDirecto = adapter.createDirectProxy(proxyPlayer.ice_getIdentity())
        player = drobots.PlayerPrx.uncheckedCast(proxyDirecto)

        adapter.activate()
        adapter2.activate()

        proxyGame = broker.propertyToProxy("Game")
        game = drobots.GamePrx.checkedCast(proxyGame)

        idrandom = random.randint(0, 9999)
        game.login(player, str(idrandom))
        print("Partida comenzada.")

        self.shutdownOnInterrupt()
        self.communicator().waitForShutdown()
Exemple #14
0
    def __init__(self, init_string):
        c = Container.Container()
        Lx = 10.
        Ly = 10.
        Lz = 0.
        dist = Lx / 5.
        vel = dist / 5.

        if init_string == 'one':
            c.Lx = Lx
            c.Ly = Ly
            c.Lz = Lz

            c.add_particle(0., dist, 0., 0., 0., 0.)

        elif init_string == 'two':
            c.Lx = Lx
            c.Ly = Ly
            c.Lz = Lz

            c.add_particle(1., 5., 0., 0.4, 0., 0.)
            c.add_particle(3., 5., 0., -0.4, 0., 0.)

        elif init_string == 'eight':
            lx = 10.
            ly = 10.
            dist = lx / 5.
            vel = dist / 5.
            #c.L = Vector_3D(10., 10., 0.)
            c.Lx = 10.
            c.Ly = 10.
            c.Lz = 0.
            c.add_particle(-dist + 5, 0. + 5, 0., vel, 0., 0.)
            c.add_particle(dist + 5, 0. + 5, 0., -vel, 0., 0.)
            c.add_particle(0. + 5, dist + 5, 0., 0., -vel, 0.)
            c.add_particle(0. + 5, -dist + 5, 0., 0., vel, 0.)
            c.add_particle(dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0.,
                           -vel / sqrt(2), -vel / sqrt(2), 0.)
            c.add_particle(-dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0.,
                           vel / sqrt(2), -vel / sqrt(2), 0.)
            c.add_particle(-dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0.,
                           vel / sqrt(2), vel / sqrt(2), 0.)
            c.add_particle(dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0.,
                           -vel / sqrt(2), vel / sqrt(2), 0.)

        elif init_string == 'eight-zeros':
            lx = 10.
            ly = 10.
            dist = lx / 5.
            vel = dist / 5.
            #c.L = Vector_3D(10., 10., 0.)
            c.Lx = 10.
            c.Ly = 10.
            c.Lz = 0.
            c.add_particle(-dist + 5, 0. + 5, 0., 0., 0., 0.)
            c.add_particle(dist + 5, 0. + 5, 0., 0., 0., 0.)
            c.add_particle(0. + 5, dist + 5, 0., 0., 0., 0.)
            c.add_particle(0. + 5, -dist + 5, 0., 0., vel, 0.)
            c.add_particle(dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0., 0., 0.,
                           0.)
            c.add_particle(-dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0., 0., 0.,
                           0.)
            c.add_particle(-dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0., 0.,
                           0., 0.)
            c.add_particle(dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0., 0., 0.,
                           0.)

        elif init_string == 'square_lattice':
            N = 8  # Particles per row
            Lx = 9.
            Ly = Lx
            #c.Ly = c.Lx       # Extents determined by Lx input
            # TODO: set L
            #c.L = Vector_3D(30., 30., 0.)
            c.Lx = 9.
            c.Ly = 9.
            c.Lz = 0.
            d = 2.**(1 / 6.)  # Particle diameter
            x = np.linspace(d / 2, Lx - d / 2, N)
            y = np.linspace(d / 2., Lx - d / 2, N)
            for i in range(x.size):
                for j in range(y.size):
                    c.add_particle(x[i], y[j], 0., 0., 0., 0.)
                    #c.addParticle(x, y, z, vx, vy, ax, ay, mass)

        elif init_string == 'tri_lattice':
            Lx = 8.
            N = 8  # particles per row
            Ly = sqrt(3) / 2. * Lx  # Set this based on Lx
            #c.L = Vector_3D(Lx, Ly, 0.)
            c.Lx = Lx
            c.Ly = Ly
            d = 2.**(1 / 6.)  # diameter
            x = np.linspace(-c.Lx / 2 + 3. * d / 4., c.Lx / 2. - 1. * d / 4.,
                            N)  # Unstaggered
            xs = np.linspace(-c.Lx / 2 + d / 4., c.Lx / 2. - 3. * d / 4.,
                             N)  # Staggered
            y = np.linspace(-c.Ly / 2 + d / 2., c.Ly / 2 - d / 2, N)

            for i in range(N):
                for j in range(N):
                    if np.mod(i, 2) == 0:
                        #c.addParticle(x[j],y[i],0,0,0,0,1)
                        c.add_particle(x[j], y[i], 0., 0., 0., 0.)
                    else:
                        #c.addParticle(xs[j],y[i],0,0,0,0,1)
                        c.add_particle(xs[j], y[i], 0., 0., 0., 0.)
        self.c = c
Exemple #15
0
    def __init__(self,
                 object,
                 message,
                 type=None,
                 name=None,
                 size=None,
                 position=None,
                 messageButtonsDto=None,
                 fontSize=None,
                 scale=None,
                 padding=None,
                 messageColor=None,
                 noImage=False,
                 surfaceColor=objectFunction.Attribute.MODAL_MESSAGE_COLOR,
                 onLeftClick=None,
                 imagePath=None,
                 audioPath=None):

        if not onLeftClick:
            onLeftClick = objectFunction.defaultOnLeftClick
        father = object
        if not name:
            name = 'Message'
        size = self.calculateSize(size, father)
        position = self.calculatePosition(position, size, father)
        fontSize = self.calculateFontSize(fontSize, father)
        textPosition = self.calculateTextPosition(size, fontSize)

        if not type:
            type = objectFunction.Type.MESSAGE

        ###- Older version - whithougth modal covering desk
        # Modal.Modal.__init__(self,name,size,father,
        #     type = type,
        #     position = position,
        #     text = message,
        #     textPosition = textPosition,
        #     fontSize = fontSize,
        #     scale = scale,
        #     padding = padding,
        #     noImage = noImage,
        #     surfaceColor = surfaceColor,
        #     imagePath = imagePath,
        #     audioPath = audioPath
        # )
        #
        # if messageButtonsDto :
        #     containerName = None
        #     containerFather = self
        #     containerPosition = [0,containerFunction.Attribute.BOTTOM]
        #     containerSize = ['100%',60]
        #     Container.Container(containerName,containerPosition,containerSize,containerFather,
        #         itemsDto = messageButtonsDto,
        #         fontSize = self.fontSize,
        #         noImage = True,
        #         imagePath = None,
        #         audioPath = None
        #     )

        ###- Newer version - whith modal covering desk
        deskPosition = sessionFunction.getDeskPosition(object.application)
        deskSize = sessionFunction.getDeskSize(object.application)

        Modal.Modal.__init__(self,
                             name,
                             deskSize,
                             father,
                             type=type,
                             position=deskPosition,
                             fontSize=fontSize,
                             scale=scale,
                             padding=padding,
                             noImage=True,
                             surfaceColor=surfaceColor,
                             onLeftClick=onLeftClick,
                             imagePath=imagePath,
                             audioPath=audioPath)

        messageFather = self
        containerFather = Container.Container(f'{name}.messageContainer',
                                              position,
                                              size,
                                              messageFather,
                                              itemsDto=[],
                                              text=message,
                                              textPosition=textPosition,
                                              fontSize=self.fontSize,
                                              noImage=False,
                                              onLeftClick=onLeftClick,
                                              imagePath=None,
                                              audioPath=None)

        if messageButtonsDto:
            containerName = None
            containerFather = containerFather
            containerPosition = [0, containerFunction.Attribute.BOTTOM]
            containerSize = ['100%', 60]
            Container.Container(containerName,
                                containerPosition,
                                containerSize,
                                containerFather,
                                itemsDto=messageButtonsDto,
                                fontSize=self.fontSize,
                                noImage=True,
                                imagePath=None,
                                audioPath=None)
    def run(self, bridge, url, run_as_service=False):
        logger = logging.getLogger(self.id)
        import xbmc

        xbmc.bridge = bridge
        import Container
        xbmc.Container = Container.Container(self)
        xbmc.LANGUAGE = kodi_utils.get_config(kodi_utils.LANGUAGE_CONFIG)
        if not xbmc.LANGUAGE:
            xbmc.LANGUAGE = 'English'
        if type(url) is not str:
            raise Exception('Kodi plugin only accepts one string argument')

        if url.startswith('http') or url.startswith('https'):
            bridge.play(url, type_='video')
            return
        orig = sys.path

        sys.path.append(os.path.join(bundle_dir, 'scripts'))
        sys.path.append(os.path.join(bundle_dir, 'scripts', 'kodi'))

        import xbmcplugin, xbmcaddon, copy

        for r in self.requires:
            if not os.path.exists(os.path.join(ADDONS_DIR, r)):
                logger.error('Addon {} is missing module {}'.format(
                    self.id, r))
                return None

            tree = ET.parse(os.path.join(ADDONS_DIR, r, 'addon.xml'))
            for e2 in tree.iter('extension'):
                if e2.attrib['point'] == 'xbmc.python.module':
                    sys.path.insert(
                        0, os.path.join(ADDONS_DIR, r, e2.attrib['library']))
                    xbmcaddon.Addon(r,
                                    copy.deepcopy(kodi_utils.get_settings(r)))

        sys.path.insert(0, self.dir)
        if '/' in self.module:
            sys.path.insert(
                0, os.path.join(*([self.dir] + self.module.split('/')[:-1])))
        print sys.path

        if run_as_service and self.service:
            try:
                if 'setproctitle' in sys.modules:
                    setproctitle.setproctitle(
                        'python TVMLServer ({} service)'.format(self.id))
                runpy.run_module(self.service.split('/')[-1][:-3],
                                 run_name='__main__')
            except:
                logger.exception('Failed in addon {} service'.format(self.id))
            return None

        try:
            if '?' in url:
                sys.argv = [
                    url.split('?')[0], '1', '?{}'.format(url.split('?')[1])
                ]
            else:
                sys.argv = [url, '1', '']

            if not sys.argv[0]:
                sys.argv[0] = 'plugin://{}/'.format(self.id)

            if not sys.argv[0].startswith(
                    'file://') and not sys.argv[0].startswith('plugin://'):
                sys.argv[0] = 'plugin://{}{}'.format(self.id, sys.argv[0])
        # sys.argv = [script, '1', url]
            logger.debug('Calling plugin {} with {}'.format(
                self.name, sys.argv))
            import xbmcplugin, xbmcaddon
            xbmcaddon.Addon(self.id,
                            copy.deepcopy(kodi_utils.get_settings(self.id)))
            import imp

            # some patches for internal python funcs
            import urllib

            quote_plus_orig = urllib.quote_plus

            def quote_plus_patch(s, safe=''):
                if type(s) == unicode:
                    s = s.encode('utf-8')
                return quote_plus_orig(s, safe)

            urllib.quote_plus = quote_plus_patch

            import sqlite3

            sqlite3_connect_orig = sqlite3.connect

            def sqlite3_connect_patch(*args, **kwargs):
                logger.debug('sqlite3 connect patch')
                database = args[0]
                dirname = os.path.dirname(database)
                if not os.path.exists(dirname):
                    logger.debug(
                        'creating non-existent directory {}'.format(dirname))
                    os.makedirs(dirname)
                if not os.path.exists(database):
                    open(database, 'a').close()
                for tries in range(10):
                    try:
                        return sqlite3_connect_orig(*args, **kwargs)
                    except:
                        time.sleep(1)
                        logger.exception('Failed to open DB')
                raise Exception('Failed to open DB file {}'.format(database))

            sqlite3.connect = sqlite3_connect_patch

            dbapi2_connect_orig = sqlite3.dbapi2.connect

            def dbapi2_connect_patch(*args, **kwargs):
                logger.debug('sqlite3.dbapi2 connect patch')
                database = args[0]
                dirname = os.path.dirname(database)
                if not os.path.exists(dirname):
                    logger.debug(
                        'creating non-existent directory {}'.format(dirname))
                    os.makedirs(dirname)
                if not os.path.exists(database):
                    open(database, 'a').close()
                for tries in range(10):
                    try:
                        return dbapi2_connect_orig(*args, **kwargs)
                    except:
                        time.sleep(1)
                        logger.exception('Failed to open DB')
                logger.exception('Failed to open DB file {}'.format(database))
                raise Exception('Failed to open DB file {}'.format(database))

            sqlite3.dbapi2.connect = dbapi2_connect_patch

            xbmcplugin.items = []
            runpy.run_module(self.module.split('/')[-1], run_name='__main__')
            #imp.load_module(self.module, fp, self.dir, ('.py', 'rb', imp.PY_SOURCE))
        except SystemExit:
            pass
        except:
            logger.exception('Failure in plugin run')
        sqlite3.connect = sqlite3_connect_orig
        sqlite3.dbapi2.connect = dbapi2_connect_orig
        urllib.quote_plus = quote_plus_orig
        sys.path = orig
        # sys.argv = old_sys_argv
        items = xbmcplugin.items
        if xbmcplugin.resolved:
            listitem = xbmcplugin.resolved
            image = listitem.thumbnailImage if listitem.thumbnailImage != 'DefaultFolder.png' else ''
            if listitem.getProperty('poster'):
                image = listitem.getProperty('poster')
            imdb = listitem.getProperty('imdb')
            if not imdb:
                imdb = listitem.getProperty('imdb_id')
            if not imdb:
                imdb = listitem.getProperty('imdbnumber')
            if not imdb:
                imdb = listitem.getProperty('code')
            global resolved
            resolved = listitem
            bridge.play(listitem.path,
                        title=listitem.getProperty('title'),
                        description=listitem.getProperty('plot'),
                        image=image,
                        imdb=imdb,
                        season=str(listitem.getProperty('season'))
                        if listitem.getProperty('season') else None,
                        episode=str(listitem.getProperty('episode'))
                        if listitem.getProperty('episode') else None)
            xbmcplugin.resolved = None
        logger.debug('Plugin {} ended with: {}'.format(self.name, items))

        # some cleanup
        for id in xbmcaddon.ADDON_CACHE:
            kodi_utils.set_settings(id, xbmcaddon.ADDON_CACHE[id].settings)
        if hasattr(bridge, 'progress'):
            logger.debug('Closing left over progress')
            bridge.closeprogress()
        ans = []
        items = xbmcplugin.items
        from Plugin import Item

        if len(items) == 1 and hasattr(items[0], 'path'):
            return items
        for item in items:
            # url, title, subtitle=None, icon=None, details=None, menuurl='', info={})
            i = Item(
                url=item['url'],
                title=kodi_utils.tag_conversion(item['listitem'].label),
                subtitle=item['listitem'].getProperty('subtitle'),
                icon=item['listitem'].thumbnailImage if
                item['listitem'].thumbnailImage != 'DefaultFolder.png' else '',
                details=item['listitem'].getProperty('details'),
                info=item['listitem'].infos,
                context=item['listitem'].context)
            try:
                if type(i.context) is list:  # needs to be dict
                    i.context = {x[0]: x[1] for x in i.context}
            except:
                pass
            infos = item['listitem'].infos
            if 'poster' in infos:
                i.icon = infos['poster']
            if 'plot' in infos:
                i.details = infos['plot']
            if 'year' in infos:
                i.year = infos['year']
            if 'trailer' in infos:
                i.context['Watch trailer'] = 'RunPlugin({})'.format(
                    infos['trailer'])
            # icon path fix
            if i.icon and i.icon.startswith(ADDONS_DIR):
                i.icon = i.icon.replace(ADDONS_DIR, '/addons')
            if i.icon:
                i.icon = i.icon.replace('\\', '/')
            ans.append(i)
        return ans
Exemple #17
0
# First Python Project
from Container import *

container1 = Container("OCL", "Clothes")
container2 = Container("MAS", "Electronics")
container3 = Container("AML", "Foods")
container4 = Container._create_empty_container("BML")

while True:
    print("please provide a number: 12")
    response = input()
    if (int(response) % 7 == 0):
        print("it's reminder of 0")
        break
    else:
        print("not a reminder of 7.")
Exemple #18
0
img_not_sel = Image()
preserve_icon_size = style['preserve_icon_size']
img_sel.set_keep_real_size(preserve_icon_size)
img_not_sel.set_keep_real_size(preserve_icon_size)
maxlen = style['maxlen']
text_not_sel = TextBlock(max_width=maxlen)
text_not_sel.set_color(color=style['text_color'])
text_sel = TextBlock(max_width=maxlen, autoscroll=style['autoscroll'])
text_sel.set_color(color=style['selected_text_color'])
text_sel.set_style(style=style['selected_font_style'])
text_not_sel.set_style(style=style['font_style'])
self.text_not_sel = text_not_sel
self.text_sel = text_sel
self.icon_not_sel = img_not_sel
self.icon_sel = img_sel
c = Container()
c_sel = Container()
tw, th = style['text_size']
iw, ih = style['icon_size']
left, top = style['text_offset']
c.add_child(text_not_sel, width=tw, height=th, top=top, left=left)
c.add_child(img_not_sel, width=iw, height=ih, right='100%', valign='50%')
tw, th = style['selected_text_size']
iw, ih = style['selected_icon_size']
left, top = style['selected_text_offset']
c_sel.add_child(text_sel, width=tw, height=th, top=top, left=left)
c_sel.add_child(img_sel, width=iw, height=ih, right='100%', valign='50%')
return (c, c_sel)
]:
	i: 
	o: 
Exemple #19
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 13:08:32 2019

@author: rosto
"""

import Row
import Container

r = Row.Row()
r2 = Row.Row()
c = Container.Container()
c.add_child(r)
c.add_child(r2)

print(c.to_html())
    def __init__(self, init_string):
        c = Container.Container()
        Lx = 10.
        Ly = 10.
        Lz = 0.
        dist = Lx / 5.
        vel = dist / 5.

        if init_string == 'one':
            c.Lx = Lx
            c.Ly = Ly
            c.Lz = Lz

            c.add_particle(0., dist, 0., 0., 0., 0.)

        elif init_string == 'two':
            c.Lx = Lx
            c.Ly = Ly
            c.Lz = Lz

            c.add_particle(1., 5., 0., 0.4, 0., 0.)
            c.add_particle(3., 5., 0., -0.4, 0., 0.)

        elif init_string == 'eight':
            lx = 10.
            ly = 10.
            dist = lx / 5.
            vel = dist / 5.
            #c.L = Vector_3D(10., 10., 0.)
            c.Lx = 10.
            c.Ly = 10.
            c.Lz = 0.
            c.add_particle(-dist + 5, 0. + 5, 0., vel, 0., 0.)
            c.add_particle(dist + 5, 0. + 5, 0., -vel, 0., 0.)
            c.add_particle(0. + 5, dist + 5, 0., 0., -vel, 0.)
            c.add_particle(0. + 5, -dist + 5, 0., 0., vel, 0.)
            c.add_particle(dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0.,
                           -vel / sqrt(2), -vel / sqrt(2), 0.)
            c.add_particle(-dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0.,
                           vel / sqrt(2), -vel / sqrt(2), 0.)
            c.add_particle(-dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0.,
                           vel / sqrt(2), vel / sqrt(2), 0.)
            c.add_particle(dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0.,
                           -vel / sqrt(2), vel / sqrt(2), 0.)

        elif init_string == 'eight-zeros':
            lx = 10.
            ly = 10.
            dist = lx / 5.
            vel = dist / 5.
            #c.L = Vector_3D(10., 10., 0.)
            c.Lx = 10.
            c.Ly = 10.
            c.Lz = 0.
            c.add_particle(-dist + 5, 0. + 5, 0., 0., 0., 0.)
            c.add_particle(dist + 5, 0. + 5, 0., 0., 0., 0.)
            c.add_particle(0. + 5, dist + 5, 0., 0., 0., 0.)
            c.add_particle(0. + 5, -dist + 5, 0., 0., vel, 0.)
            c.add_particle(dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0., 0., 0.,
                           0.)
            c.add_particle(-dist / sqrt(2) + 5, dist / sqrt(2) + 5, 0., 0., 0.,
                           0.)
            c.add_particle(-dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0., 0.,
                           0., 0.)
            c.add_particle(dist / sqrt(2) + 5, -dist / sqrt(2) + 5, 0., 0., 0.,
                           0.)

        elif init_string == 'square_lattice':
            N = 8  # Particles per row
            Lx = 8.
            Ly = sqrt(3) / 2. * Lx
            #c.Ly = c.Lx       # Extents determined by Lx input
            # TODO: set L
            #c.L = Vector_3D(30., 30., 0.)
            c.Lx = 9.
            c.Ly = 9.
            c.Lz = 0.
            d = 2.**(1 / 6.)  # Particle diameter
            x = np.linspace(d / 2, Lx - d / 2, N)
            y = np.linspace(d / 2., Lx - d / 2, N)
            for i in range(x.size):
                for j in range(y.size):
                    c.add_particle(x[i], y[j], 0., 0., 0., 0.)
                    #c.addParticle(x, y, z, vx, vy, ax, ay, mass)

        elif init_string == 'tri_lattice':
            Lx = 8.
            N = 8  # particles per row
            Ly = sqrt(3) / 2. * Lx  # Set this based on Lx
            #c.L = Vector_3D(Lx, Ly, 0.)
            c.Lx = Lx
            c.Ly = Ly
            d = 2.**(1 / 6.)  # diameter
            x = np.linspace(-c.Lx / 2 + 3. * d / 4., c.Lx / 2. - 1. * d / 4.,
                            N)  # Unstaggered
            xs = np.linspace(-c.Lx / 2 + d / 4., c.Lx / 2. - 3. * d / 4.,
                             N)  # Staggered
            y = np.linspace(-c.Ly / 2 + d / 2., c.Ly / 2 - d / 2, N)

            for i in range(N):
                for j in range(N):
                    if np.mod(i, 2) == 0:
                        #c.addParticle(x[j],y[i],0,0,0,0,1)
                        c.add_particle(x[j], y[i], 0., 0., 0., 0.)
                    else:
                        #c.addParticle(xs[j],y[i],0,0,0,0,1)
                        c.add_particle(xs[j], y[i], 0., 0., 0., 0.)

        elif init_string == 'prob3':
            N = 64
            #Lx = 8.
            #Ly = sqrt(3) / 2. * Lx
            Lx = 15.
            Ly = 15.
            c.Lx = Lx
            c.Ly = Ly
            c.Lz = 0.

            for i in range(N):
                x = np.random.random_sample() * Lx
                y = np.random.random_sample() * Ly
                print "x: " + str(x)
                print "y: " + str(y)

                c.add_particle(x, y, 0., 0., 0., 0.)
                print c.x
                print c.y

        elif init_string == 'proj1':
            cFloor = 100
            cSled = 13
            a = 2**(1 / 6)
            Lx = 100 * a
            Ly = 20 * a
            c.Lx = Lx
            c.Ly = Ly
            c.Lz = 0.

            # set up floor values
            xFloor = np.linspace(a / 2, Lx - a / 2, cFloor)
            yFloor = 1.

            # set up the bottom of the sled
            xSledBot = np.linspace(a, (2 * np.ceil(cSled) - 1) * a,
                                   np.ceil(cSled))
            ySledBot = 1 + a

            # set up the top of the sled
            xSledTop = np.linspace(2 * a, 2 * np.floor(cSled) * a,
                                   np.floor(cSled))
            ySledTop = 1 + a + np.sqrt(3) * a

            for i in range(cFloor):
                c.add_particle(xFloor[i], yFloor, 0., 0., 0., 0., 1.)

            for i in range(cSled):
                if i % 2:
                    c.add_particle(xSledTop[(i - 1) / 2], ySledTop, 0., 0., 0.,
                                   0.)
                else:
                    c.add_particle(xSledBot[i / 2], ySledBot, 0., 0., 0., 0.)

        self.c = c