text stringlengths 38 1.54M |
|---|
from django.shortcuts import render
from django.http import JsonResponse
from .models import Friends, Users
from .utils import Redis
from django.db.models.functions import Cast
from django.db.models import CharField, TextField
from django.forms.models import model_to_dict
from django.core.serializers.json import Djang... |
# Generated by Django 3.1.7 on 2021-04-09 04:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0012_auto_20210409_0344'),
]
operations = [
migrations.RemoveField(
model_name='recipe',
name='items',
... |
"""
Ontology metadata extractor Task.
It takes the output of the [IMPC Ontology Pipeline](https://github.com/mpi2/impc-ontology-pipeline)
and transforms it to a parquet files.
"""
from typing import Any
import luigi
from luigi.contrib.spark import PySparkTask
from pyspark import SparkContext
from pyspark... |
import cv2, time
video=cv2.VideoCapture(0)
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
while True:
check, frame = video.read()
#print (check)
#print (frame)
#time.sleep(3)
#gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMultiScale(frame, sca... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import get_template
from django.template import Context
from datetime import datetime
from django.shortcuts import render_to_response
from models import *
from django.shortcuts import get_object_or... |
import ply.lex as lex
tokens = (
'LINENUM',
'PRINCIPLE',
'AND',
'OR',
'IMPLIES',
'NOT',
'EQUIVALENT',
'DERIVES',
'SAYS',
'SAYS_FOR',
'CONTROLS',
'CAN_ACCESS',
'OBJECT',
'LPAREN',
'RPAREN',
'REASON',
'TO_PROVE',
'GIVEN',
'SEMICOLON',
'TRUE',
'FALSE',
#'COMMA',
)
reserved = {
'can_access' : 'CAN_... |
# Given a list of words, sort them by length of word, rather than alphabetically.
# To do this, first create a list of tuples of the form (len, word), where the first element is the length of the word.
# Next, sort the tuples.
# Finally, extract the words from the list of tuples into a new list which is now sorted by l... |
"""Test the integration between Cursor and odbql's errmsg."""
import pytest
from ..context import py3odb
def test_errmsg():
"""Create a database and then feed it junk."""
conn = py3odb.connect("")
cur = conn.cursor()
with pytest.raises(py3odb.ProgrammingError) as err:
cur.execute("i have no id... |
import dense_correspondence_manipulation.utils.utils as utils
utils.add_dense_correspondence_to_python_path()
from dense_correspondence.salad_training.training import *
import sys
import logging
#utils.set_default_cuda_visible_devices()
# utils.set_cuda_visible_devices([0]) # use this to manually set CUDA_VISIBLE_DEVI... |
import unittest
from RefCountTestBase import FieldAccessTestBase
import osg2.osg as osg
#-------------------------------------------------------------------------------
class SFPtrAccessTestBase(FieldAccessTestBase):
"""
Base class for pointer multi-field refcounting tests.
Base class for testing the... |
from django.db import models
from datetime import date
class Task(models.Model):
text = models.CharField(max_length=100)
complete = models.BooleanField(default=False)
# due_date = models.DateField(default=date.today)
# created_date_time = models.DateTimeField(auto_now_add=True)
def __str__(self):... |
from wsgiref.simple_server import make_server
from webob import Request, Response
import os
from jinja2 import Template
import core.vars as variables
class App:
def __init__(self, templates_dir='templates', static_dir='static'):
self.routes = {}
self.templates_dir = templates_dir
self.stat... |
from boto3.dynamodb.conditions import Key, Attr
from datetime import datetime
import boto3
import botocore
from botocore.exceptions import ClientError
import logging
import json
import random
import decimal
#****************************************
#S3 methods
#****************************************
def getS3object... |
import argparse
import csv
import logging
import sys
from datetime import datetime
from modules import (data, db, epochconvert, findold, formatting, markobjects,
output, queries)
PARSER = argparse.ArgumentParser()
# DB connection args
DB_GROUP = PARSER.add_argument_group('Database')
DB_GROUP.add... |
# conding:utf-8
import mxnet as mx
def squeeze(data, num_filter, kernel=(1, 1), stride=(1, 1), pad=(0, 0), act_type="relu", mirror_attr={}):
squeeze_1x1 = mx.symbol.Convolution(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad)
act = mx.symbol.Activation(data=squeeze_1x1, act_typ... |
from django.shortcuts import render
from books import models # 导入models文件
from django.contrib.auth.decorators import login_required,permission_required
from mybooks import settings
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import re
import os
from PIL import Image
import re
import base6... |
import cirq
import numpy as np
class BitAndPhaseFlipChannel(cirq.SingleQubitGate):
def __init__(self, p: float) -> None:
self._p = p
def _mixture_(self):
ps = [1.0 - self._p, self._p]
ops = [cirq.unitary(cirq.I), cirq.unitary(cirq.Y)]
return tuple(zip(ps, ops))
def _has_mi... |
from os import environ
import googlemaps
from normality import latinize_text
API_KEY = environ.get('GMAPS_APIKEY')
def tidy_address(address):
address = address.upper()
if 'ESQ,' in address or 'ESQ.,' in address:
a = address.split('ESQ,')
if len(a) == 1:
a = address.split('ESQ.,')
... |
import numpy as np
class RTable(object):
"""The RTable class contains all required behaviours to CRUD a new table """
def __init__(self, reward_matrix):
self.reward_matrix = reward_matrix
def get_rtable(self):
return self.reward_matrix
def get_rtable_element(self, state_index, ... |
import ctypes
import h5py
import os
import platform
import time
import math
from typing import Tuple, Union, List, Dict, Callable
import numpy as np
__all__ = ['CppFunc', 'CppDispatcherBase']
def CppFunc(func):
def _decorator(*args, **kwargs):
dispatcher = args[0] # type: CppDispatcherBase
as... |
#!!~/anaconda/bin python
# -*- coding: utf-8 -*-
"""util_2.py
utility functions for 2_2_optimisation_combinatoire.ipynb
"""
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
def plot_graph(graph_mat, to_highlight=None, figsize=(16,12)):
"""Plots undirected weighted graph infered by input... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79826524
# IDEA : GREEDY
class Solution(object):
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
pairs.sort(key=lambda x: x[1])
currTime, ans = float('-inf'), 0
... |
import QuantLib as ql
import pandas as pd
from WindPy import *
import numpy as np
import datetime
w.start()
today = datetime.date.today().strftime('%Y-%m-%d')
quote_sh = w.wsq("210005.IB", "rt_last_dp,rt_last_cp,rt_last_ytm").Data
quote_sh = [float(i) for i in np.ravel(quote_sh)]
quote_sh.insert(0, "210005.IB")
print... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author:summer_han
# atm 程序配置文件
import logging
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.append(BASE_DIR)
BILL_DAY = 25
DATABASE = {
'engine': 'file_storage', #support mysql,postgresql in the future
'name':'account... |
from os import path, makedirs
from csv import reader, writer
from glob import glob # fetching glob function only from the glob lib
filePath = 'C:\\python-challenge\\PyPoll\\raw_data'
# csvpath = path.join('..',fileName,'election_data_1.csv')
csvFilesOnly = glob(filePath + "\\*.csv")
# print(csvpath)
total_number_of_... |
"""
INTERVAL: MERGE INTERVALS LIST (leetcode.com/problems/merge-intervals)
Write a function which takes a list of intervals with integer endpoints, then computes and returns the union, or
merge, of the intervals in the list.
Example:
Input = [[1,8], [-4, -1], [11, 12], [0, 2], [3, 6], [7, 9], ... |
#This script is written to fetch orderbooks async from markets
import pandas as pd
from bitshares import BitShares
from bitshares.account import Account
from bitshares.market import Market
from datetime import datetime
from json import dumps
from utils import json_serial
import time
from pathlib import Path
fro... |
"""
演示默认参数(形参)
"""
# 默认参数
# def demo(a = 1, b = 2):
# print(a) # 1 5
# print(b) # 2 10
#
# demo(5) # 实参的优先级是大于默认参数的值的优先级
# # 形参 位置形参 默认形参
# def demo(a, b ,c=3 ,d=4):
# print(a) # 1
# print(b) # 2
# print(c) # 5
# print(d) # 6
#
#
# demo(1,2,5,6)
# 位置关系: 默认形参只能够写在位置形参的后面,,... |
from app import app, db, bcrypt
from flask import jsonify
import datetime
import jwt
class User(db.Model):
"""
"""
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(255), unique=True, nullable=False)
email = db.Column(db.S... |
from django.db import models
from MainApp.models import Person, Request
# Create your models here.
class Status(models.Model):
name = models.CharField(verbose_name='Название статуса', max_length=16, blank=True, null=True, default=None)
is_active = models.BooleanField(default=True)
created = models.DateTim... |
def get_best_profit(stock_prices_yesterday):
min_price = stock_prices_yesterday[0]
max_profit = 0
for current_price in stock_prices_yesterday:
min_price = min(min_price, current_price)
max_profit = max(max_profit, current_price - min_price)
return max_profit
|
import numpy as np
class buses:
def __init__(self, N, C=0, sigma=1):
self.N = N
self.positions = np.arange(0,N)/2
self.C = C
self.sigma =sigma
self.beta_closed = 2/3*(sigma ** 2 + np.sqrt(sigma **4+6*C))
self.beta_open = sigma ** 2 + np.sqrt(sigma **4+4*C)
self.beta_global = sigma ** 2 + np.sqrt(sigma ... |
#!/usr/bin/python3
import boto3
import RPi.GPIO as GPIO
import time
import datetime
import picamera
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import asyncio
import socket
import MySQLdb
import threading
GPIO.setwarnings(False)
#set GPIO Pins
GPIO_TRIGGER = 18
GPIO... |
__author__ = 'cmccully'
# For an individual image
# Get the reference catalog (include positional uncertainties)
# Get Photometer targets
# Fit an initial set of parameters to the data.
# Run an emcee loop to get distributions of photometry
def moffat_chi_vals(self,theta,N_pix, flip):
x0,y0,amp0,amp1,amp2,amp3... |
#! -*- coding: utf-8 -*-
# BERT做无监督分词
# 介绍:https://kexue.fm/archives/7476
import numpy as np
# from bert4keras.models import build_transformer_model
# from bert4keras.tokenizers import Tokenizer
# from bert4keras.snippets import uniout
#
# # BERT配置
# config_path = '/root/kg/bert/chinese_L-12_H-768_A-12/bert_config.jso... |
month=int(input())
day=int(input())
if month==2 and day==18: print('Special')
if month>2 or month==2 and day>18: print('After')
if (month<2 or month==2 and day<18): print('Before')
|
from ivdiff import checkDiff
from multiprocessing import Pool
import argparse
from functools import partial
def check(cookies, t1, t2, i):
n = i.rstrip("\n\r").rstrip("\n")
print("Trying {0}".format(n))
checkDiff(cookies, n, t1, t2)
if __name__ == '__main__':
parser = argparse.ArgumentParser(descrip... |
# Generated by Django 2.2.6 on 2019-11-06 21:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('betting', '0008_punter_user'),
]
operations = [
migrations.RenameField(
model_name='betplacing',
old_name='runner',
... |
#!/usr/bin/python
import sys
# TODO objectify this stuff, global methods for now
def mult(valA, valB):
return valA * valB
def div(valA, valB):
return valA / valB
def add(valA, valB):
return valA + valB
def subt(valA, valB):
return valA - valB
# global constants
i = 0
def computeIntermediate(innerList, ... |
X, K, D = map(int, input().split())
mid = abs(X)
if K*D > mid:
mm = mid // D
K = K - mm
mid = mid - mm * D
if K % 2 == 0:
print(mid)
else:
print(abs(mid - D))
else:
print(mid - K * D) |
#
from selenium import webdriver
import time
brower=webdriver.Firefox()
brower.get(r"file:///C:/Users/liunan/Desktop/test.html")
brower.find_element_by_name('file').send_keys(r'C:\Users\liunan\Desktop\artlogo\1.jpg') |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 22:16:27 2017
@author: hp
"""
starttime='2017-01-01'
endtime='2017-12-31'
actionname=input("请输入想要查询的活动名称,可以是全称也可以是节选\n")
start=starttime.split('-')
syear=start[0]
smonth=start[1]
sday=start[2]
end=endtime.split('-')
eyear=end[0]
emonth=end[1]
eday=end[2... |
import pandas as pd
import numpy as np
import warnings #Para suprimir los warnings de deprecated
from sklearn.metrics import explained_variance_score, mean_absolute_error #Para la confusion
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
from ... |
import unittest
import numpy as np
import numpy.testing as npt
import wisdem.drivetrainse.layout as lay
npts = 12
ct = np.cos(np.deg2rad(5))
st = np.sin(np.deg2rad(5))
class TestDirectLayout(unittest.TestCase):
def setUp(self):
self.inputs = {}
self.outputs = {}
self.discrete_inputs = {... |
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# 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 requ... |
from __future__ import print_function
import os
import glob
import pickle
class UCF101_splitter():
def __init__(self, path, split):
self.path = path
self.split = split
def get_action_index(self):
self.action_label = {}
with open(os.path.join(self.path, 'classInd.txt')) as f:
... |
# ********************************************************* #
#
# Senate Testimony Stats
#
# ********************************************************* #
# Last Updated:
# 10/30/2021 - Created script. Added cleaning fns.
# 10/31/2021 - Added sorting of exchanges. Revised Participant & Exchange ob... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import argparse
import time
import psutil
import torch
import torchvision
import torchvision.transforms as transforms
import torch.distributed as dist
import torch.utils.data.distributed
import numpy as np
import torch.nn as nn
import torch.nn.fun... |
from django.test import TestCase
HTTP_OK = 200
class IndexPageTests(TestCase):
def test_index_page_status_code(self):
self.assertEqual(self.client.get('/').status_code, HTTP_OK)
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
boston = load_boston()
bostData = pd.DataFrame(boston.data, columns=boston.feat... |
"""Class implementation for click interface.
"""
from typing import Any
from typing import Dict
from typing import Optional
from apysc.event.event_interface_base import EventInterfaceBase
from apysc.event.handler import Handler
from apysc.event.handler import HandlerData
class ClickInterface(EventInterf... |
from sqlalchemy import *
from sqlalchemy.sql.expression import select, table as TABLE
from sqlalchemy.sql.expression import column as COLUMN
from mmal.utils import extend_col
from mmal.proto import (
BetaMMALServicer,
Reply,
Path,
TimeSeries,
)
def exception_handler(func):
def inner(*args, **kwargs... |
# Generated by Django 3.1.2 on 2020-11-16 01:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('question_manager', '0005... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import random
import string
count=1
maxLatitude=39.951168
minLatitude=39.846635
maxLongitude=116.46349
minLongitude=116.344872
print "use joymove;"
while count < 100:
count = count+1
latitude = random.uniform(minLatitude,maxLatitude)
longitude = random.uniform(... |
#!/usr/bin/env pypy
import sys
lines = iter(sys.stdin)
next(lines) # throw away first line
def main():
for case, line in enumerate(lines, 1):
print 'Case #%i:' % case
N, J = (int(x) for x in line.split())
answers = 0
for coin in range(2 ** (N-2)):
coin = '1%s1' % for... |
from pyclustering.cluster.xmeans import xmeans
def get_clusters(coordinates):
xmeans_instance = xmeans(coordinates)
xmeans_instance.process()
clusters = xmeans_instance.get_clusters()
return clusters |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the operating system file-like object implementation."""
import os
import unittest
from dfvfs.file_io import os_file_io
from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.path import factory as path_spec_factory
from dfvfs.resolver impo... |
'''
An image recognition analysis powered by TensorFlow.
Prequisite: An image needs to be uploaded to the server at
http://52.65.25.198/img/{imageTitle}
Input: The imageTitle in command line arguments (including the
file format). For example: 'banana.jpg'
Output: An updated csv file saved in the same... |
import sys, os; sys.path.append('..')
import pyneb as pn
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns; sns.set_style('darkgrid')
from nebulous.cel import cel_tem_dict
n_e = 1e3
tem = np.linspace(5e3, 15e3, 25)
ions = {}
waves = {}
for ion in ['NII', 'OIII', 'NeIII', 'SIII']:
ions[ion]... |
#!/usr/bin/python3
"""
input genomic positions into the ucsc genome website and download the concurrent fasta files for any indicated organism and library
"""
from bs4 import BeautifulSoup
import bs4
from bs4 import *
import urllib.request
import sys
def getFasta(seq, output, lib):
print('using ' + lib + ' as ... |
from numbers import Number
from stats_arrays import (
UndefinedUncertainty,
UniformUncertainty,
TriangularUncertainty,
NormalUncertainty,
NoUncertainty,
LognormalUncertainty,
)
def get_uncertainty_type(obj):
guesses = ("uncertainty type", "uncertainty_type", "uncertainty_type_id")
for ... |
fword = raw_input("Enter file name: ")
fhand = open(fword)
counting = fhand.read()
counting = counting.split()
words = dict()
for item in counting:
words[item] = 1
print words |
# -*- coding: utf-8 -*-
# Copyright 2019 Kolushov Alexandr <https://it-projects.info/team/KolushovAlexandr>
# License MIT (https://opensource.org/licenses/MIT).
import odoo.tests
from odoo.api import Environment
@odoo.tests.common.at_install(True)
@odoo.tests.common.post_install(True)
class TestUi(odoo.tests.HttpCas... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import tqdm
import torch.nn.functional as F
PATH_SAVE_MODEL_WEIGHT='model_weight/model_try.pth'
training_data = np.load("train_data.npy", allow_pickle=True)
print(len(training_data))
nb_classes=8
im_size=96
class Net(nn.Module)... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import os,sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
#print(BASE_DIR)
if __name__ == '__main__': # #如果模块是被直接运行的,则代码块被运行,如果模块是被导入的,则代码块不被运行。
from core import main
main.login_entry()
|
import glob
import cv2
import os
import numpy as np
class VOC(object):
def __init__(self, pra_config):
self.root_path = pra_config.dataset_root_path #'/Users/xincoder/Documents/Dataset/VOCdevkit/VOC2007'
self.segmentation_class_path_list = glob.glob(os.path.join(self.root_path, 'SegmentationClass/*.png'))
self.... |
from Game.StartGame import chess
from Utilities.ConsleControl import clearScreen
from Utilities.PrintChess import printChess
def GetStep():
x = -1
y = -1
try:
x = int(input("请输入你想下棋的行数:"))
y = int(input("请输入你想下棋的列数:"))
global temp
temp = chess[x - 1][y - 1]
... |
import uuid
import csv
Publisher_EEBO_File = open("/Users/Brishti/Documents/Internships/Turtle-RDF/publishedby_final.csv", "rU")
outputfile = open("/Users/Brishti/Documents/Internships/Turtle-RDF/publishedby_final_uuid.txt", "w")
for ix, line in enumerate(Publisher_EEBO_File):
if ix > 0: # skip header
lin... |
"""
Copyright (C) 2017 Data61 CSIRO
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
Endpoint objects for the user to view and manipulate. These wrap around
server Session objects and call methods to talk to the server.
"""
import collections
import os
import tempfile
from functools import ... |
"""
Test suite for Financial Calculator python test
"""
import pytest
import submission as Submission
@pytest.mark.timeout(5)
@pytest.mark.parametrize("test_input,expected_output", [
([10000, 20, 0.1], 572749.99),
([20000, 10, 0.104], 324926.69),
([10000, 20, 0.1], 572749.99),
([20000, 15, 0.1], 635449... |
import RPi.GPIO as GPIO
import threading
import Queue
import time
import subprocess
# TODO: Decide if LidarReader should handle all of the lidar data or if each
# Lidar should have its own LidarReader object, perhaps? Depends on the C
# implementation, probably
# TODO: Should the C implementation run in a continuous ... |
import cv2
import time
import numpy as np
from wait_for_format import wait_for_format
def capture(cap):
while True:
ret, frame = cap.read()
yield frame
def progress(itr, update_interval=1):
start_time = None
last_time = None
for i, x in enumerate(itr):
cur_time = time.time()
... |
import Source
INIT_RECEIVER = [0, 0]
INIT_TRANSMITTER = [0, 50]
speed = 2
movecount = 10
Source(INIT_RECEIVER, INIT_TRANSMITTER, speed, movecount) |
usr_input = input("stop copying me: ")
while usr_input != "stop":
print(usr_input)
usr_input = input("stop copying me!! ")
print("You win!!!")
|
"""User scan."""
import click
from gitalizer.extensions import db
from gitalizer.models import (
Commit,
commit_repository,
Repository,
)
@click.group()
def delete():
"""Cli wrapper for the database delete command group."""
pass
@click.command()
@click.argument('full_name')
def repository(full_... |
while True:
n = int(input("Ingresar numero: "))
if n >= 1:
break
while True:
a = n % 10
if a < 10:
break
print("El ultimo digito del numero es:", a)
b = n
while True:
b = b / 10
if b < 10:
break
print("El primero digito del numero es:", b) |
"""working with numbers"""
#from math import * # Communly used to do advanced maths functions
# I watch this course : https://www.youtube.com/watch?v=rfscVS0vtbw&t=52s&ab_channel=freeCodeCamp.org
print(2) # It prints the number I wrote could be also a decimal number as 2.22208 for exemple
print(-2) # It can also pri... |
#!/usr/bin/python
'''From here: http://stackoverflow.com/questions/4250125/generate-permutations-of-list-with-repeated-elements
and here: http://blog.bjrn.se/2008/04/lexicographic-permutations-using.html'''
def lexicographic_permutations(seq):
'''Algorithm L for The Art of Computer Programming, Volume 4, Fascicle... |
from pymongo import database
from datetime import datetime
def adicionar_user(db: database, member):
data = {
"_id": member.id,
"nome_real": None,
"nome": member.name,
"discriminador": member.discriminator,
"avatar": member.avatar,
"administrador": False,
"mo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from time import sleep
import re
import sys
import requests
import urllib.request
import random
import argparse
good = "\033[92m✔\033[0m"
# This magic spell lets me erase the current line.
# I can use this to show for example "Downloading..."
# and then "Downloaded" o... |
#coding:utf-8
import numpy as np
import os
import cv2
import struct
#get the image and lable set
def load_mnist(path, kind='train'):
"""Load MNIST data from `path`"""
labels_path = os.path.join(path, '%s-labels-idx1-ubyte' % kind)
images_path = os.path.join(path, '%s-images-idx3-ubyte' % ki... |
"""
Storage for all of the HTML/Javascript which powers the web frontend.
"""
NOT_FOUND_PAGE = b'Not Found'
AJAX = b'''
function ajax(uri, data, headers, on_ready) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = (function() {
if (xhr.readyState == 4) {
on_ready(xhr.responseText... |
import numpy as np
import os
from PIL import Image
from tqdm import tqdm
folder_path = ['images', 'masks']
for folder in folder_path:
if not os.path.exists(folder):
os.makedirs(folder)
print("creat a new folder named {}".format(folder))
image_path = 'images'
label_path = 'labels'
img_size = 2448... |
import time
from graphics import *
######################
def first_riddle():
answer = 'teapot'
count = 0
while count < 3:
print("\nFirst1#: What beging with 'T', ends with 'T', and has 'T' in it?\n")
print("\n")
print("\n")
answer_user = input("\nPlease type y... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 17 19:59:43 2018
@author: Trushant Kalyanpur
"""
import pandas as pd
import numpy as np
from kerasSentModel import kerasSentiment
train_df = pd.read_csv('train.csv')
train_samples = 100000
train_df = train_df.iloc[0:train_samples,:]
#replace empty cells with Nan
tr... |
# 人员数据库:
# 姓名 年龄 性别 编号 任职公司 薪资 部门编号
# ["曹操", "56", "男", "106", "IBM", 500, "50"],
# ["大乔", "19", "女", "230", "微软", 501, "60"],
# ["小乔", "19", "女", "210", "Oracle", 600, "60"],
# ["许褚", "45", "男", "230", "Tencent", 700, "10"]
r1 = {"name": "曹操", "age": 56, "sex": "男", "eid": 106, "dep": "IBM", "salary": 500, "... |
def findMotif(s, t):
motifLen = len(t)
pos = []
for index in range(0, len(s) - motifLen):
motif = s[index:index + motifLen]
if motif == t:
pos.append(index + 1)
return pos
|
import pandas as pd
import datetime
from datetime import date
#Shows ALL ROWS - remove for testing
pd.set_option('display.max_rows', None)
#Dataframes of county & state counts
states_url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv'
states = pd.read_csv(states_url, delimiter = ',')
... |
# Judge.py
class Judge:
# 숫자 비교, 판정
def judge(self, number, exp):
# 기록용 리스트 - [스트라이크, 볼, 아웃]
result = [0, 0, 0]
for i in range(3):
# 스트라이크, 볼 판정
for j in range(3):
if number[i] == exp[j]:
if number[i] == exp[i]:
... |
# Class is a group of attributes and methods.
'''
- Attributes : Attributes are represented by variable
- Method : Method is represented by Function (99% same)
- __init__() : this is constructor and this is used only initialize the variable. and aa method ne
call karvani jarur nathi padti.
... |
import sys
from build_scripts.content import Content
if __name__ == "__main__":
content = Content()
print(content.get_page_info(sys.argv[1]).get(sys.argv[2], "")) |
from django.contrib import admin
from .models import Articulo, Clientes, Pedidos, DetallePedidos
# Register your models here.
class ArticuloAdmin(admin.ModelAdmin):
readonly_fields = ('created', 'updated')
list_filter = ("nombre", "seccion")
admin.site.register(Articulo, ArticuloAdmin)
class ClientesAdmi... |
#!/usr/bin/env python3
import numpy as np
import cv2
import os
from time import sleep
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
subjects = ["", "Rennan", "Silvio", "Unknown"]
def detect_face(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascades/... |
__plugin_name__ = 'yahourcall'
__plugin_usage__ = r"""
yet another hour call
https://github.com/noahzark/yahourcall
配置请参考constant.py
报时语音请修改config.json
""".strip()
from .yahourcall import bot
|
import json
import os
import unittest
import pandas as pd
from hed.models.df_util import get_assembled
from hed.tools.remodeling.dispatcher import Dispatcher
from hed.tools.remodeling.operations.summarize_hed_tags_op import SummarizeHedTagsOp, HedTagSummary
class Test(unittest.TestCase):
@classmethod
... |
# def sumofcollection(*num): # Tuple=> Immutable
# for i in num:
# for j in i:
# print(j)
# print('*'*10)
#
# list = [500,800,50,25,45]
# dict = {123:"Kimhour", 134: "Sereyvann", 145: "Ratanak"}
# sumofcollection(list, dict)
def sumofcollection(list_num):
return sum(list_num)
resul... |
import pandas as pd
import numpy as np
def get_stats(train_df, test_df, target_column, group_column = 'manager_id'):
'''
target_column: numeric columns to group with (e.g. price, bedrooms, bathrooms)
group_column: categorical columns to group on (e.g. manager_id, building_id)
'''
train_df['row_id'... |
from __future__ import absolute_import
from django import template
from django.db.models import get_model
from configuration.models import Configuration
register = template.Library()
@register.assignment_tag()
def get_configuration(config_string):
split = config_string.rsplit('.', 1)
if len(split) != 2:
... |
import pymysql
import datetime
pymysql.install_as_MySQLdb()
from users import db, bcrypt
class User(db.Model):
""" Class User model"""
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(10))
username = db.Column(db.String(30), unique=True, nullable=False)
email = db.Column(db... |
from __future__ import print_function
from datetime import datetime
from pandas import read_csv, DataFrame
from sklearn.cross_validation import KFold, cross_val_predict
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.