Exemplo n.º 1
1
def do_padding(img, padding):
    if not padding:
        return img
    try:
        padding = float(padding)*2.0
        if padding > .9:
            padding = .9
        if padding <= 0.0:
            return img
    except ValueError:
        return

    iw, ih = img.size

    img.thumbnail(
        (
            int( round( float(img.size[0]) * (1.0 - padding) ) ),
            int( round( float(img.size[1]) * (1.0 - padding) ) )
        ),
        pil.ANTIALIAS
        )

    img = do_fill(img, "ffffff00", iw, ih)

    return img
Exemplo n.º 2
0
def McDonalds():
    
    url = request.urlopen("http://apps.mcdonalds.se/sweden/restSite.nsf/markers?readForm")
    data = url.read().decode('utf-8')
    markers = json.loads(data)['markers']
    
    for m in markers:
        if m['vanityname'].startswith('mcdonalds'):
            
            hours = []
            
            for h in m['openhours']:
                if h == "always,1":
                    hours.append(("00:00", "24:00"))
                else:
                    hours.append(h.split(","))
            
            name = cleanupName(m['vanityname'])
            
            yield {
                'name': name,
                'title': nameToTitle(name),
                'type': 'restaurant',
                'lat': round(float(m['lat']) * 1E6),
                'lon': round(float(m['lng']) * 1E6),
                'hours': hours
            }
    def load_goal_image(self):
        '''
        It will load the truck image, that will be used
        for displaying the current vehicles.
        '''

        box_width_meters = 32.*0.2
        box_length_meters = 32.*0.2

        flag_image = pygame.image.load('resources/finishFlag.png')

        (flag_image_width, flag_image_height) = flag_image.get_size()

        [x_pixel_1, y_pixel_1] = self.convert_position_to_image_pixel(0, 0)
        [x_pixel_2, y_pixel_2] = self.convert_position_to_image_pixel(box_length_meters, 0)

        desired_box_width_pixels = float(x_pixel_2 - x_pixel_1)

        scale_down_ratio = desired_box_width_pixels/(flag_image_width/2.)

        new_size = (int(round(scale_down_ratio*flag_image_width)), int(round(scale_down_ratio*flag_image_height)))

        flag = pygame.transform.smoothscale(flag_image,new_size)

        self.goal_image = flag

        return
Exemplo n.º 4
0
def create_cube_request(modelname, px, py, pz, rr, rp, ry, sx, sy, sz):
    """Create a SpawnModelRequest with the parameters of the cube given.
    modelname: name of the model for gazebo
    px py pz: position of the cube (and it's collision cube)
    rr rp ry: rotation (roll, pitch, yaw) of the model
    sx sy sz: size of the cube"""
    cube = deepcopy(sdf_cube)
    # Replace size of model
    size_str = str(round(sx, 3)) + " " + \
        str(round(sy, 3)) + " " + str(round(sz, 3))
    cube = cube.replace('SIZEXYZ', size_str)
    # Replace modelname
    cube = cube.replace('MODELNAME', str(modelname))

    req = SpawnModelRequest()
    req.model_name = modelname
    req.model_xml = cube
    req.initial_pose.position.x = px
    req.initial_pose.position.y = py
    req.initial_pose.position.z = pz

    q = quaternion_from_euler(rr, rp, ry)
    req.initial_pose.orientation.x = q[0]
    req.initial_pose.orientation.y = q[1]
    req.initial_pose.orientation.z = q[2]
    req.initial_pose.orientation.w = q[3]

    return req
Exemplo n.º 5
0
def makeFoldTable(annotFile,analysisName,testName,controlName,testMMR,controlMMR,testIdxFile,controlIdxFile,outputFolder,epsilon = 1):

    '''
    makes the fold table and writes to disk
    fold table is ranked by fold change
    first column is guideID, second column is gene name, third is fold change
    '''

    guideDict,geneDict = makeAnnotDict(annotFile)

    testIdx = utils.parseTable(testIdxFile,'\t')
    controlIdx = utils.parseTable(controlIdxFile,'\t')

    #for each guide, divide the count by the MMR then add 1 then take the log2 ratio

    outTable = [['GUIDE_ID','GENE','LOG2_RATIO',testName,controlName]]
    for i in range(len(testIdx)):

        guideID = testIdx[i][0]
        gene = guideDict[guideID]
        
        testCount = float(testIdx[i][2])/testMMR + epsilon
        controlCount = float(controlIdx[i][2])/controlMMR + epsilon

        log2Ratio = numpy.log2(testCount/controlCount)

        newLine = [guideID,gene,log2Ratio,round(testCount,4),round(controlCount,4)]

        outTable.append(newLine)

    outputFile = '%s%s_log2Ratio.txt' % (outputFolder,analysisName)
    utils.unParseTable(outTable,outputFile,'\t')
    return outputFile
    def load_small_box_image(self):
        '''
        It will load the truck image, that will be used
        for displaying the current vehicles.
        '''

        box_width_meters = 32.*0.3
        box_length_meters = 32.*0.4

        box_image = pygame.image.load('resources/waterOffset.png')

        (box_image_width, box_image_height) = box_image.get_size()

        [x_pixel_1, y_pixel_1] = self.convert_position_to_image_pixel(0, 0)
        [x_pixel_2, y_pixel_2] = self.convert_position_to_image_pixel(box_length_meters, 0)

        desired_box_width_pixels = float(x_pixel_2 - x_pixel_1)

        scale_down_ratio = desired_box_width_pixels/(box_image_width/2.)

        new_size = (int(round(scale_down_ratio*box_image_width)), int(round(scale_down_ratio*box_image_height)))

        box = pygame.transform.smoothscale(box_image,new_size)

        self.small_box_image = box

        return
def updateProgress(percent, barLength = 20):
	"""Update progress bar in command line"""
	hashes = '#' * int(round(percent * barLength / 100 ))
	spaces = ' ' * (barLength - len(hashes))
	
	sys.stdout.write("\rGenerating ... [{0}] {1}%".format(hashes + spaces, int(round(percent))))
	sys.stdout.flush()
Exemplo n.º 8
0
 def test_sampling_empirical_dist(self):
     my_empirical_dist = [8.0, 8.0, 8.0, 8.8, 8.8, 12.3]
     params = {
         'Arrival_distributions': [['Empirical',
             'ciw/tests/testing_parameters/sample_empirical_dist.csv']],
         'Service_distributions': [['Empirical', my_empirical_dist]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nem = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nem.simulation.service_times[Nem.id_number][0](), 2), 8.8)
     self.assertEqual(round(
         Nem.simulation.service_times[Nem.id_number][0](), 2), 12.3)
     self.assertEqual(round(
         Nem.simulation.service_times[Nem.id_number][0](), 2), 8.0)
     self.assertEqual(round(
         Nem.simulation.service_times[Nem.id_number][0](), 2), 8.0)
     self.assertEqual(round(
         Nem.simulation.service_times[Nem.id_number][0](), 2), 8.0)
     self.assertEqual(round(
         Nem.simulation.inter_arrival_times[Nem.id_number][0](), 2), 7.7)
     self.assertEqual(round(
         Nem.simulation.inter_arrival_times[Nem.id_number][0](), 2), 7.7)
     self.assertEqual(round(
         Nem.simulation.inter_arrival_times[Nem.id_number][0](), 2), 7.1)
     self.assertEqual(round(
         Nem.simulation.inter_arrival_times[Nem.id_number][0](), 2), 7.1)
     self.assertEqual(round(
         Nem.simulation.inter_arrival_times[Nem.id_number][0](), 2), 7.7)
Exemplo n.º 9
0
  def onInputVolumeChanged( self ):
    '''
    '''
    if not self.__updating:

        self.__updating = 1

        SlicerVmtkCommonLib.Helper.Debug( "onInputVolumeChanged" )

        # reset the thresholdSlider
        self.__thresholdSlider.minimum = 0
        self.__thresholdSlider.maximum = 100
        self.__thresholdSlider.minimumValue = 0
        self.__thresholdSlider.maximumValue = 100

        currentNode = self.__inputVolumeNodeSelector.currentNode()

        if currentNode:

            v = self.selectVesselnessVolume()

            # if we have a vesselnessNode, we will configure the threshold slider for it instead of the original image
            # if not, the currentNode is the input volume
            if v:
                SlicerVmtkCommonLib.Helper.Debug( "Using Vesselness volume to configure thresholdSlider.." )
                currentNode = v

            currentImageData = currentNode.GetImageData()
            currentDisplayNode = currentNode.GetDisplayNode()

            if currentImageData:
                currentScalarRange = currentImageData.GetScalarRange()
                minimumScalarValue = round( currentScalarRange[0], 0 )
                maximumScalarValue = round( currentScalarRange[1], 0 )
                self.__thresholdSlider.minimum = minimumScalarValue
                self.__thresholdSlider.maximum = maximumScalarValue

                # if the image has a small scalarRange, we have to adjust the singleStep
                if maximumScalarValue <= 10:
                    self.__thresholdSlider.singleStep = 0.1

                if currentDisplayNode:

                    if currentDisplayNode.GetApplyThreshold():

                        # if a threshold is already applied, use it!
                        self.__thresholdSlider.minimumValue = currentDisplayNode.GetLowerThreshold()
                        self.__thresholdSlider.maximumValue = currentDisplayNode.GetUpperThreshold()

                    else:

                        # don't use a threshold, use the scalar range
                        SlicerVmtkCommonLib.Helper.Debug( "Reset thresholdSlider's values." )
                        self.__thresholdSlider.minimumValue = minimumScalarValue
                        self.__thresholdSlider.maximumValue = maximumScalarValue




        self.__updating = 0
Exemplo n.º 10
0
 def test_sampling_custom_dist(self):
     my_custom_dist = [[0.2, 3.7], [0.5, 3.8], [0.3, 4.1]]
     params = {
         'Arrival_distributions': [['Custom', my_custom_dist]],
         'Service_distributions': [['Custom', my_custom_dist]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nc = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nc.simulation.service_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.service_times[Nc.id_number][0](), 2), 4.1)
     self.assertEqual(round(
         Nc.simulation.service_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.service_times[Nc.id_number][0](), 2), 4.1)
     self.assertEqual(round(
         Nc.simulation.service_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.inter_arrival_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.inter_arrival_times[Nc.id_number][0](), 2), 4.1)
     self.assertEqual(round(
         Nc.simulation.inter_arrival_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.inter_arrival_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.inter_arrival_times[Nc.id_number][0](), 2), 3.7)
