text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import os
os.environ['KERAS_BACKEND'] = 'theano'
os.environ['THEANO_FLAGS']='mode=FAST_RUN,device=gpu0,floatX=float32,optimizer=fast_compile'
import pylab as pl
import matplotlib.cm as cm
import ... |
import tensorflow as tf
from module.Backbone import Backbone
from module.Encoder import Encoder
from module.Decoder import Decoder
from tensorflow.contrib import slim
class SARModel(object):
def __init__(self,
num_classes,
encoder_dim=512,
encoder_layer=2,... |
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import src.dataprocessing as dataproc
from src.evaluation import get_embeddings, inferred_variables_evaluation
import src.evaluation as evaluation
from src.flow_loss import ScaledFlowLoss, compute_simple_weighting
from src.utils import E... |
# ex29: What if
people = 20
cats = 30
dogs = 15
# An if statement creates a "branch" in the code.
# If the boolean expression is true then run the code, otherwise skip.
# The colon indicates a new block of code, and anything
# that is indented underneath is part of that block.
if people < cats:
print "Many cats! ... |
x = input("Enter cells: ")
print("---------")
print("|", x[0], x[1], x[2], "|")
print("|", x[3], x[4], x[5], "|")
print("|", x[6], x[7], x[8], "|")
print("---------")
#O match detection
VertO = False
for n in range(3):
if x[n] == "O" and x[n + 3] == "O" and x[n + 6] == "O": #Vertical "O" match detection
... |
"""
Component of WMAgent that runs an alert Processor pipeline to forward
alerts to various other systems & monitoring.
"""
import logging
import signal
import traceback
from WMCore.Agent.Harness import Harness
from WMCore.Alerts.ZMQ.Processor import Processor
from WMCore.Alerts.ZMQ.Receiver import Receiver
class... |
# -*- coding: utf-8 -*-
# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)
# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016
import warnings
from unittest import TestCase
import numpy as np
import pandas as pd
from pandas.testing import assert_fra... |
#!/usr/bin/python
#\file joint_spring.py
#\brief Joint spring controller test
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Oct.29, 2015
'''
NOTE: run beforehand:
$ rosrun baxter_interface joint_trajectory_action_server.py
'''
from bxtr import *
if __name__=='__main__':
rospy.init_no... |
li = [9, 1, 8, 7, 3, 6, 4, 2, 5]
s_li = sorted(li)
print('Sorted Variable:\t', s_li)
print('Original Variable:\t', li)
li.sort()
print('Sort Variable:\t', li)
li = [9, 1, 8, 7, 3, 6, 4, 2, 5]
s_li = sorted(li, reverse=True)
print('Reverse Sorted Variable:\t', s_li)
print('Original Variable:\t', li)
li.sort(reverse=Tr... |
value = 15
new_value = value / 2 if value < 100 else - value
print(new_value)
###############################
value = 500
new_value = 1 if value < 100 else 0
print(new_value)
################################
value = 10
new_value = True if value < 100 else False
print(new_value)
################################
my_str... |
# -*- coding: utf-8 -*-
from os.path import exists, expanduser, isfile, join
from sys import exit
import rsa
import settings
from accessory import get_abs_path
from salt import get_salt
def getpassword(path):
"""Get password from an encoded file.
Input:
path -- source path.
Output:
passw... |
import pandas as pd
from models.basic import PipeLine
from models.constants import TASK_DESEQ, TASK_MULTI_QC
CONFIG_FILE = "config/config.yaml"
configfile: CONFIG_FILE
SAMPLES_DF = pd.read_csv(config['samples'])
BASE = config['base']
PIPELINE = PipeLine(CONFIG_FILE)
def get_final_outputs(wildcards):
files = []... |
import pickle
fichero = open("lista_nombres","rb") #leemos el archivo binario
lista = pickle.load(fichero)
print(lista) |
"""empty message
Revision ID: 9f17ec120c2b
Revises: 493466ec9210
Create Date: 2018-04-17 20:41:17.155314
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9f17ec120c2b'
down_revision = '493466ec9210'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from sys import platform
class Hosts:
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
# def __del__(self):
# self.remove_from_hosts()
def get_hosts(self):
f = open(self.hosts_path, encoding='utf-8')
lines = f.readlines()
f... |
import requests
import pymysql
import re
#连接数据库:
db = pymysql.connect("localhost","root","root","search_news",charset='utf8')
while True:
info = input("输入对话内容:")
cur = db.cursor()
if info == "exit":
sql = "select * from news"
try:
cur.execute(sql)
results = cur.fetc... |
from django.db.models import Q, Count
from django.shortcuts import render, get_object_or_404
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from products.mixins import ObjectViewedMixin
# from .forms import DocProductFormSet
from products.forms impor... |
MINI_DATASET_URL = "http://files.grouplens.org/datasets/movielens/ml-latest-small.zip"
FULL_DATASET_URL = "http://files.grouplens.org/datasets/movielens/ml-latest.zip"
IG_URL = "https://www.instagram.com/yame_movies/"
GOOGLE_FORM_URL = "https://docs.google.com/forms/d/e/1FAIpQLSf9bL0StMXnjjfSlhgekbMFJNw5okT2bpFUqfO-... |
import numpy as np
import vegans.utils.loading.architectures as architectures
from vegans.utils.loading.MNISTLoader import MNISTLoader
from vegans.utils.loading.DatasetLoader import DatasetLoader, DatasetMetaData
class CIFAR10Loader(MNISTLoader):
def __init__(self, root=None):
self.path_data = "cifar10_da... |
# -*- coding: utf-8 -*-
#############
#
# Copyright - Nirlendu Saha
#
# author - nirlendu@gmail.com
#
#############
from __future__ import unicode_literals
import inspect
import sys
from django.db import models
from libs.logger import app_logger as log
class ExpressionPrimaryManager(models.Manager):
def crea... |
from django.contrib import admin
from .models from User
# Register your models here.
admin.site.register(Article)
|
"""my_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... |
import SCDM.TD3_plus_demos.TD3 as TD3
import dexterous_gym
import gym
import numpy as np
import time
filename = "models/TD3_PenSpin-v0_0_beta_0_7_norm"
beta = 0.7
env_name = "PenSpin-v0"
env = gym.make("PenSpin-v0")
steps = 1000 #long run, "standard" episode is 250
def eval_policy(policy, env_name, seed, eval_episod... |
import numpy as np
from IPython import embed
from matplotlib import pyplot as plt
from math import hypot
from skimage import draw
class MapEnvironment(object):
def __init__(self, mapfile, start, goal):
# Obtain the boundary limits.
# Check if file exists.
self.goal = goal
self... |
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
# source = cv2.imread("D:/Users/84460/Desktop/Oracle_Split/picture/003.png",0) # 读图片
def file_name(dir_path):
f_name = []
f_namelist = []
print(os.listdir(dir_path))
for i in f_namelist:#分割后缀
index = i.rfind('... |
/Users/matthewpeterson/anaconda3/lib/python3.7/hmac.py |
from django.contrib import admin
from .models import (
Faculty,
Profile,
AppraiseeComment,
AppraiserAndAppraiseeAgreement,
Competence,
OverallPerformance,
Performance,
AppraiserComment,
VcComment,
Department
)
class AppraiserAndAppraiseeAgreementAdmin(admin.ModelAdmin):
list... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
n=int(raw_input())
l=map(int,raw_input().split())
ans=chk=1
tmp=-1
for i in l:
if tmp==-1:
pass
elif i>tmp:
chk+=1
else:
chk=1
tmp=i
ans=max(ans,chk)
print ans
|
# coding:utf-8
import itchat
import math
import PIL.Image as Image
import os
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)[0:]
user = friends[0]["UserName"]
num = 0
for i in friends:
img = itchat.get_head_img(userName=i["UserName"])
fileImage = open('D:' + "/" + str(... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test4.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import requests
import re
from pyquery import PyQuery as pq
from Pyquery的应用.百度百科API... |
# Generated by Django 3.0.5 on 2020-10-20 11:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('log', '0004_log_complete_at'),
]
operations = [
migrations.RemoveField(
model_name='log',
name='complete_at',
),
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Author: shoumuzyq@gmail.com
# https://shoumu.github.io
# Created on 2015/10/27 10:46
def win_nim(n):
if n % 4 is 0:
return False
else:
return True
print(win_nim(4))
print(win_nim(5))
|
import nltk
class Stemming:
# Stemming
def execute(self, dataframe, execute):
if (execute == True):
print("Stemming words")
nltk.download('rslp')
stemmer = nltk.stem.RSLPStemmer()
for index, row in dataframe.iterrows():
... |
import time
from datetime import datetime
from IPython.display import HTML, display
# Paths and filenames for saving models/output
# path = '/home/jupyter/CSE253_FinalProject/Logistic_Regression/'
path = '/content/Logistic_Regression'
dt = datetime.now().strftime("%m_%d_%H_%M")
output_fn = path + "model_output_" +... |
from torch import tensor
from torch.nn.utils.rnn import pad_sequence
class TweetPadCollate:
def __init__(self,pad_idx):
self.pad_idx = pad_idx
def __call__(self,batch):
data = [sample[0] for sample in batch]
targets = [sample[1] for sample in batch]
padded_data... |
import cv2
import glob
images=glob.glob("*.jpg")
for image in images:
img= cv2.imread(image,1)
img2 = cv2.resize(img,(100,100))
cv2.imshow("resized_image",img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite("resized_image"+image,img2)
|
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
import threading
# Batasi hanya pada path /RPC2 saja supaya tidak bisa mengakses path lainnya
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Buat server
with SimpleXMLRPCServer(("localh... |
def bellNumber(n):
bell = [[0 for i in range(n+1)] for j in range(n+1)]
bell[0][0] = 1
for i in range(1,n+1):
bell[i][0] = bell[i-1][i-1]
for j in range(1,i+1):
bell[i][j] = bell[i-1]
return bell[n][0]
for n in range(4):
print('Bell Number',n,'is',bellNumber(n)) |
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/elements1_20.txt -o elements1.txt
def get_names() :
while True :
if(len(input_list) < 5):
input_string = input("Enter the name of an element: ").strip().lower()
if not input_string :
continu... |
import numpy as np
import ast
file = open("evaluator_1_input_script_out.txt")
contents = file.read()
ackley = ast.literal_eval(contents)
print({"ackley": ackley})
|
print('Я домашка, делаю проверку 2')
|
i=2
while i<4:
one=int(input("Enter the judge #1's score:"))
if one>10:
print('Please enter a range from 0-10')
i=2
else:
two=int(input("Enter the judge #2's score:"))
if two>10:
print('Please enter a range from 0-10')
i=2
else:
thr... |
# A list of numbers is given. If it has two adjacent
# elements of the same sign, print these numbers.
s = list(map(int, input().split()))
def Same(s):
for i in range((len(s) - 1)):
x1 = int(s[i])
x2 = int(s[i + 1])
if x1 * x2 >= 0:
print(x1, x2)
break
Same(s)
|
from pyplasm import *
from pyplasm import *
import scipy
from scipy import *
def VERTEXTRUDE((V,coords)):
return CAT(AA(COMP([AA(AR),DISTR]))(DISTL([V,coords])))
def larExtrude(model,pattern):
V,FV = model
d = len(FV[0])
offset = len(V)
m = len(pattern)
outcells = []
for cell in FV:
... |
msg = "hello"
print(msg.capitalize()) |
import logging
from twisted.internet import defer
from twisted.web.client import getPage
from scrapy import Request
from scrapy.http import HtmlResponse
from scrapy.utils.misc import arg_to_iter
from crochet import setup, wait_for, TimeoutError
setup()
class FetchError(Exception):
status = 400
def __init_... |
## Scrapes historical Rotogrinders projections by game for every active player in the MLB, and
## export each day's projections as a CSV file
##
## To run this file, pip install the packages below and install the chromedriver
## application onto your computer. Then, create a PATH variable to the chromedriver
## folder... |
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
import cv2
from cv_bridge import CvBridge, CvBridgeError
class KinectInterface:
def __init__(self):
self._image_sub = rospy.Subscriber('/kinect2/hd/image_color', Image, self.callback)
self._downsampling_pub = rospy.Publisher('dsam... |
from onegov.core.utils import module_path
from onegov.foundation import BaseTheme
class WtfsTheme(BaseTheme):
name = 'onegov.wtfs.foundation'
@property
def pre_imports(self) -> list[str]:
return ['font-newsgot', 'wtfs-foundation-mods']
@property
def post_imports(self) -> list[str]:
... |
# coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# 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... |
from django.urls import path
from . import views
app_name = 'subscriptions'
urlpatterns = [
path('api/active-products/', views.ProductWithMetadataAPI.as_view(), name='products_api'),
# team-specific URLs
# todo: it would be better if these matched the /a/team-slug/subscription pattern of other pages
... |
import sys
import time
from networktables import NetworkTables
# To see messages from networktables, you must setup logging
import logging
logging.basicConfig(level=logging.DEBUG)
if len(sys.argv) != 2:
print("Error: specify an IP to connect to!")
exit(0)
ip = sys.argv[1]
NetworkTables.initialize(server=ip)... |
def temperature(cel):
return (cel * (9/5) + 32)
c = int(input("enter temperature " ))
print(temperature(c))
|
from fastapi import FastAPI
from common.config import Config
from scripts.lambdas.initial_setup import setup
from views.schedules import router as schedules_router
def get_application() -> FastAPI:
setup()
app = FastAPI()
app.include_router(schedules_router)
@app.get("/")
asy... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-30 17:29
from __future__ import unicode_literals
from django.db import migrations
from osf_oauth2_adapter.apps import OsfOauth2AdapterConfig
def create_human_group(apps, schema_editor):
Group = apps.get_model('auth', 'Group')
Group.objects.db_ma... |
def loading():
print("loading...")
|
from pycalclib.Storage import Storage
from pycalclib.Data import Data
from pycalclib.Manager import Register
def test_storage_varaible_creation():
st = Storage()
var1 = st.createVariable('myVar', Data(
Register.getTypeByClassName('Integer'), 2))
expectedVar = Data(Register.getTypeByClassName('In... |
from scripts.systems.digg_system import DiggSystem
from config.badger_config import digg_config
def deploy_digg_minimal(deployer, devProxyAdmin, daoProxyAdmin, owner=None):
digg = DiggSystem(digg_config, deployer, devProxyAdmin, daoProxyAdmin)
digg.deploy_core_logic()
digg.deploy_digg_token()
digg.d... |
import numpy as np
import numpy.linalg as LA
import itertools
import random
#seabornはimportしておくだけでもmatplotlibのグラフがきれいになる
#import seaborn as sns
#sns.set_style("darkgrid")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#from sklearn.neighbors import NearestNeighbors
"""
def AND(f1, f2):
r... |
#!/usr/bin/env python3
"""Calculates the path of a particle in a magnetic field.
This code was written for Python 3 and tested using Python 3.5.0
(64-bit) with Anaconda 2.4.0 (64-bit) on a computer running Ubuntu 14.04
LTS (64-bit).
"""
__author__ = 'Kyle Capobianco-Hogan'
__copyright = 'Copyright 2016'
__credits__ ... |
import numpy as np
#import denemee as den
import thirdtry as thr
##***train edilecek neural network ile test edilecek dataset uzunlugu aynı olmalı(bias weightlerden dolayı)
#import denemee as dn
f = open(r'C:\Users\ASUS\Desktop\test-data\ann-test1.txt')#neural networkün çalıstıgını göstermek için aynı set kullanıl... |
import flask_bcrypt as _fb
import flask_migrate as _fm
import flask_sqlalchemy as _fs
db = _fs.SQLAlchemy()
migrate = _fm.Migrate(db=db)
bcrypt = _fb.Bcrypt()
def init_app(app, **kwargs):
db.app = app
migrate.init_app(app)
db.init_app(app)
from .user import User, Role
from .book import Book
from .categ... |
# from flask import Flask, jsonify, request, WebScraperAndFormatter
#
# app = Flask(__name__)
#
# @app.route('/<string: url>', methods=['GET'])
# def index():
# events = scrape_and_format(url) #zipped object of events
# csv = csv_generate(events, url)
# csv_filename = '{}.csv'.format(url)
# json = json_... |
"""Connect to Database and create visualizations"""
from sqlalchemy import create_engine
import pandas as pd
from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.palettes import turbo
# import concurrent.futures
call = 'mysql+mysqlconnector://mausolorio:ducinALTUM7!@localhost/s&p500'
en... |
class Solution:
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
nums = [i for i in range(1,n+1)]
result = []
def backtrack(i, data):
if len(data) == k:
result.append(data.copy())
... |
from decimal import Decimal
from ..schema_fields import (
ArrayField,
BooleanField,
DynamicArrayField,
Field,
CharField,
DecimalField,
IntegerField,
TextField
)
from .utils import assert_dict_equal
class TestField:
def test_schema_basic(self):
field = Field()
asser... |
def solution(A):
n = len(A)
lead, count = leader(A,n)
if lead == "NoDominator":
return 0
equileader = 0
temp_count = 0
for idx in range(n):
if A[idx] == lead:
temp_count +=1
if (temp_count > (idx+1)//2) and (count-temp_count > ((n-idx-1)//2)):
equi... |
# name: P.U.B.智能计算系统!
# author: Thomas·P
# date: 2020.11.29
# version:0.0.0
import math
import time
start_input = "请选择您需要的计算类型(按1或2并按下回车(ENTER)):"
print("欢迎来到P.U.B.智能计算系统!")
time.sleep(2)
print("以下是本系统支持的数学计算领域:\n1.代数\n2.几何")
time.sleep(2)
while True:
choose = input(start_input)
start_input =... |
import mosaic
import numpy as np
import prettypyplot as pplt
from matplotlib import pyplot as plt
pplt.use_style(colors='tab20c', figsize=2.4)
def main():
# Load trajectory from file
# traj = np.loadtxt(filename)
# Here we use some random sample data
traj = create_traj()
# specify parameters gri... |
# from django.test import Client
# from django.urls import reverse
# from test_plus.test import TestCase
#
# from zhihu.qa.models import Question, Answer
# class QAViewsTest(TestCase):
# def setUp(self):
# self.user = self.make_user("user01")
# self.other_user = self.make_user("user02")
# ... |
#8-12 一個簡單的類別,說明可變預設值的危險
class Bus:
"""A bus model haunted by ghost passengers"""
def __init__(self,passengers = []):
self.passengers = passengers
def pick(self,name):
self.passengers.append(name)
def drop(self,name):
self.passengers.remove(name)
|
import os
import sys
from django.conf import settings
BASE_DIR = os.getcwd() # os.path.dirname(__file__)
print('Here', BASE_DIR, __file__)
print(os.path.join(BASE_DIR, 'templates'))
print(os.listdir(os.path.join(BASE_DIR, 'templates')))
DEBUG = os.environ.get('DEBUG', 'on') == 'on'
SECRET_KEY = os.environ.get('SECRET... |
"""
File: convect.py
Author: Sean Blake
Date: December 2012 - January 2013
This code uses data from the 'Model S' solar data set. This can be found at: http://users-phys.au.dk/jcd/solar_models/
The code can be (roughly) separated into 3 parts.
1) Data extraction + definition of the functions used.
-lines 18-340
... |
from flask import *
home = Blueprint('home', __name__, url_prefix='/home', template_folder='home_templates', static_folder='home_static')
@home.route('/')
def home():
return render_template('home.html')
|
import time
from model.nethandler.battle_net_handler import BattleNetHandler
def default_callback(*args):
pass
class BattleNetClient(BattleNetHandler):
def __init__(self, name="client#" + str(round(time.time()*1000))):
self.players_names = []
self.short_rule = True
self.no_card_upside_down = False
self.... |
from discord.ext import commands
from potato_bot.bot import Bot
from potato_bot.cog import Cog
class Democracy(Cog):
"""Automatic democracy tools"""
def __init__(self, bot: Bot):
self.bot = bot
@commands.command()
async def peng(self, ctx):
await ctx.send("pong!")
def setup(bot):
... |
from canoser import Struct, Uint8, bytes_to_int_list, hex_to_int_list
from libra.transaction.transaction_argument import TransactionArgument, normalize_public_key
from libra.bytecode import bytecodes
from libra.account_address import Address
class Script(Struct):
_fields = [
('code', [Uint8]),
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MainWindow.ui'
#
# Created: Fri Jan 6 16:47:09 2017
# by: PyQt5 UI code generator 5.2.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
... |
import tornado
from tornado import web
import wtforms_json
from peewee_async import Manager
from MxForum.settings import settings, database
from MxForum.urls import urlpattern
if __name__ == '__main__':
wtforms_json.init()
app = web.Application(urlpattern, debug=True, **settings)
app.listen(8888)
obje... |
import webapp2
import os
import jinja2
import json
import datetime
import time
import urllib
import urllib2
import soundcloud
import sys
import random
import math
from google.appengine.ext import db
from google.appengine.api import memcache
from secret import client_id, client_secret
template_dir = os.path.dirname(__f... |
#coding=utf-8
x,y=input('请输入一个数值的范围:')
if x>y:
t=y
y=x
x=t
while x<2:
x,y=input('输入错误,请重新输入一个数值范围:')
if x>y:
t=y
y=x
x=t
m=1
s=[]
print '数值范围内所检索的所有素数为:'
for i in range(x,y,1):
for j in range(2,i+1,1):
if i%j==0:
break
if i==j:
s.append(i)
print i,
... |
import os
import sys
import pytest
import subprocess
import time
import re
from webapp.app import create_app
from webapp.config import config_dict
from core.constants import SQL_TEST_CONNECTION_STRING, SQL_TEST_DBNAME
from core.db import create_database, connect_db, drop_db, session_open, session_close
from util_scrip... |
import json
from .game_state import GameState
from .util import get_command, debug_write, BANNER_TEXT, send_command
class AlgoCore(object):
"""
This class handles communication with the game engine. \n
algo_strategy.py subclasses it.
Attributes :
* config (JSON): json object containing infor... |
def NumberChooser(number):
if number == 0:
return "Zero"
elif len(str(number)) == 1:
return Unit(number)
elif len(str(number)) == 2:
return Dozens(number)
elif len(str(number)) == 3:
return Hundreds(number)
elif len(str(number)) == 4:
return Thousands(number)... |
#!/usr/bin/env python
"""
Command line interface for Baltica
"""
import os
from pathlib import Path
import sys
import yaml
import logging
import subprocess
import tempfile
import snakemake
import click
from baltica.version import _program, __version__
baltica_path = Path(__file__)
# from https://stackoverflow.com/... |
# Uses python3
import sys
def get_change(m):
changeNum = 0
remainder = 0
# 10
changeNum = m//10
remainder = m%10
# 5
changeNum += remainder//5
remainder = remainder%5
# 1
changeNum += remainder
return changeNum
if __name__ == '__main__':
m = int(sys.stdin.read())
... |
# -*- coding: utf-8 -*-
# flake8: noqa
# Generated by Django 1.11 on 2017-05-28 19:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('press', '0002_auto_20170528_1624'),
]
... |
# -*- coding: utf-8 -*-
from datetime import datetime
from flask import render_template, request, session, make_response, redirect, Response
from jinja2 import Template as jTemplate
from models.project import table, col
from models.orm import User, Project, Template
from zp_tools import rdm_code, hash_pwd, json_res, is... |
from chapter3_case_study.Property import Property
from chapter3_case_study.helper_functions import get_valid_input
class Appartment(Property):
valid_laundries = ("coin", "ensuite", "none")
valid_balconies = ("yes", "no", "solarium")
def __init__(self, balcony = '', laundry = '', **kwargs):
super... |
"""
Script for loading IDN data into calibration targets and default.yml
"""
import json
import os
import pandas as pd
from autumn.settings import PROJECTS_PATH
from autumn.settings import INPUT_DATA_PATH
from autumn.models.covid_19.constants import COVID_BASE_DATETIME
# Use OWID csv for notification and death num... |
#!/usr/bin/env python
'''
Copyright (c) 2016, Juan Jimeno
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of co... |
import tkinter as tk
class MailList(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.label_username = tk.Label(self, text="Test")
self.label_password = tk.Label(self, text="TEST")
self.label_username.grid(row=0, sticky=tk.E)
self.label_password.grid(ro... |
"""
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
"""
class Solution(object):
def p... |
from django.db import models
class InsuranceCompany(models.Model):
name = models.CharField(max_length=40)
contact_phone = models.PositiveIntegerField(blank=True, null=True)
contact_email = models.EmailField(blank=True)
website = models.URLField(blank=True)
def __str__(self):
return sel... |
import sys
from rosalind_utility import parse_fasta
memo = {}
def modified_motzkin(seq):
if len(seq) in [0, 1]:
return 1
if seq in memo:
return memo[seq]
memo[seq] = modified_motzkin(seq[1:])
for i in range(1, len(seq)):
if ((seq[0] == "A" and seq[i] == "U") or
... |
import pygame.display
import Functions
from Color import Color
from Maze import Maze
from Slides import SlideFunctions
from Text import Text
from Settings import screen as screen_settings
screen_size = screen_settings.screen_size
def backtracker_slide(screen, display_settings):
text_title = Text((screen_size[0]... |
# Generated by Django 3.1.1 on 2020-10-02 10:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('joseph_blog', '0004_auto_20201002_1314'),
]
operations = [
migrations.AlterField(
model_name='comment',
... |
#!/usr/bin/env python3
from bs4 import BeautifulSoup; # for web scraping
import requests;
import urllib.request;
from urllib.request import urlopen;
import re;
import sys;
# sets the destination URL and returns parsed webpage as BeautifulSoup object
# to be used in other functions
def choose_vehicle_class(choice):
... |
#coding:utf-8
import bobo, webob
from controller import Controller
@bobo.subroute('/user', scan=True)
class UserController(Controller):
def __init__(self, request):
self.request = request
@bobo.query('')
def base(self):
return "Hello!"
|
from common.dto_dependency_loader import asinstanceof, asinstancesof, DtoDependencyLoader
from common.models.scenario_settings import ScenarioSettings
from common.models.static_analysis import StaticAnalysisResult
from common.models.vuln_type import VulnType
class Scenario:
def __init__(self, scenario_settings, a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.