コード例 #1
0
def action2_fichier_codem_niv2(entetes: "un" = "zapata", lus: "deux" = "vide"):
    """
    @param entetes headers
    @param lus paramètres dans l'url ou dans le formule post
    """
    mimes = {
        "html": "text/html",
        "css": "text/css",
        "js": "text/javascript",
        "md": "text/plain"
    }
    try:
        if not lus["ext"] in mimes.keys():
            raise Exception("forbidden")
        hs = {"Content-Type": mimes[lus["ext"]]}
        if "file" in lus.keys():
            hs["Content-Disposition"] = ("attachment; filename=\"%s\"" %
                                         lus["file"])
        bincont = readfile(www_dir + "/codem/" + lus["path2"] + "/" +
                           lus["path1"] + "." + lus["ext"])
        return answer(code=202, headers=hs, body=bincont)
    except Exception as ex:
        print("action2", ex)
        return answer(code=404,
                      body=lus["path1"] + "." + lus["ext"],
                      mime=mimes["html"])
コード例 #2
0
def static(environ, start_response):
    file_path = environ['PATH_INFO'].strip('/')
    response_body = tools.readfile(file_path)

    content_type = 'application/octet-stream'
    if file_path.endswith('.html'):
        content_type = constants.TEXT_HTML
    elif file_path.endswith('.css'):
        content_type = constants.TEXT_CSS
    elif file_path.endswith('.jpg'):
        content_type = constants.IMAGE_JPEG

    start_response('200 OK', tools.get_content_headers(content_type))
    return [
        response_body
        if file_path.endswith('.jpg') else response_body.encode(constants.UTF8)
    ]
コード例 #3
0
def result(environ, start_response):
    parsed_qs = tools.check_post_request(environ)
    scoreValue = int(parsed_qs['score'].pop()) if 'score' in parsed_qs else 0

    for question in parsed_qs:
        answer = parsed_qs[question].pop() if parsed_qs[question] else ''
        if question in constants.TEST_ANSWERS and answer in constants.TEST_ANSWERS[
                question]:
            scoreValue += 1

    response_body = tools.readfile('static/html/result.html')
    test_result = 'result-good' if scoreValue >= constants.UNICORN_LICENSE_SCORE_LIMIT else 'result-bad'
    response_body = templates.apply(test_result, response_body)
    response_body = response_body.format(score=scoreValue)

    start_response(constants.STATUS_OK,
                   tools.get_content_headers(constants.TEXT_HTML))
    return [response_body.encode(constants.UTF8)]
コード例 #4
0
    async def astropix(self, ctx, arg1=''):
        """|coro|

        Sends Discord embed with Astronomy Picture of the Day as reply.

        Parameters
        -----------
        ctx: :class:`discord.ext.commands.context.Context`
        Context object provided by discord.py module.
        arg1: :class:`str`
        `sub` or `unsub` to subscribe/unsubscribe channel.
        """
        if arg1 == ('sub' or 'unsub'):  # Subs or unsubs channel
            if Astronomy.sub(ctx.guild.id, ctx.channel.id):
                await ctx.send(
                    'This channel has been subscribed to Astronomy Picture of the Day from NASA!'
                )
            else:
                await ctx.send(
                    'This channel has been unsubscribed to Astronomy Picture of the Day from NASA.'
                )
        elif arg1 == 'new':  # Gets new Astropix
            self.getnew()
        else:  # Sends Astropix
            if not path.exists('resources/apod/apod.txt') or not path.exists(
                    'resources/apod/apod.html'):
                self.getnew()
            response = tools.readfile('resources/apod/apod.txt')
            embed = discord.Embed(title=response[1],
                                  description=response[2],
                                  colour=discord.Colour.blue())
            embed.set_author(name='Astronomy Picture of the Day')
            embed.set_footer(text='Credit: ' + response[3])
            embed.set_thumbnail(
                url=tools.import_configs()['ASTRONOMY']['thumbnail'])
            if 'youtube' in response[
                    0]:  # Embed video or image, depending on which it is
                await ctx.send(response[0])
            else:
                embed.set_image(url=response[0])
            await ctx.send(embed=embed)
コード例 #5
0
def make_response(environ, start_response, not_found=False):
    parsed_qs = tools.check_post_request(environ)

    answer_type = 'index'
    if not_found:
        answer_type = 'not-found'
    elif 'answer' in parsed_qs:
        answer_type = parsed_qs['answer'].pop()

    response_template = 'static/html/{}.html'
    if 'catif' in answer_type:
        response_template = 'static/html/catification'
        response_template += '/catif-yes.html' if 'yes' in answer_type else '/catif-main.html'

    response_body = tools.readfile(response_template.format(answer_type))
    if response_template.endswith('catif-main.html'):
        response_body = response_body.format(
            **constants.IMAGE_NAMES_WITH_CATIF_TYPES[answer_type])
    response_body = templates.apply(answer_type, response_body)

    status = constants.STATUS_NOT_FOUND if not_found else constants.STATUS_OK
    start_response(status, tools.get_content_headers(constants.TEXT_HTML))
    return [response_body.encode(constants.UTF8)]
コード例 #6
0
 async def warcrime(self, ctx):
     try:
         warcrimes = tools.readfile('resources/warcrime.txt')
         await ctx.send(warcrimes[randint(0, len(warcrimes))])
     except FileNotFoundError:
         print('No warcrime.txt file!')
コード例 #7
0
# support for GPU acceleration and automatic
# differentiation, and a flexible platform for machine
# learning research and experimentation

import time

import tensorflow as tf
import tensorflow.contrib.eager as tfe
import matplotlib.pyplot as plt
import tools

DATA_FILE = 'data/birth_life_2010.txt'

tfe.enable_eager_execution()

data, n_samples = tools.readfile(DATA_FILE)
dataset = tf.data.Dataset.from_tensor_slices((data[:, 0], data[:, 1]))

# Create variables.
w = tfe.Variable(0.0)
b = tfe.Variable(0.0)


# Define the linear predictor.
def prediction(x):
    return x * w + b


# Define loss functions of the form: L(y, y_predicted)
def squared_loss(y, y_predicted):
    return (y - y_predicted)**2
コード例 #8
0
                "Filetype_mime": Filetype_mime,
                "Reading_Byte": Reading_Byte,
                "Date_Added":Date_Added,
                "Source": Source,
                "Inputer": Inputer,
                "Details": Details }
    proceed = dbcontrols.add_url_sources(url_sourcesObject, item4db['Sha256_1024chunk'], item4db)
    if proceed == False:
        print("Previously this file with an identical Sha256 was submitted with a different Filename. Closing")
        sys.exit()


# Filename exists, reuse file metadata
else:
    time.sleep(1)
    print('\n' + str(unique_check) + '\n')
    time.sleep(1)
    question = ("Resume upload of URL list with the above variables?")
    proceed = tools.query_yes_no(question, default=None)
    if proceed == False:
        print("Restart with a unique filename. Closing.")
        sys.exit()
    print("Upload of URLs will resume with existing item variables.")
    item4db = unique_check


## Upload/Continue to upload URLs to URL collection
Reading_Byte = (item4db['Reading_Byte'])
print("Starting/Resuming URL uploads from byte:", Reading_Byte)
tools.readfile(data_base, item4db, Reading_Byte)