Exemplo n.º 11
0
 def test_sampling_lognormal_dist(self):
     params = {
         'Arrival_distributions': [['Lognormal', 0.8, 0.2]],
         'Service_distributions': [['Lognormal', 0.8, 0.2]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nl = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nl.simulation.service_times[Nl.id_number][0](), 2), 2.62)
     self.assertEqual(round(
         Nl.simulation.service_times[Nl.id_number][0](), 2), 1.64)
     self.assertEqual(round(
         Nl.simulation.service_times[Nl.id_number][0](), 2), 2.19)
     self.assertEqual(round(
         Nl.simulation.service_times[Nl.id_number][0](), 2), 2.31)
     self.assertEqual(round(
         Nl.simulation.service_times[Nl.id_number][0](), 2), 2.48)
     self.assertEqual(round(
         Nl.simulation.inter_arrival_times[Nl.id_number][0](), 2), 2.51)
     self.assertEqual(round(
         Nl.simulation.inter_arrival_times[Nl.id_number][0](), 2), 2.33)
     self.assertEqual(round(
         Nl.simulation.inter_arrival_times[Nl.id_number][0](), 2), 1.96)
     self.assertEqual(round(
         Nl.simulation.inter_arrival_times[Nl.id_number][0](), 2), 2.32)
     self.assertEqual(round(
         Nl.simulation.inter_arrival_times[Nl.id_number][0](), 2), 2.70)
Exemplo n.º 12
0
 def test_sampling_weibull_dist(self):
     params = {
         'Arrival_distributions': [['Weibull', 0.9, 0.8]],
         'Service_distributions': [['Weibull', 0.9, 0.8]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nw = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nw.simulation.service_times[Nw.id_number][0](), 2), 0.87)
     self.assertEqual(round(
         Nw.simulation.service_times[Nw.id_number][0](), 2), 1.31)
     self.assertEqual(round(
         Nw.simulation.service_times[Nw.id_number][0](), 2), 1.60)
     self.assertEqual(round(
         Nw.simulation.service_times[Nw.id_number][0](), 2), 3.34)
     self.assertEqual(round(
         Nw.simulation.service_times[Nw.id_number][0](), 2), 1.31)
     self.assertEqual(round(
         Nw.simulation.inter_arrival_times[Nw.id_number][0](), 2), 2.91)
     self.assertEqual(round(
         Nw.simulation.inter_arrival_times[Nw.id_number][0](), 2), 0.01)
     self.assertEqual(round(
         Nw.simulation.inter_arrival_times[Nw.id_number][0](), 2), 0.50)
     self.assertEqual(round(
         Nw.simulation.inter_arrival_times[Nw.id_number][0](), 2), 3.36)
     self.assertEqual(round(
         Nw.simulation.inter_arrival_times[Nw.id_number][0](), 2), 0.95)
Exemplo n.º 13
0
 def test_sampling_exponential_dist(self):
     params = {
         'Arrival_distributions': [['Exponential', 4.4]],
         'Service_distributions': [['Exponential', 4.4]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Ne = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Ne.simulation.service_times[Ne.id_number][0](), 2), 0.22)
     self.assertEqual(round(
         Ne.simulation.service_times[Ne.id_number][0](), 2), 0.31)
     self.assertEqual(round(
         Ne.simulation.service_times[Ne.id_number][0](), 2), 0.36)
     self.assertEqual(round(
         Ne.simulation.service_times[Ne.id_number][0](), 2), 0.65)
     self.assertEqual(round(
         Ne.simulation.service_times[Ne.id_number][0](), 2), 0.31)
     self.assertEqual(round(
         Ne.simulation.inter_arrival_times[Ne.id_number][0](), 2), 0.58)
     self.assertEqual(round(
         Ne.simulation.inter_arrival_times[Ne.id_number][0](), 2), 0.01)
     self.assertEqual(round(
         Ne.simulation.inter_arrival_times[Ne.id_number][0](), 2), 0.14)
     self.assertEqual(round(
         Ne.simulation.inter_arrival_times[Ne.id_number][0](), 2), 0.65)
     self.assertEqual(round(
         Ne.simulation.inter_arrival_times[Ne.id_number][0](), 2), 0.24)
Exemplo n.º 14
0
 def test_sampling_gamma_dist(self):
     params = {
         'Arrival_distributions': [['Gamma', 0.6, 1.2]],
         'Service_distributions': [['Gamma', 0.6, 1.2]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Ng = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Ng.simulation.service_times[Ng.id_number][0](), 2), 0.00)
     self.assertEqual(round(
         Ng.simulation.service_times[Ng.id_number][0](), 2), 2.59)
     self.assertEqual(round(
         Ng.simulation.service_times[Ng.id_number][0](), 2), 1.92)
     self.assertEqual(round(
         Ng.simulation.service_times[Ng.id_number][0](), 2), 0.47)
     self.assertEqual(round(
         Ng.simulation.service_times[Ng.id_number][0](), 2), 0.61)
     self.assertEqual(round(
         Ng.simulation.inter_arrival_times[Ng.id_number][0](), 2), 0.00)
     self.assertEqual(round(
         Ng.simulation.inter_arrival_times[Ng.id_number][0](), 2), 1.07)
     self.assertEqual(round(
         Ng.simulation.inter_arrival_times[Ng.id_number][0](), 2), 1.15)
     self.assertEqual(round(
         Ng.simulation.inter_arrival_times[Ng.id_number][0](), 2), 0.75)
     self.assertEqual(round(
         Ng.simulation.inter_arrival_times[Ng.id_number][0](), 2), 0.00)
Exemplo n.º 15
0
 def test_sampling_triangular_dist(self):
     params = {
         'Arrival_distributions': [['Triangular', 1.1, 6.6, 1.5]],
         'Service_distributions': [['Triangular', 1.1, 6.6, 1.5]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nt = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nt.simulation.service_times[Nt.id_number][0](), 2), 3.35)
     self.assertEqual(round(
         Nt.simulation.service_times[Nt.id_number][0](), 2), 3.91)
     self.assertEqual(round(
         Nt.simulation.service_times[Nt.id_number][0](), 2), 4.20)
     self.assertEqual(round(
         Nt.simulation.service_times[Nt.id_number][0](), 2), 5.33)
     self.assertEqual(round(
         Nt.simulation.service_times[Nt.id_number][0](), 2), 3.90)
     self.assertEqual(round(
         Nt.simulation.inter_arrival_times[Nt.id_number][0](), 2), 5.12)
     self.assertEqual(round(
         Nt.simulation.inter_arrival_times[Nt.id_number][0](), 2), 1.35)
     self.assertEqual(round(
         Nt.simulation.inter_arrival_times[Nt.id_number][0](), 2), 2.73)
     self.assertEqual(round(
         Nt.simulation.inter_arrival_times[Nt.id_number][0](), 2), 5.34)
     self.assertEqual(round(
         Nt.simulation.inter_arrival_times[Nt.id_number][0](), 2), 3.46)
Exemplo n.º 16
0
 def test_sampling_uniform_dist(self):
     params = {
         'Arrival_distributions': [['Uniform', 2.2, 3.3]],
         'Service_distributions': [['Uniform', 2.2, 3.3]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nu = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nu.simulation.service_times[Nu.id_number][0](), 2), 2.89)
     self.assertEqual(round(
         Nu.simulation.service_times[Nu.id_number][0](), 2), 3.02)
     self.assertEqual(round(
         Nu.simulation.service_times[Nu.id_number][0](), 2), 3.07)
     self.assertEqual(round(
         Nu.simulation.service_times[Nu.id_number][0](), 2), 3.24)
     self.assertEqual(round(
         Nu.simulation.service_times[Nu.id_number][0](), 2), 3.01)
     self.assertEqual(round(
         Nu.simulation.inter_arrival_times[Nu.id_number][0](), 2), 3.21)
     self.assertEqual(round(
         Nu.simulation.inter_arrival_times[Nu.id_number][0](), 2), 2.23)
     self.assertEqual(round(
         Nu.simulation.inter_arrival_times[Nu.id_number][0](), 2), 2.71)
     self.assertEqual(round(
         Nu.simulation.inter_arrival_times[Nu.id_number][0](), 2), 3.24)
     self.assertEqual(round(
         Nu.simulation.inter_arrival_times[Nu.id_number][0](), 2), 2.91)
Exemplo n.º 17
0
def main():
    print("Code to look at runtime for insertion sort vs. Python's list sort.")
    
    numDig = 5 #number of digits to output
    
    #large list with numElements elements
    numElements = 10000
    data = []
    for i in range(numElements):
        data.append(randint(1, numElements))
        
    print("\nSorting list with " + str(len(data)) + " elements.\n")
    
    start = time.time()
    insertionSort(data)
    end = time.time()
    print("Insertion sort -> " + str(round(end - start, numDig)) + " seconds.")

    #large list with numElements elements
    numElements = 10000
    data = []
    for i in range(numElements):
        data.append(randint(1, numElements))
        
    start = time.time()
    data.sort()
    end = time.time()
    print("Python's sort -> " + str(round(end - start, numDig)) + " seconds.")
Exemplo n.º 18
0
 def test_sampling_deterministic_dist(self):
     params = {
         'Arrival_distributions': [['Deterministic', 4.4]],
         'Service_distributions': [['Deterministic', 4.4]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nd = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nd.simulation.service_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.service_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.service_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.service_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.service_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.inter_arrival_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.inter_arrival_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.inter_arrival_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.inter_arrival_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.inter_arrival_times[Nd.id_number][0](), 2), 4.40)
Exemplo n.º 19
0
    def _label_iterations(self, lod):
        stroke_gradient = self.get_stroke_gradient()
        if lod == LOD.FULL and \
           self.get_style() != "flat" and stroke_gradient:
            root = self.get_layout_root()
            d = 0.4  # fake-emboss distance
            #d = max(src_size[1] * 0.02, 0.0)
            max_offset = 2

            alpha = self.get_gradient_angle()
            xo = root.context.scale_log_to_canvas_x(d * cos(alpha))
            yo = root.context.scale_log_to_canvas_y(d * sin(alpha))
            xo = min(int(round(xo)), max_offset)
            yo = min(int(round(yo)), max_offset)

            luminosity_factor = stroke_gradient * 0.25

            # shadow
            yield xo, yo, -luminosity_factor, False

            # highlight
            yield -xo, -yo, luminosity_factor, False

        # normal
        yield 0, 0, 0, True
Exemplo n.º 20
0
    def testMetaDataHandleForSavingModel(self):
        """Test the handling of SaveModel for Data with Meta Atributes
        """

        #Test the save of a model created from a train data with meta attributes
        self.assert_(len(self.WMetaTest.domain.getmetas())>=1,"The dataset WMetaTest should have Meta Attributes")
        plsM = AZorngPLS.PLSLearner(self.WMetaTest)
        AccNoMetaBefore = evalUtilities.getClassificationAccuracy(self.NoMetaTrain,plsM) 
        AccWMetaBefore = evalUtilities.getClassificationAccuracy(self.WMetaTest,plsM)


        # Save the model 
        scratchdir = os.path.join(AZOC.SCRATCHDIR, "scratchdir"+str(time.time()))
        os.mkdir(scratchdir)
        modelPath = os.path.join(scratchdir,"PLSModel")
        plsM.write(modelPath)

        # Read in the model
        plsR = AZorngPLS.PLSread(modelPath)
        self.assert_(len(plsR.imputer.defaults.domain.getmetas())==0,"There shouldn't be any Meta data now!")

        # Calculate classification accuracy 
        AccNoMetaAfter = evalUtilities.getClassificationAccuracy(self.NoMetaTrain, plsR)
        AccWMetaAfter = evalUtilities.getClassificationAccuracy(self.WMetaTest, plsR)

        # Test that the accuracy of the model before and after saved
        self.assertEqual(AccNoMetaBefore, AccNoMetaAfter,"NoMeta: Predictions after loading saved model were different")
        self.assertEqual(AccWMetaBefore, AccWMetaAfter, "WMeta: Predictions after loading saved model were different")
        self.assertEqual(round(AccWMetaAfter,9), round(0.888888888889,9),"Accuracy was not the expected value!")
        self.assertEqual(round(AccNoMetaAfter,9), round(0.605769230769,9),"Accuracy was not the expected value!")
 
        # Remove the scratch directory
        os.system("/bin/rm -rf "+scratchdir)
