text stringlengths 38 1.54M |
|---|
"""webserver URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
C... |
#coding:utf-8
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
import hashlib
#class MyUserManager(BaseUserManager):
# # 创建用户
# def create_user(self, e... |
import pickle
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import xlrd , xdrlib
from math import radians, cos, sin, asin, sqrt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer
from sklearn.model_selection import train_... |
"""
Copyright (c) 2017 Wind River Systems, 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 in wr... |
import socket
from threading import RLock, Event
import time
import struct
class SimulationTimeOracle:
CURRENT_SIM_TIME = 0
LOCK = RLock()
def __init__(self, _receive_port, _respond_port, socket_type = socket.SOCK_DGRAM):
self.sock_type = socket_type
self.receive_socket = socket.socket(s... |
from __future__ import absolute_import
import cmemcached
from zhwcore.common.rpc_proxy import RPCProxy
from zhwcore.utils.md5 import get_md5
mc_clients = {}
class MC(cmemcached.Client):
def __init__(self, servers, comp_threshold, comp_method):
super(MC, self).__init__(servers, comp_threshold, comp_metho... |
from django.urls import path
from .views import *
urlpatterns = [
path('',index,name="index"),
path('home',home,name='user-home'),
path('login',login,name="user-login"),
path('logout',Logout,name="user-logout"),
path('auth',auth,name="auth-new-user"),
path('register',register,name="user-register"),
path('sig... |
#coding: utf-8
u"""Sistema de mapeo de URLs.
copyright: Klan Estudio 2013 - klanestudio.com
license: GNU Lesser General Public License
author: Andrés Javier López <ajavier.lopez@gmail.com>
"""
class URL(object):
u"""Construye las URL de los nodos del API"""
def __init__(self):
u"""Inicializa el mapa ... |
#!/usr/bin/env python
import math,sys
PREFIX='B_DET_FTC_HV'
HEAD='''<?xml version="1.0" encoding="UTF-8"?>
<display typeId="org.csstudio.opibuilder.Display" version="1.0.0">
<auto_zoom_to_fit_all>false</auto_zoom_to_fit_all>
<macros>
<include_parent_macros>true</include_parent_macros>
</macros>
<wuid... |
import unittest, sys
sys.path.append('..')
from linkedlistintersection import Solution, ListNode
class TestLinkedListIntersection(unittest.TestCase):
def setUp(self):
self.s = Solution()
def test_get_intersection_node(self):
'''
CASE ONE - unique integers used
... |
#find kth max term term using bubble sort
def kth_Term(l,k):
#firstly sort array in assending order
for i in range(len(l)-1,0,-1):
for j in range(i):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
#find kth term in sorted array
max_kth_term=l[k-1]
print(f... |
from __future__ import absolute_import
from __future__ import unicode_literals
from website.settings import *
from website.settings.local import *
import os
# Django Haystack
HAYSTACK_WHOOSH_PATH = os.path.join(PROJECT_PATH, 'index_woosh')
INSTALLED_APPS += ['haystack', 'wiki.plugins.haystack']
HAYSTACK_CONNECTIONS... |
from django.db import models
class QuickContact(models.Model):
# id = models.BigAutoField()
name = models.CharField(
max_length=50,
verbose_name="User name",
)
email = models.EmailField(
verbose_name="User email",
)
message = models.TextField(
verbose_name="Mess... |
def x1(x2,x3):
return (10 - 2*x2 - 3*x3)
def x2(x1,x3):
return ((13 - (2.0*x1) - (3.0*x3))/3)
def x3(x1,x2):
return (5 - x1 - x2)
def error(n,o):
return ((n-o)/n) * 100
#Nilai Awal
bx1, bx2, bx3 = 0,0,0
tabel = "{0:1} | {1:7} | {2:7} | {3:7} | {4:7} | {5:7} | {6:7}"
print(tabel.format("i", "X1", "X... |
# This function prints a pyramid
def make_pyramid(n):
k = n - 1 # for spaces
# loop for number of rows
for i in range(0, n):
# loop for number spaces
for j in range(0, k):
print(end=" ")
k -= 1
# loop for number of columns
for j in range(0, i+1):
print("* ", end="")
print("\r")
n = int(input(... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 14 09:34:28 2020
@author: ANANTA SRIKAR
"""
import pygame
from pygame import mixer
import random
import math
bullet_state = "ready"
restart = True
def main():
global restart
global bullet_state
shots = 0
pygame.init()
score = 0
red = (200,... |
import numpy as np
import matplotlib.pyplot as plt
from zad3 import RBFNet, rbf
approx_data_1 = np.loadtxt("approximation_train_1.txt")
approx_test = np.loadtxt("approximation_test.txt")
X = approx_data_1[:, 0]
y = approx_data_1[:, 1]
X_test = approx_test[:, 0]
y_test = approx_test[:, 1]
epochs = 100
X_pred = np.ara... |
# -*- coding: utf-8 -*-
# @Time : 2019\2\20 0020 9:34
# @Author : 凯
# @File : urls.py
from django.conf.urls import url
from . import views
app_name='axf'
urlpatterns = [
url(r'home/$', views.home, name='home'),
url(r'^market/$', views.market, name='market'),
url(r'^cart/$', views.cart, name='cart'),
... |
# Generated by Django 3.2.2 on 2021-05-09 14:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('loans', '0003_auto_20210509_1442'),
]
operations = [
migrations.AlterField(
model_name='loan',
name='edited_datetime... |
from pydantic import BaseModel
from datetime import datetime
TRAIN_TYPES = {
"SPR": "Sprinter",
"IC": "Intercity",
}
class Departure(BaseModel):
planned_departure_time: str
direction: str
platform: str
train_type: str
def format_date(value: str):
if value:
value, _ = value.split("... |
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack as sfft
import cv2
import os
from PIL import Image
output_path = "output\\"
input_path = "input\\"
#1dspect計算
def dim1_spect_func(abs_z):
print("---------dim1_spect()---------")
h,w = abs_z.shape
size = min(h,w)
cen... |
import scrapy
import pytz
import utility
from schedules.items import SchedulesItem
from DBUtil import *
DAYS_MAP = {
"mon": 0,
"tue": 1,
"wed": 2,
"thu": 3,
"fri": 4,
"sat": 5,
"sun": 6
}
class SenorSisigSpider(scrapy.Spider):
name = "senorsisig"
start_urls = ["http://www.senorsisig.com"]
def parse(self, ... |
import numpy as np
def normalized_sigmoid_fkt(a, b, x):
"""
Returns array of a horizontal mirrored normalized sigmoid function
output between 0 and 1
Function parameters a = center; b = width
"""
s = 1 / (1 + np.exp(b * (x - a)))
return s
|
#!/usr/bin/env python
# Copyright (C) 2017 Christopher M. Biwer
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# Th... |
import sys
"""
Laryngograph Waveform *.lar,
16bit 16kHz sample rate binary files with NIST headers.
"""
#fname = sys.argv[1]
fname = '/Users/gabrielsynnaeve/postdoc/datasets/MOCHA_TIMIT/msak0/msak0_001.lar'
# TODO
|
#!/usr/bin/ env anaconda3
from pVOG_tax import increment_pvog, get_tax_id, get_accensions
test_handle = open('VOGProteinTable.txt', 'r')
handle = test_handle.readlines()
pvogs = ['VOG0001','VOG0001','VOG0002','VOG0002','VOG0005','VOG0005','VOG0005','VOG0005','VOG0006','VOG0006','VOG0006']
test_accensions = {0:'NC_025... |
# Time: O(n)
# Space: O(n)
# Given a non-empty array of non-negative integers nums,
# the degree of this array is defined as the maximum frequency of any one of its elements.
#
# Your task is to find the smallest possible length of a (contiguous) subarray of nums,
# that has the same degree as nums.
#
# Example 1:
# ... |
import ipdb
import requests
from bs4 import BeautifulSoup
import time
import re
from bs4.element import Comment
class crawler:
def __init__(self):
super(crawler, self).__init__()
self.root_url = "https://www.ptt.cc"
self.init_url = "https://www.ptt.cc/bbs/Beauty/index.html"
self.hea... |
#!/usr/bin/env python
# encoding: utf-8
"""
Compiles per V:J stats and fold changes between samples.
"""
import sys
import itertools
import numpy as np
import pandas as pd
def scale_factors(df):
median = np.median(df.sum(0))
factors = {}
for name, total in df.sum(0).iteritems():
if total == median... |
#!/usr/bin/env python
# coding: utf-8
"""
Model based on :mod:`silx.gui.hdf5.Hdf5TreeModel`
"""
from silx.gui.hdf5 import Hdf5TreeModel
class TreeModel(Hdf5TreeModel):
def __init__(self, parent=None):
super(TreeModel, self).__init__(parent=parent)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
_author = 'Farsheed Ashouri'
'''
___ _ _
/ __\_ _ _ __ ___| |__ ___ ___ __| |
/ _\/ _` | '__/ __| '_ \ / _ \/ _ \/ _` |
/ / | (_| | | \__ \ | | | __/ __/ (_| |
\/ \__,_|_| |___/_| |_|\___|\___|\__,_|
Just remember: Each comme... |
import pytest
import os
global fichierSrc
fichierSrc = "./ressources/input.txt"
def isEmptyFile(fichierSrc):
if os.path.getsize(fichierSrc) == 0:
return True
return False
# vérifie si le fichier existe
def test_file_exist():
assert os.path.isfile(fichierSrc) == True
# Vérifie si le fichier est v... |
from math import pi
epsilon_0 = 8.8541878128E-12 # permittivity of free space (in C^2/Nm^2)
mu_0 = (4*pi)*1E-7 # permeability of free space (in N/A^2)
e = 1.602176634E-19 # electronic charge (in C)
c = 299792458 # speed of light (in m/s)
k_E = 1/(4*pi* epsilon_0) # constant in Coulomb's law (in Nm^2/C^2)
k_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 21:13:48 2021
@author: giraybalci
"""
print(max("asdvz xzzxcgf"))
print(len("This is a trial"))
#%%
import math
print(math)
decibels = 10 * math.log10(4)
print(decibels)
#%%
import random
for i in range(5):
r = random.random()
p... |
from typing import List
class Solution:
def lengthLongestPath(self, input: str) -> int:
paths: List[str] = input.split('\n')
path_lens: List[int] = []
max_length = 0
length = 0
for path in paths:
level = 0
for ch in path:
if ch == '\t... |
from typing import Tuple, List
import pytest
from src.game import Game
from src.board import Board, Cell
from types_ import Color, Move, Piece
@pytest.mark.parametrize(
"board, color, dice, expected_moves",
[
pytest.param(
Board.from_dict({0: Cell(1, Color.LIGHT)}),
Color.LIG... |
# Copyright (c) OpenMMLab. All rights reserved.
from .amp_optimizer_wrapper import AmpOptimWrapper
from .apex_optimizer_wrapper import ApexOptimWrapper
from .base import BaseOptimWrapper
from .builder import (OPTIM_WRAPPER_CONSTRUCTORS, OPTIMIZERS,
build_optim_wrapper)
from .default_constructor im... |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
import datetime
from oil_and_gas.settings import SERIALIZABLE_VALUE
import pycountry # for help :- https://pypi.python.org/pypi/pycountry
from pprint import pprint
from core.mod... |
import re
def generate_sku(input_string, iteration):
# Setting Iterations
if iteration == 0:
normal_initial = 3
lower_upper_case_initial = 2
elif iteration == 1:
normal_initial = 4
lower_upper_case_initial = 2
elif iteration == 2:
normal_initial = 5
lowe... |
import numpy as np
import tensorflow as tf
# import tf.keras.layers.Conv2D
from tensorflow import keras
import matplotlib.pyplot as plt
print(tf.__version__)
print(keras.__version__)
tf.enable_eager_execution()
image = tf.constant([[[[1], [2], [3]],
[[4], [5], [6]],
[[7], [8],... |
import os
from jinja2 import Environment, FileSystemLoader
from classes import Refeicao
PATH = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_ENVIRONMENT = Environment(
autoescape=False,
loader=FileSystemLoader(os.path.join(PATH, 'templates')),
trim_blocks=False)
def render_template(template_file... |
class Punkt:
def __init__(self, x, y):
self.x = x
self.y = y
def wypisz_punkt(self):
print("Jestem punktem o współrzędnych", str(self.x), str(self.y))
def __repr__(self):
return "Punkt: " + str(self.x) + " " + str(self.y)
class Trojkat:
def __init__(self, p1, p2, p3):... |
import sys
class Board(object):
""" Internal constants of the game of Tic Tac Toe. """
N = 3
CIRCLE = 1
EMPTY = 0
CROSS = 2
board = [[]]
def __init__(self):
self.board = [[Board.EMPTY for i in xrange(Board.N)] for i in xrange(Board.N)]
def clear_board(self):
for i in xrange(Board.N):
for j i... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 3 20:38:55 2020
@author: Willi
"""
# Run en linea de comandos: !streamlit run IRIS_APP.py
# EDA
import streamlit as st
import pandas as pd
#-------------------------------------------------------------
#Title
st.title("IRIS EDA ")
st.header("Strea... |
# -*- coding: utf8 -*-
import os.path
from twisted.internet import defer, utils, threads
from twisted.python import log
from nevow import appserver, inevow, static
import PIL.Image
from zope.interface import implements
# Binaries
IDENTIFY = '/usr/bin/identify'
CONVERT = '/usr/bin/convert'
class ImageResource(object)... |
import string
def newTrie():
trie={}
for letters in string.ascii_lowercase:
trie[letters]=[{},0]
return trie
def trieAddString(trie,string):
temp=trie
count=1
for letter in string:
if count==len(string):
temp[letter][1]+=1
if len(temp[letter][0])==0:
... |
#Retrieves 15 of the most recent tweets about 'underpants'
import urllib
import json
response = urllib.urlopen("http://search.twitter.com/search.json?q=underpants")
pyresponse = json.load(response)
#print pyresponse["results"]
results = pyresponse["results"]
for i in range(15):
print results[i]["text"]
|
#!/usr/bin/env python
# coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
plt.figure(1) # 创建图表1
x = np.linspace(0, 7, 600) # 在0--6范围之间,生成300个点
y1 = [10**z for z in x] # 得到 f(n) 函数的 y 值数组
nineM = reduce(lambda a, b : a * b, xrange(1, 10))
y2 = [nineM*z for z in x] # 得到 g(n) 函数的 y 值数组
plt.figure(1)
pl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pyspark import SparkConf
from pyspark.sql import SparkSession
"""
spark相关工具类
"""
class SparkUtils:
@staticmethod
def getSparkSession(name, **kw):
"""
获取spark会话实例
:param name:
:param kw:
:return:
"""
con... |
def onlineOrderMapping(online_order):
return online_order.map({"Yes": 1, "No":0})
def tableBookingMapping(book_table):
return book_table.map({"Yes": 1, "No":0}) |
import datetime
import json
import sqlite3
import joblib
import pandas as pd
from pandas.io import sql
from nw.loggers import logger
from nw.parser import NwParser
parser = NwParser()
conn = sqlite3.connect('/media/i008/duzy1/nwdb.sqlite')
def t_to_json(html):
try:
return parser.topic_html_to_json(html... |
import pytest
from ngo_explorer.utils.utils import (
correct_titlecase,
get_scaling_factor,
nested_to_record,
record_to_nested,
scale_value,
update_url_values,
)
def test_scaling_factor():
with pytest.raises(TypeError):
assert get_scaling_factor("kljsdg")
assert get_scaling_fa... |
from flask import Flask, render_template, url_for
import stripe
app = Flask(__name__)
app.config['STRIPE_PUBLIC_KEY'] = STRIPE_PUBLIC_KEY
app.config['STRIPE_SECRET__KEY'] = STRIPE_SECRET_KEY
stripe.api_key = app.config['STRIPE_SECRET__KEY']
@app.route('/')
def index():
'''
session = stripe.checkout.Session... |
from random import choice
from django.http import Http404
from django.shortcuts import render, redirect
from django.urls import reverse
from markdown2 import Markdown
from . import util
from encyclopedia.forms import AddEntryForm, EditEntryForm
def index(request):
"""List all wiki entries."""
return render(... |
# -*- coding: utf-8 -*-
"""Utilities for working with ECS task definitions."""
import json
import os
from .. import client as boto3client
def create(profile, contents=None, filepath=None):
"""Upload a task definition to ECS.
Args:
profile
A profile to connect to AWS with.
cont... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def flatten(self,root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place ... |
#!/usr/bin/env python
from ROOT import *
from array import *
import plotSettings
inputFileName="/tmp/hsaka/results_EAtest.root"
#
tagHLTName="HLT_IsoMu22_v"
tagPathName="hltL3crIsoL1sMu20L1f0L2f10QL3f22QL3trkIsoFiltered0p09"
#tagHLTName="HLT_Mu50_v"
#tagPathName="hltL3fL1sMu22Or25L1f0L2f10QL3Filtered50Q"
#
#probeHLTNa... |
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# This file is d... |
from passlib.apps import custom_app_context as pwd_context
from sqlalchemy.ext.hybrid import hybrid_property
from . import db
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, nullable=False)
name = db.Column(db.String, unique=True)
is_admin = db.Column(db.Bo... |
def hamming_distance(str1,str2):#Distância de coincidência
diferenca = abs(len(str1)-len(str2))
difMax = max(len(str1),len(str2))
menorTamanho = min(len(str1),len(str2))
for i in range(menorTamanho):
if str1[i] != str2[i]:
diferenca+=1
return (diferenca/difMax)
def hamming_rev... |
def power(base,a):
if(a==1):
return(base)
if(a!=1):
return(base*power(base,a-1))
base=int(input("Enter base: "))
a=int(input("Enter exponential value: "))
print("Result:",power(base,a))
|
import scrapy
from ..items import PhoneItem
class PhoneBot(scrapy.Spider):
pipelines = ['phonebot']
custom_settings = {
'ITEM_PIPELINES': {
'WebSpider.pipelines.PhonePipeline': 400
}
}
name = 'phonebot'
start_urls = [
'https://www.ebay.com/b/Samsung-Cell-Phone... |
import json
from os import mkdir
from os.path import join
from django_cron import CronJobBase, Schedule
from aurora import settings
from bag_transfer.api.serializers import ArchivesSerializer
from bag_transfer.lib import files_helper as FH
from bag_transfer.lib.transfer_routine import TransferRoutine
from bag_transfe... |
import os
# This class Maintains a record of the winners of all games played in a batch
class winner():
pl=[]
pt=[]
hand=[]
maximum=0
def _init_(self):
self.pl=[]
self.pt=[]
self.hand=[]
self.maximum=0
# Finds hand name based on the numbers
# 9 Royal flush
# 8 Straight flush
# 7 Four of ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# example of the Metropolis algorithm single walker chain
# a difficult distribution: the Rosenbrock “banana” pdf
#
import math
import numpy as np
from numpy import random as rnd
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import s... |
#!/usr/bin/python
import time
import sgmllib
import urllib2
class Parser(sgmllib.SGMLParser):
def __init__(self):
# inherit from the SGMLParser class
sgmllib.SGMLParser.__init__(self)
# create a list this will store all the links found
self.links = []
# this function is called once an anchor tag is found
... |
import ply.lex as lex
declaracionesiniciales = ['iniciar_programa','inicia_ejecucion','termina_ejecucion','finalizar_programa','define_nueva_instruccion','como','define_prototipo_instruccion']
expresiones = ['apagate','gira_izquierda','avanza','coge_zumbador','deja_zumbador','sal_de_instruccion']
sentencias = ... |
# Check out the resources on the page's right side to learn more about arrays. The video tutorial is by Gayle Laakmann McDowell, author of the best-selling interview book Cracking the Coding Interview.
# A left rotation operation on an array of size shifts each of the array's elements unit to the left. For example, i... |
import threading
import socket
import sys
#Host and port declaration (uses localhost)
host = '127.0.0.1'
port = 8080
#Creates socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Server binding
server.bind((host, port))
server.listen()
#Handles the client messeges
def clientHandler(cli... |
# program to sort the list by last element of tuple in increasing order
List=[(1, 6), (1, 7), (4, 5), (2, 2), (1, 3)]
output = sorted(List, key=lambda x: x[-1])
print(output) |
from flask import render_template, session, redirect, url_for
from . import main
from app.main.recommend.recsys import RecSys
from app.main.dataprocess.useraction import \
record_dislike, record_like, record_visit, query_like, cancel_like, cancel_dislike
from app.main.dataprocess.topk import get_topk
import json
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 10 15:53:20 2021
@author: bjornzobrist
"""
import functions as fc
import time
import numpy as np
start_time = time.time()
#inputs
N = 101 #discretization
x0 = None #initial guess
curves = [[20,41,8.0]] #place of curve: per curve [start, end, v_ma... |
#!/usr/bin/env python
# this program calculates the median of an incoming list.
import sys, csv, ast
try:
myLista = ast.literal_eval(sys.argv[1]) # input expects a numeric list.
except:
print "usage:", sys.argv[0], "[list, of, numbers]"
sys.exit()
myLista.sort() # next step is to sort the list from les... |
import requests, os, bs4, threading
os.makedirs('d:/xkcd2/', exist_ok=True)
def downloadXkcd(startComic, endComic):
for urlNumber in range(startComic, endComic):
if urlNumber == 404:
return
print('Downloading page http://xkcd.com/%s' % (urlNumber))
res = requests.get('http://x... |
import json
from django.shortcuts import render
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from ma... |
import xml.etree.ElementTree as et
import pandas as pd
ENTITIES = ["LAPTOP", "DISPLAY", "KEYBOARD", "MOUSE", "MOTHERBOARD",
"CPU", "FANS_COOLING", "PORTS", "MEMORY", "POWER_SUPPLY",
"OPTICAL_DRIVES", "BATTERY", "GRAPHICS", "HARD_DISK",
"MULTIMEDIA_DEVICES", "HARDWARE", "SOFTWARE", "OS",
"WARRANTY", "SHIPPING", "SUPPO... |
# coding: utf-8
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Variable
import math
import numpy as np
from fairseq.models.fconv import Embedding, Linear
def Conv1d(in_channels, out_channels, kernel_size, dropout=0, **kwargs):
from .conv import Conv1d
m = C... |
def typein(s):
r = []
for c in s:
if c == "#":
r = r[:-1]
else:
r.append(c)
return "".join(r)
print(typein("ab#c") == typein("ad#c"))
print(typein("") == typein("#"))
print(typein("a##c") == typein("#a#c"))
|
#! /usr/bin/python
HTML_HEADER='Content-type: text/html\n\n'
def Main():
print HTML_HEADER+'<html><body>'
print '<b> Success: The server can have Python generate HTML.<br>'
print '(Now hit the BACK button)</body></html>'
Main()
|
# Generated by Django 4.1.7 on 2023-05-08 05:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dictionary', '0070_alter_queryparametermultilingual_fieldname'),
]
operations = [
migrations.AddField(
... |
import datetime
from sqlalchemy.schema import UniqueConstraint
from .db import db
from myca import x509
class Pair(db.Model):
id = db.Column(db.Integer, primary_key=True)
identity_id = db.Column(db.Integer, db.ForeignKey('identity.id'), nullable=False)
identity = db.relationship('Identity', backref=db.... |
#!/usr/bin/python
#import classdemo
from classdemo import Scientific
#print 'Quick Add a + b: %d' % classdemo.quickAdd(10, 20)
#ins = classdemo.Scientific(5, 6)
ins = Scientific(5, 6)
print '%d' % ins.power()
|
s1 = 'café'
s2 = 'cafe\u0301'
print(s1, s2)
print(len(s1), len(s2))
print(s1 == s2)
from unicodedata import normalize, name
s1 = 'café' # 把"e"和重音符组合在一起
s2 = 'cafe\u0301' # 分解成"e"和重音符
print(len(s1), len(s2))
print(len(normalize('NFC', s1)), len(normalize('NFC', s2)))
print(len(normalize('NFD', s1)), len(normalize('NFD... |
from collections import OrderedDict
from html.parser import HTMLParser
from xml.etree.ElementTree import fromstring as xml_from_string
# noinspection PyAbstractClass
class LoginInfoParser(HTMLParser):
def __init__(self):
super(LoginInfoParser, self).__init__()
self.form_opened = False
sel... |
"""
plot java heap usage by class
ex. a simple ipython usage pattern:
# gather some data from your vm
while sleep 5; do
jmap -histo $(pidof java) > /tmp/histo.$(date -I)
done
# process files
files = !ls /tmp/histo.*
H = jhisto(files, limit=30)
# plot the graph
plot_classes(... |
#!/usr/bin/env python
# encoding: utf-8
from model import *
if __name__ == '__main__':
# Clear data.
Feed.drop_collection()
Story.drop_collection()
# Seed data.
Feed(name="eff-official", title="The Electronic Frontier Foundation", site="http://www.eff.org/", url="https://www.eff.org/rss/... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 18:21:05 2019
@author: Julie Seguela
"""
import numpy as np
import pandas as pd
from meal_balancer.algos_optimisation.milp_algo import *
years = ['2018']
delta_auth = 0.2
meal_weight = 1400
print('delta_auth', delta_auth)
print('meal_weight', meal_weight)
filename =... |
import pandas
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import statistics
from scipy import stats
from collections import Counter
from sklearn import preprocessing
from operator import itemgetter
sns.set(style="ticks", color_codes=True)
pandas.set_option('display.expand_frame_... |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import string
import random
def eliza():
print('Hi, I am Eliza. How may I help you today?')
while 1:
sente... |
import numpy as np
def plummerMassDensity(radius, rScalePlummer, plummerMass):
return (3*plummerMass/(4*np.pi*rScalePlummer**3))*(1+(radius/rScalePlummer)**2)**(-5/2)
def plummerPotential(radius, rScalePlummer, plummerMass):
G = 4.3009*10**-3 # Newton's constant, (pc/solar mass) * (km/second)^2
return -G*... |
import numpy as np
import cv2
import FaceDetect
import EyeDetect
import CursorMove
import pyautogui
import dlib
# VideoCapture is the command in OpenCV for caturing video
# (0) donates the default webcam of the computer
# by changing 0 to 1 (or greater if available), we can use different webcam
cap = cv2.Vi... |
from django.urls import path
from shopping_car.views import add, modify, remove, show, indent_addr, indent_ok, settlement, auto_addr
urlpatterns=[
path('show/', show, name="show"),
path('add/',add,name="add"),
path('modify/',modify,name="modify"),
path('remove/',remove,name="remove"),
p... |
# coding: utf-8
# In[1]:
import numpy as np
input_vector = np.array([2, 4, 11])
print(input_vector)
# In[2]:
import numpy as np
input_vector = np.array([2, 4, 11])
input_vector = np.array(input_vector, ndmin=2).T
print(input_vector, input_vector.shape)
# In[3]:
number_of_samples = 1200
low = -1
high = 0
s = np... |
import numpy
import warnings
from scipy import spatial, interpolate
from collections import namedtuple
from .geometry import (
area as _area,
k_neighbors as _k_neighbors,
build_best_tree as _build_best_tree,
prepare_hull as _prepare_hull,
TREE_TYPES,
)
from .random import poisson
from ._deprecated... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/2 上午10:48
# @Author : Dicey
# @File : Lambda2Autotag.py
# @Software: PyCharm
from __future__ import print_function
import json
import boto3
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, conte... |
"""
Timer class.
8-23-2016
"""
import time
import sys
from quantum_module import sec_to_human_readable_format
from estimatetime import EstimateTime
class Timer():
"""
The timer object times the operations and prints out a nice progress bar.
At the end of the operation, the timer will print out the total... |
# Generated by Django 2.0.2 on 2018-02-20 12:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('resume', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Resume',
f... |
from urllib import request
myURL = "https://google.com"
response = request.urlopen(myURL)
mytext1 = response.readlines()
mytext2 = response.read()
print(response)
print(mytext2)
for line in mytext1:
print(line)
|
import os
from alignment import RelatedEvalInstance
from bert_api.segmented_instance.segmented_text import word_segment_w_indices
from cache import save_list_to_jsonl, save_list_to_jsonl_w_fn
from cpath import output_path
from epath import job_man_dir
from misc_lib import split_window
from tlm.qtype.partial_relevance.... |
from django.shortcuts import render
from Shop.models import *
def index(request):
shouye = Goods.objects.all()
#查询所有类型
type_list = GoodsType.objects.all()[:3]
#查询单个类型
type_data = GoodsType.objects.get(id=1)
#查询对应类型的所有商品
type_data.goods_set.all()
#查询每个类型对应的4个商品
for t in type_list:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.