text stringlengths 38 1.54M |
|---|
import tensorflow as tf
class LSTMClass(tf.keras.Model):
def __init__(self, **kargs):
super(LSTMClass, self).__init__()
# 임베딩 층에 현재 단어 사전의 개수에 맞는 input_dim을 설정
# LSTM layer을 거쳐서 특징들을 출력한 이후에
# dense layer2개를 거쳐서 대분류 데이터를 출력을 하게 된다.
# 따라서 output차원의 크기는 1이 된다.
self.embedding = tf.keras.layers.Embedd... |
# python3
from collections import deque
def max_flow(n,s,t,c):
INF = float("Inf")
max_flow = 0
f = [[0 for k in range(n)] for i in range(n)]
while True:
prev = [-1 for _ in range(n)]
prev[s] = -2
q = deque()
q.append(s)
while q and prev[t]==-1:
u ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Usage:
annotation.py call --cnv_fn=IN_FILE [--target_gene_fn=IN_FILE] [--ref=STR] [--out_prefix=STR]
annotation.py -h | --help
Options:
-h --help Show this screen.
--version Show version.
--cnv_fn=IN_FILE ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Video4.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui... |
class HTMLAttrMeta(type):
"""meta class for creating properties.
properties registed in elements will be created
in subclass.
"""
def __new__(cls, name, bases, attrs):
elements = attrs['elements']
prefix = attrs['prefix']
for each in elements:
HTMLAttrMeta.adda... |
# from autograd import grad, hessian
#
# gw = lambda x1, x2: x1**4 + x1**2 + 10*x2**3 + x2
# gradient = grad(gw)
# hessian = hessian(gw)
#
# print(gradient(10.0, 10.0))
# print(hessian)
import numpy as np
# import pickle
# from SAGE_VI import SAGE_VI
# dir = "/Users/shinbo/Desktop/metting/LDA/0. data/20news-bydate/new... |
capacity = 3
cache = [None for x in range(capacity)]
print(cache)
def get(pos):
global cache
if (pos > capacity - 1):
return -1
val = cache[pos-1]
shift(pos)
return val
def set(pos, n):
global cache
cache[pos-1] = n
def shift(pos1):
global cache
temp = cache.pop(pos1-1)
cache.appen... |
#!/usr/bin/python3
import os,sys
#打开文件
fd=os.open("foo.txt",os.O_RDWR|os.O_CREAT)
#写入字符串
str="this is test"
str=str.encode()
os.write(fd,str)
#关闭文件
os.close(fd)
print("关闭文件成功!!")
|
# -*- coding: utf-8 -*-
"""DB Vocabularies.
$Id$
"""
from zope.interface import implements
from rx.ormlite2.exc import PersistenceError
from rx.ormlite2.dbop import dbquery
from rx.ormlite2.vocabulary.interfaces import IRDBVocabulary
from pyramid.vocabulary.base import ObjectVocabulary
class RDBVoc... |
print(7*24*60)
#nie bedzie przetwa przez pythona jesli
ilosc_minut = 7*24*60
print("Liczba minut w ciagu 7 dni to:" + str(ilosc_minut))
BMI = (masa (78)) / (wzrost (m))** |
import random
import numpy as np
import os
from unidecode import unidecode
import matplotlib.pyplot as plt
def read_file(files, n=3):
# texts is a dict of dicts, so that keys are languages, and values is a dict
# of unique n-consecutive strings in language and their number of repetitions
texts = {}
... |
# Generated by Django 3.2.5 on 2021-08-01 07:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0002_remove_profile_discount'),
]
operations = [
migrations.AlterField(
model_name='profile',
... |
#!/usr/bin/env python3
"""
Created on March 28, 2023
@author: Gary Black
"""
import argparse
import csv
# absolute values less than this are considered zero due to limits on
# computational precision
NearZero = 1e-12
# print a warning flag for difference values greater than this
FlagPerDiff = 2.0
FlagAbsDiff = 0.... |
import mysql.connector
import sys
class createdb_table:
def __int__(self):
self.database="Hindunews"
self.username=''
self.password=''
self.db_list=[]
self.connection=''
self.cursor=''
def user_input(self):
#import pdb;pdb.set_trace()
self.usern... |
# Generated by Django 3.0.2 on 2020-01-31 07:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('polls', '0016_auto_20200131_1226'),
]
operations = [
migrations.RenameField(
model_name='question',
old_name='voter',
... |
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import cv2
import sys
from PIL import Image
import numpy as np
from webcam import Webcam
from glyphs.constants import *
from objloader import *
us = True
if us is not True:
from glyphs.glyphs import Glyphs
else:
from detect_and_track im... |
# Generated by Django 2.2.11 on 2020-07-20 05:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0006_auto_20200719_1222'),
]
operations = [
migrations.AddField(
model_name='visitor',
name='message',
... |
#-------------------------------------------------------------------------------
# Name: Cursor01.py
# Purpose:
#
# Author: Matthew Rowland
#
# Created: 05-02-2019
# Copyright: (c) Rowland 2019
#-------------------------------------------------------------------------------
import os
import sys
impo... |
#!/usr/bin/env python
##
## Copyright (C) Bitmain Technologies Inc.
## All Rights Reserved.
##
import argparse
import caffe
import os
import sys
import time
sys.path.append('../../calibration_tool/lib')
from Calibration import Calibration
#caffe.set_mode_gpu()
#caffe.set_device(0)
def run_calibration(args):
cal... |
from Game.PPlay.window import *
from Game.game import *
from Game.main_menu import *
from Game.gameover import *
from Game.PPlay.sound import *
level = [0]
gui = Window(1024, 768)
gui.set_title("Stone Jump")
game = Game_itself(gui, level)
main_menu = Main_menu(gui, level, game)
gameover_menu = Gameover(gu... |
import numpy as np
class GloveClassifier(object):
def __init__(self, source):
self.source = source
self.embeddings, self.word2vec, self.idx2word = self.read_glove_source()
def read_glove_source(self):
"""
The following function reads the Glove pre trained embeddings from a gi... |
# face verification with the VGGFace2 model
from matplotlib import pyplot
from PIL import Image
from numpy import asarray
from scipy.spatial.distance import cosine
from mtcnn.mtcnn import MTCNN
from keras_vggface.vggface import VGGFace
from keras_vggface.utils import preprocess_input
<<<<<<< HEAD
=======
import pickle
... |
"""Fixtures for pyintesishome_local."""
import pytest
from aioresponses import aioresponses
@pytest.fixture
def mock_aioresponse():
with aioresponses() as m:
yield m
|
# `box` let dict with advanced dot notation access.
from box import Box
import importlib
import json
import sys
def load(fp: object, lang: str = "json") -> dict:
'''Load a file to dictionary, format should be read from extension;
unless specified by the second argument `lang`
'''
mod = importlib.impor... |
from __future__ import annotations
import argparse
import platform
import pytest
from jsonargparse import Namespace, dict_to_namespace, namespace_to_dict
from jsonargparse._namespace import meta_keys
skip_if_no_setattr_insertion_order = pytest.mark.skipif(
platform.python_implementation() != "CPython",
reas... |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from students.utils import format_records
from teachers.models import Teacher
from webargs import fields
from webargs.djangoparser import use_args
# Create your views here.
@use_args({
"first_name": fields.Str(... |
# name: Stephen Wang
# date: November 7, 2020
# purpose: City class
class City:
def __init__(self, code, name, region, population, latitude, longtitude):
self.code = code
self.name = name
self.region = region
self.population = int(population)
self.latitude = float... |
# -*- coding: utf-8 -*-
import time
all_st = time.time()
# import Env
import os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
from env import Env
Env()
from convert_datetime import *
from aggregate import *
from get_start_end_sta import get_start_end_mod
from pymongo import *
client = Mon... |
#program2a
def find(lis,key):
for i in lis:
if(i==key):
print("key found")
return True
print("key not found")
return False
lis=[1,2,3,4,5]
key=int(input("enter the key value"))
value=find(lis,key)
print(value)
#program 2b
def str1(sentence):
list1=(sentence.split(" "... |
# Generated by Django 3.0.3 on 2020-04-07 22:57
import dancingcubeapp.validators
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('dancingcubeapp', '0007_a... |
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import Required, Optional
class Simulate(FlaskForm):
data = StringField('Input reference list: ', validators=[Required()])
cache_0 = StringField('', validators=[Optional()])
cache_1 = StringField('', validators=[Optional()])
... |
#
# @lc app=leetcode.cn id=212 lang=python3
#
# [212] 单词搜索 II
#
# @lc code=start
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
# 1.words遍历--> board search O(N*m*m*4^k) 单词个数,矩阵行列,四连通深搜 每个单词平均长度
# 2.trie a.all words --> 构建trie 使prefix可以高效查询
# ... |
"""
Module containing layers for MADE model
"""
import torch
from torch import nn as nn
from torch.distributions import Uniform
from torch.nn import functional as F
class MaskedLinear(nn.Linear):
"""
Masked linear layer implemented by multiplying the layer's weights with a binary mask
"""
def __init__... |
# Type your code here
def row_sum(list2d):
sam_list = []
for i in list2d:
sam = 0
for x in i:
sum = sum + x
sam_list.append(sam)
return sam_list |
'''
Escreva um programa que leia a velocidade de um carro.
Se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado.
A multa vai custar R$7,00 por cada km acima do limite.
'''
velocidade = float(input('Digite a velocidade do carro: '))
if velocidade < 0:
print('Valor Inválido!')
else:
if vel... |
import sys, math
import numpy as np
import os
import copy
import imageio
import time
from .kinematic import euler_to_rotmat, pqr_to_eulerdot_mat
from .dynamics import DynamicSystem, State
from .utils import pi_bound, cross_product
from .lookup import LookUpTable
FTS2KNOT = 0.5924838 # ft/s to knots conversion
EPS ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2017-03-16 19:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('threads', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
import pandas as pd
import pickle
import numpy as np
import sys
df = pd.read_csv("imageLinksWithAgeAndGender.csv")
print(df.shape)
df['age' ] = df['age'].loc[df['age'].str.len() ==2]
df['age'] = df['age'].fillna(0)
strs = df['age'].value_counts()
pos = strs.loc[df['age'].value_counts() > 10]
pos = pos.index.tolist()
... |
import requests
import uuid
def test_crop_validation(hostname, large_file):
"""
Test edge cases of cropping an image
:param hostname: The hostname under test (this fixture is automatically injected by pytest)
:param large_file: A large-ish filename (this fixture is automatically injected by pytest)
... |
# led-control WS2812B LED Controller Server
# Copyright 2021 jackw01. Released under the MIT License (see LICENSE for details).
import re
import math
import colorsys
# Constrain value
def clamp(x, min, max):
if x < min:
return min
elif x > max:
return max
else:
return x
# Title ge... |
from __future__ import print_function
from spyder_window_maker import win_ftset_and_label
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import keras
import tensorflow as t... |
import itertools
class Players:
def __init__(self):
self._players = set()
self.reset()
def reset(self):
self.player_queue = itertools.cycle(self._players)
def add(self, player):
self._players.add(player)
self.reset()
def remove(self, player):
... |
import logging
log = logging.getLogger(__name__)
class BalanceBase:
def __init__(self, dataDict):
self.dataDict = dataDict
def _getCommonInitialData(self):
balances = self.dataDict['initialBalances']
returnDict = {
'accruedInterest': balances['accruedInterest'],
'cash_avail... |
from django.views.generic import TemplateView
# Create your views here.
from core.models import Post
class HomeView(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['posts'] = Post.objects.all(... |
import requests
from adhack.settings import GODADDY_KEY, GODADDY_SECRET, GODADDY_API
def check_domain(name):
"""
r = requests.get(GODADDY_API+name, headers={
"Accept": "application/json",
"Authorization": "sso-key {}:{}".format(
... |
import unittest
from google.appengine.ext import testbed, ndb
from mock import patch
from src.commons.big_query.copy_job_async.copy_job.copy_job_request \
import CopyJobRequest
from src.commons.big_query.copy_job_async.copy_job_service_async \
import CopyJobServiceAsync
from src.commons.big_query.copy_job_asy... |
# -*- coding: utf-8 -*-
from app import db, login
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True... |
#Generated from java-escape by ANTLR 4.4
import antlr4
import Utils
import ECMAScriptParser
from VirtualMachine.OpCode import OpCode
from VirtualMachine.Code import Code
from VirtualMachine.Instruction import Instruction
from VirtualMachine.Stack import Stack
from ECMAScriptParser import ECMAScriptV... |
# 201016 Class Reading "Sequences: Lists, Strings, and Tuples"
# Small Exercises
# 2. Largest Number
# Create a list of numbers, print the largest of the numbers.
##declare list
nums = [30, 40, 50, 100]
##print sum
print(max(nums)) |
user_num1 = int(input("Input your ferst number pls: "))
user_num2 = int(input("Input your second number pls: "))
if user_num1 > user_num2:
print('Второе число',user_num2,"\n",'Первое число',user_num1)
else:
print('Первое число',user_num1,"\n",'Второе число',user_num2)
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import bleach
class BonniePipeline(object):
def strip_html(self, string):
return bleach.clean(string, strip=True, ... |
from django.shortcuts import render
from django.shortcuts import render,get_object_or_404,redirect
from django.views.generic import TemplateView,CreateView,UpdateView,DeleteView,ListView,DetailView
from posts.models import Post
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorator... |
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
class CouponApplyForm(forms.Form):
code = forms.CharField()
|
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from core import settings... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import os
import time
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
from torchvision import datasets, transforms
from model import PCBModel... |
import argparse
import threading
import time
from pathlib import Path
import blobconverter
import cv2
import depthai as dai
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('-nd', '--no-debug', action="store_true", help="Prevent debug output")
parser.add_argument('-cam', '--camera', action="st... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
osoba = input("Jak się nazywasz? ")
wiek = input("ile masz lat? ")
print("Witaj, ", osoba, "!")
print("Urodziłeś się w: ", 2017 - int(wiek))
rok_pythona = 1991
wiek_pythona = 2017 - rok_pythona
if wiek_pythona > int(wiek):
print ("Python jest starszy")
elif wiek_pyt... |
import socket
import config
from settings import ai,ak,sk
from aip import AipSpeech
asp = AipSpeech(ai,ak,sk)
voice_path = './'
# server_IP = '0.0.0.0'
# server_PORT = 15678
message = 'I am Client\n'
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((config.server_IP, config.server_PORT))
client... |
from typing import Union
from .abstract_classes import Field
from .schema import Schema
from .utils import from_iso_date, from_iso_datetime
class String(Field):
def deserialize(self, value: str):
return value
class Date(Field):
def deserialize(self, value: str):
return from_iso_date(value... |
"""
Some audio files in the dataset are too big to be processed in one step,
so they need to be splitted beforehand.
"""
import argparse
# empirically defined 20 MB .mp3 file is big enough to crash feature extractors
import os
from _json import make_encoder
from pathlib import Path
from shutil import copyfile
import ... |
"""connection.py: Connection for connecting to serial or sf ports."""
import logging
import threading
import time
from codecs import encode
from six.moves import queue
from moteconnection.connection_events import ConnectionEvents
from moteconnection.connection_forwarder import SfConnection
from moteconnection.connec... |
import os
def name_ext(path):
p, e = os.path.splitext(path)
if p.endswith('.tar'):
return p[:-4], '.tar' + e
return p, e
def name(path):
return name_ext(path)[0]
def ext(path):
return name_ext(path)[1]
## The search parameter is for Egg files, since they have a different structure
def ... |
from GetPot import GetPot
import numpy as np
import sys
import time
def g(xa=0.75,loc=2.0,D=0.5,S=1.0):
#S = 1.0 #source strength
#D = 0.5 #diffusion coefficient
#loc = 2.0 #depth in cm
cof = S/xa
#print '...in source.py...'
#print 'D,xa:',D,xa
L = np.sqrt(D/xa)
flux = cof*(1.0-np.exp(-loc/L))
return... |
# Generated by Django 2.0.7 on 2018-09-16 20:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ficha', '0004_auto_20180915_1036'),
]
operations = [
migrations.AddField(
model_name='ficha',
name='ajustado',
... |
"""
Unittest for familytree.layout.butterfly module.
"""
from familytree.person import Person
from familytree.table import Table
from familytree.layout.butterfly import ButterflyLayout
def _get_box(elements, person):
filtered = [e for e in elements
if getattr(e, 'person', None) == person]
as... |
#! /usr/bin/env python
# -*- coding: utf_8 -*-
# The exploit is a part of EAST Framework - use only under the license agreement specified in LICENSE.txt in your EAST Framework distribution
import sys
import os
import urllib2
from collections import OrderedDict
sys.path.append('./core')
from Sploit import Sp... |
# USAGE
# python ~/ML/cats-vs-dogs/caffe/code/check_dpu_runtime_accuracy.py -i ~/ML/cats-vs-dogs/deephi//quantiz/zcu102/rpt/logfile_top2_alexnetBNnoLRN.txt
# It checks the top-1 and top-2 accuracy obtained at runtime by DeePhi DPU, by analysis of the related logfile
# by daniele.bagni@xilinx.com
# ###############... |
def nian_qw(year):
if year%400 == 0 or (year%4 == 0 and year%100 != 0):
print("闰年")
else:
print("平年")
year = int(input("请输入你要查看的年份:"))
nian_qw(year)
|
def countryList():
colist = ['Angola',
'Benin',
'Botswana',
'Burkina Faso',
'Burundi',
'Cameroon',
#'Cape Verde', #cabo verde
'Central African Republic',
'Chad',
'Comoros',
#'Congo (Brazzaville)',
#'Congo (Democratic Republic)', #parens? #congo, rep.
#"CC4te d'Ivoire",
'Djibouti',
'Equatorial Guinea',
'... |
class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
need = 1<<k
mySet = set()
for i in range(k, len(s)+1):
now = s[i-k:i]
if now not in mySet:
mySet.add(now)
need -= 1
if need == 0:
... |
from django.contrib import admin
from sms_app.models.models import *
admin.site.register(Address)
admin.site.register(Employee)
admin.site.register(Post)
admin.site.register(Sanatorium)
admin.site.register(RoomPlacesType)
admin.site.register(RoomType)
admin.site.register(Room)
admin.site.register(TreatmentCourse)
admi... |
from service.config.service_config import ServiceConfig
from service.db.db_base import DBBase
from service.providers.channel_provider import ChannelProvider
from service.services.chat_service_base import ChatServiceBase
from service.services.web_service_base import WebServiceBase
class ServiceDependencies(object):
... |
# Decorators 2 - Name Directory
#######################################################################################################################
#
# Let's use decorators to build a name directory! You are given some information about N people. Each person has
# a first name, last name, age and sex. Print th... |
# coding: utf-8
import boto3
session = boto3.Session(profile_name='Ian-pfb')
as_client = session.client('autoscaling')
as_client.execute_policy(
AutoScalingGroupName='Notifon Example Group', PolicyName='Scale Up')
|
from hmmlearn.hmm import MultinomialHMM
def fit(seqs, n_components=1):
MultinomialHMM(
n_components=n_components,
startprob_prior=1.0,
transmat_prior=1.0,
algorithm='viterbi',
random_state=1,
n_iter=100,
tol=0.01,
verbose=True,
params='ste',
... |
# COLLE Maxime
# DOUCHET Benjamin
# TP5
#ex1
print('','\n','\n','\n','\n')
#ex2
def imprimer_vertical(s) :
"""
imprime la chaine de caractère en verticale
à la verticale
param s (str)
C,U none
>>> imprimer_vertical ('Test')
T
e
s
t
"""
for c in s:
pri... |
number1 = 3 #number given to the variable
number2 = 4 # Integer
float_ = 2.35 #Float, has decimals
boolean = True # It can have two outcomes - true or false.
character = "%"
string = "qwer" #String can be anything within the quatanion marks
sudetis = number1 + number2
rounded1float = round(float_, 1) # The round functi... |
import torch
import math
import numpy as np
from torch import nn
from torch.nn import functional as F
from typing import Union
from vq_vae_text.modules import Quantize, GeometricCategoricalDropout, CategoricalNoise, SlicedQuantize, ChannelWiseLayerNorm, wn_conv_transpose1d, wn_conv1d, wn_linear, Attention
from vq_va... |
import os
import unittest
import json
from flask_sqlalchemy import SQLAlchemy
from models import setup_db, Question, Category
from flaskr import create_app
class TriviaTestCase(unittest.TestCase):
"""This class represents the trivia test case"""
def setUp(self):
"""Define test variables and initializ... |
from importlib import import_module
from django.apps import AppConfig as BaseAppConfig
class AppConfig(BaseAppConfig):
name = "birdproj"
def ready(self):
import_module("birdproj.receivers")
import_module("birdproj.profiles.receivers")
import_module("wiki.receivers") # @@@ upgrade p... |
import argparse
import cv2
class DSample:
SUPPORTED_FORMATS = (
".bmp",
".dib",
".jpeg",
".jpg",
".jpe",
".jp2",
".png",
".pbm",
".pgm",
".ppm",
".sr",
".ras",
".tif",
".tiff",
)
def __init__(s... |
from TexTor import get_nlp
from TexTor.understand.coreference import replace_coreferences
from TexTor.understand.inflect import singularize as make_singular
from spacy.parts_of_speech import NOUN
def singularize(text, nlp=None):
nlp = nlp or get_nlp()
doc = nlp(text)
ignores = ["this", "data", "my", "was"... |
import cv2
import os
from PIL import Image
import imutils
from io import BytesIO
import base64
haar_file = 'haarcascade_frontalface_default.xml'
# img sample size
(width, height) = (130, 100)
face_algo = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
def detect():
video = cv2.Vi... |
import json
import datetime
from django import template
from django.db.models import Avg
from general.models import *
register = template.Library()
@register.filter
def is_accepted(player, game):
try:
return GameInvitation.objects.filter(player=player, game=game)[0].is_accepted
except Exception as e... |
from datetime import datetime
from app.core.domain.comment import Comment
from app.core.domain.post import Post
from .database import db
class PostModel(db.Model):
__tablename__ = "posts"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.Unicode(255))
body = db.Co... |
# -- coding: utf-8 --
import uuid
from django.contrib.auth.models import User
from django.db import models
from datetime import date, time, datetime
from django.utils.encoding import python_2_unicode_compatible
from django.db.models.query import QuerySet
""" constantes """
#momento de la encuesta
ANTES_ASCENDER = 'AA'... |
"""Export survey data to Cloud Storage.
This implements a new admin-only page that allows exporting survey data from
the App Engine Datastore into a file in Cloud Storage, for easy downloading.
Alternately, this can export the data from Datastore into a Spreadsheet in the
admin's Google Drive.
"""
import datetime
im... |
# -*- coding: utf-8 -*-
import sys
import os
import logging
import pickle
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import numpy as np
import tensorflow.contrib.keras as ker
from tensorflow.contrib.keras.python.keras import backend as K
from sklearn.metrics import preci... |
class Car:
def __init__(self, p_make, p_mileage):
self.__make=p_make
self.__mileage=p_mileage
def get_make(self):
return self.__make
def get_mileage(self):
return self.__mileage
def __str__(self):
return super().__str__()
class Toyota(Car):
def __init__(s... |
import tensorflow as tf
# from loss.ctc_ops import ctc_loss_v2, ctc_label_dense_to_sparse, ctc_unique_labels
from loss import ctc_ops
from tensorflow.python.ops import array_ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import sparse_tensor
"""
https://github.com/hirofumi08... |
from deltaconnection import make_connection
from __variables_creation import Variables
import logging
class AhuVariables(Variables):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.points_list = []
self.setup_dict = {}
for key, value in kwargs.items():
... |
import keyword_maps
import re
import pandas as pd
keywords_map = keyword_maps.keywords_map
def map_function(str1):
all = str1
converted = {}
list_param = {}
for a in range(str1.count('(')):
func_parameters = {}
ptrn = "\s*([a-zA-Z_]\w*[(](\s*[a-zA-Z_]\w*[(]|[^()]+)[)])"
... |
#! python3
import sys
import traceback
import os
import xml.etree.ElementTree as ET
from tkinter import *
import tkinter.filedialog
from modules.map_data_view import MapDataView
from modules.map_border_view import MapBorderView
from modules.map_view import MapView
from modules.utils import getGameDir
from modules.ti... |
import pytest
from tests.utils import file_response
from city_scrapers.spiders.det_schools import Det_schoolsSpider
test_response = file_response('files/det_schools.html', url='http://detroitk12.org/board/meetings/')
spider = Det_schoolsSpider()
parsed_items = [item for item in spider.parse(test_response) if isinstan... |
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import sys
import os
sys.path.append('/Users/dingyang/tim/extra/my/wall/Mac-command-wallpaper-master/bin')
from weather import address
from weather import city
from weather import fiveday
if __name__ == '__main__':
print(fiveday.getFives())
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'blochin.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
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWind... |
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QGridLayout, QGroupBox, QPushButton, QLineEdit
#from PyQt5.QtWidgets import QLabel, QFileDialog, QRadioButton, QComboBox
class App(QDialog):
def __init__(self):
# Add fields here
super().__init__()
self.title = "Title"
... |
def print_formatted(number):
# your code goes here
binNumber = bin(number)[2:]
for i in range(1,number+1):
octalNum = oct(i)[2:]
hexNum = hex(i)[2:].upper()
binNum = bin(i)[2:]
print("{} {} {} {}".format(str(i).rjust(len(binNumber),' '),octalNum.rjust(len(binNumber)... |
##############################################################################
# Copyright by The HDF Group. #
# All rights reserved. #
# #
# Th... |
import tweepy
consumer_key = "B4PbUyBHiQbch0VxFSKB2tWJf"
consumer_secret = "SbSc0v79lRYKJdzN8IDFZ3gXRKnI9DpFxOVf3mtsg3uEHJBVHN"
access_token = "3020843641-cibXWf5cW8xCXoBTw2CUId6jIcb1jfhap5mJndJ"
access_token_secret = "nYZHd4NxNemcvmjvBQtIriGyUWB6tLvJMn4T354G3pCax"
auth = tweepy.OAuthHandler(consumer_key,consumer_sec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.