Exemplo n.º 21
0
    def draw_cb(self, canvas, tag):
        obj = canvas.getObjectByTag(tag)
        if obj.kind != 'point':
            return True
        canvas.deleteObjectByTag(tag, redraw=False)

        if self.pxdqtag:
            try:
                canvas.deleteObjectByTag(self.pxdqtag, redraw=False)
            except:
                pass

        # Round to nearest pixel
        x, y = round(obj.x), round(obj.y)
        obj.move_to(x, y)

        # Change bad pix region appearance
        obj.radius = self._point_radius

        # Text label
        yt = y + self._text_label_offset
        obj_lbl = self.dc.Text(
            x, yt, self._text_label, color=self.pxdqcolor)

        # Update displayed values
        self.xcen = x
        self.ycen = y

        self.pxdqtag = canvas.add(self.dc.CompoundObject(obj, obj_lbl))
        return self.redo()
Exemplo n.º 22
0
    def translate_selection(self, x, y, x0, y0):
        x, y = 10*round(x/10), 10*round(y/10)
        
        # survey conditions
        for frame in self:
            for point in chain(frame[0], frame[1]):
                if point[2]:
                    # do any of the points fall on another point?
                    if not frame.can_fall(point[0] + x - x0, point[1] + y - y0):
                        return

        for frame in self:
            for point in chain(frame[0], frame[1]):
                if point[2]:
                    point[:2] = [point[0] + x - x0, point[1] + y - y0]

            # check y alignment
            if frame[0][0][1] != frame[1][0][1]:
                # determine which should move
                if frame[0][0][2]:
                    flip = 1
                else:
                    flip = 0
                frame[flip][0][1] = frame[not flip][0][1]

            if frame[0][-1][1] != frame[1][-1][1]:
                # determine which should move
                if frame[0][-1][2]:
                    flip = 1
                else:
                    flip = 0
                frame[flip][-1][1] = frame[not flip][-1][1]
Exemplo n.º 23
0
	def setXYScale (self, oriWidth, oriHeight,newWidth,newHeight):
		#self.oriWidth = oriWidth
		#self.oriHeight = oriHeight
		#self.newWidth = newWidth
		#self.newHeight = nnewHeight
	    self.transX = int(round(oriWidth/newWidth *1000))/1000.0
	    self.transY = int(round(oriHeight/newHeight*1000))/1000.0
    def update(self):
        #Update the Bullet, should be called once per 'tick'
        # calculate new y velocity
        self.ticks += 1
        self.yVelocity = self.yStartVelocity + self.gravity * self.ticks
        
        # find the bullets new position
        newPos = minecraft.Vec3(self.currentPos.x + self.xVelocity,
                                self.startPos.y + (self.yStartVelocity * self.ticks + 0.5 * (self.gravity * pow(self.ticks,2))),
                                self.currentPos.z + self.zVelocity)
        #Has the bullet moved from its last drawn position
        # round the new position and compare it to the last drawn
        newDrawPos = minecraft.Vec3(int(round(newPos.x, 0)),
                                    int(round(newPos.y, 0)),
                                    int(round(newPos.z, 0)))
        movedBullet = True
        if matchVec3(newDrawPos, self.drawPos) == False:
            # if the bullet is moving to a block of air, move it, otherwise explode
            if self.mc.getBlock(newDrawPos.x, newDrawPos.y, newDrawPos.z) == block.AIR:
                # clear the last drawn bullet
                self.clear()
                # move the draw position
                self.drawPos = minecraft.Vec3(newDrawPos.x, newDrawPos.y, newDrawPos.z)
                # draw the bullet
                self.draw()
            else:
                #exploded
                self.mcDrawing.drawSphere(newDrawPos, self.blastRadius, block.AIR)
                movedBullet = False
        #Update the current position
        self.currentPos = newPos

        return movedBullet
Exemplo n.º 25
0
    def __testIGE_BrokerImpl(self, quantity):
        initialCash = 42.09*quantity
        # This testcase is based on an example from Ernie Chan's book:
        # 'Quantitative Trading: How to Build Your Own Algorithmic Trading Business'
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV("ige", common.get_data_file_path("sharpe-ratio-test-ige.csv"))
        strat = strategy_test.TestStrategy(barFeed, initialCash)
        strat.setUseAdjustedValues(True)
        strat.setBrokerOrdersGTC(True)
        stratAnalyzer = drawdown.DrawDown()
        strat.attachAnalyzer(stratAnalyzer)

        # Disable volume checks to match book results.
        strat.getBroker().getFillStrategy().setVolumeLimit(None)

        # Manually place the order to get it filled on the first bar.
        order = strat.getBroker().createMarketOrder(broker.Order.Action.BUY, "ige", quantity, True)  # Adj. Close: 42.09
        order.setGoodTillCanceled(True)
        strat.getBroker().placeOrder(order)
        strat.addOrder(datetime.datetime(2007, 11, 13), strat.getBroker().createMarketOrder, broker.Order.Action.SELL, "ige", quantity, True)  # Adj. Close: 127.64
        strat.run()

        self.assertTrue(round(strat.getBroker().getCash(), 2) == initialCash + (127.64 - 42.09) * quantity)
        self.assertEqual(strat.orderUpdatedCalls, 4)
        self.assertTrue(round(stratAnalyzer.getMaxDrawDown(), 5) == 0.31178)
        self.assertTrue(stratAnalyzer.getLongestDrawDownDuration() == datetime.timedelta(days=623))
 def test_calculatePowerCoefficients(self):
     radius = 35.5
     self.pcPadded.calculatePowerCoefficients(radius)
     windSpeed = 10
     availablePower = 0.5 * pi * np.power(radius, 2) * np.power(windSpeed, 3) * 1.225
     self.assertEqual(round(self.pcPadded.data.ix[20, 'powerCoefficient'], 2),
                      round(self.pcPadded.data.ix[20, 'powerInKilowatts'] * 1000 / availablePower, 2))
def findPointOnSphere(cx, cy, cz, radius, phi, theta):
    #phi - angle around the pole 0<= phi <= 360
    #theta - angle from plan 'up' -90 <= theta <= 90
    x = cx + radius * math.cos(math.radians(theta)) * math.cos(math.radians(phi))
    z = cz + radius * math.cos(math.radians(theta)) * math.sin(math.radians(phi))
    y = cy + radius * math.sin(math.radians(theta))
    return int(round(x,0)), int(round(y,0)), int(round(z,0))
Exemplo n.º 28
0
def Discretdata(data):
    '''
    :param data: DATA FRAME style
    :return: new discreted data
    '''
    import pandas as pd
    from pandas import DataFrame
    import numpy as np

    thres_matrix=data.describe()
    xlen=thres_matrix.shape[1]
    ylen=thres_matrix.shape[0]
    for i in xrange(data.shape[1]):
        x=data.ix[:,i].values
        for j,value in enumerate(x):
            if value > round(thres_matrix.ix[6,i]):
                x[j]=4
            elif value >round(thres_matrix.ix[5,i]):
                x[j]=3
            elif value >round(thres_matrix.ix[4,i]):
                x[j]=2
            elif value >round(thres_matrix.ix[3,i]):
                x[j]=1
            else:
                x[j]=0
    return x
def gradient_check_em():
    init_theta = initialize_theta(None)
    f_approx = {}
    for f in feature_index:
        theta_plus = copy.deepcopy(init_theta)
        theta_minus = copy.deepcopy(init_theta)
        theta_plus[feature_index[f]] = init_theta[feature_index[f]] + EPS
        get_likelihood(theta_plus)  # updates fractional counts
        val_plus = get_likelihood_with_expected_counts(theta_plus)
        theta_minus[feature_index[f]] = init_theta[feature_index[f]] - EPS
        get_likelihood(theta_minus)  # updates fractional counts
        val_minus = get_likelihood_with_expected_counts(theta_minus)
        f_approx[f] = (val_plus - val_minus) / (2 * EPS)

    my_grad = get_gradient(init_theta)
    diff = []
    for k in sorted(f_approx):
        diff.append(abs(my_grad[feature_index[k]] - f_approx[k]))
        print str(round(my_grad[feature_index[k]] - f_approx[k], 3)).center(10), str(
            round(my_grad[feature_index[k]], 5)).center(10), \
            str(round(f_approx[k], 5)).center(10), k
    f_approx = sorted([(feature_index[k], v) for k, v in f_approx.items()])
    f_approx = np.array([v for k, v in f_approx])

    print 'component difference:', round(sum(diff), 3), \
        'cosine similarity:', utils.cosine_sim(f_approx, my_grad), \
        ' sign difference', utils.sign_difference(f_approx, my_grad)
Exemplo n.º 30
0
    def _str(self, i, x):
        """Handles string formatting of cell data

            i - index of the cell datatype in self._dtype 
            x - cell data to format
        """
        try:
            f = float(x)
        except:
            return str(x)

        n = self._precision
        dtype = self._dtype[i]

        if dtype == 'i':
            return str(int(round(f)))
        elif dtype == 'f':
            return '%.*f' % (n, f)
        elif dtype == 'e':
            return '%.*e' % (n, f)
        elif dtype == 't':
            return str(x)
        else:
            if f - round(f) == 0:
                if abs(f) > 1e8:
                    return '%.*e' % (n, f)
                else:
                    return str(int(round(f)))
            else:
                if abs(f) > 1e8:
                    return '%.*e' % (n, f)
                else:
                    return '%.*f' % (n, f)
Exemplo n.º 31
0
while True:
    c = res = 0
    try:
        c+=1
        a = input()
        b = float(input())
        res +=b
    except EOFError:
        print("{:.1f}".format(round(res/c)))
        break
Exemplo n.º 32
0
 def median_distance_for_user(self) -> float:
     return round(self.user_df["Distance (km)"].median(), 2)
Exemplo n.º 33
0
 def percent_not(num, denom):
     return (100 - round((num / denom) * 100))
Exemplo n.º 34
0
 def percent(num, denom):
     return round((num / denom) * 100)
