Exemple #1
0
def adjust_args_format(arg):
    arg_list = arg.split(" ")
    logger.info("バッチの引数を修正開始。" + arg)
    for i, temp in enumerate(arg_list):
        if "システム日付" in temp:
            today = datetime.now().strftime("%Y/%m/%d")
            arg_list[i] = today
        elif "当月末" in temp:
            today = datetime.today()
            last_day = (today + relativedelta(months=1)).replace(
                day=1) - timedelta(days=1)
            last_day = datetime.strftime(last_day, '%Y/%m/%d')
            arg_list[i] = last_day
        elif "前月末" in temp:
            today = datetime.today()
            last_day_last_month = today.replace(day=1) - timedelta(days=1)
            last_day_last_month = datetime.strftime(last_day_last_month,
                                                    '%Y/%m/%d')
            arg_list[i] = last_day_last_month
        elif "***" in temp:
            slash = temp.index("/")
            user_code = temp[0:slash]
            arg_list[i] = user_code + "/" + user_code
        elif temp.isdecimal():
            arg_list[i] = str(int(temp))
    return " ".join(arg_list)
Exemple #2
0
def upcoming_contests():

    # print("amit")

    url = "https://clist.by:443/api/v1/contest/?end__gt="
    stTime = datetime.today() - timedelta(hours=6, minutes=0)
    enTime = datetime.today() - timedelta(hours=6, minutes=0) + timedelta(hours=480, minutes=0)

    begin = str(stTime.year) + "-" + str(stTime.month) + "-" + str(stTime.day) + "T" + str(stTime.hour) + "%3A" + str(stTime.minute) + "%3A" + str(stTime.second)
    endd = str(enTime.year) + "-" + str(enTime.month) + "-" + str(enTime.day) + "T" + str(enTime.hour) + "%3A" + str(enTime.minute) + "%3A" + str(enTime.second)
    # print(begin)
    # print(endd)
    url3 = "https://clist.by:443/api/v1/contest/?end__gt=" + begin + "&" + "end__lt=" + endd

    # print(url3)
    # print(url)
    res = requests.get(url3,headers={'Authorization': 'ApiKey Ahb_arif:e746f33d1dca698bf9e578774d86dafb916fe288'})
    # print(res.text)
    jsonData = res.json()
    objects = jsonData["objects"]
    contestData = []
    for x in objects:

        siteName = x["resource"]["name"]
        contestName = x["event"]
        startTime = str(x["start"])
        startTime.replace("T", " , ")
        endTime = str(x["end"])
        endTime.replace("T", " , ")
        sortKey = str(x["end"])
        sortKey =  sortKey.replace("T", " ")
        link = x["href"]
        duration = int(float(x["duration"]) * 0.000277778)

        if duration >=24:
            d = int(duration/24)
            h = duration % 24
            duration = str(d) + " days "
            if h >0:
                duration+= str(h) + " hours "

        else:
            duration = str(duration) + " hours"

        if siteName == "codeforces.com" or siteName == "csacademy.com" or siteName == "hackerrank.com" or siteName=="codechef.com":
            temp = {}
            temp["sitename"] = siteName
            temp["contest_name"] = contestName
            temp["startTime"] = startTime.replace("T",", ") +" (GMT)"
            temp["endTime"] = endTime.replace("T",", ") +" (GMT)"
            temp["sortKey"] = sortKey
            temp["link"] = link
            temp["duration"] = duration

            # print(temp)
            contestData.append(temp)

    contestData = sorted(contestData, key=lambda k: datetime.strptime(str(k["sortKey"]), "%Y-%m-%d %H:%M:%S"),
                               reverse=False)
    return render_template('/contestReminder/Upcoming Contests.html',contestInfo=contestData)
