text
stringlengths
8
6.05M
# Generated by Django 2.2 on 2020-10-04 12:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('instagram', '0002_api_error_instagram_account'), ] operations = [ migrations.AddField( model_name='instagram_accounts', ...
from . import legacy from .keras_pipeline import KerasPipeline from .utils import copytree, save_parameter_dict
# Dato un numero n, contare le stringhe lunghe n su un alfabeto ternario {'a', # 'b', 'c'} in cui #a <= #b <= #c, in tempo O(n * S(n)). # # Esempio: # n | conteggio # --|---------- # 1 | 1 ('c') # 2 | 3 ('cc', 'cb', 'bc') # 3 | 10 ('cba' e permutazioni, 'ccc', 'ccb' e combinazioni) # 4 | 24 def ternario(n)...
import classes as c x = c.Datum(-1.1, 0.08) print(x) paolo = c.Person("Paolo") paolo.display() print(paolo)
import socket IP = '10.2.4.64' # 修改为别人的 IP PORT port = 8812 address = (IP, port) cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) cli.connect(address) while True: msg=input('type your msg') msg = '马塞洛:{}'.format(msg) cli.send(msg.encode('utf8')) remsg= cli.recv(1024) print(remsg.decode('utf8...
from django.db import models from django.utils.translation import gettext_lazy as _ from users.models import User class SongGroup(models.Model): name = models.CharField(verbose_name="分组名称", max_length=50) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table="singer_song_gr...
import os import json from decouple import config, Csv from django import template from django.db.models import Count from accounts.models import User from ..models import Category, Post, BibleStudies, Devotion register = template.Library() @register.filter def human_format(num): # format long number like 1000 to 1k...
from django.conf.urls import url urlpatterns = [ url(r'registration/$', 'registration.views.registration', name='registration'), url(r'register-complete/$', 'registration.views.register_complete', name='register_complete'), ]
# chat/consumers.py import json from asgiref.sync import async_to_sync,sync_to_async from channels.generic.websocket import AsyncJsonWebsocketConsumer from chat.models import Message from django.conf import settings from .views import get_last_10_messages,get_curent_chat from channels.db import database_sync_to_async #...
#!/usr/bin/python3 """ Prints all City objects from the database hbtn_0e_14_usa """ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sys import argv from model_state import Base, State from model_city import City if __name__ == '__main__': try: engine = create_engine( ...
import random import pickle from .wiki_category import WikiCategory class WikiDataLoader: """Handle data loading and saving of articles from multiple wikipedia category. Randomly select `N` wikipedia categories among `CATEGORIES` and load articles text extract for each of them using the `WikiCategory` cla...
from django import forms from django.forms import extras from datetime import datetime class Register(forms.Form): years_to_display = range(datetime.now().year - 100, datetime.now().year + 1) first_name = forms.CharField( label = "First Name", max_length = 45, min_length = 2, ...
def bouncing_ball(initial, proportion): output = 0 while initial > 1: initial *= proportion output +=1 return output ''' You drop a ball from a given height. After each bounce, the ball returns to some fixed proportion of its previous height. If the ball bounces to height 1 or less, we co...
import argparse import pandas as pd import numpy as np import os import ntpath from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA """ Preprocessing functions """ def normalize(x, scalerType): """ Nomalize the columns of the array passed Parameters ===...
from src.cached_card_lookup import CachedCardLookup from src.mongo import EXTRACTED_CARDS, AGGREGATED_CARD_SYNERGIES, AGGREGATED_CARDS, AGGREGATED_CARD_DECK_OCCURRENCES from src.redis import CACHED_CARDS class CardLoader: def __init__(self, mongo, redis): self.mongo = mongo self.redis = redis ...
''' The partially defined functions and classes of this module will be called by a marker script. You should complete the functions and classes according to their specified interfaces. ''' import search import sokoban # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def my_t...
import openpyxl from WhatsAppUIAutomation.automation import WhatsAppUi def load_excel(r, input_message): workbook = openpyxl.load_workbook('./whatsapp_ui.xlsx') print(str(workbook) + " Workbook Opened...") sheet = workbook['whatsapp'] print(str(sheet) + " Reading...") sl_no = sheet.cell(row=r, co...
from .development import Dev from .production import Pro import pymysql pymysql.install_as_MySQLdb()
from os.path import splitext, join, basename import numpy as np from torch import from_numpy import torch class WriteTensorToDisc(object): def __init__(self, write_loc, path_annotations): self.write_loc = write_loc self.annotations = path_annotations def __call__(self, sample): ...
import sys s = "I_W1sh_I_H4d_IDA_inst4lled_But_Wh0_C4n_4ff0rd_Th4t" xor = 0xd1 result = 0xd1 print "int xor_bytes[%d] = {" % len(s) for i, c in enumerate(s): xor = result ^ ord(c) result ^= xor sys.stdout.write("0x{:02x}".format(xor) + ", ") if (i + 1) % 16 == 0: print "" print "" print "...
# simple network sniffer with raw sockets on windows. # requires administrator privileges to modify the interface. import socket # the public network interface HOST = socket.gethostbyname(socket.gethostname()) # create a raw socket and bind it to the public interface s = socket.socket(socket.AF_INET, socket...
""" Log output class Created by mahiro hoshino How to use: logger = Logger().get_logger() logger.error("error msg") logger.debug("debug msg") etc... @see https://docs.python.jp/3/howto/logging.html Log output format: time(year-month-day hour-minute-seconds,millisecond): func...
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-25 14:53 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_operation', '0009_auto_20180825_0255'), ] operations = [ migrations.A...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Point of Sale [Mimoki]', 'version': '1.0.1', 'category': 'Point Of Sale', 'author': 'TrendAV', 'maintainer': 'TrendAV', 'website': 'http://www.trendav.com', 'sequence': 21, 'sum...
""" A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing. Your goal is to find that missing element. Write a function: def solution(A) that, given a zero-indexed array A, returns the value of the mis...
from django import template register = template.Library() @register.filter def str_to_float(value): try: return float(value) except ValueError as e: return None
import pandas as pd, numpy as np oneDList = [10, 20, 30, 40] oneDTable = pd.DataFrame(oneDList) print("Default Column Name:\n", oneDTable) oneDTableIndex = pd.DataFrame({"ColName" : oneDList}) print("With Column Name:\n", oneDTableIndex) withColNameAndRow = pd.Series(oneDList, index=["r1", "r2", "r3", "r4"]) print("...
import math import random import sys lastAnswer = 0.0 memory = 0.0 print("-- tCalc V1.2 -- Programmed by Bailey Dawson --") def numGet(token):#get the number out of the string if token == "m": return memory if token =="r": return random.random() if token == "p": return math.pi if str(token).isnumeric(): ...
# coding: utf-8 import argparse import os.path import numpy as np import scipy as sp import pandas as pd import hail as hl from hail.linalg import BlockMatrix from hail.utils import new_temp_file gnomad_latest_versions = {"GRCh37": "2.1.1", "GRCh38": "3.1.2"} gnomad_pops = {"GRCh37": ["afr", "amr", "eas", "fin", "nfe"...
from drivers.driver import IDriver from selenium import webdriver class DriverChrome(IDriver): def __init__(self): self.driver =None def instanceDriver(self): self.driver = webdriver.Chrome(executable_path=r'C:\Users\pc\Desktop\django\chromedriver.exe') def freeDriver(self): self...
from discord.ext import commands from DaveBOT import checks class Admin: """Admin-only commands.""" def __init__(self, bot): self.client = bot @commands.command(hidden=True) @checks.adminonly() async def load(self, *, module: str): """Load a module.""" try: sel...
import requests from bs4 import BeautifulSoup import pandas as pd wiki = requests.get('https://en.wikipedia.org/wiki/List_of_mass_shootings_in_the_United_States') soup = BeautifulSoup(wiki.content, 'html.parser') tables = soup.find_all('table', class_='wikitable sortable') alltables=pd.DataFrame() for x in tables:...
import numpy as np from copy import deepcopy import lasagne from braindecode.veganlasagne.layers import get_all_paths from braindecode.veganlasagne.layer_util import set_to_new_input_layer def get_longest_path(final_layer): all_paths = get_all_paths(final_layer) path_lens = [len(p) for p in all_paths] i_lo...
import urllib import urllib2 import hashlib url = 'http://219.223.254.66/cgi-bin/srun_portal' val = { 'action' : 'logout' } data = urllib.urlencode(val) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() print the_page
from django.urls import path from reddituser import views urlpatterns = [ path('<str:username>/', views.user_profile_view, name='user_profile'), path('<str:username>/delete/', views.delete_profile_view, name='delete_profile'), ]
# Generated by Django 2.2.1 on 2019-05-09 06:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('portalapp', '0011_auto_20190507_1806'), ] operations = [ migrations.AddField( model_name='student', name='mentor', ...
import time import datetime def create_timestamp(): today_now = datetime.datetime.now() # __secs = today_now.second # __minutes = today_now.minute # __hour = today_now.hour # __days = today_now.day # __month = today_now.month # __year = today_now.year return today_now.timestamp() ...
#!/usr/bin/env python #coding=utf-8 import os import logging import re logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S') def config_stats(): """ config the all port of config.py in the ...
# import pytest, sys from helpers_for_tests import reset_queries, run_args_on_parser as runargs # sys.path.insert(1, './backup') # from parser import create_parser def test_no_args(): result = runargs([]) assert "No arguments were provided." in result.err def test_check_if_enter_something_other_than_config_add_u...
def evaporator(content, evap_per_day, threshold): day = 0 evap_per_day /= 100.0 threshold = content * (threshold / 100.0) while content >= threshold: content -= content * evap_per_day day += 1 return day
from src.ChessQueenWorld import ChessQueenWorld cqw = ChessQueenWorld() #cqw.solve_sample_board(0) cqw.bulk_solve(10)
import requests import re from urllib.parse import urlparse import sys import keyboard url = "https://ifunny.co/" file = open("links.txt", "a+") visited = [] iteration = 0 start_index = 0 recursive_depth = -1 def scrape(links): global iteration output = [] valid = True for link ...
{ 'targets': [{ 'target_name': 'test', 'type': 'executable', 'dependencies': [ 'testlib/testlib.gyp:proxy', 'proxy/proxy.gyp:testlib', ], }], }
from unittest import TestCase from phi.field._field_math import data_bounds from phi.field._point_cloud import distribute_points from phi.flow import * def step(particles: PointCloud, obstacles: list, dt: float, **grid_resolution): # --- Grid Operations --- velocity = prev_velocity = field.finite_fill(resamp...
bu dosyaya yazdigimiz ilk satir.
# coding=utf-8 import math import os from src.util import common def split_by_proportion(src_file_path, target_dir_path, split_file_cnt): """按照相等的概率(拟合频率)将文件 src_file 划分为 split_file_cnt 个文件, 并保存在 target_dir_path 目录下. 不保证每个文件的行数严格相等, 只保证将 1 行分配到各文件的概率相等. """ with open(src_file_path) as file: s...
# coding:utf-8 # 导入Numpy(数学运算)和Matplotlib的pyplot两个模块 # matplotlib.pyplot.plot(x, y, label="标签颜色", color="折线颜色", linestyle="折线类型", linewidth="线宽", # marker="标记点符号", markersize="标记点大小") import numpy as np import matplotlib import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签 plt...
# FOR Loops or count controlled iteration # FOR loops will run for a predetermined number of times # FOR loops can also use break and continue as covered in 02 # i is a variable, you can pass one in or create a new one. i is typically used as it relates to "index". # the range() creates a sequence of values to iterat...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2018-03-20 06:55 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_depende...
import numpy as np from scipy.integrate import odeint, solve_ivp import pandas as pd import matplotlib.pyplot as plt import datetime def derivSIR(y, t, N, beta, gamma): S, I, R = y dSdt = -beta * S * I / N dIdt = beta * S * I / N - gamma * I dRdt = gamma * I return dSdt, dIdt, dRdt def derivSIR_RK...
#edit-mode: -*- python -*- #coding:gbk #工作路径. WORKROOT('../../../') #使用硬链接copy. CopyUsingHardLink(True) #支持32位/64位平台编译 #ENABLE_MULTI_LIBS(True) #C预处理器参数. CPPFLAGS('-D_GNU_SOURCE -D__STDC_LIMIT_MACROS -DVERSION=\\\"1.0.0.0\\\"') #为32位目标编译指定额外的预处理参数 #CPPFLAGS_32('-D_XOPEN_SOURE=500') #C编译参数. CFLAGS('-std=c++11 -g -p...
import os import sys import importlib import re SPACE_NORMALIZER = re.compile(r"\s+") def tokenize_line_word(line): line = SPACE_NORMALIZER.sub(" ", line) line = line.strip() return line.split() def tokenize_line_char(line): line = SPACE_NORMALIZER.sub("", line) line = line.strip() return l...
import Tkinter as tk import threading import pyaudio import wave from array import array from os import stat import socket import time import os global x x=0 def sendLastFun(): send(x) def send(n): time.sleep(2) arr = array('B') # create binary array to hold the wave file ...
""" Необходимо использовать функции. Программа должна поддерживать следующие арифметические операции: +, -, /, *, %(получение процента от числа), **(возведение в квадрат), **х(возведение в степень числа х). Запрещено подключать дополнительные модули. Для вывода результата необходимо использовать функцию print(). """ ar...
#coding:gb2312 #分析文本 filename = 'test.txt' try: with open(filename) as f: infomation = f.read() except FileNotFoundError: msg = ("Sorry,the file "+filename+" does not exit.") print(msg) else: """ 对变量infomation(它现在是一个长长的字符串,包含断箭的全部文本) 调用方法split(),以生成一个列表,其中包含这个文章中的所有文字 """ words = infomation.split() num_wor...
# -*- coding: utf-8 -*- from flask import Flask, g, json, render_template, Response, request import psycopg2 import psycopg2.extras from Config import Config import logging import os.path from subprocess import call import tempfile from zipfile import * from urllib2 import urlopen, URLError, HTTPError app ...
from __future__ import annotations from dataclasses import dataclass from typing import List @dataclass class Node: val: int = None next: Node = None @property def last(self) -> bool: return self.next is None def __lt__(self, other: Node) -> bool: return self.val < other.val d...
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verify that a target marked as 'link_dependency==1' isn't being pulled into the 'none' target's dependency (which would otherwise lead t...
#from PyML import * #from PyML import ker import matplotlib.pyplot as plt import csv as csv import numpy as np from sklearn import svm, metrics,cross_validation from sklearn.multiclass import OneVsRestClassifier,OneVsOneClassifier from sklearn import preprocessing def read_data(file_name): if file_name =='train': c...
#coding:utf-8 from pyecharts import ThemeRiver import json def tongji(filepath): rate = [] with open(filepath,'r') as f: rows = f.readlines() for row in rows: if len(row.split(',')) == 5: rate.append(row.split(',')[3].replace('\n','')) v1=(rate.count('5')+rate.count('4.5')) v2=(rate.coun...
def adding(a,b): my_sum = a+b my_string = "{} + {} = {}".format(a,b,my_sum) print(my_string) def subtract(a,b): my_sum = a-b my_string = "{} - {} = {}".format(a,b,my_sum) print(my_string) def multiply(a,b): my_product = a*b my_string = "{} * {} = {}".format(a,b,my_product) p...
from Algorithm import GreedySearchDecoder, EncoderRNN, LuongAttnDecoderRNN from LoadFile import loadPrepareData from Evaluate import evaluateInput import argparse import os import torch import torch.nn as nn parser = argparse.ArgumentParser(description='Train Data') parser.add_argument("-c", "--checkpoint", type=int, ...
from .slam_data import SLAMData from .state import State from .cone_finder import find_nearest_cone class SLAM: def __init__(self, searchable_size): self.left_index = 0 self.right_index = 0 self.searchable_size = searchable_size def update(self, car, all_left_cones, all_right_cones): ...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import io import zipfile from pathlib import PurePath from textwrap import dedent import pytest from pants.backend.python import target_types_rules fr...
import json import rdflib as rdfl import sbol3 import tyto import labop import uml from labop.execution_engine import ExecutionEngine from labop_convert.opentrons.opentrons_specialization import OT2Specialization # Dev Note: This is a test of the initial version of the OT2 specialization. Any specs shown here can be...
# OpenWeatherMap API Key api_key = "0217370abad49447a775734efd95b987"
import support_lib as bnw import time import re # This module handles interactions with special ports, and normal trading ports def specialPort(purchaseDict): specialText = "Special Port" genericText = "Trading Commodities" xBanner = "html/body/h1" xWholePage = "html/body" # cost of ...
''' Problem 12: Write a function group(list, size) that take a list and splits into smaller lists of given size. group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4) [[1, 2, 3, 4], [5, 6, 7, 8], [9]] ''' import sys print "What are the elements you wan...
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import sensor from esphome.const import CONF_ID, UNIT_EMPTY, ICON_EMPTY from . import EmptySensorHub, CONF_HUB_ID DEPENDENCIES = ['empty_sensor_hub'] sensor_ns = cg.esphome_ns.namespace('sensor') Sensor = sensor_ns.class_('Sen...
import numpy as np import sklearn import pandas as pd from sklearn.cluster import KMeans from skimage.io import imread import pylab import math import matplotlib.pyplot as plot from skimage import img_as_float as iaf image = imread('/Users/winniethepooh/PycharmProjects/ml/data-out/_3160f0832cf89866f4cc20e07ddf1a67_par...
import sys a = 0 b = 0 max = None try: max = int(sys.argv[1]) except: print("Not an integer") sys.exit(1) for n in range(1,max): if n % 3 == 0 and n % 5 == 0: print("fizz buzz") elif n % 3 == 0: print("fizz") a += 1 elif n % 5 == 0: print("buzz") b += 1 else: print(n) print("There are %d fizze...
from re import compile, match REGEX = compile(r'((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){4}$') def ipv4_address(address): # refactored thanks to @leonoverweel on CodeWars return bool(match(REGEX, address + '.'))
from django.db import models import uuid from .constants import MessageConstants from .managers import ChatMessageManager from cryptography.fernet import Fernet def getKey(): return Fernet.generate_key().decode("utf8") class ChatInfo(models.Model): member1 = models.ForeignKey( "loginsignup.Beaver", ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'qt.ui' # # Created: Tue Apr 12 14:31:51 2016 # by: PyQt4 UI code generator 4.11.3 # # WARNING! All changes made in this file will be lost! import pickle from PyQt4 import QtCore, QtGui from PyQt4.QtGui import QLabel, QMessageBox, QPixma...
#!/usr/bin/env python3 from os import system from time import sleep x = [] while True: x.append('#' * 99999) sleep(0.1) system('sleep 9999 &')
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from ticketingsystem import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('django.contrib.auth.urls')), path ('', views.home, name = ...
from django.urls import path, re_path from .apis import * urlpatterns = [ path('unemployments/add', AddUnemploymentApi.as_view(), name='unemployment_add'), re_path(r'^unemployments/list/(?:start=(?P<start>(?:19|20)\d{2}(0[1-9]|1[012])))&(?:end=(?P<end>(?:19|20)\d{2}(0[1-9]|1[012])))$', UnemploymentListApi.as_v...
from .decode import * def calc_acc(target, output): output_argmax = output.detach().permute(1, 0, 2).argmax(dim=-1) target = target.cpu().numpy() output_argmax = output_argmax.cpu().numpy() # print(target, output, output_argmax) a = np.array([decode_target(true) == decode(pred) for true, pred in zi...
import httplib import os import signal import socket import time PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) EXECFILE = os.path.join(os.path.join(PROJECT_PATH, "src"), "wheatserver") class WheatServer(object): def __init__(self, conf_file="", *options): assert os.access(EXEC...
# Массив, который нужно было создать в предыдущей задаче, хранится в переменной mat. Превратите его в вертикальный вектор и напечатайте. import numpy as np z = mat.flatten() print(z.reshape(z.shape+(1,))) # import numpy as np # mat = mat.reshape((12,1)) # print(mat)
#B intgr=input() muldig=1 for i in intgr: muldig=muldig*int(i) print(muldig)
saludo = "Hola Mundo" edad = 20 estatura = 1.55 print(saludo, edad, estatura)
# 简单dp # 可以简化为f[i] MOD = int(1e9+7) class Solution: def countHousePlacements(self, n: int) -> int: # dp[i][0] 表示前 i 块放置房子的总情况数,0表示第i块不放,1表示第i块放 dp = [[0] * 2 for _ in range(n+1)] dp[1][0] = dp[1][1] = 1 for i in range(2, n+1): dp[i][1] = dp[i-1][0] % MOD dp...
#Cubic spline curve using Hermite interpolation #@Mkchaudhary 16 sept 2018 from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import sys def init(): glClearColor(0.0,1.0,1.0,0.0) glColor3f(1.0,0.0,0.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(-10.0,10.0,-10.0,10.0) def se...
# To get started, copy over hyperparams from another experiment. # Visit rll.berkeley.edu/gps/hyperparams.html for documentation. """ Hyperparameters for Laika Reinforcement Learning experiment. """ from __future__ import division from datetime import datetime import os.path import numpy as np from gps import __fil...
from django.apps import AppConfig class EmailMessagesConfig(AppConfig): name = 'email_messages'
import subprocess user = 'dkdexpota' password = '8x5h915XXX' cmd = "git init" subprocess.call(cmd, shell=True) cmd = 'git config --global user.name "dkdexpota"' subprocess.call(cmd, shell=True) cmd = 'git config --global user.email "artur202080202080@gmail.com"' subprocess.call(cmd, shell=True)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
name = input("Enter file:") if len(name) < 1: name = "mbox-short.txt" handle = open(name) lst = list() counts = dict() for line in handle: if line.startswith("From ") == True: line = line.split() tpart = line[5] tpart = tpart.split(":") time = tpart[0] lst.append(time) ...
import pandas as pd import pytrec_eval from collections import defaultdict import os class Utils: @staticmethod def parse_query_result(filename): results = [] with open(filename, 'r') as file: for line in file: split_line = line.strip("\n").split(" ") ...
def add_menu(): pass def default_menu(): pass def update_menu(): pass
#some manual formatting required import csv with open('levelTemp.js', 'w') as the_file: #change this for different output levels with open('level/Whale Defense Force Level - Sheet1(1).csv', 'rb') as f: reader = csv.reader(f) the_file.write('var GAME_LEVELS = [\n [\n') for row in reader:...
# test 1 # 使用json存储运行过程中产生的数据 # 使用json.dump(date,file)存储数据 import json num = ['1','2','3','4'] with open("num.json", 'w') as file: json.dump(num, file) # 使用json.load(file)加载json中的数据 with open('num.json') as file: number = json.load(file) print(number)
# Generated by Django 3.0.3 on 2020-03-01 15:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main_app', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='livre', options={'ordering': ['titr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 1 12:46:45 2019 @author: thomas """ import os, shutil import pandas as pd import numpy as np import random import zipfile import matplotlib import matplotlib.pyplot as plt from shutil import copyfile import pathlib #Script will generate randomly ...
"""Git specific support and addon.""" import argparse import os import pickle import shlex import subprocess import sys from collections import UserDict from contextlib import AbstractContextManager from functools import partial from pathspec import PathSpec from pkgcore.ebuild import cpv from pkgcore.ebuild.atom imp...
from django.test import SimpleTestCase from django.test.utils import override_settings from ..checks import settings_checks class CheckSessionCookieSecureTest(SimpleTestCase): @override_settings(USE_TZ=False) def test_use_tz_false(self): """If USE_TZ is off provide one warning.""" self.assert...
r = request.get("https://api.")
import tensorflow as tf a = tf.placeholder(tf.float32, name='a') b = tf.placeholder(tf.float32, name='b') adder_node = tf.add(a, b, name='add') sess = tf.Session() print(sess.run(adder_node, {a: 3, b: 4.5})) print(sess.run(adder_node, {a: [1, 3], b: [2, 4]})) writer = tf.summary.FileWriter('placeholder_add', sess.gra...
# Faça um Programa que peça a temperatura em graus Farenheit, # transforme e mostre a temperatura em graus Celsius. # C = (5 * (F-32) / 9). # entrada de dados farenheit = float(input('Informe a temperatura em graus Farenheit: ')) # processamento celsius = 5 * (farenheit - 32) / 9 mensagem = '{} farenheit equivalem a...