index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
994,400
3ebaebd05793953cd181a72d1b8f00efae8460f3
import files.screen if __name__ == '__main__': screen = files.screen.Screen() screen.game_menu()
994,401
49f8fcfb216ea515506fa755c6c5e3b574ae4609
import string alphabet = list(string.ascii_uppercase) names = file("./names.txt") names = names.read().replace('"','').split(",") names = sorted(names,key=str.lower) def name_score(name): name = name.upper() name = list(name) score = map(lambda x:alphabet.index(x)+1,name) return sum(score) names = map(name_scor...
994,402
252cd00a48f6c1215491167afff42624353ac2fa
from rest_framework import status from rest_framework.decorators import api_view from recruit_api.apps.utils.models import ResponseData from recruit_api.apps.utils.api.response import RecruitResponse from recruit_api.apps.email.operations import EmailOperations from rest_framework.views import APIView from rest_framewo...
994,403
06132b2a6f23b8b4742a5a1150e2fafbd59d4c53
import scrapy import pandas as pd from ..items import ImdbSpiderItem import time import re def get_movies(path): data = pd.read_csv(path) url = data['url'] return url class ImdbSpider(scrapy.Spider): start = time.clock() name = 'movies' allowed_domains = ['imdb.com'] def start_requests...
994,404
3aa2d780cce7a9133064be9950ef58b92cfad049
# Copyright 2017 Google Inc. All Rights Reserved. # # 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 a...
994,405
5fc304c7255b62e0fff0f5e89e8e5100738a1504
# -*- coding:utf-8 -*- from dytt8 import * def dytt_spider(): try: print 'execfile------dytt_spider.py' task_dytt8() except: print traceback.format_exc() if __name__ == '__main__': dytt_spider()
994,406
ccf1dbee46d28800f87aac3b74d9b544456fb474
import urllib2 import requests from xml.dom.minidom import parse, parseString def get_authorization_code(): auth_url = "https://graph.api.smartthings.com/oauth/authorize?response_type=code&client_id=b882249a-a9b4-4690-935d-bf78aeeb991a&scope=app&redirect_uri=http://localhost:4567/oauth/callback" return def ge...
994,407
23943486bc80f1be6496b845bee2fe378b1fbf2d
"""Module for creating warped images """ from typing import Optional, Union from FaceEngine import IHumanWarperPtr # pylint: disable=E0611,E0401 from FaceEngine import Image as CoreImage # pylint: disable=E0611,E0401 from numpy import ndarray from PIL.Image import Image as PilImage from lunavl.sdk.detectors.bodydet...
994,408
a086bdff4bd8d7a2bc8729b9f96668a7ffea35ef
from .tasks import * task_lists = {'CartPole': CartPole, 'Acrobot': Acrobot, 'FlappyBird': FlappyBird, 'MoutainCar': MoutainCar, 'Catcher': Catcher, 'Pixelcopter': Pixelcopter, 'Pong': Pong} # task: {name, init, alpha, n_task} eq: param = init + alpha * i def param(init, alpha, i): return init + alpha * i def cr...
994,409
5595fcff09f4391186db35ea9166b5c1ca6db917
import os import json import numpy as np import pandas as pd import re from tqdm import tqdm from scipy.stats import pearsonr import matplotlib.pyplot as plt from math import log path = './PacificExcellent_CCS/PacificExcellent_CCS' filelist = os.listdir(path) # 删除解压之后留下的zip文件 # for filename in filelist: # if 'zip...
994,410
af2c3d91a0736f885d06c0ac96dbe25c0bae832f
#!/usr/bin/env python # -*-coding:utf-8 -*- #Author:HXJ #动态参数 ''' 需求: 1.对请求参数进行ascill排序 2.排序后,对请求参数进行md5的加密 1.写一个函数,获取请求参数,对请求参数进行加密 ''' # dict1={'name':'hxj','age':18,'data':{ # 'name':'wuya','age':18}} # def data(**kwargs): # return dict(sorted(kwargs.items(),key=lambda item:item[0])) # dict1={'name...
994,411
b562ee4143fe2a41fe5fc5c076c7404168442841
from django.http import HttpResponse # Create your views here. def cs(request): text = "这是一个测试接口" return HttpResponse(text)
994,412
06c7e877e684b6b26c7508ad0d127b06c9d36b9e
# parameter를 받기 # 사용예 : python sys.py life is short import sys args = sys.argv[1:] for i in args: print("Param %d : %s", i, i.upper(), end=' ')
994,413
0b838bff2fca920f411a93b41d8ed9ce833959cf
class ImageTransform(object): def __init__(self, part): self.part = part
994,414
b14931997d3e663061ab593dcaf2fbc3ff35b02f
from rest_framework.serializers import ModelSerializer from tarefas.models import Tarefa class TarefasSerializer(ModelSerializer): class Meta: model = Tarefa fields = '__all__'
994,415
81de064ec7f8529e2a8e70e076ba162dcc5349cc
# Forma 1 dict = {1: 1, 4: 4, 5: 5, 6: 6, 7: 7, 9: 9} for i, v in dict.items(): dict[i] = v**2 print(dict) # Forma 2 chaves = [1, 4, 5, 6, 7, 9] dict2 = {} for cont in chaves: dict2[cont] = cont**2 print(dict2)
994,416
b1fee8a8e4bb5df2d24f1d3a73d7b44dbe384d9e
def primo(n): for i in range(0,n): num = int(input()) s = 0 j=1 while j <= num: if num % j == 0: s = s + 1 j = j + 1 if s > 2: num.append(n_primo) else: num.append(eh_primo) n = int(input()) ...
994,417
73efe17a47c52eca33237f5a15f0cdf702c4d3fc
import requests from src.general.constants import PROD_BASE_URL as base_url def get_employees_by_area(area_id): url = base_url + 'personal/excel/personal' querystring = {'idArea' : area_id} payload = '' headers = { 'cache-control': 'no-cache' } response = requests.request('GET', url, d...
994,418
dcab2fd158e1469d0b06caa99ff4de156fc16bf2
# Contains testing utilities for tensor-train code import numpy as np import numpy.linalg as la class Grid: def __init__(self, gridIndices): # Note: this explicit initialization is only temporary... self.gridIndices = gridIndices self.dim = len(self.gridIndices) def applyFunction(sel...
994,419
a882436b6ec317d1e0fd8f9084772bfc055a563d
import sys from PyQt5.QtWidgets import QApplication, QStyleFactory from enum import Enum from cocomo import Cocomo from cocomo_model import CocomoModel from cocomo_view import CocomoView import json # Hecho por Saúl Núñez Castruita class CocomoController(): def __init__(self): app = QApplicati...
994,420
33d5dc48dcb74999434d5ca31216142349ca02b4
formatter1 = "{} {} {} {}" formatter2 = "{} {} {}" formatter3 = "{} {} " formatter4 = "{}" name="SHRITAM" print(formatter1.format(1, 2, 3, 4)) print(formatter1.format("I","AM",name,".")) print(formatter1.format("*","*","*","*")) print(formatter2.format("*","*","*")) print(formatter3.format("*","*")) print(formatter4.fo...
994,421
42419038c81541d0511adcf4eba3b6b3b67de7b3
counter = 0 sum = 0 for i in range(0,20,5): sum = sum + i counter = counter + 1 print(i) print("the sum is:",sum) print("the average is:",sum / counter) print(counter)
994,422
74b4dbee5ed9a5a722d2d656b7c464d5f359a640
import matplotlib.pyplot as plt def display_rgbd(images): # Displays a rgb image and a depth image side by side # Can take more than two images plt.figure(figsize=(15, len(images) * 5)) for i in range(len(images)): plt.subplot(1, len(images), i + 1) if i < 1: plt.title("RGB...
994,423
b3c0f180b4145fe3b422de1f0f208c02d9890452
import logging from typing import Optional, Pattern import sqlalchemy as sa from aiohttp import web from pydantic import BaseModel, ValidationError, validator from servicelib.aiohttp.application_setup import ModuleCategory, app_module_setup from ._meta import api_vtag from .constants import ( APP_DB_ENGINE_KEY, ...
994,424
4c85ba855385fb8db91f95dcbca2564da715e866
# -*- coding: utf-8 -*- from __future__ import unicode_literals from .models import Post,Category from django.shortcuts import render, get_object_or_404 from comments.forms import CommentForm import markdown def index(request): #return HttpResponse('welcome to my blog index!') post_list=Post.objects.all().order_b...
994,425
6551a27e210b33b26b6962b273751e40a1955a2e
# Generated by Django 3.0.7 on 2020-06-16 11:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('learning_partners', '0002_entry'), ] operations = [ migrations.DeleteModel( name='Entry', ), ]
994,426
0097a2fec8bae3318b472164eb23c84c586c297f
# Copyright 2013 Pervasive Displays, Inc. # # 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 i...
994,427
614881049c0ed94d650c4eb81058855921eb2509
from rest_framework import status from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from ...
994,428
2db613b1d09e9489cd7cebf08903e1870225d46a
import math SENSE_RADIUS = 7.0 TREE_RADIUS = 1.0 TRI_DX = 4.2 TRI_DY = TRI_DX / 2 * math.sqrt(3) RANGE = 3 def triangle_clusters(mx, my): xi = int(2 * mx / TRI_DX) yi = int(2 * my / TRI_DY) coords = [] cands = [] for i in range(-RANGE, RANGE + 1): for j in range(-RANGE, RANGE + 1): ...
994,429
d11d594cb858085d6f1d694a332bdf5c80762bef
""" """ from itertools import repeat from ...cfg import CFG __all__ = [ # vanilla xception "xception_vanilla", # custom xception "xception_leadwise", ] xception_vanilla = CFG() xception_vanilla.fs = 500 xception_vanilla.groups = 1 _base_num_filters = 8 xception_vanilla.entry_flow = CFG( init_nu...
994,430
1e81f585c163815a2c1def0831b3a4b413ad13ec
from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.senate_home, name='senate-home'), url(r'^constitution/$', views.senate_constitution, name='senate-constitution'), url(r'^minutes/$', views.minutes, name='senate-minutes-home'), url(r'^mi...
994,431
cf06b53554f855eb98f1f493176209a0773b0ef3
import sqlite3 from sqlite3 import Error import os.path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_path = os.path.join(BASE_DIR, "../db/breaches.db") def create_connection(): """ create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Conn...
994,432
b0b3d4fc6c3a306626e6593801eccf32556682ff
import os import unittest from setuptools import setup, find_packages def discover_tests(): test_loader = unittest.TestLoader() test_suite = test_loader.discover("tests", pattern="test_*.py") return test_suite def read(filename): filepath = os.path.join(os.path.dirname(__file__), filename) with ...
994,433
00f4835aefe7d0a045b0986ebd87e534b1df0476
__version__ = "v2.0.0"
994,434
5dc4e774ae19c3cda2641b6a26bee6ae75070cbf
import UDPComm import PIDValues if __name__ == '__main__': udpComm = UDPComm.UDPComm('10.1.95.22', 5808) udpComm.connect() try: while True: udpComm.sendPIDData(PIDValues.PIDValues(2, 1, 2, 3, 4)) print(udpComm.getResponseData()) except KeyboardInterrupt: udpComm.close()
994,435
c5ecfad5b46454e0a61ef2ad3284cd9e81a6c521
import os import requests as req from bs4 import BeautifulSoup as soup import json # GENERAL CONSTANTS WORKING_DIRECTORY = "F:\\Read Anime\\Light-Novel\\Books\\{}" WORKING_FILE_DIRECTORY = "F:\\Read Anime\\Light-Novel\\Books\\{}\\{}" TESTING_FILE_DIRECTORY = "F:\\Read Anime\\Light-Novel\\Books\\{}\\tests\\{}" FIRST_C...
994,436
97bbcaf9172c7e738d576e20ec26f063b4fdaff5
import unittest from src.actions.parsers.move.MoveActionDataParser import MoveActionDataParser, MoveDirection, ParseException class MoveActionDataParserParseToDataTests(unittest.TestCase): def test_parse_to_data_from_empty_string(self): with self.assertRaises(ParseException): MoveActionDataPar...
994,437
7b7cb59f8771d6b9d151df5ca6d870f31b130d9b
#!/usr/bin/env python2.7 # mergeBamsE3.py ENCODE3 galaxy pipeline script for merging 2 bam replicates # Must run from within galaxy sub-directory. Requires settingsE3.txt in same directory as script # # Usage: python(2.7) mergeBamsE3,py <inputBamA> <repA> <inputBamB> <repB> <galaxyOutMergedBam> \ # ...
994,438
46b34635190ca3a8346994885d65c8d6fd9c17a2
import requests, ssl, requests.adapters, socket, json from requests.packages.urllib3.poolmanager import PoolManager class HostNameIgnoringAdapter(requests.adapters.HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, ...
994,439
daa99a8034682d3ae133abbab60d65b2af49cdc4
#!/usr/bin/env python2.7 import redis import urllib2 import json infra_api = "http://jabber.khrypt.ooo:1337" # Change to your endpoint r = redis.Redis(unix_socket_path = "/var/run/redis/redis.sock") # Change to your Redis socket try: response = urllib2.urlopen("%s/status/ups" % (infra_api)) ups_status = response.re...
994,440
7424ba519064ec42b98a70cd03c8f6b8785f22a0
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from flask import request, Blueprint, jsonify import models import tasks.pinger_tasks import traceback from main ...
994,441
257200344a616ce115ef5ede73222b530b764736
""" Confident that your list of box IDs is complete, you're ready to find the boxes full of prototype fabric. The boxes will have IDs which differ by exactly one character at the same position in both strings. For example, given the following box IDs: abcde fghij klmno pqrst fguij axcye wvxyz The IDs abcde and axcye ...
994,442
55f17c9e91d97b11a2651fcc0e9fcc0554cd12bd
import time import random import matplotlib.pyplot as plt #Con recursion def ArraySum(arr): if len(arr)==1: return arr[0] #C1=5 else: return (ArraySum(arr[1:])+arr[0]) #T(n)=C2+T(n-1) donde C2=4 print(ArraySum([2,4,5,10,15,0])) """ T(n)=C2+T(n-1) """ #%% times=[] def pl...
994,443
d48a6e4a02e6ffb786301c27461f14b7d438a325
# Generated by Django 2.1.4 on 2019-01-05 12:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('clientes', '0016_auto_20190105_1230'), ] operations = [ migrations.AlterField( model_name='pessoa', name='token', ...
994,444
fbb5bc1334e7dff8432ebb84022419e8944a5076
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Author: Wellington Silva a.k.a. Well Date: July 2017 Name: how2decode-utf16.py Purpose: Decode data with JavaScript Escape. Description: Script Based on script CAL9000 by Chris Loomis from OWASP Project, posted at: <https://www.owasp.org/index.php/...
994,445
9894e1dd59eb08adf26c689fee3da3e8ea014010
# -*- coding: utf-8 -*- import Adafruit_DHT import datetime def read_sensor(): sensor = 11 # GPIO (BCM notation) pin = 17 humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) time = datetime.datetime.now() return str(time) + "\tTemperature={}ºC, Humidity={}%; ".format(temperature, hum...
994,446
8e9cf3cadbf42988f1fe32e57a84c10c3b7d3080
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import cross_val_score from sklearn import svm from sklearn.cluster import KMeans from mpl_toolkits.mplot3d import Axes3D %matplotlib notebook data = pd.read_csv("sshekha4.csv", header=None) # First copying ...
994,447
4705319091571e70c555feb5a99b7000ccd5c8cd
print("Hello World") print("Hello Sathish") print("Hello") print("Ambika")
994,448
073a626b34d3768ee26e8e6501117a36ae655368
import pandas as pd sales = pd.Series([3,5,8,11,13]) dms = pd.Series([1,2,3,4,5]) print('상관계수 :', sales.corr(dms)) # 값이 1에 가까우면 서로 관련이 높다.
994,449
51662796d18ad0fbe1f7d524d62efb251885f60f
#!/usr/bin/python3 import sys if __name__ == "__main__": sys.path.append("..") search_replace = __import__('1-search_replace').search_replace my_list = [1, 2, 3, 4, 5, 4, 2, 1, 1, 4, 89] new_list = search_replace(my_list, 2, 89) print(new_list) print(my_list)
994,450
e034ae44eeb8539ec202f6a42ec1421981cdcb29
def start_game(nivel,variables): """Muestra la ventana para jugar y todo su desarrollo.\n Retorna si termino la partida y los datos de ella """ from Juego.validarPalabra import es_valida, clasificar from Juego import pausa,terminarPartida from Windows import windowSalirJuego from datetime im...
994,451
efdd0f54827aa4a06ed1740a0f6e7ecc64c93dbd
import os import requests # To stop the warrnings when doing get/post to https from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings() # Define vmanage host, port, user, pass as eviromental variable #export vmanage_host=IP/FQDN #export vmanage_port=port...
994,452
a7753881a3d3c992f6afce663846b6e0d40b4dbf
#!/Volumes/Samsung_T5/dev/store-warehouse/venv/bin/python from django.core import management if __name__ == "__main__": management.execute_from_command_line()
994,453
6345b2f5ceaf5910a8f4e2988ee978d1077fe3ac
# load rouge for validation import rouge_score import datasets rouge = datasets.load_metric("rouge") def compute_metrics(pred): labels_ids = pred.label_ids pred_ids = pred.predictions # all unnecessary tokens are removed pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=Tru...
994,454
e7df00a27a21e87402999da668f4c29308556828
from dominion_ai.abstract_player import Player from dominion_ai.utils import GameStage import dominion_ai.cards as cards class GreenGoldPlayer(Player): def buy_card(self): """Implement the "greens and golds" strategy of buying the highest victory point card (in the game) if possible, and o...
994,455
11583f78f32c796e51583ce26d9992b6cdc687ad
#!/usr/bin/env python3 """ File: dice.py Name: Rolls a dice and outputs the result Concepts covered: Random, printing """ import random def main(): randNum = random.randint(1,6) roll = input("Press any key and then enter to roll a dice. ") print("You rolled",randNum) if __name__ == "__main_...
994,456
0089434cc291bcd44bddb869b02fe1388d9135ba
import SimpleCV as scv import numpy as np class CList(): def __repr__(self): #return self.vect oldest = (self.idx+1)%self.size return str(self.vect[oldest:] + self.vect[:oldest]) #oldest -> newest def __init__(self,size): self.vect = [None]*size self.idx = 0 #where ...
994,457
94bfb9a04b2110cdcec7b7dd8a7a7b92a299ec6c
#!/usr/bin/env python # -*- coding -*- if 1 == 1: name = 'alex' else: name = 'eric' #三元运算表达式 name1 = 'alex' if 1 == 1 else 'eric' print(name1)
994,458
c2d6d70627beaf721d175320f88349c3664315d0
from dog import Dog from animal import Animal dog1 = Dog("Garf", 12) dog2 = Dog("Snarf", 12) print(dog1.name + ", " + dog2.name) dog1.eat("meat")
994,459
0c25533be9cf5a78fab4fc3f2709fa3dd0856a35
from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from .forms import CommentForm from . models import Video from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import ...
994,460
97df5696e8363a193336c1a2230065b921645d2e
''' Created on Sep 19, 2016 @author: Gerry Christiansen <gchristiansen@velexio.com> ''' import re import sys from collections import OrderedDict import cx_Oracle from pylegos.core import LogFactory ''' ----------------------- ENUM Type Classes ----------------------- ''' class CxOracleType(object): Varchar2...
994,461
c9e0b97258df4cc9bac5dff6aee15a8422754967
#Program to reverse a string word by word class Reverse: def reverse_words(self,string): return " ".join(reversed(string.split(" "))) a=Reverse() string=input() print(a.reverse_words(string))
994,462
fb85013115102c222c4e09529e9104d615609fc6
# -*- coding: utf-8 -*- import scrapy import re import json from tutorial.items import IeeeItem class IeeexploreIeeeOrgSpider(scrapy.Spider): name = 'ieee' allowed_domains = ['ieeexplore.ieee.org'] # start_urls = ('http://ieeexplore.ieee.org/document/7185405/',) def start_requests(self): reqs=...
994,463
fded4fac6a983ed558352623cdf122f1a26e8514
import numpy as np from mytorch import tensor from mytorch.autograd_engine import Function import math def unbroadcast(grad, shape, to_keep=0): while len(grad.shape) != len(shape): grad = grad.sum(axis=0) for i in range(len(shape) - to_keep): if grad.shape[i] != shape[i]: grad = gr...
994,464
bf069f9a061a48713481f0b92cea6f865030508e
""" Run "./manage.py test blog" from healthblog root. """ from django.test import TestCase, Client from django.core.urlresolvers import reverse import datetime # need to make timezone aware import urllib.parse class AuthorizationTests(TestCase): def setUp(self): """ To fully test, create poster ac...
994,465
5b6a2fcfb179ef511d4468c5fb9248c4251e5257
#This script aim to map the predicted RxLRs effector from P. capsici on the genome to identify the corresponding transcript. #The default of this script is that it might get rid of transcript that are not predicted RxLR but for which #the position is overlaping with predicted RxLRs on the genome #2013 Gaëtan Thilliez ...
994,466
fdaf6eb7f3fa7866cf687bd438f28752dba7e4d4
import numpy as np class ServerModel: def __init__(self, n_items, n_factors): self.item_size = n_items self.n_factors = n_factors # randn genera un array di shape # Viene generato un array positivo riempito con float casuali campionati da una distribuzione "normale" (gaussiana) ...
994,467
0c53df9d2627ed05a526757a189deecfc6f5ab42
import requests import json def send_notification(player_ids, message): headers = { "Content-Type": "application/json; charset=utf-8", } headers['Authorization'] = 'Basic ' + app.config['ONESIGNAL_API_KEY'] payload = { "app_id": app.config['ONESIGNAL_APP_ID'], "include_player_id...
994,468
f20972ec9c710ac5ef9f5319d7b70a4a96075418
''' Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). ''' a = input('Введите целое число: ') # Счетчик четных цифр odd = 0 # Счетчик нечетных цифр: even = 0 # Цикл выполняется столько раз, сколько цифр в числе fo...
994,469
83d17f03563d8308ee3b46be6402f584551d765b
from flask import Flask, redirect from flask_restful import Resource, Api from agro_log_handler import AgroLogHandler from rest import Build, Request, Result, Image, Log, Output app = Flask(__name__) def init_application(app, config): """ Reads config and registers blueprints. :param Flask app: applica...
994,470
a2e6c9852e97240b72ab441940772b29cdf5e3ac
from b import * class User: def __init__(self, name, zarp, day): self.__wallet = Budget(name, zarp, day) def get_user(self): return self.__wallet
994,471
3b08c82b7c91111b4dd53e458c83a15f8c65144d
from django import forms from django.forms import extras class LoginForm(forms.Form): username = forms.CharField(max_length=30) password = forms.CharField(widget=forms.PasswordInput) class RegisterForm(forms.Form): name = forms.CharField(max_length=30) username = forms.CharField(max_length=30)...
994,472
3df473e7b48fd40c57d74006234bec1e4fa050f6
import http import base64 from openbrokerapi import errors, constants from openbrokerapi.catalog import ServicePlan from openbrokerapi.service_broker import Service from tests import BrokerTestCase class PrecheckTest(BrokerTestCase): def setUp(self): self.broker.catalog.return_value = [ Servi...
994,473
efe64aa1d879a8a46640292bf8765bf89c1e3a7c
from flask_sqlalchemy import SQLAlchemy from app import db from datetime import datetime from app.utils.exceptions import ValidationError from flask import url_for, current_app #This will delcare model class for earnings and its relevant model will be display over here . class Earnings(db.Model): __tablename__ =...
994,474
04ac2f5fc3e19ef1252a24f463d8efd5644b9afe
import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output from apps import commonmodules from app import app layout = html.Div([ commonmodules.get_header("Yammer Page"), commonmodules.get_menu(), ])
994,475
2528456fda68ded4cf64f07d2933f4f3eb4ff361
import numpy as np import pytest from d3rlpy.dataset import EpisodeGenerator, Shape from ..testing_utils import create_observations @pytest.mark.parametrize("observation_shape", [(4,), ((4,), (8,))]) @pytest.mark.parametrize("action_size", [2]) @pytest.mark.parametrize("length", [1000]) @pytest.mark.parametrize("te...
994,476
7a10516500598f4c8fa803efd7ac064d40643e2d
#Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR. número = int(input('Digite um número qualquer: ')) resultado = número % 2 if resultado == 0: print('O número {} é PAR'.format(número)) else: print('O número {} é IMPAR'.format(número))
994,477
ed81249acd136ac682f8833ec09f75b65951332e
import numpy as np from proposition1 import * def main(): # proposition1() return if __name__ == '__main__': main()
994,478
99b236d648bd5cafe4b0f62085475f3ee3080d86
from keras.utils import np_utils import sys import keras from keras import Sequential from keras.layers import Dense, Dropout, Conv1D, Flatten, BatchNormalization, Activation, MaxPooling1D from keras.callbacks import TensorBoard,ModelCheckpoint,EarlyStopping from keras.optimizers import Adam,SGD import numpy as ...
994,479
d469cbe87d0ee55c8bf76c2bb1441c5d7423dfce
from telegraph import Telegraph from telegraph import exceptions class States: S_START = 0 # Начало нового диалога S_ENTER_TITLE = 1 # Ввод названия S_ENTER_INGREDIENT = 2 # Ввод ингридиентов S_ENTER_TEXT = 3 # Ввод рецепта S_ENTER_TAG = 4 # Ввод тегов вручную S_ADD_RECIPE = 5 # Добавлени...
994,480
ff4179189b49d1f5645904b1cf005d332ef03c0a
import matplotlib.pyplot as plt import numpy as np import interpolation as inter np.seterr(divide='ignore', invalid='ignore') data = np.loadtxt('test.dat') x = data[:,0] y = data[:,1] z = np.linspace(x[0],len(x),100) plt.plot(x,y,'bo',label='Given points') # linear spline interpolation f1 = inter.linterp(x,y,z) plt....
994,481
0ebf02f807a606283e626272d26b7f45a05e79e3
import os import glob from PIL import Image from PIL import ImageEnhance for tifFile in glob.glob(R"C:\Users\swharden\Documents\temp\test\*.tif"): print("converting", os.path.basename(tifFile)) jpgFile = tifFile+".jpg" im = Image.open(tifFile) im = ImageEnhance.Contrast(im).enhance(7) im.save(jpgF...
994,482
c72237d451bbee93319c4cadc255227b3007a9da
# -*- coding=utf-8 -*- import math def is_not_empty(s): # 不要None, 也不要长度为0的 # strip取出空字符'\n' '\r' '\t' ' ' return s and len(s.strip()) > 0 def is_sqr(x): """返回开根后为整数""" # todo 如何判断是整数 math.sqrt(返回的结果是浮点数) """ 1.先转换成int 2.然后逆向思维,看谁的平方等于100内的数 """ r = int(math.sqrt(x)) ...
994,483
7a45cdd02d64deeda291496eafa699b655abea21
import tensorflow as tf import pickle import codecs from test import judge, dele_none import numpy as np import math sequence_maxlen = 256 path = '/home/joyfly/桌面/inputs_data' source_data = '/home/joyfly/桌面/word2id_data.pkl' ckpt_path = '/home/joyfly/桌面/ckpt/' maxlen = 256 def load_data(): """ 载入数据from pick...
994,484
3e152e78f81689aa17f8163e385c4f59f648cd0b
# -*- coding: utf-8 -*- import numpy as np import math def sine_wave_generator(fs, t, spl_value, freq): """It creates a sine wave signal given some input parameters like frequency, duration, sampling rate or sound pressure level. Parameters ---------- fs: int 'Hz', sampling ...
994,485
f09729d82005fad7c41ec6c44498e5250fbcc45f
from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.core.validators import EmailValidator from django.contrib.auth.validators import UnicodeUsernameValidator class Player(AbstractUser): """ This class extends the ...
994,486
5bbf4c00e9bd8b1a1aad54918f9d048c0c7a32d7
__author__ = 'Amad' import requests from . serializer import TrendsSerializer from rest_framework.decorators import api_view from rest_framework.response import Response # to send specific response from rest_framework import status class BestbuyAPI(): def PopularMobiles(self,request): try: ...
994,487
5980570ce5198faad0b96a77c4d9b899f448d500
from abc import ABC import pygame class GameButton(ABC): # content parameter can be text or image def __init__(self, x, y, width, height, content, color): self.x = x self.y = y self.width = width self.height = height self.content = content self.color = color ...
994,488
04741e8c12517d6f991b813af4fea7b00da88d2e
from plugin import blueprint, menu, plugin_load, plugin_unload, plugin_info from model import ModelCustom
994,489
8d0d6d6eee0a6bb4b2e09b6d0326e6d214dc4326
from sqlalchemy import Column, Integer, Text, ForeignKey, DateTime, orm from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.sql.functions import now from springboard.models import Base class Board(Base): __tablename__ = "boards" id = Column(Integer, primary_key=True) name = Col...
994,490
3712d14242d55487244d259ce910768879b77e65
import rest_framework from rest_framework.permissions import BasePermission class MyPermissions(BasePermission): '''The permissions set here will allow the a normal user to access only the GET API request and staff user to access all of the request methods''' def has_permission(self, request, view): ...
994,491
edfbd1adc9f039b3a4703629704e56e460375f52
import pymongo import json myclient = pymongo.MongoClient("mongodb://localhost:27017/") #print(myclient.list_database_names()) def insert_into_database(name, topic): #print("name: ", name) #print("topic: ", topic) mongoClientDB = myclient['mywikidump'] collection = mongoClientDB[topic] topic = topic + '.xml' ...
994,492
7310d14b430dcb073ff437ad08cec5ffde9d0267
# Generated by Django 3.0 on 2021-08-17 15:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Rubro', fields=[ ...
994,493
e6cddc1daf75dbb0fa99137b5540b70d64708f49
""" Module to test api connections, very hacky """ import socket def send_message(m): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", 30030)) sock.sendall(m) sock.close() if __name__ == "__main__": send_message("hello world")
994,494
1e07a59c76e055b7b42871cd9219298d8355681d
import logging from jmeter_api.basics.assertion.elements import BasicAssertion from jmeter_api.basics.utils import Renderable, tree_to_str class JSONAssertion(BasicAssertion, Renderable): root_element_name = 'JSONPathAssertion' def __init__(self, *, validation: bool = False, ...
994,495
b19208916ffa3df83beba14f26041801661f6ea2
NONE = ' ' BLACK = 'B' WHITE = 'W' class GameState: def __init__(self, col, row,turn, position): self._rows = row self._cols = col self._board = self.new_game_board() self._turn = turn self.set_piece(position.lower()) self._blacks = 0 self._whites...
994,496
cb64773561e2105dbd2b4f91d1fafa5104f60f75
def combine_csv( input_csvs, output_csv, header_lines = 1 ): ''' Combine a list of CSV files specified in input_csvs into a single output csv in output_csv. It is assumed that all CSVs have the same header structure. The number of header lines is specified in header_lines ''' with o...
994,497
6ba1b37cb2f400e0cf9463602f4070cd9cec06aa
# -*- coding: utf-8 -*- """ Created on Tue Sep 12 09:32:33 2017 @author: jinjianfei """ import re """测试正则表达式""" #test = ['4.45行权','5.23到期','5.00行权(散量)','5.23(到期)','5.23(行权)','5.23(行权)','5.23(行权)三两','5.23'] test = ['','\n','\t'] test = ['5','5.0','5.01','5.011','5.0111'] for i in test: # if re.matc...
994,498
5799334684ceddde81501b938a126541a4bf6d09
import cocos from game.visualizer.load import load, find_image class LoadingLayer(cocos.layer.Layer): def __init__(self, assets, post_method): super().__init__() self.assets = assets self.post_method = post_method loading_image = cocos.sprite.Sprite( find_image('game...
994,499
f1354fc8a7699cd7d683ed985d7c52b77734e703
# encoding: utf-8 from psi.app import const from psi.app.service import Info from flask_security import UserMixin from sqlalchemy import ForeignKey, Integer from sqlalchemy.orm import relationship from psi.app.models.data_security_mixin import DataSecurityMixin db = Info.get_db() class User(db.Model, UserMixin, Dat...