Exemple #3
0
def solve(puzzle, ui):
    board = [[[] for x in range(5)] for y in range(5)]
    sqaures = preprocess(puzzle)
    initialize_env_variables(puzzle, board)

    root = Node(board, 0, None)

    results = []
    for i in range(2):

        print(datetime.today().strftime(
            "%H:%M:%S.%f  cretae tree of possible answers with the root of:"))
        for row in root.board:
            print(row)

        results = run_pipeline(puzzle, sqaures, root, 3, 3, i)
        root = results[0]

    trace_node = results[0]

    print(datetime.today().strftime(
        "%H:%M:%S.%f  Trace from resulting leaf node to root Node: "))
    while trace_node is not None:
        for i in range(5):
            for j, children in enumerate(trace_node.children):
                print(children.board[i], end='\t')
            print('\n', end='')
        print()

        trace_node = trace_node.parent
    print(datetime.today().strftime("%H:%M:%S.%f  End of Trace"))

    return results[0].board
Exemple #4
0
def test_MakeCurrentSeasonMatchesList():
    assert current_games.CurrentGames(datetime.today().year -
                                      1).get_current_season() is None
    assert current_games.CurrentGames(
        datetime.today().year).get_current_season() is None
    assert current_games.CurrentGames(datetime.today().year +
                                      1).get_current_season() is None
Exemple #5
0
def get_possible_answers(board, questions, squares, num_of_word):
    possibilities = []
    for i, question in enumerate(questions):
        incomplete = False
        sp = ''
        words = []
        for j, square in enumerate(squares[i]):
            sp += board[square[0]][square[1]]
            if board[square[0]][square[1]] == '':
                incomplete = True
                sp += '?'
        if incomplete:
            question = question[3:]
            regex = re.compile('[^a-zA-Z ]')
            # First parameter is the replacement, second parameter is your input string
            question = regex.sub(' ', question)

            print(datetime.today().strftime(question))
            print(datetime.today().strftime(
                "%H:%M:%S.%f  acquiring words on the pattern of:" + sp))
            words = api.words(ml=question, max=num_of_word, sp=sp)
            for word in words:
                print(word['word'], end=' ')
            print()

            if len(words) == 0:
                words = api.words(max=num_of_word, sp=sp)
        possibilities.append(words)
    return possibilities
Exemple #6
0
 def get_days(self, force_download):
     today = (datetime.today().day, datetime.today().month)
     weeks = self.get_all_weeks()
     for i, week in enumerate(weeks, start=1):
         if today in week:
             if 1 <= i <= 22:
                 t = threading.Thread(target=lambda: self.set_blocks_thread_func(i, force_download))
                 t.start()
             break
Exemple #7
0
def save_to_csv(articles):
    date = datetime.today().strftime("%Y%m%d%H%M%S")
    date = date[:8]
    hour = datetime.today().hour
    minute = datetime.today().minute
    file = open(f"./csvData/naver_IT_articles__{date}_{hour}시_{minute}분.csv", mode="w", encoding="UTF-8", newline='')
    writer = csv.writer(file)
    writer.writerow(["제목", "신문사", "바로가기"])
    for article in articles:
        writer.writerow(list(article.values()))
    return
 def __init__(self,
              rentalId,
              bookId,
              clientId,
              rentedDate=datetime.today(),
              dueDate=datetime.today()):
     self._rentalId = rentalId
     self._clientId = clientId
     self._bookId = bookId
     self._rentedDate = rentedDate
     self._dueDate = dueDate
     self._returnDate = datetime(1, 1, 1)
Exemple #9
0
def get_fecha() -> str:
    '''
    Devuelve la fecha en la que estamos
    :rtype : basestring
    :return: String
    '''
    dia = datetime.today().day
    mes = datetime.today().month
    anyo = datetime.today().year
    fecha = dia + '/' + mes + '/' + anyo

    return fecha
Exemple #10
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # hide form labels and set required
        self.fields['title'].required = True
        self.fields['title'].label = ""

        self.fields['entryText'].required = True
        self.fields['entryText'].label = ""

        self.fields['dateTime'].initial = datetime.today()

        # Assign a default date/time if creating model without saved data
        if type(self.instance.dateTime) is not datetime:
            self.instance.dateTime = datetime.today()
