Exemplo n.º 1
0
    def frames():
        camera = cv2.VideoCapture(Camera.video_source)
        if not camera.isOpened():
            raise RuntimeError('Could not start camera.')

        cvt = CVThread()
        cvt.start()

        while True:
            # read current frame
            _, img = camera.read()

            if Camera.modeSelect == 'none':
                switch.switch(1, 0)
                cvt.pause()
            else:
                if cvt.CVThreading:
                    pass
                else:
                    cvt.mode(Camera.modeSelect, img)
                    cvt.resume()
                try:
                    img = cvt.elementDraw(img)
                except:
                    pass

            # encode as a jpeg image and return it
            if cv2.imencode('.jpg', img)[0]:
                yield cv2.imencode('.jpg', img)[1].tobytes()
Exemplo n.º 2
0
  def __call__ (self, val):
    tp = val.type

    try:
      switch(tp.code)
    except (case(gdb.TYPE_CODE_VOID)):
      return None
    except (case(gdb.TYPE_CODE_REF), case(gdb.TYPE_CODE_PTR)):
      tp = tp.target()
    except (case(gdb.TYPE_CODE_TYPEDEF)):
      tp = tp.unqualified().strip_typedefs()
    except:
      pass

    if (tp.code == gdb.TYPE_CODE_VOID):
      return None

    tp = tp.unqualified().strip_typedefs()
    self.typename = tp.tag
 
    if self.typename is not None:
      if self.printers.has_key(self.typename):
        return self.printers[self.typename](val)
      else:
        for f in self.regexPrinters:
          if f.search(self.typename):
            return self.regexPrinters[f](val)

    return None
Exemplo n.º 3
0
def bridge_connect(args):
    global s
    print(args)
    if len(args) == 0:
        ip_address = None
    else:
        ip_address = args[0]

    if ip_address is not None:
        s = switch(ip_address)
        if not s.valid:
            s = None
            error(
                "Error: Bridge connection is invalid. Resetting switch to None."
            )
        else:
            write_data = {"ip_address": str(ip_address)}
            with open('./widgets/configs/hue.json', 'w') as hue_config:
                json.dump(write_data, hue_config)
    else:
        with open('./widgets/configs/hue.json') as hue_config:
            read_data = json.load(hue_config)
            if 'ip_address' in read_data and read_data[
                    'ip_address'] is not None:
                ip_address = read_data['ip_address']
                # write_data = {"ip_address" : str(ip_address)}
                s = switch(ip_address)
                if not s.valid:
                    s = None
                    error(
                        "Error: Bridge connection is invalid. Resetting switch to None."
                    )
Exemplo n.º 4
0
 def call_Switch_1(event):
     global Switch_1
     if Switch_1 == 0:
         switch.switch(1, 1)
         Switch_1 = 1
     else:
         switch.switch(1, 0)
         Switch_1 = 0
Exemplo n.º 5
0
 def call_Switch_3(event):
     global Switch_3
     if Switch_3 == 0:
         switch.switch(3, 1)
         Switch_3 = 1
     else:
         switch.switch(3, 0)
         Switch_3 = 0
Exemplo n.º 6
0
 def call_Switch_2(event):
     global Switch_2
     if Switch_2 == 0:
         switch.switch(2, 1)
         Switch_2 = 1
     else:
         switch.switch(2, 0)
         Switch_2 = 0
Exemplo n.º 7
0
    def declareAction(self, data, isBet=False):
        self.initAction(data)
        amount = 0
        action = Action.Check

        for case in switch(self.stage):
            if case(Stage.PreFlop):
                withPreFlop(data)
                break
            if case(Stage.Flop):
                withFlop(data)
                break
            if case(Stage.Turn):
                withTurn(data)
                break
            if case(Stage.River):
                withRiver(data)
                break
            if case(Stage.HandOver):
                print('game over')
                break

        self.updateBetChips(action, amount)

        return super(CardCountingBot, self).declareAction(data, isBet)
Exemplo n.º 8
0
 def readMainChunk(self, bytes):
     header = Chunks.ChunkHeader()
     while bytes > 0:
         self.readChunkHeader(header)
         for case in switch(header.chunk_id):
             if case(_3DS.M3D_VERSION):
                 self.version = self.file.readInt()
                 print 'Version: %d' %(self.version)
                 break
             if case(_3DS.EDITOR_CHUNK):
                 if self.object == None:
                     break
                 self.object.materials = []
                 self.object.meshes = []
                 print " Editor Chunk"
                 self.readObjectChunk(header.chunk_length - 6)
                 break
             if case(_3DS.KEYFRAME_CHUNK):
                 if self.keyframe == None:
                     break
                 print " Key Frame"
                 self.readKeyframeChunk(header.chunk_length - 6)
                 break
             if case():
                 print ' Skip unknown %X subchunk' %(header.chunk_id)
         self.file.seek(header.start_position + header.chunk_length, os.SEEK_SET)
         bytes = self.updateBytesToRead(bytes, header.chunk_length)
Exemplo n.º 9
0
    def main(self):
        with open( args.file ) as fh:
            for idx,line in enumerate(fh):
                #if idx==54849:
                    #time.sleep(30)
                self.writelog("{0:5d}th:{1}".format(idx,line[:-1]))
                #print line
                for case in switch(line[23:29]):
                    if case('030201'):
                        self.L01(line)
                        break
                    if case('030203'):
                        self.L03(line)
                        break
                    if ( case('030301') | case('030302') | case('030303') | case('030801') | case('030802') | case('030401')):
                        self.OtherProtocol(line)
                        #time.sleep(0.1)
                        break
                    if case(): # default, could also just omit condition or 'if True'
                        self.writelog("Something wrong!!!")
                        print "Something wrong!!!"

        for key, value in self.user_sockets.iteritems():
            print "{0}:{1}".format(key,value)
            value.shutdown(socket.SHUT_RDWR)
            value.close()
Exemplo n.º 10
0
 def readObjectChunk(self, bytes):
     header = Chunks.ChunkHeader()
     while bytes > 0:
         self.readChunkHeader(header)
         for case in switch(header.chunk_id):
             if case(_3DS.MESH_VERSION):
                 self.object.version = self.file.readInt()
                 print "  Mesh Version: %d" %(self.object.version)
                 break
             if case(_3DS.MATERIAL_BLOCK):
                 print "  Material"
                 self.readMaterialChunk(header.chunk_length - 6)
                 break
             if case(_3DS.MASTER_SCALE):
                 self.object.masterScale = self.file.readFloat()
                 print "  Master scale: %.2f" %(self.object.masterScale)
                 break
             if case(_3DS.AMBIENT_LIGHT):
                 print "  Ambient light: "
                 self.object.ambientLight = self.readFloatColor()
                 break;
             if case(_3DS.MESH):
                 print "  Mesh"
                 self.readMeshChunk(header.chunk_length - 6)
                 break
             if case():
                 print "  Skip unknown %X subchunk" %(header.chunk_id)
         self.file.seek(header.start_position + header.chunk_length, os.SEEK_SET)
         bytes = self.updateBytesToRead(bytes, header.chunk_length)
Exemplo n.º 11
0
def login(request):
    global Switch
    Switch = switch()
    html = loader.get_template('frontend/index.html')
    backupCards = backupFolder.objects.all()
    context = {'backupCards': backupCards}
    return HttpResponse(html.render(context, request))
Exemplo n.º 12
0
    def get_query_string(self, filter_prefix='filter'):
        query_string = '?'

        for param in self.params:
            for case in switch(param['query_type']):
                if case('between'):
                    layout = '{}[where][{}][{}][0]={}&{}[where][{}][{}][1]={}&'
                    query_string += layout.format(
                        filter_prefix, param['property_name'],
                        param['query_type'], param['query_value'][0],
                        filter_prefix, param['property_name'],
                        param['query_type'], param['query_value'][1])
                    break
                if case('where'):
                    query_string += '{}[{}][{}]={}&'.format(
                        filter_prefix, param['query_type'],
                        param['property_name'], param['query_value'])
                    break
                # ex. filter[where][name][inq]=foo&filter[where][name][inq]=bar
                if case('inq'):
                    for item in param['query_value']:
                        query_string += '{}[where][{}][inq]={}&'.format(
                            filter_prefix, param['property_name'], item)
                    break
                if case('neq'):
                    query_string += '{}[where][{}][neq]={}&'.format(
                        filter_prefix, param['property_name'],
                        param['query_value'])
                    break
                if case():
                    # default, could also just omit condition or 'if True'
                    print('huh?')
        return query_string
