text stringlengths 8 6.05M |
|---|
def simplerec(number):
if number > high_num:
return high_num
if number % 15 == 0:
print ("Fizz Buzz")
elif number % 5 == 0:
print ("Buzz")
elif number % 3 == 0:
print("Fizz")
else:
print(number)
simplerec(number + 1)
low_num = 1
high_num = 100
simplerec(l... |
lst=input("Enter a sentence:\n ").split()
len_list=[]
for i in lst:
len_list.append(len(i))
for i in range(0,len(lst)):
for j in range(0,len(lst)-i-1):
if len_list[j]>len_list[j+1]:
t=len_list[j]
len_list[j]=len_list[j+1]
len_list[j+1]=t
t=ls... |
from __future__ import division
import os
import os.path
import sys
import time
class DULED(object):
SIDES = ['left', 'right']
def __init__(self, path):
self._path = path
self.roll()
def run(self):
while True:
used = self.percent_used()
print "%0.0f%% used" % used
self.setpct(used... |
#!/usr/bin/env python3
#
# This script shows how to set up an D/Ne SPI scenario in an ITER-like setting.
# The injection can either be separated into one stage with pure D and one stage with pure NE,
# or be made as a single stage injection with a similar total amount of particles.
#
###################################... |
import networkx as nx
import numpy as np
import scipy.sparse as sp
import torch
from math import ceil
def load_data(ds_name, use_node_labels):
node2graph = {}
Gs = []
with open("datasets/%s/%s_graph_indicator.txt"%(ds_name,ds_name), "r") as f:
c = 1
for line in f:
node2grap... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
#
# JiWER - Jitsi Word Error Rate
#
# Copyright @ 2018 - present 8x8, 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 requir... |
# 数论
# 关键是思考 因数 之间的关系
# 学习下枚举n及n以下的每个数的因子
n = 10000
divides = []
for i in range(1, n+1):
for j in range(i, n+1, i):
divides[j].append(i)
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
divisors = []
d = 1
while d * d <= k: # 预处理 k 的所有因子
if... |
# Generated by Django 2.2.4 on 2019-08-31 00:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='video',
name='filepath',
fiel... |
import pandas as pd
import pysam
import argparse
import pdb
def parse_args():
parser=argparse.ArgumentParser(description="get gc content from a bed file")
parser.add_argument("--chrom_sizes")
parser.add_argument("--ref_fasta")
parser.add_argument("--out_prefix")
parser.add_argument("--region_size",... |
from django.shortcuts import (
render, redirect
)
from django.http import HttpResponse
from django.views import View
from django.contrib import messages
from account.forms import (
UserCreationForm, PasswordChangeForm
)
from django.contrib.auth import (
authenticate, login, logout, update_session_... |
"""Installs and configures Treadmill locally.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import os
import click
from treadmill import bootstrap
from treadmill import cli
from treadmill import... |
#!/usr/bin/env python
"""
v0.1 Tool used for initating an Ipython (v0.9.1+) cluster using
multiple nodes This actually uses ipcontroller and ipengine
rather than the obsolete ipcluster.
NOTE: if installing ipython controller (and engines) on a new computer,
- need to rm ~/.ipython/security/ipcon... |
import turtle
def draw_square(some_turtle):
for i in range(1,5):
some_turtle.forward(100)
some_turtle.right(90)
def draw_triangle(some_turtle):
for i in range(1,4):
some_turtle.forward(100)
some_turtle.right(120)
def draw_art():
window = turtle.Screen()
window.bgcolor('g... |
from django.conf.urls import patterns, url, include
from django.views.generic import ListView
from ideacalculator.views import getideas
urlpatterns = patterns('',
(r'^getidea/$', getideas),
)
|
# Generated by Django 3.0.3 on 2020-06-04 20:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dimensoes', '0014_dimensaomodel_profundidade_media'),
]
operations = [
migrations.RemoveField(
model_name='dimensaomodel',
n... |
import sqlite3
from fastapi import APIRouter, HTTPException
from models.customers import Customer
router = APIRouter()
@router.on_event("startup")
async def startup():
router.db_connection = sqlite3.connect("chinook.db")
router.db_connection.row_factory = sqlite3.Row
@router.on_event("shutdown")
async def... |
from django.conf.urls import url
from players import views
urlpatterns = [
url(r'^(?P<season>\d{4}-\d{2})/$',
views.PlayerListView.as_view(), name='ranking'),
url(r'^(?P<season>\d{4}-\d{2})/vote/$',
views.PlayerVoteModalView.as_view(), name='vote_modal'),
url(r'^vote_save/(?P<signed_data>... |
import os
import re
import math
import sys
from fnmatch import fnmatch
pattern = "*.txt"
word_list = []
spam = 1
ham = 0
dict_spam = {}
dict_ham = {}
lw = []
learning_rate = sys.argv[1]
iterations = sys.argv[2]
cwd = os.getcwd()
with open('stopwords.txt') as f:
stop_words = f.read().splitlines()
def get_words(x,... |
from django.contrib import admin
from home.models import Post, Comment, LikeDislike
admin.site.register(Post)
admin.site.register(Comment)
admin.site.register(LikeDislike)
|
from read_input import *
from itertools import zip_longest
from pprint import pprint
def left_factoring(nonterminal_list,production_list):
left_part = [] # left part of productions list
right_part = [] # right part of productions list
remove_nonterminal_index_list = [] #index of productions to be removed
new_prod... |
class Hero:
def __init__(self, name, level):
self.name = name
self.level = level
class Creature:
def __init__(self, name, the_level):
self.name = name
self.level = the_level
health1 = the_level * 7
def __repr__(self):
return "{}, Level {}".format(
... |
#!/usr/bin/python3.4
# -*-coding:Utf-8
def aff_float(fl) :
""" This function take a float in param and return a string with the troncature of this float with 3 decimal"""
if type(fl) is not float :
raise TypeError("Le paramètre doit être un float")
else :
flottant = str(fl)
entier, virgule = flottant.split(... |
# MQTT Library Import
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import psutil, datetime
# Generate intial CPU Utilization Counters
psutil.cpu_percent();
# Generate CPU Stats
cpuCount = psutil.cpu_count();
print "CPU Count: ",cpuCount;
# Generate Memory Stats
virtualmemoryStats = psutil.virt... |
import pandas
import pandasql
import json
import requests
import pprint
li = []
li.ap
def add_full_name(path_to_csv, path_to_new_csv):
#Assume you will be reading in a csv file with the same columns that the
#Lahman baseball data set has -- most importantly, there are columns
#called 'nameFirst' and 'nameL... |
import json
import os
import sys
import boto3
import botocore
from garage import config
from garage.misc import console
def setup_iam():
iam_client = boto3.client(
"iam",
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_ACCESS_SECRET,
)
iam = boto3.resource(
... |
def readfile(name, fabric):
for s in open(name):
a = s.split('@')
id = a[0]
b = a[1].split(':')
from_edge = b[0].split(',')
from_left = int(from_edge[0])
from_top = int(from_edge[1])
d= b[1].split('x')
width = int(d[0])
height = int(d[1])
top_left = (from_left, from_top)
bottom_right = (from_lef... |
import logging
import json
import os
from pathlib import Path
from flask import Flask, request
from flask_cors import CORS
from flask_restplus import Api, Resource
from flask_restplus import abort
from enigma_docker_common.config import Config
from enigma_docker_common.logger import get_logger
env_defaults = {'K8S'... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
#from sklearn.preprocessing import StandardScaler
#Input dataset
data = pd.read_csv('Position_Salaries.csv')
X = data.iloc[:,1:2].values
y = data... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
import re
from typing import Any, Mapping
import pytest
from pants.backend.visibility.glob import PathGlob, PathGlobAnchorMode, TargetGlob
fr... |
val, par, impar = [], [], []
while True:
cont = ' '
val.append(int(input('Digite um número: ')))
while cont not in 'ns':
cont = str(input('Deseja continuar? [S/N] ')).lower()[0]
if cont == 'n': break
for i in val:
if i%2 == 0:
par.append(i)
else:
impar.append(i)
print(f'L... |
#Module for handling the configuration and submission of jobs via condor
import subprocess
import os
import time
class CondorJob:
def __init__(self, **kwargs):
self.workingdir=kwargs.get('workingdir')
self.universe=kwargs.get('universe')
self.executable=kwargs.get('executable')
self.arguments=kwargs.get('a... |
from backpack.core.derivatives.batchnorm1d import BatchNorm1dDerivatives
from backpack.extensions.curvmatprod.ggnmp.ggnmpbase import GGNMPBase
class GGNMPBatchNorm1d(GGNMPBase):
def __init__(self):
super().__init__(
derivatives=BatchNorm1dDerivatives(), params=["weight", "bias"]
)
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-18 08:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('resources', '0002_auto_20170903_0845'),
]
operatio... |
from collections import namedtuple
from .base import BasePlugin
Plugin = namedtuple("Plugin", ("name", "package", "class_name"))
PLUGINS = {
"base": Plugin(".base", __name__, "BasePlugin"),
"flask": Plugin(".flask_plugin", __name__, "FlaskPlugin"),
"quart": Plugin(".quart_plugin", __name__, "QuartPlugin"... |
def scramble(s1,s2):
for letter in set(s2): # after we convert the s2 to a set() , we limit the loop for max 26 letters instead of going through and each letter in a time!
if s1.count(letter) < s2.count(letter):
return False
return True |
import warnings
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Lambda
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import GlobalAveragePooling2D, GlobalMa... |
from django.db import models
from django.conf import settings
from django.utils.encoding import force_unicode
from django.utils.hashcompat import md5_constructor
from django.contrib.auth.models import User
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlF... |
n1 = int(input('Digite a primeira nota: '))
n2 = int(input('Digite a segunda nota: '))
m = (n1+n2)/2
if(m < 5):
print('Reprovado!')
elif(m >= 5 and m < 7):
print('Recuperação!')
else:
print('Aprovado!') |
from django.urls import path
from .views import (
TagsList,
TagDetails
)
urlpatterns = [
path('', TagsList.as_view()),
path('<int:pk>/', TagDetails.as_view())
]
|
from django.db import migrations
from ..services import *
from django.conf import settings
def initialize_client(apps, schema_editor):
client_data = {'email': settings.EMAIL_TEST, 'client_name':'client1', 'address':'HN', 'name': 'client1_name'}
client = create_client(data=client_data)
class Migration(migrati... |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import logging
import os
import sys
import time
from contextlib import contextmanager
from threading import Lock
from typing import Dict, Tuple
from pants.base.exiter import PANTS_FAILED_... |
# -*- coding: utf-8 -*-
"""
SVL 2016
TP1 Méthodes formelles avec contracts.py
Auteur: Honore Nintunze, antonin Durey
Classes
"""
class Disque:
"""
inv[self.taille]:
self.taille > 0
"""
def __init__(self,taille):
self.taille = taille
class Tour:
"""
Une tour pour contenir les ... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^confirm/$', views.payment_confirm, name='w1-payment-confirm'),
] |
def twoForLoops(n):
n = n * 2
counter = 1
for x in range(n):
m = min(n - counter, counter)
counter += 1
for y in range(m):
print("*", end="")
print("")
def twoWhileLoops(n):
n = n * 2
counter = 1
x = 0
y = 0
while x < n:
m = min(n... |
#-*- coding: utf-8 -*-
import operator
from math import log
import pprint
# 加载数据
def loadData(filename):
# 打开数据文件
fr = open(filename)
# 读取生成列表后存入lenses列表
lenses = [inst.strip().split('\t') for inst in fr.readlines()]
# 构建标签列表
lensesLabels = ['age', 'prescript', 'astigm... |
#!/usr/bin/python
import re
import unittest
import glue2.EntryTest
EntryTest = glue2.EntryTest.EntryTest
class EntityTest(unittest.TestCase):
def setUp(self):
self.good_entry = {
'dn' : ['EntityId=test,o=GLUE2'],
'objectClass' : ['GLUE2Entity'],
'GLUE2EntityId... |
# -*- coding: utf-8 -*-
import sys
import pygame
import nucleo
from pygame.locals import *
WIDTH = 700
HEIGHT = 700
def load_image(filename):
"""Carga la imagen de la ruta que se pasa como argumento"""
try:
image = pygame.image.load(filename)
except pygame.error.message:
raise SystemExi... |
from django import forms
from apps.users.models import UserProfile
import logging
logger = logging.getLogger(__name__)
class CommissionForm(forms.Form):
"""Form to handle the commission"""
handyman = forms.ModelMultipleChoiceField(
queryset=UserProfile.objects.filter(user_type=1, is_active=True))
... |
#produce an SQLite database that contains a User, Course, and Member table
#and populate the tables from the data file.
import json
import sqlite3
conn = sqlite3.connect('rosterdb.sqlite')
cur = conn.cursor()
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Course;
DROP TABLE IF EXIS... |
def unique(n):
return [i for c,i in enumerate(n) if n[0:c].count(i) == 0 or c == 0]
'''
Remove Duplicates
You are to write a function called unique that takes an array of integers and
returns the array with duplicates removed. It must return the values in the
same order as first seen in the given array. Thus no s... |
import paho.mqtt.client as mqtt
from pymongo import MongoClient
broker = "192.168.10.15"
port = 1883
dbClient = MongoClient('localhost', 27017)
db = dbClient.cpu_useage
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("rpi/useage")
def on_message(client, u... |
"""
make_fig3.py
Reproduces Figure 3 in O'Shaughnessy et al., 'Generative causal
explanations of black-box classifiers,' Proc. NeurIPS 2020: global
explanation for CNN classifier trained on MNIST 3/8 digits.
"""
import numpy as np
import scipy.io as sio
import os
import torch
import util
import pl... |
import threading
import time
valor = 100
valor1 = 5
def soma(num, num1):
result = num + num1
print("soma:", result)
def sub(num, num1):
result = num - num1
print("subtração:", result)
def div(num, num1):
result = num / num1
print("divisão:", result)
s = threading.Thread(target=so... |
from time import sleep
from vcenter import get_all_host_info, get_all_vm_info
from sqlit import insert_host_info, insert_vm_info
import logging
logging.basicConfig(level=logging.DEBUG,filename="log.txt",format="%(asctime)s;%(levelname)s;%(message)s")
while True:
try:
count = 0
host_info = get_all_host_info()
log... |
# -*- coding:utf-8 -*-
from threading import Thread
from time import sleep # 调用sleep函数让线程休眠
# 在Python中创建线程,需要让类像线程一样工作
# 继承Thread类
class CookBook(Thread):
def __init__(self):
Thread.__init__(self)
self.message = "Hello Parallel Python Cookbook!!\n"
def print_message(self):
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Coloque o quadrado giratorio e a bolinha dos
exercícios anteriores no mesmo programa.
Isto é, o programa deve consistir em uma animação
com um quadrado giratório crescendo constantemente
e uma bolinha "rolando" pela tela e quicando nas
bordas também em velocidade const... |
from common.run_method import RunMethod
import allure
@allure.step("极师通/作业/学生作业查阅情况详情")
def homework_readStatusOfStudentDetails_get(params=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:re... |
import re
import requests
from bs4 import BeautifulSoup
def get_movie_id(url):
# e.g. "https://tw.rd.yahoo.com/referurl/movie/thisweek/info/*https://tw.movies.yahoo.com/movieinfo_main.html/id=6707"
# -> match.group(0): "/id=6707"
pattern = '/id=\d+'
match = re.search(pattern, url)
if match is... |
"""
@description: 跟数据有关的函数库
"""
"""
import
"""
import numpy as np
import cv2
import torch
import os
def encode_gray_label(labels):
"""
将标签图的灰度值转换成类别id
注意:ignoreInEval为True的都当分类0处理
@param labels: 标签灰度图
"""
encoded_labels = np.zeros_like(labels)
# 除了下面特意转换的,其余都属于类别0
# 1
encoded_labe... |
"""
Provides a touchstone to the project root for resolution
of project-relative paths.
"""
import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
|
# Generated by Django 2.0.9 on 2018-12-18 20:02
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('empresas', '0003_acao'),
]
operations = [
migrations.AlterField(
model_name='acao',
name='data',
... |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools
__author__ = 'ingbyr'
setuptools.setup(
name='BUPTNetLogin',
version='0.0.9',
author='ingbyr',
author_email='dev@ingbyr.com',
url='http://www.ingbyr.com',
description='Command line tool to login the BUPT net',
packages=['BU... |
import speech_recognition as sr
import pyttsx3
engine = pyttsx3.init()
rate = engine.getProperty('rate')
print (rate)
r = sr.Recognizer()
with sr.Microphone() as source: # use the default microphone as the audio source
audio = r.listen(source) # listen for the first phrase and ext... |
import torch.nn as nn
import torch.nn.functional as F
import torch
from torch.autograd import Variable
class LSTMClassifier(nn.Module):
# class torch.nn.Module
# 官方文档
# 所有网络的基类
# 你的模型也应该继承这个类。
# Model description
# model = LSTMC.LSTMClassifier(embedding_dim=embedding_dim,hidd... |
"""Configuration module"""
# noqa
# System Imports
# Framework / Library Imports
# Application Imports
# Local Imports
import env_creds as creds
APP_VERSION = '0.0.1'
APP_DATE = '2020-11-02 1900'
APP_NODE = creds.APP_NODE
API_PREFIX = creds.API_PREFIX
DEBUG = creds.DEBUG
# RabbitMQ Queue Configuration
RABBITMQ =... |
def is_unique_string(string):
try:
iterator = iter(string)
except TypeError:
return False
chars = {}
for char in iterator:
if chars.get(char) != None:
return False
chars[char] = True
return True
assert is_unique_string(())
assert is_unique_string({})
assert is_unique_string('')
asse... |
#!/usr/bin/env python3
import os
import requests
from lxml import etree
from ..lib import utils
'''
desc: save the data into a file
'''
def save_linux_data(file_name, data):
with open(file_name, "w", encoding='utf-8') as f:
f.write(data)
def replace_bad_character(ori_str):
new_str = ori_str.replace("... |
# Generated by Django 2.2 on 2022-06-10 02:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basketball', '0065_auto_20180722_2036'),
]
operations = [
migrations.AlterModelOptions(
name='award',
options={'orderi... |
#coding:gb2312
#给文件添加内容
filename = 'write.txt'
with open(filename,'a') as f:
f.write("\nPython 是一门解释性语言。")
|
"""读取源数据,定义数据加载函数
"""
import numpy as np
def data_gen(data, lookback, delay, min_index, max_index,
shuffle=False, batch_size=128, step=6):
"""生成历史和预测数据集
算法执行过程:首先在合理区间里找出一系列时间基准值保存在 rows 中,
根据 shuffle 的取值以及上次取值结束位置(保存在 i 中),
这个合理区间可能是:(min_index + lookback, max_index),
或者 (i, i + batch_s... |
from tkinter import *
root = Tk()
with open("file.txt", "r") as f:
Label(root, text=f.read()).pack()
root.mainloop() |
from JapaneseTokenizer.mecab_wrapper import MecabWrapper
from JapaneseTokenizer.juman_wrapper import JumanWrapper
from JapaneseTokenizer.kytea_wrapper import KyteaWrapper
from JapaneseTokenizer.datamodels import TokenizedSenetence
from JapaneseTokenizer.datamodels import FilteredObject
|
from script.base_api.service_finance.app import *
from script.base_api.service_finance.web import *
from script.base_api.service_finance.finance import *
from script.base_api.service_finance.handCash import *
from script.base_api.service_finance.v2 import *
from script.base_api.service_finance.applet import *
|
import random
def guess(x):
random_number=random.randint(1,10)
guess=0
while guess!=random_number:
guess=input(f'guess a number between 1 and {x}')
if int(guess)<random_number:
print("Sorry,guess again, too low")
elif int(guess)>random_number:
print("Sorry, gu... |
import numpy as np
import pytest
import osmo_camera.tiff.save as module
class TestGuardImageFitsIn32Bits:
def setup_method(self):
self.test_image = np.zeros(shape=(2, 2, 3))
@pytest.mark.parametrize(
"name, in_range_value",
[
("zero", 0),
("value within range"... |
from hamcrest import assert_that, equal_to
from ..utils.geometry import RectSize
from ..utils.image import ScreenshotFromPngBytes
class Window(object):
def __init__(self, browser):
self._browser = browser
@property
@RectSize.wrapped
def outer_size(self):
size = self._browser.get_win... |
#Sean Kim
#Unit 1 What's Your Order?
print ("Welcome to the Respass Deli!")
print ("What type of sandwich would you like?")
sandwich = input ()
print ("What size fries would you like (small/medium/large)?")
fries = input ()
print ("What type of soda would you like?")
soda = input ()
print ("You have ordered: \n... |
# Generated by Django 2.1 on 2018-10-02 13:15
from django.db import migrations, models
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0028_price'),
]
operations = [
migrations.CreateModel(
name='News',
fields=[
... |
from __future__ import print_function
import sys
from operator import add
from pyspark import SparkContext
from csv import reader
import re
def check_y_coord_cd(input):
if len(input) == 0:
return 'NULL\tNULL\tNULL'
try:
x = int(input)
return 'INT\tY-COORDINATE\tVALID' if x >= 110618 an... |
from .base import FunctionalTest
class LayoutAndStylingTest(FunctionalTest):
def test_layout_and_styling(self):
# For a simple layout and styling test check user area is near to top right corner
# Visitor goes to the home page
self.browser.get(self.server_url)
# He notice user area... |
brian = "Hello life"
# Assign your variables below, each on its own line!
caesar = "Graham"
praline = "John"
viking = "Teresa"
# Put your variables above this line
print caesar
print praline
print viking
"""
The string "PYTHON" has six characters,
numbered 0 to 5, as shown below:
+---+---+---+---+---+---+
| P | ... |
# -*- coding: utf-8 -*-
import re, os, time, sys
import urllib, urllib2, urlparse
import xbmcplugin, xbmcgui, xbmcaddon
from resources.lib import kokolib, hellotools
addon = xbmcaddon.Addon()
addonname = addon.getAddonInfo('name')
addon_handle = int(sys.argv[1])
sysaddon = sys.argv[0]
xbmcplugin.setContent(ad... |
number = 19
swap = [1, 1, 2]
fib = []
if number == 1:
fib.append(1)
print(fib)
elif number == 2:
fib.append(1)
fib.append(1)
print(fib)
else:
fib.append(1)
fib.append(1)
fib.append(2)
for i in range(0, number-3):
swap[0] = swap[1]
swap[1] = swap[2]
swap[2] =... |
"""
计算句子相似度
输入参数:
2个句子 s1,s2
返回参数:
句子相似度
"""
import numpy as np
from scipy.linalg import norm
from sklearn.feature_extraction.text import CountVectorizer
def tf_similarity(s1, s2):
def add_space(s):
return ' '.join(list(s))
# 将字中间加入空格
s1, s2 = add_space(s1), add_space(s2)
# 转化为TF矩阵
cv = C... |
number = "+18684732335" |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
from .events import CoffeeOrdered
from .events import CoffeeServed
from .events import CoffeeFinished
__all__ = [
'CoffeeOrdered',
'CoffeeServed',
'CoffeeFinished',
]
|
from django import forms
from .models import Hamyar
class HamyarForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Hamyar
fields = ['country', 'city', 'address',
'postal_code', 'phone_number']
def __init__(self, *args, **kw... |
# -*- coding: utf-8 -*-
import psycopg2
class Requests:
def __init__(self):
self.registerQuery = 'select id,dni,student_number,name,lastname,email,reason,password,hash,confirmed from account_requests.requests'
def convertToDict(self, d):
r = {
'id':d[0],
'dni':d[1],
... |
from crawler import Crawler
class FindWordCrawler(Crawler):
def __init__(self, word_to_find):
super().__init__()
self.word_to_find = word_to_find
self.word_found = False
def process_data(self, data, url):
print(self.visited_urls)
for line in data:
if self.wo... |
from urllib.parse import urlparse
from crawler import Crawler
class CountWordCrawler(Crawler):
def __init__(self, word_to_count, visit_limit=100):
super().__init__()
self.word_to_count = word_to_count
self.word_counter = 0
self.pages_left = visit_limit
self.base_url_netloc =... |
# Copyright 2009-2010, BlueDynamics Alliance - http://bluedynamics.com
from zope.interface import implements
from zope.catalog.catalog import Catalog
from zope.catalog.field import FieldIndex
from zope.catalog.text import TextIndex
from zope.catalog.keyword import KeywordIndex
from cornerstone.soup.interfaces import IC... |
import torch
from torch import nn
import torch.nn.functional as F
class DeConv1(nn.Module):
# Conv1 反卷积
def __init__(self, in_channel, out_channel, kernel_size=(7, 7), stride=2, padding=3):
super(DeConv1, self).__init__()
self.deconv = nn.ConvTranspose2d(in_channel, out_channel, kernel_size=kern... |
from tkinter import *
from tkinter import ttk
import customerquery as query
import cx_Oracle
class Customer:
def __init__(self, root):
self.root = root
self.root.title("Customer")
self.root.geometry("1000x450+0+0")
self.root.config(bg="grey")
# =============== Left Frame =... |
#!/usr/bin/env python3
# Import the ZMQ module
import zmq
# Import the Thread, Lock and Event objects from the threading module
from threading import Thread, Lock, Event
# Import the uuid4 function from the UUID module
from uuid import uuid4
# Import the system method from the OS module
from os import system, name
# I... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-04-08 16:03:08
# @Author : Fallen (xdd043@qq.com)
# @Link : https://github.com/fallencrasher/python-learning
# @Version : $Id$
a = "外部定义的变量"
list1 = ['外部定义的变量']
def func():
print(a)
print(list1)
def func1():
global a
#我们在函数里声明将要修改全局变量... |
#Author: Xing Cui
#NetID: xc918
#Data: 12/3
import unittest
from unittest import TestCase
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import data_cleanser as ds
from data_cleanser import *
from assignment10_functions import *
from visualization import *
class hw10_unittest(unittest.TestC... |
"""
Useful utilities.
"""
import logging
import re
import unidecode
from kyoukai.asphalt import HTTPRequestContext
logger = logging.getLogger("OWAPI")
HOUR_REGEX = re.compile(r"([0-9]*) hours?")
MINUTE_REGEX = re.compile(r"([0-9]*) minutes?")
SECOND_REGEX = re.compile(r"([0-9]*\.?[0-9]*) seconds?")
PERCENT_REGEX = r... |
from __future__ import print_function
import boto3
import sys
import time
import threading
from multiprocessing import Queue
from lab_config import boto_args
queue = Queue()
def parallel_scan(tableName, totalsegments, threadsegment):
dynamodb = boto3.resource(**boto_args)
table = dynamodb.Table(tableName)
... |
Variables are a way to store and save data for use
This is called assignment. You are assigning a value to a variable
Declaring Variables
Do not need to use var
Cannot start with a number
Cannot declare with special characters
Written in snake case
Data Types
Strings
Strings are immutable. Once they are declared they ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.