text stringlengths 8 6.05M |
|---|
import xml.etree.ElementTree as ET
import os
import traceback
import json
def xml_getter(xml_file_path, xml_string):
tree = ET.parse(xml_file_path)
root = tree.getroot()
item = root.find(xml_string)
return item.text
def xml_parser(xml_file_path):
#return "Ishmeet"
if os.path.exists("errorFil... |
# dataset link https://www.kaggle.com/subhassing/exploring-consumer-complaint-data/data
# Step 1 Import the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import string
from nltk.stem import SnowballStemmer
from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
from ... |
#!/bin/python3
from sys import stdin
for i in stdin:
print(i.replace("\n",""))
|
import random
import json
class Igra:
def __init__(self, znesek_stave):
self.zgodovina = []
self.znesek_stave = float(znesek_stave)
def poslji_stave(self, stavljene_stevilke):
dobljena_stevilka = random.randint(0, 36)
self.zgodovina.append(dobljena_stevilka)
retu... |
# visitor을 안 만들어주고 maps에 메모제이션을 사용하다 보니, maps[0][0] = 1 이어서 한 번 더 0.0이 queue에 들어간다.
def solution(maps):
N, M = len(maps) - 1, len(maps[0]) - 1
direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]
queue = [[0, 0]]
maps[0][0] = 1
while queue:
X, Y = queue.pop(0)
Count = maps[X][Y]
# ... |
#!/usr/bin/env python
""" Arguments:
-h = Display help and exit
-o = Encrypt or Decrypt
-k = Keyword/Passphrase
-f = File for encryption
The vigenere cipher is very similar to the Caesar cipher but much more secure.
This is due to the use of multiple cipher alphabets instead of ... |
import pickle
import os.path
class Personal_data:
def __init__(self, name):
self.name = name
self.info = ['None']
def add_info(self, info):
if 'None' in self.info:
del self.info[self.info.index('None')]
self.info.append(info)
def privetstvie():
print('\nВыбе... |
first_name = "三"
last_name = "张"
print(first_name + last_name)
print(last_name + first_name)
|
# Generated by Django 2.2.13 on 2020-07-10 08:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shop', '0054_remove_about_title'),
]
operations = [
migrations.DeleteModel(
name='About',
),
migrations.DeleteModel(
... |
from django.contrib.sites.models import Site
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
_thread_locals = local()
def get_current_request():
""" returns the request object for this thead """
return getattr(_thread_locals, "request", None)
def ... |
def handleRequestForm(request_form, transform_field_config):
"""
Handles POST/GET data from user who is trying to filter BSB data,
Transform config will specify what transforms should happen to what fields,
returns appropriate mongodb query which will get user intended data.
:param http_query: dict,... |
import tensorflow as tf
import Model_hyperparameters as p
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from IPython.display import display
from seaborn import color_palette
import cv2
def batch_norm(inputs,training, data_format):
"""Performs a batch normalization using a standard set of parameters... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [1, 2, 3]
W = tf.Variable(10, dtype=tf.float32)
X = tf.constant(x, dtype=tf.float32)
Y = tf.constant(y, dtype=tf.float32)
hx = W * X
cost = tf.reduce_mean(tf.square(hx - Y))
optimizer = tf.train.GradientDescentOptimizer(lear... |
"""
Interface between python and arduino for live data logger
Author: James Keaveney
19/05/2015
"""
import time
import csv
import serial
import sys
import cPickle as pickle
import numpy as np
import matplotlib.pyplot as plt
nchannels = 2 # number of total channels (time axis + ADC channels)
datalen = 2000 # number... |
import pulp
class CitrusError(pulp.PulpError):
pass
class NonBinaryVariableError(CitrusError):
pass
class MissingProblemReference(CitrusError):
pass
def assert_binary(var):
if var.isBinary(): return
if var.isConstant() and (var.value() == 1 or var.value() == 0): return
raise NonBinaryVariabl... |
#!/usr/bin/env python3
"""
Extract a list of AP names from VisualRF Building XML
"""
from argparse import ArgumentParser
import xml.etree.ElementTree as ET
def process_building(building):
data = {}
name = building.attrib['name']
sites = building.findall("site")
for site in sites:
floor, aps =... |
"""
7. Faça um Programa que calcule a área de um quadrado,
em seguida mostre o dobro desta área para o usuário.
"""
def calc_quad(l):
return l ** 2
if __name__ == '__main__':
assert calc_quad(1) == 1
assert calc_quad(2) == 4
assert calc_quad(3) == 9
assert calc_quad(4) == 16
|
import smtplib
from email.message import EmailMessage
import os.path
from os import path
import requests
from bs4 import BeautifulSoup
from lxml import html
from selenium import webdriver
import time
import os
import sys
#"pip3 install secure-smtplib"
# bs4 mac terminal command: "pip3 install beautifulsoup4"
from selen... |
#!/usr/bin/python
import datetime
print(datetime.datetime.now())
|
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404
from django.views import View
from analytics.models import ClickEvent
from .models import fesURL
from .forms import SubmitUrlForm
# Create your views here.
class HomeView(View):
def get(self,r... |
# -*- coding: utf-8 -*-
__author__ = 'benywon'
from public_functions import *
cc=load_file('03-04-wikiQA-MAP_0.710809035076_MRR+0.727666480753.pickle')
print cc
print cc
print cc |
# -*- coding: utf-8 -*-
from odoo import models, fields, api
class utm_did_numbers(models.Model):
_name = 'utm.did_numbers'
_description = 'utm.did_numbers'
did_number = fields.Char(string='Numero DID')
source_id = fields.Many2one('utm.source', string='Origen')
medium_id = fields.Many2one('utm.m... |
# coding: utf-8
# flake8: noqa
from __future__ import absolute_import
# import models into model package
from swagger_server.models.body import Body
from swagger_server.models.http_problems import HTTPProblems
from swagger_server.models.inline_response200 import InlineResponse200
from swagger_server.models.trabajo imp... |
from flask import Blueprint, request, jsonify, Response
from ..controller import Pekerja_pekerjaan
from flask_cors import cross_origin
import json
from ..controller.utils import upload_file
pekerja_pekerjaan_routes = Blueprint('Pekerja_pekerjaan', __name__)
@pekerja_pekerjaan_routes.route("/all", methods=['GET'])
@cr... |
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from paypal.standard.ipn.models import PayPalIPN
from paypal.standard.ipn.signals import valid_ipn_received
from .tes... |
def gcd(s,v):
if(v==0):
return s
else:
return gcd(v,s%v)
s1,v1=map(int,input().split())
LCM=(s1*v1)/gcd(s1,v1)
print(int(LCM))
|
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render
from website.models import *
name = "shaligram.prajapat@gmail.com"
def login(request):
if request.method == 'GET':
return render(request, 'pbas/index.html')
if request.method == 'POST':
current_user_object = Userinfo.o... |
# Generated by Django 2.2.6 on 2020-05-27 15:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('catalog', '0005_auto_20200527_1727'),
]
operations = [
migrations.DeleteModel(
name='Test',
),
]
|
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import i2c, sensor
from esphome.const import CONF_ID
DEPENDENCIES = ['i2c']
CONF_I2C_ADDR = 0x01
empty_i2c_component_ns = cg.esphome_ns.namespace('empty_i2c_component')
EmptyI2CComponent = empty_i2c_component_ns.class_('Empty... |
# Generated by Django 2.2.7 on 2019-11-17 17:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tssite', '0004_auto_20191117_1714'),
]
operations = [
migrations.AlterField(
model_name='teacher',
name='mname',
... |
for i in range(1000000000, 1000000000000000001):
for j in range(1, )
|
# Generated by Django 2.1.7 on 2019-03-28 10:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0009_images'),
]
operations = [
migrations.AddField(
model_name='post',
name='image_2',
field=mo... |
from lib import *
def make_datapath_list(rootpath):
image_path_template = os.path.join(rootpath, 'JPEGImages', '%s.jpg')
annotation_path_template = os.path.join(rootpath, 'Annotations', '%s.xml')
train_id_names = os.path.join(rootpath, 'ImageSets/Main/train.txt')
val_id_names = os.path.join(rootpath, ... |
import logging
import importlib
import argparse
import inspect
import pkgutil
import sys
import colorama
from sv2.helpers import get_public_class, get_public_members
dev_log = logging.getLogger("dev")
fh = logging.FileHandler("/tmp/sv2.log")
fh.setLevel(logging.DEBUG)
dev_log.addHandler(fh)
user_log = logging.getLo... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
import datetime
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
df = pd.read_csv("assets/data.csv")
# 日付
dates = []
for _date in df["Date"]:
date = datetim... |
from django.shortcuts import render
from django.shortcuts import HttpResponse
from math import factorial
def index(request):
return HttpResponse("<h1>welcome to views of dp5app</h1>")
def home(request):
return render(request,"dp5app/main.html",{'pname':"abhilash"})
def fact(request,n):
n=int(n)
retur... |
from flask_testing import TestCase
from .context import slopespot
import os
from slopespot.app import app, db
from slopespot.model import Mountain
class TestMountain(TestCase):
def create_app(self):
return app
def setUp(self):
self.db = db
self.db.create_all()
def tearDown(self)... |
# -*- coding: utf-8 -*-
"""
@author: melkarmo
"""
S = [1,2,5,10,20,50,100,200,500,1000,2000,5000,10000] # liste du stock de pièces
# la fonction suivante est une fonction qui donne le minimum de a et b
# en autorisant a ou b à être infinis
def mini(a,b):
if a == "infini" :
return b
elif... |
import json
from country_codes import get_country_code
import pygal.maps.world
from pygal.style import RotateStyle as RS
from pygal.style import LightColorizedStyle as LCS
#将数据加载到一个列表中
filename='population.json'
with open(filename) as file:
pop_data=json.load(file)
#打印每个国家2016年的人口数量
cc_populations={}
for pop_dic... |
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
from .lookahead import *
from .symbol import *
from .structures import *
from .parsing import *
from .parsing_structure import *
from .interface import *
from .compact_all import *
from . import utils |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
import os
from revolver import directory as dir
from revolver import core
def repository_name():
command = "grep 'url' .git/config | cut -d':' -f2"
name = core.local(command, capture=True)
# Get the basename (e.g.... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
""" Endpoint interfaces for working with streams.
The endpoint interfaces in this module provide endpoint interfaces suitable for
connecting streams to USB endpoints.
"""
fro... |
from .server import Hardwire
from .signal import Signal
|
from typing import Iterable, Sequence
from ai.backend.client.output.fields import keypair_resource_policy_fields
from ai.backend.client.output.types import FieldSpec
from .base import api_function, BaseFunction
from ..session import api_session
__all__ = (
'KeypairResourcePolicy'
)
_default_list_fields = (
k... |
#!/usr/bin/python
#
-*- coding: utf-8 -*-
import sys, re, hashlib
hashes = raw_input('\nPlease specify hash value: ')
wordlist = raw_input('\nPlease specify wordlist path: ')
words = open(wordlist, "r")
words = words.readlines()
print "\n",len(words),"words"
for word in words:
hashed = hashlib.md5(word[:-... |
# -*- coding: utf-8 -*-
import urlparse
from django.shortcuts import render, redirect, get_object_or_404
from django import forms
from shootr.core.models import Bundle, Screenshot
from shootr.core.utils import make_screenshot
class ScreenshotForm(forms.Form):
urls = forms.CharField(widget=forms.Textarea(attrs={'c... |
n = int(input('Input n: '))
# square
print('square')
for i in range(n):
print('*' * n, end='')
print()
# triangle
print()
print('triangle')
start_point = 2
triangle_height = n // 2
if n % 2 != 0:
triangle_height = (n + 1) // 2
start_point = 1
for i in range(triangle_height):
print... |
import os
import json
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.abspath(__file__)
for __ in range(3):
BASE_DIR = os.path.dirname(BASE_DIR)
CONFIG = {}
config_file = os.path.join(BASE_DIR, 'config.json')
if config_file and os.path.isfile(config_file):
with open(... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import math
import ... |
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.preprocessing import OneHotEncoder
import numpy as np
import mglearn
import matplotlib.pylab as plt
X, y = mglearn.datasets.make_wave(n_samples=100)
line = np.linspace(-3, 3, 1000, endpoint=False).res... |
from randimal import Randimal, DisplayOption
if __name__ == "__main__":
randimal1 = Randimal(2)
print("Default: " + randimal1.get())
randimal1 = Randimal(2, displayOption=DisplayOption.LOWERCASE_HYPHENATED)
print("LCH: " + randimal1.get())
randimal1 = Randimal(2, displayOption=DisplayOption.CAMELCA... |
def get_char(text,pos):
if pos<0 or pos>=len(text):
return None
c=text[pos]
if c>='0' and c<='9':
return 'DIGIT'
return c
def scan(text,transitions,accepts,start):
pos = 0
state = start
while True :
c=get_char(text,pos)
if state in transitions and c in transitions[state]:
state = transitions[state]... |
from .cls_dataset import ClsDataset
from .transform import train_transform, val_transform |
from Request import *
from Client import Client
class RequestManager:
def __init__(self):
self.requests = [
Handshake,
Authentication,
ListUsers,
SendMessage,
Logout,
Unknown
]
def get_request(self, client: Client, raw_re... |
from rest_framework import viewsets
from photos.models import Photo, Comment
from photos.serializers import PhotoSerializer, CommentSerializer
class PhotoViewSet(viewsets.ModelViewSet):
queryset = Photo.objects.all()
serializer_class = PhotoSerializer
def get_queryset(self):
return Photo.objects... |
# coding: utf-8
from __future__ import print_function, absolute_import
import logging
import re
import json
import requests
import uuid
import time
import os
import argparse
import uuid
import datetime
import socket
import apache_beam as beam
from apache_beam.io import ReadFromText
from apache_beam.io import WriteTo... |
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import main
import components.weatherInfo as weatherInfo
import components.getNews as getNews
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source... |
import sys #pour recuperer les arguments
import requests #pour les telechargement
import os #pour la creation de repertoir
import shutil #pour le traitement des fichier
from tqdm import tqdm # module de telechergement
from bs4 import BeautifulSoup as bs #POUR rechercher des elements specifique dans une page web.
de... |
import pandas as pd
import os
import json
import logging
import sys
logging.basicConfig(filename = 'logs.log')
#This function will create customer_level_features.csv
def customer_level_features(read_from_train, read_from_test, write_to):
customer_level_features = ['customer_number',
... |
#
# @lc app=leetcode.cn id=13 lang=python3
#
# [13] 罗马数字转整数
#
# @lc code=start
class Solution:
def romanToInt(self, s: str) -> int:
# 3999/3999 cases passed (40 ms)
# Your runtime beats 97.24 % of python3 submissions
# Your memory usage beats 71.67 % of python3 submissions (14.9 MB)
... |
class Matrix:
def __init__(self, width, height):
self.width = width
self.height = height
def edge_values(self):
lowest = float('inf')
highest = float('-inf')
for x, y in self:
if self[x][y] < lowest:
lowest = self[x][y]
if self[... |
from _typeshed import Incomplete
from collections.abc import Generator
def bfs_edges(
G,
source,
reverse: bool = False,
depth_limit: Incomplete | None = None,
sort_neighbors: Incomplete | None = None,
) -> Generator[Incomplete, Incomplete, None]: ...
def bfs_tree(
G,
source,
reverse: bo... |
import boto3
def create_loadbalancer(lb_name, vpc, protocol):
"""
A fucntion to create load balancer
"""
client = boto3.client('elbv2', region_name='ap-south-1')
conn = boto3.client('ec2', region_name='ap-south-1')
# get subnets to create load balancer (Min=3)
response = conn.describe_subn... |
from textblob import TextBlob
from rake_nltk import Rake
import time
import collections
import json
import re
# Sample RSS Feed for testing purposes
rssData = '''
{
"title": "3 Questions: Why are student-athletes amateurs?",
"author": "Peter Dizikes | MIT News Office",
"description": "MIT Professor Jennifer Ligh... |
# pylint: disable=missing-docstring
''' Tasks module.
'''
import io
from behave.configuration import Configuration
from behave.formatter.base import StreamOpener
from behave.runner import Runner
from celery import Celery
from testsuite.application import create_app
from testsuite.extensions import db, socketio
from t... |
import bpy
from photogrammetry_importer.photogrammetry_import_op import ImportMeshroom
from photogrammetry_importer.photogrammetry_import_op import ImportOpenMVG
from photogrammetry_importer.photogrammetry_import_op import ImportOpenSfM
from photogrammetry_importer.photogrammetry_import_op import ImportColmap
from pho... |
def function(list):
i=0
print(min(list))
list = [8, 6, 4, 8, 4, 50, 2, 7]
function(list) |
# I pledge my honor that I have abided by the Stevens Honor System
def main():
name=0
infileName = input("What files are the names in?")
outfileName = input("Place uppercase names in this file: ")
infile=open(infileName, "r")
outfile = open(outfileName, "w")
for i in infile:
n= i.title()... |
import os
import csv
import json
import torch
from torchtext.utils import download_from_url, extract_archive
from torchtext.datasets import text_classification
from tqdm import tqdm
from tokenizer import NLTKTokenizer
os.makedirs('data', exist_ok=True)
def load_csv(path, tokenize_fn):
"""
Yields iterator of ... |
from functions import *
show_personal_info("Matti Meikäläinen", "Sodankylä", "Ohjelmistosuunnittelija") |
import tempfile
import urllib.request
from datetime import date, timedelta
from enum import Enum, unique
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.gis.db.models.functions import Distance
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from d... |
i = 'SsNn'
soma = maior = menor = c = cont = 0
while i not in 'Nn':
c = int(input('Digite um número: '))
i = input('Quer continuar [S/N]? ').upper()
cont += 1
soma += c / cont
if cont == 1:
maior = menor = c
else:
if c > maior:
maior = c
if c < menor:
... |
'''
Created on 01-08-2013
@author: klangner
'''
from collections import defaultdict
from bluenotepad.notepad.models import Notepad, DailyStats
from bluenotepad.notepad.parser import parseReportModel
from bluenotepad.settings import FILE_STORAGE
from bluenotepad.storage.log import read_sessions
from datetime import tim... |
from generators.KruskalGenerator import KruskalGenerator
import logging
class KruskalWithLoopsGenerator(KruskalGenerator):
def __init__(self):
KruskalGenerator.__init__(self)
self.log = logging.getLogger(__name__)
self.foo = lambda: self.random.random() <= 1/(2*self.size)
# @Override... |
import numpy as np
import pandas as pd
import sklearn
import sklearn.preprocessing
import scipy
import tensorflow.keras as keras
df = pd.read_csv('WISDM_clean.csv')
df_train = df[df['user_id'] <= 30]
df_test = df[df['user_id'] > 30]
# Norm
scale_columns = ['x_axis', 'y_axis', 'z_axis']
scaler = sklearn.preprocessing... |
import sys
sys.setrecursionlimit(10000)
import functools
def rodcut(tup):
rodlengt, cutlengths = tup
cutlengths = list(set(cutlengths))
if rodlengt < min(cutlengths):
return 0
mincutl = min(cutlengths)
@functools.lru_cache()
def f(rodlength):
nonlocal mincutl
# if rodleng... |
def base(time):
text=fin.readline().rstrip('\n')
b=[]
for i in xrange(2,37):
try:
a=int(text,i)
for j in xrange(2,37):
try:
c=int(str(a),10)
b.append(c)
except ValueError:
pass
... |
# Generated by Django 3.2.3 on 2021-05-19 16:57
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Game',
fields=[
('id', models.BigAutoField(... |
from selenium.webdriver.support.select import Select
from Pages.base_page import BasePage
from Utils.locators import *
class ListBoxPage(BasePage):
def __init__(self, driver):
self.locator = ListBoxLocators
super().__init__(driver)
def pick_value_by_index_list1(self, index):
selectio... |
def areaOf():
figure = input('Area of (C)ircle or area of R(ectangle)? ').upper()
if figure == 'C':
r = int(input('Enter a radius: '))
area = 3.14*r**2
return 'Area of circle is ' + str(area)
elif figure == 'R':
w = int(input('Enter a width: '))
h = int(input(... |
import os
import sys
import numpy as np
import cv2
import imgdb
import imgdata
import nnmpl
import pickle
OPIS = """recognizephone.py <mode> <database> <method> <images>
mode:
learn - uczenie na podstawie folderu podanego jako parametr images
check - sprawdzenie wybranego zdjęcia podanego jako parametr images
... |
#!usr/bin/env python3
from random import randint
tries = 0
number = randint (1, 100)
print("Rate zwischen 1 und 100!")
while True:
try:
guess = int(input(f'Versuch #{tries+1}:'))
tries += 1
if guess < number:
print("Zahl ist zu klein, du Volltrottel.")
elif guess > num... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
import shlex
from textwrap import dedent
import pytest
from pants.backend.shell.target_types import (
ShellCommandRunTarget,
Sh... |
#!/usr/bin/python3
from datetime import datetime
from utils.date import to_python_date_format
class TimeSeriesRow:
"""
Represents each row in the TimeSeries that will be analyzed by time_series_analysis_service
Attributes
- date (datetime) : date in the row
- value (float) : correspond... |
from . import models
from django import forms
from captcha.fields import CaptchaField
class VideoForm(forms.ModelForm):
captcha = CaptchaField(label='captcha')
class Meta:
model = models.Video
fields = ['title', 'description', 'url']
widgets = {
'name': forms.TextInput(att... |
# LEVEL 21
# (zip from previous level)
import bz2
import zipfile
import zlib
with zipfile.ZipFile('data/level_20.zip') as myzip:
for zi in myzip.infolist():
print(zi)
# print(zi.comment)
with myzip.open('readme.txt', 'r', pwd=b'redavni') as zf:
# print(myzip.getinfo('readme.txt'))
... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.python.util_rules import pex
from pants.backend.python.util_rules.lockfile_diff import _g... |
import time
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from 基于文本内容的垃圾短信识别.data_process import data_process
start = time.time()
data_str, data_after_stop, labels = data_process()
# 分割测试集... |
# Generated by Django 2.1.7 on 2019-03-11 16:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('milliard', '0013_auto_20190311_1734'),
]
operations = [
migrations.RenameField(
model_name='player',
old_name='help_peole',
... |
from CallBackOperator import CallBackOperator
from SignalGenerationPackage.DynamicPointsDensitySignal.DynamicPointsDensityUIParameters import DynamicPointsDensityUIParameters
class EndTimeCallBackOperator(CallBackOperator):
def __init__(self, model):
super().__init__(model)
# overridden
def Conne... |
class QAgent():
def __init__(self, nbins, state_space, action_space, epsilon=0.1, gamma=0.9, alpha=0.1):
self.epsilon = epsilon # exploration probability
self.gamma = gamma # discount factor
self.alpha = alpha # learning rate
self.nbins = nbins # for discretizing state space
... |
import turtle
class Polygon:
def __init__(self, sides, name, size=100, color="black", line_thickness=2):
self.sides = sides
self.name = name
self.size = size
self.color = color
self.line_thickness = line_thickness
self.interior_angles = (self.sides-2)*180
sel... |
import torch
from utils.model_utils import get_mask_from_lengths
def get_loss(outputs, targets, lengths, max_len=None):
mask = get_mask_from_lengths(lengths, max_len)
# Remove SOS character from the beginning of target sequence
loss = torch.nn.functional.cross_entropy(outputs[:, :-1, :].transpose(1, 2),
... |
# -*- coding: utf-8 -*-
"""Tests for simple_history extensions."""
from json import dumps, loads
from django.contrib.auth.models import User
from webplatformcompat.history import Changeset
from webplatformcompat.models import Browser
from .base import APITestCase
class TestBaseMiddleware(APITestCase):
"""Test... |
"Handle command"
import threading
import main
import config as cf
import re
command_list = {'stop': lambda x: main.stop()}
user_command_list = {}
class Command(threading.Thread):
"Handle command"
def __init__(self):
threading.Thread.__init__(self)
self.running = True
def run(self):
... |
from django.urls import path
from AdminApp.views import *
urlpatterns = [
path('', admin),
path('get_user_form/<id>/', get_user_form),
path('user/add/', add_user),
path('get_category/<_id>/', get_category),
path('get_user/<id>/', get_user),
path('delete_user/', delete_user),
path('category... |
CONFIG = """
version: '2'
networks:
byfn:
services:
"""
CA_TEMPLATE = """
ca0:
image: hyperledger/fabric-ca:$IMAGE_TAG
environment:
- FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
- FABRIC_CA_SERVER_CA_NAME=ca-org1
- FABRIC_CA_SERVER_TLS_ENABLED=true
- FABRIC_CA_S... |
import pytest
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from openslides.core.config import config
from openslides.core.models import Projector, Tag
from openslides.users.models import User
from openslides.utils.autoupdate import inform_changed_data
from... |
import random
import time
debug = 0
def playerReset():
global low
global high
global playerResponse
global randomNum
low = 1
high = 100
playerResponse = ''
randomNum = random.randint(low, high)
def startNow():
global low
global high
global playerResponse
gl... |
"""empty message
Revision ID: 486ed7f7d877
Revises: None
Create Date: 2015-09-25 09:06:58.365000
"""
# revision identifiers, used by Alembic.
revision = '486ed7f7d877'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.