Exemplo n.º 13
0
 def readFacesChunk(self, bytes):
     faces = Chunks.FacesChunk()
     faces.nrOfFaces = self.file.readShort()
     faces.flags = []
     faces.faces = []
     faces.materialGroups = []
     for i in range(0, faces.nrOfFaces):
         faces.faces.append(self.file.readArray(3, 'H'))
         faces.flags.append(self.file.readShort())
     print "    Number of faces: %d" %(faces.nrOfFaces)
     bytes = bytes - faces.nrOfFaces*8 + 2
     header = Chunks.ChunkHeader()
     while bytes > 0:
         self.readChunkHeader(header)
         for case in switch(header.chunk_id):
             if case(_3DS.MESH_MATERIAL_GROUP):
                 group = Chunks.MaterialGroupChunk()
                 group.materialName = self.readName()
                 group.nrOfFaces = self.file.readShort()
                 group.faces = self.file.readArray(group.nrOfFaces, 'H')
                 print "    Mesh Group"
                 print "     Material name: %s" %(group.materialName)
                 print "     Number of faces: %d" %(group.nrOfFaces)
                 faces.materialGroups.append(group)
                 break
             if case(_3DS.SMOOTHING_GROUP_LIST):
                 faces.smoothingList = self.file.readArray(faces.nrOfFaces, 'l')
                 print "    Face Smoothing Group"
                 break
             if case():
                 print "    Skip unknown %X subchunk" %(header.chunk_id)
         self.file.seek(header.start_position + header.chunk_length, os.SEEK_SET)
         bytes = self.updateBytesToRead(bytes, header.chunk_length)
     return faces
Exemplo n.º 14
0
 def assign_value(self, name, value):
     for case in switch(name):
         if case('Name'):
             self.Name = value
             break
         if case('Rarity'):
             self.Rarity = value
             break
         if case('Subtype'):
             self.Subtype = value
             break
         if case('Class'):
             self.Class = value
             break
         if case('Cost'):
             self.Cost = value
             break
         if case('Atk'):
             self.Atk = value
             break
         if case('HP'):
             self.HP = value
             break
         if case('Description'):
             self.Description = value
             break
         if case('Type'):
             self.Type = value
             break
Exemplo n.º 15
0
    def get_query_string(self, filter_prefix="filter"):
        query_string = "?"

        for param in self.params:
            for case in switch(param['query_type']):

                if case('between'):
                    query_string += "{}[where][{}][{}][0]={}&{}[where][{}][{}][1]={}&".format(
                        filter_prefix, param['property_name'],
                        param['query_type'], param['query_value'][0],
                        filter_prefix, param['property_name'],
                        param['query_type'], param['query_value'][1])
                    break
                if case('where'):
                    query_string += "{}[{}][{}]={}&".format(
                        filter_prefix, param['query_type'],
                        param['property_name'], param['query_value'])
                    break
                if case('neq'):
                    query_string += "{}[where][{}][neq]={}&".format(
                        filter_prefix, param['property_name'],
                        param['query_value'])
                    break
                if case(
                ):  # default, could also just omit condition or 'if True'
                    print "huh?"
        return query_string
Exemplo n.º 16
0
    def create(name, bytes, width, height, target, format, param, settings):
        glID = (GLuint)(*[])
        glGenTextures(1, glID)
        glBindTexture(target, glID)
	
	hasMipMaps = param.interpolateMode != Texture.BILINEAR_NO_MIPMAP and \
                     param.interpolateMode != Texture.NEAREST_NO_MIPMAP
	if hasMipMaps and param.autoGenerateMipMaps:
            glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE)

        for case in switch(target):
            if case(Texture.TEXTURE_1D):
		break
	    if case(Texture.TEXTURE_2D):
		if hasMipMaps and not param.autoGenerateMipMaps:
		    gluBuild2DMipmaps(target, format.internalFormat, width, height, format.format, format.dataFormat, bytes)
		else:
                    glTexImage2D(target, 0, format.internalFormat, width, height, 0, format.format, format.dataFormat, bytes)
		break
	    if case(Texture.TEXTURE_3D):
		glTexImage3DEXT(target, 0, format.internalFormat, width, height, depth, 0, format.format, format.dataFormat, bytes)
		break
	    if case(Texture.TEXTURE_CUBE_MAP):
		break
	    if case(Texture.TEXTURE_RECTANGLE):
		break
        return Texture(name, glID, target, format, param)
Exemplo n.º 17
0
 def key_map_dict(key):
     for case in switch(key):
         if case('cm'):
             return 'cmap'
             break
         if case('cms'):
             return 'cmaps'
             break
         if case('a'):
             return 'alpha'
             break
         if case('conn') \
         or case('density'):
             return 'conn_density'
             break
         if case('conn_c'):
             return 'conn_colors'
             break
         if case('conn_a'):
             return 'conn_alpha'
             break
         if case('ec'):
             return 'edgecolor'
             break
         if case('c'):
             return 'color'
             break
         if case('default'): return key
Exemplo n.º 18
0
 def img_hist_type_map_dict(type_):
     for case in switch(type_):
         if case('weights') \
             or case('bias') \
             or case('data') \
             or case('logits'):
             return type_
             break
         if case('weight') \
             or case('W') \
             or case('w'):
             return 'weights'
             break
         if case('bia') \
             or case('b'):
             return 'bias'
             break
         if case('Data') \
             or case('D') \
             or case('d'):
             return 'data'
             break
         if case('logit') \
             or case('outputs') \
             or case('output') \
             or case('f'):
             return 'logits'
             break
         if case('default'):
             raise ValueError('Invalid `type` argument of `hist_plot`'\
                              ' or `image_plot`: %s' % type_)
Exemplo n.º 19
0
 def load(self):
     for case in switch(self.format):
         if case(Image.Format.BMP):
             bitmap = Bitmap(self.file)
             self.width = bitmap.width
             self.height = bitmap.height
             self.data = bitmap.data.tolist()
Exemplo n.º 20
0
def processMsg(self, cmdId, msg, args):
    nodeStatus = args['nodeStatus']
    comm = args['comm']

    if len(msg) > 0:
        # Parse command header
        header = deserialize(msg, cmdId, 'header')
        if header != None:
            # Check for command counter
            cmdStatus = checkCmdCounter(self, header, msg, comm)
            if cmdStatus == False:  # old command counter
                return

        # Parse message contents
        try:
            msgContents = deserialize(msg, cmdId, 'body')
            if msgContents == None:
                return
        except KeyError:
            print("Invalid command ID.")
            return

        # Process message by command id
        for case in switch(cmdId):
            if case(TestCmds['SendDataBlock']):
                if header['sourceId'] == 0:  # message from GCS (node 0)
                    if msgContents[
                            'destId'] == self.nodeParams.config.nodeId:  # command is for this node
                        print("Send Block Data command received")
                        comm.sendDataBlock(b'1234567890' *
                                           100)  # start block transfer process
                break
Exemplo n.º 21
0
 def readMeshChunk(self, bytes):
     mesh = Chunks.MeshChunk()
     mesh.name = self.readName()
     print "   Name: %s" %(mesh.name)
     bytes = bytes - (len(mesh.name) - 1)
     header = Chunks.ChunkHeader()
     while bytes > 0:
         self.readChunkHeader(header)
         for case in switch(header.chunk_id):
             if case(_3DS.MESH_DATA):
                 mesh.type = 1
                 print "   Mesh data"
                 mesh.data = self.readMeshData(header.chunk_length - 6)
                 break
             if case(_3DS.LIGHT):
                 mesh.type = 2
                 print "   Light"
                 mesh.light = self.readLightChunk(header.chunk_length - 6)
                 break
             if case(_3DS.CAMERA):
                 mesh.type = 3
                 print "   Camera"
                 mesh.camera = self.readCameraChunk(header.chunk_length - 6)
                 break
             if case():
                 print "   Skip unknown %X subchunk" %(header.chunk_id)
         self.file.seek(header.start_position + header.chunk_length, os.SEEK_SET)
         bytes = self.updateBytesToRead(bytes, header.chunk_length)
     self.object.meshes.append(mesh)
