Example #1
0
    def __init__(self, width=1920, height=1080):
        # Create Screen with the provided resolution
        self.width = width  #1920
        self.height = height  #1080
        self.screen = Screen(width, height)
        self.logo = self.screen.load_image("logo.png")
        #self.logo = self.screen.scale(self.logo, 500,100)

        #self.screen.set_fps(10)
        # NOTE: Remove comment on next line to add Full screen
        #self.screen.set_full_screen()

        size = self.screen.get_size()
        self.border = 10
        b = self.border  # Just to make the next line more readable

        self.battery = Battery(self.screen,
                               x=20,
                               y=self.height - 355,
                               width=140,
                               height=300)

        # Creates a wyndow with a margin to make it pritty <3
        self.window = Window(self.screen, b + 180, b + 130,
                             size[0] - (b * 2 + 270), size[1] - (b * 2 + 180))
        self.window.set_all_colors((100, 100, 100))
        self.window.set_border_color((200, 200, 200))
        self.window.set_border_width(10)
        self.chart_og = Chart()
        self.chart_og.set_width(8)
        self.chart_og.set_color((255, 150, 0))
        self.chart_og.add_point([1, 0])
        self.chart_og.add_point([2, 0])
        self.window.add_chart(self.chart_og)

        self.chart_optimised = Chart()
        self.chart_optimised.set_width(8)
        self.chart_optimised.set_color((0, 150, 255))
        self.chart_optimised.add_point([1, 0])
        self.chart_optimised.add_point([2, 0])
        self.window.add_chart(self.chart_optimised)
        # Next we add a function that converts the X values to
        # something the window class can work with, simple numbers
        # the window class does not know how to handle dates
        # so they need to be converted to intigers. These X values
        # are still used as labels in the x axis so format them
        # wisely.
        # NOTE: Remove comment on the fallowing line to add convertion function
        #self.chart.set_conv_funct(self.convert)

        self.data = Value(self.screen, 22, 150)
Example #2
0
	def __init__(self):
		#average income
		self.averageIncome = AverageValue()
		#average unspent ressource AUR
		self.averageUnspent = AverageValue()        
		#ressource banks, army values (detailed) and supply count
		self.stats = {}
		self.workersBuilt = 0
		self.unitsTrained = 0
		self.structuresBuilt = 0
		self.unitsKilled = 0
		self.structuresRazed = 0
		self.baseCount = 1
		self.baseTimings = []
		self.saturationTimings = []

		self.charts = {}
		#army value chart (Total value of the current army)
		self.charts["armyValChart"] = Chart("armyValChart")
		#mineral income chart (Mineral collection rate)
		self.charts["incomeChartMin"] = Chart("incomeChartMin")
		#gas income chart (Vespene gas collection rate)
		self.charts["incomeChartGas"] = Chart("incomeChartGas")
		#workerCountChart: active worker count
		self.charts["workerCountChart"] = Chart("workerCountChart")
		#spendTechChart: spent ressources on technology
		self.charts["spendTechChart"] = Chart("spendTechChart")
		#resLostChart: total ressources lost
		self.charts["resLostChart"] = Chart("resLostChart")
		#resKilledArmyChart: ressources Killed in army value
		self.charts["resKilledArmyChart"] = Chart("resKilledArmyChart")
		#basecount chart
		self.charts["baseCountChart"] = Chart("baseCountChart")
		self.charts["baseCountChart"].add(0, 1)
Example #3
0
 def __getitem__(self, date):
     """
     If chart with given date is already in adt, returns it from memory,
     if not, it downloads it from internet
     :param date: datetime pbj
     :return: Chart obj
     """
     if self._compare_dates(date):
         print(self.get_latest_date(), self.get_oldest_date())
         return self._find_chart(date)
     else:
         req = 'https://api.nytimes.com/svc/books/v3/lists/{}/hardcover-fiction.json?api-key={}'.format(
             str(date.date()), nyt_api)
         response = get(req)
         data = response.json()
         try:
             books = [
                 BookRanker(book['primary_isbn13'],
                            int(book['rank']),
                            book['author'],
                            book['title'],
                            img_url=book['book_image'],
                            descr=book['description'])
                 for book in data['results']['books']
                 if int(book['rank']) < 10
             ]
             chart = Chart(books, data['results']['published_date'],
                           data['results']['previous_published_date'])
             self.append(chart)
             return chart
         except:
             print(data)
             return None
