예제 #1
0
def auth_to_lingualeo():
    # Check if you log in to lingualeo.com and can add words
    try:
        with open(appdata.CREDENTIALS_FILE_PATH, "r") as data_file:
            auth_data = data_file.read()
        if len(auth_data) < 1:
            fb = feedback.Feedback()
            fb.add_item(title="You are not logged in to Lingualeo!",
                        subtitle="")
            print fb
            sys.exit()
    except Exception as e:
        return "ERROR 34"

    # Loggin in
    auth_data_split = base64.b64decode(auth_data).split("||")
    mail = auth_data_split[0]
    password = auth_data_split[1]
    auth = {'email': mail, 'password': password}
    try:
        cj = CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        opener.open("http://api.lingualeo.com/api/login",
                    urllib.urlencode(auth))
    except Exception as e:
        return "ERROR: Cannot log in to lingualeo!"
    return opener
예제 #2
0
def translate_text():
    # Translate word and output it to XML parser for Alfred
    data = json_data
    output = data["translate"]
    sorted_output = sorted(output,
                           key=lambda student: int(student['votes']),
                           reverse=True)

    fb = feedback.Feedback()
    for item in sorted_output:
        translation = item["value"]
        popularity = str(item["votes"])
        arguments = word + "||" + str(item["id"])
        fb.add_item(title=translation, subtitle=popularity, arg=arguments)
    return fb
예제 #3
0
def check_cache():
    if os.path.isfile(appdata.DICT_FILE_PATH):
        current_time = time.time()
        time_of_changing_file = os.path.getmtime(appdata.DICT_FILE_PATH)
        difference = int(current_time - time_of_changing_file)
        if difference > 300:
            set_cache(auth_to_lingualeo())
            output_words()
        else:
            output_words()
    elif os.path.isfile(appdata.CREDENTIALS_FILE_PATH):
        set_cache(auth_to_lingualeo())
        output_words()
    else:
        fb = feedback.Feedback()
        fb.add_item(
            title='Please, enter command "llsignin" for sign in to Lingualeo!')
        print fb
예제 #4
0
def get_output(input_string):
    """Main entry point"""
    fb = feedback.Feedback()
    input_string = input_string.strip()
    if not input_string:
        fb.add_item(title="Translation not found", valid="no")
        return fb

    # Making requests in parallel
    responses = asyncio.run(process_requests(input_string))

    spelling_suggestions_items = get_spelling_suggestions(responses[0])
    # Generate possible xml outputs
    formatted_spelling_suggestions = convert_spelling_suggestions(
        spelling_suggestions_items)
    formatted_translation_suggestions = get_translation_suggestions(
        responses[1], responses[2])
    words_in_phase = len(re.split(' ', input_string))

    # Output
    if len(formatted_spelling_suggestions) == 0 and len(
            formatted_translation_suggestions) == 0:
        fb.add_item(title="Translation not found", valid="no")
        return fb

    # Prepare suggestions output
    # Spellcheck error
    if words_in_phase <= 2 and len(formatted_spelling_suggestions) != 0:
        for spelling_suggestion in formatted_spelling_suggestions:
            fb.add_item(title=spelling_suggestion['title'],
                        autocomplete=spelling_suggestion['autocomplete'],
                        icon='spellcheck.png')

    # Translations output
    for formatted_translated_suggestion in formatted_translation_suggestions:
        fb.add_item(title=formatted_translated_suggestion['translation'],
                    arg=formatted_translated_suggestion['translation'],
                    subtitle=formatted_translated_suggestion['transcription'])
    return fb
예제 #5
0
def find_files(basedir, _filter=""):
    """create a list of tp files"""
    command = [
        "mdfind", "-onlyin", basedir,
        "kMDItemContentTypeTree==public.image&&kMDItemFSName==*" + _filter +
        "*"
    ]
    __logger__.debug(command)
    # simple call to run a system process
    cmd = runcommand.RunCommand(command)
    file_list = cmd.run()
    atree = feedback.Feedback()
    if file_list != None:
        __logger__.debug(file_list)
        for file_ in sorted(file_list):
            fname = file_.split("/")[-1]
            atree.add_item(fname,
                           subtitle="Use " + fname + " as Background Image",
                           arg=file_)
    __logger__.info(atree)
    alfred_xml = repr(atree)
    return alfred_xml
예제 #6
0
def output_words():
    dictionary = parse_words()
    fb = feedback.Feedback()

    if query == "w":
        for card in dictionary[0:50]:
            if card['word'].strip().find(' ') == -1:
                fb.add_item(title=card['title'],
                            subtitle=card['context'],
                            icon=card['img_path'],
                            arg=card['word'])

    elif query == "p":
        for card in dictionary[0:50]:
            if card['word'].strip().find(' ') != -1:
                fb.add_item(title=card['title'],
                            subtitle=card['context'],
                            icon=card['img_path'],
                            arg=card['word'])

    elif query == "r":
        max_number = len(dictionary) - 1
        random_number = randint(0, max_number)
        title = dictionary[random_number]['title']
        subtitle = dictionary[random_number]['context']
        icon = dictionary[random_number]['img_path']
        arg = dictionary[random_number]['word']
        fb.add_item(title=title, subtitle=subtitle, icon=icon, arg=arg)

    else:
        for card in dictionary[0:50]:
            fb.add_item(title=card['title'],
                        subtitle=card['context'],
                        icon=card['img_path'],
                        arg=card['word'])

    print fb