Exemplo n.º 22
0
    def __init__params(self):
        """
        `W`: coefficients_for_all_dimension_in_next_space
        len of `fp_transformation`: quantity_of_variable_term
        `b`: constant_coefficient_for_all_dimension_in_next_space
        """
        W_shape = len(
            self.fp_transformation), self.config.space_mapping_process[1]
        b_shape = self.config.space_mapping_process[1],

        for case in switch(self.config.params_init):
            if case('identity'):
                self.W = np.zeros(W_shape)
                self.W[np.diag_indices(min(W_shape))] = 1
                self.b = np.zeros(b_shape)
                break
            if case('normal') \
            or case(np.random.normal):
                self.W = np.random.normal(size=W_shape)
                self.b = np.zeros(b_shape)
                break
            if case('random') \
            or case(np.random.random):
                self.W = np.random.random(W_shape)
                self.b = np.random.random(b_shape)
                break
            if case('ones') \
            or case(np.ones):
                self.W = np.ones(W_shape)
                self.b = 0.1 * np.ones(b_shape)
                break
            if case('defaults'):
                raise ValueError('illegal params initializer: %s!' %
                                 self.config.params_init)
Exemplo n.º 23
0
def sampling(sampling_style, data_style='numpy', sampling_magnitude=5):
    """
    :param sampling_magnitude:
        [int] this can be viewed as 'an adaptive sample size', which is \
        generated according to the `sampling_style` and feature dimension.
    """
    for case in switch(sampling_style):
        #         print(sampling_style)
        """ do remember write the `break`!!!!!!! """
        if case('quadratic'):
            x = np.linspace(-1, 1, sampling_magnitude)
            result = np.column_stack([x, 0.5 * np.sin(3.1 * (x - 0.5))])
            break
        if case('square'):
            #             if data_style == 'numpy':
            result = np.column_stack([
                np.repeat(np.linspace(-1, 1, sampling_magnitude), \
                          sampling_magnitude),
                np.tile(np.linspace(-1, 1, sampling_magnitude), \
                        sampling_magnitude),
            ])
            #                 .reshape(sampling_magnitude, sampling_magnitude, 2)
            #             elif data_style == 'matplotlib':
            #                 return np.mgrid[-1:1:2/sampling_magnitude, -1:1:2/sampling_magnitude]
            #             else:
            #                 raise AssertionError('illegal data style!')
            break
        if case('line'):
            result = np.column_stack([
                np.zeros(sampling_magnitude),
                np.linspace(-1, 1, sampling_magnitude)
            ])
            break
        if case('random'):
            result = np.random.random((sampling_magnitude, 2))
            break
        if case('default'):
            raise AssertionError('illegal sampling style!')
    for case in switch(data_style):
        if case('numpy'):
            return result
            break
        if case('matplotlib'):
            return result.T
            break
        #                 return np.stack((result[..., 0], result[..., 1]))
        if case('default'): raise AssertionError('illegal data style!')
Exemplo n.º 24
0
 def toString(self):
     for case in switch(self.format):
         if case(GL_RGB): return "RGB"
         if case(GL_RGBA): return "RGBA"
         if case(GL_ALPHA): return "A"
         if case(GL_LUMINANCE): return "L"
         if case(GL_LUMINANCE_ALPHA): return "LA"
         if case(GL_DEPTH_COMPONENT): return "DEPTH"
Exemplo n.º 25
0
def test_can_switch_on_string():
    with switch("yolo") as case:
        case("aosdk", 1)
        case("askdoska", 2)
        case("asodaodki", 3)
        case("yolo", 666)
        case("asdksoa", 4)
        assert case.result == 666
Exemplo n.º 26
0
def test_can_switch_on_int():
    with switch(666) as case:
        case(1, "one")
        case(2, "two")
        case(666, "number of the beast")
        result = case.result

    assert result == "number of the beast"
Exemplo n.º 27
0
def test_can_use_lambdas_as_when():
    SHRUG = r"¯\_(ツ)_/¯"
    y = object()
    with switch(y) as case:
        case(lambda: isinstance(y, str), "Some characters")
        case(lambda: isinstance(y, int), "Numberzzzz")
        case(lambda: isinstance(y, float), "Why u not double?")
        case.default(SHRUG)
        assert case.result == SHRUG
Exemplo n.º 28
0
 def readMeshData(self, bytes):
     data = Chunks.MeshData()
     header = Chunks.ChunkHeader()
     while bytes > 0:
         self.readChunkHeader(header)
         for case in switch(header.chunk_id):
             if case(_3DS.VERTICES_LIST):
                 data.vertices = []
                 data.nrOfVertices = self.file.readShort()
                 for i in range(0, data.nrOfVertices):
                     data.vertices.append(self.file.readArray(3, 'f'))
                 print "    Number of vertices: %d" %(data.nrOfVertices)
                 break
             if case(_3DS.MAPPING_COORDINATES_LIST):
                 data.nrOfCoordinates = self.file.readShort()
                 data.coordinates = []
                 for i in range(0, data.nrOfCoordinates):
                     data.coordinates.append(self.file.readArray(2, 'f'))
                 print "    Number of map coordinates: %d" %(data.nrOfCoordinates)
                 break
             if case(_3DS.FACES_DESCRIPTION):
                 data.faces = self.readFacesChunk(header.chunk_length - 6)
                 break
             if case(_3DS.LOCAL_COORDINATES_SYSTEM):
                 print "    Mesh Matrix: "
                 data.matrix = self.file.readArray(12, 'f')
                 for i in range(0, 4):
                     print "     %.2f %.2f %.2f" %(data.matrix[i*3], data.matrix[i*3+1], data.matrix[i*3+2])
                 break
             if case(_3DS.MESH_COLOR):
                 data.color = self.file.readByte()
                 print "    Mesh color: %d" %(data.color)
                 break
             if case(_3DS.MESH_TEXTURE_INFO):
                 data.textureInfo = Chunks.TextureInfoChunk()
                 data.textureInfo.mapType = self.file.readShort()
                 data.textureInfo.tiling = self.file.readFloat()
                 data.textureInfo.icon = self.file.readFloat()
                 data.textureInfo.matrix = self.file.readArray(12, 'f')
                 data.textureInfo.planIconW = self.file.readFloat()
                 data.textureInfo.planIconH = self.file.readFloat()
                 data.textureInfo.cylIconH = self.file.readFloat()
                 print "    Mesh Texture info"
                 break
             if case(_3DS.BOX_MAP):
                 print "    Box Map"
                 data.mapMaterials = []
                 for i in range(0, 6):
                     data.mapMaterials.append(self.readName())
                     print "     %s" %(data.mapMaterials[i])
                 break
             if case():
                 print "    Skip unknown %X subchunk" %(header.chunk_id)
         self.file.seek(header.start_position + header.chunk_length, os.SEEK_SET)
         bytes = self.updateBytesToRead(bytes, header.chunk_length)
     return data
Exemplo n.º 29
0
    def frames():
        global ImgIsNone
        camera = cv2.VideoCapture(Camera.video_source)
        if not camera.isOpened():
            raise RuntimeError('Could not start camera.')

        cvt = CVThread()
        cvt.start()

        while True:
            # read current frame
            _, img = camera.read()
            if img is None:
                if ImgIsNone == 0:
                    print(
                        "The camera has not read data, please check whether the camera can be used normally."
                    )
                    print(
                        "Use the command: 'raspistill -t 1000 -o image.jpg'. Close the self-starting program webServer.py"
                    )
                    print(
                        "Use the command: 'raspistill -t 1000 -o image.jpg' to check whether the camera can be used correctly."
                    )
                    ImgIsNone = 1
                continue

            if Camera.modeSelect == 'none':
                switch.switch(1, 0)
                cvt.pause()
            else:
                if cvt.CVThreading:
                    pass
                else:
                    cvt.mode(Camera.modeSelect, img)
                    cvt.resume()
                try:
                    img = cvt.elementDraw(img)
                except:
                    pass

            # encode as a jpeg image and return it
            if cv2.imencode('.jpg', img)[0]:
                yield cv2.imencode('.jpg', img)[1].tobytes()
Exemplo n.º 30
0
def usage(option):
    """ Usage function """
    print "\nUSAGE: " + option + "\n"
    for case in switch(option):
        if case('default'):
            print """
                ./rds_boto_code.py create-db-instance
                ./rds_boto_code.py delete-db-instance <dbname>
                ./rds_boto_code.py list-db-instances
            """
        break
