<commit_before>from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.core.window import Window
from kivy.uix.popup import Popup
import taskCreator

# Declare both screens
class MenuScreen(Screen):
    pass

class StartScreen(Screen):
    pass

class AddChooseDifficulty(Screen):
    category1 = "Up to 5"
    category2 = "Up to 10"
    category3 = "Up to 15"
    category4 = "Up to 20"
    category5 = "Up to 25"
    category6 = "Up to 50"
    category7 = "Up to 75"
    category8 = "Up to 100"
    category9 = "Up to 500"
    category10 = "Up to 1000"

class SubChooseDifficulty(Screen):
    category1 = "Up to 5"
    category2 = "Up to 10"
    category3 = "Up to 15"
    category4 = "Up to 20"
    category5 = "Up to 25"
    category6 = "Up to 35"
    category7 = "Up to 50"
    category8 = "Up to 65"
    category9 = "Up to 75"
    category10 = "Up to 100"

class MultiChooseDifficulty(Screen):
    category1 = "Times of 2"
    category2 = "Times of 3"
    category3 = "Times of 4"
    category4 = "Times of 5"
    category5 = "Times of 6"
    category6 = "Times of 7"
    category7 = "Times of 8"
    category8 = "Times of 9"
    category9 = "Times of 10"
    category10 = "Times of 11 and 12"

class DivChooseDifficulty(Screen):
    category1 = "Times of 2"
    category2 = "Times of 3"
    category3 = "Times of 4"
    category4 = "Times of 5"
    category5 = "Times of 6"
    category6 = "Times of 7"
    category7 = "Times of 8"
    category8 = "Times of 9"
    category9 = "Times of 10"
    category10 = "Times of 11 and 12"

class GreaterSmallerChooseDifficulty(Screen):
    category1 = "Up to 10"
    category2 = "25"
    category3 = "50"
    category4 = "100"
    category5 = "Adding values"
    category6 = "Subtracting values"
    category7 = "Multiplication"
    category8 = "Division"
    category9 = "Mixing 1"
    category10 = "Mixing 2"

class ChallengeChooseDifficulty(Screen):
    category1 = "Adding + Subtracting"
    category2 = "Adding + Subtracting 2"
    category3 = "Multiplication and Division"
    category4 = "Negative Numbers"
    category5 = "A little bit of everything 1"
    category6 = "Longer tasks 1"
    category7 = "Longer tasks 2"
    category8 = "Longer tasks 3"
    category9 = "A little bit of everything 2"
    category10 = "Grande Finale"

class ProgressScreen(Screen):
    pass

class GameActionScreen(Screen):
    errors_made = 0
    round_number = 1
    max_rounds = 10

    task_values = [0, 0, 0, 0, 0, 0]

    current_category = ""
    current_mode = ""

    def new_game(self):
        self.round_number = 0
        self.set_next_task()

    def set_next_task(self):
        operator = ""
        if self.current_mode == "addChooser":
            self.task_values = taskCreator.add_task(int(self.current_category))
            operator = "+"
        elif self.current_mode == "subChooser":
            self.task_values = taskCreator.sub_task(int(self.current_category))
            operator = "-"
        elif self.current_mode == "multiChooser":
            self.task_values = taskCreator.multi_task(int(self.current_category))
            operator = "*"
        elif self.current_mode == "divChooser":
            self.task_values = taskCreator.div_task(int(self.current_category))
            operator = "/"
        elif self.current_mode == "greaterSmallerChooser":
            pass
        elif self.current_mode == "challengeChooser":
            pass

        self.ids.task.text = str(self.task_values[0]) + " " + operator + " " + str(self.task_values[1])
        self.ids.button_1.text = str(self.task_values[2])
        self.ids.button_2.text = str(self.task_values[3])
        self.ids.button_3.text = str(self.task_values[4])
        self.ids.button_4.text = str(self.task_values[5])

        self.ids.label_1.text = "Errors: " + str(self.errors_made)
        self.ids.label_2.text = str(self.current_mode) + str(self.current_category)
        self.ids.label_3.text = str(self.round_number) + " / " + str(self.max_rounds)

    def check_answer(self, button_pressed):
        if self.current_mode == "addChooser":
            if self.round_number == self.max_rounds:
                self.manager.current = 'result'
            elif int(button_pressed.text) == self.task_values[0] + self.task_values[1]:
                self.round_number += 1
                self.ids.label_3.text = str(self.round_number) + " / " + str(self.max_rounds)
                self.set_next_task()
            else:
                self.errors_made += 1
                self.ids.label_1.text = "Errors: " + str(self.errors_made)

        elif self.current_mode == "subChooser":
            if self.round_number == self.max_rounds:
                self.manager.current = 'result'
            elif int(button_pressed.text) == self.task_values[0] - self.task_values[1]:
                self.round_number += 1
                self.ids.label_3.text = str(self.round_number) + " / " + str(self.max_rounds)
                self.set_next_task()
            else:
                self.errors_made += 1
                self.ids.label_1.text = "Errors: " + str(self.errors_made)

        elif self.current_mode == "multiChooser":
            if self.round_number == self.max_rounds:
                self.manager.current = 'result'
            elif int(button_pressed.text) == self.task_values[0] * self.task_values[1]:
                self.round_number += 1
                self.ids.label_3.text = str(self.round_number) + " / " + str(self.max_rounds)
                self.set_next_task()
            else:
                self.errors_made += 1
                self.ids.label_1.text = "Errors: " + str(self.errors_made)

        elif self.current_mode == "divChooser":
            if self.round_number == self.max_rounds:
                self.manager.current = 'result'
            elif int(button_pressed.text) == self.task_values[0] / self.task_values[1]:
                self.round_number += 1
                self.ids.label_3.text = str(self.round_number) + " / " + str(self.max_rounds)
                self.set_next_task()
            else:
                self.errors_made += 1
                self.ids.label_1.text = "Errors: " + str(self.errors_made)

        elif self.current_mode == "greaterSmallerChooser":
            pass

        elif self.current_mode == "challengeChooser":
            pass

class ResultScreen(Screen):
    pass

class HelpScreen(Screen):

    def help_text(self):
        return "Here i will provide simple tricks to become faster when\n" \
               "doing mental calculations.\n" \
               "Example: Instead of adding 5 to a digit greater than 5,\n" \
               "its often more simple to subtract 5 and then add 10.\n" \
               " 8 + 5 = ?\n" \
               " 8 - 5 = 3; 3 + 10 = 13\n" \
               "\n"\
               "Or add in two steps, first to get to an more easy number, \n" \
               "then whatever remains.\n" \
               "\n"\
               "587 + 33 = ?\n" \
               "33 = 20 + 13\n" \
               "587 + 13 = 600; 600 + 20 = 620\n" \
               "Therefore 587 + 33 is 620\n" \
               "\n"\
               "More will follow soon!\n"

class AboutScreen(Screen):

    def about_text(self):
        return "Made by: Jonas\n" \
               "Open source and free of charge \n" \
               "\n" \
               "This app has been written to help everyone to be better\n" \
               " at mental arithmetic.\n" \
               "\n" \
               "Features:\n" \
               "  - simple\n" \
               "  - rewarding\n" \
               "  - perfect for kids in elementary school\n" \
               "  - or adults who want to train their brain ;)\n" \
               "  - No ads, they only distract\n" \
               "  - never gets old, new content is generated procedurally\n" \
               "  - written in Python with the help of Kivy"

class ComingSoonScreen(Screen):
    pass

class PopUpQuit(Popup):
    pass

class MathApp(App):

    sm = ScreenManager(transition=FadeTransition())

    def build(self):

        self.sm.add_widget(MenuScreen(name='menu'))
        self.sm.add_widget(StartScreen(name='start'))
        self.sm.add_widget(ProgressScreen(name='progress'))
        self.sm.add_widget(HelpScreen(name='help'))
        self.sm.add_widget(AboutScreen(name='about'))
        self.sm.add_widget(AddChooseDifficulty(name='addChooser'))
        self.sm.add_widget(SubChooseDifficulty(name='subChooser'))
        self.sm.add_widget(MultiChooseDifficulty(name='multiChooser'))
        self.sm.add_widget(DivChooseDifficulty(name='divChooser'))
        self.sm.add_widget(GreaterSmallerChooseDifficulty(name='greaterSmallerChooser'))
        self.sm.add_widget(ChallengeChooseDifficulty(name='challengeChooser'))
        self.sm.add_widget(GameActionScreen(name='game'))
        self.sm.add_widget(ResultScreen(name='result'))
        self.sm.add_widget(ComingSoonScreen(name='comingsoon'))
        #Bind to keyboard to make the back button under android work
        Window.bind(on_keyboard=self.handle_keyboard)

        return self.sm

    def handle_keyboard(self, window, key, *largs):
        #keycode 273 equals up button, just for test purposes
        if key == 27 or key == 273:
            if self.sm.current_screen.name == 'game':
                popup = PopUpQuit()
                popup.open()
            elif self.sm.current_screen.name == 'menu':
                quit()

            return True

if __name__ == '__main__':
    MathApp().run()<commit_msg>changed max rounds to 20<commit_after>from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.core.window import Window
from kivy.uix.popup import Popup
import taskCreator

# Declare both screens
class MenuScreen(Screen):
    pass

class StartScreen(Screen):
    pass

class AddChooseDifficulty(Screen):
    category1 = "Up to 5"
    category2 = "Up to 10"
    category3 = "Up to 15"
    category4 = "Up to 20"
    category5 = "Up to 25"
    category6 = "Up to 50"
    category7 = "Up to 75"
    category8 = "Up to 100"
    category9 = "Up to 500"
    category10 = "Up to 1000"