def inserir_anexo(interacao, path, filename, target):
    anexo = PedidosAnexos(codigopedidointeracao=interacao,
                          arquivofullpath=path,
                          ativo=CONST_ATIVO,
                          criacao=datetime.today(),
                          alteracao=datetime.today(),
                          codigostatusexportacaoes='esperando',
                          arquivo=filename)

    old_anexo = busca_anexo(interacao, filename, target)
    if old_anexo is not None:
        anexo.codigo = old_anexo.codigo

    anexo.save(using=target)
    return anexo
Exemple #12
0
def age_cal():
    name_entry.get()
    year_entry.get()
    month_entry.get()
    date_entry.get()
    cal = datetime.today() - (int(year_entry))
    print(cal)
Exemple #13
0
def US36():
    query = "SELECT NAME,ALIVE,DEATH FROM INDIVIDUAL"

    result = conn.execute(query)
    rows = result.fetchall()

    date_format = "%d %b %Y"
    today = datetime.today().date()

    recent_deaths = []

    for row in rows:
        if row[1] == "False":  # If the person is dead..

            death_date = datetime.strptime(row[2], date_format).date()
            difference = today - death_date

            if difference.days <= 30:
                recent_deaths.append(row[0].replace("/", ""))  # print Name

    if len(recent_deaths) > 0:
        for person in recent_deaths:
            print("ERROR: US36: " + person + " died in the last 30 days")

    def deadRecently(name):

        if name in recent_deaths:
            return True

        return False
Exemple #14
0
def US07():
    query = "SELECT NAME,ALIVE,AGE,BIRTHDAY,DEATH FROM INDIVIDUAL"

    error_tag = "ERROR: US07: "
    result = conn.execute(query)
    rows = result.fetchall()

    date_format = "%d %b %Y"
    today = datetime.today().date()

    for row in rows:
        name = row[0].replace("/", "")

        if row[1] == "False":
            age = row[2]

            if (age > 150):
                print(error_tag + name +
                      " who is dead does not have valid age")

        elif row[1] == "True":
            birthdateText = row[3]

            birthdate = datetime.strptime(birthdateText, date_format).date()
            difference = today - birthdate

            years = difference.days / 365

            if years >= 150:
                print(
                    error_tag + name +
                    " who is alive has birthdate less than 150 years from now")
Exemple #15
0
	def Save(self):
		""" Save log to disk. """
		self.recordno += 1
		now = datetime.today()
		#path = "{}/log".format(sys.path[0])
		if not os.path.exists(self.log_path):
			print("File not saved. Invalid directory " + self.log_path)
			return
			
		fname = os.path.join(self.log_path, "rec_{}.csv".format(now.strftime("%Y%m%dT%H%M%S")))
		print("Save %d samples in file %s" % (self.length, fname))

		with open(fname, mode='wt', encoding='utf-8') as f:
			f.write(Parameter.csvHeader());
			for i in self.params:
				f.write(self.params[i].to_csv())
				f.write("\n")

			f.write("\n")
			
			f.write(Sample.csvHeader());
			for sample in self.samples[0:self.length]:
				S = Sample(sample)
				f.write(S.to_csv())
				f.write("\n")

		# np.savez(fname, samples=self.samples[0:self.length], parameters=self.params)
		return fname
Exemple #16
0
def main(days_back: int, mean_commits: int, author_email: str, author_name: str, repo_name: str):
    today = datetime.today()
    all_times = get_all_times(first_day=today, days_back=days_back, mean_commits=mean_commits)
    repo_name = repo_name.replace(".", "")
    create_repo(author_email=author_email, author_name=author_name, repo_name=repo_name)
    add_commits(author_email=author_email, author_name=author_name, repo_name=repo_name, all_times=all_times)
    return []