Exemplo n.º 31
0
  def to_string(self):
    if self.kwargs is None:
      return self.to_string_short()
    
    if self.kwargs.has_key('print-control-parameter'):
      pcp = self.kwargs['print-control-parameter']
      try:
        verbose = gdb.parameter(pcp)
      except error:
        verbose = 'short'
    else:
      verbose = 'short'

    try:
      switch(pcp)
    except ( case('long') ):
      return self.to_string_long()
    except ( case('detailed') ):
      return self.to_string_detailed()
    except:
      return self.to_string_short()
Exemplo n.º 32
0
def test_can_use_lambdas_in_both_when_and_then():
    def raise_():
        raise_.called = True
        raise ValueError

    raise_.called = False

    with switch(666) as case:
        case(lambda x: x % 777 == 0, lambda: 777)
        case(lambda: False, raise_)
        case(lambda x: x == 666, lambda: "YEAH!")
        assert case.result == "YEAH!" and raise_.called is False
Exemplo n.º 33
0
def clientMsgDealHandler(worker, identity, args, config):
	if not isinstance(args, dict) or not args.has_key('cmd'):
		return
	for case in switch(args['cmd']):
		if case('heart'):
			heartDealHandler(worker, identity, args, config)
			break
		if case('execute'):
			commandDealHandler(worker, args, identity)
			break
		if case(''):
			tprint("Error cmd", args)
Exemplo n.º 34
0
 def readColor(self):
     header = Chunks.ChunkHeader()
     self.readChunkHeader(header)
     for case in switch(header.chunk_id):
         if case(_3DS.COLOR_24) or case(_3DS.LIN_COLOR_24):
             color = self.file.readArray(3, 'B')
             print color
             break
         if case():
             print "    Skip unknown %X subchunk" %(header.chunk_id)
     self.file.seek(header.start_position + header.chunk_length, os.SEEK_SET)
     return color
Exemplo n.º 35
0
 def dataType(self):
     for case in switch(self.dataFormat):
         if case(GL_UNSIGNED_SHORT):
             return GLushort
         if case(GL_UNSIGNED_INT):
             return GLuint
         if case(GL_FLOAT):
             return GLfloat
         if case(GL_UNSIGNED_BYTE):
             return GLubyte
         if case(GL_BYTE):
             return GLbyte
Exemplo n.º 36
0
def parse_torrent(file):
    dot_torrent = file
    with open(file, "rb") as f:
        content = f.read()

        # data = decoder.decode(content)

        torrent = bdecode(content)
        # hash = gutils.sha1("bencode(torrent['info'])")
        hash = gutils.sha1(file)


        torrent_name = torrent['info']['name']

        try:
            files = torrent['info']['files']
        except KeyError:
            # return {
            #     'name': torrent_name
            # }
            files = [{'path': [torrent_name]}]
        # print files
        counter = populate_counter()
        report_files = []
        for file in files:

            fname = '/'.join(file['path'])
            report_files.append(fname)
            if not is_ignored(fname):
                cat = file_cat(fname)
                counter['globl'] += 1

                counter[cat] += 1

                for case in switch(cat):
                    if case(MUSIC_CAT):
                        break
                    if case():
                        break

        without_unk = removekey(counter, UNKNOWN_CAT, 'globl')
        most_matched_cat = max(without_unk, key=without_unk.get)
        if counter[most_matched_cat] == 0:
            most_matched_cat = 'misc'
        return {
            'matched': counter[most_matched_cat],
            'total': counter['globl'],
            'assumed_category': most_matched_cat,
            'name': torrent_name,
            'files': report_files,
            'source': dot_torrent,
            'info_hash': hash
        }
Exemplo n.º 37
0
    def processNodeCommands(self, comm):
        """Performs initial processing of incoming commands and messages from the mesh network."""

        for cmdId in list(comm.cmdQueue.keys()):  # New commands to process
            cmdContents = comm.cmdQueue.pop(cmdId)
            for case in switch(cmdId):
                if case(NodeCmds['ConfigRequest']):
                    configHash = self.nodeParams.config.calculateHash()
                    if configHash == cmdContents:
                        self.nodeParams.configConfirmed = True
                    else:
                        self.nodeParams.configConfirmed = False
                    break
Exemplo n.º 38
0
def adminMsgDealHandler(worker, identity, args):
	if not isinstance(args, dict) or not args.has_key('cmd') or not args.has_key('vod_identitys'):
		tprint('worker:%s' %(multiprocessing.current_process().name), "cmd_ret(from %s):%s" %(identity, args), "Error:adminMsgDealHandler params error")
		return
	for case in switch(args['cmd']):
		if case('update'):
			adminPushMsg(worker, args)	
			break
		if case('execute'):
			adminPushMsg(worker, args)	
			break
		if case(''):
			tprint("Error cmd", args)
Exemplo n.º 39
0
def test_can_use_functions_as_when():
    def one(x):
        one.called = True
        return x == 1

    def two(x):
        two.called = True
        return x == 2

    with switch(2) as case:
        case(one, 10)
        case(two, 20)
        assert case.result == 20 and two.called
Exemplo n.º 40
0
 def readFloatColor(self):
     percent = 0
     header = Chunks.ChunkHeader()
     self.readChunkHeader(header)
     for case in switch(header.chunk_id):
         if case(_3DS.FLOAT_PERCENTAGE):
             percent = self.file.readFloat()
             print percent
             break
         if case():
             print "    Skip unknown %X subchunk" %(header.chunk_id)
     self.file.seek(header.start_position + header.chunk_length, os.SEEK_SET)
     return percent
Exemplo n.º 41
0
def usage(option):
    """ Usage function """
    print "\nUSAGE: " + option + "\n"
    for case in switch(option):
        if case('default'):
            print("""
                Options are: ./ec2_instance <option>
                create_instance
                delete_instance
                query_instances
                control_instances
            """)
        break
Exemplo n.º 42
0
 def data_of_stock(self, stock):
     '''
     get data info of a stock from xueqiu
     '''
     code = stock[0]
     market = stock[1]
     
     for key in self._config:
         print key
         val = self._config[key]
         print val
         for case in switch(val['type']):
             url = val['url']
             if case(1):
                 url = url
             elif case(2):
                 stock = market+code
                 # url.replace("\%\s\%\s", stock)
                 url = url%(stock)
             elif case(3):
                 print url%('yonghu123123')
                 # user info pass first
                 print 'user info pass first'
                 break
             elif case(4):
                 print url%('ZHZHZH')
                 print 'zuhe info pass first'
                 break
             elif case(5):
                 url = url
             # deal the data
             print 'url: ' + url
             func_name = key
             file_path = path + func_name
             print "get " + file_path
             html = self._get_html(url)
             if self._check_token(html):
                 ## everything is OK
                 self._save(file_path, html)
             else:
                 ## Have a problem that xueqiu find the IP evil
                 s_t = random.random()*60
                 print time.time()
                 time.sleep(s_t)
                 print time.time()
                 self.data_of_stock(stock)
                 print 'Token Error'
                 return 'Error'
             # print html
             
             break
Exemplo n.º 43
0
    def main(self):
        t_fmt = '%d/%m/%Y %H:%M:%S' # format of time stamps
        nowdatetimestr=time.strftime("%d/%m/%Y %H:%M:%S")
        print "Now:{0}".format(nowdatetimestr)
        todaydate=time.strftime("%d/%m/%Y")
        shiftsec=0
        chronological_flag=False

        with open( args.file ) as fh:
            lastlogtime="" #keep last log time for comparing
            for idx,line in enumerate(fh):
                self.writelog("{0}th:{1}".format(idx,line[:-1]))
                if(lastlogtime!=line[2:10]):
                    logtime=datetime.datetime.strptime(todaydate+' '+line[2:10], t_fmt)
                    #print "logtime={0}".format(logtime)
                    lastlogtime=line[2:10]
                    if(chronological_flag == False):
                        if(lastlogtime >= "09:00:00"):
                            chronological_flag=True 
                    else:
                        delta=datetime.datetime.now()-logtime
                        if(shiftsec==0):
                            shiftsec=delta.total_seconds()
                            delta=datetime.datetime.now()-logtime
                            print "shiftsec={0}".format(shiftsec)
                        total_seconds=delta.total_seconds()-shiftsec
                        if(total_seconds<0):
                            print "sleep {0}".format(total_seconds)
                            time.sleep(-1*total_seconds)
                        if(lastlogtime >= "15:00:00"):
                            chronological_flag=False
                #os.system('read -p "Press any key to continue"') #linux
                #print line
                for case in switch(line[23:29]):
                    if case('030201'):
                        self.L01(line)
                        break
                    if case('030203'):
                        self.L03(line)
                        break
                    if ( case('030301') | case('030302') | case('030303') | case('030801') | case('030802') | case('030401')):
                        self.OtherProtocol(line)
                        break
                    if case(): # default, could also just omit condition or 'if True'
                        self.writelog("Something wrong!!!")
                        print "Something wrong!!!"

        for key, value in self.user_sockets.iteritems():
            print "{0}:{1}".format(key,value)
            value.shutdown(socket.SHUT_RDWR)
            value.close()