class SubChooseDifficulty(Screen):
    category1 = "Up to 5"
    category2 = "Up to 10"
    category3 = "Up to 15"
    category4 = "Up to 20"
    category5 = "Up to 25"
    category6 = "Up to 35"
    category7 = "Up to 50"
    category8 = "Up to 65"
    category9 = "Up to 75"
    category10 = "Up to 100"

class MultiChooseDifficulty(Screen):
    category1 = "Times of 2"
    category2 = "Times of 3"
    category3 = "Times of 4"
    category4 = "Times of 5"
    category5 = "Times of 6"
    category6 = "Times of 7"
    category7 = "Times of 8"
    category8 = "Times of 9"
    category9 = "Times of 10"
    category10 = "Times of 11 and 12"

class DivChooseDifficulty(Screen):
    category1 = "Times of 2"
    category2 = "Times of 3"
    category3 = "Times of 4"
    category4 = "Times of 5"
    category5 = "Times of 6"
    category6 = "Times of 7"
    category7 = "Times of 8"
    category8 = "Times of 9"
    category9 = "Times of 10"
    category10 = "Times of 11 and 12"

class GreaterSmallerChooseDifficulty(Screen):
    category1 = "Up to 10"
    category2 = "25"
    category3 = "50"
    category4 = "100"
    category5 = "Adding values"
    category6 = "Subtracting values"
    category7 = "Multiplication"
    category8 = "Division"
    category9 = "Mixing 1"
    category10 = "Mixing 2"

class ChallengeChooseDifficulty(Screen):
    category1 = "Adding + Subtracting"
    category2 = "Adding + Subtracting 2"
    category3 = "Multiplication and Division"
    category4 = "Negative Numbers"
    category5 = "A little bit of everything 1"
    category6 = "Longer tasks 1"
    category7 = "Longer tasks 2"
    category8 = "Longer tasks 3"
    category9 = "A little bit of everything 2"
    category10 = "Grande Finale"

class ProgressScreen(Screen):
    pass

class GameActionScreen(Screen):
    errors_made = 0
    round_number = 1
    max_rounds = 20

    task_values = [0, 0, 0, 0, 0, 0]

    current_category = ""
    current_mode = ""

    def new_game(self):
        self.round_number = 0
        self.set_next_task()

    def set_next_task(self):
        operator = ""
        if self.current_mode == "addChooser":
            self.task_values = taskCreator.add_task(int(self.current_category))
            operator = "+"
        elif self.current_mode == "subChooser":
            self.task_values = taskCreator.sub_task(int(self.current_category))
            operator = "-"
        elif self.current_mode == "multiChooser":
            self.task_values = taskCreator.multi_task(int(self.current_category))
            operator = "*"
        elif self.current_mode == "divChooser":
            self.task_values = taskCreator.div_task(int(self.current_category))
            operator = "/"
        elif self.current_mode == "greaterSmallerChooser":
            pass
        elif self.current_mode == "challengeChooser":
            pass

        self.ids.task.text = str(self.task_values[0]) + " " + operator + " " + str(self.task_values[1])
        self.ids.button_1.text = str(self.task_values[2])
        self.ids.button_2.text = str(self.task_values[3])
        self.ids.button_3.text = str(self.task_values[4])
        self.ids.button_4.text = str(self.task_values[5])

        self.ids.label_1.text = "Errors: " + str(self.errors_made)
        self.ids.label_2.text = str(self.current_mode) + str(self.current_category)
        self.ids.label_3.text = str(self.round_number) + " / " + str(self.max_rounds)

    def check_answer(self, button_pressed):
        if self.current_mode == "addChooser":
            if self.round_number == self.max_rounds:
                self.manager.current = 'result'
            elif int(button_pressed.text) == self.task_values[0] + self.task_values[1]:
                self.round_number += 1
                self.ids.label_3.text = str(self.round_number) + " / " + str(self.max_rounds)
                self.set_next_task()
            else:
                self.errors_made += 1
                self.ids.label_1.text = "Errors: " + str(self.errors_made)

        elif self.current_mode == "subChooser":
            if self.round_number == self.max_rounds:
                self.manager.current = 'result'
            elif int(button_pressed.text) == self.task_values[0] - self.task_values[1]:
                self.round_number += 1
                self.ids.label_3.text = str(self.round_number) + " / " + str(self.max_rounds)
                self.set_next_task()
            else:
                self.errors_made += 1
                self.ids.label_1.text = "Errors: " + str(self.errors_made)

        elif self.current_mode == "multiChooser":
            if self.round_number == self.max_rounds:
                self.manager.current = 'result'
            elif int(button_pressed.text) == self.task_values[0] * self.task_values[1]:
                self.round_number += 1
                self.ids.label_3.text = str(self.round_number) + " / " + str(self.max_rounds)
                self.set_next_task()
            else:
                self.errors_made += 1
                self.ids.label_1.text = "Errors: " + str(self.errors_made)

        elif self.current_mode == "divChooser":
            if self.round_number == self.max_rounds:
                self.manager.current = 'result'
            elif int(button_pressed.text) == self.task_values[0] / self.task_values[1]:
                self.round_number += 1
                self.ids.label_3.text = str(self.round_number) + " / " + str(self.max_rounds)
                self.set_next_task()
            else:
                self.errors_made += 1
                self.ids.label_1.text = "Errors: " + str(self.errors_made)

        elif self.current_mode == "greaterSmallerChooser":
            pass

        elif self.current_mode == "challengeChooser":
            pass

class ResultScreen(Screen):
    pass

class HelpScreen(Screen):

    def help_text(self):
        return "Here i will provide simple tricks to become faster when\n" \
               "doing mental calculations.\n" \
               "Example: Instead of adding 5 to a digit greater than 5,\n" \
               "its often more simple to subtract 5 and then add 10.\n" \
               " 8 + 5 = ?\n" \
               " 8 - 5 = 3; 3 + 10 = 13\n" \
               "\n"\
               "Or add in two steps, first to get to an more easy number, \n" \
               "then whatever remains.\n" \
               "\n"\
               "587 + 33 = ?\n" \
               "33 = 20 + 13\n" \
               "587 + 13 = 600; 600 + 20 = 620\n" \
               "Therefore 587 + 33 is 620\n" \
               "\n"\
               "More will follow soon!\n"

class AboutScreen(Screen):

    def about_text(self):
        return "Made by: Jonas\n" \
               "Open source and free of charge \n" \
               "\n" \
               "This app has been written to help everyone to be better\n" \
               " at mental arithmetic.\n" \
               "\n" \
               "Features:\n" \
               "  - simple\n" \
               "  - rewarding\n" \
               "  - perfect for kids in elementary school\n" \
               "  - or adults who want to train their brain ;)\n" \
               "  - No ads, they only distract\n" \
               "  - never gets old, new content is generated procedurally\n" \
               "  - written in Python with the help of Kivy"

class ComingSoonScreen(Screen):
    pass

class PopUpQuit(Popup):
    pass

class MathApp(App):

    sm = ScreenManager(transition=FadeTransition())

    def build(self):

        self.sm.add_widget(MenuScreen(name='menu'))
        self.sm.add_widget(StartScreen(name='start'))
        self.sm.add_widget(ProgressScreen(name='progress'))
        self.sm.add_widget(HelpScreen(name='help'))
        self.sm.add_widget(AboutScreen(name='about'))
        self.sm.add_widget(AddChooseDifficulty(name='addChooser'))
        self.sm.add_widget(SubChooseDifficulty(name='subChooser'))
        self.sm.add_widget(MultiChooseDifficulty(name='multiChooser'))
        self.sm.add_widget(DivChooseDifficulty(name='divChooser'))
        self.sm.add_widget(GreaterSmallerChooseDifficulty(name='greaterSmallerChooser'))
        self.sm.add_widget(ChallengeChooseDifficulty(name='challengeChooser'))
        self.sm.add_widget(GameActionScreen(name='game'))
        self.sm.add_widget(ResultScreen(name='result'))
        self.sm.add_widget(ComingSoonScreen(name='comingsoon'))
        #Bind to keyboard to make the back button under android work
        Window.bind(on_keyboard=self.handle_keyboard)

        return self.sm

    def handle_keyboard(self, window, key, *largs):
        #keycode 273 equals up button, just for test purposes
        if key == 27 or key == 273:
            if self.sm.current_screen.name == 'game':
                popup = PopUpQuit()
                popup.open()
            elif self.sm.current_screen.name == 'menu':
                quit()

            return True

if __name__ == '__main__':
    MathApp().run()<|endoftext|>


<commit_before>import random
from cassiopeia import riotapi
from slacker import Slacker
from flask import Flask, request, Response
import os

app = Flask(__name__)

# Set some variables that we store in our .bashrc file on the server
SLACK_WEBHOOK_SECRET = os.environ.get("SlackWebSecret")
slack = Slacker(os.environ.get("SlackerKey"))
riotapi.set_region("NA")
riotapi.set_api_key(os.environ.get("RiotApiKey"))

# Setting a send message function to keep the app more modular
def send_message(channel_name, message):
    slack.chat.post_message(channel_name, message)