Example #4
0
    def create_chart(self) -> Chart:
        self.calculate()

        chart = Chart(self.width, self.height)
        painter = chart.create_painter()

        if self.min_y == self.max_y:
            self.draw_constant_chart(painter)
            painter.end()
            self.add_background(chart)

            return chart

        dy = self.max_y - self.min_y
        y = self.f_x_y[self.alpha]
        yy = (self.max_y - y) * self.height / dy
        current_point = QPoint(0, yy)

        for xx in range(1, self.width):
            x = self.f_xx_x[xx]
            y = self.f_x_y[x]
            yy = (self.max_y - y) * self.height / dy if y != inf else inf
            move_point = QPoint(xx, round(yy)) if yy != inf else None

            if None not in (current_point, move_point):
                painter.drawLine(current_point, move_point)

            current_point = move_point

        back_painter = ChartBackgroundPainter(chart)
        grid_painter = GridPainter(self, back_painter.offset)
        back_painter.draw(grid_painter)

        return chart
    def create_widgets(self):
        self.tabs = ttk.Notebook(self, width=600, height=450)
        self.tabs.grid()

        self.total_exp_page = tk.Frame(self.tabs)
        self.exp_per_lvl_page = tk.Frame(self.tabs)

        self.total_exp_chart = Chart(self.total_exp_page)
        self.exp_per_lvl_chart = Chart(self.exp_per_lvl_page, ylabel_text='Exp Per Level')

        self.total_exp_chart.pack(fill=tk.BOTH)
        self.exp_per_lvl_chart.pack(fill=tk.BOTH)

        self.tabs.add(self.total_exp_page, text="Total Exp")
        self.tabs.add(self.exp_per_lvl_page, text="Exp Level")
        self.tabs.grid()
Example #6
0
 def __table_col_traverse(self, tag):
     self.__charts.append(Chart())
     for index, tag in enumerate(tag.find_all(re.compile("td"))):
         #index values tracks the current column being scraped
         if index == 3:
             airport_id = tag.text
             if airport_id[airport_id.find("(") +
                           1:airport_id.find(")")] != "":
                 self.__charts[-1].set_airport_id(
                     airport_id[airport_id.find("(") +
                                1:airport_id.find(")")])
             else:
                 self.__charts[-1].set_airport_id(airport_id[:3])
         elif index == 4:
             self.__charts[-1].set_region_name(tag.text)
         elif index == 6:
             self.__charts[-1].set_procedure_name(tag.text)
         elif index == 7:
             if tag.a:
                 chart_name = tag.text[:-6] + ".pdf"
                 self.__charts[-1].set_pdf_url(tag.a['href'])
                 self.__charts[-1].set_chart_name(
                     chart_name.replace("/", "_"))
     if self.__charts[-1].get_pdf_url() == '':
         self.__charts.pop()
Example #7
0
    def __init__(self, data, parent=None):
        super(Navigation, self).__init__(parent)

        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")

        #self.gridLayout.addWidget(self.listview, 0, 0, 2, 1)

        self.frame = QtWidgets.QFrame()
        self.chart = Chart('pie1', data, self)

        self.parent().addToolBar(self.chart.navigationBar(data))

        self.ly = QtWidgets.QVBoxLayout()
        self.frame.setLayout(self.ly)

        self.gridLayout1 = QtWidgets.QGridLayout()
        self.gridLayout1.addWidget(self.frame)

        self.gridLayout2 = QtWidgets.QGridLayout()
        self.gridLayout2.addWidget(self.chart.chartview)

        self.gridLayout.addLayout(self.gridLayout2, 0, 2, 0, 1)
        self.gridLayout.addLayout(self.gridLayout1, 0, 2, 0, 1)

        self.horizontalGroupBox = QGroupBox()
        self.horizontalGroupBox.setLayout(self.gridLayout)