Exemple #17
0
def time_extract(text):
    time_res = []
    word = ''
    key_date = {'今天': 0, '明天': 1, '后天': 2}
    for k, v in psg.cut(text):
        # 从词性标注的结果中进行时间抽取
        if k in key_date:
            if word != '':  # 如果当前已经获得了一个日期时间段,如'2018年'
                time_res.append(word)  # 那就先保存下来,避免被其他时间段覆盖
            # 将'今明后'这些与时间相关的词转换成日期
            # timedelta可以与datetime直接运算
            word = (datetime.today()+timedelta(
                days=key_date.get(k, 0))).strftime('%Y年%m月%d日')
        elif word != '':
            if v in ['m', 't']:  # 因为在词性标注中m表示数词,t表示时间词
                word += k
            else:  # 遇到时间单位的话先保存已获得的日期时间段,再清空word的值
                time_res.append(word)
                word = ''
        elif v in ['m', 't']:
            word = k

    # 将循环结束后剩余的与时间相关的部分加入到列表中
    if word != '':
        time_res.append(word)

    result = list(filter(lambda x: x is not None,
                         [check_time_valid(w) for w in time_res]))
    final_res = [parse_datetime(w) for w in result]
    return [x for x in final_res if x is not None]
def send_form(request):
    if request.method == 'POST':
        uri = request.POST['url']
        if ('http' in uri):
            pass
        else:
            uri = "http://" + uri

        if check_url(uri) is True:
            date_today = datetime.today()

            date_adds = date_today - timedelta(days=1)

            short_url = str(uri).replace("http://", "").replace("https://", "")
            short = short_url.split("/")
            dates = [date_today, date_adds]
            Results.objects.exclude(date_add__in=dates).delete()
            Results.objects.filter(base_url=short[0]).delete()

            if request.POST['site'] is "1":
                crawl(uri, short[0])

            else:
                crawl_one_pages(uri, short[0])

            start(uri, short[0])
            transfer_url(uri, short[0])
            return HttpResponseRedirect('/result/')
        else:
            form = PostForm()
            return render(request, 'form.html', {'form': form})
    else:
        form = PostForm()
        return render(request, 'form.html', {'form': form})
Exemple #19
0
def displayHistory(name, goalType):
    today = datetime.today()
    todayDT = datetime(today.year, today.month, today.day)

    history = []
    d_file = open('file/savinghistory.txt', 'r')

    for dlist in d_file:
        list = dlist.split(',')
        saveDate = list[7]
        saveDateStr = saveDate.split('-')
        dd = int(saveDateStr[0])
        mm = int(saveDateStr[1])
        yy = int(saveDateStr[2])
        date = datetime(yy, mm, dd)
        #print(mm)
        print('^^^^^^^^^^^')
        print(list[4])
        print(list[0])
        print(name)
        print(goalType)
        print(date)
        print(todayDT)
        print('^^^^^^^^^^^^^')
        if list[0] == name and list[4] == goalType and date <= todayDT:
            print('@@@@@@@@@@')
            print(list[4])
            print('@@@@@@@@@@')
            h = SavingHistory(list[0], list[1], list[2], list[3], list[4],
                              list[5], list[6], list[7])
            history.append(h)
    return history
Exemple #20
0
def get_current_season(league):
    """Return the current season based on current year or last year if season still unfinished"""
    this_year = datetime.today().year
    if is_season_finished(league, this_year - 1):
        return this_year
    else:
        return this_year - 1
Exemple #21
0
def cr_db2(path, name, last_name, passwd):

    datecr_tuple = datetime.timetuple(datetime.today())
    datecr = strftime('%d.%m.%Y_%X',
                      datecr_tuple)  #получаю дату в нужном форматке

    passwd_sha256 = sha256(bytes(
        passwd, encoding='utf-8')).hexdigest()  # шифрую пароль
    conn = sqlite3.connect(path)
    cursor = conn.cursor()

    id = 0
    try:
        id = (cursor.execute("SELECT max(id) FROM Users").fetchall()[0])[0] + 1
    except:
        id = 1

    try:
        cursor.execute(
            "CREATE TABLE Users(id integer, first_name text, last_name text,datecr text, passw text)"
        )
        cursor.execute(
            """INSERT INTO Users VALUES('{}','{}','{}','{}','{}')""".format(
                id, name, last_name, datecr, passwd_sha256))
    except sqlite3.OperationalError:
        cursor.execute(
            """INSERT INTO Users VALUES('{}','{}','{}','{}','{}')""".format(
                id, name, last_name, datecr, passwd_sha256))

    conn.commit()
    conn.close()
