text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class signup(models.Model):
email = models.EmailField()
fullname = models.CharField(max_length=120,blank=True,null=True)
timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)
update... |
A= int(input("enter a 5 digit no:"))
addition = 0
while(A>0):
B = A % 10
addition = addition + B
A = A //10
print("sum of digits are:"+str(addition))
|
import sys
_module = sys.modules[__name__]
del sys
main = _module
models = _module
densenet = _module
googlenet = _module
inceptionv4 = _module
mobilenetv2 = _module
nasnet = _module
preactresnet = _module
resnet = _module
resnet_tiny = _module
resnext = _module
senet = _module
swin = _module
vgg = _module
vit = _modul... |
from pydub import AudioSegment
from pydub.utils import make_chunks
song = AudioSegment.from_wav("file.wav")
chunk_length_ms = 1000 # pydub calculates in millisec
chunks = make_chunks(song, chunk_length_ms) #Make chunks of one sec
#Export all of the individual chunks as wav files
for i, chunk in enumerate(chunks):
... |
"""Tests for `panels.FigureSizeLocator`."""
# Copyright 2016 Andrew Dawson
#
# This file is part of panel-plots.
#
# panel-plots is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License... |
# Question 5:<br>
# Write a program to accept customer details such as : Account_no, Name, Balance in Account,
# Assume Maximum 20 Customer In the bank.
# Write a function to print the account no and name of each customer with balance below rs 100.
class Bank_Account:
def __init__(self,account_no, name, bala... |
#coding=utf8
import sys
reload(sys)
sys.setdefaultencoding("utf8")
import httplib
import hashlib
import urllib
import random
import json
appid = '20160313000015392'
secretKey = 'MCmBwJkXJRqswDFwv2I5'
urlPrefix = '/api/trans/vip/translate'
def BaiduTrans(input,fromLang='en',toLang='zh'):
httpClient = None
salt = ra... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
import sys
import os
from telemetry.testing import serially_executed_browser_test_case
from telemetry.core import uti... |
from segmentmodel import getSegModel
from utils import vocabulary
from PIL import Image
import numpy as np
import cv2
import os
from scipy.misc import imsave
from adjustTextPosition import adjust
from ocrModel import getOCRModel
from PIL import Image, ImageFont, ImageDraw, ImageOps
im_heigth = 8*40
im_width = 16*40
in... |
def create_pattern(length):
uppercase_chars = 'ABCDEFGHIJKLMNOPQRSTUVXYZ'
lowercase_chars = 'abcdefghijklmnopqrstuvxyz'
number_chars = '0123456789'
x = y = z = 0
pattern = ''
while True:
if len(pattern) < length:
pattern += uppercase_chars[x]
if len(pattern) < ... |
class Solution(object):
def replaceElements(self, arr):
j=0
if len(arr) == 1:
arr[0]=-1
else:
for j in range(len(arr)-1):
print("j",j)
if j == len(arr)-2:
maxnum = arr[j+1]
print(maxnum)
... |
#!/usr/bin/env python3
"""Extract reads from FASTA based on IDs in file"""
import argparse
import os
import sys
from Bio import SeqIO
# --------------------------------------------------
def get_args():
"""get args"""
parser = argparse.ArgumentParser(
description='Argparse Python script',
... |
__author__ = 'wing'
from clip_main import *
def test_copy_bmp():
cit3 = ClipContentItem()
cit3.cl_type = CL_IMAGE
im = Image.open('2.png')
cit3.cl_data = get_bmp_data(im)
with open('a.bmp', 'wb') as f:
f.write(cit3.cl_data)
Mypb.copy(cit3)
def test_copy_png():
cit3 = ClipContentItem... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `atkinson.pungi.depends` package."""
import copy
import os
import pytest
from toolchest.genericargs import GenericArgs
from atkinson.pungi.depends import rpmdep_to_dep, dep_to_tuple, dep_to_nevr
from atkinson.pungi.depends import dep_to_rpmdep, nevr_to_dep... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import time
import torch
import logging
cur_path = os.path.abspath(__file__)
cur_dir = os.path.dirname(cur_path)
par_dir = os.path.dirname(cur_dir)
gra_dir = os.path.dirname(p... |
# Global variable section
STANDARD_ARABIC_TO_ROMAN = ((1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))
# Maximum arabic number to convert to to roman
MAX_NUM_TO_CONVERT = 3999
de... |
# 상속 : 클래스를 정의할때 부모 클래스를 지정하는 것
from turtle import*
class MyTurtle(Turtle):
def glow(self, x, y):
self.fillcolor("red")
turtle = MyTurtle()
turtle.shape("turtle")
turtle.onclick(turtle.glow) # 거북이 클릭하면 색상이 빨강색으로 변경
#
class Person:
def greeting(self):
print("안녕하세요")
class Student(Person):
... |
a=[]
length=int(input("no of elements"))
def insert():
global length
for i in range(0,length):
element=int(input(" "))
a.append(element)
def search():
global length
j=0
element=int(input(" element to search"))
while(j<length):
if(element==a[j]):
print("elemen... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.db import models
from django.utils import timezone
EIGENSCHAFTEN = dict(
{"GE": "Gewandheit",
"KK": "Körperkraft",
"KO": "Konstitution",
"KL": "Klugheit",
"MU": "Mut",
"CH": "Charisma",
"FF": "Finge... |
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
dal_InstituteCentres_url = 'https://www.dal.ca/research/centres_and_institutes.html'
#opening up connection and grabbing the pages
uClient = uReq(dal_InstituteCentres_url)
page_html = uClient.read()
uClient.close()
#html parser
p... |
# Generated by Django 3.1.1 on 2020-10-05 08:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('events', '0002_password'),
]
operations = [
migrations.CreateModel(
name='Programme',
... |
import time
import numpy as np
import aesara
y = aesara.tensor.type.fvector()
x = aesara.shared(np.zeros(1, dtype="float32"))
f1 = aesara.function([y], updates={x: y})
f2 = aesara.function([], x.transfer("cpu"))
print(f1.maker.fgraph.toposort())
print(f2.maker.fgraph.toposort())
for i in (1, 10, 100, 1000, 10000, 1... |
import os, shutil
import json
import random
import cv2
import numpy as np
from utils import get_path
from grad_cam import get_net, get_img_and_mask
def get_word_img_map():
with open(get_path('params/synsets.json'), 'r', encoding='utf-8') as f:
context = f.read()
synsets = json.loads(context)
... |
# -*- coding: utf-8 -*-
from django import forms
from .models import *
from django.conf import settings
class RegistroRepositorForm (forms.Form):
nombres = forms.CharField(max_length=100,required=True)
apellidos = forms.CharField(max_length=100, required=True)
email = forms.CharField(required= False)
... |
# Searching for an element in the list.
# IN operator
# Linear search
my_list = [10,20,30,40,50,60,70,80,90]
print(f"My list: {my_list}")
# IN operator
print("\nSearching a value by IN operator:")
value = 20
if value in my_list:
print(f"- The index of {value} value is {my_list.index(value)}.")
else:
print("... |
import shelve
import os
def save_game(player, entities, game_map, log, game_state):
with shelve.open('save_game', 'n') as file:
file['player_index'] = entities.index(player)
file['entities'] = entities
file['game_map'] = game_map
file['log'] = log
file['game_state'] = game_s... |
import json
import logging
from multiprocessing import Process
from threading import Thread
from logging_utils.generator import generate_logger, generate_writer_logger
from src.exchangeconnector import ExchangeConnector
from src.storage import Storage
from src.static import *
import time
class Executor(Thread):
... |
import pymongo
import scrapy
from weibotest.items import BaseInfoItem
from weibotest.items import WeiboInfoItem
import re
import datetime
import json
import traceback
from weibotest.settings import MONGO_HOST, MONGO_PORT, MONGO_DB_NAME, SCHOOL_BASE_INFO
class WeiboSpider(scrapy.Spider):
name = "weibo"
# url... |
def negativo (numero):
resultado = ""
for digito in numero:
if digito == "1":
resultado += "0"
elif digito == "0":
resultado += "1"
return resultado
def rotar_izq (numero):
inicial = numero[:1]
resultado = numero[1:] + inicial
return resultado
def rotar_... |
#!/usr/bin/env python3
import hashlib, io, struct, sys
from os import path
from libyaz0 import decompress
UNCOMPRESSED_SIZE = 0x2F00000
def as_word(b, off=0):
return struct.unpack(">I", b[off:off+4])[0]
def as_word_list(b):
return [i[0] for i in struct.iter_unpack(">I", b)]
def calc_crc(rom_data, cic_typ... |
#You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.
def split_and_join(line):
list = line.split(" ")
new_line = "-".join(list)
return new_line
s= "This is Sparta"
print(split_and_join(s))
|
#!/usr/bin/env python
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$May 05, 2015 13:31:12 EDT$"
from splauncher.core import main
if __name__ == "__main__":
import sys
sys.exit(main(*sys.argv))
|
import time
import numpy as np
import common
import pupper
import sim
def main(use_imu=False, default_velocity=np.zeros(2), default_yaw_rate=0.0):
# Create config
config = pupper.config.Configuration()
config.z_clearance = 0.02
simulator = sim.sim.Sim(xml_path="sim/pupper_pybullet.xml")
hardware_interface ... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 20,
"id": "b40f9af8",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 4, 6, 8, 10]\n"
]
}
],
"source": [
"# map\n",
"\n",
"def dobro(x):\n",
" retu... |
''' Tiernan Watson Arduino Coursework '''
import pygame
import serial
import g_settings
class Player(pygame.sprite.Sprite):
def __init__(self, width, height, color):
super().__init__()
self.width = width
self.height = height
self.move_speed = g_settings.PLAYER_MOVE_VEL
se... |
class Setting:
def __init__(self) -> None:
self.BASE_URL = 'https://www.hao4k.cn/'
self.LOGIN_URL = 'https://www.hao4k.cn/member.php?mod=logging&action=login'
self.SIGN_URL = 'https://www.hao4k.cn/qiandao/'
self.USERNAME = '18697998680'
self.PASSWORD = 'q529463245'
|
#!/usr/bin/python
#
# Test Suite For furnishings.py
# test_furnishings.py
#
# Created by: Jason M Wolosonovich
# 6/04/2015
#
# Lesson 7 - Project Attempt 1
"""
test_furnishings.py: Test suite for furnishings.py
@author: Jason M. Wolosonovich
"""
import unittest
from furnishings import Sofa, Bookshelf, Bed, Table... |
"""MCMC Test Rig for COVID-19 UK model"""
# pylint: disable=E402
import sys
import h5py
import xarray
import tqdm
import yaml
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability.python.internal import unnest
from tensorflow_probability.python.internal import dt... |
"""
project = 'Code', file_name = 'main.py', author = 'AI悦创'
time = '2020/5/19 8:16', product_name = PyCharm, 公众号:AI悦创
code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
"""
import cv2
def drawing(src, id=None):
image_rgb = cv2.imread(src)
image_gray = cv2.cvt... |
import argparse
### TODO: Load the necessary libraries
import os
from inference import Network
from openvino.inference_engine.ie_api import IENetLayer
import numpy as np
import cv2
CPU_EXTENSION = "/home/aswin/Documents/Courses/Udacity/Intel-Edge-Phase2/Projects/People-Counter-App/Repository/nd131-openvino-people-coun... |
# -*- coding: utf-8 -*-
from pymongo import MongoClient
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas.io.json import json_normalize
client = MongoClient('mongodb://localhost:27017/')
db = client['idioms']
with open('/home/josejm/a.txt', 'r') as f:
for line in f:
... |
print("Probando paquetes")
from mipaquete import pruebas
from mipaquete import herramientas
pruebas.Probando()
herramientas.nombreCompleto("Flavio", "Scheck")
|
'''
Task 1
The cyber security department for Blooming Cafe wants to know the temperature of Canberra in immutable list for a specific purpose. They have certain criterions to solve this problem. The criterions are given below:
SL NO Requirement Specification
1 Provide an option where they can take temperature in either... |
# Generated by Django 2.1.4 on 2019-01-04 08:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Room',
fields=[
... |
'''
1.import All the webScrape Files
2.import the sqlite DB
3.import all priceStruct files
4.get all price Strut dictionaries
5.compare values from sqlite DB to price struct Dictionaries
6.cost retrived from step 6 to be added to a new dictionary of price struct
7.from new priceStructDictionaries/new sqlite DB echo val... |
import json
import operator
import Tweet
from sklearn import metrics
from NaiveBayesClassifier import NaiveBayesCascadeClassifier
from RandomForestClassifier import RandomForestCascadeClassifier
from SVMClassifier import SvmCascadeClassifier
from KnnClassifier import KnnClassifier
class CascadeClassifier():
_TA... |
#
# @lc app=leetcode.cn id=1360 lang=python3
#
# [1360] 日期之间隔几天
#
# @lc code=start
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
maxDate = minDate = ""
if (date1 >= date2):
maxDate = date1
minDate = date2
else:
m... |
from django.contrib import admin
from dictionary.models import Dictionary
admin.site.register(Dictionary)
|
def sendmail(From, To, Subject, Content):
print('From:', From)
print('To:', To)
print('Subject:', Subject)
print('')
print(Content)
sendmail('gabor@szabgab.com',
'szabgab@gmail.com',
'self message',
'Has some content too')
|
#!/usr/bin/env python
import Geant4 as g4
from Geant4.hepunit import *
import numpy as np
# energies = (30.0 * MeV) * 2**np.arange(6)/32
# print(energies/MeV)
# [ 0.9375 1.875 3.75 7.5 15. 30. ]
def electron_spray():
energies = (30.0 * MeV) * 2**np.arange(6)/32
for energy in energies:
... |
from django.conf.urls.defaults import * #@UnusedWildImport
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^_static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static'}, name='static'),
url(r'^$', '... |
from django.urls import path
from . import views
from django.conf.urls import url
app_name = "users"
urlpatterns = [
url(
regex=r'^top100/$',
view=views.ListTop100.as_view(),
name = 'view_top100'
),
url(
regex=r'^list/$',
view=views.ListView.as_view(),
name = 'List_V... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# Generated by Django 3.2.4 on 2021-06-18 03:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Tokens',
fields=[
('id', models.BigAutoFiel... |
from feature_selector.models.taskonomydecoder import TaskonomyDecoder
from feature_selector.utils import SINGLE_IMAGE_TASKS, TASKS_TO_CHANNELS, FEED_FORWARD_TASKS
import torch
import torch.nn.functional as F
def heteroscedastic_normal(mean_and_scales, target, weight=None, eps=1e-2):
mu, scales = mean_and_scales
... |
import pandas as pd
from psycopg2 import pool
import math
import numpy as np
import os
import time
start_time = time.time()
# use connection pool for single threaded apps. replace credentials with Timescale user pool settings
postgres_pool = pool.SimpleConnectionPool(1, 5, user='root',
... |
from controllers.course.deliverables import deliverable_controller
from controllers.relations.student_group_relation import StudentGroupRelationController
from flask_restful import Resource, reqparse
import werkzeug
from flask import jsonify
from methods.errors import *
from methods.auth import *
controller_object = d... |
from pathlib import Path
import torch
import torchvision
from torchvision import models, transforms, utils
import argparse
from utils import *
import numpy as np
from tqdm import tqdm
# +
# import functions and classes from qatm_pytorch.py
print("import qatm_pytorch.py...")
import ast
import types
import... |
num_lines = int(input())
for _ in range(num_lines):
text = input()
name = text[text.index("@") + 1:text.index("|")]
age = text[text.index("#") + 1:text.index("*")]
print(f"{name} is {age} years old.")
|
# -*- coding:UTF-8 -*-
"""
计算圆周率可以根据公式:
利用Python提供的itertools模块,我们来计算这个序列的前N项和:
"""
import itertools
def pi(N):
'计算pi的值'
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9 ... count(start, step)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
# step 3: 添加正负号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ... cycle(list)
# step 4... |
import pygame
from constants import *
from icon import *
from panel import *
__all__ = ['Lineicon', 'Coalicon', 'Sellicon', 'Windfarmicon',
'Loadicon', 'Syncicon', 'Swingicon', 'Renameicon']
class Baseicon():
def __init__(self, panel, obj, num_pics, left_click, type):
build = Buildicon(obj, num_... |
import sys
sys.path.append("/usr/local/web/d.suishoubei.com")
from app import app as application
|
# -*- coding: utf-8 -*-
import copy
import datetime
import dateutil
import arrow
from unittest.mock import patch, call
from gitlint.tests.base import BaseTestCase
from gitlint.git import GitContext, GitCommit, GitContextError, LocalGitCommit, StagedLocalGitCommit, GitCommitMessage
from gitlint.shell import ErrorRet... |
"""Provide email notification support"""
import smtplib
import logging
import json
class Emailer:
"""Class which handles sending notification emails."""
def __init__(self, config):
self._config = config['smtp']
self._logging_level = config['logging_level']
self._logger = logging.getL... |
import requests
subscription_key = "cbf2b70a2d8649079256eae159c848f8"
assert subscription_key
def analyze_image(image_path):
vision_base_url = "https://eastus2.api.cognitive.microsoft.com/vision/v1.0/"
vision_analyze_url = vision_base_url + "analyze"
image_url = image_path
headers = {'Ocp-Apim-Subscription-Key':... |
print("Append Content To Files")
content = input("Enter Content To Append to A file: ")
path = input("Enter the Path of the file: ")
File = open(str(path), "a")
File.write(str(content))
input("Press Enter to Exit: ") |
import sys
sys.path.append("/usr/lib/python2.6/site-packages")
from cloudbot.interface.ttypes import *
from cloudbot.utils import OpenLdap,utility
import threading
import copy
import vmEngineUtility
import vmEngine00
import vmEngine11
from vmEngineType import *
#import vmEngine10
#import vmEngine01
#import vmEngine00... |
import sys
sys.setrecursionlimit(100000)
def min_perm(N, K):
P = [1] * N
need = K - N
i = 0
while i < N and need > 0:
P[i] = min(need+1, N)
need = need + 1 - P[i]
i += 1
return list(reversed(P))
def assign(P, N, i, j, v):
P[i, j] = frozenset([v])
nbs = [(i, k) for k... |
from unetpy import *
modem = UnetGateway('192.168.0.11')
phy = modem.agentForService(Services.PHYSICAL)
print(phy[0][0])
|
import boto3
import json
import yaml
from aws_organized_policies import helper
import os
from datetime import datetime
import click
import os
from datetime import datetime
from betterboto import client as betterboto_client
from pathlib import Path
import time
STATE_FILE = "state.yaml"
client = boto3.client("sts")
org ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
__author__ = "Ananda S. Kannan"
__copyright__ = "Copyright 2017, pyFy project"
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Ananda S. Kannan"
__email__ = "ansubru@gmail.com"
"""
################################################################################ L... |
a = "萨达萨达"
from functools import wraps
import pickle
import openpyxl
import xlrd, xlwt
from xlutils.copy import copy
file_path = os.path.dirname(os.path.abspath(__file__))
base_path = os.path.join(file_path, 'demo.xlsx')
print(base_path)
book = xlrd.open_workbook(base_path)
sheet = book.sheet_by_index(0)
xfile = o... |
# -*- coding: utf-8 -*-
from odoo import http
# class CookBook(http.Controller):
# @http.route('/cook_book/cook_book/', auth='public')
# def index(self, **kw):
# return "Hello, world"
# @http.route('/cook_book/cook_book/objects/', auth='public')
# def list(self, **kw):
# return http.re... |
def binary_array_to_number(arr):
s = ''
for element in arr:
s += str(element)
return int(s, 2)
|
import json, datetime
from domino.core import log
from sqlalchemy import Column, Integer, String, JSON, DateTime, and_, or_
from sqlalchemy.dialects.oracle import RAW, NUMBER
from domino.databases.oracle import Oracle, RawToHex
class DominoUser(Oracle.Base):
__tablename__ = 'domino_user'
id ... |
#! /usr/bin/env python
file_name = 'covid19.fasta'
data = dict() # data = {}
with open(file_name,'r') as handle:
for line in handle:
if line.startswith(">"): #헤더부분은 그냥 넘어감.
continue
for base in line.strip(): #\n 날리기.
if base not in data: #base: A, G, C, T
dat... |
def solution(array, commands):
answer = []
for s in commands:
i = s[0]
j = s[1]
k = s[2]
new_ar = array[i-1:j]
new_ar.sort()
answer.append(new_ar[k-1])
return answer
array = [1, 5, 2, 6, 3, 7, 4]
commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]
solution(array, c... |
from flask import Flask, jsonify, request
from flask_pymongo import PyMongo, ObjectId
from flask_cors import CORS
from os import environ
# initialization
app = Flask(__name__)
CORS(app)
#Mongo Connection
app.config["MONGO_URI"] = environ.get("MONGO_URI", "mongodb://localhost:27017/student")
mongo = PyMongo(app)
db = ... |
def remove_duplicates(A, key):
"""
Implement a function which takes as input an array and a key and updates the array such that all occurances of the input key have been removed and the remaining elements have been shifted to fill the emptied indices.
Return the number of remaining elements. There are no r... |
import unittest
from functions.funtionLibrary import *
class TestGetActionSelection(unittest.TestCase):
"""Test for getting action solution"""
def testGetActionSolution(self):
"""This a True test to see if the action is selected"""
actionlist = [1,2,3,4,5]
for action in actionlist... |
"""
NeuralWOZ
Copyright (c) 2021-present NAVER Corp.
Apache License v2.0
"""
import json
from copy import deepcopy
from itertools import chain
import h5py
import torch
from torch.utils.data import Dataset
from .data_utils import make_dst_target, split_slot, pad_ids, pad_id_of_matrix
from .constants import EXPERIMENT_D... |
import sys
import os
import spotipy
import spotipy.util as util
scope = 'user-top-read'
client_id = os.environ['SPOTIPY_CLIENT_ID']
client_secret = os.environ['SPOTIPY_CLIENT_SECRET']
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print("Usage: %s username" % (sys.argv[0],))
sys.exit()
token = util.p... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
import fastavro
from sbsearch import util
def define_points(ra, dec, half_size):
"""Points for SBSearch.add_observations.
ra, dec, half_size in radians
Returns: [ra_center, dec_center, ra1, dec1, ra2, dec2, ra3, dec3,
... |
import os
from pathlib import Path
import argparse
from datetime import timedelta
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import graphviz
from sklearn import tree
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score,... |
# from rest_framework.views import APIView
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
from method10.serializers import School, Subject, Teacher, Student, SchoolSerializer, SubjectSerializer, TeacherSerializer,StudentSerializer
class StudentNested... |
'''
------------------------------------------------------------------------
This module contains utility functions that do not naturally fit with
any of the other modules.
This Python module defines the following function(s):
print_time()
compare_args()
create_graph_aux()
---------------------------------... |
import cPickle
import numpy as np
import sys
from collections import OrderedDict
def format_chars(chars_sent_ls):
max_leng = max([len(l) for l in chars_sent_ls])
to_pads = [max_leng - len(l) for l in chars_sent_ls]
for i, to_pad in enumerate(to_pads):
if to_pad % 2 == 0:
chars_sent_ls[i... |
#!/usrbin/python
#encoding:utf-8
'''
Author: wangxu
Email: wangxu@oneniceapp.com
任务更新
'''
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import logging
import tornado.web
import json
import os
import time
import datetime
import traceback
CURRENTPATH = os.path.dirname(os.path.abspath(__file__))
sys.path.ap... |
import unittest
class Testing(unittest.TestCase):
def test_string(self):
a = 'vinod'
b = 'vinod'
self.assertEqual(a, b)
def test_string(self):
a = 'vinod'
b = 'vinodh'
self.assertNotEqual(a, b)
if __name__ == '__main__':
unittest.main()
|
# -*- coding: utf-8 -*-
from django.http import HttpResponse
def home(request):
return HttpResponse('olá')
def contact(request):
return HttpResponse('contact') |
import re
string = input()
pattern = r"(#|\|){1}(?P<item>[a-zA-Z\s]+)\1(?P<date>\d{2}/\d{2}/\d{2})\1(?P<calories>\d{1,5})\1"
total_calories = 0
matches = re.finditer(pattern, string)
for match in matches:
total_calories += int(match['calories'])
days = total_calories // 2000
print(f"You have food to... |
"""
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zeros.)
"""
from pip._vendor.urllib3.connectionpool import ... |
#!/usr/bin/env python
# tested with:
# - Flask-0.11-py2.py3-none-any.whl on Python 2.7 (OS X 10.10)
# - python-flask-0.9-7.el6.noarch on Python 2.6 (CentOS 6)
'''
Integration stub / mock DCM API endpoint.
'''
from flask import Flask, Response, request
import json
# `sr.py` can fail with status code 400,404,500
SR_FA... |
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, PasswordField, SelectField, HiddenField, FloatField, FormField, FieldList
from wtforms.validators import DataRequired, InputRequired, NumberRange, ValidationError
from .models import currencies, currency_choices_form
def validate_currency(f... |
from enum import Enum, IntEnum
from itertools import chain
from dash.orgs.models import Org
from dash.utils import intersection
from django_redis import get_redis_connection
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.db import models
from django.db.mode... |
# https://www.urionlinejudge.com.br/judge/pt/problems/view/
import unittest
from desrugenstein import desrugenstein
"""
N S O L
4
|0 1 0 1 (0, 3)| 0 0 1 0 (1, 3) | 0 0 0 1 (2, 3) | 0 1 0 0 (3, 3)
|0 0 0 0 (0, 2)| 1 0 0 1 (1, 2) | 0 0 0 1 (2, 2) | 0 1 0 0 (3, 2)
|1 0 0 0 (0, 1)| 1 0 1 0 (1, 1) | 1 1 0 0 (2, 1) | 0 1 ... |
import threading
import socket
import sys
import time
from drone import drone
# このプログラムを実行するPCのアドレス
host = '192.168.11.2'
# droneA との通信でのPC側のアドレス
portA = int(9000)
locaddrA = (host,portA)
# droneB との通信でのPC側のアドレス
portB = int(9001)
locaddrB = (host,portB)
# droneA/droneB のアドレス
addressA = '192.168.11.65'
addressB = '... |
from marshmallow import fields, Schema
__all__ = [ "Event", "InstalledAppRequest", "InstalledApp" ]
class Event(Schema):
id = fields.UUID(required=True)
created = fields.DateTime(required=True)
updated = fields.DateTime(required=True)
event_time = fields.DateTime(required=True)
event_type_slug =... |
import numpy as np
import matplotlib.pyplot as plt
from time import time
import boss_problems, boss_embed, boss_bayesopt
np.random.seed(0)
#problem = 'motif'
problem = 'tfbind'
#problem = 'tfbind-small'
if problem == 'motif':
seq_len = 8
noise = 0.1
oracle, oracle_batch, Xall, yall, Xtrain, ytrain, train_nd... |
from django.db.models import Q
from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.views.generic import TemplateView, UpdateView, View, DetailView, CreateView
from django.core.urlresolvers import reverse
from django.contrib import messages
from d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.