Exemplo n.º 44
0
 def fromString(string):
     for case in switch(string):
         if case("RGB"):
             return TextureFormat.create(GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE, 3)
         if case("RGBA"):
             return TextureFormat.create(GL_RGBA, GL_RGBA8, GL_UNSIGNED_BYTE, 4)
         if case("A"):
             return TextureFormat.create(GL_ALPHA, GL_ALPHA8, GL_UNSIGNED_BYTE, 1)
         if case("L"):
             return TextureFormat.create(GL_LUMINANCE, GL_LUMINANCE8, GL_UNSIGNED_BYTE, 1)
         if case("LA"):
             return TextureFormat.create(GL_LUMINANCE_ALPHA, GL_LUMINANCE8_ALPHA8, GL_UNSIGNED_BYTE, 2)
         if case("DEPTH"):
             return TextureFormat.create(GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 1)
Exemplo n.º 45
0
def option(op):
    while switch(op):
        if case(1):
            mkdir(input("Nombre del directorio: "))
            break
        if case(2):
            touch(input("Nombre del archivo: "))
            break
        if case(3):
            # TODO: Method of option 3
            # your code goes here.
            break
        if case(4):
            # TODO: Method of option 4
            # your code goes here.
            break
        if case(5):
            # TODO: Method of option 5
            # your code goes here.
            break
        if case(6):
            # TODO: Method of option 6
            # your code goes here.
            break
        if case(7):
            # TODO: Method of option 7
            # your code goes here.
            break
        if case(8):
            # TOO: Method of option 8
            # your code goes here.
            break
        if case(9):
            # TODO: Method of option 9
            # your code goes here.
            break
        if case(10):
            # TODO: Method of option 10
            # your code goes here.
            break
        if case(11):
            # TODO: Method of option 11
            # your code goes here.
            break
        if case(12):
            # TODO: Method of option 12
            # your code goes here.
            break
        print("Adios!!")
        break
Exemplo n.º 46
0
def parse_action(action):

  # st = Stemmer()
  action = action.strip().lower()

  for case in switch(action):
    if case('дополнить'):
      return action_add
    elif case('исключить'):
      return action_remove
    elif case('заменить'):
      return action_sub
    else:
      raise Exception('unknown action')
Exemplo n.º 47
0
def unpackParameter(paramId, dataLength, msg, nodeParams):
    for case in switch(paramId):
        if case(ParamId.nodeId):
            if (dataLength == 1):
                value = unpackBytes('=B', msg)[0][0]
                return nodeParams.config.updateParameter(paramId, value)
            break
        if case(ParamId.parseMsgMax):
            if (dataLength == 2):
                value = unpackBytes('=H', msg)[0][0]
                return nodeParams.config.updateParameter(paramId, value)
            break
        else:
            return False
Exemplo n.º 48
0
def functionSelect(command_input, response):
    global functionMode
    if 'scan' == command_input:
        if OLED_connection:
            screen.screen_show(5, 'SCANNING')
        if modeSelect == 'PT':
            radar_send = fuc.radarScan()
            print(radar_send)
            response['title'] = 'scanResult'
            response['data'] = radar_send
            time.sleep(0.3)

    elif 'findColor' == command_input:
        if OLED_connection:
            screen.screen_show(5, 'FindColor')
        if modeSelect == 'PT':
            flask_app.modeselect('findColor')

    elif 'motionGet' == command_input:
        if OLED_connection:
            screen.screen_show(5, 'MotionGet')
        flask_app.modeselect('watchDog')

    elif 'stopCV' == command_input:
        flask_app.modeselect('none')
        switch.switch(1, 0)
        switch.switch(2, 0)
        switch.switch(3, 0)

    elif 'police' == command_input:
        if OLED_connection:
            screen.screen_show(5, 'POLICE')
        RL.police()

    elif 'policeOff' == command_input:
        RL.pause()
        move.motorStop()

    elif 'automatic' == command_input:
        if OLED_connection:
            screen.screen_show(5, 'Automatic')
        if modeSelect == 'PT':
            fuc.automatic()
        else:
            fuc.pause()

    elif 'automaticOff' == command_input:
        fuc.pause()
        move.motorStop()

    elif 'trackLine' == command_input:
        fuc.trackLine()
        if OLED_connection:
            screen.screen_show(5, 'TrackLine')

    elif 'trackLineOff' == command_input:
        fuc.pause()
Exemplo n.º 49
0
 def setMode(self, mode):
     """Change radio operating mode (i.e. rx, tx, sleep, off)."""
     if mode != self.mode:
         for case in switch(mode):
             if case(RadioMode.off):
                 self.setOff()
                 break
             if case(RadioMode.sleep):
                 self.setSleep()
                 break
             if case(RadioMode.receive):
                 self.setReceive()
                 break
             if case(RadioMode.transmit):
                 self.setTransmit()
                 break
Exemplo n.º 50
0
def supports(_type):
    shader = Shader.glInfo.have_extension("GL_ARB_shader_objects")
    vertex = Shader.glInfo.have_extension("GL_ARB_vertex_shader")
    fragment = Shader.glInfo.have_extension("GL_ARB_fragment_shader")
    geometry = Shader.glInfo.have_extension("GL_EXT_geometry_shader4")

    if not shader:
        return False
    for case in switch(_type):
        if case(GL_VERTEX_SHADER):
            return vertex
        if case(GL_FRAGMENT_SHADER):
            return fragment
        if case(GL_PROGRAM_OBJECT_ARB):
            return shader
        # if case(GL_GEOMETRY_SHADER_EXT): return geometry
        if case():
            return False
    def __init__(self, line, lineIdx):
        self.allLine=line
        self.idx=lineIdx
        self.lineType=str()
        self.stockId=str()
        self.timeStr=str()
        self.time13=str()
        self.time_2=str()
        self.ticketNum=str()
        self.userNum=str()
        self.orderSeq=str()
        self.price=str()
        self.isValid=True

        if line is not None:
            self.lineType=line[23:29]
            self.timeStr=line[2:17]
            self.time13=line[2:15]
            self.time_2=line[15:17]
            self.ticketNum=line[57:62]
            self.userNum=line[51:56]
            for case in switch(self.lineType):
                if ( case('030201') | case('030203') | case('030401') | case('030302') | case('030303')):
                    self.stockId="NA"
                    if (self.lineType == '030302') | (self.lineType == '030303') :
                        self.orderSeq = line[62:69]
                    elif (self.lineType == '030401'):
                        self.orderSeq = line[67:74]
                    break
                if  case('030801') : 
                    self.stockId = line[62:68]
                    self.price   = line[69:76]
                    break
                if  case('030802') :
                    self.stockId=line[62:68]
                    break
                if case('030301'):
                    self.stockId=line[78:84]
                    break
                if case(): # default, could also just omit condition or 'if True'
                    print "error, no such case!!!({0})".format(line)
print "Parsing file before comparing content...."
print "##############################################################################"
for filename in targetFileFullname:
    newtarget = newSystemLogPath + filename
    oldtarget = oldSystemLogPath + filename
    newparsed = newtarget + ".parsed"
    oldparsed = oldtarget + ".parsed"
    newpf= open(newparsed, 'w')
    oldpf= open(oldparsed, 'w')

    with open(newtarget) as f:
        new_content = f.readlines()
    with open(oldtarget) as f:
        old_content = f.readlines()

    for case in switch(filename[ filename.rindex("/")+1:]):
        if case('OrderQuote.dat'):
            print 'OrderQuote.dat'
            for line in new_content:
                print >> newpf, line[:16] + ('0' * 24) +line[40:63] + ('0' * 12) + line[75:144]+ ('0' * 12) + line[156:],
            for line in old_content:
                print >> oldpf, line[:16] + ('0' * 24) +line[28:51] + ('0' * 12) + line[63:132]+ ('0' * 12) + line[144:],
            break
        if case('EmgTrades.data'):
            print 'EmgTrades.data'
            for line in new_content:
                print >> newpf, ('0' * 8) +line[8:78] + ('0' * 16) + line[94:122] + ('0' * 4) + line[-3:],
            for line in old_content:
                #print line
                if line[126]=='Y':
                    print line