# Command to get the rank of a champion.
# Sends back the following:
# Summoner name
# Rank
# LP
@app.route('/rank', methods=['POST'])
def rank():
    try:
        if request.form.get('token') == SLACK_WEBHOOK_SECRET:
            # Get channel name and text after command
            channel     = request.form.get('channel_name')
            text        = request.form.get('text')
            # Get summoner information
            summoner    = riotapi.get_summoner_by_name(text)
            # Get ranked information about the summoner
            rank        = riotapi.get_league_entries_by_summoner(summoner)
            rankInfo    = [rank[0].tier, rank[0].entries[0].division, rank[0].entries[0].league_points]
            message     = str(text) + " is currently " + str(rankInfo[0])[5:].capitalize() + " " + str(rankInfo[1])[9:].capitalize() + " with " + str(rankInfo[2]) + " lp."
            send_message(channel,message)
        return Response(),200
    except Exception as e:
        return "I could not find that summoner, maybe they are not ranked yet."

@app.route('/winrate', methods=['POST'])
def winrate():
    try:
        if request.form.get('token') == SLACK_WEBHOOK_SECRET:
            # Code for winrate
            # Get channel name and text after command
            channel     = request.form.get('channel_name')
            text        = request.form.get('text')
            # Get summoner information
            summoner    = riotapi.get_summoner_by_name(text)
            # Get winrates for summoner
            rank        = riotapi.get_league_entries_by_summoner(summoner)
            winrate    = (int(rank[0].entries[0].wins)/(int(rank[0].entries[0].wins) + int(rank[0].entries[0].losses)))
            message     = str(text) + " has a ranked winrate of " + "{0:.0%}".format(winrate)
            print(message)
            send_message(channel,message)
        return Response(),200
    except Exception as e:
        return "I could not find that summoner"

# Route for handling accidental Web HTTP requests to the flask server
@app.route('/', methods=['GET'])
def test():
    return Response('Hm... you should go here instead: www.branwidth.com')
    print("it worked")

# Setting SSL values and running application
if __name__ == "__main__":
    context = ('/etc/letsencrypt/live/branwidth.com/fullchain.pem','/etc/letsencrypt/live/branwidth.com/privkey.pem')
    app.run(debug=True, host='0.0.0.0',ssl_context=context)
<commit_msg>removing print command<commit_after>import random
from cassiopeia import riotapi
from slacker import Slacker
from flask import Flask, request, Response
import os

app = Flask(__name__)

# Set some variables that we store in our .bashrc file on the server
SLACK_WEBHOOK_SECRET = os.environ.get("SlackWebSecret")
slack = Slacker(os.environ.get("SlackerKey"))
riotapi.set_region("NA")
riotapi.set_api_key(os.environ.get("RiotApiKey"))

# Setting a send message function to keep the app more modular
def send_message(channel_name, message):
    slack.chat.post_message(channel_name, message)

# Command to get the rank of a champion.
# Sends back the following:
# Summoner name
# Rank
# LP
@app.route('/rank', methods=['POST'])
def rank():
    try:
        if request.form.get('token') == SLACK_WEBHOOK_SECRET:
            # Get channel name and text after command
            channel     = request.form.get('channel_name')
            text        = request.form.get('text')
            # Get summoner information
            summoner    = riotapi.get_summoner_by_name(text)
            # Get ranked information about the summoner
            rank        = riotapi.get_league_entries_by_summoner(summoner)
            rankInfo    = [rank[0].tier, rank[0].entries[0].division, rank[0].entries[0].league_points]
            message     = str(text) + " is currently " + str(rankInfo[0])[5:].capitalize() + " " + str(rankInfo[1])[9:].capitalize() + " with " + str(rankInfo[2]) + " lp."
            send_message(channel,message)
        return Response(),200
    except Exception as e:
        return "I could not find that summoner, maybe they are not ranked yet."

@app.route('/winrate', methods=['POST'])
def winrate():
    try:
        if request.form.get('token') == SLACK_WEBHOOK_SECRET:
            # Code for winrate
            # Get channel name and text after command
            channel     = request.form.get('channel_name')
            text        = request.form.get('text')
            # Get summoner information
            summoner    = riotapi.get_summoner_by_name(text)
            # Get winrates for summoner
            rank        = riotapi.get_league_entries_by_summoner(summoner)
            winrate    = (int(rank[0].entries[0].wins)/(int(rank[0].entries[0].wins) + int(rank[0].entries[0].losses)))
            message     = str(text) + " has a ranked winrate of " + "{0:.0%}".format(winrate)
            send_message(channel,message)
        return Response(),200
    except Exception as e:
        return "I could not find that summoner"

# Route for handling accidental Web HTTP requests to the flask server
@app.route('/', methods=['GET'])
def test():
    return Response('Hm... you should go here instead: www.branwidth.com')
    print("it worked")

# Setting SSL values and running application
if __name__ == "__main__":
    context = ('/etc/letsencrypt/live/branwidth.com/fullchain.pem','/etc/letsencrypt/live/branwidth.com/privkey.pem')
    app.run(debug=True, host='0.0.0.0',ssl_context=context)
<|endoftext|>


<commit_before>'''Entry point for chineurs server'''
import urllib

from flask import Flask, redirect, render_template, request, session, url_for

from chineurs import (
    authentication,
    settings,
    updates)

APP = Flask(__name__)
APP.secret_key = settings.SECRET_KEY
APP.debug = settings.DEBUG

@APP.route('/')
def home():
    '''Home page, or redirect to auth'''
    if request.args.get('new'):
        session.clear()
    if 'facebook_access_token' in session and 'google_access_token' in session:
        return render_template('index.html', update_url=url_for('update'))
    else:
        return redirect(url_for('authenticate'))

@APP.route('/authenticate')
def authenticate():
    '''Authenticates the user with Facebook and Google'''
    uri = (
        'https://www.facebook.com/v2.8/dialog/oauth?'
        'client_id={}&redirect_uri={}'.format(
            urllib.parse.quote(authentication.FACEBOOK_APP_ID),
            urllib.parse.quote(full_url('facebook'))))
    return redirect(uri)

@APP.route('/facebook')
def facebook():
    '''Gets the Facebook auth token and stores it in cookies'''
    session['facebook_access_token'] = (
        authentication.get_facebook_access_token(
            request.args.get('code'),
            full_url('facebook')))
    uri = (
        'https://accounts.google.com/o/oauth2/v2/auth?'
        'scope=https://www.googleapis.com/auth/youtube&'
        'response_type=code&'
        'client_id={}&'
        'redirect_uri={}'.format(
            urllib.parse.quote(authentication.GOOGLE_APP_ID),
            urllib.parse.quote(full_url('google'))))
    return redirect(uri)

@APP.route('/google')
def google():
    '''Gets the Google auth token and stores it in cookies'''
    session['google_access_token'] = authentication.get_google_access_token(
        request.args.get('code'),
        full_url('google'))
    return redirect(url_for('home'))

@APP.route('/update', methods=['POST'])
def update():
    '''Uploads all new videos to YouTube'''
    return '
'.join(updates.update(
        session['facebook_access_token'],
        request.form['group_id'],
        session['google_access_token'],
        request.form['playlist_id']))

def full_url(route):
    '''Returns an absolute URL using the host in the request'''
    parts = urllib.parse.urlparse(request.url)
    scheme = parts[0]
    netloc = parts[1]
    return urllib.parse.urlunparse(
        [scheme, netloc, url_for(route), None, None, None])
<commit_msg>Add logging<commit_after>'''Entry point for chineurs server'''
import logging
import urllib

from flask import Flask, redirect, render_template, request, session, url_for

from chineurs import (
    authentication,
    settings,
    updates)

APP = Flask(__name__)
APP.secret_key = settings.SECRET_KEY
APP.debug = settings.DEBUG
APP.logger.addHandler(logging.StreamHandler())
APP.logger.setLevel(logging.INFO)

@APP.route('/')
def home():
    '''Home page, or redirect to auth'''
    if request.args.get('new'):
        session.clear()
    if 'facebook_access_token' in session and 'google_access_token' in session:
        return render_template('index.html', update_url=url_for('update'))
    else:
        return redirect(url_for('authenticate'))

@APP.route('/authenticate')
def authenticate():
    '''Authenticates the user with Facebook and Google'''
    uri = (
        'https://www.facebook.com/v2.8/dialog/oauth?'
        'client_id={}&redirect_uri={}'.format(
            urllib.parse.quote(authentication.FACEBOOK_APP_ID),
            urllib.parse.quote(full_url('facebook'))))
    return redirect(uri)

@APP.route('/facebook')
def facebook():
    '''Gets the Facebook auth token and stores it in cookies'''
    session['facebook_access_token'] = (
        authentication.get_facebook_access_token(
            request.args.get('code'),
            full_url('facebook')))
    uri = (
        'https://accounts.google.com/o/oauth2/v2/auth?'
        'scope=https://www.googleapis.com/auth/youtube&'
        'response_type=code&'
        'client_id={}&'
        'redirect_uri={}'.format(
            urllib.parse.quote(authentication.GOOGLE_APP_ID),
            urllib.parse.quote(full_url('google'))))
    return redirect(uri)

@APP.route('/google')
def google():
    '''Gets the Google auth token and stores it in cookies'''
    session['google_access_token'] = authentication.get_google_access_token(
        request.args.get('code'),
        full_url('google'))
    return redirect(url_for('home'))

@APP.route('/update', methods=['POST'])
def update():
    '''Uploads all new videos to YouTube'''
    return '
'.join(updates.update(
        session['facebook_access_token'],
        request.form['group_id'],
        session['google_access_token'],
        request.form['playlist_id']))

def full_url(route):
    '''Returns an absolute URL using the host in the request'''
    parts = urllib.parse.urlparse(request.url)
    scheme = parts[0]
    netloc = parts[1]
    return urllib.parse.urlunparse(
        [scheme, netloc, url_for(route), None, None, None])
<|endoftext|>


<commit_before>from django import forms
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User

from haystack.forms import SearchForm as HaystackSearchForm

