text stringlengths 8 6.05M |
|---|
# Generated by Django 3.0.1 on 2020-01-09 16:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shopUser', '0011_auto_20200109_1623'),
]
operations = [
migrations.RenameField(
model_name='category',
old_name='title',
... |
import socket
import sys
import json
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = 8003
s.connect((host, port))
data = s.recv(1024)
data = data.decode("utf-8")
s.send(b'Thank you from client')
dataj = json.loads(data)
print(type(dataj))
print(dataj)
s.close()
|
import os
import cv2
import sys
import numpy as np
from keras import applications
from keras.models import Model, load_model, Sequential
from keras.layers import GlobalAveragePooling2D, Dropout, Dense
from train_inception import encode_labels, standardize_data, shuffle_data
from keras.preprocessing.image import ImageDa... |
CLIENT_SECRET_FILE_PATH = "secrets/client_secret.json"
SEEN_EMAIL_DATA_FILE_PATH = "data/seen_email_data.json"
UNUSED_VOTERS_FILE_PATH = "data/unused_voters.json"
ERROR_LOG_FILE_PATH = "logs/error_log.txt"
ROUTINE_ACTION_LOG_FILE_PATH = "logs/routine_log.txt"
ABNORMAL_ACTION_LOG_FILE_PATH = "logs/abnormal_log.txt"
IGN... |
# Generated by Django 2.2.2 on 2019-06-08 09:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0003_auto_20190607_1502'),
]
operations = [
migrations.AddField(
model_name='showtimes',
name='active',
... |
from django.urls import path
from rest_framework.routers import DefaultRouter
from user.views import UserViewSet, AuthView, Logout, RetrieveCountryCityView
router = DefaultRouter(trailing_slash=False)
router.register('users', UserViewSet, basename='users')
urlpatterns = router.urls
urlpatterns += [
path('login'... |
Your input
"the sky is blue"
Output
"blue is sky the"
Expected
"blue is sky the"
Your input
"poetry lover"
Output
"lover poetry"
Expected
"lover poetry" |
# import libraries
from tkinter import *
from gtts import gTTS
from playsound import playsound
# Create window
root = Tk()
root.geometry("600x300")
root.config(bg="white")
root.title("TEXT TO SPEECH")
# Bottom heading
bottom_label = Label(root, text="text to speech app", font="arial 20 italic",
... |
'''Es un error en tiempo de ejecucion, la sintaxis del codigo es correcta pero durante la ejecucion ha ocurrido "algo inseperado " '''
'''El problema es que en los lenguajes que ejecutan el codigo asia abajo, una vez que el rpgrama nos da error el resto de lineas no se ejecutan '''
def suma(num1,num2):
return nu... |
#! /usr/bin/env python
from collections import Counter
from bs4 import BeautifulSoup
from RetrievalModel import TfIdf, CosineSimilarity, BM25
import os
import glob
import operator
class Retriever:
def __init__(self):
return
def get_corpus(self, req=True):
corpus = self.build_index(req)
... |
from django.contrib import admin
from .models import Blog
class BlogAdmin(admin.ModelAdmin):
#be chia dasyresi dashte bashim
# fields=['title','content']
fieldsets = [
('title', {'fields': ['title']}),
('content information',{'fields': ['content', 'author']}),
('image',... |
from idc import *
from idautils import *
from Tkinter import Tk
from operator import itemgetter
from collections import OrderedDict
import idaapi
import random
MAX_XREFS = 500
Offsets = {}
BaseOffsets = {}
def FindCallOffsetValue(address):
trueOffset = None
baseOffset = ""
subOffset = ""
leadAddy = ""
secondR... |
import pandas as pd
import numpy as np
import inquirer
import math
from ..config.config import Config
from matplotlib import pyplot as plt
from collections import Counter
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor
from sklearn.preprocessing import LabelEncoder
... |
from django.contrib import admin
from players.models import Player, Cron, Mop
admin.site.register(Player)
admin.site.register(Cron)
admin.site.register(Mop)
|
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from urllib import urlretrieve
import cPickle as pickle
import os
import gzip
import sys
from util import *
sys.setrecursionlimit(10000)
import numpy as np
import theano
import glob
import numpy
import PIL
from PIL import Image,... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
"""End-To-End Memory Networks.
The implementation is based on http://arxiv.org/abs/1503.08895 [1]
"""
from __future__ import absolute_import
from __future__ import division
import tensorflow as tf
import numpy as np
import json
import ConfigParser
from word import Word
f... |
from abc import ABC, abstractmethod
class Instruccion(ABC):
def __init__(self, fila, columna):
self.fila = fila
self.columna = columna
self.arreglo = False
super().__init__()
@abstractmethod
def interpretar(self, tree, table):
pass
@abstractmethod
def getNo... |
import sys
sys.path.append('../STANDAR_LIBRARIES')
from URL_Lib import descargarResultadoData, descargarResultado, descargarResultadoDataSinBeautiful
from File_Lib import saveFile, saveFileExc, loadFile
import re
import requests
from bs4 import BeautifulSoup # pip install beautifulsoup4
import http.client
http.clie... |
#!/usr/bin/env python
import commands
pass_string = commands.getoutput('cat /etc/passwd')
pass_list = pass_string.split('\n')
data = dict()
value = []
value_1 = []
for line in pass_list:
if line.startswith('#'):
continue
line_list = line.split(':')
value_1 = [ line_list[2], line_list[3], line_list[-1] ]
data[l... |
import os
import sys
import tensorflow as tf
import cnn_vgg16
import nn_config
DEFAULT_IMG_CATEGORIES_FILE = os.path.join('DATA', 'Anno', 'list_category_cloth.txt')
DEFAULT_IMG_ATTR_FILE = os.path.join('DATA', 'Anno', 'list_attr_cloth.txt')
DEFAULT_CATEGORY_MODEL_DIR = "category_convnet_model"
DEFAULT_ATTRIBUTE_MODE... |
import numpy as np
def norm_cm(cm):
'''
compute skew-normalized f1 score from confusion matrix
:param cm: confusion matrix
:return: f1n - skew-normalized f1 score
pn - skew-normalized precision
rn - skew-normalized recall
ncm - skew-normalized confusion matr... |
class Solution:
def countBits(self, num):
array = [0]
for i in range(1, num + 1):
array.append(array[i // 2] + i % 2)
return array
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 8 20:29:24 2020
@author: rahul
Here we are implementing some dimentionality reduction for the auto-insurance prediction problem
"""
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
from sklearn.ensemble import RandomF... |
from scadapy import NodeId
from scada_test import BaseTest
class PingTest(BaseTest):
def test_ping(self):
data_items = self.client.node(NodeId.DataItems)
assert data_items == NodeId.DataItems
assert data_items.browse_name == "DataItems"
def test_data_items(self):
data_items = self.clie... |
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import time
class bot:
def __init__(self,email,password):
self.driver = webdriver.Chrome("D:\Sourav (softwares)\chromedriver.exe")
self.email=email
self... |
name = input("Your name? ")
age = input("Age ")
print(name + " " + str(age))
|
# AdventOfCode 2019 day 4 pt 1
# https://adventofcode.com/2019/day/4
# started 7:15-paused 8:00
# started over at 9:05 - 10:00
low, high = [171309,643603]
possiblepasswords = 0
for i in range(low, high+1):
previous = 0
hasdoubledigit = False
# Loop though each digit in the number
for strdigit in str(i):
... |
from .Utils import *
from discord.ext import commands
from dice_roller.DiceThrower import DiceThrower
from card_picker.Deck import Deck
from card_picker.Card import *
from flipper.Tosser import Tosser
from flipper.Casts import *
class Games(commands.Cog):
"""Game tools! Custom RNG tools for whatever."""
de... |
from .database import *
class Model:
"""
Modellen: Klassen innehåller datastrukturen.
-- Kontrollern kan skicka meddelanden till Modellen
och Modellen kan besvara dem.
-- Modellen använder delegater för att sända meddelanden
till Kontroller... |
import os, sys
import subprocess
import fileinput
import time
import sendFile
#sysfs = os.statvfs("/media/pi/")
listNodes = []
maxNodes = 3
fileSequence = 1
totalDataSent = 0
filesDiretory = "/"
def getNewNode():
assert(len(listNodes) < maxNodes)
nextIP = "192.168.0." + str(2+len(listNodes))
nextNode = "ping -W 1 ... |
x=1
end=False
names=[]
while x<=10:
n=input("Enter Name #"+str(x)+": ")
names.append(n)
x=x+1
while end == False:
search=input("\nSearch for a name (type 'e' to stop")
if search in names:
print(search," was found")
else:
if search="e":
end=True
else:
print (search," was not found")
|
# -*- coding: utf-8 -*-
{
'name': 'variacion tipo de cambio',
'version': '1.0.0',
'category': '',
'description': """
In some organisations people want an extra state between draft - send and confirmed.
This module adds state validated to sale order and puts also a menu extra in the sales
""",
'a... |
from django.conf import settings as django_settings
from django.utils.translation import ugettext_lazy as _
from feincms.admin.tree_editor import *
class TreeEditor(TreeEditor):
def _actions_column(self, instance):
actions = super(TreeEditor, self)._actions_column(instance)
static_url = django_set... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-18 10:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nova', '0010_apphost_name'),
]
operations = [
migrations.AddField(
... |
import requests
ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' \
'AppleWebKit/537.36 (KHTML, like Gecko) ' \
'Chrome/75.0.3770.142 Safari/537.36'
headers = {
'User-Agent': ua
#'Accept': text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchan... |
from socket import *
import sys
server_port = 53533
# Create a socket (UDP)
server_socket = socket(AF_INET, SOCK_DGRAM)
# Bind to port
server_socket.bind(('', server_port))
DataDict = {}
# Now listen
print('The server is ready to receive message...')
while True:
# Receive message
message, clie... |
from scapy.all import *
import sys, getopt
import netifaces
def main(argv):
ifaceList = netifaces.interfaces()
try:
opts, args = getopt.getopt(argv,"hi:",["iface="])
except getopt.GetoptError:
print "StarvationDHCP.py -i <interface>"
print "Interfaces availables: " + str(ifaceList)
... |
from .eLABJournalObject import *
from .Samples import *
import urllib.parse
class Storage(eLABJournalObject):
def __init__(self, api, data):
"""
Internal use only: initialize storage object
"""
if ((data is not None) & (type(data) == dict) &
("name" in data)
... |
"""
test fixtures package
"""
|
import time
import imaplib
import serial
##ORG_EMAIL = "@gmail.com"
##FROM_EMAIL = "test50201" + ORG_EMAIL
##FROM_PWD = "TestTest123!"
##SMTP_SERVER = "imap.gmail.com"
##SMTP_PORT = 993
def getUsername():
return input("Username: ")
def getPassword():
return input("Password: ")
def readMail():
... |
# My solution for https://www.hackerrank.com/challenges/predicting-house-prices/problem
# this program gets a score of (9.82 / 10)
import numpy as np
def parseInput():
# put the number of features in the 'feature' variable
# put the number of training examples in the 'number' variable
features, number = li... |
#!/usr/bin/python
#\file loadcell1.py
#\brief Serial communication test with Arduino where loadcells are installed.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Apr.13, 2021
import sys
import serial
import time
if __name__=='__main__':
dev= sys.argv[1] if len(sys.argv)>1 else '/dev/tt... |
if __name__ == "__main__":
favorite_fruits = [
'apple',
'banana',
'peach',
'cherry',
'tomato'
]
if 'banana' in favorite_fruits:
print("You are right bananas are great!")
if 'cherry' not in favorite_fruits:
print("What is wrong with cherry's?")
... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
df = pd.DataFrame({'DataSet':['10', '10','20','20', '30', '30', '40', '40', '50', '50'],\
'Proposed':[0.1, 4, 0, 4.8, 0, 6, 0, 7.3, 0, 8],
'VI-ORB SLAM':[0, 3, 0, 5.1, 0, 6.2, 0, 7.6,... |
#! python3
import webbrowser
import sys
import bs4
import requests
import openpyxl
import os
import xlsxwriter
import re
rootSite = 'http://wiki.wargaming.net/en/World_of_Warships'
#shipclasses = ['DD', 'CA', 'BB', 'CV']
shipclasses = ['DD', 'CA', 'BB']
# shipclasses = ['CA', 'BB']
# skiplist = ['St. Louis']
for sh... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def forwards(apps, schema_editor):
LawFirm = apps.get_model('law_firm', 'LawFirm')
for law_firm in LawFirm.objects.all():
law_firm.payment_plan = 'daily'
law_firm.save()
def backwards(... |
from mpExperience import MpExperience
from mpParamXp import MpParamXp
import os
class MpExperienceQUICReqres(MpExperience):
GO_BIN = "/usr/local/go/bin/go"
SERVER_LOG = "quic_server.log"
CLIENT_LOG = "quic_client.log"
#CLIENT_GO_FILE = "~/go/src/github.com/lucas-clemente/quic-go/example/reqres/client/reqres.go"
... |
# -*- coding: utf-8 -*-
"""
This file contains ELMKernel classes and all developed methods.
"""
# Python2 support
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from .mltools import *
import numpy as np
import ... |
N, M = map( int, input().split())
Q = [[int(s) for s in input().split()] for _ in range(M)]
Q = sorted(Q)
ans = 1
LQ = len(Q)
stan = Q[0][1]
while LQ != 0:
k = 1
if Q[0][0] < stan:
stan = min(stan,Q.pop(0)[1])
LQ -= 1
else:
ans += 1
stan = Q[0][1]
print(ans)
|
import os
import csv
import copy
import time
import math
import numpy as np
import matplotlib.pyplot as plt
import minisam
def getConstDigitsNumber(val, num_digits):
return "{:.{}f}".format(val, num_digits)
def getUnixTime():
return int(time.time())
def eulerAnglesToRotationMatrix(th... |
#import sys
#input = sys.stdin.readline
from itertools import permutations
def main():
N = int(input())
ans = [0]*(N**2+1)
for p in permutations(range(N)):
a = 0
for i in range(N):
a += abs(i-p[i])
ans[a] += 1
print(ans)
if __name__ == '__main__':
main()
|
autor = "VOV"
version = "1.0.0"
|
import logging
import sys
import datetime
import uuid
from django.conf import settings
class RequestTimeLoggingMiddleware(object):
"""Middleware class logging request time to stderr.
This class can be used to measure time of request processing
within Django. It can be also used to log time sp... |
from queries import Query
class Base:
def __init__(self, state_controller):
self.sdk = state_controller.sdk
self.controller = state_controller
# todo remove this var
self.queries = Query(self.sdk)
self.response_phrases = {}
async def before(self, payload, data):
... |
# @Time : 2018/4/3 9:57
# @Author : Jing Xu
import sys,re,types
class NotIntegerError(Exception):
pass
class OutOfRangeError(Exception):
pass
_MAPPING = (u'零', u'一', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九',)
_P0 = (u'', u'十', u'百', u'千',)
_S4, _S8, _S16 = 10 ** 4, 10 ** 8, 10 ** 16
_MIN, _MAX = 0, 9999... |
# TODO:
# 1. why do we need to compile the example in order to build the library in lib?
# 2. related: compiling with too many processors causes some example executable to try to load the gmedia library even when it's not build. How to prevent that?
# 3. finish the export=env for various libraries
from init_env impor... |
import pytest
import pdb
#from fhir_walk.model.organization import organization
from fhir_walk.model import unwrap_bundle
from fhireval.test_suite.crud import prep_server
test_id = f"{'2.2.10':<10} - CRUD PractionerRole"
test_weight = 2
# Cache the ID to simplify calls made after crate
example_practitioner_id = No... |
# -*- coding: utf-8 -*-
import urllib
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
class googlemaps_legacy(nodes.General, nodes.Element):
pass
class GoogleMapsDirective(Directive):
"""Directive for embedding google-maps"""
has_content ... |
from mongodb import MongoTable
from migrate_data import migrate_data
import yaml
import os
class Args():
def __init__(self):
self.dir = "/home/pybeef/workspace/data"
self.config = "/home/pybeef/workspace/leancloud-backup/gen_schema_config.yml"
self.table = "Cow"
self.data_dir = "... |
from rest_framework import serializers
from .models import Delivery, Parcel
class ParcelSerializer(serializers.ModelSerializer):
class Meta:
model = Parcel
fields = '__all__'
class ParcelSerializerRead(serializers.ModelSerializer):
class Meta:
model = Parcel
fields = (
... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Message(models.Model):
sender = models.ForeignKey(User, related_name='message_user')
recipient = models.ForeignKey(User, related_name='message_target')
subject = models.CharField(max_length=100)
body = models... |
import sys
import textwrap
import traceback
import urllib
import xbmc
import datetime
import time
import _strptime
import config
DATE_FORMAT = "%Y-%m-%d %H:%M:%S.%f"
def log(s):
xbmc.log("[%s v%s] %s" % (config.NAME, config.VERSION, s), level=xbmc.LOGNOTICE)
def log_error(message=None):
exc_type, exc_valu... |
# flake8: noqa: F401
from .monero_transaction import MoneroTransaction
|
import requests
from time import sleep
array = []
file = open("sitemap.xml", 'r')
out = open("htaccess.txt", "w+")
count = 0
print("Working...\n")
for line in file:
if("<loc>" in line):
line = line.strip()
line = line[5:-6]
print("Checking URL " + line)
if(requests.get(line).status_code == 404):
... |
# Generated by Django 2.0.2 on 2018-05-30 05:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('login', '0003_auto_20180530_0540'),
]
operations = [
migrations.RenameField(
model_name='article',
old_name='c_time',
... |
# 使用函数来实现多多任务的封装
import threading
import time
def sing():
for i in range(5):
print("{}---sing---".format(threading.current_thread().name))
time.sleep(1)
def dance():
for i in range(10):
print("{}---dance---".format(threading.current_thread().name))
time.sleep(1)
def main():... |
__author__ = 'Leonel Gonzalez'
from esfera import *
from DecimalBinario import *
from memoria_estatica import *
Esferita = Esfera(56)
"""
print "El radio es:" , Esferita.getRadio()
print "El diametro es:" , Esferita.getDiametro()
print "La circunferencia es: ", Esferita.getCircunferencia()
print "El area es: ", Esferi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Xiangwan
import time
t = time.time()
print '当前时间戳为: ', t
localtime = time.localtime(time.time())#获取当地时间下的时间元组,tm_isdst=0因为是夏令时,否则为1
print '本地时间为: ', localtime#定义的localtime可以改
localtime2 = time.asctime(time.localtime(time.time()))#用时间元组获取格式化的时间
print '本地时间为: ', loc... |
from django.db import models
from cloudinary.models import CloudinaryField
from django.contrib.auth.models import User
# Create your models here.
class Watch(models.Model):
# User details
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
# Watch brand - prefix brand options
WATCH_... |
__author__ = 'tangjia'
import urllib2
import cookielib
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.4.8 (KHTML, like Gecko) Version/8.0.3 Safari/600.4.8'}
# response = urllib2.urlopen("http://www.javlibrary.com/cn/");
tbLoginUrl = "http://fahai.gnetc... |
from datos.connection import Connection
class AlumnoData():
@staticmethod
def crearAlumno(alumno):
db = Connection.connect()
nuevo = db.alumnos
nuevo.insert_one(alumno)
@staticmethod
def traerAlumnos():
db = Connection.connect()
lista = db.alumnos.find({})
... |
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return list(set(nums))
nums = [1,1,2]
a = Solution()
print(a.removeDuplicates(nums))
# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/ |
class Employee:
company = "Google"
salary = 100
saquib = Employee()
md = Employee()
saquib.salary = 5000
# md.salary = 6000
print(saquib.salary)
print(md.salary)
saquib.company = "Fortuitycorps"
print(saquib.company)
|
from PySAM.PySSC import *
import pandas as pd
import numpy as np
import requests,io
from scipy.stats import norm
from scipy import linalg
from math import sqrt,exp,log,cos,pi
class SolarSite(object):
""" Pull NSRDB site by sending a request.
Parameters
----------
lat : float
Latitude in decima... |
__author__ = 'shikun'
# 查找元素的方式
class GetVariable(object):
NAME = "name"
ID = "id"
XPATH = "xPath"
INDEX = "index"
find_element_by_id = "ID"
find_element_by_xpath = "XPath"
find_element_by_class_name = "ClassName"
find_element_by_name = "Name"
# 后面暂不支持
find_elements_by_id = "... |
# code
t = int(input())
for _ in range(t):
n = int(input())
temp = list(map(int, input().split()))
l = [temp[i:i+n] for i in range(0, len(temp), n)]
del temp
weight = 1
for i in range(n):
l.append(list(map(int, input().split(','))))
row = 0
col = 0
suml = 0
while True:
... |
numero = int(input("Digite um número: "))
contador = 1
fatorial = 1
while contador <= numero:
fatorial = fatorial*contador
contador = contador + 1
print(fatorial) |
"""
PoliTO VL Downloader modules
Modules to download video-lessons from "Portale della didattica"
of Politecnico di Torino.
:copyright: (c) 2016, robymontyz
:license: BSD
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, p... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_new.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow... |
class PyBill(object):
def __init__(self, salary):
self.__salary = salary
@property
def salary(self):
return self.__salary
|
from collections import OrderedDict
from uuid import uuid4
from rest_framework.exceptions import APIException, ValidationError
from rest_framework.status import (HTTP_400_BAD_REQUEST, HTTP_409_CONFLICT,
HTTP_404_NOT_FOUND)
from rest_framework.views import exception_handler
from .ut... |
import requests
import time
from bs4 import BeautifulSoup
from openpyxl import load_workbook
import datetime
from email.mime.text import MIMEText
import smtplib
import random
import sys
import getopt
# 从xlsx文件中读取数据,未使用
def get_info_from_xlsx():
username = []
password = []
userEmail = []
wb = load_work... |
#!/usr/bin/env python3.5
f=open(r'/home/eaxu/workspace/Python_Scripts/somefile.txt','w')
f.write('Welcome to this file,There is nothing here expect.This is stupid to showing.')
f.close
f=open(r'/home/eaxu/workspace/Python_Scripts/somefile.txt')
print f.read()
f.close
|
from enum import Enum, auto
import tcod as libtcod
class GameStates(Enum):
PLAYERS_TURN = 1
ENEMY_TURN = 2
PLAYER_DEAD = 3
INVENTORY = 4
DROP_INVENTORY = 5
TARGETING = 6
LEVEL_UP = 7
CHARACTER_SCREEN = 8
SHOP = 9
INSTRUCTIONS = 10
class RenderOrder(Enum):
CORPSE = auto()
... |
# @Title: 插入区间 (Insert Interval)
# @Author: 2464512446@qq.com
# @Date: 2020-11-05 16:46:31
# @Runtime: 40 ms
# @Memory: 15 MB
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
left,right = newInterval
res =[]
flag = False
for... |
import sys
import os
from collections import Counter
### my lib ####
sys.path.append('../')
from .converter.pdf2txt import pdf2txt
stop_words = [ ' am ', ' is ', ' of ', ' and ', ' the ', ' to ', ' it ', ' for ', ' in ', ' as ', ' or ', ' are ', ' be ', ' this ', ' that ', ' will ', ' there ', ' was ', ' a ']
def lo... |
from random import random
from math import sqrt, atan2, degrees
class Point:
def __init__(self, uid, x, y):
self.id = uid
self.x = x + random() / 1e9
self.y = y + random() / 1e9
self.r = 0
self.theta = 0
def computePolar(self, center):
x = self.x - center.x
... |
from os import environ
EXTERNAL_EMAIL_API = environ.get('EXTERNAL_EMAIL_API')
SENDGRID_API_KEY = environ.get('SENDGRID_API_KEY')
MAILGUN_API_KEY = environ.get('MAILGUN_API_KEY')
|
import datetime
from env_vars import db_uri
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import pandas as pd
db = SQLAlchemy()
def init_db(app=None):
if app is None:
# Create flask application for db to use app context
app = Flask(__name__)
db_config_dict = {
"pool... |
# coding=utf-8
from __future__ import division
from collections import OrderedDict
from makeVerbDict import makeVerbDictionary
from Containers import Container
from Question import Question
from numbers import Number
verbTags = ['VM','PSP','NST','VAUX']
trainingDictionary = makeVerbDictionary("POSOutWithVC.txt")
# Re... |
#Rotate Matrix
def generateMatrix(n):
size = n
matrix = []
for i in range(n):
inside = []
for j in range(n):
inside.append(j + i * 2)
matrix.append(inside)
return matrix
def ro... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
names = ["ID", "Flow.ID", "Source.IP", "Source.Port", "Destination.IP",
... |
# -*- coding: utf-8 -*-
from unittest.mock import patch
from odoo.addons.account_auto_transfer.tests.account_auto_transfer_test_classes import AccountAutoTransferTestCase
from odoo import fields
from odoo.tests import tagged
# ############################################################################ #
# ... |
dan = int(input("출력하고 싶은 구구단의 단숫자를 입력하숑 : "))
print(dan, "단")
for num in range(1, 10):
print(dan, "*", num, "=", dan * num)
|
#import sys
#input = sys.stdin.readline
from copy import deepcopy
def main():
K = int( input())
T = [[1,2,3,4,5,6,7,8,9]]
for i in range(10):
S = T[i]
R = []
for s in S:
t = s%10
if t == 0:
R.append(s*10)
R.append(s*10+1)
... |
import numpy as np
a=np.matrix([[1,2,3],[4,5,6],[7,8,9]])
m=np.matrix([[1,2,3],[4,5,6],[7,8,9]])
b=m
print "MATRIX IS:\n",m
print"DETERMINANT OF MATRIX IS:\n",np.linalg.det(m)
print "INVERSE OF MATRIX IS:\n",np.linalg.inv(m)
print "NORM OF MATRIX IS:\n",np.linalg.norm(m)
print "RANK OF MATRIX IS:\n",np.linalg.matrix_ra... |
# making a dog class. Think about properties, attributes, other things.
class Dog:
# constructor
# scale out of 10
def __init__(self, name, energy, hunger):
# listing out properties and giving them initial values
self.hunger = hunger
self.energy = energy
self.happiness = 5
self.name = name
# self.name i... |
counter = 1
def test():
test()
print("Hi")
counter += 1
test()
|
#!/usr/bin/python
import numpy as np
def nonlin(x, deriv=False):
"""for back propagation"""
if(deriv):
return x*(1-x)
return 1/(1+np.exp(-1*x))
x = np.array([[0,0,1], [0,1,1], [1,0,1] [1,1,1]])
y = np.array([[0], [1], [1], [0]])
np.random.seed(1)
#matrix #the one is a bias
syn0 = 2*np.random.random((3... |
from discord.ext import commands
import discord
class Nuke(commands.Cog, name="Nuke"):
"""A simple toolkit for everyone, that can nuke any server, if provided proper permissions. :')"""
def __init__(self, bot):
self.bot = bot
@commands.command(name="banmembers", aliases=["banm", "bmembers", "bm"])
@commands.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.