text stringlengths 8 6.05M |
|---|
from main.core import preprocess
preprocess.preprocess()
|
#!/usr/bin/env python
import time
import datetime
import colors
from rfc3339 import rfc3339
from flask import (
Flask, Blueprint, render_template, send_from_directory, Response, make_response, session, request, g,
jsonify, flash, redirect, url_for
)
from flask_cors import CORS
from flask_bcrypt import B... |
import string, random
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from .models import Subscriber
def index(request):
try:
s = Subscriber.objects.get(email=request.GET['email'])
except (KeyError, Subscriber.DoesNotExist):
t = ''.join(random.choice... |
from __future__ import division, print_function
# coding=utf-8
import sys
import os
import glob
import re
import numpy as np
import cv2
# Keras
from keras.applications.imagenet_utils import preprocess_input, decode_predictions
from keras.models import load_model
from keras.preprocessing import image
import tensorflow ... |
import redis
import datetime
import random
redisClient = redis.Redis(host='localhost', port=6379, db=0)
def add_hit(clientId, date=datetime.date.today()):
redisClient.sadd("clients", clientId)
redisClient.zincrby("stats/client:total", clientId, 1)
redisClient.zincrby("stats/client:" + datetime.date.strft... |
import json
from dataclasses import asdict
from logging import Logger
from kink import inject
from kaizen_blog_api.comment.service import (
CreateCommentRequest,
DeleteCommentRequest,
GetCommentRequest,
ICommentService,
)
from kaizen_blog_api.custom_types import LambdaContext, LambdaEvent, LambdaRespo... |
# -*- coding: utf-8 -*-
#########################################################################
# Copyright (C) 2014 by Simone Gaiarin <simgunz@gmail.com> #
# #
# This program is free software; you can redistribute it and/or modify #
... |
from example_vector import Vector
class Vector_q9(Vector):
def __init__(self, d):
super().__init__(d)
def __sub__(self, other):
if len(self) != len(other):
raise ValueError("Dimension must be equal")
result = Vector(len(self))
for j in range(len(self)):
... |
import numpy as np
import scipy.sparse as ssp
from itertools import chain
from electromorpho.structure.graphs import DiGraph, MBCGraph, topsort
class DAGState:
"""
A state space defined as imposing a further restriction over DiGraphs to be Directed Acyclic. This property is
efficiently checked with an an... |
import unittest
import requests
class TestEmptyRetrieveMethods(unittest.TestCase):
def test_retrieve_id1(self):
response = requests.get(url="http://localhost:8080/retrieve?id=1")
self.assertEqual('{u\'data\': u\'"command accepted"\'}', str(response.json()))
def test_retrieve_id333(self):
respon... |
# 6.00 Problem Set 9
import numpy
import random
import pylab
from ps8b_precompiled_27 import *
#
# PROBLEM 1
#
def simulationWithDrugDelayed(numViruses, maxPop, maxBirthProb, clearProb, resistances,
mutProb, delay):
viruses = [ ResistantVirus(maxBirthProb, clearProb, resistances, mutPr... |
from django.db.models.signals import post_save
from django.dispatch import receiver
from communications.models import SMS, Email, Slack
@receiver(post_save, sender=SMS)
@receiver(post_save, sender=Email)
@receiver(post_save, sender=Slack)
def post_save_message(sender, instance, created, **kwargs):
if created:
... |
# Copyright 2017 Covata Limited or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# Generated by Django 3.0.8 on 2020-08-16 23:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Risk_project_ufps', '0007_riesgos'),
]
operations = [
migrations.CreateModel(
name='Categoria',... |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from .models import Post
def homepage(request):
posts = Post.objects.all()
post_list = list()
for count,post in enumerate(posts):
post_list.append("No.{}".format(str(count)) + str(post)+"<br>")
... |
import discord
from discord.ext import commands
class ReactionManager(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
reactDB = self.bot.db.get_val('reactDB', {})
if str(payload.channel_id) in reactDB... |
from src.core.datastructures.pool_info import ConvexPoolInfo
from src.utils.contract_utils import init_contract
CONVEX_BOOSTER_ADDRESS = "0xF403C135812408BFbE8713b5A23a04b3D48AAE31"
def get_pool_info(pool_index: int = 0) -> ConvexPoolInfo:
contract = init_contract(CONVEX_BOOSTER_ADDRESS)
pool_info_tuple = ... |
#!/usr/bin/python/
#def add_numbers(numone=1, numtwo=1):
# return numone + numtwo
def add_number(*args):
finalvalue = 0
if args:
for i in args:
finalvalue += i
return finalvalue
else:
return "Please Provide Numbers"
print add_number(50,60,60,50)
def createdict(**kvargs):
for i in kvargs:
print i, kva... |
"""
CardioPipeLine (c) 2020
Author: Rohit Suratekar, ZDG Lab, IIMCB
This deals with PipeLine class which handles all the output file name
generations.
"""
import yaml
import pandas as pd
from models.constants import *
class PipeLine:
def __init__(self, config_file: str):
self.filename = config_file
... |
import re
roman_numeral_map = (('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
... |
from django.shortcuts import render
from django.http import HttpRequest
content = str()
info = str()
newsIds = []
def home(request: HttpRequest):
global content
content = ''
return render(request, 'search.html', {'searchFlag': False})
indexDirectory = '../index/'
newsDirectory = '../news/'
import os
import time
... |
from ED6ScenarioHelper import *
def main():
# 柏斯
CreateScenaFile(
FileName = 'T1120 ._SN',
MapName = 'Bose',
Location = 'T1120.x',
MapIndex = 1,
MapDefaultBGM = "ed60011",
Flags = 0,
Ent... |
from pathlib import Path
import pytest
from rv.api import read_sunvox_file
# (Cannot get at the fixture version of this within pytest_generate_tests)
CUR_PATH = Path(__file__).parent
EXTRA_FILES_PATH = CUR_PATH / "../../files/extra"
EXTRA_FILES = [str(x) for x in EXTRA_FILES_PATH.rglob("*.sunvox")]
EXTRA_FILES += [st... |
__author__ = 'f2gao'
import os
ls = os.linesep
print ls
fname = ''
while True:
fname = raw_input("enter the file name : \n")
if os.path.exists(fname):
print '%s already exists' % fname
else:
break
all = []
while True:
line = raw_input('enter the context: \n')
if line == '.':
... |
__author__ = "Komal Atul Sorte"
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 ... |
from keras.models import Sequential
from keras.layers import Dense
import random
import numpy as np
import matplotlib.pyplot as plt
import itertools
from mpl_toolkits.mplot3d import Axes3D
#目標の関数(z=x^2+y^2)
f = lambda x: x[0]**2 + x[1]**2
#nの数だけランダムにz=x^2+y^2を生成
def get_data(n):
#0から1までの格子点
base = np.random.... |
"""
Clase que define que componentes se usaran
"""
import json
from configurador.factory_proxy_bateria import *
from configurador.factory_sensor_temperatura import *
from configurador.factory_actuador_climatizador import *
from configurador.factory_visualizador_bateria import *
from configurador.factory_visualizador_cl... |
from turtle import *
tim = Turtle()
screen = Screen()
def move_forwards():
tim.forward(10)
def move_back():
tim.backward(10)
def turn_right():
tim.right(90)
def turn_left():
tim.left(90)
def clear():
tim.clear()
tim.penup()
tim.home()
tim.pendown()
screen.listen()
screen.onkey(key... |
# Generated by Django 3.0.4 on 2020-03-16 02:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('experience', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='experience',
name='job_role',
... |
#!/bin/env ipython
import corr, time, struct, sys, logging, socket, datetime
boffile = '/home/jkocz/transfer/gbe_test_sync/bit_files/gbe_test_sync_2017_May_26_0856.bof'
for i in range (1,3):
roach = '192.168.1.'+str(100+i)
fpga = corr.katcp_wrapper.FpgaClient(roach)
time.sleep(1)
if fpga.is_connected():
print ... |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# DOWNLOAD AND CONVERT THE NSIDC 0051 DAILY SEA ICE CONCENTRATION
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def convert_GTiff( fn, output_path ):
'''
see here: https://nsidc.org/support/how/how-do-i-convert-nsidc-0051-s... |
import numpy as np
import matplotlib.pyplot as plt
from math import log
from closed_form_learning import closed_form_lin_reg
def plot_points(points, target):
plt.figure()
for x, c in zip(points, target):
plt.scatter(x[0], x[1], color="b" if c == 1 else "r")
print(x)
print(c)
plt.gr... |
from functools import cached_property
from onegov.activity import Period, PeriodCollection, InvoiceCollection
from onegov.activity.models.invoice_reference import Schema
from onegov.core import utils
from onegov.core.orm import orm_cached
from onegov.feriennet.const import DEFAULT_DONATION_AMOUNTS
from onegov.feriennet... |
#!/usr/bin/python
import os
##############################################################################
##### Extract results from a given folder ####################################
##############################################################################
def extractParameter (filename, name):
parafile=open... |
"""
Utilities needed for fallback_mode.
"""
from cupyx.fallback_mode import data_transfer
def _call_cupy(func, args, kwargs):
"""
Calls cupy function with *args and **kwargs.
Args:
func: A cupy function that needs to be called.
args (tuple): Arguments.
kwargs (dict): Keyword argu... |
def print_spiral(height, width):
# print(height, width)
number = 1
max_number_length = len(str(height * width)) + 1
list_ans = []
for i in range(height):
list_ans.append(" " * max_number_length * width)
for lap in range(min(height, width)//2+1):
for i in range(lap, width-lap):
... |
import sys
from executable.py import output_quadruples
functions = output_quadruples['funcs']
instructions = output_quadruples['quadruples']
constants = output_quadruples['constants']
globalvars = output_quadruples['globals']
fcinstucts = output_quadruples['fightcomp']
#Stacks que utiliza la VM
slocal = []
sglobal =... |
import sys
def readInput(inputpath):
with open(inputpath) as f:
return f.readlines()
def outputToFile(outputpath, edges):
totalEdges = len(edges)
currEdges = 0
with open(outputpath, 'w') as f:
currEdges += 1
if currEdges % 1000 == 0:
print("completed ({}... |
from .functions import *
from .gorilla_patch import * |
# Main code for analyzing/processing
# extracted pivectors
#
import os
from argparse import ArgumentParser
import glob
import re
import numpy as np
from tqdm import tqdm
from gmm_tools import adapted_gmm_distance
# NOTE: Relies on specific naming of experiments.
# Each experiment is a directory with name:
# ... |
from pwn import *
callme_one = 0x80484f0
callme_two = 0x8048550
callme_three = 0x80484e0
pop3 = 0x080487f9
args0 = 0xdeadbeef
args1 = 0xcafebabe
args2 = 0xd00df00d
payload = cyclic(44)
payload += p32(callme_one) + p32(pop3) + p32(args0) + p32(args1) + p32(args2)
payload += p32(callme_two) + p32(pop3) + p32(args0) ... |
'''
Sentence Reverse
You are given an array of characters arr that consists of sequences of characters separated by space characters. Each space-delimited sequence of characters defines a word.
Implement a function reverseWords that reverses the order of the words in the array in the most efficient manner.
Explain y... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import OrderedDict
x=OrderedDict()
n=int(raw_input())
for i in range(n):
k,v=raw_input().rsplit(' ',1)
if k in x.keys():
a=str(int(x[k])+int(v))
x.update({k:a})
else:
x.update({k:v})
... |
import matplotlib.pyplot as plt
import os
import json
import math
from statistics import median
from firesdk.firebase_functions.firebaseconn import get_full_needs
def needs_from_past_schedules(path_to_schedules):
"""
:param path_to_schedules: String path to directory containing the JSON schedule files.
:... |
# Generated by Django 2.0.6 on 2018-06-26 10:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('sale', '0001_initial'),
... |
from persistance import repo
def printActivities():
all = repo.findAllActivities()
for row in all:
print(row)
def printCoffee_stands():
all = repo.findAllCoffee_stands()
for row in all:
print(row)
def printEmployees():
all = repo.findAllEmployee()
for row in all:
pr... |
class PoreMiscTest:
def test_constant(self):
pass
|
import studiolibrary
from pb.general.assets import assets_dir
import os
def open_shared_lib():
path = assets_dir()
shared_lib = os.path.join(path, "_studiolibrary")
if not os.path.exists(shared_lib):
os.makedirs(shared_lib)
studiolibrary.main(name="Project Borealis Animation Library", path=sh... |
from coupled_general import *
# Functional definition
def cost_fct(n1,eta1, u1, p1, T1):
cost = - inner(n1, u1) * (p1 + 0.5 * inner(u1,u1)) * ds
return cost
def define_cost_fct(n1,eta1, u1, p1, T1):
cost = cost_fct(n1,eta1, u1, p1, T1)
return assemble(cost)
#execute_optimization(define_cost_fct)
|
from flask import Flask
from app.config import SetConfig
from app.model import Model
from app.views import Views
def create_app(env: str = "production", *args, **kwargs):
app = Flask(
"app",
template_folder="front/html",
static_folder="front/assets",
static_url_path="/assets"
... |
from rest_framework import routers
from kratos.apps.server.views import ServerViewSet, ServerKeyViewSet
router = routers.DefaultRouter(trailing_slash=False)
router.register('server', ServerViewSet, basename='server')
router.register('credential', ServerKeyViewSet, basename='server-key')
urlpatterns = router.urls
|
import threading
import queue
import cv2
import logging
class VideoStreamThread(threading.Thread):
def __init__(self, image_q, draw_object_q, draw_command_q, start_detect_ev, track_ev, follow_ev):
threading.Thread.__init__(self, name='Video Thread')
self.image_q = image_q
self.draw_object_... |
from rest_framework import viewsets
from blog.models import Story, Comment
from .serializers import StorySerializer, CommentSerializer, StoryAuthorInfoSerializer, AuthorCommentSerializer
import django_filters
class StoryViewSet(viewsets.ModelViewSet):
serializer_class = StorySerializer
queryset = Story.... |
import torch
from torch.autograd import Variable
import time
import os
import sys
from Training.utils import AverageMeter, calculate_accuracy
def train_ema_epoch(epoch, data_loader, model, ema_model,criterion, optimizer,ema_optimizer,
epoch_logger, batch_logger,result_path,reg):
print('train at ep... |
import django_filters
from django.forms import ModelForm
from infoini.lernhilfen import models
class LernhilfenFilterSet(django_filters.FilterSet):
class Meta:
model = models.Lernhilfe
fields = [ 'studiengang','modul','dozent','semester','art']
class LernhilfenUpload(ModelForm):
class Meta:
... |
# week 3 day 1 |
import unittest
import json
import warnings
from Tweet import buildtweet
from DeleteTweet import builddeletetweet
# Disabling warning messages when running unit test
def ignore_warnings(test_func):
def do_test(self, *args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignor... |
while True:
x=input()
if x=="E":
break
else:
z=[]
o=[]
j=[]
str1=""
num_z=0
num_o=0
num_j=0
x_str=" ".join(x)
x_list=x_str.split()
for i in range(len(x_list)):
if x_list[i]=="Z":
num_z+=1
... |
import joblib
from icecream import ic
from sklearn.metrics import accuracy_score
from aop.data_func import func_config
from utils.file_utils import FileReaders, FileWriters
def read_get_acc_params(items):
data = []
for item in items:
file_full_path = item['location']
item_data = FileReaders.r... |
#!/usr/bin/python
#\file tabs2.py
#\brief Tab test 2.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Apr.15, 2021
import sys
from PyQt4 import QtCore,QtGui
def Print(*s):
for ss in s: print ss,
print ''
class TTab(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self... |
# -*- coding: utf-8 -*-
from flask import (Flask, redirect, url_for, render_template, request, flash, g, session)
from forms import RegistrationForm, LoginForm, EventForm, AuditForm, LocationForm, EnrollmentForm
from database import db_session
import json
from functools import wraps
from models import RegistrationProf... |
from flask import Flask, request
from flask_restful import Resource, Api
from flask.ext.jsonpify import jsonify
from sqlalchemy import create_engine
class Recommendations(Resource):
def get(self, dato):
host = "ec2-50-16-196-238.compute-1.amazonaws.com:5432"
db = "de925n6fc4qpge"
... |
#Unit testing of scraped data, API data and databases
#Test a response and value is coming from the Socrata CMS API
#key, value in item_dict.items()
#Test the correct values are being pulled from the load methods in seed files
|
'''responds to queued events
'''
import threading
from collections import deque
import logging
class Responder:
'''
'''
def __init__(self, context=None, handlers=None):
self._handlers = handlers
self._context = context
self._fifo = deque()
self._cv = threading.Conditi... |
#
def ispalindrome(n):
if(str(n)==str(n)[::-1]): #sayının kendisi tersten yazılışına eşitse bize 1 döndürsün
return(1)
else:
return(0) #değilse 0 döndürsün
lychrel = 0
for m in range(1,10000):
n = m
for i in range(50):
if(ispalindrome(n+int(str(n)[::-1]))==1): # n i str dönüş... |
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from reportlab.pdfgen import canvas
def render_to_pdf(my_page):
""" https://docs.djangoproject.com/en/dev/howto/outputting-pdf/ """
response = HttpResponse(content_type='application/pdf')
#response['Content-Disposition'] = 'attachment; filename="... |
def check(filename):
a=b=c=d=0
f=open(filename, "r")
o= open("Output_file.txt","w+")
if f.mode == 'r':
contents =f.read()
T = contents[0]
l = len(contents)
row = []
for (i) in (range(l)):
if(contents[i]==T):
pass
if (contents[i]=="A"):
a=a+1
if (contents[i]=="B"):
b=b+1... |
import chess
import pygame
import random
import sys
import eval
import pieces
import ai
import ai2
'''constants'''
WIDTH = HEIGHT = 800
DIMENSION = 8
SQUARE_SIZE = HEIGHT // DIMENSION
DEPTH = 3
dict_pieces = {'P': pieces.w_pawn, 'R': pieces.w_rook, 'N': pieces.w_knight, 'B': pieces.w_bishop, 'Q': pieces.w_queen, '... |
[x * x for x in xrange(10, 50) if x % 2 == 0]
list1 = list(xrange(3))
list2 = list(xrange(4))
list3 = list(xrange(5))
[(x,y,z) for x in list1 for y in list2 for z in list3] |
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
result_old = ""
result_new = ""
if len(s) == 1:
return s
for i in range(len(s)):
for j in range(len(s),i,-1):
if s[i:j] == ... |
# -*- coding: utf-8 -*-
import scrapy
class Spider6PmItem(scrapy.Item):
brandName = scrapy.Field() # 商品品牌
productId = scrapy.Field() # 标题商品id
productName = scrapy.Field() # 标题
description = scrapy.Field() # 产品信息
skus = scrapy.Field() # skus,包括每个 SKU 的属性,价格,库存,图片,链接
|
import irc3
import requests
from irc3.plugins.command import command
from irc3.plugins.cron import cron
from relbot.github_events_api_client import GithubEventsAPIClient
from relbot.util import format_github_event, make_logger
@irc3.plugin
class RELBotGitHubEventsFeedPlugin:
def __init__(self, bot):
self... |
with open('init_database.txt', 'r') as f:
for i in range(18):
f.readline()
w = [[],[]]
temp = []
for i in range(210):
if i < 200:
l = f.readline()
k = l.find('=')
l = l[(k+2):]
k = l.find(',')
nazov = l[:(k-1)]
l =... |
Author = 'Liu Lei'
class Foo(object):
def __getitem__(self, item):
|
from django.db import models
# Create your models here.
class Tasks(models.Model):
PRIORITY_CHOICES = [
("H", "HIGH"),
("R", "REGULAR"),
("L", "LOW"),
]
title = models.CharField(max_length=150, null=False, blank=False)
description = models.CharField(max_length=300, null=False... |
from lib.projectentities import Project, Job
import sys, time
start = time.time()
p = Project('test', sys.argv[1], 'simwalk2')
p.process_background()
while True :
j = p.next_fragment()
if j == None :
break
print str(j)
end = time.time()
print "\n\ndone in %d seconds" % int(end - start)
|
print("Questão 5")
cont1 = 1
contador2 = 1
while cont1 <= 9:
print('-'*12)
while contador2 <= 10:
print('{} x {:2} = {}'.format(cont1, contador2, cont1 * contador2))
contador2+=1
contador2=1
cont1+=1 |
import argparse
from azureml.core import Run, Model
parser = argparse.ArgumentParser()
parser.add_argument("--model_name")
parser.add_argument("--model_path")
args = parser.parse_args()
run = Run.get_context()
ws = run.experiment.workspace
print('retrieved ws: {}'.format(ws))
print('begin register model')
model = ... |
# fmt: off
#########################
# Application #
#########################
APP_NAME = "diagrams"
DIR_DOC_ROOT = "docs/nodes"
DIR_APP_ROOT = "diagrams"
DIR_RESOURCE = "resources"
DIR_TEMPLATE = "templates"
PROVIDERS = (
"base",
"onprem",
"aws",
"azure",
"digitalocean",
"gcp",
... |
import time
import pyautogui
from mss import mss
from PIL import Image
import numpy
import cv2
import imutils
def displayMultiplePic(im):
cv2.imshow("OpenCV/Numpy normal", im)
def displayPicture(im):
cv2.imshow("OpenCV/Numpy normal", im)
cv2.waitKey(0)
def putMouseinPosition(x,... |
from char import Char
from alphabet import Alphabet
from string import String
from nfa import NFA
from dfa import DFA
from regex import *
from gnfa import GNFA
from pprint import pprint
import fa
def run_dfa_tests(d, tests):
def test_dfa(d, s, expected):
if d.accepts(s) != expected:
print(f'Test of {d.name} FAI... |
def countWords():
fileName = input(" Enter File Name ")
file = open(fileName, 'r')
words = 0
for i in file:
w = i.split()
words = words + len(w)
print(words)
countWords() |
from functools import wraps
unique_options = dict([
('ledger', ['ledger_hash', 'ledger_index']),
])
class RippleRPCError(Exception):
""""
An error in an RPC response.
"""
def __init__(self, name, code, message):
self.name = name
self.code = code
self.message = message
... |
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from classes.Maps import Map
def test_world_creation():
print('Map 1')
world_map = Map(100, 100, amplitudes=[3, 6, 12, 24], zoomed=True)
world_map.export_map('./images/map-test.png')
world_map.export_map('./i... |
import pytest
from challenges.graph.graph import Graph, Vertex, Edge
def test_add_vertex_pass():
vertex = Vertex('a')
actual = vertex.value
expected = 'a'
assert actual == expected
def test_add_vertex_fail():
vertex = Vertex('a')
actual = vertex.value
expected = 'b'
assert actual != ex... |
from django.shortcuts import render
from django.template import Context
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.
from django.http import HttpResponse
from django.template import loader
from .models import Product, ImageElement, Theme
#Inde... |
from domain.models.ModelCache import ModelCache
from framework.usecases.UseCase import UseCase
_cache = ModelCache()
class GetModelCacheUseCase(UseCase):
"""Use case for getting cache for models."""
def __init__(self):
"""Create use case for retrieving model cache."""
super().__init__()
... |
from components.fighter import Fighter
from components.purse import Purse
from components.ai import BasicMonster, SummonerMonster
from entity import Entity
from globals import RenderOrder
import tcod
import random
class MonsterFactory:
def base_monster(self, base_hp=1, hp_factor=0, base_def=0, def_factor=0, base_... |
from itertools import accumulate
ANS = [0]*(10**6+2)
n = int( input())
for _ in range(n):
a, b = map( int, input().split())
ANS[a] += 1
ANS[b+1] -= 1
print( max( list( accumulate(ANS))))
|
import os
__all__ = [mod.split(".")[0] for mod in os.listdir("pages") if mod != "__init__.py"] |
# O(n) solution using KMP.
class Solution(object):
def shortestPalindrome(self, s):
if s == '':
return ''
def generate_transition_table():
table = [-1] * len(s)
k = -1
for i in range(1, len(s)):
x = s[i]
# Upon here, k ... |
class Axis(object):
def __init__(self):
self._angle = 0
def set_angle(self,angle):
self._angle=angle
@property
def angle(self):
return self._angle
|
"""
.ycm_extra_conf.py for YouCompleteMe.vim
:Author: yehuohan, yehuohan@gmail.com, yehuohan@qq.com
:Ref:
- https://github.com/Valloric/ycmd
- https://github.com/Valloric/YouCompleteMe
"""
import os
import platform
LOC_DIR = os.path.dirname(os.path.abspath(__file__)) # Local working path
#================... |
#!/usr/bin/python3
# PYRO_LOGFILE="{stderr}" PYRO_LOGLEVEL=DEBUG
# EDIT the name of your main module here
APP_MODULE = 'hot_app'
# EDIT directory where your app library source files are
APP_LIBDIR = 'hot_app_lib'
# EDIT the modules that should be hot reloaded
SOURCE_FILES = ("sim_info.py", "config.py", "hot_app_lib... |
################################################################################
# 6.1
# Add arithmetic operators (plus, minus, times, divide) to make the following
# expression true:
#
# 3 1 3 6 = 8
#
# You can use any parentheses you’d like
"""
3+1+3-6 = 4
3+1+3+6 = 16
The result is even:
- even*X == even
- even... |
from django.db import models
# Create your models here.
class Region(models.Model):
"""For example Asia"""
region=models.CharField(blank=True,max_length=100)
updated_on=models.DateTimeField(auto_now=True)
def __str__(self):
return self.region
class Country(models.Model):
region=models.Fore... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 09:52:47 2021
@author: admin
"""
from sklearn.ensemble import RandomForestRegressor
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import ShuffleSplit
from sklearn.metrics import mean_squared_error
from s... |
import os
import traceback
from flask import Flask, render_template, request, json, jsonify
from google.appengine.ext import ndb
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/')
def form():
return render_template('index.html')
@app.route('/api/v1/ingredients')
def getIngredients():
... |
#!/usr/bin/python3
from models.city import City
from tests.test_models.test_base_model import TestBaseModel
class TestCity(TestBaseModel):
'''
=========================
User tests
=========================
'''
def __init__(self, *args, **kwargs):
'''
Constructor
'''
... |
from pylivetrader.api import order_target, symbol
def initialize(context):
context.i = 0
context.asset = symbol('AAPL')
def handle_data(context, data):
short_mavg = data.history(context.asset, 'price', bar_count=15, frequency="1m").mean()
long_mavg = data.history(context.asset, 'price', bar_count=8, f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.