text stringlengths 8 6.05M |
|---|
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#################################################################################
# #
# extract_data.py: extract data needed for sci. run interruption plots #
# ... |
#!/usr/bin/python
# Copyright 2010 Alon Zakai ('kripken'). All rights reserved.
# This file is part of Syntensity/the Intensity Engine, an open source project. See COPYING.txt for licensing.
'''
Usage: mapmodels.py [raw-entities-file] [map.cfg]
raw-entities-file is the output when you load a map with
entities, it is... |
from Testing.Core import Core
if __name__ == '__main__':
Core = Core()
Core.main_loop()
|
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django_registration.forms import RegistrationForm
from users.models import Profile
class NewRegistrationForm(RegistrationForm):
class Meta(UserCreationForm.Meta):
fields = ... |
#!/usr/bin/python3.4
# -*-coding:Utf-8
ma_list = list()
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from flask import Blueprint
from flask import request, session, flash, redirect, render_template, url_for, current_app
from sqlalchemy import or_
from sqlalchemy.orm import joinedload
from lib import db, login_manager, ui
from lib.flask_login import login_user, logout_user... |
from flask import Blueprint
admin_news = Blueprint("admin/news",__name__)
import app.admin.admin_news.views |
import re
def valiate_phone_number(number):
if re.match(r'^01[016789][1-9]\d{6,7}$', number):
return True
return False
print(valiate_phone_number('01012312343')) # True
print(valiate_phone_number('0101231123')) # True
print(valiate_phone_number('010123112')) # False
print(valiate_phone_number('01012... |
for i in range(1,10):
for j in range(1,i+1):
print(j,'x',i,'=',i*j,end=' ')
if i==j:
print(' ')#这里是为了输出换行的
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
# @File:search_engine.py
# @Author: Michael.liu
# @Date:2020/4/20 19:12
# @Desc: This code is SearchEngine
import math
import operator
import sqlite3
import configparser
from datetime import *
import os
from chapter2.SegmentExample import pyHanlpSeg
class SearchEngine:
... |
import pygame
import random
pygame.init()
BLACK = [0, 0, 0]
WHITE = [255, 255, 255]
# устанавливает ширину и высоту окна
SIZE = width, height = [300, 700]
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("Тип Дождь")
speed = 10
# Плотность
val = 100
# Создает пустой список
rain_list = []
# Частот... |
from django.db import models
class counter(models.Model):
name=models.CharField(max_length=12)
counter=models.IntegerField()
|
import torch
from torch.utils.data import Dataset
from torchvision.transforms.functional import to_tensor, to_pil_image
import random
import string
import os
import glob
from PIL import Image
characters = ' ' + string.digits
n_classes = len(characters)
n_input_length, n_len = 12, 3
img_dir = 'data/num'
txt_path = 'de... |
# 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 applicable law or agreed to in writing, software
# d... |
#!/usr/bin/env python
import cgi, cgitb
from roundwared import server
import json
print "Content-type: text/plain"
print
# The following like is what should be here. However the OceanVoices client
# is still expecting a different protocol and thus the hack at the end of this
# file is in place to accomodate it.
#pri... |
from django.db import models
from django.conf import settings
# Create your models here.
class Post(models.Model):
author= models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTim... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxDepth(self, root):
if root == None: return 0
if root.left == None and root.right==None: return 1
elif root.left != None and root.right==N... |
#Python code to import function in other pgm to draw line using DDA algorithm
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
def ROUND(a):
return int(a+0.5)
def init():
glClearColor(1.0,1.0,1.0,0.0)
#glClolor3f(1.0,0.0,0.0)
glPointSize(3.0)
glMatrixMode(GL_PROJECTION)
gl... |
from manim import *
NUM_CARDS = 12
SLICE_ANGLE = TAU/NUM_CARDS
def make_sector(n):
return Sector(
start_angle=((n + (NUM_CARDS / 4)) % NUM_CARDS) * SLICE_ANGLE,
angle=SLICE_ANGLE,
outer_radius=1.5,
stroke_width=2,
stroke_color=BLUE,
fill_color=BLACK)
class Main(Scene):
def ... |
l = [2, "tres", True, [1,"dos",3]]
print "lista l =",l
l2 = l[1];
print "el segundo de la lista = ",l2
l3 = l[3][1]
print "lista de lista l[3][1] =",l3
l3 = l[3][1]=2
print "reaccion lista de lista l[3][1] =",l3
l4 = l[0:3]
print "un segmenteo de la lista l[0:3] =",l4
l5 = l[0:3:2]
print "un segmenteo de lista con int... |
#JTSK-350112
# mod_conversion.py
# Taiyr Begeyev
# t.begeyev@jacobs-university.de
def in2cm_table(start_length, end_length, step_size):
print("{0:>8} {1:>8}".format("inch", "cm"))
for i in range(start_length, end_length, step_size):
print("{0:>8.1f} {1:>8.1f}".format(i, i * 2.54)) |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 2 09:14:26 2015
@author: olaf
"""
import numpy as np
import matplotlib.pyplot as plt
import random
import time
from scipy import weave
def Startconf(anzTeilchen,anzSpinUp,anzZeitschritte):
weltlinien = np.array([[False]*anzTeilchen]*anzZeitschritte)
za... |
"""
Easy
https://leetcode.com/problems/valid-palindrome/
Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "... |
import tkinter as tk
from PIL import Image, ImageTk
import pygame
root = tk.Tk()
root.title("Tic Tac Toe")
#####################################
pygame.mixer.init()
pygame.mixer.music.load(r"C:\Users\Sam\Documents\Python\Tic Tac Toe\soundtrack_tictactoe.mp3")
pygame.mixer.music.play(loops=100)
########... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-01-29 00:33:53
# @Author : Your Name (you@example.org)
# @Link : http://example.org
# @Version : $Id$
import scrapy,pytesseract,json
from scrapy import FormRequest,Request
from PIL import Image
from io import BytesIO
from scrapy.log import logger
... |
from logging import warning
from api import gitlab
from utilities import types, validate
gitlab = gitlab.GitLab(types.Arguments().url)
def get_all(project_id, project_url):
merge_requests = []
details = gitlab.get_merge_requests(project_id)
if validate.api_result(details):
warning("[*] Found %s ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
import django
django.setup()
from some.models import DeviceData
import socket
def saveData(data):
data = data.split(', ')
d = DeviceData()
d.step = DeviceData.objects... |
'''
Created on Nov 19, 2010
@author: Jason Huang
'''
from google.appengine.ext import db
class Marker(db.Model):
'''
classdocs
'''
type = db.StringProperty( choices=('start', 'dest', 'waypoint', 'normal'),required=True)
latitude = db.FloatProperty(required=True)
longitude = db.F... |
from flask import Flask, render_template
from plot import make_plot
app = Flask(__name__)
@app.route("/")
def render_plot():
return render_template("plotly.html", plot_json=make_plot())
if __name__ == "__main__":
app.run(debug=True)
|
import copy
import os
import pickle
import warnings
import numpy as np
import scipy.stats as st
import pandas as pd
import xgboost as xgb
from ensemble.core import EnsembleBaseModel
from ensemble.modelCV import SVRCV, XGBRCV
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.linea... |
import math
import numpy as np
class DOF3:
def __init__(self, person, ax):
self.ax = ax
self.person = person
self.head_shift = 5
self.isHidden = True
self.prev_dot_head = None
if ax is not None:
self.center_line, = self.ax.plot(-1000, -1000, color='r', l... |
from bs4 import BeautifulSoup
import requests
import re
import pandas as pd
with open("all_speakers.htm", 'rb') as f:
lines = f.readlines()
soup = BeautifulSoup("".join(lines), 'html.parser')
out = []
for div in soup.find_all(class_='lumen-tile__title'):
out.append((div.text.strip(), div.a['href']))
df = pd.Da... |
import discord
class CustomClient(discord.Client):
async def on_ready(self):
print(f'{self.user} has connected to Discord!') |
from keras.optimizers import *
from dataset import Dataset
from metrics import iou_metric_all, iou_metric_fronts, iou_metric_hot, iou_metric_cold, \
iou_metric_stationary, iou_metric_occlusion, mixed_loss_gen
from deeplabv3plus import Deeplabv3
from utils import load_indexing, class_weights, trained_models
from ... |
# -*- coding: utf-8 -*-
import yaml
from django.http import HttpResponse
from django.views import View
class GetInventoryView(View):
def get(self, request, *args, **kwargs):
node_list = inventory(kwargs.get('master_id'))
result = {}
for node_name, node in node_list.items():
... |
#cloud-config
packages:
- python
- python-pip
- aws-cli
- unzip
- wget
write_files:
- path: /tmp/tempcloudwatch/config.json
content: |
{
"metrics": {
"append_dimensions":{
"InstanceId":"${aws:InstanceId}"
},
"aggregation_dimensions": [
["Inst... |
ID_COLS = ['CountryName',
'RegionName',
'Date']
#INDICES = ['ConfirmedCases']
INDICES = []
# Which IPs to choose?
MY_IPS = ['C1_School closing',
'C2_Workplace closing',
'C3_Cancel public events',
'C4_Restrictions on gatherings',
'C5_Close public transp... |
# -*- coding: utf-8 -*-
"""
Define classifier properties and operations
@author: peter
"""
#import time
class Weak_Classifier(object):
def __init__(self, haar, images, weights):
self.feature = haar
self.images = images
self.weights = weights
self.polarity, self.thr... |
#3 4 6
#5 1 2 3 4
def fun(arr,k):
n = len(arr)
for i in range(n):
maxUntilNow = arr[i]
if(i<n-k):
for j in range(i+1,i+k+1):
if(arr[j]>arr[i]):
maxUntilNow = arr[j]
if(maxUntilNow == arr[i]):
return arr[i]
else:... |
"""Training methods for rhasspyfuzzywuzzy"""
import logging
import typing
from collections import defaultdict
import networkx as nx
import rapidfuzz.utils as fuzz_utils
import rhasspynlu
from .const import ExamplesType
_LOGGER = logging.getLogger(__name__)
# ---------------------------------------------------------... |
class MovieRepository:
def alreadyNotified(self):
raise NotImplementedError("You're calling an abstract class!")
def add(self, movie):
raise NotImplementedError("You're calling an abstract class!")
class PrintMovieRepository(MovieRepository):
def alreadyNotified(self):
print "(asked for alreadyNot... |
# Generated by Django 3.2 on 2021-07-12 16:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('film', '0013_auto_20210712_1908'),
]
operations = [
migrations.AddField(
model_name='film',
name='actor',
... |
import re
import sys
from ete3 import Tree
def read_tree(tree):
lines = open(tree).readlines()
for line in lines:
if (not line.startswith(">")):
return Tree(line, format=1)
return None
def get_title(name):
split = name.split("_")
for i in range(0, len(split)):
split[i] = split[i].title()
ret... |
number = int(input())
last = []
def geacha(n):
if n == 1:
return 1
else:
return n + last[n-2]
i = 1
while True:
last.append(geacha(i))
if number <= last[-1]:
break
i += 1
if number > 1:
start = last[i-2]+1
if i % 2 == 0:
boonja = 1 + number - start
... |
import urllib2
import json
import numpy as np
def get_forecast():
f = urllib2.urlopen('http://api.wunderground.com/api/40c1e03239029f36/forecast/q/RI/Providence.json')
json_string = f.read()
parsed_json = json.loads(json_string)
windspeeds = []
for i in parsed_json['forecast']['simpleforecast']['forecastday']... |
# -*- coding: utf-8 -*-
import datetime
from django.test import TestCase
from django.contrib.auth.models import User
from todo.models import Chain, Task
from . import factories
class TaskTest(TestCase):
def setUp(self):
factories.make_fixtures()
# Сотрудники.
self.manager = User.objects.... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import textwrap
import pytest
from pants.backend.python import target_types_rules
from pants.backend.python.goals import tailor
from pants.backend.python.goals.tailor import (
Putativ... |
import unittest
import sys
import os
sys.path.append(os.path.join('..', 'Src'))
from SentimentalExtraction import SentimentExtraction
class SentimentExtractionTestCase(unittest.TestCase):
def testGeneralSentimentAccuracy(self):
sentimentClass = SentimentExtraction()
sentence = 'The prom was pretty go... |
from work.models import Site, ShiftedQty, ProgressQty, SurveyQty, ShiftedQtyExtra, ProgressQtyExtra, SiteExtra, DprQty, Log, Resolution
from consumers.models import Consumer
import pandas as pd
from .functions import getHabID, formatString
from django.db.models import F, Func
def getCompletedHabs():
num_fields = ... |
#!/usr/bin/env python
import daemon, socket
import os, sys, time
from daemon import pidlockfile, DaemonContext
WORKDIR = '/tmp/python_daemon'
LOCKFILE = os.sep.join([WORKDIR, 'lockfile.pid'])
SOCKFILE = os.sep.join([WORKDIR, 'socket.file'])
class DelegateDaemon():
def __init__(self):
self.number = 0
self.__chec... |
__author__ = "Narwhale"
class Node(object):
"""节点"""
def __init__(self,elem):
self.elem = elem
self.lchild = None
self.rchild = None
class Tree(object):
"""二叉树"""
pass |
# libraries
import numpy as np
import pandas as pd
from datetime import datetime
from typing import Union
def split_train_test(df: pd.DataFrame, train_split: int):
"""
Split a data frame into train and test sets
:param df: a data frame to split
:param train_split: split index
:return: train and te... |
#!/usr/bin/env python3
import time
import random
import typing
def pos(data, size=4):
ret = []
for x in range(0, len(data), size):
print('-->' + str(x))
ret.append( int.from_bytes(data[x:x+size], 'big') )
return ret
def neg(data, size=4):
return b''.join([e.to_bytes(size, 'big') for e ... |
# Generated by Django 2.2 on 2021-08-12 01:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('the_wall_app', '0007_comment_creator'),
]
operations = [
migrations.AddField(
model_name='comment',
name='users_who_li... |
class Solution:
def __init__(self):
self.ceil = None
def getSuccessor(self, root, val):
if root == None:
return self.ceil
if root.val == val:
return self.getSuccessor(root.right,val)
if root.val < val:
return self.getSuccessor(root.right,val)
... |
# Copyright 2021 DAI Foundation
#
# 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 applicable law or agreed to in writing,... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-24 09:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webjuego', '0008_usuario_avatar'),
]
operations = [
migrations.AlterField(
... |
"""User related tests."""
from django.urls import reverse
from modoboa.core.models import User
from modoboa.lib.tests import ModoTestCase
from ..factories import populate_database
from ..models import Alias
class ForwardTestCase(ModoTestCase):
"""User forward test cases."""
def setUp(self):
super(F... |
#! /usr/bin/env python
# ======================= Gen Imports ========================
import sys
import json
from flask import Flask
from flask_cors import CORS
from flask_restful import Api
import os
# Stupid games so we can run our api in a nested folder. Some reason we iterate though twice and changing directories ... |
from rest_framework import serializers
from django_filters.rest_framework import DjangoFilterBackend
from .models import ChatMessages
class ChatMessageSerializer(serializers.ModelSerializer):
class Meta:
model = ChatMessages
fields = ('id', 'message', 'user', 'chat_room', 'created_at')
|
from random import randint
money = 1000
while money>0:
print('总资产为:%d' % money)
first = randint(1,6)+randint(1,6)
needs_go_on = False
debt = int(input('说吧,你想下多大的赌注!:'))
if debt<0 or debt>money:
print('这样是不行滴,不想跟你玩了')
debt = int(input('说吧,你想下多大的赌注!:'))
#这里还是有点问题,如何设置... |
# Generated by Django 1.9.5 on 2016-11-05 13:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('relaydomains', '0004_auto_20161105_1424'),
]
operations = [
migrations.RemoveField(
model_name='relaydomain',
name='dates',
... |
import numpy as np
from utils import extract_column, results_to_csv, error_rate, plot_data
from spam_utils import load_spam
from decision_tree_starter import DecisionTree, RandomForest
#RandomForest(trees, sample_size, bag_size, type_map, categories_map, seed)
# fit(data, max_depth, min_samples)
#
#DecisionT... |
import utils
utils.get_lib_addr()
|
"""
This module compares Ruler performance to that of the Python standard
re library. The idea is to match the same few lines of text and
compare how long it takes using re and ruler.
Since the measurements always have non-deterministic, but always
positive, measurement errors, we will make many short measurements
and... |
# A Program to determine employee eligability for advancement
# Created by: <your name here>
# Copyright CTHS Engineering, Inc., 2021
# This code or any portion fo this code can be be reused without
# previous approval from the company CIO or CEO, in writing.
empName = "Sam"
#Project1(P1) - New school wing
#TA ... |
# -*- coding: utf-8 -*-
import requests, base64, time, os, shutil, glob, csv
from subprocess import call
import smtplib, configparser, ftplib
from datetime import datetime
from pytz import timezone
est = timezone('US/Eastern')
#Where am I running from?
dir_path = os.path.dirname(os.path.realpath(__file__))
# Read IN... |
#
# https://github.com/tensorflow/docs/blob/master/site/en/tutorials/sequences/text_generation.ipynb
from __future__ import absolute_import, division, print_function
import tensorflow as tf
print (tf.__version__)
#tf.enable_eager_execution()
import numpy as np
import os
import time
## Setup
def loss(labels, logits):... |
from grafo import Grafo
CERO = 0
UNO = 1
class Parser(object):
def escribir_stable_matching(self, nombre, E, H, Q):
"""Escribe un archivo del tipo Stable Matching"""
try:
mi_arch = open(nombre, 'w')
n = len(E)
mi_arch.write(str(n) + '\n')
for i in ... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
""" USB3 link-layer abstraction."""
from amaranth import *
from ...stream import USBRawSuperSpeedStream, SuperSpeedStreamArbiter, SuperSpeedStreamInterface
from ..phy... |
from django.test import TestCase
from common.models import Injection
from common.models import CRI
from calc.forms import CalcInjForm, CRISimpleForm, CRIAdvancedForm, CRIInsulinForm, CRICPRForm, CRIMetoclopramideForm
class InjectionTest(TestCase):
def test_injection_page_renders_injection_page_template(self):
... |
# -*- coding:utf8 -*-
import xlrd, os, csv, sys
reload(sys)
sys.setdefaultencoding("utf-8")
crash, maint, frame = {}, {}, {}
dicts = {3:crash, 4:crash, 5:maint, 6:frame}
files = os.listdir('..'+os.sep+'input')
for filename in files:
filedata = {} # all data in the file
workbook = xlrd.open_workbook('..'+os.sep+'... |
import rake
import operator
import sys
text = sys.argv[1]
rake_object = rake.Rake("stopwords_pt.txt", 4, 3, 0)
#sample_file = open("x", 'r')
#text = sample_file.read()
keywords = rake_object.run(text)
print "Keywords:", keywords
print text
kw = []
for name in keywords:
if name[1]>1:
kw.append(name[0])
myList ... |
# from bs4 import BeautifulSoup
# import urllib.request
#
# url = "F:/BlogDuCinema/201611110진교준/ㄱ.html"
# soup = BeautifulSoup(urllib.request.urlopen(url).read(), 'html.parser')
# pkg_list = soup.findAll("div", "words")
#
# count = 1
# for i in pkg_list:
# title = i.findAll('a')
# print(count, "위: ", str(title)[str(t... |
#!/usr/bin/env python3
import argparse
import re
import sys
import yaml
from matrix_client.client import MatrixClient
# Not going to care for specifics like the underscore.
# Generally match !anything:example.com with unicode support.
room_pattern = re.compile(r'^!\w+:[\w\-.]+$')
def send_message(cfg, args):
c... |
from server.currentaccount.models import CurrentAccount
from django.contrib.auth.models import User
from tastypie.authentication import Authentication, BasicAuthentication
from tastypie.authorization import Authorization, DjangoAuthorization
from tastypie.resources import ModelResource
from tastypie import fields
fro... |
head = 0
tail = 0
import random
for i in range(1,5001):
# import random
num= random.random()
# print num
num_rounded= round(num)
# print num_rounded
if num_rounded == 1:
head += 1
print "Attempt #" + str(i) + ": Throwing a coin... it's a head!... Got " + str(head) + " heads so f... |
from panda3d.core import RenderState, ColorAttrib, Vec4, Point3, GeomNode
from bsp.leveleditor.objectproperties.ObjectPropertiesWindow import ObjectPropertiesWindow
from bsp.leveleditor.geometry.Box import Box
from bsp.leveleditor.geometry.GeomView import GeomView
from bsp.leveleditor.viewport.ViewportType import VIEW... |
from app.models import Ingredients, User, Recipes
from app import db
from flask_login import current_user
ing_list = ['Apple', 'Tabantha Wheat', 'Wildberry', 'Monster Extract',
'Acorn', 'Swift Carrot', 'Fresh Milk', 'Bird Egg', 'Hylian Rice',
'Raw Meat', 'Raw Gourmet Meat', 'Raw Whole ... |
from zope import interface
from zope import component
from zope.formlib import form
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import safe_unicode
from Products.CMFPlone.interfaces import IPloneSiteRoot
from Products.CMFDefault.formlib.schema import ProxyFieldProperty
from Products.C... |
default_app_config = 'colossus.apps.subscribers.apps.SubscribersConfig'
|
#!/usr/bin/python
#
# Created by Albert Zhang on 4/10/15.
# Copyright (c) 2015 Albert Zhang. All rights reserved.
#
import os
import sys
import errno
import string
import subprocess
import re
import shutil
import random
import codecs
import json
isShowHelp = False
dirIndex = -1
outIndex = -1
for index, value in en... |
"""Reports package
"""
__version__ = "$Rev: 10 $"
import pkg_resources
try:
version = pkg_resources.require("reports")[0].version
except:
version = __version__
from .report import Report
from .htmltable import HTMLTable
|
import argparse
import json
import logging
import os
try:
from ripetor import ip2as
except:
import ip2as
from datetime import datetime
from operator import itemgetter
import subprocess
from collections import OrderedDict
from ipaddress import ip_address, ip_network
def filter_ip_addrs(addr_list, ip_version="... |
from wtforms import TextAreaField, StringField, Form, IntegerField, SelectField
from wtforms.fields.html5 import DateField
from wtforms.validators import InputRequired, ValidationError
class AdForm(Form):
title = StringField("Title", validators=[InputRequired()])
content = TextAreaField("Content", validators=... |
class Node(object):
def __init__(self,data):
self.value = data
self.less = None
self.more = None
def addL(self, data):
n = Node(data)
self.less=n
return(n)
def addR(self, data):
n = Node(data)
self.more=n
return(n)
def printer(self,lev):
print (self.value)
if (self.less):
print "left:... |
import random
# 定义一个函数,产生一个验证码
def generate_checkcode(n):
s = '0987654321qwertyuiopasdfghjklzxxcvbnmQWERTYUIOPADSFGHJKLZCXVBNM'
code = ''
for i in range(n):
ran = random.randint(0, len(s)-1)
code += s[ran]
return code
def login():
username = input("请输入用户名")
pas... |
employees = [{
'name': 'John Mckee',
'age': 38,
'department': 'sales'
}, {
'name': 'Lisa Crawford',
'age': 29,
'department': 'marketing'
}, {
'name': 'Sujan Patel',
'age': 33,
'department': 'hr'
}]
print(employees[1])
items = ['apple', 'orange', 'banana']
quantity = [5, 3, 2]
ord... |
#!/usr/bin/env python
# coding: utf-8
# In[85]:
import csv
from pathlib import Path
input_file = Path('Resources','budget_data.csv')
total_number_of_months=[]
profit_loss=[]
average_change=[]
with open (input_file, 'r') as csv_file:
csv_reader = csv.reader(csv_file,delimiter=',')
next(csv_reader)
data=[... |
# Create call Slither
class Slither:
# Define Slither Parameters
x = [220]
y = [308]
step = 44
length = 0
direction = 0
updateCountMax = 2
updateCount = 0
# Define Slither Length in game
def __init__(self, length):
self.length = length
for i in rang... |
from django.apps import AppConfig
class PatrocinadoresConfig(AppConfig):
name = 'patrocinadores'
|
# Given an array of length N whose each element is a tuple (base, exponent),
# find the position in the array (1-indexing) such that base ^ exponent
# is largest!
# Methodology: A ^ B > C ^ D iff B * ln(A) > D * ln(C)
from math import *
def findMaxExpoValue():
arrInput = readInputFromFile()
arrLen = len(arr... |
"""Top-level project Main Module."""
from IncomeAccountOverhead import income_account_overhead
from BalanceSheetOverhead import balance_sheet_overhead
from StockBondOverhead import stock_bond_overhead
from ReferenceOverhead import reference_overhead
from EndSearchOverhead import end_search_overhead
import ZoneNeutralO... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import json
import Queue
import ctypes
import select
import socket
import logging
import threading
from time import sleep
from datetime import datetime, timedelta
from threading import Event, Timer
from signal import signal, SIGINT
from collections impo... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 10 11:19:29 2019
@author: Vall
"""
import iv_analysis_module as iva
import matplotlib.pyplot as plt
import iv_save_module as ivs
import iv_utilities_module as ivu
import numpy as np
#%%
# Parameters
home = r'C:\Users\Usuario\OneDrive\Labo 6 y 7'
name = 'M_20190610_02'
... |
from django.contrib import admin
from .models import Visitors, Entry_Schedule
# Register your models here.
admin.site.register(Visitors)
admin.site.register(Entry_Schedule) |
import os
from collections import OrderedDict
import torch
import logging
from easydict import EasyDict as edict
import yaml
def print_to_screen(loss, lr, its, epoch, its_num,
logger, data_time, train_time, mem, acc=0):
logger.info(("[%d][%d/%d]\t"%(epoch, its, its_num)+
"Loss:%.5f\t"%(loss)+"Lr:%.6f\... |
# Copyright 2022 NVIDIA Corporation
#
# 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 applicable law or agreed to in wr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time, math
import socket
import numpy as np
import rospy
from std_msgs.msg import String
#
# IMPORTANT NOTE: Don't add a coding line here! It's not necessary for
# site files
#
# IBUKI MODULE 2.0
#
#=================================================================... |
def result(coords):
q1, q2, q3, q4, axis = 0, 0, 0, 0, 0
for c in coords:
if c[0] == 0 or c[1] == 0:
axis += 1
elif c[0] > 0:
if c[1] > 0:
q1 += 1
else:
q4 += 1
else:
if c[1] > 0:
q2 += 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.