text stringlengths 8 6.05M |
|---|
from django.apps import AppConfig
class MultipleauthConfig(AppConfig):
name = 'multipleauth'
|
import contextlib
import datetime
import json
import logging
import random
import string
import pytest
from django.db import transaction
from django.utils import timezone
from oauth2_provider.models import AccessToken, Application
from share.models import NormalizedData, RawDatum
from share.models import ShareUser
... |
a=int(input())
b=input().split()
for i in range(len(b)):
print(b[i],i)
|
"""
csrf 通过服务器生成随机值,通过cookie下发到浏览器,在POST提交数据时携带此随机值到server,保证请求的合法性 。
# html页面的form加入
{ csrf_token }
"""
"""
cors - 跨域访问管理
其主要是对 HEADER,HTTP-METHOD的控制
浏览器在跨域请求时提交 OPTIONS请求到目标server,server返回是否支持 GET/POST/PUT/DELETE/FETCH等操作.
CORS还可以返回客户机http请求header中可以包含哪些字段
"""
""""
pip install djang-cors-headers
"""
MIDDLE... |
#! python3
# please install tkcalendar and babel (if needed) before using.
from datetime import datetime
try:
import tkinter as tk
from tkinter import ttk
except ImportError:
import Tkinter as tk
import ttk
from tkcalendar import Calendar, DateEntry
# convert string to date with multiple f... |
from hcj import snds
from pippi import dsp, tune
def play(ctl):
pianos = ['sawvib', 'piano', 'pianooct1', 'harp', 'saw']
pianos = ['sawvib', 'piano']
piano = snds.load('genie/%s.wav' % dsp.randchoose(pianos))
notes = [1,3,5]
chord = tune.fromdegrees([ dsp.randchoose(notes) + (dsp.randchoose([0, 1])... |
# -*- coding: utf-8 -*-
import requests
def get_money(pair, base): #курс бата к доллару, рублю
url1 = 'https://api.fixer.io/latest?base=' + base
response = requests.get(url1).json()
price = response['rates'][pair]
return str(price)
def get_btc(): #курс биткоина к доллару
url1 = 'https://yobit.net/... |
import pytest
from person import Person
class TestPerson(object):
@pytest.fixture
def person(self):
return Person('Daisuke', 99)
def test_type(self, person):
assert isinstance(person, Person)
def test_val(self, person):
assert person.age == 99
class TestPerson2(object):
@... |
# 파일 생성하기
f = open('새파일.txt','w') # 파일 객체 = open(파일이름, 파일 열기 모드)
for i in range(1, 11):
data = '%d rine.\n' %i
f.write(data)
f.close()
# 프로그램의 외부에 저장된 파일을 읽는 여러 가지 방법
# readline() 함수 이용하기
f = open('새파일.txt','r')
line = f.readline()
print('한 줄만 출력 : ')
print(line)
print()
f.close()
print('여러줄... |
num=[]
while True:
x=input("Enter a number or type done if no more:" )
if x == 'done' or len(x)<1:
break
elif x!='done':
num=num+[x]
mx=[float(i) for i in num]
mx.sort()
print (mx)
print ("max :", max(mx))
print ("min :", min(mx)) |
#!/usr/bin/python
import xml.etree.ElementTree as etree;
keybindings = [];
ns = {"openbox_config": "http://openbox.org/3.4/rc"};
root = etree.parse("/home/xavier/.config/openbox/rc.xml").getroot();
keyboard = root.find("openbox_config:keyboard", ns);
for keybind in keyboard.findall("openbox_config:keybind", ns):
... |
from django.contrib import admin
from .models import Sudoku
admin.site.register(Sudoku)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import utils
def run(string, entities):
"""Leon says good bye"""
return utils.output('end', 'good_bye', utils.translate('good_bye'))
|
L = 1
R = 1000
def check_arm(num):
s = 0
n = num
while(num):
dig = num%10
num = int(num/10)
s = s + dig**3
if n==s:
return 1
else:
return 0
num_arm = 0
for num in range(L,R):
num_arm+=check_arm(num)
print(num_arm)
|
with open("hightemp.txt") as f:
lines = f.readlines()
with open("col1.txt", "w") as f1:
with open("col2.txt", "w") as f2:
cols = len(lines[0].split("\t"))
for l in lines:
splitted = l.split("\t")
assert len(splitted) == 4
f1.write("{}\n".format(splitted[0]))
... |
import pickle
import requests
irisdata = requests.get("https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data")
text_1=irisdata.text
#print(text_1)
x = iter(text_1.split("\n"))
p=list(x)
#print(p)
#print(type(p))
#create piokel
""""file = "iris.pkl"
fileobj = open(file,'wb')
pickle.dump(p,fileobj)
... |
import math
x = 2.9
print(round(x))
print(abs(-2.9))
# Math module
print(math.ceil(2.9))
print(math.floor(2.9))
#If Statements
# is_hot = True
is_hot = False
is_cold = False
if(is_hot):
print("It's a hot day")
print("Drink plenty of water")
elif(is_cold):
print("Its a cold day")
print("Wear warm clo... |
# Labo 01 - basis variabelen ("#" = commentaar)
# print("Hello world, dag Brent") #String= tekst
# #print= methode, argumenten bevinden zich tussen ()
# #1= integer, 1.0= double
# print('Hello world, dag Brent') #''=""
# print("Hello world, \... |
# Generated by Django 3.1.7 on 2021-03-20 21:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Join',
fields=[
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2020-03-17 03:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0011_auto_20200316_1537'),
]
operations = [
migrations.AddField(
... |
# -*- coding: utf-8 -*-
import torch
from collections import OrderedDict
from functools import reduce
class PreDefinedVocab(object):
"""Defines a vocabulary object that will be used to numericalize a field.
Attributes:
stoi: A collections.defaultdict instance mapping token strings to
num... |
# -*- coding: utf-8 -*-
import turtle
import math
import random
import pygame
import tkinter
pygame.init()
from pygame.mixer import Sound
# criando a tela
turtle.setup(800,800)
wn = turtle.Screen()
wn.bgcolor('black')
wn.title('Space Invaders')
wn.bgpic('bg.gif')
#registrando as imagens (shapes)
tur... |
from enum import Enum
class ConnectionState(Enum):
CLOSED = 1
UNAUTHENTICATED = 2
BROADCAST = 3
|
from logics.dice import *
from logics.weapon import Weapon
class Barbarian(object):
name = None
strength = None
stamina = None
health_point = None
base_damage = None
def __init__(self, name):
self.name = name
self.strength = roll_d10()
self.stamina = roll_d10()
... |
'''
Day 12
You walk through the village and record the ID of each program and the IDs
with which it can communicate directly (your puzzle input).
Each program has one or more programs with which it can communicate,
and these pipes are bidirectional; if 8 says it can communicate with 11,
then 11 will say it can com... |
#!/usr/bin/env python
import caffe
import string
import numpy as np
import subprocess
import heapq
import os, sys, stat
# # the last 1000 have the largest loss weight.
# class PriorityQueue:
# def __init__(self):
# self._queue = []
# self._index = 0
# def push(self, item, priority):
# heapq.heappush(self._q... |
# -*- coding: utf-8 -*-
import pandas as pd
from keras.optimizers import SGD, Adam
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.utils.np_utils import to_categorical
#%matplotlib inline
dataset = pd.read_csv("C:\\Users\\10651\\Desktop\\train.csv")
y_train = dataset['labe... |
__version__ = "1.9"
from .ac import AC
from .trie import Trie
|
from django.urls import path
from posts import views
urlpatterns=[path( route='',
view=views.PostFeedView.as_view(),
name='feed'
),
path( route='new/',
view=views.CreatePostView.as_view(),
name='new'
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 20:00:29 2020
@author: nicolai
"""
import cv2
import numpy as np
from glob import glob
from subscripts.classes import movie_obj
import threading
import time
import pandas as pd
threading._shutdown()
"""
glob - Til at finde filer
pandas (også ... |
#Print code that returns True if 10 and 10 are equal
print (10==10) |
import numpy as np
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)-8s] [%(name)-8s] [%(levelname)-1s] [%(message)s]')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
class E... |
# EXTERNAL PACKAGES
from flask import Flask
from flask_sqlalchemy import SQLAlchemy, inspect
from sqlalchemy.ext.hybrid import hybrid_property
from flask_migrate import Migrate
import pandas as pd
# PYTHON STANDARD LIBRARY
import os
import csv
# CONFIGURE APPLICATION
app = Flask(__name__)
app.config['SQLALCHEMY_DATABA... |
"""Python ChartMogul Enrichment API Wrapper
This file implements a simple wrapper around the ChartMogul enrichment API.
"""
import requests
class ChartMogulEnrichmentClient:
"""Enrichment API Wrapper Class"""
def __init__(self, account_token=None, secret_key=None,
base_url='https://api.cha... |
import datetime
from django.db import models
from django.utils import timezone
class BaseModel(models.Model):
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Genre(BaseModel):
name = models.CharField... |
import pandas as pd
from PIL import Image
import numpy as np
from skimage import metrics
import imagehash
from .flag_util import FlagUtil
import operator
import os
class FlagIdentifier:
def __init__(self):
'''
Initializes a FlagIdentifier object that has a FlagUtil object and DataFrame of
... |
#q1
# keys = ['Ten', 'Twenty', 'Thirty']
# values = [10, 20, 30]
# l=[]
# for i in keys:
# for j in values:
# l.append((i,j))
# a={}
# a.update(l)
# print(a)
##second method
# l=[]
# i=0
# while i<len(keys):
# l.append((keys[i],values[i]))
# i+=1
# a={}
# a.update(l)
# p... |
from tkinter import *
import tkinter.filedialog
import tkinter.messagebox
import os
class Menus:
def __init__(self, master):
self.master = master
self.file_operator_obj = FileOperators()
self.text_appear_obj = TextAppearance()
main_menu = Menu(master)
master.config(menu=ma... |
from openerp import models, fields
class Product_merk(models.Model):
_name = 'product.merk'
name = fields.Char('Merk', size=50, required=True)
class Product_template(models.Model):
_name = 'product.template'
_inherit = 'product.template'
merk_id = fields.Many2one('product.merk','Merk')
... |
"""
"""
from .optimizations import \
( BasicOptimization
, ASTOptimization
, ByteCodeOptimization
, all_optimizations
, ast_optimizations
, bytecode_optimizations
, install
, uninstall
)
from .transform import \
( optimize
, get_source
)
from .hook import \
( activa... |
# 분산처리
import sys
N = int(sys.stdin.readline().rstrip())
for _ in range(N):
A,B = map(int, sys.stdin.readline().rstrip().split())
# 뭘 곱해도 무조건 결과가 똑같은 밑수는 예외처리
if A == 1:
print(1)
continue
elif A == 5:
print(5)
continue
elif A == 6:
print(6)
... |
from collections import namedtuple
from io import BytesIO
from os.path import splitext, basename
from sqlalchemy import and_
from onegov.org.models import GeneralFileCollection, GeneralFile
from onegov.translator_directory import _
from docxtpl import DocxTemplate, InlineImage
def fill_docx_with_variables(
origin... |
import inspect
import os
import re
import arg
from django.db import transaction
import djarg
import daf.contrib
import daf.registry
import daf.utils
class ActionMeta(type):
"""A metaclass for validating and registering actions"""
def __new__(meta, name, bases, class_dict):
cls = type.__new__(meta, ... |
# Copyright 2017 - The Android Open Source Project
#
# 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 ... |
import requests
import json
import pickle
import random
## pun code
def findSubject():
#read from the noun list
nouns = pickle.load( open( "nouns", "rb" ))
choiceIndex = random.randrange(0, len(nouns))
word = nouns[choiceIndex]
return word.replace('\n','')
def findActionOrLocation():
#read fr... |
from django import forms
from unavis.forms import SecureBotForm
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
from django.contrib.auth import authenticate
import logging
logger = logging.getLogger('django.forms')
class LoginForm(SecureBotForm):
email = fo... |
from app import app
# turn on dev mode for development
if __name__ == "__main__":
app.run()
|
# -*- coding: utf-8 -*-
import os
import pandas as pd
from pyspark import SparkConf
from pyspark.ml.classification import LogisticRegression, SparkContext
from pyspark.ml.linalg import Vectors
from pyspark.sql import SparkSession
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
os.environ['PY... |
import sys
g=int(input())
p=int(input())
k=[]
for i in range(p):
val=int(input())
k.append(val)
s=[0 for _ in range (g)]
cnt=0
for a in k:
if s[a-1]==0:
s[a-1]=1
cnt+=1
else:
t=0
while s[a-1-t]==1 and a-1-t>0:
t+=1
if a-1-t==0:
break
... |
from .eLABJournalObject import *
class StorageType(eLABJournalObject):
def __init__(self, api, data):
"""
Internal use only: initialize storage object
"""
if ((data is not None) & (type(data) == dict) &
("name" in data)
):
super().__init__(api, d... |
../dummy_robot2.py |
from django.shortcuts import render, redirect
from books.models import Book
from django.contrib import auth
from libary.forms import SendMail
from .settings import ADMIN_EMAIL
from django.core.mail import send_mail as s_mail
from django.core.mail import EmailMessage
def base(request):
User = auth.get_us... |
try:
import urllib2
except ImportError:
import urllib.request as urllib2
import csv
import logging
import os
import re
import io
import requests
import scrapy
import zipfile
# to improve performance, regex statements are compiled only once per module
re_export = re.compile(r'.*?(http.*?export\.CSV\.zip)')
c... |
import os.path
class score_card:
"""Keeping score..."""
def __init__(self):
self.path = "./score.txt"
def addScore(self, score):
file = open(self.path, 'a')
file.write(score + '\n')
def readScores(self):
file = open(self.path, 'r')
return file.read()
def createScores(self):
if self.checkIfS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Part2. Reference (参考资料)
===============================================================================
该部分主要细致地阐述了Python语言中的各种特性。
"""
|
import torch as tr
import numpy as np
import torchvision as trv
def iou(b1, b2):
eps = 1e-7
top_rightx, top_righty = tr.min(b1[0], b2[:, 0]), tr.min(b1[1], b2[:, 1])
bot_leftx, bot_lefty = tr.max(b1[2], b2[:, 2]), tr.max(b1[3], b2[:, 3])
inter_rightx, inter_righty = tr.min(b1[2], b2[:, 2]), tr.min(b1... |
#! /usr/bin/env python3
from collections import defaultdict
from functools import partial
import numpy as np
# this is now specific for my analysis
# expects to be handed all pieces with
# all scales still present, no other index
class get_delta(object):
def __init__(self, sig_sm, sig_bsm, bkg):
self.sig... |
import datetime
from cities.models import City
from django.db.models import Count
regions_names = {
"Alberta": "AB",
"British Columbia": "BC",
"Manitoba": "MB",
"New Brunswick": "NB",
"Newfoundland and Labrador": "NL",
"Northwest Territories": "NT",
"Nova Scotia": "NS",
"Nunavut": "NU",... |
import numpy as np
import matplotlib.pyplot as plt
import math
def tail_prob(dist,t):
tail_Pr = []
for i in range(0,len(t)):
tail_Pr.append(dist[dist>(t[i]+np.mean(dist))].shape[0]/(1.0*len(dist)))
#subtracting the smaple mean from the random variable to make it centered
return tail_Pr
np.random... |
a=1 #전역변수
#전역변수는 힙이라는 저장공간에 들어가며, 끝날 때까지 유효하다.
def vartest(a): #b는 지역변수
a=a+1
return a
print(vartest(a)) |
import csv
import inspect
import json
import sys
import traceback
import unittest
# We want to proceed nicely on systems that don't have termcolor installed.
try:
from termcolor import cprint
except ImportError:
sys.stderr.write('termcolor module not found\n')
def cprint(msg, *args, **kwargs):
"""
Fallba... |
1# plot the energies
# Created by Martin Gren 2014-10-25.
# imports
import matplotlib.pylab as plt
import numpy as np
# input file
filename = 'values.dat'
# import data
data = np.loadtxt(filename)
# initial size of plot window
plt.figure(figsize=(8,6))
# plot
dasploot=plt.plot(data[:,0], data[:,1],'-')
plt.plot(10... |
print("hello space") |
from flask import *
clientes = Blueprint('clientes', __name__, url_prefix='/clientes', template_folder='clientes_templates')
@clientes.route('/')
def home():
datos = g.data.select_many('SELECT * FROM clientes')
return render_template('clientes.home.html', datos=datos)
|
from tests.test_base import TestBase
from front.pages.login_page import LogInPage
import unittest
class TestLog(TestBase):
def test_login_in(self):
groups_page = LogInPage(self.driver)\
.user_name("dmytro")\
.user_password('1234')\
.submit_log_in()
if __name__ == '_... |
x=input()
a=x.split()
if(int(a[0])<=1000 and int(a[1])<1000):
q=int(a[0])
w=int(a[1])
if q>w:
greater = q
else:
greater = w
while True:
if(greater%q==0)and(greater%w==0):
lcm=greater
break
greater+=1
print(lcm)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-23 15:01
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.utils.timezone
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('threads',... |
from .channels.ses import SES
from .channels.flash import Flash
class Publisher(object):
"""Class to publish notification objects to all channels"""
def __init__(self):
self.channels = list()
self.channels.append(SES())
self.channels.append(Flash())
def publish(self, notice):
... |
#!/usr/bin/python3
"""
x-request-id module
"""
if __name__ == "__main__":
import urllib.request
from sys import argv
req = urllib.request.Request(argv[1])
with urllib.request.urlopen(req) as response:
print(response.headers.get('X-Request-Id'))
|
#!/usr/bin/python
import sys
import fileinput
n = sys.argv[1]
m = sys.argv[2]
k = sys.argv[3]
sumFinal = sum(range(int(n),int(m)+1))
fname = 'out.' + str(k)
f = open(fname,'w')
f.write(str(sumFinal))
f.close()
|
import os
import pytz
##############################
# Config
##############################
STATUS = (
('active', 'Active'),
('inactive', 'Inactive'),
('deleted', 'Deleted'),
)
STATUS_DICT = dict(STATUS)
CATEGORIES = (
('All', 'All'),
('Main Dishes', 'Main Dishes'),
('Kids Menus', 'Kids Menu... |
from glypy.algorithms.subtree_search.inclusion import subtree_of
from glypy.structure.glycan import fragment_to_substructure
import time
import multiprocessing
from . import glycan_io
from . import __init__
from . import json_utility
import re
from glypy.io import wurcs
from glypy.io import glycoct
#### proposed fun... |
from __future__ import print_function
from os.path import join, dirname, abspath
from xlrd.sheet import ctype_text
import xlrd
import xlwt
import sys
def readFile(xl_workbook, indice):
xl_sheet = xl_workbook.sheet_by_index(indice)
num_cols = xl_sheet.ncols # Number of columns
for row_idx in range(1, xl_shee... |
from flask import url_for, redirect, flash, render_template
from flask_login import login_required, current_user
from app.models.base import db
from app.models.wish import Wish
from app.viewmodel.my_wish import WishViewModel
from . import web
__author__ = '七月'
@web.route('/my/wish')
@login_required
def... |
#! python3
# maplt.py - Launches a map in the browser using an address from the
# command line or clipboard
import sys, webbrowser, pyperclip, sys
print(sys.version)
if len(sys.argv) > 1:
# Get the address from command line.
address = ' '.join(sysargv[1:])
else:
#Get address from paperclip.
... |
#Collatz Conjecture
# if x is odd then next term 3*x + 1
# if x is even then next term x//2
def even(n):
return n%2==0
def nextVal(n):
if(even(n)):
return n//2
else:
return 3*n+1
num = int(input("Enter start parameter :- "))
i = 0
while(num != 1):
num = nextVal(num)
print(num)
... |
"""Dijkstra's Algorithm.
Given a weighted graph, find the shortest paths to all nodes.
1. Initialize a set of all nodes. Give all nodes the value of infinity.
2. Initialize an empty set of all visited nodes.
3. Give the starting node a value of 0 and visit it
4. Remove the visited node from the set of all nodes.
5. I... |
import unittest
from math_series.series import fibonacci, lucas, sum_series
# fibonacci tests for 0, 1, 5, 8
def test_zero_fib():
actual = fibonacci(0)
expected = None
assert actual == expected
def test_one_fib():
actual = fibonacci(1)
expected = 0
assert actual == expected
def test_five_fib(... |
import sys
import json
import ntpath
def minify(filepath):
filename = ntpath.basename(filepath)
fileparts = filename.split(".")
print(fileparts)
fileroot = fileparts[0]
fileext = fileparts[1]
newfilename = fileroot + "_minified." + fileext
with open(filepath) as json_file:
json_stri... |
import base64, logging
from typing import Union
def log_response(response) -> str:
"""
renders a python-requests response as json or as a string
"""
try:
log_body = response.json()
except ValueError:
log_body = response.content[:40]
return log_body
def create_logger(name: str... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# */AIPND-revision/intropyproject-classify-pet-images/get_pet_labels.py
#
# PROGRAMMER: Marcus Bremer
# DATE CREATED: 03/02/2021
# REVISED DATE:
# PURPOSE:... |
class Assignment:
def __init__(self, left, right):
self.left = left
self.right = right
def eval(self, env):
env[self.left.id] = self.right.eval(env)
def __repr__(self):
return "Assignment: {0} = {1}".format(self.left, self.right)
|
from sys import meta_path
import psycopg2
from flask import Flask, render_template, request
import json
from json import JSONEncoder
import datetime
connect = psycopg2.connect(user='postgres',
password='javb1999',
host='127.0.0.1',
port='... |
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.models import Token
from rest_framework.exceptions import AuthenticationFailed
from datetime import timedelta, datetime
from django.utils import timezone
from django.conf import settings
import pytz
from rest_framework import st... |
import pymatgen
import sys
from pymatgen.io.cif import CifParser
from pymatgen.core.lattice import Lattice
import os
import math
def cif_structure(file_name):
parser = CifParser(file_name)
structure = parser.get_structures()[0]
# print(structure[0].distance_matrix)
# print(type(structure[0].distance_matrix))
te... |
from CountOfMy import my_count
if __name__ == '__main__':
my_count()
|
"""Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solut... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import inspect
# print(inspect.getargspec(func))
if sys.version_info > (3, 4):
def signature():
"""
**中文文档**
``inspect.signature(callable)`` 能获得一个callable函数的输入参数和输出
值的信息。可以知道有哪些输入参数, 以及他们的默认值(如果有的话)
ref: https://... |
from pprint import pprint
import matcher
def test_narc1():
text = "Kaatuneiden henkilöasiakirjat (kokoelma) - Perhonen Onni Aleksi, 16.10.1907; Kansallisarkisto: https://astia.narc.fi/uusiastia/kortti_aineisto.html?id=2684857838 / Viitattu 26.5.2022"
m = matcher.matchline([text])
assert m is not None
pprint(m.__d... |
"""
Initialization for unit tests.
"""
from path import Path
from unittest import TestCase
from i18n import config
TEST_DATA_DIR = Path('.').abspath() / 'tests' / 'data'
MOCK_APPLICATION_DIR = TEST_DATA_DIR / 'mock-application'
MOCK_DJANGO_APP_DIR = TEST_DATA_DIR / 'mock-django-app'
class I18nToolTestCase(TestCase... |
#!/usr/bin/env python
import unittest
import os
import os.path
import logging
import threading
import shutil
from nose.plugins.attrib import attr
from WMCore.Agent.Configuration import Configuration
from WMQuality.TestInit import TestInit
from WMCore.Operations.RecoveryCode import PurgeJobs
from subprocess ... |
#!/usr/bin/env python3
#
# Convert a test specification to command-line options
import pscheduler
from validate import spec_is_valid
from validate import MAX_SCHEMA
spec = pscheduler.json_load(exit_on_error=True, max_schema=MAX_SCHEMA)
valid, message = spec_is_valid(spec)
if not valid:
pscheduler.fail(message)... |
import matplotlib.pyplot as plt
D = dict(
Q1=210,
Q2=260,
Q3=250,
Q4=230,
)
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice
fig1, ax1 = plt.subplots()
ax1.pie(list(D.values()), explode=explode, labels=list(D.keys()),
autopct='%1.1f%%', shadow=True, startangle=90
)
ax1.axis('equal') ... |
""" FTPServerUsingTCP.py
Yuqi Liu, Libin Feng
CISC-650 Fall 2014
Sep 26, 2014
This module will:
a. Creates a TCP socket and listens to connection request on port 12306;
b. Accepts request from client and receives the client's desired filename;
c. Searches the file under current directory. If... |
#!/Users/Ricko_Swuave/Documents/Python/refresh/refreshenv/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
from django.http import HttpResponse
from django.views.decorators.http import require_GET, require_POST
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from .models import Sensor
@csrf_exempt
@require_POST
def create_sensor(request):
body_unicode = request.body... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: youngmpjlt
#日期和时间 time calender
#获取时间戳
import time; #引入time模块
ticks = time.time()
print '当前时间戳为:', ticks
localtime = time.localtime(time.time())
print '本地时间为:',localtime #获取当前时间
localtime = time.asctime(time.localtime(time.time()))
print '本地时间为 :',localtime #获取格式... |
# -*- coding: utf-8 -*-
import webbrowser
import config
from databasemanager import ImdbLocalDatabase
from htmlgenerator import HtmlGenerator
from moviecollection import OrderedMovieCollection
import sys
def main():
if sys.version_info < (3, 5):
class PythonVersionException(Exception):
pass... |
import os
# https://stackoverflow.com/questions/15297834/infinite-board-conways-game-of-life-python
def main():
os.chdir(os.path.dirname(os.path.abspath(__file__)))
inp = open("day22_input.txt").read().splitlines()
print(solve(inp))
def solve(inp, max_cycles=10000):
grid = {}
dim = len(inp[0]... |
# Greatest product of three numbers
A = list(map(int, input().split()))
if len(A) == 3:
print(*A)
else:
Max1 = A[0]
Min1 = A[0]
for i in range(1, len(A)):
if A[i] > Max1:
Max1 = A[i]
if A[i] < Min1:
Min1 = A[i]
A.remove(Max1)
A.remove(Min1)
Max2 =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.