Exemplo n.º 35
0
    # du jour précédent et suivant ayant au moins une valeur correcte
    if (np.isnan(temperature_value_max)):
        temperature_value_max = np.average([
            getNextCorrectValue(si_savukoski, row, 6),
            getPreviousCorrectValue(si_savukoski, row, 6)
        ])
    # SI la valeur min est nulle, alors on va faire la moyenne entre les valeurs min
    # du jour précédent et suivant ayant au moins une valeur correcte
    if (np.isnan(temperature_value_min)):
        temperature_value_min = np.average([
            getNextCorrectValue(si_savukoski, row, 7),
            getPreviousCorrectValue(si_savukoski, row, 7)
        ])

    # On sauvegarde la moyenne entre la température max et la température min.
    temp_avg = round(
        np.average([temperature_value_min, temperature_value_max]), 2)
    month_temperature.append(temp_avg)
    currentMonth = si_savukoski.iloc[row, 1]
    if currentMonth > month:
        temperature_si.append(month_temperature)
        month_temperature = []
        month = currentMonth

temperature_si.append(month_temperature)

temperatures.append(temperature_si)

# In[26]:

# Calcul des moyennes des températures
temperatures_averages.append(getAveragePerArray(temperatures[current_si]))
Exemplo n.º 36
0
#!/usr/bin/env python3

import requests

miner = ""

data = requests.get(f"https://api.ethermine.org/miner/{miner}/dashboard").json()['data']['statistics']
data = data[-1]
current_hash_rate = data["currentHashrate"]
currentMHs = round(current_hash_rate/1e6, 1)

print(f"{currentMHs}MH/s")
Exemplo n.º 37
0
def get_std_dev(variance):
    return round(math.sqrt(variance),1)
Exemplo n.º 38
0
def get_variance(scores, avrg):
    s=0
    for score in scores:
        s+=(score-avrg)**2
    return round(s/len(scores), 1)
Exemplo n.º 39
0
 def setAmount(self, amount: Optional[Union[float, int]]):
     if amount is None:
         # Space forces repaint in case units changed
         self.setText(" ")
     else:
         self.setText(str(round(amount * 100.0) / 100.0))
Exemplo n.º 40
0
 def round(self):
     return round(self.celsius)
Exemplo n.º 41
0
def plotbars(filename, inputdata, upperlabel='Subreddits created', colorbg="#fff", colorfg="#000", colormid="#888", forcezero=False):
    """Create postscript vectors of data

    filename = Name of the file without extension

    inputdata = A list of two lists. First list has the x axis labels, second list
    has the y axis data. x label 14 coresponds to y datum 14, etc.
    """
    print('    Printing', filename)
    t=tkinter.Tk()

    canvas = tkinter.Canvas(t, width=3840, height=2160, bg=colorbg)
    canvas.pack()
    #Y axis
    canvas.create_line(430, 250, 430, 1755, width=10, fill=colorfg)
    #X axis
    canvas.create_line(430, 1750, 3590, 1750, width=10, fill=colorfg)

    dkeys = inputdata[0]
    dvals = inputdata[1]
    entrycount = len(dkeys)
    availablespace = 3140
    availableheight= 1490
    entrywidth = availablespace / entrycount
    #print(dkeys, dvals, "Width:", entrywidth)

    smallest = min(dvals)
    bottom = int(smallest*0.75) - 5
    bottom = 0 if bottom < 8 else rounded(bottom, 10)
    if forcezero:
        bottom = 0
    largest = max(dvals)
    top = int(largest + (largest/5))
    top = rounded(top, 10)
    print(bottom,top)
    span = top-bottom
    perpixel = span/availableheight

    curx = 445
    cury = 1735

    labelx = 420
    labely = 255
    #canvas.create_text(labelx, labely, text=str(top), font=("Consolas", 72), anchor="e")
    labelspan = 130#(1735-255)/10
    canvas.create_text(175, 100, text=upperlabel, font=("Consolas", 72), anchor="w", fill=colorfg)
    for x in range(12):
        value = int(top -((labely - 245) * perpixel))
        value = rounded(value, 10)
        value = '{0:,}'.format(value)
        canvas.create_text(labelx, labely, text=value, font=("Consolas", 72), anchor="e", fill=colorfg)
        canvas.create_line(430, labely, 3590, labely, width=2, fill=colormid)
        labely += labelspan

    for entrypos in range(entrycount):
        entry = dkeys[entrypos]
        entryvalue = dvals[entrypos]
        entryx0 = curx + 10
        entryx1 = entryx0 + (entrywidth-10)
        curx += entrywidth

        entryy0 = cury
        entryy1 = entryvalue - bottom
        entryy1 = entryy1/perpixel
        #entryy1 -= bottom
        #entryy1 /= perpixel
        entryy1 = entryy0 - entryy1
        #print(perpixel, entryy1)
        #print(entry, entryx0,entryy0, entryx1, entryy1)
        canvas.create_rectangle(entryx0,entryy0, entryx1,entryy1, fill=colorfg, outline=colorfg)

        font0x = entryx0 + (entrywidth / 2)
        font0y = entryy1 - 5

        font1y = 1760

        entryvalue = round(entryvalue)
        fontsize0 = len(str(entryvalue)) 
        fontsize0 = round(entrywidth / fontsize0) + 3
        fontsize0 = 100 if fontsize0 > 100 else fontsize0
        fontsize1 = len(str(entry))
        fontsize1 = round(1.5* entrywidth / fontsize1) + 5
        fontsize1 = 60 if fontsize1 > 60 else fontsize1
        canvas.create_text(font0x, font0y, text=entryvalue, font=("Consolas", fontsize0), anchor="s", fill=colorfg)
        canvas.create_text(font0x, font1y, text=entry, font=("Consolas", fontsize1), anchor="n", fill=colorfg)
        canvas.update()
    print('    Done')
    canvas.postscript(file='spooky\\' +filename+".ps", width=3840, height=2160)
    t.geometry("1x1+1+1")
    t.update()
    t.destroy()
Exemplo n.º 42
0
def rounded(x, rounding=100):
    return int(round(x/rounding)) * rounding
Exemplo n.º 43
0
def interpolate_tuple(t0, t1, time, scales):
    return tuple([ round(s * (a * (1.0 - time) + b * time))
                    for a, b, s in zip(t0, t1, scales) ])
Exemplo n.º 44
0
    filenames.append('/scratch/wikipedia-dump/wiki_small_1.json')

df = load_to_spark.main_init_df(filenames)

print("Selecting real users")
df_t_a = df.select(df.title, df.author)
df_t_a = df_t_a.where(col("author").isNotNull())
df_t_bot = df_t_a.where(df_t_a.author.rlike('|'.join(bot_names)))
df_t_user = df_t_a.subtract(df_t_bot)
df_t_user = df_t_user.distinct()
df_t_user.show() #show 1
print("Real Users Selected")

print("getting samples")
count = df_t_user.count()
df_t_user = df_t_user.sample(False, fraction=samples / count, seed = int(round(time.time() * 1000)))
df_t_user.cache()
print(df_t_user.count())

df1 = jaccard_similarity.jaccard_with_crossjoin(df_t_user, "title", "author", maxval=1.0).select(col("title1").alias("t11"), col("title2").alias("t12"), col("jaccard").alias("jaccard1"))
df1 = df1.where((col("jaccard1") != 1.0))
df1.cache()
df1.orderBy(asc("jaccard1")).show()
df1.count()
print("DF1", df1.count())
df2 = jaccard_similarity.jaccard_with_min_hashing(df_t_user, "title", "author", maxval=1.0).select(col("title1").alias("t21"), col("title2").alias("t22"), col("jaccard").alias("jaccard2"))
df2.cache()
df2.orderBy(asc("jaccard2")).show()
print("DF2", df2.count())

if filter == "only_non_similar":
Exemplo n.º 45
0
    def poscommand(self, idxorwp):# Show info on aircraft(int) or waypoint or airport (str)
        """POS command: Show info or an aircraft, airport, waypoint or navaid"""
        # Aircraft index
        if type(idxorwp)==int and idxorwp >= 0:

            idx           = idxorwp
            acid          = self.id[idx]
            actype        = self.type[idx]
            latlon        = latlon2txt(self.lat[idx], self.lon[idx])
            alt           = round(self.alt[idx] / ft)
            hdg           = round(self.hdg[idx])
            trk           = round(self.trk[idx])
            cas           = round(self.cas[idx] / kts)
            tas           = round(self.tas[idx] / kts)
            gs            = round(self.gs[idx]/kts)
            M             = self.M[idx]
            VS            = round(self.vs[idx]/ft*60.)
            route         = self.ap.route[idx]

            # Position report
            lines = "Info on %s %s index = %d\n" %(acid, actype, idx)     \
                  + "Pos: "+latlon+ "\n"                                  \
                  + "Hdg: %03d   Trk: %03d\n"        %(hdg, trk)              \
                  + "Alt: %d ft  V/S: %d fpm\n"  %(alt,VS)                \
                  + "CAS/TAS/GS: %d/%d/%d kts   M: %.3f\n"%(cas,tas,gs,M)

            # FMS AP modes
            if self.swlnav[idx] and route.nwp > 0 and route.iactwp >= 0:

                if self.swvnav[idx]:
                    if self.swvnavspd[idx]:
                        lines = lines + "VNAV (incl.VNAVSPD), "
                    else:
                        lines = lines + "VNAV (NOT VNAVSPD), "

                lines += "LNAV to " + route.wpname[route.iactwp] + "\n"

            # Flight info: Destination and origin
            if self.ap.orig[idx] != "" or self.ap.dest[idx] != "":
                lines = lines +  "Flying"

                if self.ap.orig[idx] != "":
                    lines = lines +  " from " + self.ap.orig[idx]

                if self.ap.dest[idx] != "":
                    lines = lines +  " to " + self.ap.dest[idx]

            # Show a/c info and highlight route of aircraft in radar window
            # and pan to a/c (to show route)
            bs.scr.showroute(acid)
            return True, lines

        # Waypoint: airport, navaid or fix
        else:
            wp = idxorwp.upper()

            # Reference position for finding nearest
            reflat, reflon = bs.scr.getviewctr()

            lines = "Info on "+wp+":\n"

            # First try airports (most used and shorter, hence faster list)
            iap = bs.navdb.getaptidx(wp)
            if iap>=0:
                aptypes = ["large","medium","small"]
                lines = lines + bs.navdb.aptname[iap]+"\n"                 \
                        + "is a "+ aptypes[max(-1,bs.navdb.aptype[iap]-1)] \
                        +" airport at:\n"                                    \
                        + latlon2txt(bs.navdb.aptlat[iap],                 \
                                     bs.navdb.aptlon[iap]) + "\n"          \
                        + "Elevation: "                                      \
                        + str(int(round(bs.navdb.aptelev[iap]/ft)))        \
                        + " ft \n"

               # Show country name
                try:
                    ico = bs.navdb.cocode2.index(bs.navdb.aptco[iap].upper())
                    lines = lines + "in "+bs.navdb.coname[ico]+" ("+      \
                             bs.navdb.aptco[iap]+")"
                except:
                    ico = -1
                    lines = lines + "Country code: "+bs.navdb.aptco[iap]
                try:
                    runways = bs.navdb.rwythresholds[bs.navdb.aptid[iap]].keys()
                    if runways:
                        lines = lines + "\nRunways: " + ", ".join(runways)
                except:
                    pass

            # Not found as airport, try waypoints & navaids
            else:
                iwps = bs.navdb.getwpindices(wp,reflat,reflon)
                if iwps[0]>=0:
                    typetxt = ""
                    desctxt = ""
                    lastdesc = "XXXXXXXX"
                    for i in iwps:

                        # One line type text
                        if typetxt == "":
                            typetxt = typetxt+bs.navdb.wptype[i]
                        else:
                            typetxt = typetxt+" and "+bs.navdb.wptype[i]

                        # Description: multi-line
                        samedesc = bs.navdb.wpdesc[i]==lastdesc
                        if desctxt == "":
                            desctxt = desctxt +bs.navdb.wpdesc[i]
                            lastdesc = bs.navdb.wpdesc[i]
                        elif not samedesc:
                            desctxt = desctxt +"\n"+bs.navdb.wpdesc[i]
                            lastdesc = bs.navdb.wpdesc[i]

                        # Navaid: frequency
                        if bs.navdb.wptype[i] in ["VOR","DME","TACAN"] and not samedesc:
                            desctxt = desctxt + " "+ str(bs.navdb.wpfreq[i])+" MHz"
                        elif bs.navdb.wptype[i]=="NDB" and not samedesc:
                            desctxt = desctxt+ " " + str(bs.navdb.wpfreq[i])+" kHz"

                    iwp = iwps[0]

                    # Basic info
                    lines = lines + wp +" is a "+ typetxt       \
                           + " at\n"\
                           + latlon2txt(bs.navdb.wplat[iwp],  \
                                        bs.navdb.wplon[iwp])
                    # Navaids have description
                    if len(desctxt)>0:
                        lines = lines+ "\n" + desctxt

                    # VOR give variation
                    if bs.navdb.wptype[iwp]=="VOR":
                        lines = lines + "\nVariation: "+ \
                                     str(bs.navdb.wpvar[iwp])+" deg"


                    # How many others?
                    nother = bs.navdb.wpid.count(wp)-len(iwps)
                    if nother>0:
                        verb = ["is ","are "][min(1,max(0,nother-1))]
                        lines = lines +"\nThere "+verb + str(nother) +\
                                   " other waypoint(s) also named " + wp

                    # In which airways?
                    connect = bs.navdb.listconnections(wp, \
                                                bs.navdb.wplat[iwp],
                                                bs.navdb.wplon[iwp])
                    if len(connect)>0:
                        awset = set([])
                        for c in connect:
                            awset.add(c[0])

                        lines = lines+"\nAirways: "+"-".join(awset)


               # Try airway id
                else:  # airway
                    awid = wp
                    airway = bs.navdb.listairway(awid)
                    if len(airway)>0:
                        lines = ""
                        for segment in airway:
                            lines = lines+"Airway "+ awid + ": " + \
                                    " - ".join(segment)+"\n"
                        lines = lines[:-1] # cut off final newline
                    else:
                        return False,idxorwp+" not found as a/c, airport, navaid or waypoint"

            # Show what we found on airport and navaid/waypoint
            return True, lines
