text stringlengths 38 1.54M |
|---|
import requests
from bs4 import BeautifulSoup
from oauth2client.service_account import ServiceAccountCredentials
import gspread
import time
# __init__
gc_key ='your gc_key'
# set oauth
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCreden... |
import re
CONFIG = re.compile(r"(?P<name>[a-z0-9\_]*)\s*(?P<value>.*);")
INCLUDE = re.compile(r"[^\#]include\s*\"(?P<file>[^\0]+)\";")
ASTERISK = re.compile(r"\*$")
WHITESPACE = re.compile(r"\s\s")
VHOST = re.compile(r"[^\#]server\s\{([^\#].*)\}")
HTTP_BASE = re.compile(r"(?P<type>GET|POST|HEAD)\s(?P<uri>.*)\sHTTP\/(... |
class Development:
def __init__(self):
pass
ES_HOST = 'search-challenge-tzmrlhv2uxu3u27atrvo5mxf2u.us-east-1.es.amazonaws.com'
ES_PORT = 80
ES_TIMEOUT = 10
class Test:
def __init__(self):
pass
ES_HOST = 'test_env'
ES_PORT = 0
ES_TIMEOUT = 10
class Production:
de... |
#!/usr/bin/env python3
# Mara Huldra & Kvaciral 2021
# SPDX-License-Identifier: MIT
import argparse
import math
import sys
import psutil
import time
from ckbpipe import CKBPipe
class Handler:
def __init__(self, ckb):
self.ckb = ckb
def set_lightbar(self, color, memory_usage=100, threshold=0):
... |
from django import forms
from signup.fields import ListTextWidget
class SignupForm(forms.Form):
county = forms.CharField(required=True, label='')
def __init__(self, *args, **kwargs):
_country_list = kwargs.pop('data_list', None)
super(SignupForm, self).__init__(*args, **kwargs)
self.fie... |
from django.urls import path
from django.views.generic.base import TemplateView
from . import views
from django.contrib.auth import views as auth_views # for login and logout
from .forms import (UserLoginForm, PwdResetForm, PwdResetConfirmForm)
app_name ='account'
urlpatterns = [
path('register/', views.accou... |
import streamlit as st
import numpy as np
import utils
import pandas as pd
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import precision_score, recall_score
from SessionState import get
st.set_option('deprec... |
from django.shortcuts import render,get_object_or_404
from .models import Course ,Subject,Teacher
from .forms import ContactForm,SnippetForm
# Create your views here.
def index(request):
course=Course.objects.all()
return render(request,"index.html", {'course':course})
def courses(request):
course=Course.objects.al... |
from random import choice, choices, randrange
from django.contrib.auth.models import Group, User
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
Create a bunch of randomly named users with random group affiliations for
testing purposes.
"""
help = 'Create test ... |
"""
These integration tests exist solely to test the interaction between pyggybank and GPG on the CLI.
All attempts should be made to avoid extending these tests in preference for unit tests of the functions
themselves (where necessary, mocking out the GPG interactions).
TODO: It would be great to bring these tests in... |
"""
Strat:
Iterate through arr, from right to left, while keeping track
of the largest element we've seen. max_so_far starts out at -1,
because that's what the last elem's value will be. As we iterate,
we compare to current num's value to max_so_far; update as appropiate.
Stats: O(n) time
Runtim... |
from flask import redirect, session
from functools import wraps
from twilio.rest import Client
import sqlite3
import arrow
from flask import Flask, render_template, request, session
from tempfile import mkdtemp
from flask_mail import Mail, Message
import os
app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = ... |
# -*- coding: utf-8 -*-
lis1=list(range(5,20,1))
lis2=list(range(9,24,1))
lis1.append(sum(lis1))
lis2.append(sum(lis2))
lis1=sorted(lis1,reverse=True)
lis2=sorted(lis2,reverse=True)
print(lis1.pop()*lis2.pop()) |
import datetime
import sqlalchemy
from flask_login import UserMixin
from sqlalchemy import orm
# from sqlalchemy.dialect.postgresql import JSON
from .db_session import SqlAlchemyBase
class Orders(SqlAlchemyBase, UserMixin):
__tablename__ = 'orders'
id = sqlalchemy.Column(
sqlalchemy.Integer, primary... |
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('bioinfobiobureau')
print(bucket)
# files = s3.Bucket('bioinfobiobureau').objects.filter(Prefix='input')
# # print(bucket)
# for file in files:
# print(file)
# for bucket in s3.buckets.all():
# print(bucket.name)
files = []
for key in bucket.objects.... |
from django.shortcuts import get_object_or_404
from rest_framework import viewsets, status, filters
from rest_framework.decorators import (
action,
api_view,
)
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from .filters import FilterByDistance, FilterByDate, Filte... |
# Generated by Django 3.2.5 on 2021-07-16 06:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0002_auto_20210716_0321'),
]
operations = [
migrations.CreateModel(
name='Brand',
... |
# Generated by Django 3.0.7 on 2020-07-05 14:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0017_auto_20200705_2044'),
]
operations = [
migrations.AddField(
model_name='category',
name='category_id',
... |
# 31. 문자열을 정수로 바꾸기
def solution(s):
answer = ''
answer += s
answer = int(answer)
return answer
str_1 = '1234'
str_2 = '-1234'
print(solution(str_1))
print(solution(str_2)) |
def average_grade(roster=[]):
total = 0
for i in range(len(roster)):
total = total + roster[i].student_grade
average = total/len(roster)
return average
|
# 辺の長さが {a,b,c} と整数の3つ組である直角三角形を考え,
# その周囲の長さを p とする. p = 120のときには3つの解が存在する:
# {20,48,52}, {24,45,51}, {30,40,50}
# p ≤ 1000 のとき解の数が最大になる p はいくつか?
import time
def get_unique_list(seq):
seen = []
return [x for x in seq if x not in seen and not seen.append(x)]
# 答えの組を返す
def get_ressult_list(num):
res = [... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
"""
common configuration settings
"""
DEBUG = False
CSRF_ENABLED = True
SECRET = os.getenv('SECRET')
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedi... |
# Aa Aa 0 - Aa a Aa a Aa a AaN
N
'''N
Aa a a a a a-a a a a a a a a a aN
a aN
N
Aa a:N
N
- Aa a a a a a a.N
- Aa a a a a a a a.N
- Aa a a a a a a a a a a a a.N
- Aa a a a a a a.N
N
'''N
N
a a a aN
a a a aN
N
N
a a('a_a_0.a', a='a-0') a a_a:N
a_a = a(a(a_a))N
a_a_a = a_a[0]N
a_a = a_a[0:]N
N
a('Aa a')N
a(a_a_... |
# coding: utf-8
"""
vault/kernel/core_api/proto/v1/accounts/core_api_account_schedule_tags.proto
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: version not set
Generated by: https://github.com/swagger-api/... |
from flask import *
import tmdbAPI
tmdb_app = Flask(__name__)
# === Start of Main Routes ===
@tmdb_app.route("/")
def index():
return render_template("index.html")
@tmdb_app.route("/search")
def search():
# valid_cats and params will be used to ensure user input is valid.
# These are defaults that wi... |
import random
def gen_random_word(num):
seed = "abcdefghijklmnopqrstuvwxyz"
sa = []
for i in range(num):
sa.append(random.choice(seed))
salt = ''.join(sa)
return salt
|
#!/usr/bin/python3.5
from PIL import Image
import random
import math
# image/canvas size
image_x_size = 1920
image_y_size = 1080
# blob properies
blobs = 10
max_blob_size = 1080
min_blob_size = 10
max_alpha = 100
# create background and foreground canvas and set 'pixels' to foreground.
# background is black and ful... |
# get current age.
# max age = 90
# count the number of days left
# assume 365 days, 52 weeks and 12 months in a year
age = int(input("Please enter your age "))
years_left = 90 - age
days_left = years_left * 365
weeks_left = years_left * 52
months_left = years_left * 12
print(f"you have {days_left} days, {months_le... |
from seis_grados import *
import sys
KB = 'Bacon Kevin'
def camino_hasta_KB(dataset, actor):
"""
Imprime el camino más corto con el cual se llega desde cualquier
actor hasta Kevin Bacon.
"""
if not pertenece_actor(dataset,actor):
print("No se pudo encontrar un camino desde el actor ingres... |
import json
import csv
from result import Result
import requests
import time
import re
import io
from extract_entities import entities
writer = csv.writer(open("welink_results_qald7.csv", 'a', newline=''))
url = 'http://127.0.0.1:8000/api/'
headers = {'Content-type': 'application/json'}
with open('q... |
import socket
def TcpClient(target_host,target_port):
# Socket object creation
#socket.AF_INET Use of Ipv4 address or hostname
#socket.SOCK_STREAM TCP Client
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#Client connection
client.connect((target_host,target_por... |
"""
Module to build and train neural networks to predict protein properties.
"""
import os
import yaml
__version__ = "0.7.2"
CONFIG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config")
BASE_CONF_FILE = os.path.join(CONFIG_DIR, "base_config.yml")
with open(BASE_CONF_FILE, 'r') as base_conf_file:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import codecs
from xml.dom.minidom import parse, parseString
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
dom = parse('data.xml')
domains = dom.getElementsByTagName('d'... |
from brownie import Impl, accounts, reverts
ERR_MSG = "Number not greater than 10"
def test_shouldThrow():
impl = Impl.deploy({ 'from': accounts[0] })
with reverts(ERR_MSG):
impl.shouldThrow(1)
def test_shouldThrowWithoutWithStatement():
impl = Impl.deploy({ 'from': accounts[0] })
impl.shouldThrow(1)
|
# crawl "snkrs pass" data from nike. It will notify you by message as long as it detects "snkrs pass" from nike.com
#But there is a delay between "pass" and message. Range:[0,50s]
from selenium import webdriver
from time import sleep
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.suppo... |
import pygame, math, sys
from map_engine import *
from entities import *
from Rendering import *
from Script_Engine import *
pygame.init()
#Declaring the Entities used in the game
player1 = Player("Alex", [0, 0], "/home/euler/Desktop/dungeons_v2/Assets/Player/blank_south.png", "Nerd", [384, 256], [])
Player.Pos_Calc... |
nota1 = float(input("primeira nota: "))
nota2 = float(input("segunda nota: "))
nota3 = float(input("terceira nota: "))
nota4 = float(input("quarta nota: "))
media = (nota1 * 1 + nota2 * 2 + nota3 * 3 + nota4 * 4)/10
print(round(media, 2))
|
import requests
import json
import random
a = ["abs", "xyz", "vrt", "alpha", "beta"]
b = {"abs":"as01hu@gmail.com","xyz":"xyz@outlook.com","vrt": "alpha@yahoomail.com", "alpha":"xwe@yahoo.in", "beta":"ade@gmail.com"}
for i in range(5):
username = random.choice(a)
name = random.choice(["Ashu", "pp"])
email... |
#https://programmers.co.kr/learn/courses/30/lessons/42862
def solution(n, lost, reserve):
answer = 0
st = []
for s in range(n):
st.append(0)
if s + 1 in lost:
st[s] -= 1
if s + 1 in reserve:
st[s] += 1
reserve = [s for s in range(n) if st[s] == 1]
... |
'''
#TRABALHO 1 DE GRAFOS
#EXERCICIO: STORMSOFSWORDS
#PYTHON V 2.7.13
#UBUNTU 17.04
#ALUNOS: LEONARDO LARANIAGA ra94985
# WELLINGTON TATSUNORI ra94595
# THIAGO KIRA ra78750
#ARQUIVO DE ENTRADA:
# stormofswords.csv
#FUNCOES:
# BFS
# CAMINHO BFS
# BIPARTIDO
# DFS (corrigido)
# STACK DFS
# C_COMPONENTS... |
#This is meant to take two files and compare them
def main():
#Stores the lines of the file specified by the user
source = readFile('Provide the name of the first file')
source2 = readFile('Provide the name of the second file')
#This calls the function to extract all the words from a file
words... |
# package com.gwittit.client.facebook.entities
import java
from java import *
from com.google.gwt.core.client.JavaScriptObject import JavaScriptObject
class StreamFilter(JavaScriptObject):
"""
Facebook Stream Filter. Use this to filter stream
@see <a href="http://wiki.developers.facebook.com/index.... |
from pylab import *
x = [1, 2, 3, 4, 5]
y = [1.6, 1.6,1 , 1, 1.5]
width = [5, 2.5, 1.5, .75, .75]
for i in range(len(x)-1):
#plot(x[i:i+2], y[i:i+2], linewidth=width[i])
print x[i:i+3]
plot(x[i:i+5], y[i:i+5], linewidth=width[i])
show() |
#program for single user recommendation
import numpy as np
import pandas as pd
#import math
from contextlib import redirect_stdout
ratings = pd.read_csv('ratings1.csv')
#print(ratings.info)
#rm[a][b] is rating matrix in which a->movie_id & b->user_id
rm =np.ndarray(shape=(100000,944), dtype=float)
dat... |
# kind of an interface
class Plugin_Prototype():
def __init__(self):
self.module_name = "Plugin_Prototype"
self.module_version = "1.0"
def set_client(self, client):
'''
The Plugin needs the client which perfoms the actions
'''
self.client = client
def r... |
num = float(input("학점을 입력하세요."))
if num == 4.5:
print("당신의 학점은 {}이며, 설명은 '신' 입니다.".format(num))
elif 4.2 <= num <= 4.49:
print("당신의 학점은 {}이며, 설명은 교수님의 사랑 입니다.".format(num))
elif 3.5 <= num <= 4.19:
print("당신의 학점은 {}이며, 설명은 현 체제의 수호자 입니다.".format(num))
elif 2.8 <= num <= 3.49:
print("당신의 학점은 {}이며, 설명은 일... |
class ZeroError(Exception):
def __init__(self, txt):
self.txt = txt
x = 100
while True:
try:
y = int(input(f'введите делитель для {x} : '))
if y == 0:
raise ZeroError("На отрицательное число делить нельзя!")
print(f"{x} разделить на {y} = {x / y}")
break
... |
from rest_framework.response import Response
from rest_framework import viewsets, status
from django.core.mail import send_mail
from main.settings import EMAIL_HOST_USER, EMAIL_LIST
from .models import Contact
from .serializers import ContactSerializer
class ContactViewSet(viewsets.ViewSet):
"""
A simple... |
# Import the necessary modules for development
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expecte... |
import math
class CandyFactory:
def __init__(self, m, w, p, n):
self.balance = 0
self.m = m
self.w = w
self.p = p
self.n = n
self.passes = 0
self.last_prod = self.m * self.w
self.curr_prod = self.m * self.w
def make(self, passes ... |
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q
User = get_user_model()
class CustomBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
try:
# 通过用户名或邮箱来获取用户对象
... |
sum=0
a=5
while a>0:
num=int(raw_input("enter a integer number"))
sum=sum+num
a=a-1
print "average number of the user input",sum/6.0 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\Pankaj\ABXpulse\REPO\SOURCE\SCRIPTS\PYTHON\LightNPray\lib\MayaAddon\inp_render_setting_ui.ui'
#
# Created: Mon Nov 01 19:26:27 2010
# by: PyQt4 UI code generator 4.4.3
#
# WARNING! All changes made in this file will be lost!
... |
# Generated by Django 2.1.7 on 2019-03-23 13:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('homedetail', '0012_auto_20190320_1438'),
]
operations = [
migrations.AlterField(
model_name='data',
name='Detail',
... |
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
from . import session
class Test_Ipwd(session.make_sessions_mixin([('otherrods', 'rods')], []), unittest.TestCase):
def setUp(self):
super(Test_Ipwd, self).setUp()
self.admin = self.admin_sessions... |
import urllib.error
import urllib.request
import scrapy
class DailyHighLowPerChanceOfRain(scrapy.Spider):
name = "DailyHighLowPerChanceOfRain"
def start_requests(self):
start_url = 'https://tds.scigw.unidata.ucar.edu/thredds/catalog/grib/NCEP/NDFD/NWS/CONUS/NOAAPORT/latest.html'
yield scrapy... |
# /ticket/<id>/vote/<user> --> payload karte
# /ticket/<id>/close --> kein voten mehr möglich
# /ticket/<id>
# @app.route('/ticket')
# def user():
# return '{"status":"user"}' |
def heapify(arr, size, index):
largest = index
left = 2 * index + 1
right = 2 * index + 2
if left < size and arr[left] > arr[index]:
largest = left
if right < size and arr[right] > arr[index]:
largest = right
if largest != index:
arr[index], arr[largest] = arr[largest], a... |
import os
import django.core.handlers.wsgi
os.environ['DJANGO_SETTINGS_MODULE'] = 'example_client.settings'
application = django.core.handlers.wsgi.WSGIHandler()
|
from heapq import heapify, heappush, heappop
class Solution:
# @param A : integer
# @param B : list of integers
# @return a list of integers
def solve(self, K, A):
ans = []
minheap = []
heapify(minheap)
for i, num in enumerate(A):
if len(minheap) < K:
... |
import os
import sys
os.system('mspaint')
print('结束进程才能执行')
print(os.path)
print(sys.path)
os.system('mspaint C:\\Users\\GaoAolei\\Desktop\\1.png')
os.system('dir d:\\pycharmtest')
print('%x' %512) # 计算512的十六进制
|
import numpy as np
IMG_PX_SIZE = 80
HM_SLICES = 16
LR = 1e-3
MODEL_NAME = 'boldvst1w-{}-{}.model.tflearn'.format(LR, '2conv')
train_data = np.load('muchdata-80-80-16.npy')
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_c... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 4 16:41:40 2019
@author: z5075710, The Minh Tran
"""
#Need to validate using isinstance(x, int)/(y, str)
from Order import Order
class Staff:
def __init__(self, username = None, password = None):
self._order = []
self._orderRead... |
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui, uic
import pwd, grp
import pickle, operator
from os.path import expanduser
import os
idstart = 1000
form_class = uic.loadUiType("ui/main.ui")[0] # Load the main UI
dial1 = uic.loadUiType("ui/dial1.ui")[0] # Load the UI for profile managing
assign =... |
#!/usr/bin/env python3
""" represents a gated recurrent unit:"""
import numpy as np
class GRUCell:
""" represents a gated recurrent unit:"""
def __init__(self, i, h, o):
"""
-i is the dimensionality of the data
-h is the dimensionality of the hidden state
-o is the dimensionali... |
# Copyright 2023 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from unittest import TestCase
from coursedashboards.models import Term, StudentMajor
class TestStudentMajors(TestCase):
def setUp(self):
# create terms
self.winter2016 = Term()
self.winter2016.quarter... |
'''
tests for geojson outputter
'''
import os
from glob import glob
from datetime import timedelta
import numpy as np
import pytest
from gnome.outputters import TrajectoryGeoJsonOutput
from gnome.spill import SpatialRelease, Spill, point_line_release_spill
from gnome.basic_types import oil_status
from gnome.environme... |
import os
def count(dir='.', counter=0):
"returns number of files in dir and subdirs"
for pack in os.walk(dir):
for f in pack[2]:
counter += 1
return "No of files in '" + dir + "' : " + str(counter) + " files"
#print(count(".")) |
from __future__ import absolute_import
from django.db import IntegrityError, transaction
from django.utils import timezone
from rest_framework import serializers
from rest_framework.response import Response
from uuid import uuid4
from sentry.api.base import DocSection
from sentry.api.bases.project import ProjectEndpo... |
import numpy
from src.SphereHandModel.utils import xyz_uvd
from scipy.spatial.distance import cdist
# from src.SphereHandModel.ShowSamples import *
def cost_function(setname,DepthImg, inSpheres, Center, SilhouetteDistImg,SubPixelNum):
# if setname=='mega':
# Center = [320,240]
# if setname=='icvl':
... |
import FWCore.ParameterSet.Config as cms
displacedMuons = cms.EDProducer("MuonProducer",
ActivateDebug = cms.untracked.bool(False),
InputMuons = cms.InputTag("displacedMuons1stStep"),
FillPFMomentumAndAssociation = cms.bool(True),
... |
import graphene
from graphene_django import DjangoObjectType
from .models import Room
class RoomType(DjangoObjectType):
# Dynamic fields
# https://docs.graphene-python.org/en/latest/types/objecttypes/#resolver-parameters
is_fav = graphene.Boolean()
class Meta:
model = Room
# 공식문서에 따르... |
from __future__ import annotations
from typing import Literal
from prettyqt import statemachine
from prettyqt.utils import bidict
ChildModeStr = Literal["exclusive", "parallel"]
CHILD_MODE: bidict[ChildModeStr, statemachine.QState.ChildMode] = bidict(
exclusive=statemachine.QState.ChildMode.ExclusiveStates,
... |
from flask import Flask, request, jsonify, make_response, json
from flask_jwt_extended import (
JWTManager, create_access_token, create_refresh_token, jwt_required,
get_jwt_identity, jwt_refresh_token_required, get_raw_jwt)
from app.api.v2.models.user import UserClass as user
from app.api.errorHandler.user... |
from app import app, celery
from app.tasks import retrieve_page, boilerpipe_extract_and_populate
from flask import render_template, flash
@app.route('/')
def welcome():
return render_template('crawler.html')
@app.route('/initiate_crawl')
def initiate_crawl():
retrieve_page.delay(app.config['SEED_URL'])
f... |
import serial
import time
import sys
# Stolen from http://stackoverflow.com/questions/472977/binary-data-with-pyserialpython-serial-port
def a2s(arr):
""" Array of integer byte values --> binary string
"""
return ''.join(chr(b) for b in arr)
# @param block string
def print_response(block, n=0):
if n =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QApplication
from models.window_main import MainWindow
if __name__ == "__main__":
# 记录崩溃信息
# log_dir = os.path.join(os.getcwd(), 'crash')
# if not os.path.exists(log_dir):
# os.mkdir(log_dir)
# cgitb.enable(fo... |
from django.conf.urls import url
from . import views
handler404 = views.e404;
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^news/$', views.NewsView.as_view(), name='news'),
url(r'^contact/$', views.ContactView.as_view(), name='contact'),
url(r'^comps/$', views.CompositionsView.as_view(),... |
from app.stories.models import User,Bot,Channel
user1=User(userName='Admin',password="Admin")
user1.save()
#bot1=Bot(botName='SampleBot',botDescription="This is sample bot")
#bot1.save()
#channel1=Channel(channelName='Spark')
#channel1.save() |
class Solution(object):
def findMinArrowShots(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
if not len(points):
return 0
def overlap(i1, i2):
return ((i2[0] <= i1[0] <= i2[1]) or (i1[0] <= i2[0] <= i1[1]))
... |
import six.moves.urllib as urllib
import os
import sys
import tarfile
base_path = './pretrained_models'
filename ='faster_rcnn_inception_v2_coco_2018_01_28.tar.gz'
try:
import urllib.request
except ImportError:
raise ImportError('You should use Python 3.x')
if not os.path.exists(os.path.join(base_path, file... |
#!/usr/bin/python3
import jinja2
import os
import logging as log
import sys
log.basicConfig(stream=sys.stderr, level=os.environ.get("LOG_LEVEL", "WARNING"))
def convert(src, dst):
logger = log.getLogger("convert()")
logger.debug("Source: %s, Destination: %s", src, dst)
open(dst, "w").write(jinja2.Templat... |
import unittest
from format_price import format_price
class FormatPriceTest(unittest.TestCase):
def test_integer_part_is_zero(self):
self.assertEqual(format_price(0.10), '0.10')
def test_decimal_part_is_zero(self):
self.assertEqual(format_price(3245.000000), '3 245')
def test_input_is_i... |
# -*- coding: utf-8 -*-
# Python面试题:请写出一段Python代码实现删除一个list里面的重复元素
l = [1, 3, 2, 'a', 'z', 'd', 3, 'd', 'z']
# set
print list(set(l))
# dict
print {}.fromkeys(l).keys()
|
"""
Titanic Data - exploring our titanic data set
"""
import pandas as pd
import numpy as np
def main():
# import data
df = pd.read_csv('../data/titanic-train.csv')
print('------------COLUMNS------------')
print(df.columns)
btwn_70_and_75 = df[(df['Age'] > 70) & (df['Age'] < 75)]
print('... |
from django.contrib import admin
from webapp.models import News, Category
admin.site.register(News)
admin.site.register(Category)
|
import fileinput
from functools import reduce
from itertools import permutations
def parse(l):
a, b = l.split(' | ')
return (tuple(a.split()), tuple(b.split()))
'''
a
b c
d
e f
g
'''
toi = {
'abcefg': 0,
'cf': 1,
'acdeg': 2,
'acdfg': 3,
'bcdf': 4,
'abdfg': 5,
'abdefg': 6,
... |
from main import app, get_db
from starlette.testclient import TestClient
import pytest
import asyncio
from databases import Database
database = Database("sqlite:///./test_test.db", force_rollback=True)
# @app.on_event("startup")
# async def startup():
# await database.connect()
# @app.on_event("s... |
import streamlit as st
import pandas as pd
import numpy as np
import faiss
'''
Similar Movies Recommender
==========================
Search for a title and get recommendations for similar movies.
------
## Recommendations
'''
def load_data():
# Import movie indexes
movie_index = pd.read_pickle('output/embe... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
class TextRNN(nn.Module):
def __init__(self):
super(TextRNN, self).__init__()
#三个待输入的数据
self.embedding = nn.Embedding(5000,... |
import tempfile
import os
from page_loader import engine
from page_loader.storage import url_normalization
URL = 'https://gevhoo.github.io/python-project-lvl3/tests/fixtures/index'
HTML_FILE_NAME = 'gevhoo-github-io-python-project-lvl3-tests-fixtures-index.html' # noqa: E501
RESOURCE1 = 'gevhoo-github-io-python-proje... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import OrderedDict
import fnmatch
import obspy
import os
import re
import shelve
import warnings
import uuid
import event_query as search
class EventShelveException(Exception):
"""
Exception raised by this module.
"""
pass
class EventSh... |
import pygame
from pygame.display import *
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Checkers")
class Button:
def __init__(self,text,x,y,width,height,color1,color2):
mPos = pygame.mouse.get_pos()
mPressed = pygame.mouse.get_pressed()
self.dct = {'2':'X','1... |
from django.conf.urls import url
from . import views
urlpatterns = [
# vacantes
url(r'^crear-vacante/',
views.VacanteCreateView.as_view(),
name='crear_vacante'),
url(r'^editar-vacante/(?P<pk>\d+)/',
views.VacanteUpdateView.as_view(),
name='editar_vacante'),
url(r'^li... |
a, b, c, d, e, f = map(int, input().split())
cap = e / (100 + e)
max_noudo = 0
sugar_ans, water_ans = 0, 0
for i in range(f//(100*a)+1):
for j in range((f - (100 * a * i)) // (100 * b) + 1):
water = 100 * (i * a + j * b)
for k in range(((i * a + j * b)*e)//c+1):
for l in range(((i * a ... |
from django.apps import AppConfig
class OneEndpointPracticeConfig(AppConfig):
name = 'one_endpoint_practice'
|
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length = 50)
description = models.TextField()
image = models.ImageField(blank=True, upload_... |
# Generated by Django 2.2.1 on 2019-06-23 12:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('channelaudit', '0002_auto_20190623_1246'),
('senseid', '0001_initial'),
]
operations = [
migrations... |
"""Training Script"""
import os
import shutil
import numpy as np
import pdb
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import MultiStepLR
import torch.backends.cudnn as cudnn
from torchvision.... |
from multiprocessing import Process
import os
import time
class MyNewProcess(Process):
# 重写run方法, 调用p.start()的时候自动调用
def run(self):
for i in range(5):
print("--- ", i)
time.sleep(1)
def run_pro(name):
print("Run child process %s ( %s )" % (name, os.getpid()))
if __name__ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.