from pybb.contrib.search.fields import TreeModelMultipleChoiceField
from pybb.models import Forum

class SearchForm(HaystackSearchForm):
    user = forms.ModelChoiceField(queryset=User.objects.all(),
                                  required=False,
                                  label=_('Username'))

    replies = forms.IntegerField(label=_('Number of answers'),
                                 min_value=0, required=False)

    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)

        self.fields['forums'] = TreeModelMultipleChoiceField(queryset=Forum.objects.all(),
                                                             join_field='forum_id',
                                                             required=False)

    def search(self):
        if not self.is_valid():
            return self.no_query_found()

        sqs = super(SearchForm, self).search()

        if self.cleaned_data.get('forums', None):
            sqs = sqs.filter(topic_breadcrumbs__in=[f.id for f in self.cleaned_data['forums']])
        if self.cleaned_data.get('user_id', None):
            sqs = sqs.filter(user_id=self.cleaned_data['user'].pk)
        if self.cleaned_data.get('replies', None):
            sqs = sqs.filter(replies__gte=self.cleaned_data['replies'])
        if self.cleaned_data.get('topic_id', None):
            sqs = sqs.filter(topic_id=self.cleaned_data['topic_id'])

        return sqs
<commit_msg>order search responses by date<commit_after>from django import forms
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User

from haystack.forms import SearchForm as HaystackSearchForm

from pybb.contrib.search.fields import TreeModelMultipleChoiceField
from pybb.models import Forum

class SearchForm(HaystackSearchForm):
    user = forms.ModelChoiceField(queryset=User.objects.all(),
                                  required=False,
                                  label=_('Username'))

    replies = forms.IntegerField(label=_('Number of answers'),
                                 min_value=0, required=False)

    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)

        self.fields['forums'] = TreeModelMultipleChoiceField(queryset=Forum.objects.all(),
                                                             join_field='forum_id',
                                                             required=False)

    def search(self):
        if not self.is_valid():
            return self.no_query_found()

        sqs = super(SearchForm, self).search()
        sqs = sqs.order_by('-created')

        if self.cleaned_data.get('forums', None):
            sqs = sqs.filter(topic_breadcrumbs__in=[f.id for f in self.cleaned_data['forums']])
        if self.cleaned_data.get('user_id', None):
            sqs = sqs.filter(user_id=self.cleaned_data['user'].pk)
        if self.cleaned_data.get('replies', None):
            sqs = sqs.filter(replies__gte=self.cleaned_data['replies'])
        if self.cleaned_data.get('topic_id', None):
            sqs = sqs.filter(topic_id=self.cleaned_data['topic_id'])

        return sqs
<|endoftext|>


<commit_before># php.py - sublimelint package for checking php files

import subprocess, os

def check(codeString, filename):
	info = None
	if os.name == 'nt':
		info = subprocess.STARTUPINFO()
		info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
		info.wShowWindow = subprocess.SW_HIDE

	process = subprocess.Popen(('php', '-l'), stdin=subprocess.PIPE, stdout=subprocess.PIPE, startupinfo=info)
	result = process.communicate(codeString)[0]

	return result

# start sublimelint php plugin
import re
__all__ = ['run', 'language']
language = 'PHP'