Exemplo n.º 46
0
    def find_solution(self):
        """ Finds paths for all agents from their start locations to their goal locations
        """

        self.start_time = timer.time()
        init_groups = list([
            i,
        ] for i in range(self.num_of_agents))
        root = {
            'cost': 0,
            'constraints': [],
            'paths': [],
            'groups': init_groups
        }
        for i in range(self.num_of_agents):  # Find initial path for each agent
            path = a_star(self.my_map, self.starts[i], self.goals[i],
                          self.heuristics[i], i, root['constraints'])
            if path is None:
                raise BaseException('No solutions')
            root['paths'].append(path)

        root['cost'] = get_sum_of_cost(root['paths'])
        self.push_node(root)

        # High-Level Search
        while len(self.open_list) > 0:
            if timer.time() - self.start_time > 100:
                raise Exception('timeout|' + str(self.num_of_expanded) + '|' +
                                str(self.num_of_generated) + '|' +
                                str(round(timer.time() - self.start_time, 2)))
            # print("===high-level loop===")
            curr = self.pop_node()
            # print("curr", curr)
            new_collision = detect_collisions(curr['paths'], curr['groups'])
            if new_collision is None:
                # print(curr['paths'])
                self.print_results(curr)
                CPU_time = timer.time() - self.start_time
                return (curr['paths'], "{:.03f}".format(CPU_time),
                        self.num_of_expanded, self.num_of_generated)
            # check should merge
            group_idx1 = new_collision['group1']
            group_idx2 = new_collision['group2']
            group1 = curr['groups'][group_idx1]
            group2 = curr['groups'][group_idx2]
            cnt = count_collision(self.conflict_matrix, group1, group2)
            if cnt > self.B:  # should-merge
                # print("Merging meta-agents {} and {} with total conflict count {}".format(group1, group2, cnt))
                child = init_node_from_parent(curr)
                # update constraints
                update_constraints(group1, group2, group_idx1, group_idx2,
                                   child)
                # update solutions
                agents_need_update = child['groups'][group_idx1]
                keep = compute_paths(self.my_map, self.starts, self.goals,
                                     self.heuristics, agents_need_update,
                                     child, group_idx1)
                # print("keep", keep)
                if keep:
                    child['cost'] = get_sum_of_cost(child['paths'])
                    self.push_node(child)
                    # print("openlist", self.open_list)
                continue
            else:  # basic CBS
                new_constraints = standard_splitting(new_collision)
                for constraint in new_constraints:
                    child = init_node_from_parent(curr)
                    child['constraints'].append(constraint)
                    agents_need_update = constraint['agent']
                    keep = compute_paths(self.my_map, self.starts, self.goals,
                                         self.heuristics, agents_need_update,
                                         child)
                    if keep:
                        child['cost'] = get_sum_of_cost(child['paths'])
                        self.push_node(child)
        raise Exception('No Solutions|' + str(self.num_of_expanded) + '|' +
                        str(self.num_of_generated) + '|' +
                        str(round(timer.time() - self.start_time, 2)))
Exemplo n.º 47
0
def edge_strength(x, weight, base):
    res = round(base + (weight * abs(x)), 3)
    return str(res)
Exemplo n.º 48
0
    def create(self, n=1, actype="B744", acalt=None, acspd=None, dest=None,
                aclat=None, aclon=None, achdg=None, acid=None):
        """ Create multiple random aircraft in a specified area """
        area = bs.scr.getviewbounds()
        if acid is None:
            idtmp = chr(randint(65, 90)) + chr(randint(65, 90)) + '{:>05}'
            acid = [idtmp.format(i) for i in range(n)]

        elif isinstance(acid, str):
            # Check if not already exist
            if self.id.count(acid.upper()) > 0:
                return False, acid + " already exists."  # already exists do nothing
            acid = [acid]
        else:
            # TODO: for a list of a/c, check each callsign
            pass

        super(Traffic, self).create(n)

        # Increase number of aircraft
        self.ntraf += n

        if aclat is None:
            aclat = np.random.rand(n) * (area[1] - area[0]) + area[0]
        elif isinstance(aclat, (float, int)):
            aclat = np.array(n * [aclat])

        if aclon is None:
            aclon = np.random.rand(n) * (area[3] - area[2]) + area[2]
        elif isinstance(aclon, (float, int)):
            aclon = np.array(n * [aclon])

        # Limit longitude to [-180.0, 180.0]
        if n == 1:
            aclon = aclon - 360 if aclon > 180 else \
                    aclon + 360 if aclon < -180.0 else aclon
        else:
            aclon[aclon > 180.0] -= 360.0
            aclon[aclon < -180.0] += 360.0

        if achdg is None:

            achdg = np.random.randint(1, 360, n)
        elif isinstance(achdg, (float, int)):
            achdg = np.array(n * [achdg])

        if acalt is None:
            acalt = np.random.randint(2000, 39000, n) * ft
        elif isinstance(acalt, (float, int)):
            acalt = np.array(n * [acalt])

        if acspd is None:
            acspd = np.random.randint(250, 450, n) * kts
        elif isinstance(acspd,(float, int)):
            acspd = np.array(n * [acspd])

        actype = n * [actype] if isinstance(actype, str) else actype
        dest = n * [dest] if isinstance(dest, str) else dest

        # SAVEIC: save cre command when filled in
        # Special provision in case SAVEIC is on: then save individual CRE commands
        # Names of aircraft (acid) need to be recorded for saved future commands
        # And positions need to be the same in case of *MCRE"
        for i in range(n):
            bs.stack.savecmd(" ".join([ "CRE", acid[i], actype[i],
                                        str(aclat[i]), str(aclon[i]), str(int(round(achdg[i]))),
                                        str(int(round(acalt[i]/ft))),
                                        str(int(round(acspd[i]/kts)))]))

        # Aircraft Info
        self.id[-n:]   = acid
        self.type[-n:] = actype

        # Positions
        self.lat[-n:]  = aclat
        self.lon[-n:]  = aclon
        self.alt[-n:]  = acalt

        self.hdg[-n:]  = achdg
        self.trk[-n:]  = achdg

        # Velocities
        self.tas[-n:], self.cas[-n:], self.M[-n:] = vcasormach(acspd, acalt)
        self.gs[-n:]      = self.tas[-n:]
        hdgrad = np.radians(achdg)
        self.gsnorth[-n:] = self.tas[-n:] * np.cos(hdgrad)
        self.gseast[-n:] = self.tas[-n:] * np.sin(hdgrad)

        # Atmosphere
        self.p[-n:], self.rho[-n:], self.Temp[-n:] = vatmos(acalt)

        # Wind
        if self.wind.winddim > 0:
            applywind         = self.alt[-n:]> 50.*ft
            self.windnorth[-n:], self.windeast[-n:]  = self.wind.getdata(self.lat[-n:], self.lon[-n:], self.alt[-n:])
            self.gsnorth[-n:] = self.gsnorth[-n:] + self.windnorth[-n:]*applywind
            self.gseast[-n:]  = self.gseast[-n:]  + self.windeast[-n:]*applywind
            self.trk[-n:]     = np.logical_not(applywind)*achdg + \
                                applywind*np.degrees(np.arctan2(self.gseast[-n:], self.gsnorth[-n:]))
            self.gs[-n:]      = np.sqrt(self.gsnorth[-n:]**2 + self.gseast[-n:]**2)
        else:
            self.windnorth[-n:] = 0.0
            self.windeast[-n:]  = 0.0

        # Traffic performance data
        #(temporarily default values)
        self.apvsdef[-n:] = 1500. * fpm   # default vertical speed of autopilot
        self.aphi[-n:]    = 0.            # bank angle output of autopilot (optional)
        self.ax[-n:]      = kts           # absolute value of longitudinal accelleration
        self.bank[-n:]    = np.radians(25.)

        # Traffic autopilot settings
        self.selspd[-n:] = self.cas[-n:]
        self.aptas[-n:]  = self.tas[-n:]
        self.selalt[-n:] = self.alt[-n:]

        # Display information on label
        self.label[-n:] = n*[['', '', '', 0]]

        # Miscallaneous
        self.coslat[-n:] = np.cos(np.radians(aclat))  # Cosine of latitude for flat-earth aproximations
        self.eps[-n:] = 0.01

        # Finally call create for child TrafficArrays. This only needs to be done
        # manually in Traffic.
        self.create_children(n)
