text stringlengths 8 6.05M |
|---|
import sys
import os
from selenium import webdriver
ELEMENT_WAIT_TIMEOUT = 15
def get_config():
from utils.config import Config
return Config().configuration
REQUESTS_WAIT_TIMEOUT = 15
ROOT_URL = get_config()["environments"]["url"]
def get_driver():
executable_path = os.path.join('driv... |
from flask import Blueprint, jsonify, request
from videoblog import logger, docs
from videoblog.schemas import VideoSchema
from videoblog.models import Video
from flask_apispec import use_kwargs, marshal_with
from flask_jwt_extended import jwt_required, get_jwt_identity
from videoblog.base_view import BaseView
from vid... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 28 14:10:00 2020
@author: kevin
!!! MAJOR ERROR: Our custom trained language cannot be used as it results in an error with Tesseract v5
It works with v4 but v5 will of course be the future
This script uses tesseract's conf value during ocr processing and writes the... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 13 09:51:22 2019
@author: charlie
"""
import socket
import string
import time
# vars specificying server
SERVER = "127.0.0.1"
PORT = 6667
CHANNEL = "#test"
# open socket
IRCSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connec... |
MENU_ID = 'featurelets'
|
l = list(map(int, input().split(' ')))
l.sort()
a, b, c = l
if a + b <= c:
print("Invalido")
else:
if a == b and b == c:
t = "Valido-Equilatero"
elif a == b or b == c:
t = "Valido-Isoceles"
else:
t = "Valido-Escaleno"
if (a ** 2) + (b ** 2) == c ** 2:
r = 'S'
el... |
from Features import Features
from sklearn import svm
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import BernoulliNB
from sklearn.naive_bayes import MultinomialNB
from sklearn import tree
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
impor... |
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--n-trials',
type=int, default=1,
help='Number of trials'
)
parser.add_argument(
'--n-modules',
type=int, default=1,
help='Number of modules'
)
parser.a... |
def LCS (x,y) :
global X,Y
if (x == 0) or (y == 0) :
return 0
else :
if (X[x-1] == Y[y-1]) :
return 1 + LCS (x-1,y-1)
else :
return max(LCS(x,y-1) , LCS(x-1,y))
X = input()
Y = input()
x = X.__len__()
y = Y.__len__()
print(LCS(x,y))
|
for _ in range(int(input())):
tc = input()
print(tc[0].upper()+tc[1:])
|
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def length(node):
current = node
result = 0
while current is not None:
current = current.next
result += 1
return result
def count(node, data):
current = node
result = 0
whi... |
ppl_json_file_path = "C://Users//ericw//CodingProjects//0 - Secrets//ppl//Owner - Eric Sang.json"
|
Checklist01 = [
'2021-08-02 13:14:59.844443',
{'position00': False, 'position01': False, 'position02': False, 'position10': False, 'position11': False,
'position12': False, 'position20': False, 'position21': False, 'position22': False}]
Checklist02 = [
'2021-08-02 13:15:02.508831',
{'position00': F... |
from room import Room
word_part_list1 = ["動詞編", "名詞編", "形容詞編", "副詞・その他", "すべて"]
word_part_list2 = ["動詞編", "名詞編", "形容詞編", "副詞", "すべて"]
word_part_list3 = ["動詞編", "名詞編", "形容詞編", "すべて"]
def generate_rooms():
game_stages = [Part(1, 9), Part(2, 8), Part(3, 4)]
return game_stages
class Part:
def __init__(self... |
def calc(s):
num = ''.join(str(ord(a)) for a in s)
num2 = num.replace('7', '1')
return abs(sum(int(b) for b in num) - sum(int(c) for c in num2))
|
# caller.py
import receiver
print("caller_haha")
print(__name__)
def test():
print("caller_test can be called!")
def caller_print():
print("I'm caller.py")
if __name__ == '__main__':
caller_print()
test() |
import sys
import numpy as np
import astropy.modeling.fitting
from matplotlib import pyplot as plt
import seaborn as sns
from scipy.interpolate import interp1d
import equation6
import conic_parameters
import theta_ratio_fit
sys.path.append('../conic-projection')
from conproj_utils import Conic
XI_LIST = [None, 1.0, 0... |
# demo02_dtype.py numpy的数据类型
import numpy as np
data=[('zs', [90, 80, 85], 15),
('ls', [92, 81, 83], 16),
('ww', [95, 85, 95], 15)]
# 创建ndarray时,指定dtype
ary = np.array(data, dtype='U2, 3int32, int32')
print(ary[0])
print(ary['f0'])
# 第二种设置dtype的方式
ary = np.array(data, dtype=[('name', 'str', 2),
... |
def read_file(file, Dict):
while True:
string = file.readline()
if not string: break
sub_strings = string.split()
Dict[sub_strings[0]] = int(sub_strings[1])
stock_dict = {}
f1 = open('stock.txt', 'r')
read_file(f1, stock_dict)
f1.close()
input_file = input('보유 주식 파일을 입력하시오 : ')
f2 = open(input_file, 'r')
my... |
from aws_cdk import (
aws_ec2 as ec2,
aws_ecr as ecr,
aws_codecommit as codecommit,
core
)
class DevTools(core.Construct):
@property
def code_repo(self):
return self._code_repo
@property
def ecr_repo(self):
return self._ecr_repo
def __init__(self, scope: core.Cons... |
'''
Chapter 3, Exercise 9
Input: pocket_number, int, 0 -36
Process: Determine what color the roulette pocket number is, by using boolean
and logical operators to determine if the pocket number is odd.
The color may be either black or red
Output: Color of the roulette pocket number entered, print(str... |
# create and define variables
"""name = input("What is your name?: ")
country = input("What country are you from?: ")
age = int(input("How old are you?: "))
hourly_wage = int(input("What is your hourly wage?: "))
satisfied = input("Are you satisfied?: ")
daily_wage = hourly_wage * 8"""
# print variables
#print("My na... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import gzip
import sys
import os
import psycopg2
import time
class Main():
def __init__(self):
print("실행할 메인 클래스")
file_list = self.get_file_dir()
print(file_list)
self.start = time.time()
#self.write_file_to_db(file_list[0])
... |
# Linux example for external capture trigger on econsystems FSCAM_CU135
# By Taylor Alexander, MIT License. Please enjoy, expand, and share.
# Run as root or add a udev rule to give user appropriate rights.
# Note: Hook the hardware trigger input up to an arduino or other device
# with a pin toggling on and off at 10... |
from math import sqrt
limit = 10000000
t = [n*(n+1)/2 for n in xrange(1, limit)]
p = set(n*(3*n-1)/2 for n in xrange(1, limit))
h = set(n*(2*n-1) for n in xrange(1, limit))
isti = [x for x in t if x in p and x in h]
print (-1 + sqrt(1+8*isti[2]))/2
|
c=eval(input("Enter a celsius"))
fah=(c*18/10)+32
print(fah)
|
import pickle
import time
from .rcversion import VersionList, VERSION_FILE
from .path import relative
class VimrcVersionController:
def __init__(self, vimrc_path :str):
self.__vimrc_path = vimrc_path
def __try_load_version_list(self) -> VersionList:
try:
return pickle.load(
... |
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pickle
import os
df = pd.read_csv ("titanic.csv")
def pre_process (df):
d... |
class Solution:
def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
map = {}
for it in rectangles:
key = it[0] / it[1]
value = map.get(key)
if value is None:
value = 0
map[key] = value + 1
count = 0
... |
import logging
from datetime import datetime
import os
import pytest
import sys
from pydriller import Repository, Git
from pydriller.repository import MalformedUrl
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO)
@pytest.fixture
def repo(request):
r... |
import System.Drawing as drawing
import random
import util
import Rhino as rc
import geometry as geo
from colorsys import rgb_to_hls, hls_to_rgb
import scriptcontext as sc
import rhinoscriptsyntax as rs
#Random
def GetRandomNamedColor():
"""Randomly selects a windows color from System.Drawing.Color
Excludes w... |
import requests
import json
import time
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from jupextdemo.const import (CHECKIN_MESSAGE_AKS, APP_NAME_DEFAULT, APP_NAME_PLACEHOLDER,
ACR_PLACEHOLDER, RG_PLACEHOLDER, PORT_NUMBER_DEFAULT,
... |
from LayerProvider import *
from NeuralNet import *
import numpy as np
import matplotlib.image as mpimg
import scipy.misc
from Utils import LoadList
from Trainer import Trainer
from MainLoop import *
import glob
import scipy
from coco_utils import *
from PrepareCOCOData import VGG_preprocess
import pdb
def LoadVGG():
... |
#RBF
import math
import random
import vectorEntrenamiento as vE
import numpy as np
MAX_INT = 100000
class Cluster(object):
"""docstring for Cluster"""
def __init__(self, dimensiones, coordenadas):
super(Cluster, self).__init__()
self.dimensiones = dimensiones
#self.centro = [-1 ] * dimensiones
self.centro... |
from responses.models import Response
from rest_framework import serializers
from .news_org_type import NewsOrgTypeSerializer
from .tool import ToolSerializer
from .tool_task import ToolTaskSerializer
class ResponseSerializer(serializers.ModelSerializer):
news_org_type = serializers.SerializerMethodField()
t... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
'''
Code developed by - Narender Kumar
This code requires Python 3.0, and for other versions, the code will not compile.
Please make sure that all the required contstraints are met in the input text file,
the code will not check for the required constraints. That is 1 ≤ N ≤ 200,000 days
and 1 ≤ K ≤ N days.
This code c... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
class SinaPipeline(object):
def __init__(self):
self.conn = None
self.cursor = None
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import gensim
from crf import CRFDevice, CRF
from conll_vectorizer import Const
class CNNEmbeddings(nn.Module):
def __init__(self, vocab_size, embedding_dim, in_channels, padding_idx=Const.PAD_ID):
super().__init__()
self.vocab_si... |
import numpy as np
import graphlab as gl
from scipy.stats import multivariate_normal
def log_sum_exp(Z):
""" Compute log(\sum_i exp(Z_i)) for some array Z."""
return np.max(Z) + np.log(np.sum(np.exp(Z - np.max(Z))))
def loglikelihood(data, weights, means, covs):
""" Compute the loglikelihood of the data f... |
from sklearn.base import BaseEstimator,BiclusterMixin
class fill_na(BaseEstimator,BiclusterMixin):
def __init__(self,fillna={'fillna_assign_str':None,'fillna_default_str':None}):
self.fillna = fillna
def fit(self,X,y=None):
return self
def transform(self,X,convertList... |
total_price_with_taxes = 0
total_price = 0
total_taxes = 0
while True:
token = input()
if token == "special" or token == "regular":
break
price = float(token)
if price < 0:
print("Invalid price!")
continue
taxes = price * 20/100
total_price += price
total_taxes += ta... |
from django.db import models
from django.utils import timezone
from mywing.angel.models import Angel
class Task(models.Model):
description = models.CharField(max_length=256)
cost = models.FloatField()
owner = models.ForeignKey(Angel, on_delete=models.SET_NULL, null=True, related_name='owned_tasks')
h... |
from django.db import models
class MiningPool(models.Model):
name = models.CharField(
max_length=50
)
url = models.URLField()
def __str__(self):
return f'{self.name}'
class BlockExplorer(models.Model):
name = models.CharField(
max_length=50
)
url = models.URLFiel... |
from pycolate.Percolation import Percolation, PercolationExperiment, CRIT_PROB
from pycolate.CoarseGraining import coarse_graining_estimate, percolates, majority
|
#!/usr/bin/env python3
i = 10000000
def get_sequence_length_and_sum(i, length=0, sum=0):
length += 1
sum += i
if i > 1:
if i % 2:
return get_sequence_length_and_sum(i * 3 + 1, length, sum)
else:
return get_sequence_length_and_sum(i / 2, length, sum)
return leng... |
import os
import sys
import errno
import socket
import logging
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(
os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(
os.path.join(SCRIPT_DIR, PACKAGE_PARENT, PACKAGE_PARENT)))
from src.utils import get_l... |
from camelcase import CamelCase
c = CamelCase()
txt = "a aa aaa aaaaa aa a aaa a aaa a_b a.aa am is be go"
print(c.hump(txt))
|
from gui.MainApp import MainApp
MainApp().run()
|
def total_bill(s):
num = s.count('r')
return num * 2 if num <5 else (num - num // 5) * 2
'''
Sam has opened a new sushi train restaurant - a restaurant where sushi is served
on plates that travel around the bar on a conveyor belt and customers take the plate that they like.
Sam is using Glamazon's new visual ... |
# (c) 2016-2017 Continuum Analytics, Inc. / http://continuum.io
# All Rights Reserved
import re
from os.path import join
from distutils.core import setup
# read version from anaconda_verify/__init__.py
pat = re.compile(r'__version__\s*=\s*(\S+)', re.M)
data = open(join('anaconda_verify', '__init__.py')).read()
versi... |
import unittest
from katas.beta.first_character_that_repeats import first_dup
class FirstDuplicateTestCase(unittest.TestCase):
def test_none(self):
self.assertIsNone(first_dup('like'))
def test_none_2(self):
self.assertIsNone(first_dup('bar'))
def test_equals(self):
self.assertE... |
'''
class Shape(object):
pass
class Triangle(Shape):
def draw(self):
print("三角形")
class Square(Shape):
def draw(self):
print("正方形")
s1 = Triangle()
s2 = Square()
s1.draw()
s2.draw()
'''
class Shape(object):
def draw(self):
raise NotImplementedError
... |
import csv
import numpy as np
import matplotlib.pyplot as plt
import math
import scipy.stats
from math import *
from scipy import interpolate
import scipy.signal
from scipy.integrate import simps
thresholds = np.arange(70)
def heaviside(actual):
return thresholds >= actual
def erfcc(x):
"""Complementary erro... |
class Solution(object):
def isValid(self, s):
open_stack = []
for char in s:
if char in ['(', '{', '[']:
open_stack.append(char);
elif char in [')', '}', ']']:
if len(open_stack) == 0: return False
should_match = open_stack.pop(... |
# Python program to reverse the user provided input
#Accept a word from user and save it in word variable
word = input("Input a word to reverse: ")
for char in range(len(word) - 1, -1, -1):
print(word[char], end="")
#Print the word in reverse format
print("\n") |
import re
import sys
import requests
import socket
from struct import *
socket.setdefaulttimeout(10000)
reload(sys)
sys.setdefaultencoding("utf-8")
def visitPhones(phone_url, phone_id):
result = []
headers = {
'User-Agent': 'Mozilla/5.0'
}
response = requests.get(phone_url, headers= headers)
if response.... |
import hashlib
import pymongo
import random
from pymongo.errors import DuplicateKeyError, PyMongoError
import string
from blog.repo import errors
__author__ = 'tyerq'
class User:
"""
Users DAO Class
"""
def __init__(self, db):
self.db = db
self.coll = self.db.users
def validate_... |
"""
Heber Cooke 10/8/2019
Chapter 2 Exercise 10
The Credit Plan calculates the payments for the life as a loan
with a 10% down payment and payments 5% of price after down payment
annual interest rate of 12%
input: price of item
output: table
month number (start at 1)
current total balance owed
intrest ow... |
# Generated using https://godot-build-options-generator.github.io
optimize = "size"
disable_advanced_gui = "yes"
deprecated = "no"
minizip = "no"
module_arkit_enabled = "no"
module_bmp_enabled = "no"
module_bullet_enabled = "no"
module_camera_enabled = "no"
module_csg_enabled = "no"
module_dds_enabled = "no"
module_en... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('query', '0016_auto_20160203_1324'),
]
operations = [
migrations.AddField(
model_name='daystatistic',
... |
"""Device HA Pair Services Classes."""
import logging
from .ftddevicehapairs import FTDDeviceHAPairs
from .ftddevicehapairs import DeviceHAPairs
from .failoverinterfacemacaddressconfigs import FailoverInterfaceMACAddressConfigs
from .failoverinterfacemacaddressconfigs import DeviceHAFailoverMAC
from .monitoredinterfac... |
from rest_framework import serializers
from .models import SongGroup, Song, SongList
from django.shortcuts import get_object_or_404
from users.models import User
class SongGroupSerializer(serializers.ModelSerializer):
class Meta:
model = SongGroup
fields = ["id", "name", "user_id" ]
extra... |
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'LotteryKiller.settings')
django.setup()
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
import numpy as np
import pandas as pd
from django.forms.models import model_to_dict
from killer.models import Re... |
import logging
from restless.dj import DjangoResource
from restless.preparers import FieldsPreparer
from restless.exceptions import BadRequest
from django.db import IntegrityError
from postmon.responser import PostmonResponse
from zipcodes.models import ZipCode
# Get an instance os a logger
logger = logging.getLog... |
import re
freq = {}
def get_and_process_input():
unprocessed_data = input("Enter the data in given format CL1-CL2=f,CL2-CL3=f1 eg:(100-200=40,200-300=10): ")
split_unprocessed_data = unprocessed_data.split(',')
for a in split_unprocessed_data:
pattern = r"^([0-9]*)-([0-9]*)=(\d*\.?\d*|[0-9]+)$"
... |
"""structure models"""
class Products:
"""product model"""
def __init__(self, product_name, category, unit_price, quantity, measure):
self.product_name = product_name
self.category = category
self.unit_price = unit_price
self.quantity = quantity
self.measure = measure
cl... |
import itertools
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from fit_d2p import vddm_params, tdm_params, Tdm, Vddm, model_params, mangle_tau, actgrid
import hikersim
from hikersim import braking_spec
import scipy.optimize
import scipy.interpolate
#START_TIME = -3
#END_TIME = 20
leader_start... |
import unittest
from hylite.project import Camera
from hylite.reference.spectra import R90
from hylite.correct.panel import Panel
import numpy as np
from tests import genHeader, genCloud, genImage
class TestHyData(unittest.TestCase):
def test_header(self):
#load header from file
header = genHeade... |
# _*_ coding: utf-8 _*_
import django_filters
from .models import Goods
from django.db.models import Q
class GoodsFilter(django_filters.rest_framework.FilterSet):
'''Pdocut filter'''
pricemin = django_filters.NumberFilter(field_name='shop_price', help_text="lower bound of price", lookup_expr='gte')
price... |
"""Test universal resolver with http bindings."""
from typing import Dict, Union
import pytest
from asynctest import mock as async_mock
from aries_cloudagent.resolver.base import DIDNotFound, ResolverError
from universal_resolver import resolver as test_module
from universal_resolver.resolver import UniversalResolve... |
import unittest
def remove(s):
ss = '.'
for c in s:
previous = ss[-1]
if previous != c and c.upper() == previous.upper():
ss = ss[:-1]
else:
ss += c
return ss[1:]
class TestStringMethods(unittest.TestCase):
def test(self):
self.assertEqual( remove('aA'), '')
self.assertEqual( remove('abBA'), '')... |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. ... |
#The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143 ?
number=int(input('Enter the number: '))
factor=2
while factor*factor<number:
while number%factor==0:
number=number/factor
factor+=1
print(number)
|
# config/__init__.py
# Copyright (C) 2011-2014 Andrew Svetlov
# andrew.svetlov@gmail.com
#
# This module is part of BloggerTool and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from .config import Config
__all__ = ['Config']
|
import warnings
from typing import Any, Tuple, Union
from phiml.math import wrap, expand, non_batch, extrapolation, spatial
from phi import math
from phi.geom import Geometry, GridCell, Box, Point
from ._field import SampledField, resample
from ..geom._stack import GeometryStack
from phiml.math import Tensor, instanc... |
import berserk
import json
from Game import Game
import os
with open("./envs.json", "r") as f:
TOKEN = json.load(f).get("lichess_token")
session = berserk.TokenSession(TOKEN)
bot = berserk.clients.Bots(session)
users = berserk.clients.Users(session)
def game_listener():
for event in bot.stream_incoming_eve... |
lista = [1,2,3,4]
soma = 0
soma = (lista[0]*10) +(lista[1]*10)+(lista[2]*30)+(lista[3]*50)
media = soma/100
print(media)
|
#!/usr/bin/env python
#Bao Dang
#Assignment 2
class node:
def __init__(self):
self.label = None
self.leftmost_child = None
self.right_sibling = None
self.parent = None
class tree:
def __init__(self):
self.cellspace = [None]*maxnodes
self.root = Non... |
# -*-coding:utf-8-*-
#线程之间的通信。(我们都知道线程之间是数据共享的)
import threading,queue
def run():
q.put('测试')
if __name__ == '__main__':
q = queue.Queue()
p = threading.Thread(target=run,)
p.start()
print(q.get()) |
tenThings = "Apples Oranges Crows Telephone Light Sugar"
print(tenThings)
print("Need more items")
stuff = tenThings.split(" ")
more = ["Day","night","Song","Frisbee","Corn","Banana"]
print(stuff)
# for stuff in more: #code doesnt work whren this line run.
# print(stuff)
while len(stuff) != 10:
nextOne =... |
from flask import Flask, request, render_template
import codecs, pymysql
from datetime import date
app = Flask(__name__)
@app.route("/")
def show():
return render_template("main.html")
@app.route('/result', methods=["POST", "GET"])
def result():
connection = pymysql.connect(
host='database-1.cop2pvzm3... |
'''7. По длинам трех отрезков, введенных пользователем,
определить возможность существования треугольника,
составленного из этих отрезков.
Если такой треугольник существует, то определить, является ли он
разносторонним, равнобедренным или равносторонним. '''
a = int(input('Введите сторону a: '))
b = int(input('... |
from selenium import webdriver
from bs4 import BeautifulSoup
driver = webdriver.Chrome("/mnt/c/Users/Peter/Documents/setup/chromedriver")
driver.get("http://www.dividend.com/ex-dividend-dates.php?from_filter=yes&ex_div_date_min=2018-01-11&ex_div_date_max=2018-01-11&common_shares=on&preferred_shares=on&adrs=on&etns=on&... |
"""
Ablation study to test the effect of the % of training data on precision and recall.
Run several times and save the output to a pandas frame
"""
from comet_ml import Experiment
import keras
import tensorflow as tf
import sys
import os
from datetime import datetime
import glob
import pandas as pd
import copy
impor... |
# Generated by Django 3.1.7 on 2021-03-14 00:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0012_auto_20210313_0040'),
]
operations = [
migrations.CreateModel(
name='Client',
... |
from tools import Calaculation
import math
calc = Calaculation()
print('=========================================')
print('支持常用三角函数以及反函数(tan,sin,cos)\t支持括号优先级运算\n支持乘方及开方\tpi=π')
while True:
result = calc.main(input('>>').replace('pi',str(math.pi)))
# if len(result)>10:
# print('结果过长,自动四舍五入..')... |
#ASSIGNMENT15
#QUESTION:1 Extract the user id, domain name and suffix from the following email addresses.
# emails = "zuck26@facebook.com" "page33@google.com"
# "jeff42@amazon.com"
# desired_output = [('zuck26', 'facebook', 'com'), ('page33', 'googl... |
exports = [] #__:skip
require = None #__:skip
App = require("./App")['default']
vue = require("vue")
app = vue.createApp(App)
exports['default'] = app.mount("#app")
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
import sys
import cuisine
from fabric.api import run as _run
from fabric.api import sudo as _sudo
from fabric.api import put as _put
from fabric.api import local, get, env
from revolver import contextmanager as _ctx
from revolv... |
import torch
import torch.nn as nn
import numpy as np
import argparse
class BasicBlock(nn.Module):
# For Resnet18 or34
expansion = 1
def __init__(self, in_channel, out_channel, stride=1):
super(BasicBlock, self).__init__()
# Main branch of the BasicBlock
self.basic = nn.Sequential... |
from __future__ import absolute_import
from docutils import nodes
from docutils.parsers.rst import Directive, directives
import loremipsum
class LoremIpsumNode(Directive):
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
option_spec = {}
sent... |
N = int(input())
if N == 1:
print(N, end='\r\n')
elif N == 2:
print(N, end='\n')
elif N == 3:
print(N, end='\n\r')
elif N == 4:
print(N, end='\n\n')
elif N == 5:
print(N, end='\r')
elif N == 6:
print(N, end=' ')
|
from os import environ
from fastapi_plugins import RedisSettings
class AppSettings(RedisSettings):
api_name: str = 'fun_box'
config = AppSettings()
|
def readNumber(line, index):
number = 0
while index < len(line) and line[index].isdigit():
number = number * 10 + int(line[index])
index += 1
if index < len(line) and line[index] == '.':
index += 1
keta = 0.1
while index < len(line) and line[index].isdigit():
number += int(line[index]) *... |
import atexit
import os
ip = get_ipython()
LIMIT = 100000 # limit the size of the history
def save_history():
"""save the IPython history to a plaintext file"""
histfile = os.path.join(ip.profile_dir.location, "history.txt")
print("Saving plaintext history to %s" % histfile)
lines = []
# get previ... |
import pygame,time,keyboard, random
pygame.init()
screen= pygame.display.set_mode((400,432))
pygame.display.set_caption("Alien_Run")
ball=pygame.image.load(r'alien.png')
enemy=pygame.image.load(r'military.png')
coin=pygame.image.load(r'coin.png')
background=pygame.image.load(r'bg.jpg')
px,py=2,2
d=1
e... |
def part_one():
with open('input') as mass:
result = []
for m in mass:
result.append(int(float(str(m).strip()) / 3) - 2)
sum_of_fuel = str(sum(result))
print(sum_of_fuel)
def part_two():
with open('input') as mass:
result = []
for m in mass:
... |
#
#
#
#Atzamis Iosif, 3094
#Dedousis Andreas , 3018
#Kardoulakis Nikos, 3086
#
#
import socket
import sys
import random
import pickle
import os
import re
import subprocess
import urllib
import time
from Crypto import Random
from Crypto.Cipher import AES
import smtplib
def email_authentication():
gmail_user = 'a... |
# Implementation of the Viterbi Algorithm
"""
viterbi_algo.py: Viterbi Algorithm
Decoding: Given as input an HMM with two hidden states (A, B) and
an observation sequence O, find the most probable sequence of states
Q = q1q2q3q4...qT
Author: Dung Le (dungle@bennington.edu)
Date: 10/17/201... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.