Exemplo n.º 53
0
Arquivo: test.py Projeto: knome/Hacks
# example usage of the evil python switch statement

from switch import switch

print "FIRST TEST :: Skip entries, fallthrough and escape"
with switch( 27 ) as case:
    
    if case( 1, 5, 20, 40 ):
        print "ALPHA CASE SKIPPED"
        
    if case( case.range( 1, 20 ) ):
        print "BETA CASE SKIPPED"
        
    if case( 2 ):
        print "CHARLIE CASE SKIPPED"
        
    if case( 0, 15, 27, 30 ):
        print "DELTA CASE TAKEN"
        case.fallthrough()
        
    if case( case.range( 40, 60 ) ):
        print "EPSILON FALLTHROUGH"
        case.fallthrough()
        
    if case( 0 ):
        print "FOXTROT FALLTHROUGH"
        case.fallthrough()
        
    if case( 45 ):
        print "GULF FALLTHROUGH AND ESCAPE"
Exemplo n.º 54
0
 def readTextureChunk(self, bytes):
     texture = Chunks.TextureChunk()
     header = Chunks.ChunkHeader()
     while bytes > 0:
         self.readChunkHeader(header)
         for case in switch(header.chunk_id):
             if case(_3DS.INT_PERCENTAGE):
                 texture.percentage = self.file.readShort()
                 print texture.percentage
                 break
             if case(_3DS.MAPPING_FILENAME):
                 texture.name = self.readName()
                 print "    Filename: %s" %(texture.name)
                 break
             if case(_3DS.MAP_TEXBLUR):
                 texture.blur = self.file.readFloat()
                 print "    Texture blur: %.2f" %(texture.blur)
                 break
             if case(_3DS.MAP_TILING):
                 texture.tiling = self.file.readShort()
                 print "    Texture tiling: %d" %(texture.tiling)
                 break
             if case(_3DS.MAP_ANGLE):
                 texture.rotationAngle = self.file.readFloat()
                 print "    Rotation angle: %.2f" %(texture.rotationAngle)
                 break
             if case(_3DS.MAP_U_SCALE):
                 texture.uScale = self.file.readFloat()
                 print "    U Scale: %.2f" %(texture.uScale)
                 break
             if case(_3DS.MAP_V_SCALE):
                 texture.vScale = self.file.readFloat()
                 print "    V Scale: %.2f" %(texture.vScale)
                 break
             if case(_3DS.MAP_U_OFFSET):
                 texture.uOffset = self.file.readFloat()
                 print "    U Offset: %.2f" %(texture.uOffest)
                 break
             if case(_3DS.MAP_V_OFFSET):
                 texture.vOffset = self.file.readFloat()
                 print "    V Offset: %.2f" %(texture.vOffset)
                 break
             if case(_3DS.MAP_COL1):
                 os.write(1, "    Color 1: ")
                 texture.firstBlendColor = self.readColor()
                 break
             if case(_3DS.MAP_COL2):
                 os.write(1, "    Color 2: ")
                 texture.secondBlendColor = self.readColor()
                 break
             if case(_3DS.MAP_R_COL):
                 os.write(1, "    R_Color: ")
                 texture.redBlendColor = self.readColor()
                 break
             if case(_3DS.MAP_G_COL):
                 os.write(1, "    G_Color: ")
                 texture.greenBlendColor = self.readColor()
                 break
             if case(_3DS.MAP_B_COL):
                 os.write(1, "    B_Color: ")
                 texture.blueBlendColor = self.readColor()
                 break
             if case(_3DS.MAT_BUMP_PERCENT):
                 texture.bumpPercentage = self.file.readShort()
                 print "    Bump percent: %d" %(texture.bumpPercentage)
                 break
             if case():
                 print "   Skip unknown %X subchunk" %(header.chunk_id)
         self.file.seek(header.start_position + header.chunk_length, os.SEEK_SET)
         bytes = self.updateBytesToRead(bytes, header.chunk_length)
     return texture
Exemplo n.º 55
0
 def readMaterialChunk(self, bytes):
     header = Chunks.ChunkHeader()
     material = Chunks.MaterialChunk()
     material.textures = []
     while bytes > 0:
         self.readChunkHeader(header)
         for case in switch(header.chunk_id):
             if case(_3DS.MATERIAL_NAME):
                 material.name = self.readName()
                 print "   Name: %s" %(material.name)
                 break
             if case(_3DS.AMBIENT_COLOR):
                 os.write(1,"   Ambient color: ")
                 material.ambientColor = self.readColor()
                 break
             if case(_3DS.DIFFUSE_COLOR):
                 os.write(1, "   Diffuse color: ")
                 material.diffuseColor = self.readColor()
                 break
             if case(_3DS.SPECULAR_COLOR):
                 os.write(1, "   Specular color: ")
                 material.specularColor = self.readColor()
                 break
             if case(_3DS.SHININESS_PERCENT):
                 os.write(1, "   Shininess percent: ")
                 material.shininess = self.readPercent()
                 break
             if case(_3DS.SHIN2PCT_PERCENT):
                 os.write(1, "   Shininess sterngth: ")
                 material.shininessSterngth = self.readPercent()
                 break
             if case(_3DS.SHIN3PCT_PERCENT):
                 os.write(1, "   Shininess secoind sterngth: ")
                 material.secondShininessSterength = self.readPercent()
                 break
             if case(_3DS.TRANSPARENCY_PERCENT):
                 os.write(1, "   Transparency percent: ")
                 material.transparency = self.readPercent()
                 break
             if case(_3DS.TRANSP_FALLOF_PERCENT):
                 os.write(1, "   Transparency fallof percent: ")
                 material.transparencyFallof = self.readPercent()
                 break
             if case(_3DS.REFLECTION_BLUR_PERCENT):
                 os.write(1, "   Reflection Blur percent: ")
                 material.reflectionBlur = self.readPercent()
                 break
             if case(_3DS.SELF_ILLUM):
                 print "   Self illuminted"
                 material.isSelfIlluminated = True
                 break
             if case(_3DS.TWO_SIDE):
                 print "   Two-sided lighting"
                 material.twoSided = True
                 break
             if case(_3DS.ADDITIVE):
                 print "   Additive blend"
                 material.aditive = True
                 break
             if case(_3DS.WIREFRAME):
                 print "   Wireframe"
                 material.wireframe = True
                 break
             if case(_3DS.WIRESIZE):
                 material.wireSize = self.file.readFloat()
                 print "   Wire size: %.2f" %(material.wireSize)
                 break
             if case(_3DS.SHADING):
                 material.shadingType = self.file.readShort()
                 print "   Shading: %d" %(material.shadingType)
                 break
             if case(_3DS.TEXTURE_MAP_1):
                 print "   Texture Map 1"
                 os.write(1, "    Percentage: ")
                 material.textureMap1 = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.textureMap1)
                 break
             if case(_3DS.TEXTURE_MAP_2):
                 print "   Texture Map 2"
                 os.write(1, "    Percentage: ")
                 material.textureMap2 = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.textureMap2)
                 break
             if case(_3DS.BUMP_MAP):
                 print "   Bump Map"
                 os.write(1, "    Percentage: ")
                 material.bumpMap = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.bumpMap)
                 break
             if case(_3DS.SPECULAR_MAP):
                 print "   Specular Map"
                 os.write(1, "    Percentage: ")
                 material.specularMap = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.specularMap)
                 break
             if case(_3DS.REFLECTION_MAP):
                 print "   Reflection Map"
                 os.write(1, "    Percentage: ")
                 material.reflectionMap = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.reflectionMap)
                 break
             if case(_3DS.OPACITY_MAP):
                 print "   Opacity Map"
                 os.write(1, "    Percentage: ")
                 material.opacityMap = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.opacityMap)
                 break
             if case(_3DS.SHININESS_MAP):
                 print "   Shininess Map"
                 os.write(1, "    Percentage: ")
                 material.shininessMap = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.shininessMap)
                 break
             if case(_3DS.TEXTURE_1_MASK):
                 print "   Texture 1 mask"
                 material.textureMask1 = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.textureMask1)
                 break
             if case(_3DS.TEXTURE_2_MASK):
                 print "   Texture 2 mask"
                 material.textureMask2 = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.textureMask2)
                 break
             if case(_3DS.OPACITY_MASK):
                 print "   Opacity mask"
                 material.opacityMask = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.opacityMask)
                 break
             if case(_3DS.BUMP_MASK):
                 print "   Bump mask"
                 material.bumpMask = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.bumpMask)
                 break
             if case(_3DS.SHININESS_MASK):
                 print "   Shininess mask"
                 material.shininessMask = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.shininessMask)
                 break
             if case(_3DS.SPECULAR_MASK):
                 print "   Specular mask"
                 material.specularMask = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.specularMask)
                 break
             if case(_3DS.REFLECTION_MASK):
                 print "   Reflection mask"
                 material.reflectionMask = self.readTextureChunk(header.chunk_length - 6)
                 material.textures.append(material.reflectionMask)
                 break
             if case():
                 print "   Skip unknown %X subchunk" %(header.chunk_id)
         self.file.seek(header.start_position + header.chunk_length, os.SEEK_SET)
         bytes = self.updateBytesToRead(bytes, header.chunk_length)
     self.object.materials.append(material)