Exemplo n.º 49
0
def flash_spawn_test(old_score, score ,delta, beans, bean_speed):
    delta += score - old_score
    if delta >= 5000:
        beans.add(Flash_Bean(randint(10,480), round(uniform(1,bean_speed))))
        delta = 0
    return delta
Exemplo n.º 50
0
def main():

    pygame.mixer.pre_init(44100, -16, 2, 1536)
    pygame.mixer.init()
    pygame.init()
    screen = pygame.display.set_mode(screensize)
    pygame.display.set_caption("Bird & Beans")

#Prepare Game Resources
    #Values
    score = 0
    old_score = 0
    player_speed = 3
    bean_speed = 2
    angel_speed_scale = 1
    spawn_idx = 0
    collide_flag = False
    game_over = False
    game_over2 = True
    help_screen = False
    countdown = 0
    countdown2 = 1
    delta = 0
    stage = 0
    respawn_bean = pygame.event.Event(RESPAWNBEAN)
    pygame.time.set_timer(SPAWNBEAN, spawn_time[spawn_idx])
    clock = pygame.time.Clock()

    #Objects / Resources
    player = Player()
    spit_line = Spit_line()
    back = Background(path.join("images", "back1_4.png"))
    frame = Background(path.join("images", "frame2.png"))
    beans = pygame.sprite.Group()
    blocks = pygame.sprite.Group()
    angels = pygame.sprite.Group()
    blockArr = []
    #go through and create 30 blocks
    for i in range(0,30):
        x = (1+i)*16
        y = 352
        block = Block(x, y)
        blocks.add(block)
        blockArr.append(block)
    l_edge = Block(0,352)   #make the edges
    r_edge = Block(496,352)
    l_edge.visible = False
    r_edge.visible = False
    l_edge.active = False
    r_edge.active = False
    l_edge.hitbox.move_ip(0,-2)
    r_edge.hitbox.move_ip(0,-2)
    blockArr.append(l_edge)
    blockArr.append(r_edge)
    active_sprite_list = pygame.sprite.Group()
    active_sprite_list.add(player)

    #Sounds
    spit_sound = pygame.mixer.Sound(path.join("sounds", "spit.ogg"))
    bgm1_sound = pygame.mixer.Sound(path.join("sounds", "bgm1.ogg"))
    Angel_sound = pygame.mixer.Sound(path.join("sounds", "Angel.ogg"))
    Die_sound = pygame.mixer.Sound(path.join("sounds", "Die.ogg"))
    Game_Over_sound = pygame.mixer.Sound(path.join("sounds", "Game_Over.ogg"))
    Kill_Bean_sound = pygame.mixer.Sound(path.join("sounds", "Kill_Bean.ogg"))
    walk_sound = pygame.mixer.Sound(path.join("sounds", "walk3.ogg"))
    bomb_sound = pygame.mixer.Sound(path.join("sounds", "bomb.ogg"))
    bgm1_sound.play(-1)

    done = False

    #Main Loop
    while not done:

  # ***EVENTS***
        #handle single events
        for event in pygame.event.get(): # User did something
            if event.type == pygame.QUIT: # If user clicked close
                done = True # Flag that we are done so we exit this loop
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_z:
                    spit_sound.play()
                    player.stop()
                    player.spit()
                elif event.key == pygame.K_F1:
                    help_screen = True
                elif event.key == pygame.K_ESCAPE:
                    done = True
            elif event.type == SPAWNBEAN:
                testnum = randint(1,100)
                if testnum <= 13:
                    beans.add(White_Bean(randint(10,480), uniform(1,bean_speed)))
                else:
                    beans.add(Bean(randint(10,480), uniform(1,bean_speed)))
            elif event.type == RESPAWNBEAN:
                location = round(player.rect.x / 16) * 16
                if(block_test(blocks) == True):
                    Angel_sound.play()
                    spawn_loc = angel_spawn(location, blockArr)
                    angels.add(Angel(spawn_loc, blockArr[int(spawn_loc / 16)]))
            elif event.type == FLASHBEANHIT:
                if block_test(blocks) == False:
                    countdown = 0
                if(countdown > 0):
                    countdown -= 1
                if countdown == 0:
                    pygame.time.set_timer(FLASHBEANHIT, 0)
                    pygame.time.set_timer(RESPAWNBEAN, 0)
            elif event.type == KILLBEANS:
                for bean in beans:
                    beans.remove(bean)
                    bean.kill()
                    Kill_Bean_sound.play()
                    score += 50
                    break
                if len(beans) == 0:
                    pygame.time.set_timer(KILLBEANS, 0)


        #handle held down events
        keyState = pygame.key.get_pressed()
        if keyState[pygame.K_RIGHT] and player.spitt != True:
            walk_sound.play()
            player.go_right(player_speed)
            spit_line.go_right(player_speed)
        elif keyState[pygame.K_LEFT] and player.spitt != True:
            walk_sound.play()
            player.go_left(player_speed)
            spit_line.go_left(player_speed)
        else:
            player.stop()
        pygame.event.pump()


  # ***COLLISION***
        #handle bean collision with floor and player
        remove_one_flag = True
        for bean in beans:
            if bean.hitbox.y >= 295:
                for i in range(0,30):
                    if bean.hitbox.colliderect(blockArr[i].rect) and blockArr[i].visible == True and remove_one_flag == True:
                        bomb_sound.play()
                        beans.remove(bean)
                        bean.kill()
                        blockArr[i].visible = False
                        blockArr[i].active = False
                        blockArr[i].hitbox.move_ip(0,-2)
                        remove_one_flag = False
                    else:
                        remove_one_flag = True
            #test for hitting player and game over
            game_over = player_death_test(bean, player, game_over)
            if game_over == True and game_over2 == True:
                bgm1_sound.stop()
                Die_sound.play()
                Game_Over_sound.play()
                game_over2 = False
            if bean.rect.y >= 400:
                beans.remove(bean)
                bean.kill()

        #handle spit_line collision
        if collide_flag == True:
            collisions = pygame.sprite.spritecollide(spit_line, beans, False, pygame.sprite.collide_mask)
            score = update_score(len(collisions) , score)
            for sprite in collisions:
                if sprite.color == "white":
                    pygame.event.post(respawn_bean)
                elif sprite.color == "flash":
                    pygame.time.set_timer(KILLBEANS, 100)
                    pygame.time.set_timer(FLASHBEANHIT, 200)
                    pygame.time.set_timer(RESPAWNBEAN, 200)
                    countdown = 10
                Kill_Bean_sound.play()
                beans.remove(sprite)
                sprite.kill()


  # ***UPDATES***
        collide_flag = player.update()
        player_collisions(blockArr, player,spit_line, player_speed)
        spit_line.update()
        blocks.update()
        beans.update()
        for angel in angels:    #delete angels who are out of screen
            if angel.rect.y < -64:
                angels.remove(angel)
                angel.kill()
        angels.update(angel_speed_scale)

        #Tests to check whether or not to update certain values
        spawn_faster = False
        spawn_faster = update_spawn_time(old_score, score)
        if spawn_faster == True:
            spawn_idx += 1
            pygame.time.set_timer(SPAWNBEAN, spawn_time[spawn_idx])
        delta = flash_spawn_test(old_score, score ,delta, beans, bean_speed)
        bean_speed = update_speed_test(score, stage, bean_speed);
        stage = stage_test(bean_speed)
        old_score = score



        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        back.draw(screen)
        blocks.draw(screen)
        beans.draw(screen)
        frame.draw(screen)
        angels.draw(screen)
        active_sprite_list.draw(screen)
        draw_text(screen, "SCORE: " + str(score), 14, 250, 26)
        if game_over == True:
            draw_text(screen, "GAME OVER", 25 ,250 , 150)
        if help_screen == True:
            pygame.time.set_timer(SPAWNBEAN, 0)
            if countdown2 > 0:
                screen.fill((0,0,0))
                draw_text(screen, "Objective: Keep the beans from hitting your head", 18, 265, 25)
                draw_text(screen, "Press Z to spit in a diagonal line and clear the beans", 18, 265, 125)
                draw_text(screen, "Hitting multiple beans at the same time gives a higher score", 18, 265, 225)
                draw_text(screen, "Go for a high score!", 18,265, 325)
                countdown2 -= 1
            else:
                pygame.time.wait(10000)
                pygame.time.set_timer(SPAWNBEAN, spawn_time[spawn_idx])
                help_screen = False
        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        clock.tick(40)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
Exemplo n.º 51
0
    def start_monitor_process(self):
        pass
        now = datetime.datetime.now()
        lunch_start_time = datetime.datetime.strptime(
            '10:00:00', '%H:%M:%S').replace(year=now.year,
                                            month=now.month,
                                            day=now.day)
        lunch_end_time = datetime.datetime.strptime(
            '10:25:00', '%H:%M:%S').replace(year=now.year,
                                            month=now.month,
                                            day=now.day)
        supper_start_time = datetime.datetime.strptime(
            '15:40:00', '%H:%M:%S').replace(year=now.year,
                                            month=now.month,
                                            day=now.day)
        supper_end_time = datetime.datetime.strptime(
            '16:20:00', '%H:%M:%S').replace(year=now.year,
                                            month=now.month,
                                            day=now.day)
        snack_start_time = datetime.datetime.strptime(
            '20:59:00', '%H:%M:%S').replace(year=now.year,
                                            month=now.month,
                                            day=now.day)
        snack_end_time = datetime.datetime.strptime(
            '21:15:00', '%H:%M:%S').replace(year=now.year,
                                            month=now.month,
                                            day=now.day)

        if lunch_start_time < now:
            lunch_start_time = lunch_start_time + datetime.timedelta(days=1)
        time_to_lunch_start = int(
            round(
                (lunch_start_time - datetime.datetime.now()).total_seconds()))

        if lunch_end_time < now:
            lunch_end_time = lunch_end_time + datetime.timedelta(days=1)
        time_to_lunch_end = int(
            round((lunch_end_time - datetime.datetime.now()).total_seconds()))

        if supper_start_time < now:
            supper_start_time = supper_start_time + datetime.timedelta(days=1)
        time_to_supper_start = int(
            round(
                (supper_start_time - datetime.datetime.now()).total_seconds()))

        if supper_end_time < now:
            supper_end_time = supper_end_time + datetime.timedelta(days=1)
        time_to_supper_end = int(
            round((supper_end_time - datetime.datetime.now()).total_seconds()))

        if snack_start_time < now:
            snack_start_time = snack_start_time + datetime.timedelta(days=1)
        time_to_snack_start = int(
            round(
                (snack_start_time - datetime.datetime.now()).total_seconds()))

        if snack_end_time < now:
            snack_end_time = snack_end_time + datetime.timedelta(days=1)
        time_to_snack_end = int(
            round((snack_end_time - datetime.datetime.now()).total_seconds()))

        self.lunch_start_monitor = threading.Timer(time_to_lunch_start,
                                                   self.order_lunch_start)
        self.lunch_start_monitor.start()

        self.lunch_end_monitor = threading.Timer(time_to_lunch_end,
                                                 self.order_lunch_end)
        self.lunch_end_monitor.start()

        self.supper_start_monitor = threading.Timer(time_to_supper_start,
                                                    self.order_supper_start)
        self.supper_start_monitor.start()

        self.supper_end_monitor = threading.Timer(time_to_supper_end,
                                                  self.order_supper_end)
        self.supper_end_monitor.start()

        self.snack_start_monitor = threading.Timer(time_to_snack_start,
                                                   self.order_snack_start)
        self.snack_start_monitor.start()

        self.snack_end_monitor = threading.Timer(time_to_snack_end,
                                                 self.order_snack_end)
        self.snack_end_monitor.start()
