text stringlengths 38 1.54M |
|---|
import functools
from typing import Type
from ._Test import Test
from .. import AbstractTest
def ExceptionTest(*exceptions: Type[Exception]):
"""
Decorator that specifies a test that should raise one
of the given exception classes.
:param exceptions: The exceptions, one of which should be raised.
... |
t = [[False for i in range(5)] for j in range(17)]
t[0] = ['A','B','C','D','F']
for i in range(8,17): t[i][0] = True
for i in range(5,14,8):
for j in range(4):
t[i+j][1] = True
for i in range(3,17,4):
t[i][3] = True
t[i+1][3] = True
for el in t:
el[4] = ((el[0] and el[3] or el[3]) and (el[1] !=... |
# Environment variables that affects:
# KF_HOME - base folder for kungfu files
# KF_LOG_LEVEL - logging level
# KF_NO_EXT - disable extensions if set
import kungfu.command as kfc
from kungfu.command import __all__
def main():
kfc.execute()
if __name__ == "__main__":
main()
|
#!/usr/bin/env python2
# Flask with necessary methods for route handling and logging session data
from flask import Flask, render_template, url_for, request, redirect, flash, \
jsonify, session as login_session, make_response
# SQLAlchemy for configuring database schema and CRUD operations on the data
from sqlalc... |
import torch
import torch.nn as nn
import math
from .DCNv2.dcn_v2 import DCN_ID
class DenseBlock(torch.nn.Module):
def __init__(self, input_size, output_size, bias=True, activation='relu', norm='batch'):
super(DenseBlock, self).__init__()
self.fc = torch.nn.Linear(input_size, output_size, bias=bi... |
from sqlmodel import Session, select
from warehouse import engine
from warehouse.models import Customer
from warehouse.ultis import update_attr
def get_all():
with Session(engine) as session:
statement = select(Customer)
results = session.exec(statement)
return results.fetchall()
def get... |
# #自己组装一个类
# class A():
# pass
# def say(self):
# print("saying")
# say(9)
#
# A.say = say
# a = A()
# a.say()
# 自定义类
# def say(self):
# print("Saying ")
# def talk(self):
# print("talking")
# A = type("AName",(object,),{"class_say":say,"class_talk":talk})
# a = A()
#
# a.class_say()
# a.class_talk()
#... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("JERDBLocalReader")
process.load('Configuration.StandardSequences.Services_cff')
process.load("JetMETCorrections.Modules.JetResolutionESProducer_cfi")
from CondCore.DBCommon.CondDBSetup_cfi import *
process.maxEvents = cms.untracked.PSet(input = cms.unt... |
'''
Leia quatro valores inteiros A, B, C e D. A seguir, calcule e mostre a diferença do produto de A e B pelo produto de C e D
segundo a fórmula: DIFERENCA = (A * B - C * D).
Entrada: Saida:
5 DIFERENCA = -26
6
7
8
'''
A = int(input())
B = int(input())
C = int(input())
D =... |
import pytest
import numpy as np
import torch
from itertools import product
from ding.model import MAPPO
from ding.torch_utils import is_differentiable
B = 32
agent_obs_shape = [216, 265]
global_obs_shape = [264, 324]
agent_num = 8
action_shape = 14
args = list(product(*[agent_obs_shape, global_obs_shape]))
@pytest... |
# Compute final course grades for students based on percentage scores using a function.
score = float(input("Enter the numerical score: "))
def letterGrade(score):
if score >= 95:
return 'A+'
elif score >= 90 and score < 95:
return 'A'
elif score >= 85 and score < 90:
return 'A... |
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.db import models
# reverse() 함수를 사용하기 위해 임포트
from django.core.urlresolvers import reverse
# tagging를 사용하기 위한 임포트
from tagging.fields import TagField
# Create your models here.
@python_2_unicode_compatibl... |
from unittest import TestCase
from tcontrol import frequency
import tcontrol as tc
class TestFrequency(TestCase):
def test_nyquist(self):
frequency.nyquist(tc.tf([0.5], [1, 2, 1, 0.5]), plot=False)
def test_bode(self):
frequency.bode(tc.zpk([], [0, -1, -2], 2), plot=False)
frequency.b... |
"""
ipfjes - Our Opal Application
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ipfjes.settings")
from opal.core import application, menus
class Application(application.OpalApplication):
javascripts = [
'js/ipfjes/routes.js',
'js/ipfjes/occupational_history.js',
'js/ipfjes... |
# loops man
'''
for variable in list_name:
# Do stuff!
A variable name follows the for keyword; it will be assigned the value of each list item in turn.
'''
'''
iteratition:
for item in list:
print item
for i in range(len(list)):
print list[i]
for somthing
printing 'somthing',
puts ' ' between ... |
import requests
import json
from xlwt import *
url = "https://prodapi.metweb.ie/observations/valentia/yesterday"
response = requests.get(url)
data = response.json()
#creating a workbook
w = Workbook()
ws = w.add_sheet('weather')
rowNumber = 0;
ws.write(rowNumber,0,"name")
ws.write(rowNumber,1,"temperat... |
from slackclient import SlackClient
import copy
import sys
import time
import os
import re
import importlib
import InitModule
import ColorPrint
import password_crypt
sys.path.insert(0, './modules/')
sys.path.insert(0, './common/')
# wantname = ["REGEXBOT","CustomResponse"]
wantname = ["FBTOSLACK"]
class Slack_RTM:
... |
from rdflib import Namespace, Graph, Literal, RDF, URIRef
from rdfalchemy.rdfSubject import rdfSubject
from rdfalchemy import rdfSingle, rdfMultiple, rdfList
from brick.brickschema.org.schema._1_0_2.Brick.Chilled_Water_Pump_Differential_Pressure_Dead_Band_Setpoint import Chilled_Water_Pump_Differential_Pressure_Dead_B... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
# .so name, [.pyx files,.pyx files]
ext_modules = [Extension("helloworld", ["HWorld.pyx"])]
)
|
#!/usr/bin/python3
# Lists all states from a database
if __name__ == "__main__":
import MySQLdb
from sys import argv, exit
if len(argv) != 5:
print("Usage: ./5.py <username> <password> <database> <search>")
exit(1)
usr, pwd, dbe = argv[1], argv[2], argv[3]
sch = argv[4].split("'")... |
import urllib
import re
for lang in file("good.txt"):
(name, selfname, code, url) = lang.strip().split(',')
page = urllib.urlopen("http://watchtower.org" + url + "index.htm")
# if page.getcode() != 200:
# print "FAIL:", code
# else:
chaps = re.findall(r'\b([a-z0-9]+)/chapter(?:s|_\d\d\d).htm"... |
from django.conf import settings
from rest_framework import serializers
from openbook_auth.models import User, UserProfile
from openbook_categories.models import Category
from openbook_categories.validators import category_name_exists
from openbook_common.models import Badge
from openbook_common.serializers_fields.com... |
from gensim.models import Word2Vec
path = "mat2vec/training/models/"
model = "processedCorpusSG100"
#model = "FlowModelNew"
print(path+model+'\n')
w2v_model = Word2Vec.load(path+model)
w2v_model.wv.save_word2vec_format(path+'CompleteProjectorModel')
|
# print the pascal's triangle
l1 = [1,1]
l2 = [1,2,1]
l3 = [1,3,3,1]
n = int(input("# of levels?: "))
if n == 1:
print(l1)
if n == 2:
print(l2)
print(l2)
if n == 3:
print(l1)
print(l2)
print(l3) |
import time
import sys
import psutil
import threading
sys.path.append("../lib/")
import server as SC
import responses as RE
services = [["HTTP80", 80, RE.DLink_200],
["TR069", 7547, RE.generic],
["TOMCAT", 8080, RE.DLink_200],
["WSD", 5358, RE.generic],
["P500", 500, RE.generic]]
pidSafe = {}
p... |
# programmers lv2 다리를 지나는 트럭
# https://programmers.co.kr/learn/courses/30/lessons/42583
def solution(bridge_length, max_weight, truck_weights):
bridge = deque([0]*bridge_length, maxlen=bridge_length)
bridge_current_weight = 0
time = 0
truck_weights.reverse()
while truck_weights:
time += 1
... |
def findDecision(obj): #obj[0]: Outlook, obj[1]: Temp., obj[2]: Humidity, obj[3]: Wind
# {"feature": "Outlook", "instances": 14, "metric_value": 0.9403, "depth": 1}
if obj[0] == 'Sunny':
# {"feature": "Humidity", "instances": 5, "metric_value": 0.971, "depth": 2}
if obj[2] == 'High':
return 'No'
elif obj[2] ... |
import sys
from jinja2 import Template
from utils import LogTable
class TableRenderer:
def __init__(self, table):
self.table = table
def render(self, output_name):
with open('log_template.tex') as inf:
template = Template(inf.read())
with open(output_name, 'w') as outf:
... |
import logging
import logging.handlers
logger = logging.getLogger(__name__.split('.')[0])
def setup_logging(syslog=False, debug=False):
'''
Configures logging
'''
# logger.propagate = False
print(logger.name)
formatter = logging.Formatter('[%(levelname)s] %(asctime)s - %(message)s')
if deb... |
from django.db.models import Q
from rcreg_project.settings import (CUSTOM_SITE_ADMIN_EMAIL,
RC_GENERAL_ADMIN_EMAIL)
def all_challenge_notifications(request):
"""user notified via sidebar if:
user has unaccepted or unsubmitted challenges, or
submission window is closed due to too many challenge... |
import cProfile
import pstats
from io import StringIO
import re
def profile(func):
"""A decorator that uses cProfile to profile a function"""
def wrapper(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
ret = func(*args, **kwargs)
pr.disable()
s = StringIO()
... |
#!/usr/bin/python
import mkit.inference.ip_to_asn as ip2asn
import socket
import socket
import alexa
import json
from networkx.readwrite import json_graph
import networkx as nx
import pdb
from graph_tool.all import *
import os
import settings
EYEBALL_THRES = 500
files = [ x for x in os.listdir( settings.GRAPH_DIR_FINAL... |
#[<開始位置>:<終了位置>:<ステップ幅>]
test_list = ['https', 'www', 'python', 'izm', 'com']
print(test_list[:])
print(test_list[::])
test_list = ['https', 'www', 'python', 'izm', 'com']
print(test_list[:4])
test_list = ['https', 'www', 'python', 'izm', 'com']
print(test_list[2:])
test_list = ['https', 'www', 'python', 'iz... |
matrix = [[int(n) for n in input().split(", ")] for _ in range(int(input()))]
primary_diagonal = [matrix[r][r] for r in range(len(matrix))]
secondary_diagonal = [matrix[r][len(matrix[r]) - r - 1] for r in range(len(matrix))]
print(f"First diagonal: {', '.join([str(n) for n in primary_diagonal])}. Sum: {sum(primary_diag... |
#!/usr/bin/env python
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='speed-tracker',
version='1.0',
description='Check and save internet speed',
author='Kyle Ramey',
author_email='hello@kyleramey.dev',
url='htt... |
from dataprocess import *
import matplotlib.pyplot as plt
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import cufflinks as cf
df_certified, totaldf, Companyd, jobs, sorted_Company_count, sorted_Site_count = load_data_company('totalnew.csv')
new_input_new, new_list_name = data_for_... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 21 14:51:19 2016
@author: caoxiang
"""
import numpy as np
import pandas as pd
result1 = pd.read_csv('submission_10fold-average-xgb_fairobj_1130.892212_2016-12-12-10-50.csv')
result1_1133 = pd.read_csv('submission_5fold-average-xgb_1133.827593_2016-12-12-01-30.csv')
resul... |
# -*- coding: utf-8 -*-
#
# License:
#
# Copyright (c) 2013 AlienVault
# All rights reserved.
#
# This package is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 dated June, 1991.
# You may not u... |
import discord
import json
import random
from discord.ext import commands #算是一種導入 class 或 function 的方法
import os
with open('setting.json', mode='r', encoding='utf-8') as jFile: #用來開啟 json 檔案用的
jdata = json.load(jFile)
bot = commands.Bot(command_prefix='~') #輸入指令前必須先輸入 ~ 字元
@bot.event
async def on_ready(): # 當 bo... |
'''
Problem 5 - Rope
Make use of the modified splay tree from the previous problem
#This works but using code from previous example, could definetly speed it up and maybe condense the process function
'''
import sys
from collections import deque
# Vertex of a splay tree
###############################################... |
import numpy as np
import os
from utils import *
root_path = "/data/share/frame_border_detection_db_v6/results/experiments_20200404_higher_features"
experiment_list = os.listdir(root_path)
experiment_list = [name for name in experiment_list if os.path.isdir(os.path.join(root_path, name))]
loss_history_all = np.zeros... |
import os
import torch
import pickle
import numpy as np
from mmcnn import MMCNN
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from torch.optim.lr_scheduler import ReduceLROnPlateau
from sklearn.metrics import accuracy_score, f1_score, confusion_matrix
os.env... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 09:51:20 2018
@author: philippe
example of usage: python SC_bempp.py 450 meshes/cylinders_coarse.msh
"""
import bempp.api
from bempp.api.operators.potential import helmholtz as helmholtz_potential
import numpy as np
import time
import matplotlib... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# mcp3008_lm35.py - read an LM35 on CH0 of an MCP3008 on a Raspberry Pi
# mostly nicked from
# http://jeremyblythe.blogspot.ca/2012/09/raspberry-pi-hardware-spi-analog-inputs.html
import spidev
import time
import sys
import os.path
sys.path.append(os.path.join(os.path.dirn... |
__author__ = 'lukas'
from sklearn.metrics import accuracy_score
def optimize_clustering(sub_dir, inputs):
iterations = inputs['iterations']
n_test = inputs['n_test']
fs_method = inputs['fs_method']
fs_arg = inputs['fs_arg']
cluster_min = inputs['cluster_min']
print "performing analysis with z... |
import torch
import os
import random
import sys
import argparse
sys.path.append('/home-nfs/gilton/learned_iterative_solvers')
# sys.path.append('/Users/dgilton/PycharmProjects/learned_iterative_solvers')
import torch.nn as nn
import torch.optim as optim
from torchvision import transforms
import operators.blurs as blu... |
import scratch
import serial
import sys
import time
ScratchConnect = False
ColiasConnect = False
port = '/dev/rfcomm0'
#Initialise Colias Connection
while ColiasConnect == False:
print '-------------------------------------------------------\nAttempting to connect to port: %s' % port
#Connect to default serial port... |
import requests
import json
from enum import Enum
import config
# import boto3
# from botocore.config import Config
# iot_client = boto3.client('iot')
# iot = boto3.client(
# "iot",
# config=Config(
# retries={
# 'max_attempts': 7,
# 'mode': 'standard'
# }
# )
# )
... |
from tkinter import *
from tkinter import filedialog as fd
from pathlib import Path
root = Tk()
file1 = StringVar()
file1.set("File1")
file2 = StringVar()
file2.set("File2")
filename1 = ""
filename2 = ""
root.geometry('400x400')
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=... |
"""Script to take an excel worlist generated by LIMS at ALS and convert it into a filterable and more condensed
excel sheet for ease of use"""
from tkinter import filedialog
from tkinter import *
import xlrd, re, xlsxwriter, tkinter as tk
#regex setup to recognize different portions of a samples input data
rege... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, getopt
from multiprocessing import Pipe
import random
from operator import itemgetter
import itertools
import json
import threading
import copy
from protocols import *
def runAg(agent, connection, protocol, known, pattern, absint, learn):
""" Method to start an i... |
# Challenge: http://pastebin.com/MvLSdU2A
from math import factorial
def nChooseK(n, k):
"""n choose k binomial coefficient"""
return factorial(n) // factorial(k) // factorial(n-k)
class BSTNode():
"""A single Node in the Binary Search Tree"""
def __init__(self, value):
self.value = value
... |
import json
import uuid
from typing import Any, Dict, Callable
import pika
from Core import settings
from Core.Tools.Misc.ObjectSerializers import object_to_json
class RabbitMqAdapter:
@classmethod
def serialize_message(cls, data: Any) -> Dict:
return object_to_json(data)
def __init__(
... |
import torch.nn as nn
from .. model import Model
from ... modules.inplace_clip import InplaceClip
class VGG7(Model):
name = "waifu2x.vgg_7"
def __init__(self, in_channels=3, out_channels=3, **kwargs):
super(VGG7, self).__init__(VGG7.name, in_channels=in_channels,
ou... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 14 21:42:39 2019
@author: Henri_2
"""
from music21 import converter, instrument, note, chord, stream
def create_midi(prediction_output):
print('creating midi-file')
""" convert the output from the prediction to notes and create a midi file
from the notes... |
import json
import pytest
from quetz_content_trust import db_models
@pytest.fixture
def trust_roles():
return ["root.json"]
@pytest.fixture
def package_files(pkgstore, channel, trust_roles):
pkgstore.create_channel(channel.name)
for filename in trust_roles:
with open(filename, 'rb') as fid:
... |
#!/usr/bin/env python3
# coding=utf-8
"""
@author: guoyanfeng
@software: PyCharm
@time: 17-7-28 上午10:45
"""
|
"""
Classes for calculationg different energy terms
"""
import numpy as np
class Hamiltonian():
"""
Parent class for different types of interactions.
Assumptions and rules used in interaction construction:
1) Interaction contibution to the Hamiltonian can be described as
H = sum_i (gamma(a_i)*Q... |
class Solution(object):
def findPoisonedDuration(self, timeSeries, duration):
"""
:type timeSeries: List[int]
:type duration: int
:rtype: int
"""
preTime, poisonTime = -1, -1
answer = 0
for newTime in timeSeries:
if newTime >= poisonTime:
... |
from unittest.mock import Mock, patch
from django.contrib import admin
from datetime import date
from django.http import HttpResponseRedirect
from django.test import TestCase
from django.urls import reverse
from django.utils.timezone import now
from mep.accounts.models import Account, Subscription
from mep.books.mod... |
"""
This file contains all of the sqlite functions for scenes
"""
def init_scene(scene_db, name):
"""initializes the scene db"""
import uuid
from src.praxxis.sqlite import connection
conn = connection.create_connection(scene_db)
cur = conn.cursor()
scene_id = str(uuid.uuid4())
create_me... |
# import the necessary packages
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from keras.layers.core import Activation
from keras.layers.core import Flatten
from keras.layers.core import Dense
from keras import backend as bk
... |
# -*- coding: utf-8 -*-
DESC = "domain-2018-08-08"
INFO = {
"DescribeDomainPriceList": {
"params": [
{
"name": "TldList",
"desc": "查询价格的后缀列表。默认则为全部后缀"
},
{
"name": "Year",
"desc": "查询购买的年份,默认会列出所有年份的价格"
},
{
"name": "Operation",
"desc":... |
# Copyright 2019 Ondrej Skopek.
#
# 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... |
#
# Data for analyzing causality.
# By Nick Cortale
#
# Paper:
# Detecting Causality in Complex Ecosystems
# George Sugihara et al. 2012
#
# Thanks to Kenneth Ells and Dylan McNamara
#
import numpy as np
from numpy import genfromtxt
from scipy import integrate
def coupled_logistic(rx1, rx2, b12, b21, ts_length,rando... |
from django.urls import path
from App_Shop import views
app_name='App_Shop'
urlpatterns = [
path('create_title/',views.create_category,name='catagory'),
path('add_product/<int:pk>/',views.create_product,name='add_product'),
path('add_another_product/',views.create_another_product,name='add_another_product... |
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
# 文件目的:
# 创建日期:2017-12-30
# -------------------------------------------------------------------------
import hashlib
try:
import threading
except ImportError: # pragma: no cover
threading = None
from random im... |
import numpy as np
import theano
import theano.tensor as T
import sys, random
from theano_util import *
class MemNN:
def __init__(self, n_words=1000, n_embedding=100, lr=0.01, margin=0.1, n_epochs=100):
self.n_embedding = n_embedding
self.lr = lr
self.margin = margin
self.n_epochs ... |
#!usr/bin/python
given=600851475143
primes=[2]
def nextPrime():
global primes
n=primes[-1]
found=False
test=n+1
while not found:
for prime in primes:
divides= bool(test%prime==0)
broken=False
if divides:
broken=True
break
... |
from flask import render_template, request, redirect, url_for
from flask_script import Manager
from mainapp import app
from mainapp.views import user_v, logger_v
from models.user import db, User
from utils import cache
# 钩子函数
@app.before_request
def check_login():
app.logger.info(request.path + '被访问了')
if re... |
#!/usr/bin/python
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
from pytube import YouTube
import moviepy.editor as mp
import os
from flask import Flask, jsonify, request
import socket
import pprint as p
# Set DEVELOPER_KEY to the API key value f... |
import collections.abc
from datetime import datetime
import math
import os
from itertools import takewhile
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler
import torch
from torch.utils.tensorboard import SummaryWriter
from fpua.models.fetchers import single_input_single... |
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import argparse
import subprocess
def main(args):
input = args.input
N = args.size # size of USPTO-15k training set = 9236
scores = np.empty(N)
X = np.load(args.dir+'hidden_states_b' + str(input) + '.npy')
X = np.mean(X, ax... |
from rest_framework import serializers
from .models import Personas
def validar_edad(source):
if source <= 100:
pass
else:
raise serializers.ValidationError("No hay nadie mayor a 100")
pass
class PeopleGetName(serializers.Serializer):
nombre = serializers.CharField(max_length=100)
class PersonasCreationSer... |
import sys
from magma import *
from mantle.xilinx.spartan6.RAM import RAM128
from loam.shields.megawing import MegaWing
megawing = MegaWing()
megawing.Clock.on()
megawing.Switch.on(7)
megawing.LED.on(1)
main = megawing.main()
ram = RAM128(64*[0,1])
ADDR = main.SWITCH[0:7]
wire(ram(ADDR, 0, 0), main.LED[0])
compil... |
from unittest.mock import Mock, patch, PropertyMock
from scripts.generate_hamilton_input_UPL import GenerateHamiltonInputUPL
from tests.test_common import TestEPP, NamedMock
def fake_all_inputs1(unique=False, resolve=False):
"""Return a list of 2 mocked artifacts with container names and locations defined as a t... |
__version__ = '0.2.0.dev0'
__version_info__ = tuple([field for field in __version__.split('.')])
__api_version__ = 'v1.0'
|
# Generated by Django 3.0 on 2020-08-20 15:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0014_navmenu_file_menu'),
]
operations = [
migrations.AddField(
model_name='navchild',
name='is_file_active',
... |
import json
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.db import models
from facet_core import primo
class FacetQuery(models.Model):
query = models.CharField( max_length=150)
query_facets = models.TextField()
clean_query = models.Foreign... |
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
#print(arr)
arr1 = list(set(arr))
arr1.sort(reverse = True)
print(arr1[1])
#leap year
def is_leap(year):
# Write your logic here
leap = False
if year % 400 ==0:
leap = True
elif year % 100 =... |
from django.forms import ModelForm, DateTimeInput, Textarea, DateInput
from django.forms.models import inlineformset_factory
from project.models import Project, ProjectTeam, Task
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ('name', 'desc', 'owners', 'start_date', 'end_date')... |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, \
TextAreaField, FileField
from wtforms.validators import DataRequired
import os
class LoginForm(FlaskForm):
username = StringField('Login', validators=[DataRequired()])
password = PasswordF... |
import re
import requests
from find.models import FastaSource, MicroRNAAlias
headers = None # TODO: Implement proper headers
class SequenceNotFoundError(Exception):
pass
class Fasta:
def __init__(self, desc, seq, fasta_source):
self.description = desc
self.sequence = seq
self.fas... |
#!/usr/bin/python//Wi2018-Classroom/students/jean-baptisteyamindi/session05
#This is to proper exception handler in the except mailroom code, so that the code can run.
#We make sure to catch specifically the error you find
NameError
~/Pythonpython/Wi2018-Classroom/students/jean-baptisteyamindi/session05 except-mailroom... |
# 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
# distributed under t... |
#!/usr/bin/python
# This program is to show basic of python programming
# I'm opening a file using python
#
import os
import sys
import time
import getopt
from datetime import datetime
def print_help():
message = """\n******** Script Information *********\n
Usage : This script takes three arguments. env, action ... |
"""
Created on Tue Dec 17 16:10:32 2019
@author: Mohsen Mehrani, Taha Enayat
"""
import numpy as np
class arrays_glossary():
def array(self,what_array):
"""
Extracts information from agent matrix and graph. It generates and
returns desired arrays.
Parameters
----------
... |
import inspect
class Base():
def __init__(self, *args, **kwargs):
if self.__class__.__name__ == 'Base':
raise Exception('You are required to subclass the {} class'
.format('Base'))
methods = set([ x[0] for x in
inspect.getmembers(self.__class__, predicate=in... |
import os
ROOT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
SHORT_DATE_FORMAT = "%d.%m"
LONG_DATE_FORMAT = "%d.%m.%Y"
TIME_FORMAT = "%H:%M" |
import controls
import engine_factory
from audio_device import AudioDevice
engine = engine_factory.v_four_90_deg()
audio_device = AudioDevice()
stream = audio_device.play_stream(engine.gen_audio)
print('\nEngine is running...')
try:
controls.capture_input(engine) # blocks until user exits
except KeyboardInterru... |
import pandas as pd
import numpy as np
import mpmath
import periodictable as pt
import matplotlib.pyplot as plt
import functools
from .compositions import renormalise
from .normalisation import ReferenceCompositions, RefComp
from .util.text import titlecase
from .util.pd import to_frame
from .util.math import OP_consta... |
from sqlalchemy import create_engine
from flask_sqlalchemy import SQLAlchemy
# Initialize Flask-SQLAlchemy
db = SQLAlchemy()
def db_connection():
return 'sqlite:///test.db'
|
__version__ = '0.0.1'
__all__ = ["fig_to_d3", "display_d3", "show_d3"]
from .display import fig_to_d3, display_d3, show_d3
|
from random import randint
import matplotlib.pyplot as plt
import numpy as np
cant_tiros = 0
cant_simulaciones = 0
# Input
print("Elija un numero de la ruleta (0-36)")
num_elegido = input()
print("Ingrese la cantidad de tiros que desea simular")
cant_tiros = input()
print("Ingrese la cantidad de simulaciones que de... |
#Author: Dylan E. Wheeler
#Email: dylan.wheeler@usm.edu
#Date: 2019 05 20
#Course: CSC411 - Intro to Databases
#Prof.: Dr. Bo Li
import sqlite3
import random
import glob
import engine
from engine import get_cmd
from datetime import date
#use formatted text colors if library is a... |
from db import db, ma
class ReviewModel(db.Model):
__tablename__ = 'Review'
review_id = db.Column(db.Integer(), primary_key=True)
title = db.Column(db.String(45), nullable=False)
comment = db.Column(db.String(2000), nullable=False)
rating = db.Column(db.Float(), nullable=False)
date = db.Colum... |
from django.shortcuts import render, get_object_or_404, redirect
from .models import Question, Answer, Comment
from django.utils import timezone
from .forms import QuestionForm, AnswerForm, CommentForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginat... |
import torch
from torch import nn
def loss_function(d, d_hat):
# L2 = (d - d_hat).pow(2).mean()
L1 = nn.L1Loss()(d, d_hat).mean()
start = (d[:, 0] + d_hat[:, 0]) / 2
start = start.reshape(-1, 1, 8)
cosine_distance = 1 - nn.CosineSimilarity()(d - start, d_hat - start).mean()
return cosine_dista... |
# 从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存。
inputOut = input("请输入:")
if inputOut:
with open("test", 'w', encoding="utf-8") as stream:
stream.write(inputOut.upper())
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 列表
# my_list = ['加油', '运动场', '图书馆', 777]
# len
# print(len(my_list))
# 索引
# print(my_list[1])
# 切片
# print(my_list[0: 2])
# for循环
# for item in my_list:
# print(item)
# 练习1
"""
name_list = ["詹姆斯", "韦德", "罗斯"]
for item, index in enumerate(name_list):
print(index,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.