text stringlengths 8 6.05M |
|---|
#coding=utf-8
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer, BaseSerializer, Serializer
from drf_writable_nested import WritableNestedModelSerializer
from TestOnline.models import User
from TestOnline.models import *
class FormatDataTimeField(BaseSerializer):
def to... |
import sys
from itertools import permutations
if __name__ == "__main__":
'''
Given: A positive integer n≤7.
Return: The total number of permutations of length n, followed by a list of all such permutations (in any order).
'''
n = int(sys.stdin.read().splitlines()[0])
permutations = list(permuta... |
# Generated by Django 2.2.3 on 2019-11-01 19:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basket', '0003_auto_20191102_0131'),
]
operations = [
migrations.AlterField(
model_name='order',
name='customer_emai... |
# Generated by Django 3.0.7 on 2020-10-12 10:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cl_app', '0005_auto_20201012_0655'),
]
operations = [
migrations.AlterField(
model_name='sitegroup',
name='code',
... |
# https://www.hackerrank.com/challenges/2d-array/problem
# Complete the hourglassSum function below.
def hourglassSum(arr):
result = []
for i in range(len(arr)-2):
for j in range(len(arr)-2):
total = 0
for k in range(i, i+3):
for l in range(j, j+3):
... |
#substruct two numbers
#author Angelina B
#reads input and converts it into float
a = float(input("Please enter first number: "))
b = float(input("Please enter second number: "))
print("{} minus {} is {}".format(a, b, a-b)) |
# Problem
# There are N houses for sale. The i-th house costs Ai dollars to buy. You have a budget of B dollars to spend.
# What is the maximum number of houses you can buy?
# Input
# The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a single line containin... |
import OpenPNM
class SGL10Test:
def setup_class(self):
self.net = OpenPNM.Network.Cubic(shape=[3, 3, 3])
self.geo = OpenPNM.Geometry.SGL10(network=self.net,
pores=self.net.Ps,
throats=self.net.Ts)
|
from django.shortcuts import render
from DB_Crawling import route_table
# Create your views here.
def route_table(request):
routTable = route_table()
return render(request, 'cTable/cTable.html', rout_table) |
def length_words(string):
string = string.lower()
repl = ",.?!"
for i in repl:
string = string.replace(i, "")
string = string.split()
dic = {}
#print(string)
for word in string:
word_length = len(word)
dic[word_length] = []
if word_length in dic:
... |
from werkzeug.security import check_password_hash
class User:
def __init__(self, username, email, password):
self.username=username
self.email=email
self.password=password
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymou... |
#import sys
#input = sys.stdin.readline
def main():
N, X = map( int, input().split())
L = list( map( int, input().split()))
ans = 1
now = 0
for i in range(N):
now += L[i]
if now > X:
break
ans += 1
print(ans)
if __name__ == '__main__':
main()
... |
import pytest
import Triangulo
#Exemplo de teste 1(simples sem criar classes)
'''def testa_perimetro():
t = Triangulo.Triangulo(1,1,1)
assert t.perimetro() == 3'''
#Exemplo de teste 3
'''@pytest.mark.parametrize("entrada, esperado", [
((1,1,1),(3)),
(),
(),
()
])'''
... |
import numpy
import math
import matplotlib.pyplot as pyplot
import pyfits
fits = pyfits.open("nr29.fits")
image = fits[0].data
t = numpy.arange(image.shape[0])
print "Loaded data"
def load(image, quadrant):
if quadrant == 1:
image_subset = image[:, :, 1024:1536]
if quadrant == 2:
image_subset = image[:, :... |
from django.apps import AppConfig
class MyappConfig(AppConfig):
name = 'myapp'
def ready(self):
# Makes sure all signal handlers are connected
from myapp import handler # noqa
|
# -*- coding: utf-8 -*-
# @Author : 赵永健
# @Time : 2020/1/8 13:20
# -*- coding: utf-8 -*-
# 本地图片在html中显示
import os
import re
import base64
import time
def findimg(content):
'''
查找网页中所有的img,类似img src='1.png',返回1.png
:param content: 网页内容
:return: 返回找到的所有图片文件名列表
'''
patt = re.compile("<img s... |
import struct
import os
UTF_16 = 'UTF-16-LE'
class DBError(Exception):
pass
class Field(object):
def __init__(self, name, dtype, to_py=None, to_db=None):
self.name = name
self.dtype = dtype
self.to_py = to_py
self.to_db = to_db
self.value = None
def __setattr_... |
file = open('writexample.txt', 'w')
file.write('Line 1\n')
file.close()
file = open('writexample.txt', 'a')
file.write('Line 2\n')
file.close()
|
import math
import collections
import aer
import warnings
def get_lprob(s_word, t_word, lprobs):
return lprobs[s_word].get(t_word, 0) #prob 0 if s/t word do not co-occur in training
def source_dependencies(s_sentence, t_word, t_pos, t_length, lprobs, jump_probs):
s_length = len(s_sentence)
jump_probs... |
from django.core import validators
from django import forms
from .models import Patient
class Register_patient(forms.ModelForm):
class Meta:
model = Patient
fields = ['patient_name','patient_code','complain','gender','address']
widgets= {
'patient_name' : forms.TextInput(attrs... |
#!/usr/bin/env python
import sys, collections, random
from tcc import tcc
tag_whitelist = (
'RB', 'CD', 'VB', 'VBD', 'VBG', 'VBZ', 'JJ', 'JJR', 'JJS',
'NN', 'NNS', 'NNP', 'NNPS'
)
tag_whitelist_phrases = ('JJ', 'NNP', 'NNPS', 'VB', 'NN', 'CD')
word_blacklist = (
'be', 'is', '\'s', '(', ')', 'was', 'n\'t'... |
import numpy as np
from scipy.stats import hypergeom
# n - unknown population size
# Desired confidence level
p = 95/100
# Marked in first group
m = 24
# Caught in second group
c = 19
# Tagged in second group
t = 3
print("Lincoln-Petersen estimator = ",(m*c/t))
print("Chapman estimator = ",((m+1)*(c+1)/(t+1)-1))
l... |
#! /usr/bin/python
print 'Content-type: text/html'
print ''
for i in range(11):
print i
for i in range (5, 21):
print i
myFoodList = ["pizza", "chicken", "chocolate"]
for food in myFoodList:
print "I like eating " + food + " . "
x = 0
while x <= 10:
print x
x... |
from flask import Flask, render_template, request, flash, redirect, session, jsonify
from werkzeug.security import generate_password_hash as passgen
from werkzeug.security import check_password_hash as passcheck
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import os
... |
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
# carrega datasets
ds_l = pd.read_csv('grpc_metrics_localhost.csv')
ds_r = pd.read_csv('grpc_metrics_192.168.0.109.csv')
ds_rpyc = pd.read_csv('rpyc_metrics_localhost_2.csv')
ds_rpyc_r = pd.read_csv('rpyc_metrics_192.168.0... |
r=int(input())
print(3.141592653589793*(r**2)) |
from conf import all as conf
|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 24 22:18:50 2017
@author: JATIN
"""
import zipfile
import pandas as pd
import urllib.request, urllib.error, urllib.parse
from bs4 import BeautifulSoup
from datetime import datetime
from dateutil.parser import parse
def sec_dataframe():
#Set variable for... |
# Generated by Django 2.2.3 on 2019-07-04 15:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('budget', '0037_remove_account_bank'),
]
operations = [
migrations.DeleteModel(
name='Bank',
),
]
|
from django.contrib import admin
from .models import Image, WebPage, AsyncResults
@admin.register(WebPage)
class WebPageAdmin(admin.ModelAdmin):
pass
@admin.register(Image)
class ImagePageAdmin(admin.ModelAdmin):
pass
@admin.register(AsyncResults)
class AsyncResultAdmin(admin.ModelAdmin):
pass
|
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Book, User
engine = create_engine('postgresql:///books')
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bin... |
from translationstring import TranslationStringFactory
_ = TranslationStringFactory('onegov.gazette')
|
#!/usr/local/bin/python
from ROOT import *
import subprocess
import os
import sys
XrayInDir = sys.argv[1]
def placeHRFiles():
for f in os.listdir(XrayInDir + '/000_FPIXTest_p17'):
if 'hr' in f and 'root' in f and 'NoCal' not in f:
hrdig = list(f)[2] + list(f)[3]
hrVal = int(hrdig)/5 + 1
hrDir ... |
__author__ = 'ryan@barnett.io'
#python makes this efficient with string slicing
def reverse_string(string):
return string[::-1] |
import os
import torch
from models import model_utils
from utils import eval_utils, time_utils
import numpy as np
def get_itervals(args, split):
if split not in ['train', 'val', 'test']:
split = 'test'
args_var = vars(args)
disp_intv = args_var[split+'_disp']
save_intv = args_var[split+'_save'... |
import json
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import expit as sigmoid
from sklearn.utils import shuffle
from datetime import datetime
from scipy.spatial.distance import cosine as cos_dist
from sklearn.metrics.pairwise import pairwise_distances
from glob import glob
import os... |
from onegov.user.auth.core import Auth
__all__ = ('Auth', )
|
from adapters.dimmable_bulb_adapter import DimmableBulbAdapter
immax_adapters = {
'IM-Z3.0-DIM': DimmableBulbAdapter, # Immax LED E14/230V C35 5W TB 440LM ZIGBEE DIM
} |
import lxml.etree as ET
from lxml.builder import E as B
def buildPerson(personid ,firstname, lastname, title, address, street, zipcode, city, country, day, month, year):
root = B.person(
B.firstname(firstname),
B.lastname(lastname),
B.title(title),... |
from stnu import NamedStnu
from fast_dc import DcTester
def main():
network = NamedStnu()
network.read_from_stdin()
dc_tester = DcTester(network)
print 'dc' if dc_tester.is_dynamically_controllable() else 'notdc'
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
# client.py
# 要测试这个服务器程序,我们还需要编写一个客户端程序:
# 导入socket库:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
s.connect(('127.0.0.1', 7777))
# 接收欢迎消息:
print(s.recv(1024).decode('utf-8'))
for data in [b'shisan', b'luckypot', b'lakiGuo']:
# 发送数据:
s.send(data)
print(... |
import string
import random
from django.db import models
from .enum import SexEnum, NationalityEnum
class School(models.Model):
name = models.CharField(max_length=20)
maximum_student = models.PositiveIntegerField(default=1000)
def __str__(self):
return self.name
class StudentQuerySet(models.Que... |
import requests
from allauth.socialaccount import providers
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import SchedulePic... |
import math
num_rows=int(input("enter the no of rows:"))
if num_rows%2 ==0:
print('enter a valid odd number')
else:
k=1
num = num_rows/2
upper = math.ceil(num)
for rows in range(0,upper):
for coloumn in range(k):
print("*", end=" ")
k=k+2
print()
k=k-4
for row... |
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
pCur = head
pRev = None
while pCur:
pTemp = pCur
pCur = pCur.next
... |
from django.forms import ModelForm
import pytest
from ..schema_fields import BooleanField, CharField, ObjectField
from .mock_app.models import RecordShop
@pytest.fixture
def scooby_doo():
return {'name': 'Scooby Doo', 'breed': 'Daschund'}
@pytest.fixture
def snoopy():
return {'name': 'Snoopy', 'breed': 'Be... |
'''
Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.
For example,
Given the tree:
4
/ \
2 7
/ \
... |
from PIL import Image
import requests
from io import BytesIO
# Some sample token. Instead replace with the token returned by authentication endpoint
JWT_TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0IiwiaWFkIjoxLCJhY3AiOm51bGwsInRicCI6bnVsbCwiaWF0IjoxNTg4MTgzMjg5LCJleHAiOjE1ODgxODY4ODl9.PK1gZswB1_dzV13... |
import CAL
'''def main():
# my code here
#menu
print "menu (please select an option)"
print "1-test gui"
print "2-quit"
num = raw_input('enter a number: ')
if num == '1':
gui = GUI.GUI()
gui.run_GUI()
print "im in 1"
elif num == '2':
print "im in 2"
quit()
if __name__ == "__main__":
... |
from bert_serving.client import BertClient
import numpy as np
with open('wordList.txt', 'r', encoding='utf-8') as f:
words = []
for line in f.readlines():
line = line.strip('\n') # 去掉换行符\n
b = line.split(' ') # 将每一行以空格为分隔符转换成列表
def not_empty(s):
return s and s.strip()
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import tagged, common
from odoo.tools.misc import formatLang
import time
from odoo import fields
from odoo.addons.account.tests.account_test_no_chart import TestAccountNoChartCommon
from odoo.addons.accou... |
import tensorflow as tf
import util.TensorflowUtils as tu
from util.dataLoader import loadNormalData
from util.Util import Normalize, DummyCM
def train(loss_val, var_list, lr, max_grad):
optimizer = tf.train.AdamOptimizer(lr, beta1=0.9)
grads, _ = tf.clip_by_global_norm(tf.gradients(loss_val, var_list), max_gr... |
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.datasets import SupervisedDataSet
from pybrain.structure import FeedForwardNetwork, LinearLayer, SigmoidLayer,FullConnection
import fitsio
import numpy as np
import time
import pickle
import sys
sys.path.insert(0, '../')
from redshift_utils import na... |
import numpy as np
from bresenham import bresenham
import scipy.ndimage
from PIL import Image
def mydrawPNG(vector_image, Side = 256):
raster_image = np.zeros((int(Side), int(Side)), dtype=np.float32)
initX, initY = int(vector_image[0, 0]), int(vector_image[0, 1])
stroke_bbox = []
pixel_length = 0
... |
number = int(input())
numbersToText = []
numbersToText[0:9] = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
try:
print(numbersToText[number])
except IndexError:
print("number too big")
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
try:
from rpython.rlib.rarithmetic import ovfcheck, LONG_BIT # pylint: disable=W
from rpython.rlib.rbigint import rbigint, _divrem as divrem # pylint: disable=W
from rpython.rlib.rbigint import rbigint as BigIntType # pylint: disable=W
from rpython.rlib.rarithmetic import string_to_int # pylint: dis... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
#importing dataset
dataset=pd.read_csv('Salary_Data.csv')
X=dataset.iloc[:,:-1].values
y=dataset.iloc[:,1:].values
#splitting the dataset into training and test sets
from sklearn.model_selection i... |
"""create table organizations
Revision ID: 538755761e27
Revises:
Create Date: 2020-10-09 11:30:40.155436
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "538755761e27"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_tab... |
import os
def confirm_move_forward(message):
move_forward = 'n'
while move_forward.lower() != 'y':
move_forward = input('{0} (y)'.format(message))
confirm_move_forward('Make bot message files?')
######################################
# MAKE THE BOT MESSAGE AND LOG FILES #
############################... |
#packing and unpacking
#Create packed tuple
pair = ("dog","cat",)
#unpack tuple
(key, value) = pair
#display
print(key)
print(value) |
import os
import time
source = [r'D:\Backup\phone', r'E:\Dropbox\Photos']
target_dir = 'd:/backup/'
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip -qr '%s' %s" % (target, ''.join(source))
print zip_command
if os.system(zip_command) == 0:
print 'Successful backup ... |
# Generated by Django 2.2.11 on 2020-06-01 19:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wishlist', '0010_auto_20200413_1512'),
]
operations = [
migrations.CreateModel(
name='WishlistDpModel',
fields=[
... |
from flask import Flask, render_template,request
from flask_sqlalchemy import SQLAlchemy
import mysql.connector as sql
import pandas as pd
import sqlite3
#import pyodbc
import sqlalchemy as sa
import pymysql
target = sa.create_engine(f'mysql://sql6424418:kZPRYYclcY@sql6.freemysqlhosting.net/sql6424418')
app... |
# coding = UTF-8
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
import datetime
import re
import lp2_while
import planet
import bot_constants
import mycalc
logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s',
level=logging.INF... |
#!/usr/bin/python
# This is a sentence rectangle
# Author: Eason
sentence = raw_input("Input your sentences:")
screen_width = 120
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width) // 2
print
print ' ' * left_margin + '+' + '-' * (box_width - 6) + '+'
print ' ' * left_margin ... |
import requests
import pprint
pp = pprint.PrettyPrinter()
class Token:
def __init__(self):
self.token = None
self.expires_in = None
self.active = False
self.code = None
self.access_token = None
self.refresh_token = None
def get_token(self):
return self... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import web
import sys
import kenlm
import json
if len(sys.argv) < 3:
print >>sys.stderr, "Usage: server.py port lm-path"
lm_path = sys.argv[2]
sys.stderr.write("Loading language model from %s..." % lm_path)
lm = kenlm.LanguageModel(lm_path)
sys.stderr.write("Done.\n... |
from poyonga.client import Groonga
from poyonga.result import GroongaResult
__version__ = '0.1.4'
|
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
# Load model that was previously created
model = tf.keras.models.load_model('digits_detect.model')
# Runs model prediction for each image file in the directory
for num in os.listdir():
if ".png" in num:
# Uses ... |
import FWCore.ParameterSet.Config as cms
source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(
'/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R2_HISTATS/outfile14TeVSKIM_100_1_PiG.root',
'/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R2_HISTATS/outfile14TeVSKIM_101_1_LBd.root',
'/store/... |
user = {
'first_name': str,
'last_name': str,
'username': str,
'password': str
}
login_user = {
'username': str,
'password': str
}
|
import logging
import os
import subprocess
from src.definitions import INPUT_APK_DIR, DECODED_APK_DIR
logger = logging.getLogger(__name__)
DIR = os.path.dirname(os.path.abspath(__file__))
def disassemble_apk(apk_name):
input_apk = INPUT_APK_DIR + apk_name + ".apk"
output_path = DECODED_APK_DIR + apk_name
... |
from django import forms
from doctor import constants
from doctor.models import AvailableTime
class ScheduleAppointmentForm(forms.Form):
"""
Form for schedule appointment
"""
start_date = forms.DateInput(label='Start Date', format=('%d-%m-%Y'))
no_of_days = forms.IntegerField(label="Number of Days... |
print("Enter your name")
n=raw_input()# Greetings
print("Hello "+ n)
|
from __future__ import print_function
from twisted.internet.defer import inlineCallbacks
from autobahn import wamp
from autobahn.twisted.wamp import ApplicationSession
class ControllerBackend(ApplicationSession):
def __init__(self, config):
ApplicationSession.__init__(self, config)
@inlineCallbacks... |
from agents.common import PLAYER1, PLAYER2
def test_auto_rematch():
from agents.agent_mlp.mlp_training.auto_rematch import auto_rematch
from agents.agent_random import generate_move as random_move
import numpy as np
n_matches = 100
boards, moves, a_wins = auto_rematch(random_move, random_move, n... |
# Copyright 2016 Husky 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 law or agreed to in writing, softw... |
# protest.py
# by aaron montoya-moraga
# march 2017
# to distribute, on terminal do
# python setup.py sdist
# from distutils.core import setup
from setuptools import *
from codecs import open
from os import path
# taken from https://tom-christie.github.io/articles/pypi/
here = path.abspath(path.dirname(__file__))
... |
__all__ = ['UserSerializer', 'EditUserSerializer', 'GroupSerializer']
from django.contrib.auth.models import Group
from extuser.models import ExtUser
from rest_framework import serializers
from helpers import roles
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = ExtUser
fi... |
string1 = str(input('Please enter a first string: '))
string2 = str(input('Please enter a second string: '))
#First case, the first string is longer.
if len(string1) > len(string2):
print('The first string, {0}, is the longest of the two'.format(string1))
#Second case, the second string is longer.
elif len(string2... |
#Número 84
i = 0
nome_peso = list()
lista = list()
while(i == 0):
del nome_peso[:]
nome_peso.append(input('Digite o nome:'))
nome_peso.append(int(input('Digite o peso:')))
lista.append(nome_peso[:])
i = int(input('Digite 0 para adicionar mais pessoas!'))
total = len(l... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
'''
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime,
contains 21 ... |
# -*- coding: utf-8 -*-
from http import HTTPStatus as statuses
import flask
from sqlalchemy import desc
from ...result import make_result
from ...utils import api_location
from ...resource import ApiResource
from ...utils import paginated_query
from ....database import schema as db
VERSION = 1
resource = ApiRes... |
import json
import requests
import sys
query = input("Enter an IP or Domain name: ")
endpoint = f"http://ip-api.com/json/{query}"
if query == '': #Conditia daca valoarea de la input lipseste
print("Value error")
sys.exit() #Terminates the program immediatly
response = requests.get( endpoint )
data... |
"""
TFeat Implementation
Author: Alex Butenko
"""
import sys
import os
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import cv2
from features.DetectorDescriptorTemplate import DetectorAndDescriptor
import features.feature_utils as utils
dirname = os.path.dirname(__file__)
clas... |
"""
Primitive types and type conversions.
"""
import math
from itertools import izip_longest
from .exceptions import ESTypeError, ESSyntaxError
from .literals import NumberLiteralParser
NaN = float('nan')
inf = float('inf')
sign = lambda x: math.copysign(1, x)
MASK16 = (2 ** 16) - 1
MASK32 = (2 ** 32) - 1
class Typ... |
from django.contrib import admin
from .models import Beach, SelectedBeach
admin.site.register(Beach)
admin.site.register(SelectedBeach)
|
"""
תשע"ב מועד א' שאלה 5
"""
import numpy as np
from numpy import random as rn
import scipy.stats as ss
#Black and Scholes
def d1(S0, K, r, sigma, T):
return (np.log(S0/K) + (r + sigma**2 / 2) * T)/(sigma * np.sqrt(T))
def d2(S0, K, r, sigma, T):
return (np.log(S0 / K) + (r - sigma**2 / 2) * T) ... |
import datetime
import logging
from typing import Any, Dict, List, Tuple
import flask_restless
import gunicorn.app.base
from dbcat import Catalog
from dbcat.catalog import CatColumn
from dbcat.catalog.db import DbScanner
from dbcat.catalog.models import (
CatSchema,
CatSource,
CatTable,
ColumnLineage,
... |
import os
import logging
import pandas as pd
from pathlib import Path
from cropcore.model_data_access import (
insert_model_run,
insert_model_product,
insert_model_predictions,
get_sqlalchemy_session,
)
# relative or non-relative imports, depending on where we run from :-/
if os.getcwd() == os.path.di... |
from forest import RandomForest
from kneighbors import KNeighbors
from linear import LinearModel, RidgeModel
from svr import SVRModel
|
import unittest
from lib.workflow.workflow_runner import WorkflowRunner
from lib.exception.file_format_exception import FileFormatException
from mockito import Mock, verify, when, any, inorder
from mock import mock_open, patch, Mock as mock_Mock
class WorkflowRunnerTest(unittest.TestCase):
def setUp(self):
... |
#-*- coding:utf8 -*-
__author__ = 'meixqhi'
import re
import json
from django.core.urlresolvers import reverse
from djangorestframework.views import ModelView
from djangorestframework.response import ErrorResponse
from djangorestframework import status
from shopback.orders.models import Order,Trade
from shopback.trade... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("custom.html")
if __name__ == "__main__":
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.run(debug=True)
|
"""
Convert CSV language file to JS and PY files
"""
import sys
import csv
SEPERATE_FIELD = ';'
CLIENT_LANG = 'lang.js'
SERVER_LANG = 'i18n.py'
FILE = sys.argv[1]
FIRST = True
LANG_DICT = []
with open(FILE, 'rb') as csvfile:
LINES = csv.reader(csvfile, delimiter=';', quotechar='"')
for line in LINES:
... |
__all__ = ["create2api","configGenerator"] |
print("hello")
a=input("please enter no;")
print(a) |
from mnist import MNIST
import numpy as np
import os
from PIL import Image
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
# Import the modules
from sklearn.externals import joblib
from sklearn import datasets
from skimage.feature import hog
from s... |
def main():
edad = int(input("Ingresa tu edad: "))
# Escribe el código adecuado para completar el programa
# Para pedir el dato de la idetificación oficial emplea este mensaje:
# "¿Tienes identificación oficial? (s/n): "
if(edad<=0):
print("Respuesta incorrecta")
elif(edad<18 ):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.