Exemplo n.º 52
0
                greatest_decrease = current_profit - previous_profit
                greatest_decrease_month = row[0]
            if current_profit - previous_profit > greatest_increase:
                greatest_increase = current_profit - previous_profit
                greatest_increase_month = row[0]
                
        #update total months
        total_months = total_months + 1
        
        #add the profits of the current row to the total profits
        sum_profits = sum_profits + current_profit

#print results
print(f"Total Months: {total_months}")
print(f"Total: ${sum_profits}")

#there are total_months profit entries, so only total_months - 1 changes in profits
average_change = round(( current_profit - first_profit ) / (total_months - 1), 2)
print(f"Average Change: ${average_change}")
print(f"Greatest Increase in Profits: {greatest_increase_month}  (${greatest_increase})" )
print(f"Greatest Decrease in Profits: {greatest_decrease_month}  (${greatest_decrease})" )

#create new file and add results
file = open("results.txt", "w")
file.write(f"Total Months: {total_months}\n")
file.write(f"Total: ${sum_profits}\n")
file.write(f"Average Change: ${average_change}\n")
file.write(f"Greatest Increase in Profits: {greatest_increase_month}  (${greatest_increase})\n")
file.write(f"Greatest Decrease in Profits: {greatest_decrease_month}  (${greatest_decrease})\n" )
file.close()
Exemplo n.º 53
0
 def outputColor(self, colorNumber):
     colorR = round(self.redColorArray[colorNumber] / 31 * 255)
     colorG = round(self.greenColorArray[colorNumber] / 31 * 255)
     colorB = round(self.blueColorArray[colorNumber] / 31 * 255)
     hexValue = "#%02x%02x%02x" % (colorR, colorG, colorB)
     return hexValue
Exemplo n.º 54
0
def main():
    engine = create_engine('mysql+pymysql://%s:%s@%s:%d/%s' % (user, passwd, server, port, db),
                           echo=False)
    conn = engine.connect()

    api_key = ''

    tier_to_point = {'IRON':0, 'BRONZE':4, 'SILVER':8, 'GOLD':12, 'PLATINUM':16, 'DIAMOND':20, 'MASTER':23, 'GRANDMASTER':25, 'CHALLENGER':27}
    rank_to_point = {'IV':0, 'III':1, 'II':2, 'I':3}
    
    point_to_tier_under_m = {0:'IRON', 1:'BRONZE', 2:'SILVER', 3:'GOLD', 4:'PLATINUM', 5:'DIAMOND'}
    point_to_rank = {0:' IV', 1:' III', 2:' II', 3:' I'}
    point_to_tier_over_m = {0:'DIAMOND I', 1:'MASTER', 2:'GRANDMASTER', 3:'CHALLENGER'}
    
    
    matchid_df = pd.read_csv('c_matchid.csv')
    
    gameid_already_in_tuple = engine.execute('SELECT gameId FROM match_id GROUP BY gameId').fetchall()
    gameid_already_in = [gameId_tuple[0] for gameId_tuple in gameid_already_in_tuple]
    
    
    i = 0
    for j in range(53000, 68600):
        now_matchid = str(matchid_df.iloc[j]['gameId'].item())
        
        if now_matchid in gameid_already_in:
            print(now_matchid + ' already in')
            continue


        data_url = 'https://kr.api.riotgames.com/lol/match/v4/matches/' + now_matchid + '?api_key=' + str(api_list[i])
        data_json = request_url(data_url)

        match = pd.DataFrame(list(data_json.values()), index=list(data_json.keys())).T
        summoner_ids = pd.DataFrame(dict(pd.DataFrame(match['participantIdentities'].iloc[0])['player'])).T['summonerId']
        season = match['gameVersion'].item().split('.')[0]
        version = match['gameVersion'].item().split('.')[1]


        point_sum = 0
        ranked_count = 0
        for k in range(10):
            summoner_url = 'https://kr.api.riotgames.com/lol/league/v4/entries/by-summoner/' + summoner_ids.iloc[k] + '?api_key=' + str(api_list[i])
            summoner_json = request_url(summoner_url)
            summoner_df = pd.DataFrame(summoner_json)

            if len(summoner_df) == 0: # unranked
                continue

            if 'RANKED_SOLO_5x5' not in list(summoner_df['queueType']): # solo unranked
                continue

            summoner_rank_df = summoner_df[summoner_df['queueType']=='RANKED_SOLO_5x5']
            tier = summoner_rank_df['tier'].item()
            rank = summoner_rank_df['rank'].item()

            point = tier_to_point[tier] + rank_to_point[rank]
            ranked_count += 1
            if tier == 'DIAMOND' and rank == 'I':
                point += 1
            point_sum += point

        if ranked_count == 0:
            tier = 'UNRANKED'
        else:
            point_average = point_sum/ranked_count
            if point_average//4 < 6:
                point_under_m = round(point_average) // 4
                if point_under_m == 6:
                    tier = 'DIAMOND I'
                else:
                    rank_under_m = round(point_average) % 4
                    tier = point_to_tier_under_m[point_under_m] + point_to_rank[rank_under_m]
            else:
                point_over_m = round((point_average-24)/2)
                tier = point_to_tier_over_m[point_over_m]

        match_dict = {'gameId':now_matchid, 'season':season, 'version':version, 'averageTier':tier}
        match_df = pd.DataFrame(match_dict, index=[0])
        match_df.to_sql('match_id', con=engine, index=False, if_exists='append')

        print(now_matchid + ' matchid in')
        
        i += 1
        if i == 7:
            i = 0
            
            
    conn.close()
Exemplo n.º 55
0
async def download(target_file):
    """ For .download command, download files to the userbot's server. """
    await target_file.edit("Processing ...")
    input_str = target_file.pattern_match.group(1)
    if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
        os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
    if "|" in input_str:
        url, file_name = input_str.split("|")
        url = url.strip()
        # https://stackoverflow.com/a/761825/4723940
        file_name = file_name.strip()
        head, tail = os.path.split(file_name)
        if head:
            if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)):
                os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head))
                file_name = os.path.join(head, tail)
        downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "/" + file_name
        downloader = SmartDL(url, downloaded_file_name, progress_bar=False)
        downloader.start(blocking=False)
        c_time = time.time()
        display_message = None
        while not downloader.isFinished():
            status = downloader.get_status().capitalize()
            total_length = downloader.filesize if downloader.filesize else None
            downloaded = downloader.get_dl_size()
            now = time.time()
            diff = now - c_time
            percentage = downloader.get_progress() * 100
            speed = downloader.get_speed()
            progress_str = "[{0}{1}] `{2}%`".format(
                "".join(["■" for i in range(math.floor(percentage / 10))]),
                "".join(["▨" for i in range(10 - math.floor(percentage / 10))]),
                round(percentage, 2),
            )
            estimated_total_time = downloader.get_eta(human=True)
            try:
                current_message = (
                    f"`Name` : `{file_name}`\n"
                    "Status"
                    f"\n**{status}**... | {progress_str}"
                    f"\n{humanbytes(downloaded)} of {humanbytes(total_length)}"
                    f" @ {speed}"
                    f"\n`ETA` -> {estimated_total_time}"
                )

                if round(diff % 10.00) == 0 and current_message != display_message:
                    await target_file.edit(current_message)
                    display_message = current_message
            except Exception as e:
                LOGS.info(str(e))
        if downloader.isSuccessful():
            await target_file.edit(
                "Downloaded to `{}` successfully !!".format(downloaded_file_name)
            )
        else:
            await target_file.edit("Incorrect URL\n{}".format(url))
    elif target_file.reply_to_msg_id:
        try:
            c_time = time.time()
            downloaded_file_name = await target_file.client.download_media(
                await target_file.get_reply_message(),
                TEMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, target_file, c_time, "[DOWNLOAD]")
                ),
            )
        except Exception as e:  # pylint:disable=C0103,W0703
            await target_file.edit(str(e))
        else:
            await target_file.edit(
                "Downloaded to `{}` successfully !!".format(downloaded_file_name)
            )
    else:
        await target_file.edit("Reply to a message to download to my local server.")