Exemple #22
0
 def logger_inf(msg: str):
     """
     write INFO message into log file (append) with timestamp point
     :param msg: - message
     """
     timestamp = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
     logging.info(timestamp + '\t' + msg)
Exemple #23
0
def db_user_add(user):
    name, u_id, u_ip, is_active = user
    a = Users(name, u_id, u_ip, is_active)
    b = UsersLog(u_id, datetime.today().isoformat(), '')
    session.add(a)
    session.add(b)
    session.commit()
Exemple #24
0
 def form_valid(self, form):
     form.instance.personal = PersonalColegio.objects.get(
         pagos__proveedor__user=self.request.user)
     form.instance.caja_chica = CajaChica.objects.get(
         colegio__id_colegio=self.request.session.get('colegio'))
     form.instance.fecha = datetime.today()
     return super(RegistrarPagoCreateView, self).form_valid(form)
class Table(Base):
    __tablename__ = 'task'
    id = Column(Integer, primary_key=True)
    task = Column(String)
    deadline = Column(Date, default=datetime.today())

    def __repr__(self):
        return "%s|%s|%s\n" % (self.id, self.task, self.deadline)
Exemple #26
0
def main():
    new_student = Student("Joann", "Fishstick Studies", 2022)
    print(new_student.name)
    print(new_student.gradyear)
    yearstillgrad = new_student.timetograd(
        datetime.today().year)  # accessing a function associated w/ class
    print("This student has {} more years till graduation.".format(
        yearstillgrad))
Exemple #27
0
 def logger_err(msg: str, ex: Exception):
     """
     write ERROR message into log file (append) with timestamp point
     :param msg: - message
     :param ex: - exception message
     """
     timestamp = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
     logging.error(timestamp + '\t' + msg + '\t' + str(ex))
Exemple #28
0
 def get_info(*args, **kwargs):
     date = datetime.today().replace(microsecond=0)
     new_function = function(*args, **kwargs)
     information = f'Дата и время {date}, функция {decorator_logger.__name__}, аргументы: {args}, {kwargs}'
     with open('logger.json', 'w', encoding='utf-8') as f:  # запись в файл
         json.dump(information, f, ensure_ascii=False, indent=2)
     print(f'Данные записаны в файл', 'logger.json')
     return new_function
class user(db.Model):
    id = Column(Integer, autoincrement=True, primary_key=True)
    name = Column(Text, nullable=True)
    username = Column(Text, nullable=False)
    email = Column(Text, nullable=False)
    password = Column(Text, nullable=False)
    created = Column(Date, default=datetime.today())
    receipts = relationship("Receipt", backref="user")
Exemple #30
0
def store_answered(answered_q):
    """Writes a list of tuples (question, answer) to a folder ./Storage/*YEAR*/*MONTH*/*DAY*.txt"""
    today = datetime.today()
    folder = "Storage" + "/" + str(today.year) + "/" + str(today.month)
    os.makedirs(folder, exist_ok=True)
    filename = folder + "/" + str(today.day) + ".txt"
    with open(filename, "a", encoding="utf-8") as outfile:
        for question, answer in answered_q:
            outfile.write(question + '\n')
            outfile.write(answer + '\n\n')
