text stringlengths 38 1.54M |
|---|
# -*- coding:UTF-8 -*-
"""
Instagram批量关注
https://www.instagram.com/
@author: hikaru
email: hikaru870806@hotmail.com
如有问题或建议请联系
"""
import time
from common import *
from project.instagram import instagram
IS_FOLLOW_PRIVATE_ACCOUNT = False # 是否对私密账号发出关注请求
# 获取账号首页
def get_account_index_page(account_name):
accoun... |
from setuptools import setup, find_packages
from codecs import open
import os
here = os.path.abspath(os.path.dirname(__file__))
def read_text(fname):
if os.path.isfile(fname):
with open(os.path.join(here, fname)) as f:
return f.read()
else:
print("warning: file {} does not exist".... |
# Generated by Django 3.0.7 on 2020-06-30 00:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('restaurants', '0001_initial'),
]
operations = [
migrations.CreateModel(
nam... |
from Inference import Inference
def main():
'''main program'''
Inference.promptQuestion()
Inference.answerQuestion()
main()
|
import tweepy
import psycopg2
import psycopg2.extensions
from psycopg2.extensions import AsIs
import psycopg2.extras
import pickle
import string
import pandas as pd
import json
data = pickle.load( open( "twitter_data_Trump_SINCE.p", "rb" ))
data_dict = (data["statuses"])
# Connecting to database
try:
conn = psy... |
#!/usr/bin/env python3
import socket
import postgres
import csv
import os
import time
import sys
import collections
import multiprocessing as mp
from datetime import datetime
from psycopg2 import OperationalError
from psycopg2.extras import execute_values
def write_to_csv(wr_buff, can_bus):
# Write to CSV from ... |
from rest_framework.serializers import ModelSerializer
from manager.models import Comment, LikeCommentUser, Book
class CommentSerializer(ModelSerializer):
class Meta:
model = Comment
fields = "__all__"
class LikeCommentUserSerializer(ModelSerializer):
class Meta:
model = LikeCommentU... |
from sklearn import preprocessing
from sklearn.neural_network import MLPClassifier
from model_nnlm import *
import Write_xls
import pickle
import data_build
#准备训练数据x和y
with open('./data/label_transfer_dict.pkl', 'rb') as f:
dict = pickle.load(f)
print('ceshi', dict['肺经蕴热'])
# y_keras = np_utils.to_c... |
import numpy as np
ytrainn = np.load('data/ytrainn.npy')
ytestn = np.load('data/ytestn.npy')
ydevn = np.load('data/ydevn.npy')
trainwords=np.load('data/trainwords.npy')
testwords=np.load('data/testwords.npy')
devwords = np.load('data/devwords.npy')
Xtrain=np.load('data/Xtrain.npy')
Xtest=np.load('data/Xtest.npy')
Xd... |
#A suduko solver with Backtracking
#Main Sudoku Solving Class
class Sudoku_Solver:
def __init__ (self,sudoku):
self.grid = [[0 for x in range(9) for y in range(9)]]
self.grid = sudoku
self.curr = [0,0]
#finds empty cell in the sudoku
def EmptyFinder(self):
for row in range ... |
#aklından bir sayı tut oyunu
#aklımdan tuttuğum sayıyı bilgisayar tahmin ediyor.
import random
enKucukDeger=1
enBuyukDeger=100
tahminSayisi=1
cevap="h"
while cevap!="e":
print("ek-{} , eb-{}".format(enKucukDeger,enBuyukDeger))
bilgisayarinTahminEttigiSayi=random.randint(enKucukDeger,enBuyukDeger)
cevap=input("{}... |
from django.db import models
# Create your models here.
class Grades(models.Model):##继承models.Model模型中的字段就对应表种的属性
gname = models.CharField(max_length=20)
gdate = models.DateTimeField()
ggirlnum = models.IntegerField()
gboynum = models.IntegerField()
isDelete = models.BooleanField(default=False)
cla... |
class Solution(object):
def genLR(self, l, r, rStr, rLst):
if l > r: return
if l == 0 and r == 0:
rLst.append(rStr)
else:
if l > 0:
self.genLR(l-1, r, rStr+'(', rLst)
if r > 0:
self.genLR(l, r-1, rStr+')', rLst)
... |
from playsound import playsound
playsound('C:/Users/HIMA/Music/life_goes_on.mp3')#specify the path of the song
print('playing sound using playsound') |
# 1. Write a function make_change that accepts two argument:
# A. total_charge = amount of money owed
# B. payment = amount of money paid
# 2. Return a 2-dimensional tuple whose values represent bills and coins
# (singles, fives, tens, twentys, fifties, hundreds)
# (pennies, nickles, dimes, quarters)
# First c... |
# Programa que lista todas las imagenes
import json
with open("imagenes.json") as data_file:
data = json.load(data_file)
print " "
print "La lista de imagenes es la siguiente: "
print " "
for a in data["results"]["bindings"]:
print a["rdfs_label"]["value"]
print " "
|
from flask import Flask, Blueprint, request, json
from views import WalletViews
from decorators import api_login_required, check_wallet_amount_status
from App.Response import Response
wallet = Blueprint('wallet', __name__, template_folder='templates')
'''
Get Wallet balance
'''
@wallet.route('/wallet', methods=['GET'... |
# coding=utf-8
import json
import re
from string import Template
from meitData import shopData
import connectdb
# 店铺列表
def main():
res = json.loads(shopData)
if res.get("data"):
shopList = res.get("data").get('shopList')
get_connect(shopList)
# 连接
def get_connect(shopList):
for shop in shopList:
i... |
def gen(n, C, r):
if n == 0:
return [ 1 if i == r else 0 for i in range(3) ], C[r]
A1, s1 = gen(n - 1, C, r)
A2, s2 = gen(n - 1, C, (r + 1) % 3)
return [ A1[i] + A2[i] for i in range(3) ], min(s1, s2) + max(s1, s2)
def check(n, N, C, r):
A, s = gen(n, C, r)
if A[0] == N[0] and A[1] == N[1] and A[2] ... |
from .base_page import BasePage
from .locators import BasketPageLocators
class BasketPage(BasePage):
# в корзине нет товаров
def not_product_in_basket(self):
assert not self.is_element_present(*BasketPageLocators.BASKET_BUTTON_BLOCK), "Product in basket"
# в корзине есть товар
def product_in_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 7 10:01:05 2021
@author: kutalmisince
"""
import numpy as np
import matplotlib.pyplot as plt
class Superpixel:
def __init__(self, compactness = 8.0, tiling = 'iSQUARE', exp_area = 256.0, num_req_sps = 0, spectral_cost = 'Bayesian', spatial_co... |
# # declare a list with numbers 1 to 5 and add 6 at the end of list
# num_list = [1, 2, 3, 4, 5]
# print(num_list)
# num_list.append(6)
# print(num_list)
# 2 Create a tuple with values 1 - 5
# num_tuple = {1, 2, 3, 4, 5}
# num_list = list(num_tuple)
# print(num_list[:3])
# # You cannot append this
#
# # 3 declare a di... |
# Embedded file name: .\Demo4.py
import random
def do_turn(game):
if len(game.islands()) == 0:
return
not_mine = game.islands()
for i in range(len(game.my_pirates())):
pirate = game.my_pirates()[i]
directions = game.get_directions(pirate, not_mine[i % len(not_mine)])
random.... |
class Stack(list):
def push(self, v):
self.append(v)
def peek(self):
return self[-1]
def __iter__(self):
self.current = 0
return self
def __next__(self):
if self.current < len(self):
self.current += 1
return self[self.cu... |
from api.middlewares.application import ApplicationManager
from api.controllers import login
app = ApplicationManager().get_app()
app.add_url_rule('/login', 'login', login.login, methods=['POST']) |
# Generated by Django 3.2.2 on 2021-05-13 16:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('constituent_operations', '0013_actionplanparticipants'),
]
operations = [
migrations.AlterModelOptions(
name='actionplanparticipants',
... |
# coding: utf-8
import time
import logging
import datetime
import sys
import os
import getopt
from config import Config
from lib.nframe import PublicLib
from zookeeper import Zookeeper
from flow import Flow
from zk_redo import ZkRedo
from lib.receive_signal import ReceiveSignal
ReceiveSignal.receive_signal()
pl = Pub... |
#! /usr/bin/env python
#coding=utf-8
'''
______________________________________________
_______________#########_______________________
______________############_____________________
______________#############____________________
_____________##__###########___________________
____________###__######_#####___________... |
from celery import Celery
from django.core.mail import send_mail
from django.conf import settings
import time
app = Celery('celery_task.tasks', broker='redis://127.0.0.1:6379/7')
@app.task
def send_register_active_email(to_email, username, token):
subject = 'Welcom to Daily Fresh'
msg = ''
sender = setti... |
# Generated by Django 2.2.7 on 2021-09-24 13:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('CororateInfo', '0001_initial'),
('User', '0001_initial'),
]
operations = [
migrations... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main(args):
n = int(input("Podaj liczbe: "))
i = 2
while n % i > 0:
if n == 1:
print("Ani pierwsze ani zlozone")
break
if i * i >= n:
print("pierwsze")
break
i += 1
while(n % i =... |
from djangobench.utils import run_benchmark
def setup():
global Book
from query_order_by.models import Book
def benchmark():
global Book
list(Book.objects.order_by('id'))
run_benchmark(
benchmark,
setup=setup,
meta={
'description': 'A simple Model.objects.order_by() call.',
}... |
import MegaPracticaDos
def test_PedirTotales_NmayoraX():
N,X = MegaPracticaDos.PedirTotales([8,2])
if(N>=X):
test= False
else:
test = True
assert test == True
def test_PedirTotales_NmenorX():
N,X = MegaPracticaDos.PedirTotales([2,8])
if (N>=X):
test = False
else:
test = True
as... |
##
# This module defines an employee class hierarchy for payroll processing.
#
## An employee has a name and a mechanism for computing weekly pay.
#
class Employee :
## Constructs an employee with a given name.
# @param name the name of the employee
#
def __init__(self, name) :
self._name = name
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-11-30 22:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('staff', '0006_auto_20171128_0109'),
]
operations = [
migrations.AlterField(
... |
import random
class NPC:
def __init__(self):
pass
def Power(self):
pass
class Person:
def __init__(self,Monster):
self.name = "Person"
self.HP = 100
def Power(self):
return 0
class Zombie:
def __init__(self):
self.name = "... |
'''
@author: Saurab Dulal
Date: Nov 13, 2017
Developed in Linux OS
Requirement = python 3.x +
Problem Description: This is a dynamic programming solution to the cloth cutting problem - please see the problem
description in README.md file
'''
import time
import sys
'''Using Dynamic Programming - orientation less c... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RANSACRegressor
from sklearn.model_selection import train_test_split
import scipy as sp... |
# coding=utf-8
import math
from nose.tools import assert_almost_equal
from Rotation_Matrix.calc_pose import calculate_translation
# calculations:
# mag = sqrt(100^2 + 150^2- 2*100*150×cos(30))
# theta = asin(150 × sin(30) ÷ mag)
def test_translation_behind_right():
(theta, mag) = calculate_translation(math.radian... |
"""
Plot of radial density for Hookium k=1/4.
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import erf
import matplotlib
from matplotlib import rc
matplotlib.rcParams.update({'font.size': 22})
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = r'\usepac... |
import sys
sys.path.insert(0, "/home/yluo/learn/flaskbyex/waitercaller")
from waitercaller import app as application
|
from django.conf.urls import include, url
from django.conf.urls import *
from dealerfunnel.funnel.view.user import *
urlpatterns = [
url(r'^$',user().landing,name='user_landing'),
url(r'^create/$',user().createuser,name='create_user'),
url(r'^edituser/$',user().editusermodal,name='user_edituser'),
url(r... |
file = open("new.txt", "w")
listd = ["Zero" ,"Sqeezed " ,"Lemonade ", "Grandma ", " Gameplay ", "Mechanics ", "Walkers ", "Extreme ", "Produced "]
file.writelines(listd)
file.close()
listd.sort()
file=open("new.txt", "w")
file.writelines(listd)
file.close()
file=open("new.txt","r")
print(file.read())
|
class Solution:
def findMinStep(self, board: str, hand: str) -> int:
def helper(board: str, counter: collections.Counter) -> int:
if not board:
return 0
min_balls, i = 6, 0
while i < len(board):
j = i + 1
while j < l... |
import os
import random
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
BASE_URL = 'https://ww... |
import PySimpleGUI as sg
sg.theme('LightBlue6') # akna värvilahenduse muutmine
def arvuta(bruto, sots, pens, tooandja, tootaja, tulumaks, brutoo, neto, maksud, tooandjamaks, tulum, tmv, aasta):
#brutoo = int(bruto)
bruto = float(bruto)
if sots == True:
tooandjamaks += bruto * 0.33
... |
import win32com.client
import os
class Macros():
def __init__(self, MacroContainingExcelFilePath, VBAModule):
self.ExcelMarcoFilePath = MacroContainingExcelFilePath
excel_file = os.path.basename(MacroContainingExcelFilePath)
self.Macro_Prefix = excel_file + "!" + VBAModule + "."
self.xl = win32com.client.Dis... |
import psycopg2
url = "dbname='IReporter' user='postgres' host='localhost' port=5433 password='Boywonder47'"
class database_setup(object):
def __init__(self):
self.conn = psycopg2.connect(url)
self.cursor = self.conn.cursor()
def destroy_tables(self):
self.cursor.execute("""DROP TAB... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 OpenERP SA (<http://openerp.com>).
# Application developed by: Carlos Andrés Ordóñez P.
# Country: Ecuador
#
# This program is free so... |
import tensorflow as tf
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import Session
from time import process_time
assert (tf.test.is_built_with_cuda())
tf.keras.backend.clear_session()
config = ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.7
tf.compat.v1.keras.backend.s... |
import argparse
import json
import os
import random
import time
import tqdm
from pytok import PyTok
from pytok import exceptions
def main(args):
this_dir_path = os.path.dirname(os.path.abspath(__file__))
data_dir_path = os.path.join(this_dir_path, 'data')
videos_dir_path = os.path.join(data_dir_path, 'v... |
# Complete the breakingRecords function in the editor below.
# It must return an integer array containing the numbers of times she broke her records.
# Index 0 is for breaking most points records, and index 1 is for breaking least points records.
# https://www.hackerrank.com/challenges/breaking-best-and-worst-reco... |
import numpy as np
from scipy.ndimage import affine_transform
# Functions to convert points to homogeneous coordinates and back
pad = lambda x: np.hstack([x, np.ones((x.shape[0], 1))])
unpad = lambda x: x[:,:-1]
def plot_matches(ax, image1, image2, keypoints1, keypoints2, matches,
keypoints_color='k'... |
import datetime
from functools import cached_property
from typing import Optional, cast
from models_library.basic_types import (
BootModeEnum,
BuildTargetEnum,
LogLevel,
VersionTag,
)
from models_library.docker import DockerLabelKey
from pydantic import Field, PositiveInt, parse_obj_as, validator
from ... |
print "this will run forever if you don't \n use ctrl+c"
while True:
for i in ["/","-","|","\\","|"]:
print "%s\r" % i,
|
#!/usr/bin/env python
import os
import sys
import json
import time
import urllib2
import imghdr
import traceback
from ConfigParser import SafeConfigParser
import pynotify
DEFAULT_CONFIG_FILE = "~/.ttrss-notify.cfg"
class TTRSS(object):
def __init__(self, config_file):
# parse configuration
parse... |
# Author: Xinshuo Weng
# email: xinshuo.weng@gmail.com
from .math_geometry import *
from .prob_stat import *
from .bbox_transform import *
from .mask_transform import *
from .math_algebra import *
from .math_conversion import *
from .pts_transform import *
from .bbox_3d_transform import *
|
import math
r,n=raw_input().split()
rad=float(r)
onts=int(n)
print round(onts*math.sqrt(2*rad*rad-2*rad*rad*math.cos(2*3.14/onts)),1)
|
class Behavior(object):
"""docstring for Comment"""
def __init__(self, comments, views):
super(Behavior, self).__init__()
self.comments = comments
self.views = views
class Tag(object):
tag = 0
attrs = []
def __init__(self, tag, attrs):
self.tag = tag
... |
#Author:karim shoair (D4Vinci)
#Extract the best stargazers for any github repo
import mechanicalsoup as ms
from tqdm import tqdm
import readline
browser = ms.StatefulBrowser()
url = input("Repository link : ")+"/stargazers"
check_str = "This repository has no more stargazers."
G,W,B = '\033[92m','\x1b[37m','\033[94m'
... |
# Generated by Django 2.0.4 on 2018-05-08 01:05
from django.db import migrations
import internal.fields
class Migration(migrations.Migration):
dependencies = [
('internal', '0012_auto_20180508_0859'),
]
operations = [
migrations.AlterField(
model_name='stuinfo',
... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import xlsxwriter
from sklearn.cluster import KMeans
from sklearn.manifold import MDS
filename = "/Users/Shatalov/Downloads/European Jobs_data.csv"
df = pd.read_table(filename, sep=";")
data = df.iloc[:, 1:10].values
wcss = []
for i in range(1,... |
# ref[1]: https://stackoverflow.com/questions/19695214/python-screenshot-of-inactive-window-printwindow-win32gui
# ref[2]: http://pythonstudy.xyz/python/article/406-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EC%B2%98%EB%A6%AC-Pillow
# ref[3]: https://pythonpath.wordpress.com/2012/09/17/pil-image-to-cv2-im... |
from typing import Any, Callable, Dict, Optional
import pytest
from tartiflette import Directive, Resolver, create_engine
from tartiflette.schema.registry import SchemaRegistry
@pytest.mark.asyncio
async def test_tartiflette_deprecated_execution_directive():
schema = """
type Query {
fieldNormal: In... |
from assertpy import assert_that
from django.test import TestCase
from model_bakery import baker
from self_date.models import image_path
class SelfDateProfileImagePathTestCase(TestCase):
def test_image_path(self):
# Given: profile 하나가 주어진다.
self_date_profile = baker.make('self_date.SelfDateProfil... |
import argparse
parser = argparse.ArgumentParser(description='Input arguments for generating input addresses to Character RNN')
parser.add_argument('inputFile', nargs='?', type=str)
parser.add_argument('functionName', nargs='?', default='increment', type=str)
parser.add_argument('delimeter', nargs='?', default=';... |
from dataclasses import dataclass
from typing import List, Optional, Tuple
import torch
from .file_utils import ModelOutput
@dataclass
class BaseModelOutput(ModelOutput):
"""
Base class for model's outputs, with potential hidden states and attentions.
Args:
last_hidden_state (:obj:`torch.FloatTe... |
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
# 정규표현식 url(r'^$', views.post_list, name='post_list'),
#url(r'^post/1/$', views.post_detail, name='post_detail'),
path('post/<int:pk>/', views.post_detail, nam... |
'''
Created on 5 Aug 2018
@author: Ken
'''
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include, url
from karaokeapp.modules.room.room_info.views.room_info_views import listRoomInfo, addRoomInfo, getRoom
urlpatterns = [
url(r'^listRoomInfo/$', l... |
# Problem 1
def multiply():
num1 = int(raw_input('Type a number'))
while num1 < 1:
num1 = int(raw_input('your number is negative, enter a positive'))
num2 = int(raw_input('Type a number'))
while num2 < 1:
num2 = int(raw_input('your number is negative, enter a positive'))
product = 0... |
# -*- coding: utf-8 -*-
"""
Created on 2020/1/30 10:01
@author: dct
"""
import requests
from lxml import etree
def getNewsURLList(baseURL):
x = requests.get(baseURL)
x.encoding = 'utf-8'
selector = etree.HTML(x.text)
contents = selector.xpath('//div[@id = "content_right"]/div[@class = "content_list"]/... |
array = ['a','b','c','a','b','d']
#next = 0 0 0 1 2 0
#index = 0 1 2 3 4 5
next = [0] * len(array)
####t与i的初始位置
i = 1
t = 0
while i < len(array):
if array[i] == array[t]:
next[i] = t + 1
i += 1
t += 1
elif t>0: #这个地方最难记,把t退回到next[t-1]位置
t = next[t-1]
... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Camp'
db.create_table('rsvp_camp', (
('id', self.gf('django.db.models.fields.Aut... |
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_P... |
# Write a function to check if a linked list is a palindrome
from utils import LinkedList
# List visual: [r, a, c, e, c, a, r]
a_palindrome = LinkedList()
a_palindrome.add_to_tail("r")
a_palindrome.add_to_tail("a")
a_palindrome.add_to_tail("c")
a_palindrome.add_to_tail("e")
a_palindrome.add_to_tail("c")
a_palindrome.... |
from django.db import models
from django.utils import timezone
# Create your models here.
class Interesados (models.Model):
id = models.AutoField(primary_key=True)
nombres = models.CharField(max_length=50)
apellidoPaterno = models.CharField(max_length=50)
email = models.CharField(max_length=50)
tel... |
#!/usr/bin/python3
from cffi import FFI
ffibuilder = FFI()
ffibuilder.cdef('struct exb;')
ffibuilder.cdef('struct exb_server;')
ffibuilder.cdef('struct exb_request_state;')
#ffibuilder.cdef('struct exb_request_state *exb_py_get_request();')
ffibuilder.cdef('int exb_response_set_header_c(struct exb_request_state *rqstat... |
#! /usr/bin/env python3
name = input("Enter the file name: ")
f = open(name)
print(f.read())
f.close()
|
"""
What is this script:
--------------------
create a custom generator on top of existing keras data augmentation functionalities
such as random cropping and PCA whitening (details see `random_crop_n_pca_augment.py`)
and correct generator indices (details see `labels_corrector.py`)
"""
import numpy as np
i... |
#!/usr/bin/env python
from distutils.core import setup
CLASSIFIERS = [
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
]
long_desc = 'coming soon.'
setup(name='Octo',
version='0.2',
description='uPortal Log reader',
long_description=long_desc,
author='Toben Archer',
... |
import tkinter as tk
class Calculator(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title('Simple Calculator')
self.master.resizable(0, 0)
self.entry = tk.Entry(self, width=30, borderwidth=5)
self.buttons = []
... |
import ml
def test_month_length():
assert ml.month_length("January") == 31, "failed on January"
assert ml.month_length("February") == 28, "failed on February"
assert ml.month_length("February", leap_year=True) == 29, "failed on February, leap_year"
assert ml.month_length("March") == 31, "failed on Marc... |
def namescore(name):
return sum(ord(i)-64 for i in name)
names = open('problem022.txt','r')
names = names.read().split(',')
names[-1] = names[-1][:-1]
names.sort()
print sum(namescore(names[i]) * (i+1) for i in xrange(len(names)))
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
def emp_list(request):
return render(request, 'emp_list.html')
def house_list(request):
return render(request, 'house_list.html')
def house_type_list(request):
return render(re... |
dict={}
dict['1']='apple'
dict['3']='banana'
dict['2']='cherry'
list=dict.keys()
#sorted by key
print("sorted by key:", sorted(list)) |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Rahul Handay <rahulha@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (
MagicMock,... |
import json
import base64
def requirebegin(func):
def inner(self, *args, **kwargs):
if not self._begin:
raise Exception('CAN bus not started')
return func(self, *args, **kwargs)
return inner
class CAN_message(object):
len = 0
id = 0x0
buf = ''
def __str__(self):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Generate JSON dataset for errmodel directly from yay.tsv and yay.summary
Prepare examples with
- multiple error lines (1-5)
- (no error lines.) instead, during training, predict code for err lines as well as randomly chosen other lines (which are already correct)... |
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
# Pakai app dari package yang diatasnya
from aplikasi.form import app
# Import model
from aplikasi.model.anggota import tambah
# Decorator yang menyatakan kalau:
# + Untuk URL: /daftar
# + Jalankan method... |
"""DGM"""
from typing import (
List,
Dict
)
from re import sub
from .dataset import Dataset
class Dimension():
"""Metric Dimension"""
name: str
value: str
def __init__(self, name: str, value: str) -> None:
self.name = name
self.value = value
def api_structure(self) -> dict... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 4 21:52:33 2020
@author: steve
"""
"""
1296. Divide Array in Sets of K Consecutive Numbers
https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
"""
# I think the easiest way for me is to sort it first
"""
Runtime: 6788 ms, fast... |
# contours: continuous lines or curves the bound the object
import cv2
import numpy as np
# load the image
image = cv2.imread('../images/sudoku.jpg')
# convert it to grayscale
image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow("original image", image)
cv2.waitKey(0)
# find the canny edges
edged = cv2.Can... |
import unittest
from bond import *
class TestBondMethods(unittest.TestCase):
def test_correct_form(self):
b = Bond("C1", "corporate", 3, 1.3)
self.assertEqual(b.get_name(), "C1")
self.assertEqual(b.get_type(), "corporate")
self.assertEqual(b.get_term(), 3)
self.assertEq... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime, timedelta
def r_style_interval(from_tuple, end_tuple, frequency):
"""
create time interval using R-style double-tuple notation
"""
from_year, from_seg = from_tuple
end_year, end_seg = end_tuple
... |
import numpy as np
import copy
import random
import time
##设备.#
class S():
def __init__(self, p, t):
self.p = p
self.t = t
##任务.#
class T():
def __init__(self, time, d, i, j):
self.time = time
self.endtime = None
self.d = d
self.i = i
self.j = j
s... |
import numpy as np
# 1. 학습데이터
x_train = np.array([1,2,3,4,5,6,7,8,9,10]) #10행 1열
y_train = np.array([1,2,3,4,5,6,7,8,9,10])
x_test = np.array([11,12,13,14,15,16,17,18,19,20])
y_test = np.array([11,12,13,14,15,16,17,18,19,20])
x3 = np.array([101, 102, 103, 104, 105, 106]) #6행 1열
x4 = np.array(range(30, 50))
from k... |
import secrets
from flask import request, render_template, redirect, url_for, flash, session
from shoppinglist import app
from shoppinglist.models.dashboard import Dashboard
dashboard = Dashboard()
app.secret_key = secrets.token_hex(32)
@app.route("/")
@app.route("/signup", methods=['GET', 'POST'])
def signup():
... |
from __future__ import print_function
from robot_skills import api, base, ears, ebutton, head, lights, perception, robot, sound_source_localisation, speech, \
topological_planner, torso, world_model_ed
from robot_skills.arm import arms, gripper, handover_detector
from robot_skills.simulation import is_sim_mode, Si... |
# -*- coding: utf-8 -*-
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.contrib.auth.decorators import permission_required
# #index
from models import IndexHead, IndexDash, IndexHopper, IndexCity, IndexAcrepay
from serializers i... |
from scipy import signal, fft
from scipy.io import wavfile
import numpy as np
GROUND_TRUTH_FILE = "music_speech.mf"
RESULT_FILE = "results.arff"
BUFFER_LEN = 1024
HOP_SIZE = 512
L = 0.85 # used for SRO
PRECISION = "%.6f"
HEADER = "@RELATION music_speech\n" \
"@ATTRIBUTE RMS_MEAN NUMERIC\n" \
"@AT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.