text
stringlengths
8
6.05M
from flask import g, abort from functools import wraps __all__ = ['AdminPermissionException', 'check_admin', 'check_moderator', 'check_reviewer', 'level_compare', 'is_level', 'check_level'] LEVELS = ['user', 'reviewer', 'moderator', 'admin'] class AdminPermissionException(Exception): pass def leve...
# Moderate dtObs and non-0 Q. # Named 'm30' in Datum. from common import * from mods.Lorenz63.sak12 import * t.dkObs = 15 f['noise'] = 2 X0.C = CovMat(0.5*ones(m)) other = {'name': os.path.relpath(__file__,'mods/')} HMM = HiddenMarkovModel(f,h,t,X0,**other) #################### # Suggested tuning ###############...
import argparse import json import os from random import choice command_file = "command.txt" place_ship_file = "place.txt" game_state_file = "state.json" output_path = '.' map_size = 0 data_file = "data.txt" stack_file = "stack.txt" def main(player_key): #create initial external file global map_size # Re...
import argparse import subprocess import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim from time import time from unet2d import UNet from unet3d import UNet3D parser = argparse.ArgumentParser(description='UNet3D benchmark') parser.add_argument('--no-cuda', action='store_t...
import os import pwd import grp #常量参数配置 #评判机基础工作空间 JUDGER_WORKSPACE_BASE = "/judger/run" # 日志基础路径 LOG_BASE = "/log" # 编译器日志路径 COMPILER_LOG_PATH = os.path.join(LOG_BASE, "compile.log") #评判机运行日志路径 JUDGER_RUN_LOG_PATH = os.path.join(LOG_BASE, "judger.log") #服务器日志路径 SERVER_LOG_PATH = os.path.join(LOG_BASE, "judge_se...
#!/usr/bin/python import numpy as np import math from roboclaw import * speed = 0 M1Forward(128,0) M2Forward(128,0) M2Forward(129,0) M1Forward(128,0) M2Forward(128,0) M2Forward(129,0) M1Forward(128,0) M2Forward(128,0) M2Forward(129,0) M1Forward(128,0) M2Forward(128,0) M2Forward(129,0)
import pytest from bromine.utils.geometry import RectSize def test_adding_two_rect_sizes(): assert RectSize(1, 2) + RectSize(3, 4) == RectSize(4, 6) def test_subtracting_two_rect_sizes(): assert RectSize(1, 2) - RectSize(1, 4) == RectSize(0, -2) class TestRectSizeDecorator(): def test_undecorated_va...
import uuid import boto3 import botocore from io import BytesIO from datetime import datetime, timedelta import os BUCKETNAME = 'my-userdata' bucket = boto3.resource('s3').Bucket(BUCKETNAME) client = boto3.client('s3') class NoFileException(Exception): pass class WrongTypeException(Exception): pass class Fi...
print("hello dhana")
import socket import hashlib sk = socket.socket() sk.connect(('127.0.0.1',43)) yanzheng = sk.recv(1024) sha = hashlib.sha1(b'043') sha.update(yanzheng) ret = sha.hexdigest().encode('utf-8') sk.send(ret) msg = sk.recv(1024) print(msg)
from random import randint computador = randint(0, 10) print(7*'=', 'Adivinhação', 7*'=') print('Sou seu computador e pensei em um número...\n Tente advinhar') acertou = False while not acertou: numeroJogador = int(input('É o número: ')) if numeroJogador == computador: acertou = True elif numeroJoga...
import nmap while True: nmScan = nmap.PortScanner() host = input("host(ip/url :)") port = input("port:") output = nmScan.scan(host,port) print(output)
# -*- coding: utf-8 -*- import os import pytest from scrapy.http import TextResponse from coral.spiders.github import parse_release_link, parse_release_links @pytest.fixture def landing_page(page_path): with open(os.path.join(page_path, 'landing_page.html'), 'r') as f: return f.read() @pytest.fixture ...
#!/usr/bin/python import pygame from glm import vec3, ivec2 import random import math from game.entities.message import Message from game.entities.weapons import WEAPONS from game.base.entity import Entity from game.constants import * class Powerup(Message): def __init__(self, app, scene, letter, **kwargs): ...
import argparse import select import socket as socketlib from gamelib.utils import patch_default_subcommand from .game import SnakeGame def runclient(args): try: sock = socketlib.socket(socketlib.AF_INET, socketlib.SOCK_STREAM) host = socketlib.gethostname() sock.connect((host, PORT)) ...
#!/usr/bin/env python3.6 # Copyright (c) 2019 Trail of Bits, Inc. # # 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 app...
# 一开始看标签 单调栈,但是发现由于攻击力可能相同,所以不是很好处理 # 故还是得按照下面的方法排序才行 # 攻击力降序 # 防御力必须升序,因为同一攻击力下不可能出现弱角色 class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key=lambda x : (-x[0],x[1])) res, maxv = 0, -1 for item in properties: if maxv > item[1...
pytest_plugins = [ 'fixtures.fixture_user', 'fixtures.fixture_data', ]
import getpass import io import os from django.contrib.auth import get_user_model from django.core.files import File from django.core.files.base import ContentFile from django.shortcuts import get_object_or_404, redirect, render from django.views import generic from django.urls import reverse from urllib.parse import ...
# -*- coding: utf-8 -*- """ pyxdevkit.event ~~~~~~~~~~~~~ module that implements the event object that is used in xdevkit """ from xbox_thread import XboxThread class EventInfo(object): def __init__(self, properties, ip_addr): """ Basically the event just holds information that we can use i...
n = int(input()) arr = [n] if n == 1: print(1) else: while n > 1: if n % 2 == 0: n = n // 2 else: n = 3*n + 1 arr.append(n) print(*arr,sep = " ")
''' 编写注释的主要目的是阐述代码要做什么,以及是如何做的。在开发项目期间,你对各个部分如何协同工作了如指掌,但过段时间后,有些细节你可能不记得了。当然,你总是 可以通过研究代码来确定各个部分的工作原理,但通过编写注释,以清晰的自然语言对解决方案进行概述,可节省很多时间。 要成为专业程序员或与其他程序员合作,就必须编写有意义的注释。当前,大多数软件都是合作编写的,编写者可能是同一家公司的多名员工,也可能是众多致力于同一个开源 项目的人员。训练有素的程序员都希望代码中包含注释,因此你最好从现在开始就在程序中添加描述性注释。作为新手,最值得养成的习惯之一是,在代码中编写清晰、简洁的 注释。 如果不确定是否要编写注释,就问问自己,找到合...
import datetime import pytest from prereise.gather.winddata.rap.noaa_api import NoaaApi @pytest.fixture def noaa(): box = {"north": 49.8203, "south": 25.3307, "west": -122.855, "east": -96.2967} return NoaaApi(box) start_date = "2018-03-05" end_date = "2018-03-06" start = datetime.datetime.strptime(start_...
import patch import validata_core import requests import yaml import functools from urllib.parse import urlencode from collections import defaultdict import csv import datetime import sys import json import os import textwrap CSV_PATH = "data/data.csv" COMMENT_SUBJECT = "Conformité au schéma" USER_SLUG = "validation...
__author__ = 'Greg Ziegan' from rest_framework import serializers from rest_framework import pagination from .models import User, Location class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'phone', 'first_name', 'age', 'profile_picture', 'curre...
import asyncio import time n = 0 async def monitor(): global n while True: await asyncio.sleep(1) print(f"{n} reqs/sec") n = 0 async def client(address): global n reader, writer = await asyncio.open_connection(*address) while True: writer.write(b'10000') aw...
def solution(n): return round(n * 2) / 2.0
#include <Adafruit_NeoPixel.h> from machine import Pin, SPI, ADC from neopixel import NeoPixel from time import sleep import urandom import util import ustruct import utime import ntptime as np leds = 8 width = 15 pixel = NeoPixel(Pin(14, Pin.OUT), leds) #D5 dimFactor = 4 num = "32" color = urandom.getrandbits(8) ...
# -*- coding: utf-8 -*- # @Time : 2018/12/24 14:16 # @Author : Monica # @Email : 498194410@qq.com # @File : Common_Datas.py # 全局 - 系统访问地址 - 登录链接 web_login_url = "https://www-beta.mycloudhawk.com/login"
""" 6. Faça um Programa que peça o raio de um círculo, calcule e mostre sua área. """ from math import pi raio_circulo = float(input("Digite o raio do círculo: ")) area_circulo = pi * (raio_circulo ** 2) print(f"A área do círculo é: {area_circulo:.2f} m2")
from django.contrib import admin from .models import Event # Register your models here. class EventAdmin(admin.ModelAdmin): list_display = ('event_name', 'is_published', 'event_start', 'event_end', 'event_country', 'event_city', 'event_state', 'get_partners') list_display_links = ('event_name',) search_fields = ('...
import pandas as pd import numpy as np from tensorflow import keras from matplotlib import pyplot as plt from sklearn.preprocessing import MinMaxScaler, QuantileTransformer # Cols, not stored in file because its easier for date parsing. timestamp,Ttl Volume,Avg Volume,Ttl Through, # Ttl Left Turn,Ttl Right Turn,Ttl Wr...
from _typeshed import Incomplete def random_reference( G, niter: int = 1, connectivity: bool = True, seed: Incomplete | None = None ): ... def lattice_reference( G, niter: int = 5, D: Incomplete | None = None, connectivity: bool = True, seed: Incomplete | None = None, ): ... def sigma(G, niter:...
import datetime print("Introduction to CI") now=datetime.datetime.now() print("Date& Time: ") print (now.strftime("%Y/%m/%d - %H:%M:%S"))
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
import numpy as np MAX = 26 def compare(arr1, arr2): z = np.subtract(arr1,arr2) # z = list(z) if z.count(0) != 26: return False return True class Solution(object): def findAnagrams(self, s, p): M = len(p) N = len(s) if N<M: return countP...
#!/usr/bin/python def divide(n): curNum = 10 history = [10] while curNum > 0: temp = curNum // n curNum -= n * temp curNum *= 10 if curNum in history: return len(history) history.append(curNum) return 0 index = 0 maxNum = 0 for i in range(1, 1000):...
import json from django.core import serializers from django.http import HttpResponse from django.http import JsonResponse from django.shortcuts import render from django.urls import reverse_lazy as r from django.views.generic import ListView, DetailView from django.views.generic import UpdateView, DeleteView from .mixi...
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # %matplotlib inline train = pd.read_csv("../input/train.csv", index_col=None) # train.head() test = pd.read_csv("../input/test.csv", index_col=None) # test.head() target = train.TARGET print (target.describe()) plt.hist(t...
''' 本程序的目的是定义 ——图像的布局 ——并且指定非数据层面的信息 1. 非数据层面的信息指的是线型、颜色等 2. 整个ax的信息需在外部定义 ''' import matplotlib.pyplot as plt import numpy as np import my_ax class Fig1: color_list = ['#FF0000', '#FF7D00', '#FFFF00', '#00FF00', '#00FFFF', ...
def palindrome(string): dict = {} string = string.lower() for char in string: if char == " ": pass elif char not in dict: dict[char] = 1 else: dict[char] += 1 values = dict.values() middle = False for value in values: ...
int1 = 1 float2 = 1.0 float3 = 1.1 int4 = -1 print(int1,type(int1)) print(float2,type(float2)) print(float3,type(float3)) print(int4,type(int4)) print("0.4+0.6=",0.4 + 0.6) print("0.4+0.55=",0.4 + 0.55);'浮点数计算不精确'
import re from random import uniform import amath.Computation.relationship as _gcd import amath.Computation.trig as _trig import amath.constants as const from amath.Computation.Basic import sqrt from amath.Computation.num_properties import factors from amath.Computation.rounding import round from amath.algebra.Functio...
import numpy as np from scipy import linalg from scipy.integrate import dblquad #For Olivier and qcm #Copyright Charles-David Hebert #MIT Licencse, use it as you see fit, but please give retributions to the author. class ModelNambu: """ """ def __init__(self, t: float, tp: float, tpp:float, mu: float, z_...
from django.contrib.auth.hashers import check_password # from django.contrib.auth.models import User from django.contrib.auth import get_user_model from .models import Student, Faculty User = get_user_model() class StudentBackend: def authenticate(self, request, username=None, password=None): if "-" not...
p1 = int(input('Primeiro termo: ')) r = int(input('Razão da PA: ')) cont = 1 total = 0 c = 10 while c != 0: total += c while cont <= total: p1 += r cont += 1 print('{}...'.format(p1), end='') print('PAUSA') c = int(input('Quer adicionar quantos mais termos? '))
from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from sqlalchemy import create_engine, or_ from datetime import datetime from .app_config import SQLALCHEMY_DATABASE_URI from . import create_app app = create_app() db = SQLAlchemy(app) engine = create_engine(SQLALCHEMY_DATABASE_URI, con...
class Solution(object): """ https://leetcode.com/problems/rotate-list/ find the tail. connect head with tail. find the new tail of new list. Set its next to None. Return its previous element. """ def rotateRight(self, head, k): if head is None: return None length = 0 ...
""" Priority Queue in Python 1. Use heapq module The heapq implements a min-heap sort algorithm suitable for use with Python's lists. 2. Use queue.PriorityQueue Note: The PriorityQueue uses the same heapq implementation internally """ # Use heapq import heapq customers = [] heapq.heappush(customers, (2, "Harr...
import numpy as np class IncorrectArraySize(): array = list(arr.shape) if array[0] != array[1]: raise ValueError('Input should be a square matrix') arr = np.array([[1,2,3,7], [4,5,6,8], [5,8,9,7], [4,3,5,2]]) try: hold = [] for ...
from nipype.pipeline.engine import Node, Workflow import nipype.interfaces.fsl as fsl from nipype.algorithms.misc import TSNR import nipype.interfaces.utility as util import nipype.interfaces.freesurfer as fs import nipype.interfaces.afni as afni import nipype.algorithms.rapidart as ra from compcor import extract_noise...
def removevow(string1): newstring = "" vow_list = ['a','e','i','o','u'] for letters in string1: if letters.lower() not in vow_list: newstring = newstring + letters return newstring print (removevow("Vivek"))
import requests as Re import execjs as jsexe import re import time from smtp import send_email from html_escape_sequence import escape2normal user="" pd=""#你的账号密码 rsa_key="" lt_str="" execution="" vatify_code="" s=Re.Session() login_flag=0 class_list_info=[] pwd="/root/lazy_student_assist/" records_file=pwd+"inform_rec...
from django.contrib import admin # Register your models here. from .models import Author, BlogPost admin.site.register(Author) admin.site.register(BlogPost)
class Solution: def maxProduct(self, nums: List[int]) -> int: n = len(nums) dp = [0]*n dp[0] = nums[0] dpn = [0]*n dpn[0] = nums[0] for i in range(1,n): if nums[i] > 0: dp[i] = max(nums[i],nums[i]*dp[i-1]) dpn[i] = ...
# Deylik bizga bitta list berilgan va bu list elemnetlarining ichidan eng kattasini topish talab qilinsa numbers=[3,1,5,2,6,3,10,32,5,21] max=numbers[0] min=numbers[0] for number in numbers: if number<min: min=number print(f"Min number={min}") for number in numbers: if number>max: max=number pr...
import math ## # A class to represent a vector in 3D space, with various operations that can be applied to it ## class Vector3D: def __init__(self, x, y, z, cols=None): self.x = float(x) self.y = float(y) self.z = float(z) self.cn = None self.spec = 0 self.col = co...
__author__ = """Xuanzhe Wang""" __email__ = 'wangxuanzhealbert@gmail.com' __version__ = '0.0.1' from . import app
''' Created on 2017年1月3日 @author: admin ''' import socket s = socket.socket() host = socket.gethostname() port = 1234 s.connect((host, port)) print(s.recv(1024))
import cv2 import matplotlib.pyplot as plt import numpy as np import matplotlib.image as mpimg from scipy import signal from scipy import ndimage #reading image ##################### img = mpimg.imread('maze1.jpg') print("img=" + str(img)) print("img shape=" + str(img.shape)) plt.imshow(img, cmap='gray', vmin=0, vmax...
from unittest import TestCase """ 测试模板 """ class TestSolver(TestCase): def test_demo(self): self.fail()
import pandas as pd def clean_cov_df(df_tsv,ID): df=pd.read_csv(df_tsv, sep="\t",dtype={"Chr":"str"}) df["parent_gene"]=df["info"].str.split(";").str[0].str.split(":").str[1] df["exon_id"]=df["info"].str.split(";").str[1].str.split("=").str[1] cov_dict=dict(zip(df["exon_id"],df["cov"])) cov_dict["...
import sublime, sublime_plugin import re # Plugin Globals NoRegion = sublime.Region(-1, -1) openTagRx = r"<\w[^>]+>" closeTagRx = r"</\w+>" tagRx = r"<[^>]+>" tagsNotAllowedInSpanRx = r"<(p|div|br)\b[^>]*>" startSentenceRx = ( r"(" "[“\"(]+" # open quote or parenthesis "(<[^>]+>)*" # possibly followed b...
import plugins import importlib class Store(object): """ """ def __init__(self): """ """ #TO-DO: this id broken in the tests, we need to fix the plugin importing for tests self.services = [] try: module_list = plugins.get_all_plugins() for m...
Not_found = {"Error": "Not Found"} Bad_request = {"Error": "Bad Request"} Not_modified = {"Error": "Not Modified"} No_Content = {"Error": "Not Content"} Not_Allowed = {"Error": "Method Not Allowed"}
from operator import mul def numbers_with_digit_inside(x, d): num_str = str(d) nums = [a for a in xrange(1, x + 1) if num_str in str(a)] return [len(nums), sum(nums), reduce(mul, nums) if nums else 0]
import matplotlib.pyplot as plt reg_val = {"000": 0, "001": 0, "010": 0, "011": 0, "100": 0, "101": 0, "110": 0} reg_list = ["000", "001", "010", "011", "100", "101", "110"] flag_val = {"V": 0, "L": 0, "G": 0, "E": 0} var_storage = {} PC = 0 mem_touched = [] cycle_touched = [] list_in = [] output = [] halted = False c...
import numpy as np from keras import backend as K import scipy import scipy.misc from skimage.measure import label, regionprops def pro_process(temp_img,input_size): img = np.asarray(temp_img).astype('float32') img = scipy.misc.imresize(img, (input_size, input_size, 3)) return img def BW_img(input, thres...
import os import json import pickle import threading from time import sleep, time def delayed(timeout): def __dec(func): def __wrapper(*args, **kwargs): sleep(timeout) return func(*args, **kwargs) return __wrapper return __dec def repeated(timeout): def __dec(func...
# Copyright 2022 Open Source Robotics Foundation, Inc. # # 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...
s=int(input()) for x in range(1,s+1): if(s%x==0): print(x,end=" ")
#!/usr/bin/env python3 # coding=utf-8 import pdb # 命令行执行调试 python -m pdb my_script.py def show_trace(): pdb.set_trace() return "show_trace done" def outer_func(): var_str = show_trace() var_str += "succ" print("var_str " + var_str) if __name__ == "__main__": outer_func()
# services/users/project/api/__init__.py
class Demo: Value = 50 def __init__(self,no1,no2): self.i= no1 self.j= no2 def fun(self): print(self.i,self.j) def gun(self): print(self.i,self.j) def main(): obj1 = Demo(11,21) obj2 = Demo(51,101) print("Fun:") obj1.fun() obj2....
from mod_base import* class Run(Command): """Run a command as another user (and/or on another channel). Usage: [channel] user command""" def run(self, win, user, data, caller=None): args = Args(data) target_win = win if len(args) < 2: win.Send("provide at least nick, command...
""" pubsub.py -- simple Publish/Subscribe implementation """ from tl_logger import TLLog log = TLLog.getLogger( 'pubsub' ) class PubSub(object): """ Simple Publish/Subscribe implementation """ def __init__(self, name='pubsub'): self.name = name self._dctSubEvents = {} self._lstAllE...
import numpy as np from chardet import detect import pandas as pd import collections import pickle import csv path='C:/users/anjali/environments/acl/data/handeset.csv' df = pd.read_csv(path) names = np.unique(df['name'].values) with open('C:/users/anjali/environments/acl/theo.pkl','rb') as f: edge_list,users_list = p...
#!/bin/env python import os, sys fileList = open('list.txt') fileInfo = [item for sublist in [map(lambda x:'%s%s' % (info[1],x), os.listdir(info[1])) for info in [line.split() for line in fileList.readlines() if (len(line) > 1 and line.split()[0] == sys.argv[1])]] for item in sublist] fileList.close() newFile = open...
def test_plate_from_zero(): # Plate geometry and laminate data a = 0.406 b = 0.254 E1 = 1.295e11 E2 = 9.37e9 nu12 = 0.38 G12 = 5.24e9 G13 = 5.24e9 G23 = 5.24e9 plyt = 1.9e-4 laminaprop = (E1, E2, nu12, G12, G13, G23) angles = [0, 45, -45, 90, 90, -45, 45, 0] # Gene...
def sieve(N): s = [0,0,1]+[1,0]*(N/2) i = 3 while i*i < N: if s[i]: for itr in xrange(i*2,N,i): s[itr] = 0 i += 2 return [i for i in range(N) if s[i]==1] from sys import argv with open(argv[1], 'r') as f: for line in f: print ','.join(str(i) for ...
''' You're given an ancient book that unfortunately has a few pages in the wrong position, fortunately your computer has a list of every page number in order from 1 to n. You're supplied with an array of numbers, and should return an array with each page number that is out of place. Incorrect page numbers will not app...
import pytest # If you want to assert that some code raises an exception you can use the raises helper: def f(): raise SystemExit(1) def test_mytest(): with pytest.raises(SystemExit): f() """ Run in "quiet" reporting mode: $ py.test -q test_sysexit.py . 1 passed in 0.12 seconds """
from django.conf.urls import url from django.conf.urls import url, include from django.urls import path from .bars_merge.views import FindSimilarEP, FindSimilarWP, CreateCheckPoint from .educational_program.views import DepartmentCreateAPIView, DepartmentListAPIView, DepartmentDetailsView, \ DepartmentDestroyView,...
import numpy as np from matplotlib import pyplot as plt ## Parameters #Load Global papas # Generate time domain channel H_G and H_r from Global_paras import * # Distance between BS and the center of user areas /m # the center of the user areas coordinate Lroom = 200 Wroom= 30 User_position = np.zeros((Num_User,2)) ...
from django.conf.urls import url from . import views urlpatterns=[ url(r'^$',views.index), url(r'^gold_here$',views.gold_here), url(r'^reset$',views.reset) ]
# -*- coding: utf-8 -*- """ 处理数据的导出 [初始化数据分片] 1 启动事务 2 创建临时表,只有主表的主键 3 记录相关表的 modify_time 4 分批导出 主表的主键, 按page_size 分好,持久化 5 放弃事务 [导出数据] 1 启动只读事务 2 创建临时表 3 关联主表与临时表 4 关联从表与临时表 5 保存数据,(标记为完成) 6 放弃事务 """ class DBSyncTaskBase(object): """ 数据库的同步,分为若干细小...
import Tkinter from Tkinter import * root = Tk() root.title('A Tk Application') Label(text='I am a label').pack(pady=15) root.mainloop()
from typing import List from torch.nn import Parameter import torch from torch import nn class AntisymmetricRNNCell(torch.jit.ScriptModule): def __init__(self, input_dim, hidden_size, eps, gamma, init_W_std=1, bias = True): super(AntisymmetricRNNCell, self).__init__() #init Vh ...
import pygame from pygame import * from pygame.locals import QUIT, KEYDOWN, MOUSEMOTION import time from random import choice, randint import numpy class Wall(object): is_blockable = True def __init__(self): pass # def generate_rectangles(player, minRec, maxRec, grid, gridx, gridy, maxwidth, maxheigh...
for word in open("dictionary.txt").read().splitlines(): print(word)
import tensorflow as tf from zipfile import ZipFile import os import pandas as pd def download_data(download_dir, filename, url, unzip=True): # download file from given url # download dir is an absolute path file_path = os.path.join(download_dir, filename) _ = tf.keras.utils.get_file( file_path, url, ) if ...
# coding: utf-8 ''' Created on 2017-5-25 @author Alex Wang ''' import logging class LogUtil: def __init__(self, log_path="info.log"): logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', ...
import smtplib from email.mime.text import MIMEText class EmailService(): def __init__(self, user, password): self._from = user self.server = smtplib.SMTP('smtp.gmail.com:587') self.server.ehlo() self.server.starttls() self.server.login(user, password) def __exit__(sel...
import os # ----------------------------------------------------------------------------- # Add the directory holding the package to the start of the module search path. # ----------------------------------------------------------------------------- os.sys.path.insert(0, '/home/ukdp/site-packages') # ----------------...
from django.http import HttpResponse from django.template import loader from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.shortcuts import render from django.shortcuts import render_to_response from django.template import RequestContext from django.http impo...
# KVM-based Discoverable Cloudlet (KD-Cloudlet) # Copyright (c) 2015 Carnegie Mellon University. # All Rights Reserved. # # THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT...
import list_updated as list_updated import manual as man import xmltools import extract_ExoPlanet as extract_ExoPlanet import translate_NASA as extract_NASA import cleanup as cleanUp import compare as cmpXml import gitPush as git import databasecmp as matchSystems import repo as repoTools import glob import os, sys imp...
__author__ = "Narwhale" class ListNode: def __init__(self,elem): self.elem = elem self.next = None class Solution(object): def __init__(self,node=None): self.__head = node def is_empty(self): return self.__head == None def append(self,item): node = ListNode(...
# Made in gamingexpx12, not china. from grovepi import * from grove_rgb_lcd import * import time # Pref dhtsensor = 7 # DI pin with PWM # display is ic2 based pinMode(dhtsensor, "input") out = "" prevt = 0 prevhum = 0 # Main time.sleep(1) while True: try: t, hum = dht(dhtsensor, 0) out = "Det er ...
#!/usr/bin/env python # encoding: utf-8 #LTB:import NEWSCRIPTNAME;reload(NEWSCRIPTNAME);NEWSCRIPTNAME.main() """ NEWSCRIPTNAME.py Created by Tim Reischmann on 2011-10-26. Copyright (c) 2011 Tim Reischmann. All rights reserved. usage: import NEWSCRIPTNAME;reload(NEWSCRIPTNAME);NEWSCRIPTNAME.main() """ import pymel...