Exemplo n.º 56
0
    try:
        f = open(path, 'a+')
        f.write("http://www.doomsdaymydear.com/?id={0}\n".format(nextId))
        f.close()
    except Exception as e:
        print(e)


if __name__ == '__main__':
    site = sys.argv[1]
    
    #connect to mysql
    conn = pymysql.connect(host='localhost', port=3306, user='******', passwd='TGSTGSTGS', db='crts')
    cur = conn.cursor()

    for case in switch(site):
        if case('XKCD'):
            AddXKCD(cur)
            break
        if case('DoomsDayMyDear'):
            AddDoomsDayMyDear(cur)
            break
        if case():
            print ("That site isn't recognized!")
            break
        #more cases here

    #close connections
    cur.close()
    conn.close()
Exemplo n.º 57
0
import sys
import os
sys.path.insert(0, '/home/jack/quick2wire-python-api/src')

from time import sleep
from quick2wire.gpio import Pin
from switch import switch
## import switch

LED = int(sys.argv[1]) if len(sys.argv) > 1 else 1
ontime = int(sys.argv[2]) if len(sys.argv) > 2 else 5



for case in switch(LED):
    if case(1):
        pin = Pin(3, Pin.Out); break
    if case(2):
        pin = Pin(5, Pin.Out); break
    if case(3):
        pin = Pin(7, Pin.Out); break
    if case(4):
        pin = Pin(11, Pin.Out); break
    if case(5):
        pin = Pin(12, Pin.Out); break
    if case(6):
        pin = Pin(13, Pin.Out); break
    if case(7):
        pin = Pin(15, Pin.Out); break
    if case(8):
Exemplo n.º 58
0
    def setTexParameters(target, param):
        color = (GLfloat * 4)(*[0, 0, 0, 0])
        mode = GL_NONE
        for case in switch(param.wrapMode):
            if case(Texture.TILE):
                mode = GL_REPEAT
                break
            if case(Texture.CLAMP):
                if Texture.info.have_extension("GL_EXT_texture_edge_clamp"):
                    mode = GL_CLAMP_TO_EDGE
                else: mode = GL_CLAMP
                break
            if case(Texture.ZERO):
                if Texture.info.have_extension("GL_ARB_texture_border_clamp"):
                    mode = GL_CLAMP_TO_BORDER_ARB
                else: mode = GL_CLAMP
                glTexParameterfv(target, GL_TEXTURE_BORDER_COLOR, color)
                break
        glTexParameteri(target, GL_TEXTURE_WRAP_S, mode)
        glTexParameteri(target, GL_TEXTURE_WRAP_T, mode)
        if Texture.info.have_extension("GL_EXT_texture3D"):
            glTexParameteri(target, GL_TEXTURE_WRAP_R, mode)

        hasMipMaps = (target != Texture.TEXTURE_RECTANGLE) and \
    		     (param.interpolateMode != Texture.BILINEAR_NO_MIPMAP) and \
    		     (param.interpolateMode != Texture.NEAREST_NO_MIPMAP)

    	if hasMipMaps and (Texture.info.have_extension("GL_EXT_texture_lod") or \
                           Texture.info.have_extension("GL_SGIS_texture_lod")):
            glTexParameteri(target, GL_TEXTURE_MAX_LOD_SGIS, param.maxLOD)
            glTexParameteri(target, GL_TEXTURE_MIN_LOD_SGIS, param.minLOD)

        supports_generate_mipmaps = Texture.info.have_extension("GL_SGIS_generate_mipmap")

        for case in switch(param.interpolateMode):
            if case(Texture.TRILINEAR_MIPMAP):
                glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
	        glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
	        if supports_generate_mipmaps:
	            glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE)
	        break
            if case(Texture.BILINEAR_MIPMAP):
	        glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
	        glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST)
	        if param.autoGenerateMipMaps and supports_generate_mipmaps:
	            glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE)
	        break
	
	    if case(Texture.NEAREST_MIPMAP):
	        glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
	        glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST)
	        if param.autoGenerateMipMaps and supports_generate_mipmaps:
	            glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE)
	        break
	
	    if case(Texture.BILINEAR_NO_MIPMAP):
	        glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
	        glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
	        break
	
	    if case(Texture.NEAREST_NO_MIPMAP):
	        glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
	        glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
	        break

        if Texture.info.have_extension("GL_EXT_texture_filter_anisotropic"):
            glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, param.maxAnisotropy)

        if Texture.info.have_extension("GL_ARB_shadow"):
            if param.depthReadMode == Texture.DEPTH_NORMAL:
                glTexParameteri(target, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE)
            else:
                glTexParameteri(target, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE_ARB)
                glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC_ARB, param.depthReadMode)
Exemplo n.º 59
0
 def __init__(self, ch1=0, ch2=0):
   self.switchmodule = switch.switch(0, ch1, ch2)