def run(code, view, filename='untitled'):
	errors = check(code, filename)

	lines = set()
	underline = [] # leave this here for compatibility with original plugin

	errorMessages = {}
	def addMessage(lineno, message):
		message = str(message)
		if lineno in errorMessages:
			errorMessages[lineno].append(message)
		else:
			errorMessages[lineno] = [message]

	for line in errors.splitlines():
		match = re.match(r'^Parse error:\s*syntax error,\s*(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line)

		if match:
			error, line = match.group('error'), match.group('line')

			lineno = int(line) - 1
			lines.add(lineno)
			addMessage(lineno, error)

	return underline, lines, errorMessages, True
<commit_msg>possibly fixed php lint on windows<commit_after># php.py - sublimelint package for checking php files

import subprocess, os

def check(codeString, filename):
	info = None
	if os.name == 'nt':
		info = subprocess.STARTUPINFO()
		info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
		info.wShowWindow = subprocess.SW_HIDE

	process = subprocess.Popen(('php', '-l', '-d display_errors=On'), stdin=subprocess.PIPE, stdout=subprocess.PIPE, startupinfo=info)
	result = process.communicate(codeString)[0]

	return result

# start sublimelint php plugin
import re
__all__ = ['run', 'language']
language = 'PHP'

def run(code, view, filename='untitled'):
	errors = check(code, filename)

	lines = set()
	underline = [] # leave this here for compatibility with original plugin

	errorMessages = {}
	def addMessage(lineno, message):
		message = str(message)
		if lineno in errorMessages:
			errorMessages[lineno].append(message)
		else:
			errorMessages[lineno] = [message]

	for line in errors.splitlines():
		match = re.match(r'^Parse error:\s*syntax error,\s*(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line)

		if match:
			error, line = match.group('error'), match.group('line')

			lineno = int(line) - 1
			lines.add(lineno)
			addMessage(lineno, error)

	return underline, lines, errorMessages, True
<|endoftext|>


<commit_before>import tensorflow as tf

class Graph:
    def __init__(self, actions, tf_session, load_dir=None):
        self.actions = actions
        self.load_dir = load_dir
        self.tf_session = tf_session
        self.graph = None

    def _get_weights(self, shape, name='weights'):
        with tf.name_scope(name):
            weights = tf.Variable(tf.truncated_normal(shape, stddev=0.005))
        tf.summary.histogram(name, weights)
        return weights

    def _get_bias(self, shape, name='bias'):
        with tf.name_scope(name):
            bias = tf.Variable(tf.constant(0.005, shape=shape))
        tf.summary.histogram(name, bias)
        return bias

    def _convolution_layer(self, input_layer, weights, name='conv_layer'):
        with tf.name_scope(name):
            return tf.nn.conv2d(input_layer, weights, strides=[1, 1, 1, 1], padding='SAME')

    def _max_pooling_layer(self, input_layer, name='max_pool_layer'):
        with tf.name_scope(name):
            return tf.nn.max_pool(input_layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    def _create_new_graph(self):

        with tf.name_scope('Input'):
            input_layer = tf.placeholder(tf.float32, shape=[None, 25600], name='id')
            input = tf.reshape(input_layer, [-1, 80, 320, 1])

        with tf.name_scope('Updated_value'):
            updated_action = tf.placeholder(tf.float32, shape=[None, self.actions])

        with tf.name_scope('Layer1'):
            conv_1_weights = self._get_weights([5, 5, 1, 32])
            conv_1_bias = self._get_bias([32])
            conv_layer_1 = tf.nn.relu(self._convolution_layer(input, conv_1_weights) + conv_1_bias)
            conv_pool_1 = self._max_pooling_layer(conv_layer_1)

        with tf.name_scope('Layer2'):
            conv_2_weights = self._get_weights([5, 5, 32, 64])
            conv_2_bias = self._get_bias([64])
            conv_layer_2 = tf.nn.relu(self._convolution_layer(conv_pool_1, conv_2_weights) + conv_2_bias)
            conv_pool_2 = self._max_pooling_layer(conv_layer_2)

        with tf.name_scope('Layer3'):
            conv_3_weights = self._get_weights([5, 5, 64, 128])
            conv_3_bias = self._get_bias([128])
            conv_layer_3 = tf.nn.relu(self._convolution_layer(conv_pool_2, conv_3_weights) + conv_3_bias)
            conv_pool_3 = self._max_pooling_layer(conv_layer_3)

        with tf.name_scope('Layer4'):
            conv_4_weights = self._get_weights([5, 5, 128, 256])
            conv_4_bias = self._get_bias([256])
            conv_layer_4 = tf.nn.relu(self._convolution_layer(conv_pool_3, conv_4_weights) + conv_4_bias)
            conv_pool_4 = self._max_pooling_layer(conv_layer_4)

        with tf.name_scope('HiddenLayer'):
            hidden_1_weights = self._get_weights([5 * 20 * 256, 2048])
            hidden_1_bias = self._get_bias([2048])
            hidden_layer_input = tf.reshape(conv_pool_4, [-1, 5 * 20 * 256])
            hidden_1_layer_output = tf.nn.relu(tf.matmul(hidden_layer_input, hidden_1_weights) + hidden_1_bias)

        with tf.name_scope('ReadoutLayer'):
            readout_weights = self._get_weights([2048, self.actions])
            readout_bias = self._get_bias([self.actions])

        with tf.name_scope('Output_Distribution'):
            action_value = tf.matmul(hidden_1_layer_output, readout_weights) + readout_bias
            tf.summary.histogram('output', action_value)

        with tf.name_scope("Loss"):
            diff =  action_value - updated_action
            tf.summary.histogram("Diff", diff)
            loss = tf.reduce_sum(diff)
            tf.summary.scalar("Loss", loss)

        train_op = tf.train.AdamOptimizer(1e-6).minimize(loss)

        return train_op, input_layer, action_value, updated_action , loss

    def _load_graph(self, load_dir):
        saver = tf.train.Saver()

        saver.restore(self.tf_session, self.load_dir)
        tf.logging.INFO('Successfully loaded the graph')

    def save_graph(self,save_dir):
        saver = tf.train.Saver()
        saver.save(self.tf_session, save_dir)
        tf.logging.INFO('Successfully saved the graph at %s'%save_dir)

    def get_graph(self):
        self.graph, input_layer, action_value, updated_action ,loss= self._create_new_graph()
        if self.load_dir:
            self._load_graph(self.load_dir)
        return self.graph, input_layer, action_value, updated_action, loss

if __name__ == '__main__':
    Graph(action=10).get_graph()
<commit_msg>Addittion of L2 regularization<commit_after>import tensorflow as tf

class Graph:
    def __init__(self, actions, tf_session, load_dir=None):
        self.actions = actions
        self.load_dir = load_dir
        self.tf_session = tf_session
        self.graph = None

    def _get_weights(self, shape, name='weights'):
        with tf.name_scope(name):
            weights = tf.Variable(tf.truncated_normal(shape, stddev=0.005))
        tf.summary.histogram(name, weights)
        return weights

    def _get_bias(self, shape, name='bias'):
        with tf.name_scope(name):
            bias = tf.Variable(tf.constant(0.005, shape=shape))
        tf.summary.histogram(name, bias)
        return bias

    def _convolution_layer(self, input_layer, weights, name='conv_layer'):
        with tf.name_scope(name):
            return tf.nn.conv2d(input_layer, weights, strides=[1, 1, 1, 1], padding='SAME')

    def _max_pooling_layer(self, input_layer, name='max_pool_layer'):
        with tf.name_scope(name):
            return tf.nn.max_pool(input_layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    def _create_new_graph(self):
        with tf.name_scope('Input'):
            input_layer = tf.placeholder(tf.float32, shape=[None, 25600], name='id')
            input = tf.reshape(input_layer, [-1, 80, 320, 1])

        with tf.name_scope('Updated_value'):
            updated_action = tf.placeholder(tf.float32, shape=[None, self.actions])

        with tf.name_scope('Layer1'):
            conv_1_weights = self._get_weights([5, 5, 1, 32])
            conv_1_bias = self._get_bias([32])
            conv_layer_1 = tf.nn.relu(self._convolution_layer(input, conv_1_weights) + conv_1_bias)
            conv_pool_1 = self._max_pooling_layer(conv_layer_1)

        with tf.name_scope('Layer2'):
            conv_2_weights = self._get_weights([5, 5, 32, 64])
            conv_2_bias = self._get_bias([64])
            conv_layer_2 = tf.nn.relu(self._convolution_layer(conv_pool_1, conv_2_weights) + conv_2_bias)
            conv_pool_2 = self._max_pooling_layer(conv_layer_2)

        with tf.name_scope('Layer3'):
            conv_3_weights = self._get_weights([5, 5, 64, 128])
            conv_3_bias = self._get_bias([128])
            conv_layer_3 = tf.nn.relu(self._convolution_layer(conv_pool_2, conv_3_weights) + conv_3_bias)
            conv_pool_3 = self._max_pooling_layer(conv_layer_3)

        with tf.name_scope('Layer4'):
            conv_4_weights = self._get_weights([5, 5, 128, 256])
            conv_4_bias = self._get_bias([256])
            conv_layer_4 = tf.nn.relu(self._convolution_layer(conv_pool_3, conv_4_weights) + conv_4_bias)
            conv_pool_4 = self._max_pooling_layer(conv_layer_4)

        with tf.name_scope('HiddenLayer'):
            hidden_1_weights = self._get_weights([5 * 20 * 256, 2048])
            hidden_1_bias = self._get_bias([2048])
            hidden_layer_input = tf.reshape(conv_pool_4, [-1, 5 * 20 * 256])
            hidden_1_layer_output = tf.nn.relu(tf.matmul(hidden_layer_input, hidden_1_weights) + hidden_1_bias)

        with tf.name_scope('ReadoutLayer'):
            readout_weights = self._get_weights([2048, self.actions])
            readout_bias = self._get_bias([self.actions])

        with tf.name_scope('Output_Distribution'):
            action_value = tf.matmul(hidden_1_layer_output, readout_weights) + readout_bias
            tf.summary.histogram('output', action_value)

        with tf.name_scope("Loss"):
            diff = action_value - updated_action
            tf.summary.histogram("Diff", diff)
            loss = tf.reduce_sum(diff)
            tf.summary.scalar("Loss", loss)
            loss_with_reg = loss + 0.01 * (tf.reduce_sum(tf.square(hidden_1_weights)) +
                                           tf.reduce_sum(tf.square(readout_weights)) + tf.reduce_sum(
                tf.square(conv_1_weights)) +
                                           tf.reduce_sum(tf.square(conv_2_weights)) + tf.reduce_sum(
                tf.square(conv_3_weights)) + tf.reduce_sum((tf.square(conv_4_weights))))
            tf.summary.scalar("Loss_with_regg", loss_with_reg)
            train_op = tf.train.RMSPropOptimizer(1e-6).minimize(loss_with_reg)

        return train_op, input_layer, action_value, updated_action, loss

    def _load_graph(self, load_dir):
        saver = tf.train.Saver()

        saver.restore(self.tf_session, self.load_dir)
        tf.logging.INFO('Successfully loaded the graph')

    def save_graph(self, save_dir):
        saver = tf.train.Saver()
        saver.save(self.tf_session, save_dir)
        tf.logging.INFO('Successfully saved the graph at %s' % save_dir)

    def get_graph(self):
        self.graph, input_layer, action_value, updated_action, loss = self._create_new_graph()
        if self.load_dir:
            self._load_graph(self.load_dir)
        return self.graph, input_layer, action_value, updated_action, loss

if __name__ == '__main__':
    Graph(action=10).get_graph()
<|endoftext|>


<commit_before>"""
This module contains tests for tofu.geom in its structured version
"""

# Built-in
import sys
import os
import warnings

# Standard
import numpy as np
import matplotlib.pyplot as plt

# tofu-specific
_PATH_HERE = os.path.abspath(os.path.dirname(__file__))
_PATH_TOFU = os.path.dirname(os.path.dirname(os.path.dirname(_PATH_HERE)))

sys.path.insert(0, _PATH_TOFU)
import tofu as tf
sys.path.pop(0)

#######################################################
#
#     Setup and Teardown
#
#######################################################

def setup_module():
    pass

def teardown_module():
    pass

#######################################################
#
#     Utilities routines
#
#######################################################

def _ref_line():

    start = np.r_[4, 0, 0]

    vect = np.r_[-1, 0, 0]
    vect = vect / np.linalg.norm(vect)

    v0 = np.r_[-vect[1], vect[0], 0.]
    v0 = v0 / np.linalg.norm(v0)

    v1 = np.cross(vect, v0)

    return start, vect, v0, v1

def _nine0e1_from_orientations(
    vect=None,
    v0=None,
    v1=None,
    theta=None,
    phi=None,
):

    nin = (
        vect * np.cos(theta)
        + np.sin(theta) * (np.cos(phi) * v0 + np.sin(phi) * v1)
    )

    e0 = (
        - vect * np.sin(theta)
        + np.cos(theta) * (np.cos(phi) * v0 + np.sin(phi) * v1)
    )

    e1 = np.cross(nin, e0)

    return nin, e0, e1

def _apertures():

    start, vect, v0, v1 = _ref_line()

    # ap0 : planar from outline
    out0 = 0.01 * np.r_[-1, 1, 1, -1]
    out1 = 0.005 * np.r_[-1, -1, 1, 1]
    cent = start + 0.15 * vect
    nin, e0, e1 = _nine0e1_from_orientations(
        vect=vect,
        v0=v0,
        v1=v1,
        theta=np.pi/10.,
        phi=0.,
    )
    ap0 = {
        'outline_x0': out0,
        'outline_x1': out1,
        'cent': cent,
        'nin': nin,
        'e0': e0,
        'e1': e1,
    }

    # ap1 : planar from 3d
    out0 = 0.01 * np.r_[-1, 1, 0]
    out1 = 0.01 * np.r_[-0.5, -0.5, 0.5]
    cent = start + 0.2 * vect
    nin, e0, e1 = _nine0e1_from_orientations(
        vect=vect,
        v0=v0,
        v1=v1,
        theta=-np.pi/10.,
        phi=np.pi/20.,
    )

    px = cent[0] + out0 * e0[0] + out1 * e1[0]
    py = cent[1] + out0 * e0[1] + out1 * e1[1]
    pz = cent[2] + out0 * e0[2] + out1 * e1[2]

    ap1 = {
        'poly_x': px,
        'poly_y': py,
        'poly_z': pz,
        'nin': nin,
    }

    # ap2 : non-planar
    out0 = 0.005 * np.r_[-1, 1, 2, 0, -2]
    out1 = 0.005 * np.r_[-1, -1, 0, 1, 0]
    cent = start + 0.3 * vect
    nin, e0, e1 = _nine0e1_from_orientations(
        vect=vect,
        v0=v0,
        v1=v1,
        theta=0.,
        phi=-np.pi/20.,
    )

    scatter = 0.001 * np.r_[-1, 1, 1, -1, -1]
    px = cent[0] + out0 * e0[0] + out1 * e1[0] + scatter * nin[0]
    py = cent[1] + out0 * e0[1] + out1 * e1[1] + scatter * nin[1]
    pz = cent[2] + out0 * e0[2] + out1 * e1[2] + scatter * nin[2]

    ap2 = {
        'poly_x': px,
        'poly_y': py,
        'poly_z': pz,
        'nin': nin,
    }

    return {'ap0': ap0, 'ap1': ap1, 'ap2': ap2}

def _cameras():

    start, vect, v0, v1 = _ref_line()

    # c0: 1d parallel
    out0 = 0.002 * np.r_[-1, 1, 1, -1]
    out1 = 0.005 * np.r_[-1, -1, 1, 1]
    cent = start + 0.01 * vect

    nin, e0, e1 = _nine0e1_from_orientations(
        vect=vect,
        v0=v0,
        v1=v1,
        theta=np.pi/20.,
        phi=0.,
    )

    kl = 0.02*np.linspace(-1, 1, 10)
    cents_x = cent[0] + kl * e0[0]
    cents_y = cent[1] + kl * e0[1]
    cents_z = cent[2] + kl * e0[2]

    c0 = {
        'outline_x0': out0,
        'outline_x1': out1,
        'cents_x': cents_x,
        'cents_y': cents_y,
        'cents_z': cents_z,
        'nin_x': nin[0],
        'nin_y': nin[1],
        'nin_z': nin[2],
        'e0_x': e0[0],
        'e0_y': e0[1],
        'e0_z': e0[2],
        'e1_x': e1[0],
        'e1_y': e1[1],
        'e1_z': e1[2],
        'lamb': np.linspace(3, 4, 100)*1e-10,
        'qeff': 0.99*np.ones((100,))
    }

    # c1: 2d
    out0 = 0.005 * np.r_[-1, 1, 1, -1]
    out1 = 0.005 * np.r_[-1, -1, 1, 1]
    cent = start + 0.01 * vect

    cent0 = 0.02*np.linspace(-1, 1, 5)
    cent1 = 0.02*np.linspace(-1, 1, 5)

    nin, e0, e1 = _nine0e1_from_orientations(
        vect=vect,
        v0=v0,
        v1=v1,
        theta=np.pi/20.,
        phi=0.,
    )

    c1 = {
        'outline_x0': out0,
        'outline_x1': out1,
        'cent': cent,
        'cents_x0': cent0,
        'cents_x1': cent1,
        'nin': nin,
        'e0': e0,
        'e1': e1,
    }

    return {'c0': c0, 'c1': c1}

def _diagnostics():

    # d0: single 1d camera
    d0 = {'optics': 'c0'}

    # d1: single 2d camera
    d1 = {'optics': 'c1'}

    # d2: 1d + 1 aperture
    d2 = {'optics': ('c0', 'ap0')}

    # d3: 2d + 1 aperture
    d3 = {'optics': ('c1', 'ap0')}

    # d4: 1d + multiple apertures
    d4 = {'optics': ('c0', 'ap0', 'ap1', 'ap2')}

    # d5: 2d + multiple apertures
    d5 = {'optics': ('c1', 'ap0', 'ap1', 'ap2')}

    return {
        'd0': d0,
        'd1': d1,
        'd2': d2,
        'd3': d3,
        'd4': d4,
        'd5': d5,
    }

#######################################################
#
#     Tests
#
#######################################################

class Test01_Diagnostic():

    def setup(self):

        # get dict
        dapertures = _apertures()
        dcameras = _cameras()
        ddiag = _diagnostics()

        # instanciate
        self.obj = tf.data.Diagnostic()

        for k0, v0 in dapertures.items():
            self.obj.add_aperture(key=k0, **v0)

        for k0, v0 in dcameras.items():
            if k0 == 'c0':
                self.obj.add_camera_1d(key=k0, **v0)
            else:
                self.obj.add_camera_2d(key=k0, **v0)

        for k0, v0 in ddiag.items():
            self.obj.add_diagnostic(key=k0, **v0)

    # ----------
    # tests

    def test01_etendues(self, res=np.r_[0.005, 0.003, 0.001]):
        for k0, v0 in self.obj.dobj['diagnostic'].items():
            if k0 in ['d0', 'd1', 'd2', 'd3']:
                continue
            self.obj.compute_diagnostic_etendue(
                key=k0,
                res=res,
                check=True,
            )
<commit_msg>[#665] Added unit tests for outline and plot of diagnostics<commit_after>"""
This module contains tests for tofu.geom in its structured version
"""

# Built-in
import sys
import os
import warnings

# Standard
import numpy as np
import matplotlib.pyplot as plt

# tofu-specific
_PATH_HERE = os.path.abspath(os.path.dirname(__file__))
_PATH_TOFU = os.path.dirname(os.path.dirname(os.path.dirname(_PATH_HERE)))

sys.path.insert(0, _PATH_TOFU)
import tofu as tf
sys.path.pop(0)

#######################################################
#
#     Setup and Teardown
#
#######################################################

def setup_module():
    pass

def teardown_module():
    pass

#######################################################
#
#     Utilities routines
#
#######################################################

def _ref_line():

    start = np.r_[4, 0, 0]

    vect = np.r_[-1, 0, 0]
    vect = vect / np.linalg.norm(vect)

    v0 = np.r_[-vect[1], vect[0], 0.]
    v0 = v0 / np.linalg.norm(v0)

    v1 = np.cross(vect, v0)

    return start, vect, v0, v1

def _nine0e1_from_orientations(
    vect=None,
    v0=None,
    v1=None,
    theta=None,
    phi=None,
):

    nin = (
        vect * np.cos(theta)
        + np.sin(theta) * (np.cos(phi) * v0 + np.sin(phi) * v1)
    )

    e0 = (
        - vect * np.sin(theta)
        + np.cos(theta) * (np.cos(phi) * v0 + np.sin(phi) * v1)
    )

    e1 = np.cross(nin, e0)

    return nin, e0, e1

def _apertures():

    start, vect, v0, v1 = _ref_line()

    # ap0 : planar from outline
    out0 = 0.01 * np.r_[-1, 1, 1, -1]
    out1 = 0.005 * np.r_[-1, -1, 1, 1]
    cent = start + 0.15 * vect
    nin, e0, e1 = _nine0e1_from_orientations(
        vect=vect,
        v0=v0,
        v1=v1,
        theta=np.pi/10.,
        phi=0.,
    )
    ap0 = {
        'outline_x0': out0,
        'outline_x1': out1,
        'cent': cent,
        'nin': nin,
        'e0': e0,
        'e1': e1,
    }

    # ap1 : planar from 3d
    out0 = 0.01 * np.r_[-1, 1, 0]
    out1 = 0.01 * np.r_[-0.5, -0.5, 0.5]
    cent = start + 0.2 * vect
    nin, e0, e1 = _nine0e1_from_orientations(
        vect=vect,
        v0=v0,
        v1=v1,
        theta=-np.pi/10.,
        phi=np.pi/20.,
    )

    px = cent[0] + out0 * e0[0] + out1 * e1[0]
    py = cent[1] + out0 * e0[1] + out1 * e1[1]
    pz = cent[2] + out0 * e0[2] + out1 * e1[2]

    ap1 = {
        'poly_x': px,
        'poly_y': py,
        'poly_z': pz,
        'nin': nin,
    }

    # ap2 : non-planar
    out0 = 0.005 * np.r_[-1, 1, 2, 0, -2]
    out1 = 0.005 * np.r_[-1, -1, 0, 1, 0]
    cent = start + 0.3 * vect
    nin, e0, e1 = _nine0e1_from_orientations(
        vect=vect,
        v0=v0,
        v1=v1,
        theta=0.,
        phi=-np.pi/20.,
    )

    scatter = 0.001 * np.r_[-1, 1, 1, -1, -1]
    px = cent[0] + out0 * e0[0] + out1 * e1[0] + scatter * nin[0]
    py = cent[1] + out0 * e0[1] + out1 * e1[1] + scatter * nin[1]
    pz = cent[2] + out0 * e0[2] + out1 * e1[2] + scatter * nin[2]

    ap2 = {
        'poly_x': px,
        'poly_y': py,
        'poly_z': pz,
        'nin': nin,
    }

    return {'ap0': ap0, 'ap1': ap1, 'ap2': ap2}

def _cameras():

    start, vect, v0, v1 = _ref_line()

    # c0: 1d parallel
    out0 = 0.002 * np.r_[-1, 1, 1, -1]
    out1 = 0.005 * np.r_[-1, -1, 1, 1]
    cent = start + 0.01 * vect

    nin, e0, e1 = _nine0e1_from_orientations(
        vect=vect,
        v0=v0,
        v1=v1,
        theta=np.pi/20.,
        phi=0.,
    )

    kl = 0.02*np.linspace(-1, 1, 10)
    cents_x = cent[0] + kl * e0[0]
    cents_y = cent[1] + kl * e0[1]
    cents_z = cent[2] + kl * e0[2]

    c0 = {
        'outline_x0': out0,
        'outline_x1': out1,
        'cents_x': cents_x,
        'cents_y': cents_y,
        'cents_z': cents_z,
        'nin_x': nin[0],
        'nin_y': nin[1],
        'nin_z': nin[2],
        'e0_x': e0[0],
        'e0_y': e0[1],
        'e0_z': e0[2],
        'e1_x': e1[0],
        'e1_y': e1[1],
        'e1_z': e1[2],
        'lamb': np.linspace(3, 4, 100)*1e-10,
        'qeff': 0.99*np.ones((100,))
    }

    # c1: 2d
    out0 = 0.005 * np.r_[-1, 1, 1, -1]
    out1 = 0.005 * np.r_[-1, -1, 1, 1]
    cent = start + 0.01 * vect

    cent0 = 0.02*np.linspace(-1, 1, 5)
    cent1 = 0.02*np.linspace(-1, 1, 5)

    nin, e0, e1 = _nine0e1_from_orientations(
        vect=vect,
        v0=v0,
        v1=v1,
        theta=np.pi/20.,
        phi=0.,
    )

    c1 = {
        'outline_x0': out0,
        'outline_x1': out1,
        'cent': cent,
        'cents_x0': cent0,
        'cents_x1': cent1,
        'nin': nin,
        'e0': e0,
        'e1': e1,
    }

    return {'c0': c0, 'c1': c1}

def _diagnostics():

    # d0: single 1d camera
    d0 = {'optics': 'c0'}

    # d1: single 2d camera
    d1 = {'optics': 'c1'}

    # d2: 1d + 1 aperture
    d2 = {'optics': ('c0', 'ap0')}

    # d3: 2d + 1 aperture
    d3 = {'optics': ('c1', 'ap0')}

    # d4: 1d + multiple apertures
    d4 = {'optics': ('c0', 'ap0', 'ap1', 'ap2')}

    # d5: 2d + multiple apertures
    d5 = {'optics': ('c1', 'ap0', 'ap1', 'ap2')}

    return {
        'd0': d0,
        'd1': d1,
        'd2': d2,
        'd3': d3,
        'd4': d4,
        'd5': d5,
    }

#######################################################
#
#     Tests
#
#######################################################

class Test01_Diagnostic():

    def setup(self):

        # get dict
        dapertures = _apertures()
        dcameras = _cameras()
        ddiag = _diagnostics()

        # instanciate
        self.obj = tf.data.Diagnostic()

        for k0, v0 in dapertures.items():
            self.obj.add_aperture(key=k0, **v0)

        for k0, v0 in dcameras.items():
            if k0 == 'c0':
                self.obj.add_camera_1d(key=k0, **v0)
            else:
                self.obj.add_camera_2d(key=k0, **v0)

        for k0, v0 in ddiag.items():
            self.obj.add_diagnostic(key=k0, **v0)

    # ----------
    # tests

    def test01_etendues(self, res=np.r_[0.005, 0.003, 0.001]):
        for k0, v0 in self.obj.dobj['diagnostic'].items():
            if k0 in ['d0', 'd1']:
                continue
            self.obj.compute_diagnostic_etendue(
                key=k0,
                res=res,
                check=True,
            )

    def test02_get_outline(self):

        # apertures
        for k0, v0 in self.obj.dobj['aperture'].items():
            dout = self.obj.get_optics_outline(k0)

        # camera
        for k0, v0 in self.obj.dobj['camera'].items():
            dout = self.obj.get_optics_outline(k0)

    def test03_plot(self):
        for k0, v0 in self.obj.dobj['diagnostic'].items():
            for pp in [None, 'cross', ['cross', 'hor']]:
                dax = self.obj.plot_diagnostic(k0, proj=pp)
            plt.close('all')
<|endoftext|>


<commit_before>#!/usr/bin/env python

import argparse
import os
import subprocess
import sys
import threading
from collections import OrderedDict

import yaml
import yodl

debug = False

class DockerCompose:
    def __init__(self, compose, project, compose_base_dir, requested_services):
        self.project = project
        self.compose_base_dir = compose_base_dir
        self.services = self.merge_services(compose.get('services', {}))
        self.networks = compose.get('networks', {})
        self.volumes = compose.get('volumes', {})
        self.filtered_services = filter(lambda service: not requested_services or service in requested_services, self.services)

    def project_prefix(self, value):
        return '{}_{}'.format(self.project, value)

    def merge_services(self, services):
        result = OrderedDict()

        for service in services:
            service_config = services[service]
            result[service] = service_config

            if 'extends' in service_config:
                extended_config = service_config['extends']
                extended_service = extended_config['service']

                del result[service]['extends']

                if 'file' in extended_config:
                    extended_service_data = self.merge_services(
                        yaml.load(open(self.compose_base_dir + extended_config['file'], 'r'), yodl.OrderedDictYAMLLoader)['services']
                    )[extended_service]
                else:
                    extended_service_data = result[extended_service]

                for k, v in extended_service_data.items():
                    if k not in result[service]:
                        result[service][k] = v

        return result

    @staticmethod
    def call(cmd, ignore_return_code=False):
        print('Running: \n' + cmd + '\n')
        if not debug:
            ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            returncode = ps.wait()
            stdout = ps.communicate()[0]
            if returncode != 0 and not ignore_return_code:
                print >> sys.stderr, ('Error: command "{}" failed: {}'.format(cmd, stdout))
                sys.exit(returncode)
            else:
                return stdout

    def is_service_exists(self, service):
        return self.call('docker service ls -f name={} | tail -n +2'.format(self.project_prefix(service)))

    def is_external_network(self, network):
        return isinstance(self.networks[network], dict) and 'external' in self.networks[network]

    def up(self):
        for network in self.networks:
            if not self.is_external_network(network):
                cmd = '[ "`docker network ls -f name={0} | tail -n +2`" != "" ] || docker network create --driver overlay --opt encrypted {0}' \
                    .format(self.project_prefix(network))
                self.call(cmd)

        for volume in self.volumes:
            cmd = '[ "`docker volume ls -f name={0} | tail -n +2`" != "" ] || docker volume create --name {0}'.format(self.project_prefix(volume))
            self.call(cmd)

        services_to_start = []

        for service in self.filtered_services:
            if self.is_service_exists(service):
                services_to_start.append(service)
                continue

            service_config = self.services[service]
            cmd = ['docker service create --with-registry-auth \\\n --name', self.project_prefix(service), '\\\n']

            service_image = []
            service_command = []

            for parameter in service_config:
                value = service_config[parameter]

                def restart():
                    cmd.extend(['--restart-condition', {'always': 'any'}[value], '\\\n'])

                def logging():
                    cmd.extend(['--log-driver', value['driver'], '\\\n'])
                    log_opts = value['options']
                    for k, v in log_opts.items():
                        cmd.extend(['--log-opt', '{}={}'.format(k, v), '\\\n'])

                def mem_limit():
                    cmd.extend(['--limit-memory', value, '\\\n'])

                def image():
                    service_image.append(value)

                def command():
                    service_command.extend(value.split(' '))

                def expose():
                    pass  # unsupported

                def container_name():
                    pass  # unsupported

                def hostname():
                    pass  # unsupported; waiting for https://github.com/docker/docker/issues/24877

                def extra_hosts():
                    pass  # unsupported

                def ports():
                    for port in value:
                        cmd.extend(['--publish', port, '\\\n'])

                def networks():
                    for network in value:
                        cmd.extend(['--network', network if self.is_external_network(network) else self.project_prefix(network), '\\\n'])

                def volumes():
                    for volume in value:
                        src, dst = volume.split(':')

                        if src.startswith('.'):
                            src = src.replace('.', self.compose_base_dir, 1)

                        if src.startswith('/'):
                            cmd.extend(['--mount', 'type=bind,src={},dst={}'.format(src, dst), '\\\n'])
                        else:
                            cmd.extend(['--mount', 'src={},dst={}'.format(self.project_prefix(src), dst), '\\\n'])

                def environment():
                    if isinstance(value, dict):
                        for k, v in value.items():
                            cmd.extend(['--env', '{}={}'.format(k, v), '\\\n'])
                    else:
                        for env in value:
                            if env.startswith('constraint') or env.startswith('affinity'):
                                constraint = env.split(':', 2)[1]
                                cmd.extend(['--constraint', "'{}'".format(constraint), '\\\n'])
                            else:
                                cmd.extend(['--env', env, '\\\n'])

                def replicas():
                    cmd.extend(['--replicas', value, '\\\n'])

                def unsupported():
                    print('WARNING: unsupported parameter {}'.format(parameter))

                locals().get(parameter, unsupported)()

            cmd.extend(service_image)
            cmd.extend(service_command)

            self.call(' '.join(cmd))

        if services_to_start:
            self.start(services_to_start)

    def pull(self):
        nodes = self.call("docker node ls | grep Ready | awk -F'[[:space:]][[:space:]]+' '{print $2}'").rstrip().split('\n')

        threads = []

        for node in nodes:
            cmd = '; '.join(['docker -H tcp://{}:2375 pull {}'.format(node, self.services[service]['image']) for service in self.filtered_services])
            threads.append((node, threading.Thread(target=self.call, args=(cmd,))))

        for node, thread in threads:
            print('Pulling on node {}'.format(node))
            thread.start()

        for node, thread in threads:
            thread.join()
            print('Node {} - DONE'.format(node))

    def stop(self):
        services = filter(self.is_service_exists, self.filtered_services)
        cmd_args = ['{}={}'.format(self.project_prefix(service), 0) for service in services]
        if cmd_args:
            self.call('docker service scale ' + ' '.join(cmd_args))

    def rm(self):
        services = filter(self.is_service_exists, self.filtered_services)
        cmd_args = [self.project_prefix(service) for service in services]
        if cmd_args:
            self.call('docker service rm ' + ' '.join(cmd_args))

    def start(self, services=None):
        if services is None:
            services = self.filtered_services

        cmd = 'docker service scale ' + \
              ' '.join(['{}={}'.format(self.project_prefix(service), self.services[service].get('replicas', '1')) for service in services])
        self.call(cmd)

def main():
    parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=50, width=120))
    parser.add_argument('-f', '--file', type=argparse.FileType(), help='Specify an alternate compose file (default: docker-compose.yml)', default='docker-compose.yml')
    parser.add_argument('-p', '--project-name', help='Specify an alternate project name (default: directory name)')
    parser.add_argument('--dry-run', action='store_true')
    subparsers = parser.add_subparsers(title='Command')
    parser.add_argument('_service', metavar='service', nargs='*', help='List of services to run the command for')

    services_parser = argparse.ArgumentParser(add_help=False)
    services_parser.add_argument('service', nargs='*', help='List of services to run the command for')

    pull_parser = subparsers.add_parser('pull', help='Pull service images', add_help=False, parents=[services_parser])
    pull_parser.set_defaults(command='pull')

    rm_parser = subparsers.add_parser('rm', help='Stop and remove services', add_help=False, parents=[services_parser])
    rm_parser.set_defaults(command='rm')
    rm_parser.add_argument('-f', help='docker-compose compatibility; ignored', action='store_true')

    start_parser = subparsers.add_parser('start', help='Start services', add_help=False, parents=[services_parser])
    start_parser.set_defaults(command='start')

    stop_parser = subparsers.add_parser('stop', help='Stop services', add_help=False, parents=[services_parser])
    stop_parser.set_defaults(command='stop')

    up_parser = subparsers.add_parser('up', help='Create and start services', add_help=False, parents=[services_parser])
    up_parser.set_defaults(command='up')
    up_parser.add_argument('-d', help='docker-compose compatibility; ignored', action='store_true')

    args = parser.parse_args(sys.argv[1:])

    global debug
    debug = args.dry_run

    compose_base_dir = os.path.dirname(os.path.abspath(args.file.name))

    if not args.project_name:
        args.project_name = os.path.basename(compose_base_dir)

    docker_compose = DockerCompose(yaml.load(args.file, yodl.OrderedDictYAMLLoader), args.project_name, compose_base_dir + '/', args.service)
    getattr(docker_compose, args.command)()

if __name__ == "__main__":
    main()
<commit_msg>Return False if network is not in networks<commit_after>#!/usr/bin/env python

import argparse
import os
import subprocess
import sys
import threading
from collections import OrderedDict

import yaml
import yodl

debug = False

class DockerCompose:
    def __init__(self, compose, project, compose_base_dir, requested_services):
        self.project = project
        self.compose_base_dir = compose_base_dir
        self.services = self.merge_services(compose.get('services', {}))
        self.networks = compose.get('networks', {})
        self.volumes = compose.get('volumes', {})
        self.filtered_services = filter(lambda service: not requested_services or service in requested_services, self.services)

    def project_prefix(self, value):
        return '{}_{}'.format(self.project, value)

    def merge_services(self, services):
        result = OrderedDict()

        for service in services:
            service_config = services[service]
            result[service] = service_config

            if 'extends' in service_config:
                extended_config = service_config['extends']
                extended_service = extended_config['service']

                del result[service]['extends']

                if 'file' in extended_config:
                    extended_service_data = self.merge_services(
                        yaml.load(open(self.compose_base_dir + extended_config['file'], 'r'), yodl.OrderedDictYAMLLoader)['services']
                    )[extended_service]
                else:
                    extended_service_data = result[extended_service]

                for k, v in extended_service_data.items():
                    if k not in result[service]:
                        result[service][k] = v

        return result

    @staticmethod
    def call(cmd, ignore_return_code=False):
        print('Running: \n' + cmd + '\n')
        if not debug:
            ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            returncode = ps.wait()
            stdout = ps.communicate()[0]
            if returncode != 0 and not ignore_return_code:
                print >> sys.stderr, ('Error: command "{}" failed: {}'.format(cmd, stdout))
                sys.exit(returncode)
            else:
                return stdout

    def is_service_exists(self, service):
        return self.call('docker service ls -f name={} | tail -n +2'.format(self.project_prefix(service)))

    def is_external_network(self, network):
        return isinstance(self.networks[network], dict) and 'external' in self.networks[network] if network in self.networks else False

    def up(self):
        for network in self.networks:
            if not self.is_external_network(network):
                cmd = '[ "`docker network ls -f name={0} | tail -n +2`" != "" ] || docker network create --driver overlay --opt encrypted {0}' \
                    .format(self.project_prefix(network))
                self.call(cmd)

        for volume in self.volumes:
            cmd = '[ "`docker volume ls -f name={0} | tail -n +2`" != "" ] || docker volume create --name {0}'.format(self.project_prefix(volume))
            self.call(cmd)

        services_to_start = []

        for service in self.filtered_services:
            if self.is_service_exists(service):
                services_to_start.append(service)
                continue

            service_config = self.services[service]
            cmd = ['docker service create --with-registry-auth \\\n --name', self.project_prefix(service), '\\\n']

            service_image = []
            service_command = []

            for parameter in service_config:
                value = service_config[parameter]

                def restart():
                    cmd.extend(['--restart-condition', {'always': 'any'}[value], '\\\n'])

                def logging():
                    cmd.extend(['--log-driver', value['driver'], '\\\n'])
                    log_opts = value['options']
                    for k, v in log_opts.items():
                        cmd.extend(['--log-opt', '{}={}'.format(k, v), '\\\n'])

                def mem_limit():
                    cmd.extend(['--limit-memory', value, '\\\n'])

                def image():
                    service_image.append(value)

                def command():
                    service_command.extend(value.split(' '))

                def expose():
                    pass  # unsupported

                def container_name():
                    pass  # unsupported

                def hostname():
                    pass  # unsupported; waiting for https://github.com/docker/docker/issues/24877

                def extra_hosts():
                    pass  # unsupported

                def ports():
                    for port in value:
                        cmd.extend(['--publish', port, '\\\n'])

                def networks():
                    for network in value:
                        cmd.extend(['--network', network if self.is_external_network(network) else self.project_prefix(network), '\\\n'])

                def volumes():
                    for volume in value:
                        src, dst = volume.split(':')

                        if src.startswith('.'):
                            src = src.replace('.', self.compose_base_dir, 1)

                        if src.startswith('/'):
                            cmd.extend(['--mount', 'type=bind,src={},dst={}'.format(src, dst), '\\\n'])
                        else:
                            cmd.extend(['--mount', 'src={},dst={}'.format(self.project_prefix(src), dst), '\\\n'])

                def environment():
                    if isinstance(value, dict):
                        for k, v in value.items():
                            cmd.extend(['--env', '{}={}'.format(k, v), '\\\n'])
                    else:
                        for env in value:
                            if env.startswith('constraint') or env.startswith('affinity'):
                                constraint = env.split(':', 2)[1]
                                cmd.extend(['--constraint', "'{}'".format(constraint), '\\\n'])
                            else:
                                cmd.extend(['--env', env, '\\\n'])

                def replicas():
                    cmd.extend(['--replicas', value, '\\\n'])

                def unsupported():
                    print('WARNING: unsupported parameter {}'.format(parameter))

                locals().get(parameter, unsupported)()

            cmd.extend(service_image)
            cmd.extend(service_command)

            self.call(' '.join(cmd))

        if services_to_start:
            self.start(services_to_start)

    def pull(self):
        nodes = self.call("docker node ls | grep Ready | awk -F'[[:space:]][[:space:]]+' '{print $2}'").rstrip().split('\n')

        threads = []

        for node in nodes:
            cmd = '; '.join(['docker -H tcp://{}:2375 pull {}'.format(node, self.services[service]['image']) for service in self.filtered_services])
            threads.append((node, threading.Thread(target=self.call, args=(cmd,))))

        for node, thread in threads:
            print('Pulling on node {}'.format(node))
            thread.start()

        for node, thread in threads:
            thread.join()
            print('Node {} - DONE'.format(node))

    def stop(self):
        services = filter(self.is_service_exists, self.filtered_services)
        cmd_args = ['{}={}'.format(self.project_prefix(service), 0) for service in services]
        if cmd_args:
            self.call('docker service scale ' + ' '.join(cmd_args))

    def rm(self):
        services = filter(self.is_service_exists, self.filtered_services)
        cmd_args = [self.project_prefix(service) for service in services]
        if cmd_args:
            self.call('docker service rm ' + ' '.join(cmd_args))

    def start(self, services=None):
        if services is None:
            services = self.filtered_services

        cmd = 'docker service scale ' + \
              ' '.join(['{}={}'.format(self.project_prefix(service), self.services[service].get('replicas', '1')) for service in services])
        self.call(cmd)

def main():
    parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=50, width=120))
    parser.add_argument('-f', '--file', type=argparse.FileType(), help='Specify an alternate compose file (default: docker-compose.yml)', default='docker-compose.yml')
    parser.add_argument('-p', '--project-name', help='Specify an alternate project name (default: directory name)')
    parser.add_argument('--dry-run', action='store_true')
    subparsers = parser.add_subparsers(title='Command')
    parser.add_argument('_service', metavar='service', nargs='*', help='List of services to run the command for')

    services_parser = argparse.ArgumentParser(add_help=False)
    services_parser.add_argument('service', nargs='*', help='List of services to run the command for')

    pull_parser = subparsers.add_parser('pull', help='Pull service images', add_help=False, parents=[services_parser])
    pull_parser.set_defaults(command='pull')

    rm_parser = subparsers.add_parser('rm', help='Stop and remove services', add_help=False, parents=[services_parser])
    rm_parser.set_defaults(command='rm')
    rm_parser.add_argument('-f', help='docker-compose compatibility; ignored', action='store_true')

    start_parser = subparsers.add_parser('start', help='Start services', add_help=False, parents=[services_parser])
    start_parser.set_defaults(command='start')

    stop_parser = subparsers.add_parser('stop', help='Stop services', add_help=False, parents=[services_parser])
    stop_parser.set_defaults(command='stop')

    up_parser = subparsers.add_parser('up', help='Create and start services', add_help=False, parents=[services_parser])
    up_parser.set_defaults(command='up')
    up_parser.add_argument('-d', help='docker-compose compatibility; ignored', action='store_true')

    args = parser.parse_args(sys.argv[1:])

    global debug
    debug = args.dry_run

    compose_base_dir = os.path.dirname(os.path.abspath(args.file.name))

    if not args.project_name:
        args.project_name = os.path.basename(compose_base_dir)

    docker_compose = DockerCompose(yaml.load(args.file, yodl.OrderedDictYAMLLoader), args.project_name, compose_base_dir + '/', args.service)
    getattr(docker_compose, args.command)()

if __name__ == "__main__":
    main()
<|endoftext|>