Exemple #31
0
    def run_document_application(self, private):
        with open(
                Path(__file__).parent.joinpath('resources', 'document.xlsx'),
                "rb") as file:
            app = DocumentApplication(path=self.tm1py_app_folder,
                                      name=self.document_name,
                                      content=file.read())
            self.tm1.applications.create(application=app, private=private)

        app_retrieved = self.tm1.applications.get(app.path,
                                                  app.application_type,
                                                  app.name,
                                                  private=private)
        self.assertEqual(app_retrieved.last_updated[:10],
                         datetime.today().strftime('%Y-%m-%d'))
        self.assertIsNotNone(app_retrieved.file_id)
        self.assertIsNotNone(app_retrieved.file_name)

        self.assertEqual(app, app_retrieved)
        exists = self.tm1.applications.exists(
            app.path,
            name=app.name,
            application_type=ApplicationTypes.DOCUMENT,
            private=private)
        self.assertTrue(exists)

        self.tm1.applications.rename(
            app.path,
            application_type=ApplicationTypes.DOCUMENT,
            application_name=app.name,
            new_application_name=app.name + self.rename_suffix,
            private=private)
        exists = self.tm1.applications.exists(
            app.path,
            name=app.name,
            application_type=ApplicationTypes.DOCUMENT,
            private=private)
        self.assertFalse(exists)
        exists = self.tm1.applications.exists(
            app.path,
            name=app.name + self.rename_suffix,
            application_type=ApplicationTypes.DOCUMENT,
            private=private)
        self.assertTrue(exists)

        self.tm1.applications.delete(app.path,
                                     app.application_type,
                                     app.name + self.rename_suffix,
                                     private=private)
        exists = self.tm1.applications.exists(
            app.path,
            name=app.name + self.rename_suffix,
            application_type=ApplicationTypes.DOCUMENT,
            private=private)
        self.assertFalse(exists)
Exemple #32
0
def Buy(request):
    if request.user.is_authenticated():
        oruser = OrdinaryUser.objects.get(user=request.user)
        bill = oruser.bill_set.filter(pay=False)[0];
        bill.pay = True;
        bill.date = datetime.today()
        bill.save()
        for tr in bill.transaction_set.all():
            tr.pay=True;
            tr.save();
        return render(request, "buyDone.html")
    else:
        return redirect("/index/login/" + request.path)
Exemple #33
0
def get_semana() -> str:
    '''
    Devuelve el dia de la semana en el que estamos
    :rtype : basestring
    :return: String
    '''
    dias = ['Lunes',
            'Martes',
            'Miercoles',
            'Jueves',
            'Viernes',
            'Sabado',
            'Domingo']
    return dias[datetime.today().weekday()]
def stock_random_walk(starting_price, mu, sigma, steps, name):
    '''
    Random process for stock prices.

    Geometric Brownian Motion.

    Options Futures and Other Derivatives 5th edition. John Hull.
    Pages:222-228

    :param starting_price: the stock price at the beginning of simulation
    :param mu: Expected annual return
    :param sigma: Annualized volatility
    :param steps: Forecasting horizon

    :return Pandas dataframe of simulated stock prices with datetimeindex
            starting today
    '''
    daily_sigma = sigma / np.sqrt(254)
    daily_mu = ((1 + mu) ** (1 / 254) - 1)

    prices = []
    for each_step in range(steps):
        if each_step == 0:
            price = starting_price + ((daily_mu * starting_price) +
                                      (daily_sigma * starting_price
                                       * np.random.randn()))
        else:
            price = prices[-1] + ((daily_mu * prices[-1]) +
                                  (daily_sigma * starting_price
                                   * np.random.randn()))
        prices.append(price)

    index = pd.bdate_range(
        datetime.today().strftime("%Y-%m-%d"), periods=steps, tz='UTC')

    ans = pd.DataFrame(data=prices, index=index, columns=[name])
    ans.index.names = ['Date']

    return ans
Exemple #35
0
from _datetime import datetime
from _datetime import timedelta
today = datetime.today()
print(today)
today = today - timedelta(hours=24)
print(datetime.today() > today)
print( (datetime.today() - today).total_seconds())
print(datetime.today() - today)

