index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
3,800
781ce153d5053078ee11cecc13d055a67999a651
# -*- coding: utf-8 -*- from flask import jsonify from flask.views import MethodView class Users(MethodView): def get(self): return jsonify( { 'status': 'OK', 'users': [ {'name': 'Pepe', 'age': 35, 'ocupation': "Engineer"}, ...
3,801
50c7ce95f17cbd40a753d16d9f9fab349ad4f4ce
""" 100 4 200 1 3 2 100 4 200 1 3 2 6:35 """ class Solution: def longestConsecutive(self, nums: List[int]) -> int: numset = set(nums) ans = 0 # visited = set(nums) maxnum = float('-inf') if not nums: return 0 for n in numset: ...
3,802
15eed401728e07bfe9299edd12add43ad8b9cb71
# -*- coding: utf-8 -*- import luigi from luigi import * #from luigi import Task import pandas as pd from pset.tasks.embeddings.load_embeding import EmbedStudentData from pset.tasks.data.load_dataset import HashedStudentData import numpy as npy import pickle import os class NearestStudents(Task): github_id = Par...
3,803
b713e38824db13f919484b071fb35afb29e26baa
import os,sys parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,parentdir) import xmind from xmind.core.markerref import MarkerId xmind_name="数据结构" w = xmind.load(os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind") s2=w.createSheet() s2.setTitle("二叉树——递归套路")...
3,804
9f479ad2acf4f6deb0ca4db606c3d804979c10bd
from rllab.algos.trpo import TRPO from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline from rllab.envs.gym_env import GymEnv from rllab.envs.normalized_env import normalize from rllab.misc.instrument import run_experiment_lite from rllab.policies.gaussian_mlp_policy import GaussianMLPPolicy from rl...
3,805
e807cef534226f3efb4a8df471598727fa068f02
# -*- python -*- # ex: set syntax=python: # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # See master.experimental/slaves.cfg for documentation. slaves = [ #########################################...
3,806
f561846c943013629e417d16f4dae77df43b25c4
from flask_sqlalchemy import SQLAlchemy from flask_security import UserMixin, RoleMixin db = SQLAlchemy() roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): ...
3,807
a4697f0a0d0cc264b28a58bcc28528c221b4cb49
import os import datetime from classifier import Classification class PersistableClassificationModel(Classification): """ Classification classifier with ability to persist trained classifier on the disk. """ def __init__(self, output_dir, origin): self.originModel = origin if not os...
3,808
167c36627c7c3377266bde266e610792ba29b3e4
import re #lines = open("input.1").read() lines = open("input.2").read() lines = lines.splitlines() moves = {} moves["nw"] = [-1, -1] moves["ne"] = [ 0, -1] moves["w"] = [-1, 0] moves["e"] = [ 1, 0] moves["sw"] = [ 0, 1] moves["se"] = [ 1, 1] tiles = {} def fliptile(tile): if tile == "B": tile = "...
3,809
1a8c9be389aad37a36630a962c20a0a36c449bdd
def func(i): if(i % 2 != 0): return False visited = [0,0,0,0,0,0,0,0,0,0] temp = i while(i): x = i%10 if (visited[x] == 1) or (x == 0): break visited[x] = 1; i = (int)(i / 10); if(i == 0): for y in str(temp): if(temp % int(y) != 0): return False else: return False...
3,810
dae8529aa58f1451d5acdd6607543c202c3c0c66
#### #Some more on variables #### #Variables are easily redefined. #Let's start simple. x=2 #x is going to start at 2 print (x) x=54 #we are redefining x to equal 54 print (x) x= "Cheese" #x is now the string 'cheese' print (x) #Try running this program to see x #printed at each point #Clearly variables can be...
3,811
ae6cbb181e024b8c0b222d14120b910919f8cc81
"""Restaurant""" def main(): """Restaurant""" moeny = int(input()) service = moeny*0.1 vat = moeny*0.07 print("Service Charge : %.2f Baht" %service) print("VAT : %.2f Baht" %vat) print("Total : %.2f Baht" %(moeny+vat+service)) main()
3,812
e15524d7ae87cbf0b10c54ee0bdc613ba589c1a9
from Cars import Bmw from Cars import Audi from Cars import Nissan # Press the green button in the gutter to run the script. if __name__ == '__main__': print('In Sample.py........') # Import classes from your brand new package # Create an object of Bmw class & call its method ModBMW = Bmw.Bmw() ...
3,813
9081d0f75ac53ab8d0bafb39cd46a2fec8a5135f
from django import forms from .models import Profile class ImageForm(forms.ModelForm): userimage = forms.ImageField(required=False, error_messages={'invalid':("Image file only")}, widget=forms.FileInput) class Meta: model = Profile fields = ['userimage',]
3,814
9725c4bfea1215e2fb81c31cbb8948fd1656aca9
from airbot import resolvers from airbot import utils import unittest from grapher import App import pprint OPENID_CONFIG = { 'ISSUER_URL': 'https://dev-545796.oktapreview.com', 'CLIENT_ID': '0oafvba1nlTwOqPN40h7', 'REDIRECT_URI': 'http://locahost/implicit/callback' } class TestEndToEnd(unittest.TestCas...
3,815
aea92827753e12d2dc95d63ddd0fe4eb8ced5d14
#!/usr/bin/env python # coding: utf-8 # In[2]: from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU'))) # In[1]: import numpy as np import pandas as pd import matplotlib.pypl...
3,816
e03290746d6520fde63836e917f6af0c76596704
# find the 12-digit number formed by concatenating a series of 3 4-digit # numbers who are permutations of each other and are all prime from itertools import permutations, dropwhile from pe_utils import prime_sieve prime_set = set(prime_sieve(10000)) def perm(n, inc): perm_set = set(map(lambda x: int("".join(x))...
3,817
8ce2e9cd9ceed6c79a85682b8bc03a3ffb5131c4
""" This module provides an optimizer class that is based on an evolution strategy algorithm. """ import copy, random, math from time import time from xml.dom import minidom from extra.schedule import Schedule from extra.printer import pprint, BLUE class Optimizer(object): """ This class is the implementation of the...
3,818
f379092cefe83a0a449789fbc09af490081b00a4
from igbot import InstaBot from settings import username, pw from sys import argv def execute_script(InstaBot): InstaBot.get_unfollowers() #InstaBot.unfollow() #InstaBot.follow() #InstaBot.remove_followers() def isheadless(): if len(argv) > 1: if argv[1] == 'head': return False else: raise ValueError("...
3,819
2b8b502381e35ef8e56bc150114a8a4831782c5a
class Solution(object): def maxDistToClosest(self, seats): """ :type seats: List[int] :rtype: int """ start = 0 end = 0 length = len(seats) max_distance = 0 for i in range(len(seats)): seat = seats[i] if seat ==...
3,820
a5559ff22776dee133f5398bae573f515efb8484
# MINISTを読み込んでレイヤーAPIでCNNを構築するファイル import tensorflow as tf import numpy as np import os import tensorflow as tf import glob import numpy as np import config as cf from data_loader import DataLoader from PIL import Image from matplotlib import pylab as plt dl = DataLoader(phase='Train', shuffle=True) X...
3,821
3acbb37809462ee69ff8792b4ad86b31dba5d630
#!/usr/bin/env python2.7 from __future__ import print_function, division import numpy as np import matplotlib import os #checks if there is a display to use. if os.environ.get('DISPLAY') is None: matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.colors as clr import dtk import sys import ti...
3,822
2ba5cb1265090b42b9a4838b792a3e81b209ba1a
import unittest import A1 import part_manager import security class test_A1(unittest.TestCase): # ----------------------------------- set up the mock data for test cases ----------------------------------- def setUp(self): self.security1 = security.Security("XXX-1234-ABCD-1234", None) self...
3,823
726aaa0ef129f950e6da6701bb20e893d2f7373b
import os import numpy as np from argparse import ArgumentParser from tqdm import tqdm from models.networks import Perceptron from data.perceptron_dataset import Dataset, batchify from utils.utils import L1Loss, plot_line from modules.perceptron_trainer import Trainer if __name__ == '__main__': parser = Argumen...
3,824
65d08fe1a3f6e5cc2458209706307513d808bdb2
#!/usr/bin/env python import os import sys #from io import open import googleapiclient.errors import oauth2client from googleapiclient.errors import HttpError from . import auth from . import lib debug = lib.debug # modified start def get_youtube_handler(): """Return the API Youtube object.""" ...
3,825
7531480f629c1b3d28210afac4ef84b06edcd420
# coding=utf-8 # __author__ = 'lyl' import json import csv import sys reload(sys) sys.setdefaultencoding('utf-8') def read_json(filename): """ 读取json格式的文件 :param filename: json文件的文件名 :return: [{}, {}, {}, {}, {},{} ......] """ return json.loads(open(filename).read()) def...
3,826
68c9944c788b9976660384e5d1cd0a736c4cd0e6
import drawSvg import noise import random import math import numpy as np sizex = 950 sizey = 500 noisescale = 400 persistence = 0.5 lacunarity = 2 seed = random.randint(0, 100) actorsnum = 1000 stepsnum = 50 steplenght = 2 noisemap = np.zeros((sizex, sizey)) for i in range(sizex): for j in range(sizey): n...
3,827
d71ffd022d87aa547b2a379f4c92d767b91212fd
from channels.db import database_sync_to_async from django.db.models import Q from rest_framework.generics import get_object_or_404 from main.models import UserClient from main.services import MainService from .models import Message, RoomGroup, UsersRoomGroup class AsyncChatService: @staticmethod @database_s...
3,828
08ed57ffb7a83973059d62f686f77b1bea136fbd
from flask import Flask, request, render_template, redirect from stories import Story, stories # from flask_debugtoolbar import DebugToolbarExtension app = Flask(__name__) # app.config['SECRET_KEY'] = "secret" # debug = DebugToolbarExtension(app) # my original approach involved using a global story variable to sto...
3,829
6336b31e51f0565c6b34ab5148645748fe899541
import copy import pandas as pd import numpy as np from pandas import DataFrame from collections import Counter from sklearn.metrics import roc_auc_score, roc_curve from statsmodels.stats.outliers_influence import variance_inflation_factor class Get_res_DataFrame: ''' sheet1:数据概况 sheet2:变量的大小,效果,相关性 ok ...
3,830
85e5bf57f7eba2cbee0fbb8a4d37b5180208f9b7
# -*- coding: utf-8 -*- from odoo import fields, models class LunchWizard(models.TransientModel): _name = "lunch.wizard" _description = "LunchWizard" lun_type = fields.Char(string="Set New Lunch Type") lunch_id = fields.Many2one('lunch.lunch', string="Lunch Id") def action_process_lunch(self):...
3,831
53eb1dcd54ce43d9844c48eb1d79f122a87dca39
from selenium.webdriver import Chrome path=("/Users/karimovrustam/PycharmProjects/01.23.2020_SeleniumAutomation/drivers/chromedriver") driver=Chrome(executable_path=path) driver.maximize_window() driver.get("http://www.toolsqa.com/iframe-practice-page/") # driver.switch_to.frame("iframe2") # When working with few wi...
3,832
99c12e925850fe7603831df5b159db30508f4515
from coarsegrainparams import * from inva_fcl_stab import * from Eq import * from Dynamics import * from sympy import Matrix,sqrt def construct_param_dict(params,K_RC,K_CP,m_P): """ Construct all the parameters from its relationships with body size and temperature, using the normalizing constants and scaling e...
3,833
91eb0ae8e59f24aeefdabd46546bc8fb7a0b6f6c
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.feature_selection import SelectKBest, chi2 from sklearn import metrics, ensemble, linear_model, svm from numpy import log, ones, array, zeros, mean, std, repeat import numpy as np import scipy.sparse as sp import re import csv fro...
3,834
7251d32918b16166e9b7c9613726e6dc51d6fea4
from sqlalchemy import (Column, Integer, Float, String, ForeignKey) from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import relationship from .meta import Base, BaseModel class Stock(Base, BaseModel): __tablename__ = 'stock' name = Column(String(255), nullable=False) starting_price = ...
3,835
429af603bf8f1c003799c3d94c0ce9a2c2f80dfc
class Solution(object): def sortArrayByParityII(self, A): """ :type A: List[int] :rtype: List[int] """ i = 0 for j in range(1, len(A), 2): if A[j] % 2 == 1: continue else: while i + 2 < len(A) and A[i] % 2 == 0:...
3,836
b07073a7f65dbc10806b68729f21a8bc8773a1ab
#!/usr/bin/env python from math import ceil, floor, sqrt def palindromes(n: int) -> int: """yield successive palindromes starting at n""" # 1 -> 2 -> 3 ... 9 -> 11 -> 22 -> 33 -> 44 .. 99 -> 101 # 101 -> 111 -> 121 -> 131 -> ... -> 191 -> 202 -> 212 # 989 -> 999 -> 1001 -> 1111 -> 1221 # 9889 -> 9...
3,837
2539411c7b348662dbe9ebf87e26faacc20f4c5e
import numpy as np import math import os if os.getcwd().rfind('share') > 0: topsy = True import matplotlib as mpl mpl.use('Agg') else: topsy = False from matplotlib import rc import matplotlib.pyplot as plt from matplotlib import rc from matplotlib import cm from scipy.optimize import curve_fit import sys import h...
3,838
63a2c8b0c2eba2d5f9f82352196ef2b67d4d63b5
inp = int(input()) print(bytes(inp))
3,839
7bf81954bef81004b6c9838ed00c624d24fcf0c6
# Generated by Django 2.0.3 on 2018-07-05 04:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('application_manager', '0015_auto_20180705_0415'), ] operations = [ migrations.RemoveField( model_name='application', name='u...
3,840
4d707e23f66e8b6bea05a5901d3d8e459247c6c1
import cv2 import sys # Load the Haar cascades face_cascade = cv2.CascadeClassifier('./haar_cascades/haarcascade_frontalface_default.xml') eyes_cascade = cv2.CascadeClassifier('./haar_cascades/haarcascade_eye.xml') capture = cv2.VideoCapture(0) _, image = capture.read() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ...
3,841
791df87235f5da634fc62ebc3a3741cea6e2deca
def summation(numbers): positive_numbers = [] normalized_numbers = [] numbers_list = numbers.split() for idx, arg in enumerate(numbers_list): int_arg = int(arg) if int_arg < 0: new_arg = abs(int_arg) * 2 else: new_arg = int_arg positive_numbers.app...
3,842
c179d27f1620414061d376d4f30d2ddd4fd2750e
import sys, serial, time, signal, threading from MFRC522 import MFRC522 from event import Event class Sensor(threading.Thread): # main program for reading and processing tags def __init__(self, name): threading.Thread.__init__(self) self.name = name self.continue_reading = False self.tag_reader = MFRC522() ...
3,843
bee6ba1db608c1d9c8114f89d4b3abab795a6b86
from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import config import os db = SQLAlchemy() static_file_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static') def create_app(config_name): app = Flask(__name__, static_folder=static_file_dir) app.config.from_object...
3,844
38abc4bc99f3b15b416c77481818464a6c7f11ef
import mysql.connector from mysql.connector import errorcode DB_NAME = 'PieDB' TABLES = {} # TABLES['pietweets'] = ( # "CREATE TABLE `pietweets` (" # " `id` int NOT NULL AUTO_INCREMENT," # " `tweet_id` bigint NOT NULL," # " `username` varchar(32) NOT NULL," # " `geo_lat` float(53) NOT NULL," # " `geo_lon...
3,845
9f3b7d6dbf57157b5ebd6ad72f46befc94798a5f
def count_words(word): count = 0 count = len(word.split()) return count if __name__ == '__main__': print count_words("Boj is dope")
3,846
d0d86d8b5b276218add6dd11a44d5c3951cc4e14
from django.db.models import Q from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from carga_horaria.models import Profesor, Asignat...
3,847
ad1aa69f92f104ac8b82aca3c0a64ce3de48b36d
# Copyright (c) 2021 Koichi Sakata from pylib_sakata import init as init # uncomment the follows when the file is executed in a Python console. # init.close_all() # init.clear_all() import os import shutil import numpy as np from control import matlab from pylib_sakata import ctrl from pylib_sakata import plot prin...
3,848
599c5c02397f283eb00f7343e65c5cb977442e38
from django import forms from .models import Project from user.models import User from assets.models import Assets class CreateProjectForm(forms.ModelForm): project_name = forms.CharField( label='项目名', widget=forms.TextInput( attrs={"class": "form-control"} ) ) project_...
3,849
dabc38db6a5c4d97e18be2edc9d4c6203e264741
from django import forms from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import time from page.models import Submit, Assignment class UploadFileForm(forms.ModelForm): class Meta: model = Submit fields = ['email', 'student_no', 'file'] @csrf_exempt def up...
3,850
2fd40f4d69223933d53d8ed2abd5f6d3ccd2f509
from django.shortcuts import render from django.views.generic.base import View from .models import Article, Tag, Category from pure_pagination import Paginator, EmptyPage, PageNotAnInteger class ArticleView(View): '''文章详情页''' def get(self, request, article_id): # 文章详情 article = Article.object...
3,851
5da61b4cd8e4faf135b49396d3b346a219bf73f6
import os from src.model_manager import ModelManager dir_path = os.path.dirname(os.path.realpath(__file__)) config_file = '{}/data/config/config_1.json'.format(dir_path) model_dir = '{}/data/models'.format(dir_path) def test_init(): mm = ModelManager(config_file, model_dir) def test_predict(): pass
3,852
5a2106f5255493d2f6c8cb9e06a2666c8c55ed38
""" Suffix Arrays - Optimized O(n log n) - prefix doubling A suffix is a non-empty substring at the end of the string. A suffix array contains all the sorted suffixes of a string A suffix array provides a space efficient alternative to a suffix tree which itself is a compressed version of a trie. Suffix array can do ...
3,853
44e9fd355bfab3f007c5428e8a5f0930c4011646
from flask import Flask, jsonify, abort, make_response from matchtype import matchtyper from db import db_handle import sys api = Flask(__name__) @api.route('/get/<key_name>', methods=['GET']) def get(key_name): li = db_handle(key_name) if li[1] is None: abort(404) else: result = matchtype...
3,854
f87d08f3bb6faa237cce8379de3aaaa3270a4a34
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from rasa_core.actions.action import Action from rasa_core.events import SlotSet from rasa_core.dispatcher import Button, Element, Dispatcher import json import pickle class ActionWeather(Action): def na...
3,855
309090167c2218c89494ce17f7a25bd89320a202
from google.appengine.api import users from google.appengine.ext import ndb from datetime import datetime from datetime import timedelta import os import logging import webapp2 import jinja2 JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2....
3,856
6162911befc8ad37591f7c19b14b349c655ccac0
def generator(factor, modulus=-1, maxx=2147483647): def next(prev): nxt = (prev*factor) % maxx if modulus > 0: while nxt % modulus != 0: nxt = (nxt * factor) % maxx return nxt return next def main(a, b, a_mod=-1, b_mod=-1, N=40000000, a_fact=16807, b_fact=48...
3,857
fc9742ceb3c38a5f8c1ad1f030d76103ba0a7a81
# Generated by Django 3.2.7 on 2021-09-23 07:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sms_consumer', '0006_auto_20210923_0733'), ] operations = [ migrations.RemoveField( model_name='smslogmodel', name='hello', ...
3,858
e6c7b15e5b42cfe6c5dec2eaf397b67afd716ebd
myfavoritenumber = 5 print(myfavoritenumber) x=5 x=x+1 print(x) x,y,z=1,2,3 print(x,y,z)
3,859
03e92eae4edb4bdbe9fa73e39e7d5f7669746fe5
from integral_image import calc_integral_image class Region: def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height def calc_feature(self, cumul_sum): yy = self.y + self.height xx = self.x + self.width ...
3,860
921c45af3ba34a1b12657bf4189fc8dd66fa44a6
import tensorflow as tf import numpy as np import tensorflow_datasets as tfds print(tf.__version__) imdb, info = tfds.load("imdb_reviews", with_info=True, as_supervised=True) train_data = imdb['train'] test_data = imdb['test'] # 25000 in each set training_sentences = [] training_labels = [] testing_sentences = [] ...
3,861
88071df9367804b1c6e2b1c80da178ab7658e7a4
# Copyright (c) 2018, Raul Astudillo import numpy as np from copy import deepcopy class BasicModel(object): """ Class for handling a very simple model that only requires saving the evaluated points (along with their corresponding outputs) so far. """ analytical_gradient_prediction = True def __in...
3,862
d0997f5001090dd8925640cd5b0f3eb2e6768113
#!/usr/bin/env python from pymongo import MongoClient import serial import sys, os, datetime os.system('sudo stty -F /dev/ttyS0 1200 sane evenp parenb cs7 -crtscts') SERIAL = '/dev/ttyS0' try: ser = serial.Serial( port=SERIAL, baudrate = 1200, parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ON...
3,863
f2abb7ea3426e37a10e139d83c33011542e0b3d1
from .menu import menu from .create_portfolio import create_portfolio from .search import search from .list_assets import list_assets from .add_transaction import add_transaction from .stats import stats from .info import info
3,864
0402096f215ae600318d17bc70e5e3067b0a176b
from django.core.paginator import Paginator, EmptyPage from django.shortcuts import render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from logging import getLogger from django_redis import get_redis_connection from decimal import Decimal import json from django import http f...
3,865
62d0818395a6093ebf2c410aaadeb8a0250707ab
# This is a generated file, do not edit from typing import List import pydantic from ..rmf_fleet_msgs.DockParameter import DockParameter class Dock(pydantic.BaseModel): fleet_name: str = "" # string params: List[DockParameter] = [] # rmf_fleet_msgs/DockParameter class Config: orm_mode = True...
3,866
47cee0c659976a2b74e2bb07f6c4d622ceab7362
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
3,867
3b4799f43ec497978bea3ac7ecf8c6aaeb2180b4
# coding: utf8 from __future__ import absolute_import import numpy as np def arr2str(arr, sep=", ", fmt="{}"): """ Make a string from a list seperated by ``sep`` and each item formatted with ``fmt``. """ return sep.join([fmt.format(v) for v in arr]) def indent_wrap(s, indent=0, wrap=80): "...
3,868
4c3a27bf1f7e617f4b85dc2b59efa184751b69ac
import os from redis import Redis try: if os.environ.get('DEBUG'): import settings_local as settings else: import settings_prod as settings except ImportError: import settings redis_env = os.environ.get('REDISTOGO_URL') if redis_env: redis = Redis.from_url(redis_env) elif getattr(se...
3,869
0588aad1536a81d047a2a2b91f83fdde4d1be974
from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'index'), path('about/', views.about, name='about'), path('contact/', views.contact, name= 'contact'), path('category/', views.category, name='category'), path('product/<str:id>/<slug:slug>',views.product...
3,870
bd2a5c2dd3eef5979c87a488fb584dce740ccb05
import io import os import sys import whwn from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand here = os.path.abspath(os.path.dirname(__file__)) with open('README.md') as readme: long_description = readme.read() with open('requirements.txt') as reqs: install_re...
3,871
e5e460eb704e2ab5f747d1beee05e012ea95fbd2
class UnknownResponseFormat(Exception): pass
3,872
283b93437072f0fd75d75dab733ecab05dc9e1f3
#!/usr/bin/env python3 import logging import datetime import os import time import json import prod import secret from logging.handlers import RotatingFileHandler import requests import sns from kafka import KafkaProducer logger = logging.getLogger() logger.setLevel('INFO') log_path = os.path.basename(__file__).split...
3,873
d90aeaaa682b371afb4771ecfbf1077fc12520b4
from django.contrib import admin # Register your models here. from django.contrib import admin from practice_app.models import Person class PersonAdmin(admin.ModelAdmin): pass admin.site.register(Person)
3,874
2ae953d1d53c47da10ea4c8aace186eba0708ad0
# Copyright (c) 2012, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np import pylab as pb from .. import kern from ..core import model from ..util.linalg import pdinv,mdot from ..util.plot import gpplot,x_frame1D,x_frame2D, Tango from ..likelihoods import E...
3,875
55a392d63838cbef027f9cf525999c41416e3575
import torch from torch import nn from torch.nn import functional as F from models.blocks import UnetConv3, MultiAttentionBlock, UnetGridGatingSignal3, UnetUp3_CT, UnetDsv3 class AttentionGatedUnet3D(nn.Module): """ Attention Gated Unet for 3D semantic segmentation. Args: config: Mus...
3,876
bd2c327915c1e133a6e7b7a46290369440d50347
#import fungsi_saya as fs # from fungsi_saya import kalkulator as k # hasil = k(10,5,'+') # print(hasil) from kelas import Siswa siswa_1 = Siswa('Afif', "A.I.", 17, 'XII IPA') siswa_2 = Siswa('Bayu', 'Sudrajat', 20, 'XII IPS') siswa_3 = Siswa('Bayu', 'Sudrajat', 20, 'XII IPS') siswa_4 = Siswa('Bayu', 'Sudrajat', 20,...
3,877
a7f348b258e1d6b02a79c60e4fe54b6d53801f70
# coding=utf-8 """ author: wlc function: 百科检索数据层 """ # 引入外部库 import json import re from bs4 import BeautifulSoup # 引入内部库 from src.util.reptile import * class EncyclopediaDao: @staticmethod def get_key_content (key: str) -> list: """ 获取指定关键字的百科内容检索内容 :param key: :return: """ # 1.参数设置 url = 'https://...
3,878
03da813650d56e7ab92885b698d4af3a51176903
import datetime with open('D:\Documents\PythonDocs\ehmatthes-pcc-f555082\chapter_10\programming.txt') as f_obj: lines = f_obj.readlines() m_lines = [] for line in lines: m_line = line.replace('python', 'C#') m_lines.append(m_line) with open('D:\Documents\PythonDocs\ehmatthes-pcc-f555082\chapter_10\prog...
3,879
a85d06d72b053b0ef6cb6ec2ba465bfb8975b28e
def sum_numbers(numbers=None): sum = 0 if numbers == None: for number in range(1,101): sum += number return sum for number in numbers: sum += number return sum
3,880
1b645ab0a48b226e26009f76ea49fd3f10f5cc7b
#デフォルト引数の破壊 #以下、破壊的な操作 def sample(x, arg=[]): arg.append(x) return arg print(sample(1)) print(sample(2)) print(sample(3)) #対策・・・デフォルト引数にはイミュータブルなものを使用する def sample(x, arg=None): if arg is None: arg = [] arg.append(x) return arg print(sample(1)) print(sample(2)) pr...
3,881
d724b4f57cf7683d6b6385bf991ed23a5dd8208f
"""added Trail.Geometry without srid Revision ID: 56afb969b589 Revises: 2cf6c7c1f0d7 Create Date: 2014-12-05 18:13:55.512637 """ # revision identifiers, used by Alembic. revision = '56afb969b589' down_revision = '2cf6c7c1f0d7' from alembic import op import sqlalchemy as sa import flask_admin import geoalchemy2 de...
3,882
84e84d9f35702c2572ad5e7daa92a271674986dc
#Coded by J. Prabhath #14th April, 2020 #Released under GNU GPL import numpy as np import matplotlib.pyplot as plt from scipy import signal K = 96 Kp = 1 Td = 1.884 s1 = signal.lti([-1/Td],[0,-2,-4,-6], K) s2 = signal.lti([],[0,-2,-4,-6], K) w,mag1,phase1 = signal.bode(s1) _,mag2,phase2 = signal.bode(s2) plt.xlabel...
3,883
e2948c0ad78ce210b08d65b3e0f75d757e286ad9
# 在写Python爬虫的时候,最麻烦的不是那些海量的静态网站,而是那些通过JavaScript获取数据的站点。Python本身对js的支持就不好,所以就有良心的开发者来做贡献了,这就是Selenium,他本身可以模拟真实的浏览器,浏览器所具有的功能他一个都不拉下,加载js更是小菜了 # https://zhuanlan.zhihu.com/p/27115580 # C:\Users\hedy\AppData\Local\Programs\Python\Python36\Scripts\;C:\Users\hedy\AppData\Local\Programs\Python\Python36\ # pip 换源 # http://...
3,884
7e71c97070285b051b23448c755e3d41b2909dda
class Solution(object): def removeNthFromEnd(self, head, n): dummy = ListNode(-1) dummy.next = head first, second = dummy, dummy for i in range(n): first = first.next while first.next: first = first.next second = second.next second....
3,885
b0a51877b59e14eefdd662bac468e8ce12343e6b
from django.db import models # Create your models here. class Glo_EstadoPlan(models.Model): descripcion_estado = models.CharField(max_length=100) def __str__(self): return '{}'.format(self.descripcion_estado)
3,886
22b9868063d6c5fc3f8b08a6e725fff40f4a1a03
from __future__ import annotations import math from abc import abstractmethod from pytown_core.patterns.behavioral import Command from pytown_core.serializers import IJSONSerializable from .buildings import BuildingProcess, BuildingTransaction from .buildings.factory import BuildingFactory from .check import ( A...
3,887
cc1b3c3c65e8832316f72cbf48737b21ee4a7799
########################################################################### # This file provides maintenance on the various language files # 1. Create new "xx/cards_xx.json" files that have entries ordered as: # a. the card_tag entries in "cards_db.json" # b. the group_tag entries as found in "cards_db.json" # ...
3,888
263347d1d445643f9c84e36a8cbb5304581ebaf6
from django.urls import path from django.views.decorators.csrf import csrf_exempt from .views import TestView, index, setup_fraud_detection, verify_testing_works urlpatterns = [ path('test/<str:name>/', index, name='index'), path('ml/setup/', setup_fraud_detection, name='fraud_detection_setup'), path('ml/...
3,889
8c458d66ab2f9a1bf1923eecb29c3c89f2808d0b
''' www.autonomous.ai Phan Le Son plson03@gmail.com ''' import speech_recognition as sr import pyaudio from os import listdir from os import path import time import wave import threading import numpy as np import BF.BeamForming as BF import BF.Parameter as PAR import BF.asr_wer as wer import BF.mic_array_read as READ i...
3,890
606a6e7ecc58ecbb11aa53602599e671514bc537
import torch.utils.data import torch import math from util.helpers import * from collections import defaultdict as ddict class _Collate: def __init__(self, ): pass def collate(self, batch): return torch.squeeze(torch.from_numpy(np.array(batch))) class PR: dataset = None eval_data = N...
3,891
d133a07f69d2dadb5559d881b01050abb2a9602b
#!/usr/bin/env python # ! -*- coding: utf-8 -*- ''' @Time : 2020/6/4 16:33 @Author : MaohuaYang @Contact : maohuay@hotmail.com @File : pinganFudan-GUI.py @Software: PyCharm ''' import time import requests import tkinter as tk from login import Ehall def set_win_center(root, curWidth='', curHight=''): """ ...
3,892
1dab0084666588f61d0f9f95f88f06ed9d884e5b
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'KEY.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_KEY(object): def setupUi(self, KEY): KEY.setObjectName("KEY") ...
3,893
bfd8385e8f4886b91dde59c04785134b9cd6a2b6
# Generated by Django 3.1 on 2020-08-28 14:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api_rest', '0004_auto_20200828_0749'), ] operations = [ migrations.RemoveField( model_name='event', name='user_id', ...
3,894
e4a0f26afe8c78e4abbd85834c96ed5ba84e1f0b
import tensorflow as tf import numpy as np import math import sys import os import numpy as np BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, '../utils')) import tf_util # from transform_nets import input_transform_net, feature_transform_net import...
3,895
c8d27965df83eb3e673b3857ee700a8474826335
#!/usr/bin/python debug = 0 if debug == 1: limit = [8,20] n = 3 p = [[2,10],[10,12],[8,30],[1,5]] #n = 1 # p = [[8,30]] print limit print n print p def isIn(arr): if arr[0] > limit[1] or arr[1] < limit[0] or \ arr[1] == 0: return False else: return True ...
3,896
0f3e12f35cc29a71be5b8e6d367908e31c200c38
from numpy import * from numpy.linalg import* preco = array(eval(input("Alimentos: "))) alimento = array([[ 2, 1 ,4 ], [1 , 2 , 0], [2 , 3 , 2 ]]) r = dot(inv(alimento),preco.T) # print("estafilococo: ", round(r[0] , 1)) print("salmonela: ", round(r[1], 1)) print("coli: ", round(r[2], 1)) if r[0] ...
3,897
bc1aefd0b0a87b80a10cecf00407b4608a6902b5
# # cuneiform_python.py # # Example showing how to create a custom Unicode set for parsing # # Copyright Paul McGuire, 2021 # from typing import List, Tuple import pyparsing as pp class Cuneiform(pp.unicode_set): """Unicode set for Cuneiform Character Range""" _ranges: List[Tuple[int, ...]] = [ (0x10...
3,898
2874e05d6d5e0f13924e5920db22ea3343707dfa
_base_ = [ '../models/cascade_rcnn_r50_fpn.py', #'coco_instance.py', '../datasets/dataset.py', '../runtime/valid_search_wandb_runtime.py', '../schedules/schedule_1x.py' ] pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth' # noqa model...
3,899
4d7696c832f9255fbc68040b61fde12e057c06fa
import numpy as np import mysql.connector from mysql.connector import Error import matplotlib.pyplot as plt def readData(): connection = mysql.connector.connect(host='localhost',database='cad_ultrasound',user='root',password='') sql_select_Query = "SELECT id_pasien,nama,pathdata FROM datasets" cu...