index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
996,000
1279209d055bb6083db67eebe18954aab648fa90
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-01 21:13 from __future__ import unicode_literals import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('outros', '0005_auto_20170801_13...
996,001
6173362d4f04d3e63df4f709da495559fc2fd72b
import pickle import six import warnings from functools import partial import paddle.fluid as fluid def load_dygraph(model_path, keep_name_table=False): """ To load python2 saved models in python3. """ try: para_dict, opti_dict = fluid.load_dygraph(model_path, keep_name_table) return p...
996,002
678e671846b511dd34bcc5e317ada4d89786a572
from pyrave.base import BaseRaveAPI from pyrave.encryption import RaveEncryption class Preauth(BaseRaveAPI): """ Preauthorization Class """ def __init__(self): super(Preauth, self).__init__() self.rave_enc = RaveEncryption() def preauthorise_card(self, log_url=False, **kwargs): ...
996,003
2328d7a645a6a15b7df2d0bf56fa06631ea2f455
listone = list(input("Enter a sequence of comma separated values: ").split(",")) listtwo = list(input("Enter a sequence of comma separated values: ").split(",")) print("First List ", listone) print("Second List ", listtwo) thirdList = [] for num in listone: i = int(num) if (i % 2 != 0): thirdLis...
996,004
414115bfbf03095646f07e245c24a4976724e117
import asyncio import time import requests import socket def ddos(addr): TCPClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TCPClient.connect(addr) #连接服务器 TCPClient.send('0x00'.encode()) #@asyncio.coroutine def main(): tasks = [] result = [] for site in sites: #tasks.append(...
996,005
4f886187559336acf27f9cbc1a0406bd20a6721e
#! python3 # -*- encoding: utf-8 -*- ''' Current module: tests.test_AppiumJs Rough version history: v1.0 Original version to use ******************************************************************** @AUTHOR: Administrator-Bruce Luo(罗科峰) MAIL: luokefeng@163.com RCS: tests.test_Appium...
996,006
b6f52454683ea74895e241cd3b7a04ceeeffbaef
#!/usr/bin/env python # -*- coding: utf-8 -*- # import functions for opencv from __future__ import print_function from collections import deque from imutils.video import VideoStream import numpy as np import cv2 import imutils import time from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelativ...
996,007
fbd0fef9e825f19c23fbd65dd316f8e9b903fe52
import threading from smbus2 import SMBusWrapper import time import sys #from clean_print import Cprint import math import numpy as np #from read_magneto_data import readData as read_magnet import motor #length = 455 cm #width = 149 cm #data :: R, F, L, B # 1, 2, 4, 3 d_format = {'fwd' : 1, 'bkwd' : 3, 'left'...
996,008
8774f627f22f42d01edebb95fb14ce609dd73ad9
import os import sys import glob import argparse import pandas as pd import numpy as np import mdtraj as md import prody import variables as vrb def open_structure_from_dataframe(csv_file, path_to_simulations, path_to_clusters=vrb.PATH_PATTER_TO_CLUSTERS_FROM_SIMS, file_column="file...
996,009
3c3f46273413abfaf293da8d715d1e99d9668b89
def Simulate_Network_modified( Ni, Npc, v, PFcent, L, IntNoise): from brian import * # This function uses slightly different parameters to Simulate_Network.m, and was used for the majority of simulations # Note: Npc must be an integer multiple of Ni # Parameters of integrate and fire neuron tauI = 40 * m...
996,010
cf6a26189ed2d8621c3a67bc4c862f7de013d4bf
# Generated by Django 3.2.4 on 2021-06-06 17:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0008_auto_20210606_2246'), ] operations = [ migrations.AddField( model_name='product', name='keywords', ...
996,011
7a6aea46d05ffc224cf1487ee0d61b16f9e1b3f5
class Animation: def __init__(self): self.playList = [] self.loop = False self.step = 0 def addAction(self, action): self.playList.append(action) def play(self): if len(self.playList) <= self.step: return; action = self.playList[self.step] ...
996,012
04ebe8f52cfd4c0332286daf5c10b6c75812f79b
from machine import Pin, I2C class PCA9685: """ 16 units PWM output """ min_values = [0 for i in range(16)] max_values = [4095 for i in range(16)] max_angles = [360 for i in range(16)] def _writeByte(self, register, value): self.i2c.writeto_mem(self.address, register, int(value).to_...
996,013
8f1275f062088f3b6f2b113e085ec4b7899f79e3
#EXTRACT IMPORTANT INFO FROM OSM FILE import xml.etree.ElementTree as ET from neo4j.v1 import GraphDatabase print("Reading XML") osmFile = ET.parse("wyandotte.osm") print("Done parsing...") root = osmFile.getroot() # Look for all roads in osm file print("Collecting roads...") roads = [] for way in...
996,014
83ff18ad213b36ff7b54715f8870eda045967f6f
from orator.migrations import Migration class CreatePrestamosTable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('prestamos') as table: table.increments('id') table.integer('user_id').unsigned() table.foreign('use...
996,015
7d547d3496b09fd9e989e9e1155c6b8db1bc123b
import logging import os from utils.file_names_builder import get_model_filename from utils.database_handler import DatabaseHandler from utils.logger import create_loggers_helper from configuration.configuration_constants import limit_date, excluded_values, \ validation_split_value, verbose_value, epochs_value, cu...
996,016
ea4571ce1bdaa585ad067c69eb97dc4087edb695
## @file EventCount_jobOptions.py ## @brief JobOptions: Defaults. ## @author Jack Cranshaw (Jack.Cranshaw@cern.ch) ## $Id: EventCount_jobOptions.py,v 1.6 2007-10-18 13:46:20 gemmeren Exp $ #-------------------------------------------------------------- # Event related parameters #---------------------------------------...
996,017
468f2a1b09e40336dfbb2118e7427a17e1da5ea4
import torch class AttentionBase(torch.nn.Module): def __init__(self, attentionName, attentionScope, featuresNumber, cudaFlag): self.attentionName, self.attentionScope, self.cudaFlag = attentionName, attentionScope, cudaFlag super(AttentionBase, self).__init__() if attentionName == 'Standa...
996,018
b72d9092c65950318d497000a5610307dbfb9cfc
import django_filters CHOICES = [ ["name", "По алфавиту"], ["cheaper_price", "Дешевые сверху"], ["-cheaper_price", "Дорогие сверху"], ["-sale", "Найбольшая скидка"], ["sale", "Найменьшая скидка"], ] class ProductFilter(django_filters.FilterSet): ordering = django_filters.OrderingFilter(choice...
996,019
a7415ab2d91f7d1db7bd8df433c96194ac9a0845
import image_search import numpy as np import random import Image # btm_file_path = "/home/bkko/ml_study/fddb/FDDB-folds/rectbtm-1.txt" # btm_file_path = "/home/bkko/ml_study/week7/ofile_12net/o_annot.txt" btm_file_path = "/home/bkko/ml_study/week7/ofile_12net/o_annot_10.txt" top_file_path = "/home/bkko/ml_study/w...
996,020
6307e7d2e4d4a563e89744b78cd94f2f29f2f9e1
#calss header class _BRAKING(): def __init__(self,): self.name = "BRAKING" self.definitions = brake self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['brake']
996,021
ac3dce3b0e3cc07b57252f2ce92591d67459d4c4
from django.db import models # Create your models here. class AdminProfile(models.Model): phone = models.BigIntegerField() photo = models.ImageField() email = models.EmailField() name = models.CharField(max_length=30)
996,022
d82891ff87724ded88e98f6b1321c56be2164738
import time import os from astropy import wcs import numpy as np from astropy.io import fits import scipy import argparse import sys import jwst from gwcs import wcstools from jwst import datamodels from . import auxiliary_functions as auxfunc from astropy.visualization import (ImageNormalize, AsinhStretch) import ma...
996,023
6615dc687e28638fc2365883d4ba7d7781fff4a2
arr = [] for i in range(0,10): num = int(input()) arr.append(num%42) print(len(set(arr)))
996,024
0232555471dc9aaf993f180e6e4139cdca90d9fe
# -*- coding: utf-8 -*- """ Created on Sat Feb 11 19:24:59 2017 @author: weilun """ import re import urllib def getHtml(url): page=urllib.urlopen(url) html=page.read() return html def getFolder(html): r=r'href=".*/"' re_folder=re.compile(r) folderList=re.findall(re_folder,html) return f...
996,025
1ab9a69264b05394e7e810d01024c0fdbc2b0b2b
from rest_framework.views import APIView from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import permissions from django.contrib.auth import login, logout, authenticate from django.http.response import HttpResponseNotAllowed, HttpResponse from django.c...
996,026
9dea10c491c35d8da2cb5d22e1e57fb5c432e145
''' Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Input: strs = ["eat","tea","tan","ate","nat","bat"] Ou...
996,027
3e8cab01c3d42f20d926bd76820867796da0d0f6
import jinja2 import webapp2 import datetime from utils import time_sec, valid_user, valid_password, valid_verify, valid_email, make_pw_hash, match_pw, front_articles from handlers import FrontPage, NewPost, Flush, BlogPost, Signup, Welcome, Login, Logout, JsonBlogPost, JsonFront from db import Blog, User ...
996,028
100c3a755921adaa48d6010dc87bee001d26cc5d
from django.contrib import admin from .models import LinkedInPost # Register your models here. admin.site.register(LinkedInPost)
996,029
15af0cad8f8b132569cb26a5491ea96ccdb92c46
import math import random class Organism: fitness = None data = None def __init__(self, data): self.data = data def mutate(self, mutate_func): self.data = mutate_func(self.data) def reproduce(self, reproduce_func, other): return Organism(reproduce_func(self.data, other.data)...
996,030
e0e9247461d3b1c39b0d35cc9963fa9a7fd50c10
import math def countValleys(A=[]): if len(A) < 2: return 0,0 tree = A.copy() tree.insert(0, math.inf) tree.append(math.inf) oddValleys = 0 evenValleys = 0 even = True for i in range(1, len(tree) - 1): if tree[i - 1] > tree[i] and tree[i] < tree[i + 1]: i...
996,031
8f163fea901e825132012623ad2a3eb94d97dba5
#!/usr/bin/python3 import unittest from models.engine.file_storage import FileStorage class TestFileStorage(unittest.TestCase): """ test engine: file storage """ def setUp(self): """ standard setUp() """ self.file_storage = FileStorage() def test_public_attr(self): """ test if att...
996,032
9ccb1180b7fb933894cc2bc98cf148862d78cd14
from collections import defaultdict count = defaultdict(int) print(count[8])
996,033
02ffaf51c723b71cb377cf272342c44e7a2165fb
# -*- coding: UTF-8 -*- from playwright import sync_playwright def run(playwright): browser = playwright.chromium.launch(headless=False) context = browser.newContext() # Open new page page = context.newPage() # Go to https://mail.qq.com/ page.goto("https://mail.qq.com/") # Click input[n...
996,034
9e0901e6379bf3268a8dab55955b793051de0491
import numpy as np from tensorflow.keras.layers import Activation from tensorflow.keras.layers import Dense from tensorflow.keras.layers import Input from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam class Actor(Model): def __init__(self, num_observations: int, num_actions: in...
996,035
86b3517b277730e0d53dcd0eebc6bf56625b50de
class GameController: """Maintains the state of the game.""" def __init__(self, WIDTH, HEIGHT): self.WIDTH = WIDTH self.HEIGHT = HEIGHT self.player_wins = False self.pinky_wins = False def update(self): """Carries out necessary actions if pinky or player wins""" ...
996,036
f5d58f11240e193918f4d8ba6398230ef077e765
a = [int(s) for s in input().split()] b = [] if len(a) % 2 == 0: for i in range (0, len(a), 2): b += a[i+1], a[i] else: for i in range (0, len(a)-1, 2): b += a[i+1], a[i] b.append(a[-1]) print(' '.join([str(i) for i in b]))
996,037
4390274faa3d2fc15541ec060e2210ec6a60afcd
#!/usr/bin/env python """ Extract Wikipedia article-term count matrix from KOPI plain text dump. """ import logging from reader import KopiReader from sklearn.feature_extraction.text import CountVectorizer from writer import Writer MAX_DF = 1.0 logging.basicConfig(format='%(asctime)s %(message)s') log = logging.getLo...
996,038
d1312a4a5525f0fd7dcc9c6bcce257c043034a60
""" Implementation of a Connect-4 Board class Author: RR """ class Board: """A type for representing the state and behavior of a Connect-4 board Attributes: width - an integer denoting the number of columns in the board height - an integer denoting the number of rows in the board dat...
996,039
b0b83f29854b231d0170288538cf64b1d42ba6d3
import os from os.path import basename from gc3libs import Application from gc3libs.quantity import GB class GrayscaleApp(Application): """Convert an image file to grayscale.""" def __init__(self, img): inp = basename(img) out = "gray-" + inp Application.__init__( self, ...
996,040
a1475fb980a5ac85345c2ec26a1ccaf1e2c549b2
#!/usr/bin/env python from herepy import ( MapTileApi, MapTileApiType, BaseMapTileResourceType, TrafficMapTileResourceType, ) map_tile_api = MapTileApi(api_key="api_key") # Returns a map tile map_tile = map_tile_api.get_maptile(latitude=52.525439, longitude=13.38727, zoom=12) print(map_tile) # Retur...
996,041
be4f47fdea628a8b32eb4986b694549773ed61d6
import os import sys # The config system depends on the `ply` parser generator. On Android, this may # come as a prebuilt, but may _not_ automatically be added to PYTHONPATH. If # we're on Android (tested by checking for `envsetup.mk`), then add the `ply` # prebuilt to `sys.path`: if os.path.isfile("build/make/core/en...
996,042
c40978b9c318b2dbbbf52e2b93a96c4afce04d08
import pygame import random import math pygame.init() click ="right" X=800 Y=600 #print("helo") screen = pygame.display.set_mode((X,Y)) pygame.display.set_caption("Skier") img= pygame.image.load("ski.png") pygame.display.set_icon(img) #---------------------player-------------------> playerimg=p...
996,043
dacc1709f85a62521d42aba4fba09c0c72f83961
import sys import nltk from nltk import word_tokenize,sent_tokenize import re import keras from keras.layers.embeddings import Embedding from keras.layers import Dense, Dropout, RepeatVector,Merge from keras.layers import LSTM from keras.layers import recurrent from keras.models import Sequential from keras.preprocessi...
996,044
fadfce915292be575cecf3c4f2fafe1fdce15327
def solve_for_coefficients_natural(n, r): if n == 2: return natural_interpolate_2(r) elif n == 3: return natural_interpolate_3(r) elif n == 4: return natural_interpolate_4(r) elif n == 5: return natural_interpolate_5(r) elif n == 6: return natural_interpolate_6(r) elif n == 7: return natural_inte...
996,045
26238d8310c5deb17528ea600b5bd18b40c8f108
#! "C:\Program Files (x86)\Python37-32\python.exe" import openpyxl from openpyxl import load_workbook file = "MOCK_DATA.xlsx" #load the work book wb_obj = load_workbook(filename = file) wsheet = wb_obj['MOCK_DATA'] #store data in a dictionary for convenience dataDict = {} for key, *values in wsheet.iter_rows(min...
996,046
c10fdc2b4961f45864d70246a988fee6c4ca0b19
# smtplib 发送邮件流程 # 连接到smtp服务器 import smtplib smtp = smtplib.SMTP('smtp.qq.com', 25) # 发送SMTP的'hello'信息 # smtp.ehlo() # Out[24]: # (250, # b'smtp.qq.com\nPIPELINING\nSIZE 73400320\nSTARTTLS\nAUTH LOGIN PLAIN\nAUTH=LOGIN\nMAILCOMPRESS\n8BITMIME') # 将当前会话加密 smtp.starttls() # Out[25]: (220, b'Ready to start TLS') # 登陆到...
996,047
a10e4a6fa4d3e74083ef00595536b0cb4b473146
import pandas as pd import pygal from pygal.style import DarkStyle def spirit(): """start age""" data = pd.read_csv("never_female.csv") line_graph = pygal.Pie(fill=True, interpolate='cubic', style=DarkStyle) line_graph.x_labels = data.AGE line_graph.y_labels = map(int, range(0, 400001, 20000)) ...
996,048
772486d949a13627a8c8540e1531a99ad901843b
continua = True while continua: try: x = int(input('Primeiro valor:')) y = int(input('Segundo valor:')) if y == 0: raise ZeroDivisionError except ValueError: print('O valor informado deve ser númerico') except ZeroDivisionError: print('Impossivel dividir p...
996,049
ab88cb9d42934ab40b600826fd5229359920f6c5
i=0 while i<=100: print("中秋节快乐",end='') i+=1 print("热烈庆祝中华人民共和国成立70周年!")
996,050
d978e77ffb92321720ef54bc9c3d0aba0a8ce0d9
from django.conf.urls import url from . import views urlpatterns = [ url('^$' ,views.index), url(r'^mycrude/$', views.mycrude_list), url(r'^mycrude/(?P<id>[0-9]+)$', views.mycrude_detail), ]
996,051
7742430c8f376f5850ca3cb44b06c4ad0b58fb37
from prodtest import ProduceTestCase class PretendUpToDatePatternTest(ProduceTestCase): def test_pretend_up_to_date(self): # a1 # | # b1 # / \ # c1 d1 normal = lambda: self.produce('a1') pretending = lambda: self.produce('a1', **{'-u': 'b%{i}'}...
996,052
4c61e35b4054669c3219f78abfa548fbbe985258
import unittest from contextlib import contextmanager class MiCustomManager: def __init__(self, estado): self.estado = estado def __enter__(self): print("Entrando en el contexto") return self.estado def __exit__(self, exc_type, exc_val, exc_tb): print("Salien...
996,053
9fe7729a70e77b4c2980c5d2079e8d2894db0750
import cv2 import numpy as np import RPi.GPIO as GPIO LimiarBinarizacao = 125 #este valor eh empirico. Ajuste-o conforme sua necessidade AreaContornoLimiteMin = 5000 #este valor eh empirico. Ajuste-o conforme sua necessidade #GPIOs utilizados: GPIOMotor1 = 18 #Broadcom pi2067n 18 (P1 pin 12) GPIOMotor2 = 1...
996,054
46fc04f94749f2dd6759fd7457cba23777f51564
largura = int(input("digite a largura: ")) altura = int(input("digite a altura: ")) if altura == largura: cont = largura while altura > 0: while cont > 0: cont = cont - 1 print("#", end= "") cont = largura print() altura = altura - 1 else: cont = larg...
996,055
92d7a4b90a1c838f70f50d1e121382ef2442cef7
import unittest class TestDatLoad(unittest.TestCase): """ Data Load lambda tests """ def test_data_load(self): print ('to be implemented') if __name__ == '__main__': unittest.main()
996,056
9d0216e47cd6636915004c12ac12be3adcc3f9e6
def fun(a): if len(a)==1: return 0 dp = [0]*len(a) dp[0]=a[0] dp[1]=dp[0]+abs(a[0]-a[1]) for i in range(2,len(a)): dp[i]=min(dp[i-1]+abs(a[i]-a[i-1]) ,dp[i-2]+abs(a[i]-a[i-2])) return dp[-1]-a[0] n = int(input()) a = list(map(int , input().split())) print(fun(a))
996,057
4413b3b897d95c91235537e5c415538622476634
# from optionModelsDEF.blackScholesModel import * # from optionModelsDEF.commonFuncs import * from optionModelsDEF.commonFuncs import fillDerivativesArray as f
996,058
4fafab702d70738229f307b96f3453d7577b5076
# -*- coding: utf-8 -*- import sys import Xerces, XQilla def main(): # Get the XQilla DOMImplementation object xqillaImplementation = Xerces.DOMImplementationRegistry.getDOMImplementation('XPath2 3.0') # Create a DOMDocument document = xqillaImplementation.createDocument() # Parse an XPath 2 expression express...
996,059
1ca587eb7d4b26449dca116350ef3416bbffb432
# The Best Dictionary in The World # created in Sleepy Hollow NY on October 28, 2015 # by Aneta Zolkiewicz for Edward Eames print "You are the best in the world!\n" world_best_dic = {'you are': "jestes", 'the best': "najlepsza", 'in': "na", 'the world': "swiecie"} print world_best_dic['you are'], world_best_dic['...
996,060
c71156e02198a12a2025d4aae59bd858626e9e65
import pdfquery import scraperwiki from bs4 import BeautifulSoup import StringIO #from pdfquery.cache import FileCache import re base_url = "http://dpc.sa.gov.au" html = scraperwiki.scrape("http://www.dpc.sa.gov.au/lobbyist-who-register") soup = BeautifulSoup(html, "html5lib") lobbys = [] for tr in soup.tbody: lob...
996,061
ea4147923a64b3b613feb41556d619db8f2f3b47
# Extract names around each word regex &gt;&gt;&gt; import re &gt;&gt;&gt; re.findall(r"([a-zA-Z]+) loves ([a-zA-Z]+)", "Mary loves Mike,Jack loves Lily,Ethan loves Lydia") [('Mary', 'Mike'), ('Jack', 'Lily'), ('Ethan', 'Lydia')]
996,062
26b6c7cdd3887e471cfe7b72ae6b0a2cd957e6f9
from room import Room from items import Item # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", """North of you, the cave mount beckons"""), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""...
996,063
6ba5cf5974e59ea5a78a107d14bd98f920e040dc
import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt POBLACION_TOTAL = 1. INFECTADOS_INICIAL, RECUPERADOS_INICIAL = 0.03, 0 SUSCEPTIBLES_INICIAL = POBLACION_TOTAL - INFECTADOS_INICIAL - RECUPERADOS_INICIAL ALFA, BETA = 0.27, 0.043 TIEMPO_DIAS = np.linspace(0, 150, 150) def modelo_sir(...
996,064
81104078d33d89699254099d30d53e4b6910f0ae
import csv import json import colorama from termcolor import cprint import sys sys.path.append('../../Code/Algorithms') sys.path.append('../../Data') sys.path.append('../../Results') from read_data import read_data from smart_grid import SmartGrid, SmartHouse, SmartBattery def main(): """ fixed, you can now use ...
996,065
c3f379a20bd340d9d9827fc87a61f59638543f37
# 당신은 최근에 코딩 스터지 모임을 새로 만들었습니다.
996,066
1121eb433f425a5bfde1d68e433a3af98554119c
num = int(input("Number Nakh")) if (num % 2) == 0: print("Beki Chhe") else: print("Eki Chhe") if (num % 4) == 0: print("4 na pada ma aave chhe") else: print("4 na pada ma nathi aavto") num1 = int(input("pelo Number Nakh")) num2 = int(input("bijo Number Nakh")) devide = num1 / 2 if devide == num2: ...
996,067
9ec1d0c0da5cc232ff4c44caa7f23dac4ed7c7fd
import re pattern =re.compile(r'\d+') #用于匹配至少一个数字 m=pattern.match('one12twothree34four') #查找头部,没有匹配 print(m,'\n') m=pattern.match('one12twothree34four',2,10) #从脚标为2的‘e’开始匹配,并没有匹配 print(m) m=pattern.match('one12twothree34four',3,10) #从脚标为3的‘1’开始匹配,正好匹配 print(m) # <re.Match object; span=(3, 5), match='12'> pr...
996,068
3b2f1798f70c319c3474b87726e9f46a9f0230fa
import ast import pytest import re import shutil import tarfile from poetry.io import NullIO from poetry.masonry.builders.sdist import SdistBuilder from poetry.packages import Package from poetry.poetry import Poetry from poetry.utils._compat import Path from poetry.utils._compat import to_str from poetry.utils.venv i...
996,069
64d6c2c9b9bc3bb659579fa496a8d44eb13a2169
import random def generate(count): """This module will generate values for requests and write them into a file Alternatively we can read from db or from file here. If we care about the memory, we can replace this with generator. :param count: how many values to generate :return: lst - list of valu...
996,070
4506d703398d64a8bc7347b3905c682f564bcecb
#!/usr/bin/env python #-*- coding:utf-8 -*- """ @author:BanShaoHuan @file: Python自动生成表情包.py @time: 2018/05/11 @contact: banshaohuan@163.com @site: @software: PyCharm # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏┛┻━━...
996,071
98129813f36a577c04068a1b3002ce27668454ec
from sklearn.decomposition import PCA from keras.utils import normalize as norm_keras from sklearn.preprocessing import normalize as norm_skl from numpy import asarray, concatenate, transpose, column_stack, array, isnan, amin, amax, vstack, ndarray from random import sample from numpy.random import shuffle from itertoo...
996,072
cbcfffe4ba4deb756f691ede1405be9d451af490
from src.environment import Environment from src.action import Action from src.q_learning.q_agent import QAgent from src.q_learning.q_episode import QEpisode from src.performace import Performance from src.state import State from src.q_learning.q_function import QFunction import pickle class QLearning: def __init...
996,073
40d2e354701cb65b18c78beab16be13bd7ab2cbd
# Bomb Rewards Policies BOMB_NO_REWARD = 0 BOMB_REWARD_PER_STONE_DESTROYED = 1 BOMB_REWARD_PER_STONE_DESTROYED_PROPORTIONAL_TO_EXIT = 2 # Navigation Rewards Policies NAVIGATION_NO_REWARD = 0 NAVIGATION_REWARD_PROPORTIONAL_TO_EXIT = 1 # Agents QLEARNING = 0 RMAX = 1 FACTOREDRMAX = 2 SARSA = 4 SARSALAMBDA = 5 DYNA = 6 ...
996,074
3373f324d629d4eecd01c706388d13f938a12175
import os import glob import shutil import json from pprint import pprint import numpy as np def evaluate_check_point_json(checkpoint_json_file): with open(checkpoint_json_file) as data_file: data = json.load(data_file) loss_history = data['val_loss_history'] checkpoint_pointer = data['val_loss_h...
996,075
e7390d6311f6e4d56de52698ba6b389df681675c
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from torch.autograd import Variable class EncoderCNN(nn.Module): def __init__(self, embed_size): super(EncoderCNN, self).__init__() resnet = models.resnet50(pretrained=True) for param in ...
996,076
7087817c88b5df17cb3f50abd57174561c3dfbb4
import random from wordlist import * POINTS = {"A": 1, "C": 3, "B": 3, "E": 1, "D": 2, "G": 2, "F": 4, "I": 1, "H": 4, "K": 5, "J": 8, "M": 3, "L": 1, "O": 1, "N": 1, "Q": 10, "P": 3, "S": 1, "R": 1, "U": 1, "T": 1, "W": 4, "V": 4, "Y": 4, "X": 8, "Z": 10} FREQ_DICT = {'A': 9, 'B':...
996,077
954d65e0c0df8353fcdee7b3437622fe32283553
import discord from discord.ext import commands import hashlib from hashlib import sha256 import json import os ## Define your TOKEN environment variable for the bot to work! token = os.environ.get("TOKEN") ## Define your OWNER environment variable for the bot to work and to recognize the bot owner! owner = ...
996,078
46b0fc4cec8922211a82f58e0ca7072af94f14d3
from touchworks.api.http import TouchWorks, TouchWorksException import json import unittest import uuid from touchworks.logger import Logger import pprint from nose.tools import raises import random logger = Logger.get_logger(__name__) class TestAPIs(unittest.TestCase): @classmethod def setUpClass(cls): ...
996,079
6416530f9c66ac5526ef0e9060fbe8fa6978de53
from django import template from django.urls import reverse register = template.Library() navbar_options = [ ("Home", reverse("Home")), ("Testing Strips", reverse("Testing Strips")), ("Scheduled Tests", reverse("Scheduled Tests")), ("Test Results", reverse("Graph Results")), ] option_format = '<li cl...
996,080
9e49d3537cae7b0d727fdda29b854a50a19bf864
import sys, os here = os.path.dirname(os.path.realpath(__file__)) vendored_dir = os.path.join(here, 'vendored') sys.path.append(vendored_dir) import boto3 import json import datetime # Create CloudWatch client cloudwatch = boto3.client('cloudwatch') ddb = boto3.client('dynamodb') aas = boto3.client('application-autosc...
996,081
e60f92ce944ffa521f0feeba98e12e8f8a7dba71
# -*- coding: utf-8 -*- """ Created on Sat Jun 6 12:13:12 2020 @author: thecr """ import pandas import numpy import csv from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator import matplotlib.pyplot as plt from sklearn import linear_model import statsmodels.api as sm #Read our data from c...
996,082
c7a54bbbd5fbaef91c3e479d17b6aad8647d7418
from app import models class Queries(): def get_n_comans(self, post): if type(post) is models.Post: #returns number of comments on post. n_answers = models.Post_Comments.query.filter_by(post_id = post.id).count() return n_answers elif type(post) is models.Answers: #returns number of comments on answer...
996,083
12f17e57ce1a7c35ac8f6f949baacd133afcfaa4
from django.db import models from web3 import Web3 class ETHAddressField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 42 super().__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = getattr(model_instance, self.attname, None) ...
996,084
dcffd6c15695a265fbb6e40c772ee3171192aa7a
# -*- coding: utf-8 -*- # -*- author: Jiangtao -*- """setup file""" from setuptools import setup, find_packages from os import path as os_path from codecs import open this_directory = os_path.abspath(os_path.dirname(__file__)) # 读取文件内容 def read_file(filename): with open(os_path.join(this_directory, filename),...
996,085
8eb98ef6cd83ee9dc6cb66168b1c9ebdf6252c86
import yaml import pandas as pd import re from argparse import ArgumentParser def parsed_args(): """ Parse and returns command-line args Returns: argparse.Namespace: the parsed arguments """ parser = ArgumentParser() parser.add_argument( "--input_csv", default="bios.csv...
996,086
a10562113001e8244e2775ee6a9c8945ebea8f9a
""" 给定一个整数类型的数组 nums,请编写一个能够返回数组 “中心索引” 的方法。 我们是这样定义数组 中心索引 的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。 如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。   示例 1: 输入: nums = [1, 7, 3, 6, 5, 6] 输出:3 解释: 索引 3 (nums[3] = 6) 的左侧数之和 (1 + 7 + 3 = 11),与右侧数之和 (5 + 6 = 11) 相等。 同时, 3 也是第一个符合要求的中心索引。 示例 2: 输入: nums = [1, 2, 3] 输出:...
996,087
3a0294086761647d9b3ed32e1920646ee3d8e9f1
#题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少? number = 0 for i in range(1,5,1): for j in range(1,5,1): for k in range(1,5,1): if (i != j) & (j != k) & (i != k): number = number + 1 print(i,j,k) print('一共有%d个互不相同且无重复数字的三位数'%number)
996,088
f86a5462d028936695cc18b7add4b21a5382d8d2
star = int(input('ENter the nu of start do you want to print? \n')) for i in range(star): print(f"{'*'*(i+1)}")
996,089
130ffb6051383d778f9adc5b470bffaa7093a6e9
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 4 12:33:10 2018 @author: danamulligan """ def ratio(dna): counter = 0 total = len(dna) for k in dna: if k == 'g' or k == 'c': counter += 1 return counter/total
996,090
a619db60c2d8e906fbfeafa9297b503822ad2b7b
import flask from flask import request, render_template, redirect, url_for from network_graph.models.graph import Graph blueprint = flask.Blueprint('main', __name__) @blueprint.route('/') def index(): from networkx.readwrite import json_graph g = Graph() return render_template( 'main/index.html',...
996,091
0f6c3c01da9804090ad24f44013b9f5589d89438
''' Exercise 1 Start the Python interpreter and use it as a calculator. 1. How many seconds are there in 21 minutes and 15 seconds? 2. How many miles are there in 5 kilometers? 3. If you run a 5 kilometer race in 21 minutes and 15 seconds, what is your average pace (time per mile in minutes and seconds)? 4. What i...
996,092
4f6dc851465c27678d88b677e2324e1700b76c24
# Generated by Django 2.1.1 on 2018-09-27 10:06 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Database'...
996,093
ba24a8d68bf8b7e0b9800efa9c2f4dbed157507e
topics = ["Alaska is the best State because", "The world will end with a Bang and a ", "Cryptocurrencies are a sham", "The Singularity is nigh", "John's Hackathon submission was awarded ", "This years Super Bowl winner will be: ", "Deep Learning has lead to countless jobs being replaced", "The best job in the computer ...
996,094
3159b09f9d33e30b01209e878d553f8f045e4744
p=[] expresão=input('Digite a expressão:\n') correto=False for i in expresão: if i=='(': p.append(i) elif i==')': p.append(i) print(p) while p!=[]: if(p[0]=='(' and p[len(p)-1]==')'): correto=True del(p[0]) del(p[len(p)-1]) else: correto = False ...
996,095
a7969b2e8a000f523879f3821c3d04ac030960bf
#import numpy as np #from numpy import * from numpy import array x=array([1,2,5,6,3,74],int) print(x)
996,096
239cc8ce7ca3da8c9523d42d268e1a536fbeffd3
from django.db import models """ MVT 中的 M """ # Create your models here. class BookInfo(models.Model): title=models.CharField(max_length=20) pub_date=models.DateTimeField() class HeroInfo(models.Model): name=models.CharField(max_length=20) gender=models.BooleanField(default=True) content=models.Cha...
996,097
80d9462ccae142e3882ec68ddbf3b796dbaab825
from math import sqrt from numpy import concatenate from pandas import DataFrame from pandas import concat from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error # Import sklearn.preprocessing.StandardScaler from sklearn.preprocessing import MinMaxScaler def series_to_supervised...
996,098
7d54c78dff467eb24613338ec7a0af128040cbfd
""" pyexcel_xlsbr ~~~~~~~~~~~~~~~~~~~ The lower level xlsb file format handler :copyright: (c) 2019-2020 by Onni Software Ltd & its contributors :license: New BSD License """ # flake8: noqa from pyexcel_io.io import get_data as read_data from pyexcel_io.io import isstream from pyexcel_io.plugins imp...
996,099
20c3f0794ca0131eb04bb44be3fa17822c16785b
import pandas as pd import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # input parameters Sigma = np.array([[1, -0.8], [-0.8, 2]]) # Covariance matrix of the Bivariate Normal distribution c = np.sqrt(Sigma[1, 1] - Sigma[1, 0] * 1/(Sigma[0, 0]) * Sigm...