import datetime
from datetime import timedelta
# in_str = '2016-07-07'
# out_str = '2016-07-08'
# in_array = in_str.split('-')
# out_array = out_str.split('-')
# checkin_time = datetime.datetime(int(in_array[0]),int(in_array[1]),int(in_array[2])).date()
# checkout_time = datetime.datetime(int(out_array[0]),int(out_array[1]),int(out_array[2])).date()
# interval =  (checkout_time-checkin_time).days
# aDay = timedelta(days=1)
#
# for i in range(1,interval+1):
#     checkin_time += aDay
#     print(checkin_time.day)


# str =datetime.datetime.now().strftime('%Y%m%d%H')[2:]
# print(str)
# import django.utils.timezone

# from django.utils.dates import WEEKDAYS
# now = datetime.now()
Exemple #36
0
def get_fecha():
    fecha = dia_semana() + ', '
    fecha += datetime.today().date().__str__() + ' '
    fecha += get_hora()
    return fecha
Exemple #37
0
def init_data():
    """
    Script to fake fixtures for first test
    """

    # CUSTOMER PART

    user = User.objects.create_user(
        first_name="David",
        last_name="Dahan",
        address="13 rue de Montyon, 75009 PARIS",
        phone_number="06 62 10 25 08",
        email="*****@*****.**",
    )

    customer = Customer.objects.create(
        user=user
    )

    # FIELDS (can be use in 1 -> N letter types)

    field1 = Field.objects.create(name="Date d'envoi", default_value=datetime.today(), field_type=Field.DATE)
    field2 = Field.objects.create(name="Numéro client", default_value="123456789", field_type=Field.SHORT_TEXT)
    field3 = Field.objects.create(name="Services à résilier", field_type=Field.SIMPLE_CHOICE,
        choices="le service TV;le service Internet;l'ensemble des services")
    field4 = Field.objects.create(name="Date de résiliation", field_type=Field.DATE)
    field5 = Field.objects.create(name="Ville", field_type=Field.SHORT_TEXT)

    field6 = Field.objects.create(name="N° de contrat", default_value="123456789", field_type=Field.SHORT_TEXT)
    field7 = Field.objects.create(name="Logement concerné par la résiliation", field_type=Field.SHORT_TEXT)
    field8 = Field.objects.create(name="Motif de résiliation", field_type=Field.SIMPLE_CHOICE,
        choices="changement de domicile;autre")  # To be updated

    # LETTER TYPE 1

    organization_1 = Organization.objects.create(
        name="Numéricable",
        website="http://numericable.fr",
    )

    letter_type_1 = LetterType.objects.create(
        html_template="resiliation_numericable.html",
        description="Résiliation abonnement Numéricable",
        purpose=LetterType.RESILIATION,
        organization=organization_1,
        url="http://offres.numericable.fr/",
        uploader=None,
        default_to_address="NUMERICABLE\nService Clients\nTSA 61000\n92894 Nanterre cedex 9",
    )
    letter_type_1.fields.add(field1, field2, field3, field4, field5)

    # LETTER TYPE 2 # Incomplete

    organization_2 = Organization.objects.create(
        name="Amaguiz",
        website="https://www.amaguiz.com"
    )

    letter_type_2 = LetterType.objects.create(
        html_template="resiliation_amaguiz.html",
        description="Résiliation abonnement Amaguiz",
        purpose=LetterType.RESILIATION,
        organization=organization_2,
        url="https://www.amaguiz.com/resilier-assurance",
        uploader=None,
        default_to_address="Amaguiz.com\nService Client\nTSA 47717\n35577 Cesson Sevigne CEDEX",
    )
    letter_type_2.fields.add(field1, field6, field4, field7, field8)



    # LETTER CONTENT

    letter = Letter.objects.create(
        letter_type=letter_type_1,
        creator=customer
    )

    # WARN: how to translate data type to str? (here is an exemple : date to string)
    FieldValue.objects.create(field=field1, letter=letter, value="20 septembre 2015")
    FieldValue.objects.create(field=field2, letter=letter, value="91793889")
    FieldValue.objects.create(field=field3, letter=letter, value="l'ensemble des services")
    FieldValue.objects.create(field=field4, letter=letter, value="14 octobre 2015")