Exemplo n.º 60
0
def main():
    def drawScreen():   #updates all the gates (and this also sockets and cables), then draws them to the screen.
        pygame.draw.line(screen, black,(250,0),(250,screensize[1]),2)
        for Gate in gates:
            Gate.update()
        for creator in creators:
            creator.draw()
        for button in buttons:
            button.draw()
    pygame.init()
    screensize = (1200,700)
    screen = pygame.display.set_mode(screensize)
    
    # The FPS the simulation will run at.
    FPS = 30
    sleeptime = 1/float(FPS) #default sleep time


    creatorTypes = ["and","or","xor","nand","nor","xnor","not","switch","bulb"]

    gates = []  #in a sense, this is LIFO when it comes to drawing: the last element will be drawn on top.
    cables = []
    creators = [gateCreator() for x in range(len(creatorTypes))]
    
    for index, creator in enumerate(creators):
        creator.setType(creatorTypes[index])
        creator.setCords(75,index*50)#creator.rect.height)
        creator.setScreen(screen)
    
    compiler = button()
    compiler.setType("compile")
    compiler.setCords(10,len(creatorTypes)*50) # under the creators
    compiler.setScreen(screen)
    buttons = [compiler]

    running = True

    while running: #each iteration of this is one frame, unless gates are clicked (framerate will remain the same however)
        time.sleep(sleeptime)   #wait a little on each frame
        events = pygame.event.get()
        screen.fill(white)
        drawScreen()
        pygame.display.flip()
        for g in gates: #check if any gates should be deleted
            if g.rect.center[0]<100:
                g.SHUTDOWNEVERYTHING()
                gates.remove(g)
                    
        for event in events:                #handle events
            if event.type == 2 and event.key == 27:     #escape key pressed? -> quit
                running = False
            
            if event.type == pygame.MOUSEBUTTONDOWN:    #mouse pressed?
                mouse = pygame.mouse.get_pos()
                mousePressed = True
                for gC in creators:                     #check if creators have been pressed  -  if so, create gate.
                    if gC.pressed(mouse):
                        if gC.type == "bulb":
                            Gate = bulb()
                            cOffset = (gC.rect.topleft[0] - mouse[0], gC.rect.topleft[1]-mouse[1]) 
                            Gate.create(gC.type,(mouse[0]+cOffset[0],mouse[1]+cOffset[1]),screen)
                            gates.append(Gate)
                        elif gC.type == "switch":
                            Gate = switch()     #HAHA! It's not actually a gate!
                            cOffset = (gC.rect.topleft[0] - mouse[0], gC.rect.topleft[1]-mouse[1]) #mouse offset - we want to be able to drag the gate from wherever we press it
                            Gate.create(gC.type,(mouse[0]+cOffset[0],mouse[1]+cOffset[1]),screen)
                            gates.append(Gate)
                        else:
                            Gate = gate()
                            cOffset = (gC.rect.topleft[0] - mouse[0], gC.rect.topleft[1]-mouse[1]) #mouse offset - we want to be able to drag the gate from wherever we press it
                            Gate.create(gC.type,(mouse[0]+cOffset[0],mouse[1]+cOffset[1]),screen)
                            gates.append(Gate)
                    
                        offset = (Gate.rect.topleft[0] - mouse[0], Gate.rect.topleft[1]-mouse[1])
                        
                        while pygame.MOUSEBUTTONDOWN not in [ev.type for ev in pygame.event.get()]:
                            mouse = pygame.mouse.get_pos()
                            screen.fill(white)
                            Gate.setCords(mouse[0]+offset[0],mouse[1]+offset[1])
                            drawScreen()
                            pygame.display.flip()
                for b in buttons:
                    if b.pressed(mouse):
                        print "%s clicked" %b
                        if b.type == 'compile':
                            pc(gates)
                #### FOR THE LOVE OF ALL THAT IS HOLY DO NOT TOUCH THIS NEXT PART #####
                for Gate in gates:                      #check if gate was clicked
                    ev = pygame.event.get()
                    mouse = pygame.mouse.get_pos()
                    p = Gate.pressed(mouse)
                    if p:
                        if p == "main":         #gate was clicked "on body", not sockets so we dont need to worry about cable stuff here.
                            offset = (Gate.rect.topleft[0] - mouse[0], Gate.rect.topleft[1]-mouse[1])   #dragging offset again
                            while pygame.MOUSEBUTTONUP not in [ev.type for ev in ev]:
                                time.sleep(sleeptime)
                                mouse = pygame.mouse.get_pos()
                                Gate.setCords(mouse[0]+offset[0],mouse[1]+offset[1])
                                screen.fill(white)
                                drawScreen()
                                ev = pygame.event.get()
                                pygame.display.flip()
                            
                        elif p[:2] == "in":         # oh boy, someone clicked an input socket, now what do we do
                            
                            ### Disconnect logic - only inputs can be disconnected
                            if Gate.inSockets[int(p[2:])].connected:    #great, the socket already had a connection on it. lets change that..
                                print "disconnecting"
                                Cable = Gate.inSockets[int(p[2:])].attachedCables[0]
                                Cable.disconnect("in")
                                mousePressed = False
                                gatePressed = False
                                while not mousePressed:     #loop for dragging the loose cable around. also yes, I should probably have called them wires
                                        time.sleep(sleeptime)
                                        mouse = pygame.mouse.get_pos()
                                        screen.fill(white)
                                        drawScreen()
                                        Cable.drawCable(Cable.startSocket.rect.center,mouse)
                                        if pygame.MOUSEBUTTONDOWN in [ev.type for ev in pygame.event.get()]:
                                            print "mousedown"
                                            for g in gates:
                                                press = g.pressed(mouse)    #a socket was clicked, lets attach the cable here
                                                if press:
                                                    print "#############"
                                                    mousePressed = True
                                                    if press[:2]=="in":     #only worry about input sockets
                                                        print "connecting to ", g
                                                        inSock = g.inSockets[int(press[2:])]    #saving the socket for connecting to later
                                                        gatePressed = True
                                                        break
                                            if not gatePressed: #none of the gates were clicked, but the mouse was -> delete the cable.
                                                print "no gate pressed, deleting cable"
                                                mousePressed = True
                                                break
                                                    
                                        pygame.display.flip()
                                        if gatePressed: # this part could have probably gone where we check if a gate was pressed
                                            print "gate pressed after disconnect, should be reconnecting"
                                            if inSock.connect(Cable):
                                                Cable.setEndSocket(inSock)
                                                print "connected",Cable.endSocket," to ", Cable.startSocket, " with ", Cable
                                            break
                                        if mousePressed: # here we delete the cable
                                            Cable.startSocket.attachedCables.remove(Cable)
                                            Cable.endSocket.attachedCables = []
                                            Cable.startSocket = None
                                            Cable.endSocket = None
                                            break
                
                            #### connect logic for input -> outpout
                            else:   #whew, long if statement there
                                print "cable from in"
                                Cable = cable()
                                Cable.setScreen(screen)
                                Cable.setEndSocket(Gate.inSockets[int(p[2:])])
                                if Gate.inSockets[int(p[2:])].connect(Cable):       # this whole thing pretty much runs analog to the disconnect logic, just in reverse
                                    mousePressed = False
                                    gatePressed = False
                                    while not mousePressed:#(pygame.MOUSEBUTTONDOWN not in [ev.type for ev in pygame.event.get()]):
                                        time.sleep(sleeptime)
                                        mouse = pygame.mouse.get_pos()
                                        screen.fill(white)
                                        drawScreen()
                                        Cable.drawCable(mouse,Cable.endSocket.rect.center)
                                        if pygame.MOUSEBUTTONDOWN in [ev.type for ev in pygame.event.get()]:
                                            print "mousedown"
                                            for g in gates:
                                                if g.pressed(mouse)=="out":     #only connect if an output socket was clicked
                                                    print "connecting to output"
                                                    outSock = g.outSocket
                                                    gatePressed = True
                                                    break
                                                mousePressed = True
                                            if not gatePressed:
                                                print "mouse pressed, gates iterated, none pressed, disconnecting cable."
                                                Gate.inSockets[int(p[2:])].disconnect(Cable)
                                                
                                        pygame.display.flip()
                                        if gatePressed:
                                            if outSock.connect(Cable):
                                                Gate.inSockets[int(p[2:])].connect(Cable)
                                                Cable.setStartSocket(outSock)
                                                print "connected",Cable.startSocket," to ", Cable.endSocket, " with ", Cable
                                            else:
                                                Gate.inSockets[int(p[2:])].disconnect(Cable)
                                            break
                        ### connect logic for output -> input
                        else:
                            print "cable from out"
                            Cable = cable()
                            Cable.setScreen(screen)
                            Cable.setStartSocket(Gate.outSocket)
                            if Gate.outSocket.connect(Cable):
                                mousePressed = False
                                gatePressed = False
                                while not mousePressed:#(pygame.MOUSEBUTTONDOWN not in [ev.type for ev in pygame.event.get()]):
                                    time.sleep(sleeptime)
                                    mouse = pygame.mouse.get_pos()
                                    screen.fill(white)
                                    drawScreen()
                                    Cable.drawCable(mouse,Cable.startSocket.rect.center)
                                    if pygame.MOUSEBUTTONDOWN in [ev.type for ev in pygame.event.get()]: #little different here: we need to specify which input socket to connect to
                                        print "mousedown"
                                        for g in gates:
                                            press = g.pressed(mouse)    #this returns "in0" and "in1" depending on which socket was clicked
                                            print press
                                            if press =="in0":#(("in0" in [g.pressed(mouse) for g in gates])):
                                                print "connecting to input0"
                                                inSock = g.inSockets[0]
                                                gatePressed = True
                                                break
                                            elif press =="in1":#("in1" in [g.pressed(mouse) for g in gates]):
                                                print "connecting to input1"
                                                inSock = g.inSockets[1]
                                                gatePressed = True
                                                break
                                            mousePressed = True
                                        if not gatePressed:
                                            print "not connecting."
                                            Gate.outSocket.disconnect(Cable)
                                            break
                                    
                                    pygame.display.flip()
                                    if gatePressed:
                                        if inSock.connect(Cable):
                                            Cable.setEndSocket(inSock)
                                            print "connected",Cable.endSocket," to ", Cable.startSocket, " with ", Cable
                                        break
                        break
                ########################################
    pygame.quit()