Exemplo n.º 56
0
def main(argv):
    maze = argv[0] if len(argv) > 0 else "../Mazes/maze01.txt"
    model = argv[1] if len(argv) > 1 else "../Models/auto-gen-c.pkl"
    show_freq = int(
        argv[2]) if len(argv) > 2 else 0  # frequency to show frames
    directory_name = argv[5] if len(argv) > 5 else "tmp_diagnostics"
    # cmd_in = bool(distutils.util.strtobool(argv[6]) if len(argv) > 6 else False
    print("DIR NAME: " + directory_name)

    model_type = (argv[3] if len(argv) > 3 else "c"
                  )  # 'c' for classification, 'r' for regresssion
    stacked = (
        bool(distutils.util.strtobool(argv[4])) if len(argv) > 4 else False
    )  # True for stacked input

    world = PycastWorld(320, 240, maze)

    if model_type == "cmd" or model_type == "rnn":
        model_inf = ConvRNN()
        model_inf.load_state_dict(torch.load(model))
    else:
        path = Path("../")
        model_inf = load_learner(model)

    prev_move = None
    prev_image_data = None
    frame = 0
    frame_freq = 5
    num_static = 0
    prev_x, prev_y = world.x(), world.y()
    animation_frames = []

    outcome = "At goal? "
    stuck = False
    # Initialize maximum number of steps in case the robot travels in a completely incorrect direction
    max_steps = 3500

    # Initialize Maze Check
    maze_rvs, _, _, maze_directions, _ = read_maze_file(maze)
    start_x, start_y, _ = maze_directions[0]
    end_x, end_y, _ = maze_directions[-1]
    _, maze_path = bfs_dist_maze(maze_rvs, start_x, start_y, end_x, end_y)
    on_path = is_on_path(maze_path, int(world.x()), int(world.y()))

    print("Predicting...")
    while not world.at_goal() and num_static < 5 and on_path:

        # Get image
        image_data = np.array(world)

        # Convert image_data and give to network
        if model_type == "c":
            if stacked:
                move = model_inf.predict(
                    stacked_input(prev_image_data, image_data))[0]
            else:
                move = model_inf.predict(image_data)[0]
        elif model_type == "r":
            if stacked:
                pred_coords, _, _ = model_inf.predict(
                    stacked_input(prev_image_data, image_data))
            else:
                pred_coords, _, _ = model_inf.predict(image_data)
            move = reg_predict(pred_coords)
        elif model_type == "cmd":
            model_inf.eval()
            # Predict
            tmp_move_indx = 2 if prev_move == "straight" else 1 if prev_move == "right" else 0
            img = (tensor(image_data) / 255).permute(2, 0, 1).unsqueeze(0)
            cmd = tensor([tmp_move_indx])
            output = model_inf((img, cmd))
            # Assuming we always get batches
            if output.size()[0] > 0:
                for i in range(output.size()[0]):
                    # Getting the predicted most probable move
                    action_index = torch.argmax(output[i])
                    move = 'left' if action_index == 0 else 'right' if action_index == 1 else 'straight'
            else:
                # is there any reason for us to believe batch sizes can be empty?
                move = 'straight'
        elif model_type == "rnn":
            model_inf.eval()
            img = (tensor(image_data) / 255).permute(
                2, 0, 1).unsqueeze(0).unsqueeze(0)
            output = model_inf(img)
            # Assuming we always get batches
            for i in range(output.size()[0]):
                # Getting the predicted most probable move
                action_index = torch.argmax(output[i])
                move = 'left' if action_index == 0 else 'right' if action_index == 1 else 'straight'

        if move == "left" and prev_move == "right":
            move = "straight"
        elif move == "right" and prev_move == "left":
            move = "straight"

        # Move in world
        if move == "straight":
            world.walk(Walk.Forward)
            world.turn(Turn.Stop)
        elif move == "left":
            world.walk(Walk.Stop)
            world.turn(Turn.Left)
        else:
            world.walk(Walk.Stop)
            world.turn(Turn.Right)

        prev_move = move
        world.update()
        curr_x, curr_y = round(world.x(), 5), round(world.y(), 5)

        if show_freq != 0 and frame % show_freq == 0:
            if int(curr_x) == int(prev_x) and int(curr_y) == int(prev_y):
                num_static += 1
            else:
                maze_path.remove((int(prev_x), int(prev_y)))
                num_static = 0
            prev_x = curr_x
            prev_y = curr_y
        if frame % frame_freq == 0:
            animation_frames.append(image_data.copy())
        on_path = is_on_path(maze_path, int(world.x()), int(world.y()))
        frame += 1
        prev_image_data = image_data
        if frame == max_steps:
            print("Exceeds step limit")
            break

    # this chunk gets the completion percentage
    lost = False
    if num_static >= 5:
        stuck = True
    if frame >= max_steps:
        lost = True
    outcome = ("At Goal? " + str(world.at_goal()) + "\n Stuck? " + str(stuck) +
               "\n Exceed step limit? " + str(lost) + "\n On path? " +
               str(on_path))
    print(outcome)

    completion_per = percent_through_maze(maze_rvs, int(world.x()),
                                          int(world.y()), start_x, start_y,
                                          end_x, end_y)

    animate(animation_frames, model, directory_name)

    if num_static >= 5 and not world.at_goal(
    ):  # model failed to navigate maze
        return frame, False, completion_per
    else:  # model successfully navigated maze
        return frame, True, completion_per
Exemplo n.º 57
0
        # wpraw ją w ruch
        m.ruch(vx, vy)
        #narysuj mszyce na ekranie
        m.rysuj()

        #odbicie mszycy od lewej i prawej ściany
        if m.x <= 0 or (m.x + m.szerM) >= szer :
            vx = vx * -1
        #odbicie mszycy od górnej i dolnej ściany
        elif m.y <= 0 or (m.y + m.wysM) >= wys :
            vy = vy * -1

        # jak biedra zdeży się z mszycą
        for b in biedry :
            if b.czyZezarla(m.ksztalt) :
                coPokazuje = "koniec"

        napisz("PUNKTY: " + str(round(punkty)), 100, 50, 32)
        #szybkosc poruszania sie obiektów
        pygame.time.wait(80)

    elif coPokazuje == "koniec" :
        napisz("KONIEC GRY!!!", 100, 150, 56)
        napisz("PUNKTY: "+str(round(punkty)), 100, 350, 32)
        napisz("naciśnij spację aby zagrać jeszcze raz ", 100, 400, 28)
        napisz("lub ESC aby zakończyć grę ", 100, 430, 28)

    #odświeżenie ekranu
    pygame.display.update()
#program kalkulator sederhana untuk pembagian

while True:
    print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
    print('Selamat datang di menu pembagian aritmetika dasar')
    print("===================================================")
    try:
        angka_pertama = int(input('Silahkan input angka pertama : '))
        print("'Anda memilih angka pertama :", str(angka_pertama) + "'")

        angka_kedua = int(input('Silahkan input angka kedua : '))
        print("'Anda memilih angka kedua :", str(angka_kedua) + "'")
        print("===================================================")

        hasil = angka_pertama / angka_kedua
        print('Hasil dari', angka_pertama, '/', angka_kedua, '=', hasil)
        print('Hasil pembulatannya =', round(hasil))
        print("===================================================")
    except:
        print("***************************************************")
        print('Input hanya diperbolehkan angka, dimulai dari 0 - 9')
        print("***************************************************")
Exemplo n.º 59
0
def main():
    if len(sys.argv) != 4:
        sys.exit("usage: " + sys.argv[0] +
                 " <itcont.txt> <percentile.txt> <repeat_donors.txt>")
    # getting locations of itcont.txt, percentile.txt, and repeat_donors.txt
    itcont_location = sys.argv[1]
    percentile_location = sys.argv[2]
    repeat_donors_location = sys.argv[3]
    # itcont_location is a pipe separated value file
    delimiter = "|"
    # the first line of percentile_location holds the percentile
    with open(percentile_location, 'r') as percentile_file:
        try:
            percentile = int(percentile_file.readline())
        except ValueError:
            sys.exit("ERROR: first line of " + percentile_location +
                     " must be a single value")
    if percentile < 1 or percentile > 100:
        sys.exit("ERROR: first line of " + percentile_location +
                 " must be a single value between 1 and 100")
    # donations is a dictionary which holds a list of transaction_year and transaction_amt tuples
    # from a unique donor (name and zip code combination)
    #
    # Key: zip_code+delimiter+name
    #
    # Value: list of (transaction_year, transaction_amt) tuples from the unique donor
    donations = {}
    # contributors is a dictionary which holds a list of donors for a given recipient and year
    #
    # Key: cmte_id+delimiter+transaction_year
    #
    # Value: List of keys to donations
    contributors = {}
    # open repeat_donors_location for writing during itcont_location parsing
    repeat_donors_file = open(repeat_donors_location, "w")
    # parsing itcont_location
    with open(itcont_location, 'r') as itcont_file:
        for itcont_file_line in itcont_file:
            itcont_file_line_list = itcont_file_line.split(delimiter)
            # ignore lines with invalid number of fields
            if len(itcont_file_line_list) == 21:
                cmte_id = itcont_file_line_list[0]
                name = itcont_file_line_list[7]
                # only consider the first five characters of the zip code
                zip_code = itcont_file_line_list[10][:5]
                transaction_dt = itcont_file_line_list[13]
                transaction_amt = itcont_file_line_list[14]
                other_id = itcont_file_line_list[15]
                # only consider records with
                # 1. an empty other_id
                # 2. a valid transaction_dt
                # 3. a zip code with at least 5 digits
                # 4. a non-empty name
                # 5. a non-empty cmte_id
                # 6. a non-empty transaction_amt that represents a float
                if not other_id and isDatetime(transaction_dt) and isZipCode(
                        zip_code
                ) and name and cmte_id and transaction_amt and isFloat(
                        transaction_amt):
                    # the year of the transaction is the last 4 characters of transaction_dt
                    transaction_year = transaction_dt[-4:]
                    transaction_amt = float(transaction_amt)
                    donations_key = zip_code + delimiter + name
                    contributors_key = cmte_id + delimiter + transaction_year
                    # converting transaction_year to an integer for O(1) comparisons
                    transaction_year = int(transaction_year)
                    # appending contributors_key to contributors
                    if contributors_key in contributors:
                        contributors[contributors_key].append(donations_key)
                    else:
                        contributors[contributors_key] = [donations_key]
                    # updating donations
                    if donations_key in donations:
                        # this donor is a repeat donor
                        donations[donations_key].append(
                            (transaction_year, transaction_amt))
                        number_of_repeat_donors = 0
                        repeat_donors_donations = []
                        repeat_donors_donations_sum = 0
                        # look for contributions from other repeat donors
                        for donor in contributors[contributors_key]:
                            if len(donations[donor]) > 1:
                                # this is a contribution to this candidate, this year, from a repeat donor
                                # add their information to repeat_donors_file
                                number_of_repeat_donors += 1
                                for year_amt in donations[donor]:
                                    if year_amt[0] == transaction_year:
                                        repeat_donors_donations.append(
                                            year_amt[1])
                                        repeat_donors_donations_sum += year_amt[
                                            1]
                        percentile_amt = int(
                            round(
                                nearestRankPercentile(repeat_donors_donations,
                                                      percentile)))
                        repeat_donors_donations_sum = int(
                            round(repeat_donors_donations_sum))
                        # format: cmte_id|zip_code|transaction_year|percentile_amt|repeat_donors_donations|number_of_repeat_donors
                        repeat_donor_file_line = cmte_id + delimiter + zip_code + delimiter + str(
                            transaction_year
                        ) + delimiter + str(percentile_amt) + delimiter + str(
                            repeat_donors_donations_sum) + delimiter + str(
                                number_of_repeat_donors) + "\n"
                        repeat_donors_file.write(repeat_donor_file_line)
                    else:
                        # this is the first time we have seen this unique donor
                        donations[donations_key] = [(transaction_year,
                                                     transaction_amt)]
    # close repeat_donors_file after itcont_location parsing
    repeat_donors_file.close()
Exemplo n.º 60
0
                min_wbt = wbt_data[0]

                try:  #Computing Class Gap

                    # Computing Class Gap as per User Input
                    for gap in np.arange(min_class_gap, max_class_gap, 0.1):
                        score = 0
                        for temp_vals in np.arange(min_wbt, max_wbt, gap):
                            if (len(df.iloc[0:, 1][(x >= temp_vals)
                                                   & (x < (temp_vals + gap))])
                                    < 10):  #[0-10), [10-20)....
                                break
                            else:
                                score += 1

                        if (round(
                            (max_wbt - gap - min_wbt) / gap, 0) <= score):
                            #print(round((max_wbt-gap-min_wbt)/gap))
                            final_gap = round(gap, 2)
                            #print(final_gap)
                            break
                        else:
                            continue

                    # Computing Class Gap as per Default Input
                    if (final_gap == ''):
                        for gap in np.arange(min_class_gap,
                                             max_class_gap * 1.5, 0.1):
                            score = 0
                            for temp_vals in np.arange(min_wbt, max_wbt, gap):
                                if (len(df.iloc[0:,
                                                1][(x >= temp_vals)