text stringlengths 38 1.54M |
|---|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 Joachim Muth <joachim.henri.muth@gmail.com>
#
# Distributed under terms of the MIT license.
"""
Allow a rescale of the data regarding the user mean, variation and deviation.
BEST: deviation
USE:
rescaler = Rescaler(df)
rescal... |
# Generated by Django 3.1.1 on 2020-09-13 23:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data_deal', '0015_auto_20200913_2242'),
]
operations = [
migrations.AlterField(
model_name='original_file',
name='cl... |
import sys
def read_input(fname):
arr = []
with open(fname,'r') as f:
ln = f.readline().rstrip()
while(ln):
arr.append(int(ln))
ln = f.readline().rstrip()
return arr
def solve_p1(adapters):
# go through the sorted ratings and note the diffs
diffs = {}
a... |
def aaddrf():
h = 0
m = []
ma = -1
mq = int(input())
for i in range(mq):
mq.append(int(input()))
for i in range():
if m[i] < m[i + 1]:
h+= 1
else:
continue
if ma < h:
ma = h
print(ma)
|
def atlag(x,y):
atl=(x+y)/2
return atl
while True:
try:
a=input('Adjon meg ket szamot: ')
x,y=a.split()
x=int(x)
y=int(y)
if ((x>0 and x<100) and (y>0 and y<100)):
if atlag(x, y) < 60:
raise Exception('Megbukott!')
... |
#!/usr/bin/env python
# coding: utf-8
# ### By Raksha Choudhary
# ### Data Science and Bussiness Analytics Internship
# ### GRIP The Sparks Foundation
# ### Task 2 : From the given ‘Iris’ dataset, predict the optimum number of clusters and represent it visually.
# ### Import libraries
# In[1]:
import numpy as ... |
from calc import init_frees_by_date, merge_single_list
from random import shuffle
from timeslot import TimeSlot
def test_init():
begin_datetime = '2017-04-10T08:00:00-05:00'
end_datetime = '2017-04-15T19:00:00-05:00'
init = init_frees_by_date(begin_datetime, end_datetime)
ans = [
TimeSlot('Free Time',... |
#vim: set fileencoding=utf-8
from BeautifulSoup import *
import re
import mechanize
import urllib2
#variables:
# #comments, subreddit, title content, img/video/text/link
#cluster by subreddit, but not black/white:stuff in coding could be relveant to stuff in programming etc.
#cluster by word relatedness, floppy disks... |
from pfc import controllers
import pymqr.mobject
from flask import session
@controllers.controller(
url="/",
template="index.html"
)
class index(controllers.Controller):
def OnGet(self,sender):
x=self.request
dmobj = pymqr.mobject.dynamic_object
sender.user = pymqr.mobject.dynamic_ob... |
# coding :utf-8
from . import db
class Recommend(db.Model):
__tablename__ = 'recommend'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20))
tag = db.Column(db.Integer) # 类别
recommend_level = db.Column(db.String(20)) # 推荐指数
problemId = db.Column(db.String(20)) # ... |
# see https://www.codewars.com/kata/52449b062fb80683ec000024/train/python
def generate_hashtag(s):
s = s.strip()
if s == "": return False
if len(s) > 140: return False
return "".join(['#'] + [x.capitalize() for x in s.split(" ")])
from TestFunction import Test
test = Test(None)
test.describe("Basic tests... |
# <<<<<<< HEAD
from flask import Flask, render_template, request, redirect,url_for
import speech_recognition as sr
import os
import glob
import librosa
from tqdm import tqdm
import numpy as np
from python_speech_features import mfcc, fbank, logfbank
import pickle
from annoy import AnnoyIndex
from pydub import AudioSe... |
import numpy as np
import pandas as pd
pd.set_option('display.max_colwidth', -1)
import os
import collections
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classif... |
# coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
# -*- coding: utf-8 -*-
'''
Created on Nov 28, 2013
@author: markito
'''
import DB2
from ConfigParser import ConfigParser
'''
GemFireXD client example using pyDB2
@see: Check config file for database properties
'''
class GfxdClient():
_cursor = None
_conn = None
_config = ConfigParser()
def __ini... |
import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soupe
import json
def jsonfile(data):
file="Espn.json"
with open (file,"w") as fp:
json.dump(data,fp)
url="http://www.espn.com/"
page1= uReq(url)
page_html=page1.read()
page1.close()
page_soupe=soupe(page_html,"html.parser")
c... |
# Copyright (C) 2015-2020 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
from dolfin import *
from mshr import *
# Create mesh
x = 0.5
y = 1.
z = 0.2
domain = Box(Point(0., 0., 0.), Point(x, y, z))
# for i in range(3):
# for j in range(3):
# # print(i... |
"""
Workflow definition to book data
"""
from __future__ import division, absolute_import, print_function
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators import (
BookData
)
dag_id = "book_data"
schedule_interval = None
default_args = {
'owner': 'europython',
'de... |
#!/usr/bin/env python
### This program plots a channel's state variables / hinf, htau etc. as a function of voltage.
mechanism_names = [
'Na_rat_ms','KDR_ms','KA_ms', # migliore and shepherd
'TCa_d','Ih_cb', # PG cell of Cleland and Sethupathy uses channels from various places
'Na_mit_usb','K2_mit_usb','K_mit_usb','L... |
from django.conf.urls import url, include
from django.contrib import admin
from alunos import views
from django.contrib.auth import views as auth_views
admin.autodiscover() # DON'T TOUCH THIS LINE
urlpatterns = [
# django.auth views
url(r'^login/$', auth_views.login, {
'template_name': 'alunos/login... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('sblog.views',
url(r'^bloglist/$', 'blog_list', name = 'bloglist'),
url(r'^blog/(?P<blog_id>\d+)/$', 'blog_show', name = 'detailblog'),
url(r'^blog/tag/(?P<blog_id>\d+)/$', 'blog_filter', name = 'filtrblog'),
url(r'^blog/(?P<blog_id>\w+)/u... |
from Gaudi.Configuration import FileCatalog
FileCatalog().Catalogs += [ 'xmlcatalog_file:$AGAMMAD0TOHHPI0ROOT/options/data/real/RealData_2015_Charm_MagDown_catalog.xml' ]
|
from urllib.parse import urljoin
import sys
import urllib.request
import configparser
class NoRedirectHandler(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, hdrs, newurl):
self.newurl = newurl
return None
def domain():
config = configparser.ConfigParser()
config.read... |
from dubbo.client import DubboClient
if __name__ == '__main__':
client = DubboClient('127.0.0.1', 12358)
resp = client.send_request_and_return_response(service_name='calc', method_name='exp', args=[4])
print(resp.data) # 16
|
"""QuickCheck random generator set state."""
import traceback
import hashlib
import functools
# Map from (type, args, kwargs, SHA1(str(traceback))) to generator functions
GENERATORS = {}
# Map from type string to generator function
TYPES = {}
def getGenerator(t, *args, **kwargs):
"""Get the next thing in the t(*... |
def solution(stones, k):
n = len(stones)
i = 0
answer = 0
while True:
while :
if stones[i] > 0:
continue
else:
answer += 1 |
#!/usr/bin/python
import argparse
import binascii
import struct
import matplotlib.pyplot as plt
import numpy as np
parser = argparse.ArgumentParser(description='Process emount data')
parser.add_argument('--infile', dest='infile', help='input file')
args = parser.parse_args()
infile=open(args.infile,'r')
def apertu... |
from L1TriggerConfig.CSCTFConfigProducers.CSCTFConfigOnline_cfi import *
#from L1TriggerConfig.CSCTFConfigProducers.CSCTFAlignmentOnline_cfi import *
from L1TriggerConfig.CSCTFConfigProducers.L1MuCSCPtLutConfigOnline_cfi import *
from L1TriggerConfig.DTTrackFinder.L1MuDTEtaPatternLutOnline_cfi import *
from L1TriggerC... |
@app.route('/',methods = ['GET'])
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import pandas as pd
import os
os.chdir("C:\\Users\hp\Desktop\dell")
users = pd.read_csv('users.csv' ).values.tolist()
user_id = [users[i][0] for i in range(len(users))]
loyal_customer ... |
import anytree
from code.node import Node as MyNode
from itertools import chain
import numpy.random as np_random
class Tree:
def __init__(self, data_list, sampling_ratio, shingle, max_depth=1000):
"""
data_list - [(x,y), (x,y), ...]
"""
self._elements_count = round(len(data_list) ... |
# coding=utf-8
from django.http import HttpResponseRedirect
from xadmin.views.base import filter_hook
from xadmin.plugins.actions import BaseActionView
from document.models import Document, DocumentLineItem, PROJECT_TYPE
from workflow.models import Route, Item, ITEM_START
from workflow.workflow import Workflow
from or... |
import numpy as np
import pandas as pd
import random
import progressbar
from sklearn.decomposition import PCA
import torch
def simulate(model,
pca_rad, rad_cols_means,
pca_size, size_cols_means,
device,
size_mtx_sim_NA,
rad_mtx_sim_NA,
extra... |
#——————手机号验证码登录页面——————#
from selenium.webdriver.common.by import By
from base.base_action import BaseAction
class Login_phone_captcha(BaseAction):
# 验证码输入框
captchaBox =By.ID,'com.huiian.timing:id/captcha_et'
# 【完成】
completeBtn =By.ID,'com.huiian.timing:id/login_verify_tv'
def input_captcha(self,... |
class Solution:
def isPalindrome(self, x: int) -> bool:
reverse = str(x)[::-1]
if reverse == str(x):
return True
|
#!/usr/bin/python3
""" module that divides all elements of a matrix of similar sized rows """
def matrix_divided(matrix, div):
""" function that returns a new matrix with each element divided by da div
Args:
matrix: a 2d array, each row should be the same size or else: error
div: a number tha... |
# def centared_average(some_list):
# sum = 0
# count = 0
# temp_list = some_list.sort()
# for i in range(1,len(some_list)-1):
# sum = sum+some_list[i]
# count = count+1
# return sum/count
# some_list = [1,2,3,4,5,6,7]
# print(centared_average(some_list))
import copy as cp
s = [10, 2... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import Artus.Utility.logger as logger
log = logging.getLogger(__name__)
from multiprocessing import Pool, cpu_count
import argparse
import copy
import os
import sys
import shutil
import yaml
import Artus.Utility.tools as tools
import Artus.HarryPlotter.ut... |
"""
@Project: pythonProject
@Description: LeetCode-242-有效的字母异位词
@Time:2021/6/4 15:46
@Author:zexin
"""
from collections import Counter
"""
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母... |
from PyObjCTools.TestSupport import TestCase, min_os_level
import CloudKit
class TestCKShareParticipant(TestCase):
def test_enum_types(self):
self.assertIsEnumType(CloudKit.CKShareParticipantAcceptanceStatus)
self.assertIsEnumType(CloudKit.CKShareParticipantPermission)
self.assertIsEnumTyp... |
from django import forms
class RRDForm(forms.Form):
#target = forms.IPAddressField(label='IP')
monitor_type = forms.CharField(max_length=100,label='monitor_type')
target = forms.CharField(max_length=100,required=False,label='target')
metric = forms.CharField(max_length=100,label='metric')
timestamp... |
from typing import Optional
import gdsfactory as gf
from gdsfactory.components.bend_circular import bend_circular
from gdsfactory.components.straight_heater_metal import straight_heater_metal
from gdsfactory.types import ComponentSpec, CrossSectionSpec
@gf.cell
def bend_port(
component: ComponentSpec = straight_... |
import pandas as pd
# load the dataset
anime_data = pd.read_csv("Anime Recommendation.csv")
# input your favorite anime
print("Give me one anime title: ", end='')
base_anime = input()
# input your anime
if base_anime in list(anime_data['Anime']) :
idx = list(anime_data['Anime']).index(base_anime)
# search for y... |
from enum import IntEnum
class PacketType(IntEnum):
REGISTRATION = 0,
AUTHENTICATION = 1,
GET_TOPICS = 2,
GET_MESSAGES = 3,
ADD_TOPIC = 4,
ADD_MESSAGE = 5,
GET_USERS = 6
class DataType(IntEnum):
STRING = 0,
RANGE = 1,
STATUS = 2
class Status(IntEnum):
OK = 0,
PERMIS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
load and and plot single objective results from Sferes 2 optimisation
Copyright (c) 2013 Guillaume VIEJO. All rights reserved.
"""
import sys
import os
from optparse import OptionParser
import numpy as np
sys.path.append("../src")
from fonctions import *
from Mo... |
"""
Based on
http://www.physics.sfasu.edu/astro/color/spectra.html
Taken from
https://hsugawa.blogspot.co.uk/2010/01/matplotlib-colormap-for-visible.html
RGB VALUES FOR VISIBLE WAVELENGTHS by Dan Bruton (astro@tamu.edu)
"""
import numpy as np
def factor(wl):
return np.select(
[ wl > 700.,
... |
"""
@author: sachin paramesha
"""
from numbers import Number
def classify_triangle(a, b, c):
"""
This function returns the string depending on the lenghts of the triangles
"""
if not isinstance(a, Number) or not isinstance(b, Number) or not isinstance(c, Number):
return 'Not a tri... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Created by Ross on 19-1-18
"""由于垃圾windows把我的代码无缘无故给删了,所以现在直接使用MKYAN的代码,若有侵权,请告知"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, ... |
from nutritionix import Nutritionix
nix = Nutritionix(app_id="a43c505b", api_key="ce2e2ad8e38bbf9dbb2043575c591179")
a=nix.search("pizza", results="0:1").json()
b=a['hits']
_id=b[0]
food_calorie=nix.item(id=_id['_id']).json()['nf_calories']
|
# -------------------------------------------------------------------------
#
# PYTHON for DUMMIES 18-19
# Problème 3
#
# Canevas de départ....
#
# -------------------------------------------------------------------------
#
# NE PAS AJOUTER D'AUTRES INSTRUCTIONS import / from :-)
#
from numpy import *
from numpy.linal... |
# -*- encoding: utf-8 -*-
from urllib.request import urlopen
def removeABs(step):
for i in range(len(step)):
while('<' in step[i]):
x = step[i]
step[i] = x.replace(x[x.index('<'):(x.index('>')+1)],'')
return step
def toDict(step):
ret = []
while len(step)!=0:
i... |
import json
import websockets
from datetime import datetime, timedelta, timezone
from collections import namedtuple
from db.db_pool import logger
import asyncpg
from retrying import retry
twelvedata_namedtuple = namedtuple(
"twelvedata_msg",
['datetime', 'symbol', 'price']
)
def create_twelvedata_msg(*, resp... |
#print("jai srirama")
#List funtions()
'''l = [1,2,3,4,5,6,7,8,9,10]
print(l)
print(type(l))
print(dir(l))
#'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
# 'reverse', 'sort']
l.append([5,67,8,9,10,11,12,13])
print(l)
l2 = [1,2,3,4,5,6,7,8,9,10]
l2.clear()
print(l2)
l3 = l.copy()... |
from django.conf.urls import url
from . import storefront_views
from .dashboard_views import views as dashboard_views
urlpatterns = [
url(r'^popular-categories/$',
storefront_views.PopularCategoriesList.as_view(),
name='popular-category-list'),
url(r'^dashboard/popular-categories/$',
d... |
from django.urls import path
from .views import PollDetail
PollRoutes = [
path('<pollId>/', PollDetail.as_view(), name="poll_detail")
] |
""" World contains multiple chunks, which are populated game sections """
import operator
import random
from foxtrot import log, math
from foxtrot.models import words
from foxtrot.models.missions.generate import create_missions
from foxtrot.models.chunk import Colony, Planet, RoomType, Ship, Station
from foxtrot.model... |
import argparse
import json
from Tests.scripts.utils import logging_wrapper as logging
import sys
import time
import requests
from Tests.scripts.utils.log_util import install_logging
GITLAB_CONTENT_PIPELINES_BASE_URL = 'http://code.pan.run/api/v4/projects/2596/pipelines/' # disable-secrets-detection
TIMEOUT = 60 * 6... |
#------------------------------------------#
# Title: CD_Inventory.py
# Desc: The CD Inventory App main Module
# Change Log: (Who, When, What)
# DBiesinger, 2030-Jan-01, Created File
# DBiesinger, 2030-Jan-02, Extended functionality to add tracks
# jstevens, 2020-Mar-21, added sub menu to tracks and additional fu... |
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic.base import TemplateView
from django.conf import settings
from django.utils.safestring import mark_safe
from haystack.generic_views import SearchView
from .forms import SectionSearchForm
from dsp_index.models import Conce... |
#importo la libreria para utilizar json https://docs.python.org/3/library/json.html
#definición de json: https://www.json.org/
import json
#importo config.py donde esta jsonLocation
import config
#Obtengo todos los datos
def getData():
#abro un archivo como json_file
with open(config.jsonLocation) a... |
import numpy as np # linear algebra
import tensorflow as tf
import nltk
import spacy
from nltk import word_tokenize
from nltk.util import ngrams
import re
import os
from datetime import date
today = date.today()
input_path = "training_data"
text = ""
for dirname, _, filenames in os.walk(input_path):
for filename... |
# coding=utf-8
import socket
import threading
from tkinter import *
from game.plane_war.run_plane_fight import run
from server.game_server import Server
class GameMenu:
def __init__(self):
"""
Init the game menu.
"""
self.game_win = Tk()
self.choose_label = Label(self.gam... |
from django.contrib import admin
from .models import Album, Song, Comment, Email
admin.site.register(Album)
admin.site.register(Song)
admin.site.register(Comment)
admin.site.register(Email) |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import requests as re
import random
import time
# In[2]:
delay = int(input("Provide delay value after each request in SECONDS(int): "))
for i in reversed(range(int(input("Provide min dataset size in INT: ")))):
re.post('http://localhost:3000/esp8266', json={"val... |
class Solution:
def longestPalindrome(self, s):
# new_nums = '!#' + '#'.join(nums) + '#$'
nums = list(s)
# 索引的话,为什么就一定要想着是列表呢? 你个傻子
new_nums = '!#' + '#'.join(nums) + '#$'
print('new_nums is {}'.format(new_nums))
mark = [0 for _ in range(len(new_nums))]
mxRigh... |
try:
Numbers = []
while True:
Numbers.append(int(input()))
except:
print(Numbers)
Numbers.sort()
length = len(Numbers)
#print (length)
if (length % 2 == 0):
median = (Numbers[(length)//2] + Numbers[(length)//2-1])/2
else:
median = Numbers[(length-1)//2]
... |
# Generated by Django 2.0.5 on 2018-09-01 15:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AmadoAccounting', '0024_employeepayment'),
]
operations = [
migrations.AddField(
model_name='person',
name='childs',... |
# -*- coding: utf-8 -*-
"""
"""
import os
import pulp
import numpy as np
import pandas as pd
curr_wk = 16
""" YOU NEED TO UPDATE THE SCHEDULE FILE TO INCLUDE CURRENT WEEK GAMES """
working_directory = ''
pred_dir = ''
os.chdir(working_directory)
def pred_lineup(df, lineups, overlap):
pr... |
"""
Test Data Generator in Library
"""
import pytest
from library import DataGen
@pytest.fixture
def generate_input():
dg = DataGen()
inputdict = dg.dict_gen()
return inputdict
def test_dictionary_keys(generate_input):
"""
Test that all keys are in data generator dictionary
"""
columns ... |
if __name__ == '__main__':
radius = float(input("Enter radius: "))
height = float(input("Enter height: "))
volume_of_cylinder = (3.14 * (radius ** 2) * height)
print(volume_of_cylinder)
|
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
job_title = models.CharField(max_length=200)
image = models.ImageField(blank=True)
text_desc = models.TextField()
cv = models.FileField(bla... |
N, Q = map(int, input().split())
result = [0] * (N + 1)
for _ in range(Q):
L, R, T = map(int, input().split())
for i in range(L, R + 1):
result[i] = T
for i in result[1:]:
print(i)
|
import numpy as np
from tensorflow import keras
# Preparing data:
TRAINING_CASES = 50000
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
x_val = x_train[TRAINING_CASES:] / 255
y_val = keras.utils.to_categorical(y_train[TRAINING_CASES:], num_classes=10)
x_train = x_train[:TRAINING_CASES] / 255... |
from controllers import base
class Handler(base.Handler):
def post(self):
nn = self.get_body_argument("name")
utype = self.get_body_argument("type")
if utype == "image":
outf = open("files/" + nn + ".png", "wb")
outf.write(self.request.files['filearg'][0]['body'])
... |
import unittest
from markdown import render_markdown
class TestMarkdown(unittest.TestCase):
def test_code(self):
inp = '`code`'
exp = '<code>code</code>'
oup = render_markdown(inp)
self.assertEqual(exp, oup)
def test_image(self):
inp = " 2012 The Multiverse Foundation
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without restrict... |
from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View
from mydjango import settings
from .models import *
#from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.r... |
from ROOT import *
import sys
sys.path.append('/home/tkimmel/Research/codeplot/functions/')
from plottingfunctions import *
f = TFile("/home/tkimmel/Research/root/nbvars.root","READ")
t = f.Get("pi0tree")
gm1p3cms = RooRealVar("gm1p3cms","gm1p3cms",0,2)
nBins = 100
lb = gm1p3cms.getMin()
rb = gm1p3cms.getMax()
frame... |
from cryptography.fernet import Fernet
from Crypto.PublicKey import ECC
import multihash
class Symmetric():
@classmethod
def generate_key(cls):
return Fernet.generate_key()
@classmethod
def encrypt(cls, key, data_in_bytes):
f = Fernet(key)
if isinstance(data_in_bytes, bytes):
... |
from flask import g
from flask_restplus import Resource
from app.constants.cashier import TRANSACTION_PAGE_SIZE
from app.docs.doc_cashier.deposit_withdraw import UserOrderSelect, ResponseOrderEntryList
from app.forms.deposit_form import UserOrderSelectForm
from app.libs.datetime_kit import DateTimeKit
from app.libs.do... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Author : ice-melt@outlook.com
@File : nlp-5-6-tag_brill_demo.py
@Time : 2019/4/22 17:42
@Version : 1.0
@Desc : None
"""
import nltk
ll = [t for t in nltk.tag.brill.nltkdemo18()]
print(ll) |
from django.db import models
import re
from datetime import datetime
class UserManager(models.Manager):
def validator(self, postData):
errors = {}
EMAIL_REGEX = re.compile(
r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
if (len(postData['registered_first_name']) == 0 or
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
module: find_regime_change.py
author: Zach Lamberty
created: 2014-10-04
Description:
solution to the ecofactor regime change toy problem
Usage:
<usage>
"""
import argparse
import os
import re
import matplotlib.pyplot as pyplot
import numpy
import scipy.stat... |
import random
import time
n = random.randint(1, 20)
tahmin = int(input("1 ve 20 arasinda bir sayi giriniz: "))
start_time = time.time()
count = 0
while n != "tahmin":
count += 1
if tahmin < n:
print ("tahminin dusuk")
tahmin = int(input("1 ve 20 arasinda bir sayi giriniz: "))
... |
import os
from datetime import datetime, timedelta
#
# Airflow root directory
#
PROJECT_ROOT = os.path.dirname(
os.path.dirname(
os.path.dirname(__file__)
)
)
#
# Paths
#
base_dir = os.getenv('BASE_DIR','/var/data/')
regions_base_dir = os.path.join(base_dir, 'regions')
repository_base_dir = os.getenv(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import xml.sax, xml.sax.handler
from jubatus.classifier import client
from jubatus.classifier import types
host = "127.0.0.1"
port = 9199
instance_name = ""
class Handler(xml.sax.handler.ContentHandler):
read = False
count = 0
def __i... |
from typing import List, Optional, Tuple, Union, TYPE_CHECKING, Dict
from numpy import nan
from numpy.random import seed
from pandas import Series, concat
from mpl_format.axes import AxesFormatter
from mpl_format.compound_types import Color
from mpl_format.utils.color_utils import cross_fade
from mpl_format.utils.num... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class EvMeta(Model):
"""NOTE: This class is auto generated by the swagger code... |
import sys
sys.stdin = open("최소합_input.txt", "r")
def dfs(x, y, sum):
global min
###########################
if min <= sum: # 가지치기
return
#########################
if x == N-1 and y == N-1:
if min > sum:
min = sum
else:
if x + 1 < N:
dfs(... |
from django.shortcuts import render
# Create your views here.
from . import views
from rest_framework import routers
from django.urls import path, include
router=routers.DefaultRouter()
router.register('awsimage',views.awsimageview)
urlpatterns=[
path('',include(router.urls))
]
|
"""
test
"""
import numpy as np
def test_calc_db():
"""
test calc_db
"""
from tests.const import const
from src.beam import init_beam
from src.e2k import load_e2k
from src.etabs_design import load_etabs_design, post_e2k
from src.stirrups import calc_stirrups
from src.bar_size_num i... |
字典 = input("請輸入你要查詢的英文:")
if 字典 == "apple":
print("蘋果")
elif 字典 == "蘋果":
print("apple")
elif 字典 == 1:
print("one")
elif 字典 == 2:
print("two")
elif 字典 == 3:
print("there")
elif 字典 == 4:
print("four")
elif 字典 == 5:
print("five")
elif 字典 == 6:
print("six")
elif 字典 == 7:
print("seven")
elif 字典 == 8:
print("eight... |
import requests
import re
from bs4 import BeautifulSoup
import optparse
parser = optparse.OptionParser()
parser.add_option('-f', '--file', action="store", dest="Filename", help="File storing the list of URLs to be checked", default="spam")
parser.add_option('-t', '--target', action="store", dest="target", help="Which s... |
from os.path import join, isdir
from sys import argv
from os import listdir, rename, mkdir
import os
dir = argv[1]
dir = join('datasets', dir, 'video')
for clas in os.listdir(dir):
for element in os.listdir(join(dir,clas)):
if isdir(join(dir, clas, element)):
continue
folder = element... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('history', views.history, name='history'),
path('newuser', views.newuser, name='newuser'),
path('customer', views.customer, name='customer'),
path('transfer/<str:pk>', views.transfer, name='tr... |
#!/usr/bin/env python
# Copyright (C) 2015 MTA SZTAKI
"""
Infrastop
~~~~~~~~~
This script tears down an infrastructure using OCCO-ResourceHandler and
OCCO-InfraProcessor.
An infra_id is required.
Author: adam.visegradi@sztaki.mta.hu
"""
import occo.api.occoapp as occoapp
import occo.infobroker as ib
import occo.u... |
import cv2 as cv
import numpy as np
import os
import sys
from PIL import Image
path = "/home/aditasyhari/Project Python/AI/bakteri/dataset/"
for root, subdirs, files in os.walk(path):
for file in files:
print(os.path.join(root, file))
img = cv.imread(os.path.join(root, file))
#convert ... |
pi = 3.14
def max_user(a, b):
return a if (a > b) else b
def max3_user(a, b, c):
return max_user(a, max_user(b, c))
def summ_user(*vals):
print("lec26/lib ")
print("summa = ")
s = 0
for x in vals:
s += x
return s
|
input1= input('Enter the First number :')
input2= input('Enter the Second number :')
# Adding two Numbers
sum= input1 + input2
# Subracting two Numbers
subraction= input1 - input2
# Mutiplicating two Numbers
multiplication= input1 * input2
# Dividing two Numbers
division= input1 / input2
print "Addition :%d"%sum
print ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 2 23:57:13 2015
@author: brian
"""
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 17 14:39:21 2015
@author: brian
"""
from datetime import datetime, timedelta
from traffic_estimation.TrafficEstimation import estimate_travel_times
from routing.Map import Map
from db_... |
import pytest
from voting import voter
@pytest.fixture
def turtle_voter():
return voter.Voter(["turtle", "tiger", "monkey"])
def test_voter_first_choice_is_best_choice(turtle_voter):
assert turtle_voter.top_choice == "turtle"
def test_convert_to_string(turtle_voter):
assert str(turtle_voter) == "turt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.