text stringlengths 38 1.54M |
|---|
# derived from test_random_things.py
import py
from ctypes import *
import sys
def callback_func(arg):
42 / arg
raise ValueError(arg)
class TestCallbackTraceback:
# When an exception is raised in a ctypes callback function, the C
# code prints a traceback.
#
# This test makes sure the exceptio... |
class Solution(object):
def findMaxAverage(self, nums, k):
maxV = 0
sumV=0
for idx ,v in enumerate(nums):
if idx==0:
sumV=sum(nums[:k])
maxV=sumV
elif idx+k-1 <len(nums):
sumV=sumV-nums[idx-1]+nums[idx+k-1]
maxV =max(sumV,maxV)
return maxV*1.0/k
sol =Solution()
print sol.findMa... |
import datetime
import locale
import pytz
#Trabajando datetime NOW
dt = datetime.datetime.now()
print(dt)
print(dt.year)
print(dt.month)
print(dt.day)
print(dt.hour)
print(dt.minute)
print(dt.second)
print(dt.second)
print(dt.microsecond)
print(dt.tzinfo)
# Ejemplo de como Mostrar la fecha
print('{}:{}:{}'.format(dt... |
from PyFlow.Core import NodeBase
from PyFlow.Core.Common import *
from copy import copy
class rerouteExecs(NodeBase):
def __init__(self, name):
super(rerouteExecs, self).__init__(name)
self.input = self.createInputPin("in", 'ExecPin')
self.output = self.createOutputPin("out", 'ExecPin')
... |
from django import forms
from django.contrib.auth.models import User
from .models import MakeWord
class FirstForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'password', 'email']
class TranslateForm(forms.Form):
text = forms.CharField(max_length=20, label='Search ')
cl... |
from threading import Thread, Semaphore
import numpy as np
import time
import pandas as pd
import pickle
import sys
import datetime
from kafka import KafkaConsumer, KafkaProducer, TopicPartition
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accura... |
class Pancake(self, eggs, flour, salt, milk, butter):
self.eggs = eggs
self.flour = flour
self.salt = salt
self.milk = milk
self.butter = butter
def portion(eggs, flour, salt, milk, butter):
numEgg = input(int('enter numbers of eggs you got'))
ingredient_basis = {}
ingredient_basis['e... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 17 16:53:55 2021
@author: Doğukan Bozkurt
"""
import animals
# This program demonstrates polymorphism.
def main():
mammal = animals.Mammal('regular animal')
dog = animals.Dog()
cat = animals.Cat()
# Display information about eac... |
class Student:
roll=0
nm=' '
def insert(self):
self.roll=input("Enter Roll Number :")
self.nm=raw_input("Enter your name :")
def disp(self):
print "The Roll Number you inserted :",self.roll
print "The Name you inserted :",self.nm
ob1=[Student() for i in range(3)]
for ... |
"""
You are given a binary tree.
Write a function that returns the binary tree's
node values using an in-order traversal.
Example:
Input: [2,None,3,4]
2
\
3
/
4
Output: [2,4,3]
[execution time limit] 4 seconds (py3)
[input] tree.integer root
[output] array.integer
"""
# Binary trees are alread... |
import curses, os #curses es la interfaz para capturar pulsaciones de teclas en el menú, os lanza los archivos
def get_param(prompt_string,X_pos,Y_pos,screenn):
screenn.addstr(X_pos, Y_pos, prompt_string)
input = screenn.getstr(X_pos, len(prompt_string)+Y_pos, 60)
return input
def Tela_Benvinda():... |
import torch
import numpy as np
import matplotlib.pyplot as plt
import pickle
import advOpt
from poisson_example import Poisson_FIM
##############
##VECTOR FIELD
##############
fim = Poisson_FIM(omega=(2., 1.))
logit_design_grid, eta11_grid = np.meshgrid(np.linspace(-0.65, 0.65, 10),
... |
from random import shuffle
import numpy as np
import config
import asyncio
import ujson as json
from scipy.optimize import linear_sum_assignment
import math
from static import osrm_host
"""
for finding ( distance | duration ) matrix ->
1. brute force
2. bfs and find all with summation => d(vu) = d(vx) + d(xu) ... |
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from collections import Counter
class Training:
def __init__(self, X, Y, X_te, Y_te, net, handler, args):
"""
"""
self.X = X
self.Y = Y
self.... |
from django.contrib import admin
from projects.models import project,users,s_project
from import_export.admin import ImportExportModelAdmin
# Register your models here.
@admin.register(project)
class projectAdmin(ImportExportModelAdmin):
pass
@admin.register(users)
class usersAdmin(ImportExportModelAdmin)... |
import math
import time
# Method to find prime numbers
# Optimized implementation
# Don't worry still not faster than, same implementation of C lang.
def prime(n):
if(n == 1 and n == 2):
return True
if(n > 2 and n % 2 == 0):
return False
divisor = math.floor(math.sqrt(n))
for... |
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
number_of_cookies = models.IntegerField(default=0)
class Tasks(models.Model):
ACTIVE = 'Active'
SNOOZED = 'Snoozed'
COMPLETED = 'Completed'
CANCELED = 'Canceled'
... |
'''EXERCÍCIO 20
O mesmo professor do desafio anterior quer sortear a ordem de apresentação dos trabalhos dos
alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.'''
from random import shuffle
p1 = input('Primeiro nome: ')
p2 = input('Segundo nome: ')
p3 = input('Terceiro nome: '... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import deeptensor as dt
from enum import IntEnum
from enum import IntFlag
class DbgChn(IntFlag):
NONE = 0
STD = 1
NET = 2
DATA = 4
MODEL = 8
TRAIN = 16
VALID =... |
import os
from datetime import timedelta
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
TESTING = True
if TESTING:
UPLOAD_FOLDER = os.path.join(basedir, "storage")
else:
UPLOAD_FOLDER = '/root/uploads'
DATASET_LOCATION = os.path.join(basedir, "storage... |
# -*- coding: utf-8 -*-
"""A Tk scrolled frame containing and handling keywords.
This megawidget displays a list of keywords that the user can add to and also
delete. It provides tab completion as the user types, highlights incorrect
keywords in red and generally helps the user find the keywords they wish.
"""
from ... |
import os
import numpy as np
import pandas as pd
import warnings
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader.data as web
import scipy.stats as st
from datetime import datetime
import matplotlib.pyplot as plt
import cvxopt as opt
import cvxopt.solvers as optsolvers
import finances.... |
from django.conf.urls import url
from .import views
#BASE = 'suelo/'
urlpatterns = [
url(r'index$', views.index, name='index'),
url(r'thiessen$', views.thiessen, name='thiessen'),
# ---------------------------------------------------------------------------------------
# ----------------------------------- JSON ... |
#
# Copyright 2011-2012 Jeff Bush
#
# 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 ... |
"""We’re given an ascending string of integers that represents page numbers.
Write a function get_last_page to return the last page number in the string.
If the string of integers is not in correct page order, return the last number in order. """
def get_last_page(int_string):
cursor = 0
expected_number = 0
... |
# 28. 비밀 지도
def solution(n, arr1, arr2):
answer = []
# 지도 1 2진수 문자열로 바꾼 리스트 ... 9 -> '0b1001'
bi_map1_lst = [bin(i) for i in arr1]
# 지도 1 2진수 문자열 정리한 리스트 ... '0b1001' -> '1001'
map1_lst = []
# 지도 2 2진수 문자열로 바꾼 리스트(지도 1과 같음)
bi_map2_lst = [bin(i) for i in arr2]
# 지도 2 2... |
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
data=np.genfromtxt(path, delimiter=',',skip_header=1)
print("\nData: \n\n", data)
print("\nType of data: \n\n", type(data))
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
census... |
import socket
import threading
import time
class mycgi:
def __init__(self, host='', port=10000, app=None):
if app == None:
assert 'Must be set app'
self.app = app
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
self.sock = sock
... |
import FWCore.ParameterSet.Config as cms
BtagPerformanceESProducer_TTBARMCBTAGCSV = cms.ESProducer("BtagPerformanceESProducer",
# this is what it makes available
ComponentName = cms.string('TTBARMCBTAGCSV'),
# this is where it gets the payload from
PayloadName = c... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright SAS Institute
#
# 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 b... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Sorting:
CREATED_AT = "created_at"
PRICE = "price"
class SortingDirection:
DESCENDING = "desc"
ASCENDING = "asc"
class Processor:
PAYPAL = "paypal"
BITCOIN = "bitcoin"
BANK_WIRE = "bank wire"
|
import pytest
from collections import OrderedDict
from torrent.torrent_file import valid_torrent_path, read_file, decode_raw_data, TorrentFile, generate_torrent_file,\
parse_info, create_tracker, _validate_division_by_20
from os import listdir
import logging
from utilities import _files_list
logger = logging.getLogger... |
''' 2 Liner for HackerRank contraints
for i in xrange(1,int(raw_input())+1):
print ((10**i) / 9)**2
'''
BASE_10 = 10
SQUARE = 2
def repunit(n):
''' Creates repunits
R_n = (10^n - 1) / (10 - 1)
1 = 1, 2 = 11, 3 = 111
'''
return (BASE_10**n) / 9
def demlo_number... |
import streamlit as st
from src import home_page, chart_page
from src.markdown_module import get_markdown
#--- Available Contents
page_home = 'HOME'
page_chart = 'Charts'
page_morningstar = 'MorningStar Dashboard'
page_about = 'About'
pages = (page_home, page_chart, page_morningstar, page_about)
def main():
#--- Ad... |
from django.contrib import admin
# Register your models here.
from .models import Form_1
admin.site.register(Form_1) |
def main():
d = {'Roses': "Red", 'Violets': "blue"}
for key, value in d.items():
print(key, 'is', d[key])
if __name__ == "__main__":
main() |
import os
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
DB_ENGINE = os.environ.get('DB_ENGINE')
DB_CONNECTOR = os.environ.get('DB_CONNECTOR')
DB_USERNAME = os.environ.get('DB_USERNAME')
DB_PASSWORD = os.environ... |
from django.forms import ModelForm, Textarea
from django import forms
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from .models import Comment, GenericLike
class CommentForm(ModelForm):
parent_id = forms.IntegerField(widget = forms.HiddenInput(), initial = -1)
class Meta:
m... |
import pandas as pd
class LicensePlateIdentifier():
def __init__(self, frame, alpr):
self.frame = frame
self.alpr = alpr
pass
def apply_alpr(self):
self.results = self.alpr.recognize_ndarray(self.frame)
def extract_output(self):
i = 0
for plate in self.res... |
import codecs
import configparser
class Location:
__slots__ = ["name", "id"]
def __init__(self, name, id):
assert len(name) <= 3
assert len(id) <= 4
self.name = name
self.id = id
def __str__(self):
return "{:>3}{:>4}".format(self.name, self.id)
class Key:
__s... |
#导入对应的模块
import pandas as pd
import matplotlib
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
#设置全部列显示和浮点数格式
pd.options.display.max_columns=None
pd.set_option('display.float_format',lambda x:'%.6f'%x)
#数据读取
df=pd.read_csv(open(r".\data\customer_data.csv"),encoding='utf-8',index_col=0)
#为了方便分... |
import logging
from PIL import Image, ImageDraw, ImageFont, ImageFilter,ImageOps
import random
import os
logger = logging.getLogger("rotate")
ROTATE_ANGLE = 5 # 随机旋转角度
NUM_IN_DIRECTION = 2 # 每个方向上的数量
classes_name = ["正图","90度","180度","270度"]
degrees = [0,90,180,270]
def init_logger():
logging.basicCon... |
#!/usr/bin/env python3
import requests
import click
from bs4 import BeautifulSoup
def gildas_release(package, archive=False):
uri = 'https://www.iram.fr/~gildas/dist/'
if archive and package == "gildas":
uri = 'https://www.iram.fr/~gildas/dist/archive/gildas'
elif archive and package == "piic":
... |
#!/ usr/bin/python
import numpy as np
import csv
import datetime as dt
import sys
def timereader(timestr, formatstr="%d/%m/%Y %H:%M"): #Change %Y to %y if necessary...
return dt.datetime.strptime(timestr, formatstr)
def binlistxor(list1, list2):
if len(list1) != len(list2):
raise TypeError("Lists... |
def linsearch(x,ns):
counter = 0
for n in ns:
if n == x:
return counter
counter = counter + 1
return -1
def binsearch(x,ns):
low = 0
high = len(ns)-1
while low <= high:
mid = (low + high)//2
item = ns[mid]
if x == item:
... |
#!\/usr/bin/python
class AbstractAnalysis(object):
def __init__(self):
pass
def __del__(self):
pass
def init( self ):
raise Exception( "Can not call abstract class method AbstractTest.init" )
def exit( self ):
raise Exception( "Can not call abstract class method AbstractTest.exit" )
de... |
from flask import Flask,render_template, request,jsonify,Response, redirect,url_for
import requests
import json
import sys
import time
import numpy as np
from filestore.k8.ner_service.ner_predict import prepare_model
from filestore.k8.ner_service.ner_predict import make_prediction
from filestore.k8.ner_service.flask_pr... |
class person ():
def __init__(self):
self.height = 180
self.__weight = 666
def getweight(self):
return self.__weight
def __move (self):
return "跑跑跑"
def moves (self):
return self.__move()
def __str__(self):
return "shengao%s"%self.height
def eat (... |
# Generated by Django 3.0.4 on 2020-03-10 18:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Bus',
fields=[
... |
from django.db import models
class Lobby(models.Model):
lobby_name = models.CharField(max_length=50)
|
#!/usr/bin/python3
import random
import time
class Police:
def __init__(self,inventory,hit_rate):
self.hp = 100
self.inventory = inventory
self.hit_rate = hit_rate
def is_dead(self):
return self.hp<=0
def recover(self):
self.hp += 60
self.inventory.rem... |
import simplejson as json
import boto3
def admin(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('tasks')
response = table.scan().get("Items")
client = boto3.client("lambda")
response2 = client.get_function(
FunctionName='taskmanager-dev-run_task')
dc = {
... |
# Core
import sys
import time
import os
# Manipulation + Draw + CLI
import numpy as np
import pygame
import pygame.gfxdraw
import fire
from tqdm import trange, tqdm
# Dev
from pprint import pprint as pp
# Default colors
COLOR_BLACK = (0, 0, 0)
# Pygame Constants
TIME_DELTA = 0.001
TIME_EVENT_ID = pygame.USEREVENT+1... |
import time
from typing import List
from bs4 import BeautifulSoup
from parser_app.logic.global_status import get_usual_webdriver
from parser_app.logic.handlers.handler_tools import remove_odd_space, load_page_with_TL
class ProxynovaProxyHandler:
def get_name(self) -> str:
return "proxynova.com"
de... |
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV , KFold
from sklearn.metrics import accuracy_score
from keras.models import Sequential, Model
from keras.layers import Dense, Input
import numpy as np
import pandas as pd
iris_data = pd.read_csv('./data/ir... |
from __future__ import print_function
from apiclient import discovery, errors
from httplib2 import Http
from oauth2client import file, client, tools
import base64
import email
import json
import mysql.connector
import re
import datetime
SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
class GmailClient(object)... |
import csv
import numpy as np
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import train_test_split
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import cross_val_score
# import pylab as ... |
"""
Задание 5:
В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве.
Составим список только из отрицательных элементов и в нем найдем максимум
"""
a = [1, 2, -4, 3, -34, 1, -5, 15, 1, -100, 58, -1, 0, -25, 10, 17]
a = [x for x in a if x < 0]
max_min = 0
if len(a) > 0:
... |
'''
@Author: Sankar
@Date: 2021-04-03 08:42:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-03 09:12:09
@Title : Temperature Conversion
'''
import pytest
import logging
import re
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')
def num_regex_choice():
'''
Description:
Ge... |
#Geo plot of CF for wind energy
import numpy as np
import pandas as pd
import geoplot as gplt
import geopandas as gpd
import matplotlib.colors as clrs
import matplotlib.pyplot as plt
ShapeFileCoast="./GEO_data/ne_10m_coastline.shp"
ShapeFileStates="./GEO_data/ne_10m_admin_1_states_provinces_lines.shp"
HourlyData=np.... |
from fxpmath import Fxp
import numpy as np
fs = 2793 # Hz
t = 0.4 # segundos
M = 1
N = 15
SIGNED = True
POINTS = fs*t
Hanning_filter = np.hanning(POINTS)
#Mitad derecha de un filtro de un filtro Hanning
Hanning_filter = Hanning_filter[int(POINTS/2):]
print(Hanning_filter)
if(SIGNED):
MIN =... |
from src.mymathhelper import *
import pprint
class Prediction:
def __init__(self, training_set):
self.training_set = training_set.training_set
self.training_set_iuf = training_set.training_set_iuf
self.movie_variance = training_set.movie_variance
self.movie_popularity = training_set... |
from django.test import TestCase
from rest_framework.test import APIClient
from unittest.mock import patch
class WeatherLookupViewSetTestCase(TestCase):
"""Test WeatherLookupViewSet."""
mock_weather_hourly_data = [
{
'temp': 10.0
}
]
mock_city = 'Some_city'
mock_period... |
from drip.models import BaseDripModel
from .drips import (BarnGardenDripBase, HundredRecordDripBase,
InactiveGardenDripBase, NewGardenGroupDripBase)
class BarnGardenDrip(BaseDripModel):
@property
def drip_class(self):
return BarnGardenDripBase
class BarnHundredRecordDrip(BaseDri... |
eng = int(input('英語の成績を入力してください> '))
math = int(input('数学の成績を入力してください> '))
x = eng + math
y = x / 2
print('英語の成績' + str(eng))
print('数学の成績' + str(math))
print('合 計' + str(x))
print('平 均' + str(y))
|
# Generated by Django 2.2 on 2020-04-20 02:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('asset', '0001_initial'),
('basic', '0001_initial'),
('user', '__first__'),
]
oper... |
# -*- coding: utf-8 -*-
import logging
import os
from urllib.request import urlopen
import boto
import youtube_dl
from django.conf import settings
logger = logging.getLogger('podcastninja')
class YtLogger(object):
def debug(self, msg):
pass
def warning(self, msg):
logger.warning('[YoutubeDL... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os.path
import math
import random
cnf = []
'''
#description: script turn given sudoku document into cnf formula document
#input :sudoku txt document
#output :cnf formula document combied with sudoku rules(end with .cnf)
'''
def convert2cnf(name):
arr ... |
#!/usr/bin/env python3
#
# Enumerates an UVW representing simple chains that are all accepted by a given
# transition-based deterministic parity automaton in HOA format, as produced by SPOT's ltl2tgba tool.
#
# Example command to produce a transition-based deterministic parity automaton
# OLD: ./ltl2tgba -Ht -f "[] <> ... |
import argparse
if __name__ == 'main':
parser = argparse.ArgumentParser(description='Train CongressIdeology model')
parser.add_argument('input_file', type=str)
parser.add_argument('meta_info_file', type=str)
parser.add_argument('model_type', type=str)
parser.add_argument('param_grid_file', type=st... |
# -*- coding: utf-8 -*-
"""intopython URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.... |
# import tensorflow and keras
import tensorflow as tf
from keras import backend as K
from keras.layers import Dense
from keras.objectives import categorical_crossentropy
from tensorflow.examples.tutorials.mnist import input_data
from keras.metrics import categorical_accuracy as accuracy
# create tensorflow session
ses... |
import sys
import numpy as np
import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def f(x):
return 10 - 5*x[0] + 2*x[1]
def h(theta, x):
return theta[0] + theta[1]*x[0] + theta[2]*x[1]
X = np.random.randint(500, size=(100, 2)).astype(dtype=np.float32)
Y = np.array([f(i) + 100 * (... |
from sinegy_python.marketplace import Marketplace
sinegy = Marketplace(api_key = '', secret_key = '')
print('----- TRADE FEES -----')
print(sinegy.get_trade_fees('ethmyr'))
print('----- ORDER STATUS -----')
print(sinegy.get_order_status('ethmyr'))
print('----- ORDER TYPES -----')
print(sinegy.get_order_types('ethmy... |
import skfuzzy as fuzz
from skfuzzy import control as ctrl
def fuzzy_fusion():
dist_cam = ctrl.Antecedent(np.arange(0, 320, 1), 'dist_cam')
offset_center = ctrl.Antecedent(np.arange(0, 320, 1), 'offset_center')
ult_weight = ctrl.Consequent(np.arange(0, 1, 0.01), 'ult_weight')
# input
offset_center... |
import cv2 as cv
img =cv.imread('photos/dog.jpg')
img =cv.resize(img, (400,250))
cv.imshow('Dog', img)
gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
cv.imshow('Gray', gray)
#Simple Thresholding
threshold, thresh = cv.threshold(gray, 150, 255, cv.THRESH_BINARY)
cv.imshow('Thresholded Simple', thresh)
#Simle thersholdin... |
# -*- coding: utf-8 -*-
# import custom module
from bot import webpage_auto_gen, game_objects, db_query_manager
from bot.system import line_api_proc, string_can_be_int, system_data, imgur_proc
import msg_handler
import os, sys, errno
import tempfile
import traceback
import validators
import time
from collections imp... |
"""
Idea:
keep track of the max sum that ends at i-th position, denoted by max_end[j]
we have:
max_end[j+1] = max(max_end[j] + nums[j+1], nums[j+1])
then the answer is just the max of all max_ends
Time: O(n)
Space: O(n)
"""
class Solution(object):
def maxSubArray(self, nums):
"""
... |
sender = '' # number of the sandbox number
receiver = '' # number to recieve coutput
account_sid = '' # twilio sid
auth_token = '' # twilio auth token
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from comlink.models import EmailMessage, Attachment, MailingList
class AttachmentInline(admin.TabularInline):
model = Attachment
extra = 0
def has_change_permission(self, request, obj=None):
return False
class EmailAdmin(admin.ModelAdmin)... |
a,b,c = map(int,input().split())
z = [a,b,c]
z = sorted(z)
p = z[1]-z[0]
q = z[2] - z[1]
print(p+q)
|
import sys
def moon_weight():
print('请输入你的体重')
First=int(sys.stdin.readline())
print('请输入每年增加的体重')
And=int(sys.stdin.readline())
print('请输入总共有多少年')
Year=int(sys.stdin.readline())
for x in range(1,Year+1):
Moon=(First+And)*0.165
First=Fi... |
from notebook.services.contents.manager import ContentsManager
from nbformat.v4 import new_notebook
from .checkpoints import Checkpoints
from .cenitio import CenitIO
from tornado import web
import itertools
import datetime
import re
copy_pat = re.compile(r'\-Copy\d*\.')
class ApiContentsManager(ContentsManager, Ceni... |
import numpy as np
import tensorflow as tf
import sys
import time
import random
import os
sys.path.append("..")
import utils.conf as conf
import utils.data_utils as data_utils
from gen_model import gen_model
SEED = int(time.time())
random.seed(SEED)
np.random.seed(SEED)
# Generate responses during inference
def inf... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# -*- coding: utf-8 -*-
from google_translate import GoogleTranslate
google = GoogleTranslate()
google.read_file("/Users/litaofan/github_code/AudioRecorder/app/src/main/res/values/strings.xml")
google.start('ja') |
# -------------------------------
# author: Hao Li, hao.li@uni-heidelberg.de
# data: 06.05.2021
# -------------------------------
import momepy
import geopandas as gpd
import matplotlib.pyplot as plt
import osmnx as ox
# load street and buildings
gdf_projected = gpd.read_file('HD_building.geojson').to_crs(epsg=3035)... |
# --------------------
#Integrantes:
#Manuel Rodriguez 13-11223
#Ian Goldberg 14-10406
# ---------------------
import ply.yacc as yacc
import re
from ast import *
from lexer import *
# Símbolo inicial
def p_inicio(p):
'''INICIO : TkWith DEC TkBegin INSTR TkEnd
| TkBegin INSTR TkEnd'''
if (len(p) == 6):
v... |
import numpy as np
import os
import time
import pandas as pd
routes_df = pd.read_csv('dataSets/training/routes (table 4).csv')
routes = dict()
for i in range(routes_df.shape[0]):
key = str(routes_df.loc[i, 'intersection_id']) + ',' + str(routes_df.loc[i, 'tollgate_id'])
val = str(routes_df.loc[i, 'link_seq'])... |
'''
Move the code you previously wrote to calculate how many seconds are in a year into this file.
Then execute it as a script to see the output printed to your console.
'''
seconds_in_year = 60 * 60 * 24 * 365
print("there are " + str(seconds_in_year) + " seconds in a year")
print(f"there are {seconds_in_year} sec... |
import pyttsx3
from flask_api import status
from flask import jsonify
import os, os.path
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r'/*': {'origins': '*'}})
@app.route("/api/level/<int:level_num>")
def read_level(level_num):
with open("levels/%i.txt" % level_nu... |
#!/usr/bin/env python
import numpy as np
import scipy.interpolate as interp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
X = [1,1,1,1,2,2,2,2,3,3,3,3]
Y = [1,4,5,6,1,4,5,6,1,4,5,6]
Z = [2,6,3,6,2,7,4,6,2,4,2,3]
plotx,ploty, = np.meshgrid(np.linspace(np.min(X),np.max(X),10),\
... |
from .base import *
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
if 'SENTRY_DSN' in os.environ:
sentry_sdk.init(
dsn=os.environ.get('SENTRY_DSN'),
integrations=[DjangoIntegration()],
# Set traces_sample_rate to 1.0 to capture 100%
# of transaction... |
list1 = [1, 2, 3, 4, "1", '2', 4]
def sums(x):
count = 0
for i in x:
if isinstance(i, str):
continue
else:
count += i
return count
print(sums(list1))
|
from django.db import models
from django.contrib.auth.models import User
from djazz.contrib.posts.signals import types_choice
def posttype_choices():
types = []
types_choice.send(sender=None,types_list=types)
return types
## Models
class Category(models.Model):
name = models.CharField(max_length=30,... |
##Import Models and Libs
import numpy as np
import pandas as pd
from datetime import datetime
def convert_date(my_date):
res = datetime.now().date()
try:
res = datetime.strptime(my_date, '%d %b %Y').date()
except:
pass
return res
def import_process_df(path):
## Our Main DataFrame
... |
from app import app
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_table
import pandas as pd
import numpy as np
from collections import defaultdict
import pickle
import plotly.graph_objects as go
from sklearn.feature_extraction.... |
# modules import
import requests
from bs4 import BeautifulSoup
from csv import writer
import pandas as pandasForSortingCSV
'''
A function to sort generated csv file
and overwrite the unsorted version.
'''
def sort_and_overwrite_csv():
try:
# CSV file name
filename = "./data/eu_road_safety_stati... |
from marshmallow import Schema, fields, post_load
import collections
class Random:
def __init__(self, data):
self.useRandomDotOrg = data.get('useRandomDotOrg', True)
self.preFetchCount = data.get('preFetchCount', 30)
class Config:
def __init__(self, data):
self.prefix = data.get('pre... |
import arcade
def OttoJ(x, y):
xCenter = x + 20
yCenter = y + 40
arcade.draw_rectangle_filled(x + 20, y + 40, 40, 80, arcade.color.BLACK)
arcade.draw_line(x + 5, y + 5, x + 35, y + 75, (255, 255, 255), 10)
arcade.draw_line(x + 35, y + 5, x + 5, y + 75, (255, 255, 255), 10)
arcade.draw_circle_... |
import numpy as np
import os
import itertools
from tqdm import tqdm
from ..utils import ImageUtil, get_imageset
import matplotlib.pyplot as plt
def iou_dice_val(
nb_classes, height, width, data_set, model, train_colors=None):
image_util = ImageUtil(nb_classes, (height, width))
confusion = np.zeros((nb... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.