Example #8
0
 def __init__(self,
              ambient_manifold,
              n,
              coordinates,
              chart_name,
              embedding_functions,
              name=None,
              latex_name=None,
              ambient_chart=None,
              start_index=0):
     from sage.symbolic.ring import SR
     Manifold.__init__(self, n, name, latex_name, start_index)
     if not isinstance(ambient_manifold, Manifold):
         raise TypeError(
             "The argument ambient_manifold must be a manifold.")
     self.ambient_manifold = ambient_manifold
     Chart(self, coordinates, chart_name)
     if ambient_chart is None:
         ambient_chart = ambient_manifold.def_chart.name
     n_amb = ambient_manifold.dim
     if len(embedding_functions) != n_amb:
         raise ValueError(
             str(n_amb) + " coordinate functions must be provided.")
     embedding_expressions = [
         SR(embedding_functions[i]) for i in range(n_amb)
     ]
     self.embedding = DiffMapping(self, ambient_manifold,
                                  embedding_expressions, chart_name,
                                  ambient_chart)
Example #9
0
    def create_chart(self) -> Chart:
        o = QPoint(self.width // 2, self.height // 2)
        h, r, d = self.h, self.r, self.r * 2
        dh = int(d * sin(rad(self.skew)))

        rect = QRect(o.x() - r, o.y() - h // 2, d, h)
        bottom_ellipse = QRect(o.x() - r, o.y() + h // 2 - dh // 2, d, dh)
        top_ellipse = QRect(o.x() - r, o.y() - h // 2 - dh // 2, d, dh)

        chart = Chart(self.width, self.height, Qt.black, 2)
        chart.image.fill(Qt.white)

        painter = QPainter(chart.image)

        painter.setPen(QPen(Qt.black, 5))
        painter.drawRect(rect)
        painter.drawEllipse(bottom_ellipse)
        painter.setPen(QPen(Qt.blue, 0))
        painter.setBrush(QBrush(Qt.blue))
        painter.drawRect(rect)
        painter.drawEllipse(bottom_ellipse)
        painter.setPen(QPen(Qt.black, 3))
        painter.drawEllipse(top_ellipse)

        painter.end()

        return chart
Example #10
0
def main():

   c = Chart()
   buying = 'y'
   while buying == 'y':
      c.buySeat()
      buying = input("Continue to buy seats? y/n: ")
def entries_by_date(country, date):
    day_chart = DayChart.get_by_id('{}/{}'.format(country,
                                                  date.strftime('%Y/%m/%d')))
    entries = []

    if day_chart == None:
        chart = Chart(country)
        results = chart.read(date.strftime('%Y/%m/%d'))
        if not results:
            return None
        day_chart = DayChart(id='{}/{}'.format(country,
                                               date.strftime('%Y/%m/%d')),
                             date=date,
                             country=country)
        day_chart_key = day_chart.put()

        for result in results:
            entry = Entry(rank=result['rank'],
                          artist=result['artist'],
                          song=result['song'],
                          parent=day_chart_key)
            entry_key = entry.put()
            entries.append(entry)
    else:
        day_chart_key = day_chart.key
        query = Entry.query(ancestor=day_chart.key).order(Entry.rank)
        entries = query.fetch(100)
    return (day_chart, entries)
Example #12
0
    def __new__(self, shape):
        if shape == "Chart":
            return Chart()
        if shape == "Image":
            return Image()
        if shape == "Table":
            return Table()
        if shape == "BarCode":
            return BarCode()
        if shape == "Text":
            return Text()
        if shape == "Rounded":
            return Rounded()
        if shape == "Box":
            return Box()
        if shape == "Connector":
            return Connector()
        if shape == "Curve":
            return Curve()
        if shape == "Line":
            return Line()
        if shape == "Arc":
            return Arc()

        return None
Example #13
0
    def __init__(self, file):
        """
        Parse course.yml contents into instances.
        """
        self.config = Config()
        self.helm = Helm()
        self._dict = yaml.load(file)
        self._repositories = []
        self._charts = []
        for name, repository in self._dict.get('repositories', {}).iteritems():
            repository['name'] = name
            self._repositories.append(Repository(repository))

        for name, chart in self._dict.get('charts', {}).iteritems():
            self._charts.append(Chart({name: chart}))

        for repo in self._repositories:
            type(repo)
            if not self.config.local_development:
                logging.debug("Installing repository: {}".format(repo))
                repo.install()

        self.helm.repo_update()

        if not self.config.local_development:
            self._compare_required_versions()
Example #14
0
    def create_chart(self) -> Chart:
        self.calculate()
        self.min_y = self.min_y if self.min_y >= self.lim_min_y \
            else self.lim_min_y
        self.max_y = self.max_y if self.max_y <= self.lim_max_y \
            else self.lim_max_y

        chart = Chart(self.width, self.height)

        dy = self.max_y - self.min_y if self.max_y - self.min_y >= 0 else 0
        y = self.f_x_y[self.alpha]
        yy = (self.max_y - y) * self.height / dy if y != inf and dy != 0 \
            else inf
        xx0, yy0 = 0, yy

        for xx in range(1, self.width):
            x = self.f_xx_x[xx]
            y = self.f_x_y[x]
            yy = (self.max_y - y) * self.height / dy if y != inf and dy != 0 \
                else inf

            if inf not in (yy, yy0) and (yy > 0 or yy0 > 0):
                draw_bresenham_line(chart, xx0, round(yy0), xx, round(yy))

            xx0, yy0 = xx, yy

        chart = self.zoom(chart)
        back_painter = ChartBackgroundPainter(chart)
        grid_painter = GridPainter(self, back_painter.offset, self.step)
        back_painter.draw(grid_painter)

        return chart
Example #15
0
def main(argv):
    chart = Chart("bittrex", "BTC-LTC", "fiveMin", False)

    logger = Logger

    strategy = Strategy(capital=0.01, pair="BTC-LTC", client=chart.conn)

    # candlesticks = []
    # developing_candlestick = BotCandlestick()

    while True:
        try:
            price = chart.get_current_price()
        except Exception as e:
            logger.log("ERROR: Exception occurred: " + e.message, "error")
            time.sleep(int(1))
            price = chart.get_current_price()

        logger.log("Received price: " + str(price))

        strategy.live_tick(price)

        # if developing_candlestick.is_closed():
        #     candlesticks.append(developing_candlestick)
        #     strategy.tick(developing_candlestick)
        #     developing_candlestick = BotCandlestick()

        time.sleep(int(1))
Example #16
0
def create_chart(plot_data, image_path):
    blue = '#2e7eb3'
    light_blue = '#81b1d1'
    green = '#4aa635'
    light_green = '#7db471'
    ylabels = ['0 %', '25 %', '50 %', '75%', '100 %']
    xlabels = [0, 2, 4, 6, 8, 10, '12 hours']
    plot = Chart(xlabels=xlabels,
                 ylabels=ylabels,
                 inverseX=True,
                 padding_top=30,
                 height=450)
    plot.set_minimal_canvas([0, 0], [12, 100])

    for p in plot_data['history charging']:
        plot.add(xs=p['xs'], ys=p['ys'], stroke=green, fill=green, drop=green)

    for p in plot_data['history discharging']:
        plot.add(xs=p['xs'], ys=p['ys'], stroke=blue, fill=blue, drop=blue)

    for p in plot_data['future charging']:
        plot.add(xs=p['xs'], ys=p['ys'], stroke=green, stroke_dash=True)

    for p in plot_data['future discharging']:
        plot.add(xs=p['xs'], ys=p['ys'], stroke=blue, stroke_dash=True)

    plot.render_to_svg(image_path)
Example #17
0
    def __init__(self, file):
        """
        Parse course.yml contents into instances.
        """
        self.config = Config()
        self._dict = yaml.load(file)
        if not self.config.helm_args:
            self.config.helm_args = self._dict.get('helm_args')
        self.helm = HelmClient(default_helm_arguments=self.config.helm_args)
        self._repositories = []
        self._charts = []
        for name, repository in self._dict.get('repositories', {}).iteritems():
            repository['name'] = name
            self._repositories.append(Repository(repository, self.helm))

        for name, chart in self._dict.get('charts', {}).iteritems():
            self._charts.append(Chart({name: chart}, self.helm))

        for repo in self._repositories:
            type(repo)
            if not self.config.local_development:
                logging.debug("Installing repository: {}".format(repo))
                repo.install()

        self.helm.repo_update()

        if not self.config.local_development:
            try:
                self._compare_required_versions()
            except MinimumVersionException as e:
                logging.error(e)
                sys.exit(1)
Example #18
0
    def draw(self) -> None:
        try:
            self.parse_options()
        except GeometryError:
            print('Incorrect polygon')
            return

        chart = Chart(self.width, self.height, pen_size=2)
        chart.colors.append(Qt.red)

        painter = chart.create_painter()
        inside, outside = self.get_symmetric_difference()

        for chain in inside:
            self.draw_chain(chain, painter)

        painter.setPen(QPen(Qt.red, 2))

        for chain in outside:
            self.draw_chain(chain, painter)

        back_painter = ChartBackgroundPainter(chart, revers=True)
        grid_painter = GridPainter(self, back_painter.offset, self.unit)
        back_painter.draw(grid_painter)

        self.chart_area.update(chart)
Example #19
0
    def __init__(self,
                 coordinate=None,
                 name='R',
                 latex_name=r'\RR',
                 start_index=0,
                 names=None):
        r"""
        Construct the real line manifold.

        TESTS::

            sage: R = RealLine() ; R
            field R of real numbers
            sage: R.category()
            Category of sets
            sage: TestSuite(R).run()

        """
        from chart import Chart
        Manifold.__init__(self,
                          1,
                          name,
                          latex_name=latex_name,
                          start_index=start_index)
        if coordinate is None:
            if names is None:
                coordinate = 't'
            else:
                coordinate = names[0]
        self._canon_chart = Chart(self, coordinates=coordinate)
        self._lower = minus_infinity  # for compatibility with OpenInterval
        self._upper = infinity  # idem
Example #20
0
def query_chart(request):
    """
    Returns query chart for given request
    """
    # TODO: Move this to one line e.g. queries to query
    query = request.GET.get("query", None)
    queries = request.GET.getlist("queries[]")
    if query:
        queries = [query]

    request_timeframe = Timeframe(start=request.GET.get("start", None),
                                  end=request.GET.get("end", None),
                                  interval=request.GET.get("interval", "hour"))

    response_chart = None
    try:
        response_chart = Chart(queries=queries,
                               start=request_timeframe.start,
                               end=request_timeframe.end,
                               interval=request_timeframe.interval)
    except GNIPQueryError as e:
        return handleQueryError(e)

    response_data = {}
    response_data['days'] = request_timeframe.days
    response_data['start'] = request_timeframe.start.strftime(DATE_FORMAT_JSON)
    response_data['end'] = request_timeframe.end.strftime(DATE_FORMAT_JSON)
    response_data['columns'] = response_chart.columns
    response_data['total'] = response_chart.total

    return HttpResponse(json.dumps(response_data),
                        content_type="application/json")
Example #21
0
def current_day():
    chart = Chart(title='Dag X', labels=['one', 'two', 'three'])
    washes, http_code = stats.get_todays_washes()
    ok, commented, unknown = filtered_count(washes)
    chart.add_serie('Tvättade', ok, "#4BC0C0")
    chart.add_serie('Kommenterade', commented, "#36A2EB")
    chart.add_serie('Okända', unknown, "#FF6384")
    return render_template('day.html', series_names=chart.series_names(), bars=chart.get_series(), title=chart.title)
Example #22
0
 def _show_scan_chart(self, event=None):
     items = self.scan_result_treeview.selection()
     if len(items) == 0:
         return
     item = items[0]
     item_text = self.scan_result_treeview.item(item, "values")
     chart = Chart(item_text[1], self.db, self.cursor)
     chart.gui_arrang()
     tkinter.mainloop()
Example #23
0
def parse_chart_lines(song, tags, diff_str, settings):
	chart = Chart()
	chart.num_columns = 5 # TODO: idk if GH can have non-5key charts too
	
	# Split e.g. "EasyEnhancedGuitar" into "Easy" and "EnhancedGuitar"
	diff_type = None
	chart_type = None
	for i in range(1, len(diff_str)):
		if diff_str[i].isupper():
			diff_type = diff_str[:i]
			chart_type = diff_str[i:]
			break
	else: raise Exception(f"Unknown diff string '{diff_str}'")
	
	# Set diff type and, in case of Edit, also set chart string to best
	# represent the GH diff
	if chart_type == "Single":
		# In case of the basic chart type just use the standard .sm diff
		# types. Map diff_type to .sm diff types and write into Chart
		diff_type = {
			"Easy": DiffType.EASY,
			"Medium": DiffType.MEDIUM,
			"Hard": DiffType.HARD,
			"Expert": DiffType.EXPERT,
		}.get(diff_type, None)
		if diff_type is None:
			raise Exception(f"Unknown diff type '{diff_str}'")
		chart.diff_type = diff_type
	else:
		# If we have DoubleBass or EnhancedGuitar we have to get fancy
		# with Edit diff
		chart.diff_type = DiffType.EDIT
		
		if settings.get("jolemode", False):
			# jole wanted to discard everything except ExpertDoubleBass
			# which should be saved as "EXPERT+" Edit
			if diff_type == "Expert" and chart_type == "DoubleBass":
				chart.chart_string = "EXPERT+"
			else:
				return # Discard everything else
		else:
			# In the general case I think it#s sensible to add a "+" to
			# DoubleBass and add " G" to EnhancedGuitar charts
			if chart_type == "DoubleBass":
				chart.chart_string = diff_type + "+"
			elif chart_type == "EnhancedGuitar":
				chart.chart_string = diff_type + " G"
			else:
				raise Exception(f"Unknown chart type '{chart_type}'")
	
	# STUB: parse the actual notes
	chart.notes = []
	
	song.charts.append(chart)
Example #24
0
def createChart():
    g = Chart(scheme.shape[0])

    for index, row in scheme.iterrows():

        if list(row[row.apply(lambda x: x == 1)].index):

            for dest in row[row.apply(lambda x: x == 1)].index:
                g.addEdge(index, dest)

    return g
Example #25
0
 def parse(self, start_symbol, lexicon, grammar, sentence):
     agenda = Agenda(self.logger)
     chart = Chart(grammar, agenda, logger=self.logger)
     chart.introduce_symbol(start_symbol, 0)
     position = 0
     while position < len(sentence) or agenda.size() > 0:
         if agenda.size() == 0:
             agenda.add_alternatives(
                 lexicon.get_interpretations(sentence[position]), position)
             position = position + 1
         chart.extend_arcs(agenda.next_constituent())
Example #26
0
def main(_argv):
    # Uśmiech
    usmiech = Chart(None, True)
    x = np.linspace(-2, 2, 8)
    y = (x + 2) * (x - 2)
    x = np.concatenate((x, np.flip(x, 0)))
    y = np.concatenate((y, np.flip(-y, 0)))
    usmiech.wykres_linie_rysuj(x, y, 'glowa')
    usmiech.wykres_linie_rysuj([-1, 0, 1], [0, -1, 0], 'usmiech')
    usmiech.wykres_punkty_rysuj([-1, 0, 1], [1, 0, 1], 'oczy i usta')
    plt.legend(loc='upper right')
    usmiech.show()
Example #27
0
    def nbest_parse(self, tokens, n=None):
        self._grammar.check_coverage(tokens)
        chart = Chart(list(tokens))
        grammar = self._grammar

        # Chart parser rules.
        bu_init = ProbabilisticBottomUpInitRule()
        bu = ProbabilisticBottomUpPredictRule()
        fr = SingleEdgeProbabilisticFundamentalRule()

        # Our queue!
        queue = []
        
        # Initialize the chart.
        for edge in bu_init.apply_iter(chart, grammar):
            if self._trace > 1: 
                print '  %-50s [%s]' % (chart.pp_edge(edge,width=2),
                                        edge.prob())
            queue.append(edge)

        while len(queue) > 0:
            # Re-sort the queue.
            self.sort_queue(queue, chart)

            # Prune the queue to the correct size if a beam was defined
            if self.beam_size:
                self._prune(queue, chart)

            # Get the best edge.
            edge = queue.pop()
            if self._trace > 0:
                print '  %-50s [%s]' % (chart.pp_edge(edge,width=2),
                                        edge.prob())

            # Apply BU & FR to it.
            queue.extend(bu.apply(chart, grammar, edge))
            queue.extend(fr.apply(chart, grammar, edge))

        # Get a list of complete parses.
        parses = chart.parses(grammar.start(), ProbabilisticTree)

        # Assign probabilities to the trees.
        prod_probs = {}
        for prod in grammar.productions():
            prod_probs[prod.lhs(), prod.rhs()] = prod.prob()
        for parse in parses:
            self._setprob(parse, prod_probs)

        # Sort by probability
        parses.sort(lambda a,b: cmp(b.prob(), a.prob()))
        
        return parses[:n]
Example #28
0
 def __init__(self, grid):
     self.__grid = grid
     self.__score = 0
     self.__chart = Chart()
     self.__history = []
     self.__state = State.game_waiting
     self.__undo_counter = 0
     self.__difficulty = Difficulty.NORMAL
     self.__slider = {
         'left': self.__grid.slide_left,
         'right': self.__grid.slide_right,
         'up': self.__grid.slide_up,
         'down': self.__grid.slide_down
     }
Example #29
0
def week_chart(weekdays, week_nbr):
    days = stats.get_washes_as_list(weekdays)
    week_bookings = list(map(len, days))

    ok = stats.filter_count(days, stats.returned_check)
    commented = stats.filter_count(days, stats.commented_check)
    unknown = stats.filter_count(days, stats.unknown_check)
    traceable = round((sum(ok) + sum(commented)) * 100 / sum(week_bookings))

    chart = Chart(title = 'Vecka {}'.format(week_nbr), labels = [d.name() for d in weekdays])
    chart.add_serie('Tvättade', ok, "#4BC0C0")
    chart.add_serie('Kommenterade', commented, "#36A2EB")
    chart.add_serie('Okända', unknown, "#FF6384")
    return render_template('week.html', labels=chart.labels, bars=chart.get_series(), title = chart.title, total=sum(week_bookings), traceable=traceable)
Example #30
0
    def create_chart(self) -> Chart:
        u0, u1, r = self.alpha, self.beta, self.f
        x0, y0, unit = self.width // 2, self.height // 2, 40
        chart = Chart(self.width, self.height)
        painter = chart.create_painter()
        u, du, d, a, b = u0, 1, 10, 3, 2
        ru = r(u) if not None else None
        point = PixelPoint(ru * cos(rad(u)), ru * sin(rad(u)), unit) if \
            ru is not None else None

        while u < u1:
            u += du
            ru = r(u)

            if not ru:
                point = None
                continue

            new_point = PixelPoint(ru * cos(rad(u)), ru * sin(rad(u)), unit)

            if fabs(new_point.x) > x0 or fabs(new_point.y) > y0:
                point = None
                continue

            if not point:
                point = new_point
                continue

            if point.get_distance(new_point) > d:
                u -= du
                du /= a
                continue

            if point == new_point:
                u -= du
                du *= b
                continue

            xx0, yy0 = point.x + x0, y0 - point.y
            xx1, yy1 = new_point.x + x0, y0 - new_point.y
            point = new_point

            painter.drawLine(xx0, yy0, xx1, yy1)

        back_painter = ChartBackgroundPainter(chart, h_axis='r', v_axis='φ')
        grid_painter = GridPainter(self, back_painter.offset)
        back_painter.draw(grid_painter)

        return chart