예제 #7
0
import feedback  # quelques fonctions utiles plbank/pysrc/src/utils
import sys
import json

fb = feedback.Feedback()
try:
    with open("student.py", "r") as f:
        exec(f.read(),
             globals())  # chargement du code de l'élève ou X doit être défini
    if X == "Toto":
        fb.setsuccess(True)
        fb.addFeedback("Bravo c'est bon !!!")
    else:
        fb.setsuccess(False)
        fb.addFeedback("La variable est mal initialisé !!!")

except NameError as e:
    fb.setsuccess(False)
    fb.addFeedback("Il faut déclarer une variable X \n" + str(e))
except Exception as e:
    fb.setsuccess(False)
    fb.addFeedback("Proposez un code qui compile" + str(e))
print(json.dumps(fb.outputdic()))
# pour être sur que le grader se termine bien ;)
sys.exit(0)
예제 #8
0
def test_feedback2():
    f = feedback.Feedback()
    f.addCompilationError("beurk ca compile pas ")
    print(f.feedback())
    assert f.success == False
    assert f.feedback() == """
예제 #9
0
def test_feedback():
    f = feedback.Feedback()
    f.addFeedback("texte")
    print(f.feedback())
    assert f.feedback() == """
예제 #10
0
 def parseFeedbackElement(self, element):
     value = element.classes.pop() == "plus"
     content = element.xpath("div/p").pop().text
     return feedback.Feedback(content.strip(), value, False)
예제 #11
0
def get_output(input_string):
    """Main entry point"""
    pool = Pool(processes=3)
    fb = feedback.Feedback()
    input_string = input_string.strip()
    if not input_string:
        fb.add_item(title="Translation not found", valid="no")
        return fb

    # Building urls
    translationDirection = get_translation_direction(input_string)

    # Build spell check url
    spellCheckParams = {'text': input_string, 'lang': get_lang(input_string)}
    spellCheckUrl = 'https://speller.yandex.net/services/spellservice.json/checkText' + '?' + urllib.urlencode(
        spellCheckParams)

    # Build article url
    articleParams = {
        'key': dict_api_key,
        'lang': translationDirection,
        'text': input_string,
        'flags': 4
    }
    articleUrl = 'https://dictionary.yandex.net/api/v1/dicservice.json/lookup' + '?' + urllib.urlencode(
        articleParams)

    # Build translation url
    translationParams = {
        'key': translate_api_key,
        'lang': translationDirection,
        'text': input_string
    }
    translationUrl = 'https://translate.yandex.net/api/v1.5/tr.json/translate' + '?' + urllib.urlencode(
        translationParams)

    # Making requests in parallel
    requestsUrls = [spellCheckUrl, translationUrl, articleUrl]
    responses = pool.map(process_response_as_json, requestsUrls)

    spelling_suggestions_items = get_spelling_suggestions(responses[0])
    # Generate possible xml outputs
    formatted_spelling_suggestions = convert_spelling_suggestions(
        spelling_suggestions_items)
    formated_translation_suggestions = get_translation_suggestions(
        input_string, spelling_suggestions_items, responses[1], responses[2])
    words_in_phase = len(re.split(' ', input_string.decode('utf-8')))

    # Output
    if len(formatted_spelling_suggestions) == 0 and len(
            formated_translation_suggestions) == 0:
        fb.add_item(title="Translation not found", valid="no")
        return fb

    # Prepare suggestions output
    # Spellcheck error
    if words_in_phase <= 2 and len(formatted_spelling_suggestions) != 0:
        for spelling_suggestion in formatted_spelling_suggestions:
            fb.add_item(title=spelling_suggestion['title'],
                        autocomplete=spelling_suggestion['autocomplete'],
                        icon='spellcheck.png')

    # Translations output
    for formatted_translated_suggestion in formated_translation_suggestions:
        fb.add_item(title=formatted_translated_suggestion['translation'],
                    arg=formatted_translated_suggestion['translation'],
                    subtitle=formatted_translated_suggestion['transcription'])
    return fb
예제 #12
0
        layout.window['leave_cal'].update(visible=False)
        layout.window['gra_display'].update(visible=False)
        layout.window['pen_display'].update(visible=False)
        layout.window['home'].update(visible=False)
        layout.window['username'].update(visible=False)
        layout.window['feedback_layout'].update(visible=True)

    if event == "feedback_ok":
        if values['feedback_name'] != "" and values['feedback_email'] != "" and \
                values['feedback_body'] != "":
            true_mail = feedback.check_mail(str(values['feedback_email']))
            if true_mail:
                internet = feedback.connect()
                if internet:
                    try:
                        feed_back = feedback.Feedback("*****@*****.**", "pa&ao@t1")
                        result = feed_back.send_feedback(values['feedback_name'], values['feedback_email'],
                                                         values['feedback_body'])
                        if result:
                            layout.window['validate'].update("Successful!")
                            layout.sg.popup("Your feedback sent successfully", title="Success!", icon=r'icon.ico')
                        else:
                            layout.window['validate'].update("Error!")
                            layout.sg.popup("Somethings went wrong! Please try again.", title="Error!",
                                            icon=r'icon.ico')
                    except:
                        layout.sg.popup("Please enter all the required fields.", title="Error!", icon=r'icon.ico')
                else:
                    layout.sg.popup("Please check your Internet connection and try again", title="Error!",
                                    icon=r'icon.ico')
            else: