text stringlengths 38 1.54M |
|---|
H = 1.
kernel_lr_multiplier = 'Glorot'
data_format = 'channels_last'
# nn
batch_size = 32
epochs = 20
channels = 1
img_rows = 28
img_cols = 28
filters = 32
kernel_size = (3, 3)
pool_size = (2, 2)
hidden_units = 128
classes = 10
use_bias = False
# learning rate schedule
lr_start = 1e-3
lr_end = 1e... |
import json
import datetime
import os
data_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data.json'))
output_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../README.md'))
with open(data_path, 'r') as f:
datastore = json.load(f)
YEAR =... |
# Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES.
# 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 requ... |
#! /usr/bin/env python
import argparse
import pyfits
import numpy as np
import matplotlib.pyplot as plt
from target_utils import apertures_from_region
def head_append(header):
new=header
new['CTYPE1']='LINEAR'
new['CTYPE2']='LINEAR'
new['CDELT1']=1
new['CDELT2']=1
new['CD1_1']=1
new['CD2_2'... |
import streamlit as st
import base64
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
st.set_page_config(layout="wide")
st.title('EURO 2020 ANALYSIS')# st.set_page_config(layout="wide")
st.markdown("""
This app is developed by Theevagaraju to perform an analysis on EURO 2020
* **Python**: pan... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.generic import TemplateView
import json
import re
import boto
from boto.s3.key import Key
from django.conf import settings
class FileView(TemplateView):
def buildTree(list, parent_id='root'):
branch = []
... |
# file name: problem2.py
def example1():
""" This is an example for matrix [[0, 1], [1, 0]]
Note:
For the multi-qubit or multi-operations quantum circuit, use ';' to split them.
"""
quantum_circuit = 'X | qubits[0]'
return quantum_circuit
def example2():
""" This is an example for matri... |
from functools import reduce
import time
def timeit(func, *args, **kwargs):
try:
startime = time.time()
print(startime)
result = func(*args, **kwargs)
stoptime = time.time()
print(stoptime)
usetime = stoptime - startime
except Exception as e:
return 'Erro... |
from rest_framework import serializers
from api.models import Cabinet, Charger, SiteNavi, Collective, ProductLine, Project, AuthCenter, Interval, Crontab, Cxfb
class ChargerModelSerializer(serializers.ModelSerializer):
class Meta:
model = Charger
fields = "__all__"
class AuthCenterModelSerialize... |
# load svm trained model to predict cars color
import pickle
from sklearn.model_selection import train_test_split
from sklearn import svm
from matplotlib import pyplot as plt
import os
import cv2 as cv
import numpy as np
from sklearn.metrics import plot_confusion_matrix
def extract_features_hist(img_path, bins):
... |
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.utils import simplejson
from django.template import RequestContext
from django.http import HttpResponseRedirect
from crawler import spider
from crawler import monitor
from crawler.models import Item
from datetime import *
i... |
from flask import Blueprint, render_template, request, jsonify, url_for, redirect
from flask_login import login_required, current_user
from service import profile, stats
from datetime import datetime
from time import strptime
import json
import config
app = Blueprint("profile", __name__, url_prefix="/profile")
@app.r... |
#!/usr/bin/env python
import rospy
import sys
import matplotlib.pyplot as plt
import numpy as np
from network_faults.msg import Network, Velocity
txrx_pl = 0
txrx_td = 0
offset = 0
path_data = []
count = 0
pl_percent = 0.0
stop = 0
def gotdata(txrx):
global offset, txrx_pl,txrx_td, path_data, count, pl_percent, ... |
import os, sys
sys.path.append(os.path.abspath(os.path.join('../..')))
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from sklearn.metrics import r2_score
from scipy import stats
from numba import njit
import tensorflow as tf
from tensorflow.keras.models import Sequentia... |
from typing import Optional
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="Crypto/static"), name="static")
templates = Jinja2Templates(directory="Crypto/templates") |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
class PhysiologicalPlotsCreator:
def __init__(self, baseFolder):
# After this you can chose what plots to create in the main method.
self.baseFolder = baseFolder
## Todo. not sure what this... |
#!/usr/bin/env python3
# import json
# import sys
import requests
import datetime
import urllib
import time
import subprocess
import os
from os.path import expanduser
import logging
# import pysnooper
###
#
# ToDo: Add probing macro generation
# Add file interaction on Duet (read/write)
# Calibrate then print
# Slice... |
import sys
import caffe
if __name__ == '__main__':
solver_prototxt = sys.argv[1]
max_steps = int(sys.argv[2])
solver = caffe.SGDSolver(solver_prototxt)
if len(sys.argv) > 3:
solver_state = sys.argv[3]
solver.restore(solver_state)
for i in range(0, max_steps):
solver.step(1)... |
from rest_framework import routers
from csvapp.views import CSVview
router = routers.SimpleRouter()
router.register(r'',CSVview)
|
"""
Class for plotting a aircraft
Author: Josue H. F. Andrade
Based on: Daniel Ingram (daniel-s-ingram)
"""
from math import cos, sin
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FixedLocator, FormatS... |
# Generated by Django 3.2 on 2021-04-23 15:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('groups', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='group',
name='description',
... |
import sys
import pytest
from numpy.testing import assert_allclose
import numpy as np
from keras.backend import theano_backend as KTH
from keras.backend import tensorflow_backend as KTF
from keras.utils.np_utils import convert_kernel
def check_single_tensor_operation(function_name, input_shape, **kwargs):
val = ... |
#! /usr/bin/env python3
def func1():
try:
for m in map(int, ['1', '2', '3', '4L']):
print(m)
except ValueError as instance:
print(instance)
if __name__=='__main__':
print("\nfunc1()")
func1()
|
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
"""
时间:2019/9/23
作者:大发
功能:练习用 导入
"""
# import c2_some_module
# result = c2_some_module.f(5)
# pi = c2_some_module.PI
# from c2_some_module import f , g , PI
# result = g (5 , PI )
import c2_some_module as csm
from c2_some_module import PI as pi , g as gf
r1 = csm.f(pi)
r2 = gf(6 , pi) |
# -*-coding:utf-8 -*-
__author__ = 'Administrator'
from PyQt5 import QtCore, QtGui, QtWidgets
from quote_api import *
'''
银行股息率计算
接收主页面的更新股息率的信号
从quote_api接口获取实时行情数据
emit获取的实时行情数据到主页面,主页面更新银行信息表
'''
class BankThread(QtCore.QThread):
df_bank_out = QtCore.pyqtSignal(pd.DataFrame)
signal_df_ah_premium = QtCore... |
from flask import Flask, request, redirect, render_template
app = Flask(__name__)
app.config['DEBUG'] = True
@app.route("/welcome")
def welcome_new():
welcome_user = request.args.get("username")
return render_template("welcome.html", username = welcome_user)
@app.route("/", methods=["POST", "GET"])
def index... |
"""
@Author: yanzx
@Date: 2021/4/7 22:50
@Description:
"""
from rest_framework.authentication import BaseAuthentication, TokenAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.serializers import VerifyJSONWebTokenSerializer
class TokenAuth():
def authenticate(self,... |
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import APIKeyHeader
from api import prediction
from api import healthcheck
api_router = APIRouter()
router = APIRouter()
API_KEY_SCHEME = APIKeyHeader(name='x-api-key')
async def verify_api_key(api_key: str = Depends(API_KEY_SCHEME)):
... |
'''
The Daily Weather app obtains the most recent weather data from weather.gov and emails it to the specified recipients at 9am every day.
The default station is set to Central Park, NYC.
Please ensure that you have entered your email address and password in the send_html_file module.
Note: usage requires inst... |
#! /usr/bin/env python
#This code is a python implementation of the atom counts features used in
#Ballester PJ, Mitchell JB. A machine learning approach to predicting protein-ligand binding affinity with applications to molecular docking. Bioinformatics. 2010; 26:1169-75.
#Inspiration for the CartesianPoint,Atom ... |
import unittest
from dxpy.task import configs
from dxpy.task.exceptions import UnknownConfigName
# TODO: add unittests
class TestConfigs(unittest.TestCase):
def setUp(self):
self.config_name = 'config_unittest'
class ConfigUnitTest:
def __init__(self):
self.field1 = '... |
# coding: utf-8
"""
HCE project, Python bindings, Distributed Tasks Manager application.
PostProcessingModuleClass is a base class for postprocess modules.
@package: dc_postprocessor
@file PostProcessingModuleClass.py
@author Alexander Vybornyh <alexander.hce.cluster@gmail.com>
@link: http://hierarchical-cluster-engi... |
from dcmodule import load_with_args, result_dump
if __name__ == "__main__":
with load_with_args() as _iotuple:
_stdin, _stdout = _iotuple
result_dump(True, data={
"stdin": _stdin,
"stdout": _stdout,
})
|
# -*- coding:UTF8 -*-
import re
import traceback
try:
n = input()
pattern = re.compile(r'\d+') # 查找数字
result1 = list(map(int,pattern.findall(n)))
result1.sort(reverse=True)
print(result1[0])
except:
traceback.print_exc()
pass |
import requests as req
def main():
URL_MENSAJE = "https://api.telegram.org/bot1943187472:AAHl6kFfARl1MiCIs09rEcADcZR0asEkIyY/sendMessage?chat_id=-589260794&text=Hola que tal"
consulta = req.get(URL_MENSAJE)
if (consulta.status_code == 200):
print("Mensaje enviado")
else:
print... |
# -*- coding: utf-8 -*-
from flask import Flask, url_for
from flask import render_template
import pymysql
app = Flask(__name__)
class GetMysqlData(object):
def __init__(self, table='douban_books_info'):
self.con = pymysql.connect(host='127.0.0.1', port=3306, user="root", password="", db="test", charset='... |
from __future__ import print_function, division
import os
import time
import tensorflow as tf
import numpy as np
from .loss import get_loss, get_mean_iou
from .optimizer import get_optimizer
from utils.eval_segm import mean_IU
class Trainer(object):
"""
Trains a CU-Net instance
:param net: the CU-Net-n... |
from InfopulseWebChatApp.models import ChatUser, Ban
class ChatUserService:
@staticmethod
def save_user(user_form):
if user_form.is_valid():
user_name=user_form.cleaned_data["name"]
user_login=user_form.cleaned_data["login"]
user_password=user_form.cleaned_d... |
from dejmps import dejmps_protocol_bob, get_fidelity_phi00
from netqasm.sdk import EPRSocket
from netqasm.sdk.external import NetQASMConnection, Socket, get_qubit_state
def main(app_config=None):
# Create a socket for classical communication
classical_socket = Socket("bob", "alice")
# Create a EPR socket... |
import re
import pandas as pd
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_extraction.text import Cou... |
#!/usr/bin/env python3
# import of built-in modules
import datetime
import os
import sys
# import of third party modules
# None
# import of local modules
import DeDriftAndResampleHCP7T_OneSubjectCompletionChecker
import hcp.hcp7t.archive as hcp7t_archive
import hcp.hcp7t.subject as hcp7t_subject
import utils.file_ut... |
import numpy as np
import matplotlib.pyplot as plt
class ImagesHelper:
def __init__(self):
pass
@staticmethod
def get_bit_mask_from_bitmap(image):
PIXEL_COLOR_LIMIT = 10
pixels = image.load()
bitMask = np.zeros(image.size[0] * image.size[1])
for i in range(0, ima... |
import unittest
import unittest.mock as mock
import splendor_sim.interfaces.coin.i_coin_type as i_coin_type
import splendor_sim.interfaces.game_state.i_game_state as i_game_state
import splendor_sim.interfaces.player.i_player as i_player
import splendor_sim.interfaces.player.i_player_card_inventory as i_player_card_in... |
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
class Net(nn.Module):
def forward(self, x):
x = self.layer1(x)
return x
Network = torch.load('CNN-L22-100.net')
Network.eval()
Ts = 10000-100
NX = 64
data = np.fromfile('1d_... |
# -*- coding: utf-8 -*-
import KBEngine
from KBEDebug import *
import const
import utility
import json
import switch
import x42
import copy
from roomParamsHelper import roomParamsChecker, roomParamsGetter
class iRoomOperation(object):
""" 玩家游戏相关 """
def __init__(self):
self.room = None
# 当前正在创建房间时再次请求创建需要拒绝
s... |
from discord_webhook import DiscordWebhook, DiscordEmbed
class discord_data:
url = None
name = None
class Message:
header = ""
content = ""
user = ""
footer = ""
color = 0xc8702a
class Discord:
def __init__(self,config):
self.data = discord_data()
self.data.url = confi... |
from .models import Utilisateur,Evenement
from .exceptions import Exception_sans_var, Exception_avec_var,Exception_participant
import re
def verifie_user(mail, mdp):
user = Utilisateur.objects.filter(email=mail, mdp_hashe=mdp).first()
if user is None:
raise Exception_sans_var(1000)
def verifie_mail(em... |
# prompt user with series of inputs for Mad Lib fill ins - example, a singular noun, an adjective, etc.
# place that data in pre made story template
print("Lets Mad Lib!!!")
adjetive1 = input("Give me an adjetive >")
adjetive2 = input("Another adjetive please >")
adjetive3 = input("Another adjetive >")
plural_noun... |
from django.conf.urls import include, url
from forum_messages.views import AorMessageView, AorConversationView, \
AorReplyView, AorWriteView
merged_patterns = [
url(r'^reply/(?P<message_id>[\d]+)/$', AorReplyView.as_view(), name='reply'),
url(r'^view/(?P<message_id>[\d]+)/$', AorMessageView.as_view(), nam... |
#!/usr/bin/env python3
red = '\033[0;31m'
reset = '\033[0m'
print(red + 'what is your name' + reset )
name = input('> ')
print('hi there ' + name)
|
import logging
import numpy as np
import cv2 as cv
import triangulation
from numpy.core.numeric import Inf
from scipy.optimize import minimize
from numpy.linalg import pinv, norm
from math import acos, cos, pi, sin, sqrt
from numpy import dot
ref = None
VpStar = None
depthVector = None
def run(images) :
patch... |
from unittest import TestCase
from poe.config import settings
from poe.web_api.session import (
PathSession, InvalidLoginException
)
class PathSessionTestCase(TestCase):
@classmethod
def setUpClass(cls):
cls.session = PathSession(settings["USERNAME"], settings["PASSWORD"])
def test_good_logi... |
from database.db import db
class AgeData(db.Model):
"""
Stores age bands, their data and the relativity.
"""
id = db.Column(db.Integer, autoincrement=True,
primary_key=True, nullable=False)
data = db.Column(db.Integer, nullable=False)
lower_limit = db.Column(db.Integer, null... |
import ble2lsl as bl
from ble2lsl.devices import muse2016, ganglion
from pylsl import StreamInlet, resolve_byprop, StreamOutlet #receiving the EEG signals
import time
import numpy as np
import bokeh
import pylsl as lsl
# this is the first revision of convert.py from Samuel White
# taking alot of insporation from t... |
a=[1,2,3,4,5,6,7]
b=["ab","cd","ef","gh","ij"]
c=[1.1,2.1,3.1,4.1,5.1,6.1,7.1]
d=[1.1,2.1,3.1,4.1,5.1,6.1,7.1]
e=["ab","cd","ef","gh","ij"]
print(a)#打印所有元素
print(b[0])#打印部分元素
print(a[-1])#打印倒数第一个元素
#添加元素
a.append(8)
print(a)
print(a.append(7))
#插入元素
b.insert(2,"yy")
print(b)
#删除元素
del c[0]
print(c)
#弹出元素
d.pop(1)
pri... |
#!/usr/bin/python3
'''initializes repo as a module, includes file storage'''
from models.engine import file_storage
__all__ = ["base_model", "amenity", "city", "user", "state", "place", "review"]
storage = file_storage.FileStorage()
storage.reload()
|
import logging
'''
logging.DEBUG -> 10
logging.INFO ->20
logging.WARNING -> 30
'''
#logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
#logging.basicConfig(level=logging.DEBUG, filename='example.log', fil... |
from web.controllers.api import route_api
from flask import request,jsonify
from application import app,db
import requests,json
from common.models.member.Member import Member
from common.libs.Helper import getCurrentDate
from common.libs.member.MemberService import MemberService
@route_api.route('/member/login',method... |
# Copyright 2021 Intel-KAUST-Microsoft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
import couchdb
couch = couchdb.Server()
def iscodeTaken(code):
db = couch["courses"]
for courseid in db:
if db[courseid]['code'] == code:
return True
return False
def suggestCode(n):
db = couch["courses"]
count = n
for courseid in db:
if count < db[courseid]["code"... |
from vision.ssd.vgg_ssd import create_vgg_ssd, create_vgg_ssd_predictor
from vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd, create_mobilenetv1_ssd_predictor
from vision.ssd.mobilenetv1_ssd_lite import create_mobilenetv1_ssd_lite, create_mobilenetv1_ssd_lite_predictor
from vision.ssd.squeezenet_ssd_lite impor... |
#!/usr/bin/env python3
import extract_audio_wav as eaw
from preprocess_shrek2 import *
s2 = load_only_shrek_from_shrek_2_srt()
s2_lines = [
str(eaw.Ffmpeg_Command(subtitle=sub, mov_path="Shrek_2.wav"))
for sub in s2
]
lines = [line + " &\nwait $!\n" for line in s2_lines]
with open('gen_wav_synchr... |
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
# 显示学生信息
from django.urls import reverse
from students.models import Student
# 学生信息展示页
def student_list(request):
student_list = Student.objects.all()
return render(request,'students/student.html',locals())
# return redi... |
import smtplib
from datetime import date
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from dao.borrow_dao import BorrowDAO
def send_reminder(password, book_recipient_list):
# order:
# start conn, ehlo, start tls, log in, make message object, send it, close conne... |
dict1 = {
'Name' : 'ROHIT',
'Gender' : 'Male',
'Age' : 28,
'Education' : 'B.tech',
'Nationality': 'Indian',
'DOB' : '23-5-1995',
'Religion' : 'Hindu'
}
print("----------------------")
print(dict1.get('Age')) # printing particular items using get.
... |
# Copyright 2017 The TensorFlow 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 required by applica... |
#coding: utf-8
from django.contrib import admin
from ppa_participativo.diretrizes.models import Eixo, Area, Acao
class EixoAdmin(admin.ModelAdmin):
list_display = ('descricao', 'ativo',)
list_filter = ['dt_cadastro', ]
class AreaAdmin(admin.ModelAdmin):
list_display = ('descricao', 'fk_eixo', 'ativo',)
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-08 23:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0004_auto_20160605_2219'),
]
operations = [
migrations.CreateModel(
... |
from datetime import date, timedelta
from django.db import models
from django.db.models import Avg, Sum
from django.db.models.signals import post_save
from django.dispatch import receiver
class Currency(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
clas... |
import datetime
import json
from collections import namedtuple
from copy import deepcopy
from os import listdir
import Augmentor
import numpy as np
from PIL import Image
from src.data.constants import LayerType
from src.data.setup import Constants
'''
I do not own this '
taken from: https://github.com/huyouare/CS231... |
"""Write a function that encrypts a string with a variable rotary cipher.
The function should take in a number and string and shift the string's
characters by that number:
>>> rot_encode(1, 'abcxyz')
'bcdyza'
It should be able to shift characters by any number:
>>> rot_encode(3, 'abcxyz')
'defabc'
It should preser... |
import math
x = int(input())
targetMoney = x
currentMoney = 100
yearCounter = 0
while currentMoney < targetMoney:
yearCounter += 1
currentMoney += currentMoney // 100
print(yearCounter)
|
import os
import random
from copy import deepcopy
import logging
import time
import json
import numpy as np
import torch
from sentencepiece import SentencePieceProcessor as sp
from config import Config
class Reader:
def __init__(self, config):
self.tokenizer = sp(config.kogpt2_tokenizer_path)
se... |
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
post_save.connect(reset_state, sender=self.__... |
# Generated by Django 2.0.8 on 2018-08-21 20:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0091_user_mc_pk'),
]
operations = [
migrations.RemoveField(
model_name='person',
name='current_through',
),
... |
#import necessary libraries
import os
import keras
import numpy as np
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator
from A4.mixup_generator import MixupImageDataGenerator
# setup current work path
baseDir = os.path.abspath('.')
modelPath = os.path.join(baseDir,'A4','efficientNetMixUp_be... |
from pymongo import MongoClient
import RPi.GPIO as GPIO
from hw_pins import hw_pins
import threading
import socket
import pika
import time
import pickle
from rmq_params import rmq_params, rmq_routing_keys
import pytz
from datetime import datetime
current_id = None
def get_current_time():
tz = pytz.timezone('US/... |
"""Rewrites raw M-Lab FQDNs to apply post-processing or annotations."""
import logging
from mlabns.util import message
def rewrite(fqdn, address_family, tool_id):
"""Rewrites an FQDN to add necessary annotations and special-casing.
Performs the following rewrites on an FQDN:
* Adds a v4/v6 annotation i... |
from numpy.core.numeric import NaN
from src.Point import Point
from .RansacLineInfo import RansacLineInfo
import numpy as np
from skimage.measure import LineModelND, ransac
from typing import List
from sklearn.neighbors import KDTree
import statistics
import simplegeometry as sg
from .StoppingCriteria import StoppingCr... |
from .movie_library import spearman_corr
from .movie_library import sentiment_boxoffice_all
from .movie_library import sentiment
from .movie_library import tweet_collector
|
import base64
import hashlib
from Crypto.Cipher import AES
from django.conf import settings
class AESEncrypt:
def __init__(self, key: str = settings.KUNMING_PICC_CLUB_AES_KEY):
self.aes = AES.new(self.get_sha1prng_key(key), AES.MODE_ECB)
@staticmethod
def get_sha1prng_key(key: str) -> bytes:
... |
from typing import Mapping, Union, Optional, Sequence
import numpy as np
from .operation import Operation
from .op_placeholder import OpPlaceholder
from .op_keepdims import OpKeepdims
class OpMin(OpKeepdims):
"""Calculate the minimum of elements."""
def __init__(self,
x: Operation,
... |
from __future__ import print_function
import numpy as np
from astropy.io import fits
from astropy.table import Table
from astropy.io import ascii
import astropy.units as u
c = 299792.458 * u.Unit('km/s')
import matplotlib as mpl
import seaborn as sns
sns.set_style("whitegrid", {'axes.grid' : False})
mpl.rcParams['fo... |
# SANYAM MITTAL
# CE 42
# 18001003110
import sys
input = sys.stdin.readline
def multi_input():
return map(int, input().split())
def array_print(arr):
print(' '.join(map(str, arr)))
def shortest_path(parent, node, dist, graph, visited):
if visited[node]==0 or distance[node]>distance[parent]+dist:
... |
# y = ax + b
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("satislar.csv")
data.sample(10)
data.shape
data.columns
data.... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pygame
from pygame.locals import *
from sys import exit
from vector import Vec2d
background_image = '../image/sushiplate.jpg'
sprite_image = '../image/fugu.png'
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
background = pygame.image.load(backg... |
import turtle
turtle.shape('turtle')
n = 1
while n < 360:
turtle.forward(1)
turtle.left(1)
n = n + 1
input()
|
def trojkat(rozmiar):
gwiazdka = "*"
i = 1
while i <= rozmiar:
print(gwiazdka * i)
i += 1
trojkat(2)
trojkat(3)
trojkat(4)
def trojkatOdwrotny(rozmiaro):
for i in range(rozmiaro,0,-1):
print('*' * i)
trojkatOdwrotny(3)
trojkatOdwrotny(4)
trojkatOdwrotny(5)
def trojkatPira... |
# coding=utf-8
import json
import subprocess
import sys
if __name__ == '__main__':
if len(sys.argv) != 2:
exit
fnt = sys.argv[1]
'''
obj = subprocess.check_output(('otfccdump.exe', '-n', '0', '--hex-cmap', fnt)).decode('utf-8', 'ignore')
obj = json.loads(obj.encode('utf-8')... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('D:\pythonFile\mtest.jpg',0) #直接读为灰度图像
for i in range(2000): #添加点噪声
temp_x = np.random.randint(0,img.shape[0])
temp_y = np.random.randint(0,img.shape[1])
img[temp_x][temp_y] = 255
#9---滤波领域直径
#后面两个数字:空间高斯函数标准差,灰度值相似性标准差
blur = c... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
import json
import sys
import time
import os
import glob
import shutil
import datetime
import argparse
from OCC.Display.SimpleGui import init_display
from OCC.Core.gp import gp_Pnt, gp_Vec, gp_Dir
from OCC.Core.gp import gp_A... |
# Generated by Django 3.2.6 on 2021-08-21 10:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('residential', '0008_residentialdetails_title'),
]
operations = [
migrations.AlterField(
model_name='residentialdetails',
... |
'''
2gbhosting gozlanurlresolver plugin
Copyright (C) 2011 t0mm0, DragonWin
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option... |
from python_imagesearch.imagesearch import imagesearch_loop
from python_imagesearch.imagesearch import imagesearch
from python_imagesearch.imagesearch import imagesearcharea
import pyautogui
import msvcrt as m
import pygetwindow as gw
import time
from time import sleep
import keyboard
timeInterval = 0.5
inn... |
from datetime import datetime
from typing import List, cast
from uuid import UUID
from eventsourcing.application import ProcessingEvent
from eventsourcing.examples.cargoshipping.application import BookingApplication
from eventsourcing.examples.cargoshipping.domainmodel import Cargo
from eventsourcing.examples.searchab... |
from joblib import Parallel, delayed
from farm_energy.layout import read_layout
from power_models import power_v90 as power
from site_conditions.wind_conditions.windrose import read_windrose
from wake_models import jensen_1angle, ainslie_1angle, larsen_1angle, ainsliefull_1angle
def jensen_windrose(layout_file, wind... |
# -*- coding: utf-8 -*-
# © 2018 Hideki Yamamoto
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
from datetime import datetime
class ees_group_tagging_multi_action(models.TransientModel):
_name = 'ees_group_tagging.multi_tag_action'
categories = fields.Man... |
#!/usr/bin/env python
from kafka import KafkaProducer
from flask import Flask, request
from flask import json
app = Flask(__name__)
producer = KafkaProducer(bootstrap_servers='kafka:29092')
def log_to_kafka(topic, event):
"""
This function will first add some metadata (such as: Host, User-Agent, etc) to our ... |
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import math
import torch.nn.functional as F
import pdb
def Entropy(input_):
bs = input_.size(0)
entropy = -input_ * torch.log(input_ + 1e-7)
entropy = torch.sum(entropy, dim=1)
return entropy
def grl_hook(coeff)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.