index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
5,400 | acb85a16e45472dac61eed4162dc651f67a0e8ca | import settings
#from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
#admin.autodiscover()
# Uncomment the next two lines to enable the admin... |
5,401 | d472a15d6fa826e50a550996369b00b6c599a1c7 | from .scheduler import Scheduler
MyScheduler = Scheduler()
|
5,402 | e44e19dbeb6e1e346ca371ca8730f53ee5b95d47 | from boa3.builtin import public
@public
def Main() -> int:
a = 'just a test'
return len(a)
|
5,403 | 3366d1d4ecc4cc9f971dff0c8adfbadc5511cc9e | #print 'g'
class Client:
def __init__(self, mechanize, WEBSERVICE_IP,WEBSERVICE_PORT, FORM_INPUT_PATH, dat , data_id = 'data', rasp_id_id = 'rasp_id',password = 'pass'):
self.WEBSERVICE_PORT = WEBSERVICE_PORT
self.mechanize = mechanize
self.WEBSERVICE_IP = WEBSERVICE_IP
self.FORM_INPUT_P... |
5,404 | 803283c9dac78c821373fa1025008b04919df72c | from turtle import *
from freegames import vector
def line(start, end):
"Draw line from start to end."
up()
goto(start.x, start.y)
down()
goto(end.x, end.y)
def square(start, end):
"Draw square from start to end."
up()
goto(start.x, start.y)
down()
begin_fill()
... |
5,405 | cdc8c8aba384b7b1b5e741ffe4309eaee30aaada | # Generated by Django 3.0.5 on 2020-04-30 06:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('products_app', '0003_auto_20200429_0739'),
]
operations = [
migrations.CreateModel(
name='User'... |
5,406 | b0e4042ac4ed54cafedb9e53244c164527559e39 | rak="hello\n"
n=input()
print(rak * int(n))
|
5,407 | 1857d76b8c68c58d2d721de529811a6aeb09fcbb | from fastapi import FastAPI
from app.router.routes import initRoutes
from app.cors.cors import initCors
app = FastAPI(debug=True,title="Recipe API")
initCors(app)
initRoutes(app)
|
5,408 | f5e60f2d384242b9675e756f67391ea09afcc262 | from customer_service.model.customer import Customer
def get_customer(customer_id, customer_repository):
return customer_repository.fetch_by_id(customer_id)
def create_customer(first_name, surname, customer_repository):
customer = Customer(first_name=first_name, surname=surname)
customer_repository.stor... |
5,409 | 76348448a658736627efe8fa6b19c752191966e7 | f=open('poem.txt')
for line in f:
print line,
|
5,410 | 958d7ec966179d63c6ba0a651e99fff70f0db31a | from collections import defaultdict, deque
import numpy as np
import gym
from chula_rl.policy.base_policy import BasePolicy
from chula_rl.exception import *
from .base_explorer import BaseExplorer
class OneStepExplorerWithTrace(BaseExplorer):
"""one-step explorer but with n-step trace"""
def __init__(self... |
5,411 | 467b919f6953737eedd3f99596df244bd1177575 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
r_data_df = pd.read_csv('./Shootout Data/Shootout_Mac2017.csv')
em_data_df = pd.read_csv('./Shootout Data/Shootout_Emily.csv')
aishah_data_df = pd.read_csv('./Shootout Data/Shootout_Aishah_Mac2011.csv')
agni_data_df = pd.read_csv('./Shootout Data/S... |
5,412 | 5e06dfb7aac64b5b98b4c0d88a86f038baf44feb | import math
import os
import pathfinder as pf
from constants import X_ROBOT_LENGTH, Y_ROBOT_WIDTH, Y_WALL_TO_EXCHANGE_FAR, \
X_WALL_TO_SWITCH_NEAR
from utilities.functions import GeneratePath
class settings():
order = pf.FIT_HERMITE_QUINTIC
samples = 1000000
period = 0.02
maxVelocity =... |
5,413 | c248d653556ecdf27e56b57930832eb293dfd579 | from ShazamAPI import Shazam
import json
import sys
print("oi")
|
5,414 | 4fb563985bd99599e88676e167ee84a95b018aba | import os
import struct
import sys
import wave
sys.path.insert(0, os.path.dirname(__file__))
C5 = 523
B4b = 466
G4 = 392
E5 = 659
F5 = 698
VOLUME = 12000
notes = [
[VOLUME, C5],
[VOLUME, C5],
[VOLUME, B4b],
[VOLUME, C5],
[0, C5],
[VOLUME, G4],
[0, C5],
[VOLUME, G4],
[VOLUME, C5],
... |
5,415 | 8c11463e35fb32949abbb163a89f874040a33ad0 | import cv2
import numpy as np
import time
from dronekit import connect, VehicleMode
connection_string = "/dev/ttyACM0"
baud_rate = 115200
print(">>>> Connecting with the UAV <<<<")
vehicle = connect(connection_string, baud=baud_rate, wait_ready=True)
vehicle.wait_ready('autopilot_version')
print('ready')
cap = cv2.V... |
5,416 | db22e568c86f008c9882181f5c1d88d5bca28570 | import sqlite3 as lite
import sys
con = lite.connect("test.db")
with con:
cur = con.cursor()
cur.execute('''CREATE TABLE Cars(Id INT, Name TEXT, Price INT)''')
cur.execute('''INSERT INTO Cars VALUES(1, 'car1', 10)''')
cur.execute('''INSERT INTO Cars VALUES(2, 'car2', 20)''')
cur.execute('''INSERT INTO C... |
5,417 | c6fdb9c405427a3583a59065f77c75c4aa781405 | from flask import Flask, app
from flask_sqlalchemy import SQLAlchemy
db= SQLAlchemy()
DBNAME = 'database.db'
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'KARNISINGHSHEKHAWAT'
app.config['SQLALCHEMY_DATABASE_URL'] = f'sqlite:///{DBNAME}'
db.init_app(app)
from .views impo... |
5,418 | 2b88bec388f3872b63d6bfe200e973635bb75054 | from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.core.paginator import Paginator
from .models import post
from django.contrib.auth.decorators import login_required
from .forms import post_fo
from django.db.models import Q
def index(request):
posts_l... |
5,419 | 566dab589cdb04332a92138b1a1faf53cd0f58b8 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
from typing import List, Dict, NamedTuple, Union, Optional
import codecs
import collections
import enum
import json
import re
import struct
from refinery.lib.structures import StructReader
from refinery.units.formats.office... |
5,420 | d2da346e11fa9508cab22a3a2fd3ca57a0a755e6 | # Number Guessing Game
import random
#assign secrectNumber to random number from range 1-10, inclusive of 10
secrectNumber = random.randint (1, 11)
#initialize number or guesses to 1 and call it guess
numGuesses = 1
#prompt user to enter their name and enter their guess
name = int (input("Enter your name: ))
print(... |
5,421 | c0b5a0605bdfcb7cb84211d3ad0d24f78f838cdf | import os
import pytest
def get_client():
from apiserver import app, is_caching_enabled
app.config['TESTING'] = True
app.enable_cache(is_caching_enabled())
return app.test_client()
@pytest.fixture
def client():
os.environ['FLASK_ENV'] = 'testing'
yield get_client()
@pytest.fixture
def c... |
5,422 | b76d3b6a4c15833ee2b25fede5923e1fe1dc4dd7 | # stdlib
from typing import Any
# third party
import numpy as np
# syft absolute
import syft as sy
from syft.core.common.uid import UID
from syft.core.node.new.action_object import ActionObject
from syft.core.node.new.action_store import DictActionStore
from syft.core.node.new.context import AuthedServiceContext
from... |
5,423 | 8b4590cf2d8c040b6ab31c63baff0d83ab818641 | '''
config -- config manipulator module for share
@author: shimarin
@copyright: 2014 Walbrix Corporation. All rights reserved.
@license: proprietary
'''
import json,argparse
import oscar,groonga
def parser_setup(parser):
parser.add_argument("base_dir")
parser.add_argument("operations", nargs="*")
... |
5,424 | df00cc501b7b682cc1f4fbc9ae87a27984e6b5ef | class Boundary():
def __init__(self, py5_inst, x1, y1, x2, y2):
self.py5 = py5_inst
self.a = self.py5.create_vector(x1, y1)
self.b = self.py5.create_vector(x2, y2)
def show(self):
self.py5.stroke(255)
self.py5.line(self.a.x, self.a.y, self.b.x, self.b.y)
|
5,425 | bbd421d39894af163b56e7104c3b29a45635d5a3 | from math import *
def heron(a, b, c):
tmp = [a, b, c]
tmp.sort()
if tmp[0] + tmp[1] <= tmp[-1]:
raise ValueError ("Warunek trojkata jest nie spelniony")
halfPerimeter = (a + b + c)/2
return sqrt(halfPerimeter * (halfPerimeter - a)*(halfPerimeter-b)*(halfPerimeter-c))
print heron... |
5,426 | cad881dd29be16de8375b3ce6e4a437562a05097 | files = [
"arria2_ddr3.qip"
]
|
5,427 | f8d0cc9cb0e5f8adf9077ffb39dd6abedfedaa12 | a = int(input('점수를 입력하세요'))
if a >= 70 :
print:('통과입니다.')
print:('축하합니다.')
else :
print:('불합격입니다.')
print("안녕")
|
5,428 | 3bb408f2b2ac63a2555258c05844881ccdfc5057 | import math
import pygame
import numpy as np
from main import Snake, SCREEN_WIDTH, SCREEN_HEIGHT, drawGrid, GRIDSIZE
from random import randint
FOOD_REWARD = 5
DEATH_PENALTY = 10
MOVE_PENALTY = 0.1
LIVES = 5
SQUARE_COLOR = (80,80,80)
SNAKE_HEAD_COLOR = ((0,51,0), (0,0,153), (102,0,102))
SNAKE_COLOR = ((154,205,50), ... |
5,429 | 88e34878cdad908ed4ac30da82355aaa46ed719b | from rest_framework import serializers
from django.contrib import auth
from rest_framework.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from django.utils.translation import gettext as _
from rest_users.utils.api import _build_initial_user
User = auth.get_user_... |
5,430 | d3342507cb1966e14380ff28ae12b5c334abd20a | from datetime import *
dd=int(input("enter number day: "))
nn=int(datetime.now().strftime("%w"))+1
# print(dd)
# print(nn)
print((datetime.now().date())+(timedelta(days=dd-nn)))
|
5,431 | 88cc4ae4137cf9c0e9c39874b36f7a2770550f96 | from app.exceptions import UserAlreadyExist, UserDoesNotExist
class Accounts(object):
""" Creates an Account where users can be stored """
def __init__(self):
self.users = {}
def add_user(self, user):
if user.id in self.users:
raise UserAlreadyExist
else:
s... |
5,432 | b90678c8f7ad9b97e13e5603bdf1dc8cb3511ca5 | # PySNMP SMI module. Autogenerated from smidump -f python DOCS-IETF-QOS-MIB
# by libsmi2pysnmp-0.1.3 at Thu May 22 11:57:36 2014,
# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imports
( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integ... |
5,433 | 2908d34165fac272c9571be623855a0613c952f3 | from django.contrib.auth.models import User
from django_filters import (
NumberFilter,
DateTimeFilter,
AllValuesFilter
)
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import permissions
from rest_framework.throttling import ScopedRateThrottle
fr... |
5,434 | db93de33f537eeaf64ca8e2b2b79aba1f592305b | import urllib.request
username = ''
link = r'https://www.instagram.com/' + username
html = urllib.request.urlopen(link)
print(html.read()) |
5,435 | de9b85c250dea15ff9201054957ebc38017a8c35 | n=7
a=[]
for i in range(1,n+1):
print(i)
if(i<n):
print("+")
a.append(i)
print("= {}".format(sum(a)))
|
5,436 | b724b04c6303cc9021539ad7df5a198000491029 | # -*- coding: utf-8 -*-
# Project = https://github.com/super-l/search-url.git
# Author = superl
# Blog = www.superl.org QQ:86717375
# Team = Code Security Team(C.S.T) | 铭剑创鼎
import urllib2
import re
import ConfigParser
from lib.filter import *
from lib.getdata import *
from lib.count import *
from lib.status... |
5,437 | b51e0ee80a2488197470627821204d1f74cd62a1 | # POST API for Red Alert project - NLP and Metalearning components
# Insikt Intelligence S.L. 2019
import pandas as pd
import pickle
from flask import Flask, render_template, request, jsonify
from utilities import load_data, detect_language
from preprocessing import preprocess, Tagger, remove_stopwords
import json
fro... |
5,438 | 5209638ec97a666783c102bec7a2b00991c41a08 | # ----------------------------------------------------------------------------
# Written by Khanh Nguyen Le
# May 4th 2019
# Discord: https://discord.io/skyrst
# ----------------------------------------------------------------------------
import operator
def validInput(x):
if x=="a": return True
elif x=... |
5,439 | d287123acdbabdd5a223e774c89945ab888fcbcc | #os for file system
import os
from sys import platform as _platform
import fnmatch
import inspect
files = 0
lines = 0
extension0 = '.c'
extension1 = '.cpp'
extension2 = '.h'
extension3 = '.hpp'
filename = inspect.getframeinfo(inspect.currentframe()).filename
startPath = os.path.dirname(os.path.abspath(... |
5,440 | 8286407987301ace7af97d6acdcf6299ce3d8525 | from django.db import models
class Book(models.Model):
title = models.TextField(max_length=32, blank=False, null=False)
# from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
#
#
# class UserAccountManager(BaseUserManager):
# def create_user(self, email, firstname,lastna... |
5,441 | b4d31fd05f8a9d66dcfffb55d805ab93d7ff9cdf | #Write a function remove_duplicates that takes in a list and removes elements of the list that are the same.
#For example: remove_duplicates([1,1,2,2])
#should return [1,2].
#Do not modify the list you take as input! Instead, return a new list.
def remove_duplicates(lst_of_items):
new_list=list()
#dict={}
... |
5,442 | c96a64573fc6cc207ee09be4f4b183d065736ff6 | from collections import deque
'''
Big O
เวลาเรียก queue จะมี2operation 1deque 2enqueue เวลาเอาไปใช้
อยู่ที่การimplementation
โปรแกรมที่ดี 1.ทำงานถูกต้อง 2.ทันใจ 3.ทรัพยากรที่ใช้รันได้ทุกเครื่อง(specคอมกาก)
4.ทำงานได้ตามต้องการ5.ความเสถียรของระบบ 6.Bugs
แพง คือ memory expansive ใช้หน่วยความจำเยอะ
runtime exp... |
5,443 | 5c315a49ead80e8d8ce057bd774f97bce098de59 | import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
import tensorflow as tf
from tensorflow.python.framework import ops
from pathlib import Path
from scipy.io import loadmat
from skimage.transform import resize
from sklearn.... |
5,444 | b0dbc4e8a2ce41dc9d2040890e3df4d078680fa1 | from collections import deque
def solution(people, limit):
people.sort()
cnt = 0
left_idx = 0
right_idx = len(people)-1
while left_idx <= right_idx:
if people[left_idx] + people[right_idx] <= limit:
cnt += 1
left_idx += 1
right_idx -= 1
else:
... |
5,445 | 4e66fe0485d987da590d11c848009b2e1665b3dc | from flask import Blueprint, render_template, flash, redirect, url_for, request, current_app, g, session
from flask_login import current_user
from app import decorators
from app.models import User, Post, Comment, Tag
from slugify import slugify
from app.main.forms import CommentForm, TagForm, ProfileForm, ContactForm
f... |
5,446 | bc5e928305d82c92c10106fe1f69f5979d57e3d2 | import os
from tqdm import tqdm
from system.krl import KRL
from system.utils.format import format_data
from system.oie import OIE
# extract one file
def execute_file(input_fp, output_fp):
oie = OIE()
oie.extract_file(input_fp, output_fp)
# extract one sentence
def execute_sentence():
... |
5,447 | e1968e0d6146ce7656505eeed8e9f31daa4b558a | from django.contrib import admin
# from django.contrib.admin import AdminSite
# class MyAdminSite(AdminSite):
# site_header = 'Finder Administration'
# admin_site = MyAdminSite(name='Finder Admin')
from finder.models import Database, Column, GpsData, Alarm, System
class ColumnInline(admin.TabularInline):
mo... |
5,448 | d3e728bda85d2e72b8e477ab439d4dcffa23d63a | #!/usr/bin/env python
import speech_recognition as sr
from termcolor import colored as color
import apiai
import json
from os import system
import wikipedia as wiki
from time import sleep
import webbrowser as wb
BOLD = "\033[1m" #use to bold the text
END = "\033[0m" #use to close the bold text
CLIENT_ACCESS_TOK... |
5,449 | 5b4a196de60a3a30bc571c559fe5f211563b8999 | # -*- coding: utf-8 -*-
# @File : config.py
# @Author: TT
# @Email : tt.jiaqi@gmail.com
# @Date : 2018/12/4
# @Desc : config file
from utils.general import getchromdriver_version
from chromedriver.path import path
import os
import sys
chromedriver = os.path.abspath(os.path.dirname(__file__)) + "\\chromedriver\\"+ g... |
5,450 | aa4226c377368d1ece4e556db9b7fdd0134472c9 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
5,451 | 00051a4087bfcf2e6826e9afa898830dc59aa5ab | # -*-coding:utf-8-*-
# Author: Scott Larter
import pygame
import pygame.draw
import numpy as np
from agent import *
from tools import *
SCREENSIZE = [1200, 400] # walls.csv
#SCREENSIZE = [1200, 650] # walls2.csv
RESOLUTION = 180
AGENTSNUM = 12
GROUPSNUM = 2
MAXGROUPSIZE = 6
MAXSUBGROUPSIZE = 3
BACKGROUNDCOLOR = [255... |
5,452 | 519dbe97ce9de30e616d660ef168e686c52b01b5 | #!/usr/bin/env python3
#
# main.py - By Steven Chen Hao Nyeo
# Graphical interface for Socionics Engine
# Created: August 8, 2019
import wx
from cognitive_function import *
from entity import Entity
from function_to_type import Translator
from function_analysis import *
class TypeFrame(wx.Frame):
def __init__(s... |
5,453 | 81b920ab5417937dc0fc1c9675d393efc6a4d58d | import pandas as pd #@UnusedImport
import matplotlib.pyplot as plt
import matplotlib #@UnusedImport
import numpy as np #@UnusedImport
class Plotter():
def __init__(self):
self.red_hex_code = '#ff0000'
def AlkDMIonStatsSplitPlot(self, df):
PV1_DataSets_lst = df[df['inst'] == 'PV1']['DataSet'].unique()
... |
5,454 | aa952e8f9a1855b5578cb26d6e5aca42605ee585 | # https://leetcode-cn.com/problems/zigzag-conversion/
# 6. Z 字形变换
class Solution:
def convert(self, s: str, numRows: int) -> str:
res = ''
for i in range(numRows):
pass
return res
|
5,455 | 0e47a7d9cd6809886674291d6a535dd18205a012 | #!/usr/bin/env python3
def GetDensity(T, P, config):
return P/(T*config["Flow"]["mixture"]["gasConstant"])
def GetViscosity(T, config):
if (config["Flow"]["mixture"]["viscosityModel"]["type"] == "Constant"):
viscosity = config["Flow"]["mixture"]["viscosityModel"]["Visc"]
elif (config["Flow"]["mixture"]... |
5,456 | 4379d89c2ada89822acbf523d2e364599f996f8c | import numpy as np
import pandas as pd
import sklearn
import sklearn.preprocessing
import matplotlib.pyplot as plt
import tensorflow as tf
from enum import Enum
from pytalib.indicators import trend
from pytalib.indicators import base
class Cell(Enum):
BasicRNN = 1
BasicLSTM = 2
LSTMCellPeephole = 3
GR... |
5,457 | 4d82e68faa3102fc2949fd805588504b7d874589 | import os, sys, datetime, pytz, tzlocal, urllib.request, requests, csv, hashlib, json, boto3
uri = 'ftp://ftpcimis.water.ca.gov/pub2/daily/daily107.csv' #Station 107 is Santa Barbara
base_et = 0.15
def main():
try:
tempfile = tempfile_name()
get_datafile(tempfile)
except:
print("Could not retrieve da... |
5,458 | 382f7119beba81087c497baf170eb6814c26c03e | """byte - property model module."""
from __future__ import absolute_import, division, print_function
class BaseProperty(object):
"""Base class for properties."""
def get(self, obj):
"""Get property value from object.
:param obj: Item
:type obj: byte.model.Model
"""
ra... |
5,459 | beb9fe8e37a4f342696a90bc624b263e341e4de5 | #!/usr/bin/python
L=['ABC','ABC']
con1=[]
for i in range (0,len(L[1])):
#con.append(L[1][i])
con=[]
for j in range (0, len(L)):
print(L[j][i])
con.append(L[j][i])
con1.append(con)
con2=[]
for k in range (0,len(con1)):
if con1[k].count('A')==2:
con2.append('a')
elif con1[k].count('B')... |
5,460 | 8f14bbab8b2a4bc0758c6b48feb20f8b0e3e348b | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File: software/jetson/fastmot/utils/sot.py
# By: Samuel Duclos
# For: Myself
# Description: This file returns detection results from an image.
from cvlib.object_detection import draw_bbox
class ObjectCenter(object):
def __init__(self, args)... |
5,461 | bb730606c7357eeb605292d5b9c05e8e8a797ea2 | n,k=[int(input()) for _ in range(2)]
ans=1
for _ in range(n):
ans=min(ans*2,ans+k)
print(ans)
|
5,462 | 4c38d0487f99cdc91cbce50079906f7336e51482 | from platypush.message.response import Response
class CameraResponse(Response):
pass
# vim:sw=4:ts=4:et:
|
5,463 | b72bf00d156862c7bddecb396da3752be964ee66 | # SaveIsawQvector
import sys
import os
if os.path.exists("/opt/Mantid/bin"):
sys.path.append("/opt/mantidnightly/bin")
#sys.path.append("/opt/Mantid/bin") # Linux cluster
#sys.path.append('/opt/mantidunstable/bin')
else:
sys.path.append("C:/MantidInstall/bin") # Windows PC
# import ma... |
5,464 | 1599f5e49ec645b6d448e74719e240343077aedd | from django.conf.urls import patterns, include, url
from django.contrib import admin
from metainfo.views import DomainListView
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'metapull.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', DomainListView.as_view()),
url(... |
5,465 | 1b09b18926dc95d4c4b3088f45088f12c162ccb3 | # -*- coding: utf-8 -*-
a=float(input('Digite um número:'))
b=(a-(a%1))
c=(a%1)
print('O valor inteiro é %d' %b)
print('O valor decimal é %.6f' %c) |
5,466 | 9e987e057ee5322765415b84e84ef3c4d2827742 | # Copyright (c) 2008-2016 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test the `interpolation` module."""
from __future__ import division
import logging
import numpy as np
from numpy.testing import assert_almost_equal, assert_array_almost_eq... |
5,467 | cfc0ca0d8528937526f6c42721870f1739a2ae95 | from turtle import Screen
import time
from snake import Snake
from snake_food import Food
from snake_score import Scoreboard
screen = Screen()
screen.setup(width=600,height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)
snake = Snake()
food=Food()
score=Scoreboard()
screen.... |
5,468 | 9adf18b3a65bf58dd4c22a6fe026d0dd868533fb | from .models import Stock
from .serializers import StockSerializer
from rest_framework import generics
class StockListCreate(generics.ListCreateAPIView):
queryset = Stock.objects.all()
serializer_class = StockSerializer
|
5,469 | a76a0631c97ba539019790e35136f6fd7573e461 | from google.cloud import pubsub_v1
import os
from flask import Flask, request, jsonify
from google.cloud import pubsub_v1
import os
from gcloud import storage
import json
import datetime
import time
app = Flask(__name__)
os.environ[
"GOOGLE_APPLICATION_CREDENTIALS"] = "/home/vishvesh/Documents/Dal/serverless/api-... |
5,470 | 4cdd5fc15096aac01ad6d97d38ef7397859de18b | import json
import urllib
while True:
# Get input URL
url = raw_input("Enter URL: ")
# Check valid input
if len(url) < 1:
break
# Get data
print("Retrieving", url)
connection = urllib.urlopen(url)
data = connection.read()
print("Retrieved", len(data), "characters")
# P... |
5,471 | 20c081dc47f541a988bccef89b8e51f446c80f58 | # terminal based game in Python
from random import randint
print('Terminal based number guessing game')
while True:
try:
numberOfGames = int(input('Please choose how many games you want to play ---> '))
except:
print('Only numbes accepted')
continue
if (numberOfGames > 0 and numberO... |
5,472 | 6bde0ce30f33b155cc4c9ce9aa2ea6a6c5a1231d | """Coroutine utilities."""
from decorator import decorator
@decorator
def coroutine(f, *a, **kw):
"""This decorator starts the coroutine for us."""
i = f(*a, **kw)
i.next()
return i
|
5,473 | f1601d3d820b93631f9b1358627a5716016ad135 | import os
def is_admin():
"""
The function ``is_admin`` detects whether the calling process is running
with administrator/superuser privileges. It works cross-platform on
either Windows NT systems or Unix-based systems.
"""
if os.name == 'nt':
try:
# Only Windows users wit... |
5,474 | 021f224d031477bd305644261ad4d79d9eca98b3 | import pytest
from flaat.issuers import IssuerConfig, is_url
from flaat.test_env import FLAAT_AT, FLAAT_ISS, environment
class TestURLs:
def test_url_1(self):
assert is_url("http://heise.de")
def test_valid_url_http(self):
assert is_url("http://heise.de")
def test_valid_url_https(self):... |
5,475 | 0f0adde7241898d2efe7e2b5cc218e42ed7b73d8 | from functools import reduce
from collections import defaultdict
def memory(count: int, start_numbers: list):
numbers = defaultdict(lambda: tuple(2 * [None]), { el: (idx,None ) for idx,el in enumerate(start_numbers) })
last = start_numbers[-1]
for idx in range(len(numbers), count):
last = 0 if None... |
5,476 | b794a4cca3303ac7440e9aad7bc210df62648b51 | from pkg.models.board import Board
class BaseAI:
_board: Board = None
def __init__(self, board=None):
if board is not None:
self.set_board(board)
def set_board(self, board):
self._board = board
def find_move(self, for_player):
pass
|
5,477 | 957fb1bd34d13b86334da47ac9446e30afd01678 | data = {
'title': 'Dva leteca (gostimo na 2)',
'song': [
'x - - - - - x - - - - -',
'- x - - - x - - - x - -',
'- - x - x - - - x - x -',
'- - - x - - - x - - - x'
],
'bpm': 120,
'timeSignature': '4/4'
}
from prog import BellMusicCreator
exportFile = __file__.replac... |
5,478 | f75e0ddf42cc9797cdf1c4a4477e3d16441af740 | import openpyxl # 适用于xlsx文件
'''
纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示:
{
"1":["张三",150,120,100],
"2":["李四",90,99,95],
"3":["王五",60,66,68]
}
请将上述内容写到 student.xls 文件中
'''
def read_file():
words = []
with open('15.txt', 'r') as file:
content = file.read()
# print(content)
# print(... |
5,479 | 200552b638d6b1a6879b455837677b82689e0069 |
STATUS_CHOICES = (
(-1, 'Eliminado'),
(0, 'Inactivo'),
(1, 'Activo'),
)
USERTYPES_CHOICES = ()
#-- Activation Request Values
ACTIVATION_CHOICES = (
(1, 'Activacion'),
(2, 'Solicitud Password'),
(3, 'Invitacion'),
)
#-- Activation Status Values
ACTIVATIONSTATUS_CHOICES = (
(-1, 'Expirado... |
5,480 | 2c4f27e7d1bfe6d68fd0836094b9e350946913f6 | from django.db import models
class Survey(models.Model):
"""Survey representation.
"""
name = models.CharField(max_length=255)
description = models.TextField()
start_date = models.DateTimeField()
end_date = models.DateTimeField()
def __str__(self):
return self.name
class Questi... |
5,481 | 9ae9fd6da5c3d519d87af699dd4ea9b564a53d79 | import hashlib
hash = 'yzbqklnj'
int = 0
while not hashlib.md5("{}{}".format(hash, int).encode('utf-8')).hexdigest().startswith('000000'):
print("Nope luck for {}{}".format(hash, int))
int += 1
print("Key: {}{}".format(hash, int))
print("Number: {}").format(int) |
5,482 | 36e7398f576aa1d298a20b4d4a27a7b93e3bd992 | import numpy as np
import matplotlib.pyplot as plt
def sigmoid(X):
""" Applies the logistic function to x, element-wise. """
return 1 / (1 + np.exp(-X))
def x_strich(X):
return np.column_stack((np.ones(len(X)), X))
def feature_scaling(X):
x_mean = np.mean(X, axis=0)
x_std = np.std(X, axis=0)
... |
5,483 | 1c60620814a4aea2573caf99cee87590a8d57c18 | #Write by Jess.S 25/1/2019
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
def draw_point(x,y):
plt.scatter(x, y)
plt.title('点分布图')#显示图表标题
plt.xlabel(... |
5,484 | dfbbbaf6b5f02c60ca48f7864068d59349c547d1 | """AWS CDK application.
See https://docs.aws.amazon.com/cdk/ for details.
"""
from ias_pmi_cdk_common import PMIApp
from stacks import MainStack
APP_NAME = 'etl-pm-pipeline-be'
# create CDK application
app = PMIApp(APP_NAME)
# add stacks
MainStack(app, app, 'main')
# synthesize application assembly
app.synth(... |
5,485 | 89881f3cc6703b3f43f5d2dae87fa943d8a21513 | from random import random, randint, choice
from copy import deepcopy
from math import log
"""
Обертка для функций, которые будут находиться в узлах,
представляющих функции. Его члены – имя функции, сама функция
и количество принимаемых параметров.
"""
class fwrapper:
def __init__(self, function, childcou... |
5,486 | 2681bd9fe93a4d61214b7c45e5d73097ab73dc07 | import torch as th
from tpp.processes.hawkes.r_terms_recursive_v import get_r_terms
from tpp.utils.test import get_test_events_query
def run_test():
marks = 3
events, query = get_test_events_query(marks=marks)
beta = th.rand([marks, marks])
get_r_terms(events=events, beta=beta)
if __name__ == '__m... |
5,487 | f46dd5217c8e015546d7fff7ee52569ecc2c8e41 | #8
def matrix(m):
for i in range(len(m)):
for j in range (len(m[0])):
m[i][j]=(m[i][j])**2
a=[[1,2,3],[4,5,6],[8,9,0]]
print('The matrix is ',a)
matrix(a)
print('The updated matrix is ',a)
|
5,488 | 1ac0f5c62ee3cb60d4443b65d429f4f0e6815100 | from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.contrib.auth.forms import SetPasswordForm
from . import views
urlpatterns = [
url(regex=r'^(?P<pk>\d+)$', view=views.UserDetailView.as_view(), name='user_detail'),
url(regex=r'^update/(?P<pk>\d+)$', view=views.UserUpd... |
5,489 | b8a41c56a31acab0181ec364f76010ac12119074 | # PDE:
# add_library('hype')
# processing.py:
from hype.core.util import H
from hype.core.interfaces import HCallback
from hype.extended.behavior import HOscillator
from hype.extended.drawable import HCanvas, HRect
from hype.extended.layout import HGridLayout
from hype.extended.util import HDrawablePool
from random im... |
5,490 | 957545649e9bf1eaabe42a1caa627d544e68f108 | """
This file is part of GALE,
Copyright Joe Krall, 2014.
GALE is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version... |
5,491 | 74de0da708c7eb792dea15afb23713d9d71af520 | #!/usr/bin/env python3
# Created by: Khang Le
# Created on: Dec 2019
# This program uses lists and rotation
def rotation(list_of_number, ratating_time):
numbers = list_of_number[0]
numbers = [list_of_number[(i + ratating_time) % len(list_of_number)]
for i, x in enumerate(list_of_number)]
... |
5,492 | 7b2ca3db44c5f71c2975bd8af701dafca3b3d081 | import math
import numpy as np
class incStat:
def __init__(self, Lambda, isTypeJitter=False): # timestamp is creation time
self.CF1 = 0 # linear sum
self.CF2 = 0 # sum of squares
self.w = 0 # weight
self.isTypeJitter = isTypeJitter
self.Lambda = Lambda # Decay Factor
... |
5,493 | e7f511b97f316157a768203afe9f36ea834ebb6c | import requests
import urllib.request
from utilities.read_write_utilities import read_set,write_to_csv
import time
from bs4 import BeautifulSoup
import pickledb
import json
import glob
import csv
drugs = read_set('/Users/sandeep.dey/Downloads/2020-02-06_scrape/drugs')
print(drugs)
output_records = []
# fields = ["equ... |
5,494 | 77531233219b76be51aed86536e4d92b8dc5ccad | #!/usr/bin/env python3
# Script qui permet de couper au début ou à la fin d'un fichier audio (.wav)
# un silence ou un passage musical à partir d'un fichier de transcription correspondant.
# Supporte uniquement l'extension audio .wav.
# Supporte les formats de transcriptions suivants :
# - .stm
# - .mlfmanu... |
5,495 | d7b426727e11833b3825baac7b379f5ce44ea491 | def ehcf(a, b):
p1, q1, h1, p2, q2, h2 = 1, 0, a, 0, 1, b
from math import floor
while h2 != 0:
r = floor(h1/h2)
p3 = p1-r*p2
q3 = q1-r*q2
h3 = h1-r*h2
p1,q1,h1,p2,q2,h2 = p2,q2,h2,p3,q3,h3
return (p1, q1, h1)
def findinverse(k, p):
l = ehcf(k,p)[0] % p
return l |
5,496 | 1c66ccb80383feeee96b3fb492ff63be1a67a796 | import pytest
from django_swagger_utils.drf_server.exceptions import NotFound
from unittest.mock import create_autospec
from content_management_portal.constants.enums import TextType
from content_management_portal.interactors.storages.storage_interface \
import StorageInterface
from content_management_portal.inter... |
5,497 | 06992263599fe3290c87ec00c6cb8af3748920c8 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# jan 2014 bbb garden shield attempt
# AKA
'''
Sensors:
analog level sensor, pin AIN0
TMP102 i2c temperature sensor, address 0x48
(if add0 is grounded) or 0x49 (if pulled up)
Outputs:
Analog RGB LED strip
I2C display(?)
Pump Activate/Deactivate (GPIO pin)
Some measurem... |
5,498 | d081abf3cd9bc323486772b4f6235fbbc9022099 | '''
@mainpage Rat15S Compiler
@section intro_sec Introduction
This will become a Rat15S compiler. Currently working on Lexical Analyzer.
@author Reza Nikoopour
@author Eric Roe
'''
def main():
tokens = Lexer()
if __name__ == '__main__':
sys.path.append('Lib')
from lexicalanalyzer import Lexer
mai... |
5,499 | 2e6bce05c8ba21aa322e306d2cdb8871531d7341 | import random
OPTIONS = ['rock', 'paper', 'scissors']
def get_human_choice():
print('(1) Rock\n(2) Paper\n(3) Scissors')
return OPTIONS[int(input('Enter the number of your choice: ')) - 1]
def get_computer_choice():
return random.choice(OPTIONS)
def print_choices(human_choice, computer_choice):
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.