text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
"""
Use os walk to encrypt or decrypt all PDFs in a tree structure and save as
new file.
"""
import os
import PyPDF2
import EncryptPDF
def pdf_encrypt(filename, password):
'''
Accept filename parameter and create new PDF file as encrypted version
of given file.
'''
print('A... |
############### EDITOR FUNCTIONS ################
# Editor dependent functions
# Should be changed for portability between editors
import sublime, re
# --------------- Debug Log
class log:
sep = ' '
log_file = None
barra = '\n' + '-' * 40 + '\n'
# Join Args
def join(*args, sep = sep):
... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from sklearn import tree
from sklearn.datasets import load_wine
from sklearn.utils import Bunch
from sklearn.model_selection import train_test_split as TTS
import pandas as pd
from pandas import DataFrame, Series
from matplotlib import pyplot as plt
import graphviz
impo... |
from ActionsAnalysis import *
import numpy as np
import time
import cPickle
time.sleep(0*3600)
for fileName in ['new/norm/dummy_all_pu1.0_single_100_norm_d100',
'new/norm/dummy_all_pu1.0_single_100_norm_d25']:
for epochs in ['300']:
aa = ActionsAnalysis(expDir =... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pdb
# Create a dataframe
start = np.array([2015, 2016, 2017, 2019])
end = start + np.array([4, 2, 1, 2])
music = np.array(['pop', 'rock', 'hip hop', 'jazz'])
df = pd.DataFrame({'group':music, 'start':start , 'end':end })
# Reorder it foll... |
from researchdatabasecatalog import IResearchDatabaseCatalog
|
# -*- coding: utf-8 -*-
{
'name': 'Cambio Busqueda Campos',
'version': '0.1',
'category': 'sale',
'description': """
Cambia las funciones de busqueda por defecto en los campos many2one many2many Etc
""",
'author': 'Econube | Pablo Cabezas, Jose Pinto',
'website': 'http://www.econube.cl',
... |
"""
use basic control structure to calculate the sum of values in n*n array
"""
n = 20
data = [[1]*n for _ in range(n)]
total = 0
for i in range(len(data)):
for j in range(len(data[i])):
total += data[i][j]
print(total) |
from click.testing import CliRunner
from mazel.commands.label_common import MakeLabelPassInterrupt, RunOrder
from mazel.main import cli
from .utils import LabelCommandTestCase
class RunCommandTest(LabelCommandTestCase):
def test_command(self):
runner = CliRunner()
result = runner.invoke(cli, ["r... |
def word_count(string):
storage = dict()
empty_dict = {}
bad_chars = [':', ';', ',', '.', '-', '+', '=', '/', '\\', '|', '[', ']', '{', '}', '(', ')', '*', '^', '&', '"']
for word in string.split():
word = ''.join(c for c in word if not c in bad_chars)
word = word.lower()
if len... |
# How do you get a python module that someone else wrote
# PyPi massive python repository for python module
# if you can imagine a piece of software PyPi has it
# PyPi an app store but for python modules
# npm in JS
# maven central repo for Java
# PyPi for Python
# pip is a dependenecy management tool that will insta... |
import collections
import asyncio
import enum
from typing import (
Generic,
Any,
Union,
Optional,
List,
Deque,
Dict,
ContextManager,
Type,
TypeVar,
)
from types import TracebackType
T = TypeVar('T')
Key = Any
OptionalEventLoop = Optional[asyncio.AbstractEventLoop]
class End... |
# -*- coding: utf-8 -*-
import nysol._nysolshell_core as n_core
from nysol.mcmd.nysollib.core import NysolMOD_CORE
from nysol.mcmd.nysollib import nysolutil as nutil
class Nysol_Msep(NysolMOD_CORE):
_kwd ,_inkwd,_outkwd = n_core.getparalist("msep",3)
_disabled_ouputlist = True
def __init__(self,*args, **kw_args)... |
#!/usr/bin/env python
# coding=utf-8
from scrapy.spiders import Spider
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor as link
from scrapy.http import Request, FormRequest
from scrapy.selector import Selector
from illustrious.items import ProblemItem, SolutionItem, AccountIt... |
import os
from code import interact
from koalanlp.Util import initialize, finalize
from koalanlp.proc import SentenceSplitter, Tagger, Parser
from koalanlp import API
class Tokenizer:
def __init__(self, sentence_divider, sentence_tokenizer, sentence_parser):
"""문장 종합 전처리기
"""
... |
from rest_framework import serializers
from .models import Projetos, Atividades, Perfil, Apontamento
class PerfilSerializer(serializers.ModelSerializer):
"""
Classe para serialização dos dados do modelo Perfil e servir uma Api com esses dados
"""
class Meta:
model = Perfil
depth =... |
import xgboost as xgb
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score,accuracy_score,recall_score
import numpy as np
import pandas as pd
from sklearn.preprocessing import Imputer
# boston=load_boston()
# xtrain,xtest,ytrain,ytest=train_... |
from django.shortcuts import render
from django.shortcuts import redirect
from questionnaire.models import Question
from questionnaire.models import Image
from questionnaire.models import User
import uuid
import random
# Create your views here.
def home_page(request):
return render(request, 'home.html')
def sub... |
g_num1 = None
g_num2 = None
def test01(name,like,val=0):
"""测试位置实参和缺省参数"""
print("test01:name = %s like = %s val = %d" %(name,str(like),val))
def test02(num1,num2,arr,dic):
"""测试传递局部变量、全局变量、列表、字典的区别"""
global g_num2
print("\ng_num1 = %d, g_num2 = %d,num1 = %d num2 = %d\narr=%s\ndic = %s" %
... |
import itertools
fav_team = int(input())
total_count = 0
scores = [0] * 4
queue = [
[1, 2],
[1, 3],
[1, 4],
[2, 3],
[2, 4],
[3, 4]
]
for game in range(int(input())):
stat = [int(i) for i in raw_input().split()]
if stat[2] > stat[3]:
scores[stat[0] - 1] += 3
elif stat[3] >... |
from random import randint
number = int(input("Enter sides: "))
first_roll = randint(1, number)
print("First roll:")
print(first_roll)
second_roll = randint(1, number)
print("Second roll:")
print(second_roll)
third_roll = randint(1, number)
print("Third roll:")
print(third_roll)
print("Sum is:")
print(first_roll +... |
import pygame
pygame.init()
canvas = pygame.display.set_mode([500, 250])
#rect(surface, color, (x, y, width, height) [, line width])
pygame.draw.rect(canvas, (255, 255, 255), (225, 100, 50, 50), 1)
#circle(surface, color, center (x, y), radio [, line width])
pygame.draw.circle(canvas, (0, 255, 0), (250, 125), 50, 1)... |
import pytest
from share.schema.exceptions import SchemaLoadError
from share.schema.loader import SchemaLoader
from share.schema.shapes import (
ShareV2SchemaType,
ShareV2SchemaAttribute,
ShareV2SchemaRelation,
AttributeDataType,
RelationShape,
)
@pytest.mark.parametrize('bad_attribute', [
{}... |
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
def backtrack(permutation, l, r):
if l == r:
result.append(permutation.copy())
else:
for i in range(l, r... |
from BFT.positional_embeddings.positional_embedding import BasePositionalEmbedding
from torch import nn
import torch
class LearntEmbeddings(BasePositionalEmbedding):
def __init__(self,
positional_embedding_size,
num_channels,
**kwargs
):
... |
import random
#show a banner
print ("--------------------------------------------------------------------------")
print (" WORD JUMBLE ")
print (" The computer chooses a word and you need to guess it...Good Luck! ")
print ("-------------------... |
from pdb import set_trace as st
import os
import numpy as np
import cv2
import glob
import argparse
import rawpy
#splits = os.listdir(args.fold_A)
splits = glob.glob('*.ARW')
cnt=1
for sp in splits:
path_A = sp
raw = rawpy.imread(path_A)
im_A = raw.postprocess(use_camera_wb=True, no_auto_bright=False, ... |
print("Ishra Hussain")
print("Abdul Hussain")
print("0333-3333333")
print("PIAIC Batch 3 Islamabad")
print("we are working") |
#!/usr/bin/python
# vim: set expandtab ts=4
import unittest
from sympy import bspline_basis
from coords import *
from sympy import *
from sympy import pi
import numpy as np
import mpmath as mp
class Cylinder:
def __init__(self,etha,l,startset):
self.etha=etha
self.l=l
self.rootlist=sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import sys
import re
import StringIO
DEVICES_TO_CHECK = "/dev/sd[a-z]"
WARNING_THRESHOLD = 50
CRITICAL_THRESHOLD = 60
"""
NOTE:
The hddtemp command needs to be run as root.
Paste this into the bottom of /etc/sudoers:
dataloop ALL=(ALL) NOPASSWD: /usr/... |
from python_framework import Controller, ControllerMethod, HttpStatus
from dto import QRCodeDto
@Controller(url = '/login/qr-code', tag='Login', description='Login controller')
class LoginQRCodeController:
@ControllerMethod(url = '/')
def post(self):
return self.service.login.initiateAuthenticationBy... |
/home/miaojian/miniconda3/lib/python3.7/abc.py |
# A list ordered by non-decreasing elements in it.
# Determine how many different elements are in it.
A = list(map(int, input().split()))
s = 1
for i in range(len(A) - 1):
if A[i + 1] != A[i]:
s += 1
print(s)
|
"""
תשע"ה מועד א שאלה 2
"""
import numpy as np
from numpy import random as rn
import matplotlib.pyplot as plt
S0=1
r=0.01
M=10000
T=1
sigma=0.2
N=252
h=T/N
dw=rn.randn(M,N)*np.sqrt(h)
k=np.linspace(0.8,1.2,19)
Y=[]
for x in k:
S=S0*np.ones((M,N+1))
for i in range(0,N):
S[:,i+1]=S[:... |
import requests
from requests.auth import HTTPBasicAuth
import json
import array
import os
class cloudcenter:
def __init__(self, base_url, account_id, api_token):
self.base_url = base_url
self.account_id = account_id
self.api_token = api_token
self.deployments = ""
def __getDep... |
from django.db import models
from django.conf import settings
# Create your models here.
class Post(models.Model):
title=models.CharField(max_length=100)
body=models.TextField()
date=models.DateTimeField(auto_now_add=True)
image=models.ImageField(null=True)
def __str__(self):
return self.tit... |
'''
Created on 11.03.2017
@author: zhechkoz
'''
import math
class MMKGraphItem(object):
def __init__(self, id, vertices):
self.id = id
self.vertices = self.decodeVertices(vertices)
def decodeVertices(self, verticesList):
vertices = []
for i in xrange(0, (len(verticesList) - ... |
'''
Jared Bawden
Project - Balanced Binary Search Tree
'''
from recursioncounter import RecursionCounter
class Node:
''' node class '''
def __init__(self, data, left_child=None, right_child=None):
''' contructor for node class '''
self.data = data
self.left_child = left_child
... |
RED = "\033[0;31m"
GREEN = "\033[0;32m"
PURPLE = "\033[35m"
YELLOW = "\033[93m"
RESET = "\033[0;0m"
SPLIT = " ========================= "
class UI:
@staticmethod
def red(msg):
print(RED + msg + RESET)
@staticmethod
def green(msg):
print(GREEN + msg + RESET)
@staticmethod
de... |
#!/usr/bin/python
import math
a = float( 'Infinity' )
b = float( '-Infinity' )
if 3 < a:
print( "3 is less than infinity" )
if 3 > b:
print( "3 is greater than -infinity" )
|
import io
from contextlib import redirect_stdout
from unittest import mock
import pytest
from share.bin.util import execute_cmd
import share.version
def run_sharectl(*args):
"""run sharectl, assert that it returned as expected, and return its stdout
"""
fake_stdout = io.StringIO()
try:
with... |
#import sys
#input = sys.stdin.readline
def main():
t = int( input())
N = 1000
A = [(t+100)*i//100 for i in range(N)]
F = [True]*(N*(1+t))
for a in A:
F[a] = False
ANS = [i for i in range(N) if F[i]]
for i in range(len(ANS)):
p = i+1
if ANS[i] == ((100+t)*p-1)//t:
... |
import base64
import hmac
import requests
from datetime import datetime, timedelta
def parse_params_to_str(params):
url = "?"
for key, value in params.items():
url = url + str(key) + '=' + str(value) + '&'
return url[1:-1]
def hash_string(qs, secret_key):
mac = hmac.new(bytes(secret_key, enc... |
from django.conf.urls import include, url
from django.contrib import admin
from rapidsignnow import views
urlpatterns = [
# Examples:
# url(r'^$', 'rapidsignnow.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^administrator/',... |
from flask import Flask
from flask import request, make_response, render_template
app = Flask(__name__)
@app.route('/cookie/', methods=['GET'])
@app.route('/cookie/<username>', methods=['POST'])
def cookie(username=None):
if request.method == 'POST':
resp = make_response("SAVE")
resp.set_cookie('u... |
from .project import (
Project,
get_project,
build_rel_path,
run_project_locally,
post_process_scenario_outputs,
DiffOutput,
get_all_available_scenario_paths,
use_tuned_proposal_sds,
)
from .params import ParameterSet, Params
from .timeseries import load_timeseries
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-08-07 23:16
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import messaging.models
import model_utils.fields
import phonenumber_field.modelfields
... |
from backend.user_service.user.domain.rider import Rider
from backend.carpool_request_service.carpool_request.domain.carpool_request \
import CarpoolRequest
from backend.common.messaging.infra.redis.redis_message_publisher \
import RedisMessagePublisher
from backend.common.command.group_create_command import Gr... |
import os
#Variables
s_list = []
c_list = []
e_list = []
u_list = []
temp_list = []
fin_list=[]
period1 = 0
exec1 = 0
server = "server.txt"
ecu2 = "ecu2.txt"
client = "client.txt"
unit = "Unit.txt"
#Main
#First Subfolder
for z in range(0,5):
for y in range(0,11):
os.chdir(r"C:\Users\D-Flow\Desktop\BA\Analyzer Me... |
__author__ = 'Gianluca Barbon'
import time
import sys
import glob
import serial
import socket
import os
import pipes
from threading import Thread
import threading
from serial import Serial
try:
from Queue import Queue
from Queue import Empty
except ImportError:
from queue import Queue
from queue import... |
import paramiko
import os
class node:
def __init__(self, ip):
self.ip = ip
k = paramiko.RSAKey.from_private_key_file("private.key")
self.c = paramiko.SSHClient()
self.c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.c.connect( hostname = ip, username = "cliqruser... |
class Solution:
def maxSubarraySumCircular(self, A: list) -> int:
n = len(A)
if n == 1:
return A[0]
sum_list = [0] * n
sum_list[0] = A[0]
for i in range(1, n):
sum_list[i] = sum_list[i - 1] + A[i]
minnum = min(0, sum_list[0])
maxnum = ... |
# -*- coding: utf-8 -*-
import scrapy
from ..items import MovieName
class VietnamMovieNameSpider(scrapy.Spider):
name = 'vietnam_movie_name'
allowed_domains = ['http://movies.hdviet.com']
urls = ['http://movies.hdviet.com/phim-hdviet-de-cu/trang-{}.html'.format(i) for i in range(1, 3)]
urls.extend(['ht... |
from gevent import monkey
monkey.patch_all()
import werkzeug.serving
from gevent import pywsgi
import os
import unittest
import logging
from datetime import datetime as dt
from flask import (
json,
current_app,
request
)
from gms_services.main.controller.auth_controller import user_auth
from gms_services.m... |
# Starter Python Code
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name:peopledaily
Author:jason
date:2018/3/15
-------------------------------------------------
Change Activity:2018/3/15:
-------------------------------------------------
"""
import re
class PeopleDailyUt... |
def random_number(n):
pass
|
# coding:utf-8
# 交叉
import random;
def crossover(pop, pc, chrom_length = 16):
pop_len = len(pop)
new_pop1 = []
new_pop2 = []
select = random.sample(range(0, pop_len), int(pop_len * pc))
for i in range(len(select) / 2):
c1 = select[i + 1]
c2 = select[i * 2]
r = random.randint(0, chrom_length - 1)
new_pop... |
from typing import List,Optional
from pydantic import BaseModel
class BookBase(BaseModel):
title:str
authors:List[str]
published_date:int
categories:List[str]
average_rating:float
ratings_count:int
thumbnail:str
book_id:str
class Config:
orm_mode = True
class BookT... |
import os
import sys
import mimetypes
import hashlib
from urllib.request import urlopen
from urllib.parse import urlparse
class InvalidURLException(Exception):
pass
class InvalidFileTypeException(Exception):
pass
class DuplicateException(Exception):
pass
def clean_url(url):
result = urlparse(url... |
#!/usr/bin/env python
#encoding:utf-8
#
# Copyright (c) 2015 Ministerio de Fomento
# Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Softw... |
__author__ = 'sannies'
from django.conf.urls import url
from django_cas import views
urlpatterns = [
url(r'^login$', views.login, name='cas_login'),
url(r'^logout$', views.logout, name='cas_logout'),
url(r'^proxycallback$', views.proxy_callback, name='cas_proxy_callback'),
]
|
from itertools import combinations as combi
in_file = open('input_9.txt', 'r'); preamble_size = 25
# in_file = open('test_9.txt', 'r'); preamble_size = 5
def calc_possible(data, current_index, pre_size):
return list(map(lambda x: x[0]+x[1], combi(data[current_index-pre_size : current_index], 2)))
def solve(data, pre... |
import numpy as np
def get_mnist_download_data(path):
f = np.load(path)
x_train = f['x_train']
y_train = f['y_train']
x_test = f['x_test']
y_test = f['y_test']
f.close()
return (x_train, y_train), (x_test, y_test) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 26 18:11:42 2021
@author: chulke
"""
def factorial(n):
if n == 1:
r = 1
return r
f = factorial(n-1)
r = n * f
return r
factorial(4)
#%%
def sumar(lista):
"""Devuelve la suma de los elementos en la lista."""
... |
#!/usr/bin/python3
# vim:fileencoding=utf-8:ts=2:sw=2:expandtab
# Setup the path
import os, os.path, sys
import re
import json
import argparse
import base64
import urllib
import subprocess
import logging
import logging.handlers
from botocore.vendored import requests
try:
from DocStruct.Base import GetSession
fro... |
import io
import datetime
class TrainingFile:
lData = []
oDate = datetime.datetime.now()
print(oDate)
sFilePath = "../../Data/"
sFileTimeStamp = str(oDate.year) + str(oDate.month) + str(oDate.day) + str(oDate.hour) + str(oDate.minute) + str(oDate.second)
sTestFileName = "Test_" + sFileTimeStamp + ".csv"
s... |
__author__ = 'm&g'
import abc
from abc import ABCMeta
# from backtester.models.sizing.single_option_model import SingleOptionSizingModel
# from backtester.models.sizing.single_equity_model import SingleEquitySizingModel
class BaseSizingModel:
__metaclass__ = ABCMeta
@abc.abstractmethod
def initialize(se... |
class AdressHolder:
def __init__(self, street=None, city=None, state=None, code=None):
self.street = street
self.city = city
self.state = state
self.code = code |
#!/usr/bin/python
import exifread
import sys
import logging
#from exifread.tags import DEFAULT_STOP_TAG, FIELD_TYPES
from exifread import process_file, exif_log
import math
def main():
buf=['Make','Model','DateTime','GPSLatitude','GPSLongitude']
if (len(sys.argv) < 2 or len(sys.argv) > 2):
print("Error! - No Imag... |
class StateMachine:
def __init__(self, input_list):
self.tape = input_list
self.index = 0
self.plus_state = 1
self.multi_state = 2
self.final_state = 99
self.current_state = 0
self.get_next_state()
def __str__(self):
return '{self.tape}'.format(self=self)
def update_tape(self, tape):
self.ind... |
# -*- coding: utf-8 -*-
# * Copyright (c) 2009-2017. Authors: see NOTICE file.
# *
# * 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... |
a = 141.10000000000002
a = round(a, 2)
print(a)
print(type(a))
|
#Se desea saber cuántos meses han transcurrido entre los mismos inicios de dos años cualesquiera dados.#
print ("Bienvenido, en este programa te diré cuantos meses hay entre un año y otro.")
primerAño = input ("Escribe el primer año: ")
segundoAño = input ("Escribe el segundo y último año: ")
if (int(primerAño) > int... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
prev = ListNode(0)
... |
__author__ = 'Geoge'
from floraparser.TaxaToCharacters import *
fromdb = False
#fromdb = True
if fromdb:
# query="Select * from AllTaxa where flora_name = 'FZ' and rank = 'species' and genus = 'Salacia' ;"
# query = "Select * from AllTaxa where flora_name = 'FTEA' and rank = 'species' and genus = 'Salacia' ... |
from __future__ import unicode_literals
from .models import Urls,Keywords_Search
from django.conf import settings
import requests
from django.views.decorators.csrf import csrf_exempt
from bs4 import BeautifulSoup
import traceback
from nltk.corpus import stopwords
from urllib import request
stop_words = set(stopwords.... |
import telebot
import config
from telebot import types
from datetime import datetime
bot = telebot.TeleBot(config.TOKEN)
day_of_week = config.day_of_week
start = config.start
end = config.end
timetable = config.timetable1
def gap(str1, str2):
str1 = list(map(int, str1.split(':')))
str2 = list(m... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 12:21:36 2020
@author: degananda.reddy
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LeakyReLU,PReLU,ELU
from keras.layers import Drop... |
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
import numpy as np
import mne
from mne.transforms import _ensure_trans, invert_transform, Transform
from mne.transforms import combine_transforms, apply_trans
from mne.surface import transform_surface_to
from mne.forward._make_forward import _to_forward_dict
... |
# -*-coding:utf-8-*-
from flask import g
from flask_restful import reqparse
from albumy.common.restful import RestfulBase, success_response
from albumy.extensions import login_required
from albumy.models import UserProfile
from albumy.utils.validate import validate_nickname, validate_age
class Profile(RestfulBase):
... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from progress.models import Goal, DayLog
def index(request):
goals = Goal.objects.all()
daylogs = sorted(DayLog.objects.all()[:7], key=lambda k: k.date, reverse=True)
return render_to_response('index.html'... |
num = int(input ("Please choose your number: "))
while num > 1:
if num % 2 == 0:
num = num/2
print(int(num))
else:
num = num*3+1
print(int(num))
|
import torch
a=torch.randint(11,(3,2,2))
b=torch.randint(11,(3,2,2))
print(a,b)
# print(torch.mm(a,b))
print(torch.matmul(a,b))
print(a*b)
# batch1 = torch.randn(2,3,4)
# batch2 = torch.randn(2,4,5)
batch1=torch.randint(10,(3,2,2))
batch2=torch.randint(3,(3,2,2))
res = torch.bmm(batch1, batch2)
print(batch1, batch2)
... |
import bibliopixel.colors as colors
from bibliopixel.animation import BaseGameAnim
import math
from random import randint
import bibliopixel.util as util
import time
class Flappy(BaseGameAnim):
def __init__(self, led, inputDev):
super(Flappy, self).__init__(led, inputDev)
self._speed = 5
s... |
# Generated by Django 2.2.4 on 2019-10-23 23:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0002_auto_20191022_1055'),
]
operations = [
migrations.AlterField(
model_name='category',
name='name',
... |
import numpy as np
from keras import layers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.models import Model
from keras.preprocessing import im... |
# Generated by Django 3.2 on 2021-04-24 13:35
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django_resized.forms
class Migration(migrations.Migration):
dependencies = [
('working_app', '0003_auto_20210424_1443'),
]
operations = [
... |
"""
Json,用于字符串 和 python数据类型间进行转换
Pickle,用于python特有的类型(类,函数)和 python的数据类型间进行转换,使用方法和json一样
json.dumps(data) #将data转化为str类型
json.loads(data) #还原data的数据类型
json不能序列化函数(函数名)、类等对象,但是pickle可以
json提供四个功能:dumps,dump,loads,load
pickle提供四个功能:dumps,dump,loads,load
pickle模块和json模块还是比较实用的,还有许多的信息可以去了解,
那么为什么需要序列化和反序列化这一操作呢?... |
import os
import argparse
import datetime
import re
import numpy as np
import pandas as pd
import geopandas as gpd
import rasterio
import rioxarray
import shapely
import pykrige.kriging_tools as kt
import dask.array as da
from osgeo import ogr, osr, gdal
from rasterio.crs import CRS
from rasterio.warp import reprojec... |
""" This module creates the web server for the catalog application """
import random
import string
import json
import os
import httplib2
import requests
from flask import Flask, render_template, request, redirect, jsonify, url_for, flash
from flask import session as login_session
from flask import make_response
from... |
import tensorflow as tf
from cnn_model import conv_net
from cnn_kicker_model import conv_net_k
model_path = './play_model'
kicker_model_path = './kicker_model'
top_n = 309
kicker_top_n = 5
sess = tf.InteractiveSession()
# init graph
serialized_tf_example = tf.placeholder(tf.string, name='tf_example')
feature_config... |
#import sys
#input = sys.stdin.readline
from collections import defaultdict, deque
from math import log2
def main():
n, k = map( int, input().split())
A = list( map( int, input().split()))
logNK = int(log2(n) + log2(k))
double = [ [0]*(logNK+1) for _ in range(n)]
d = defaultdict( lambda :-1)
for... |
#!/usr/bin/python
import csv
import json
import sys
try :
fileName = sys.argv[1]
except IndexError :
sys.stderr.write("USAGE: csv2json.py filename.csv")
sys.exit(1)
fp = open(fileName, 'r')
reader = csv.reader(fp)
obj = []
first = True
for line in reader :
if first :
first = False
... |
import common_vars as c_vars
import pandas as pd
import numpy as np
from datetime import datetime
from scipy import sparse
import pickle
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from imblearn.over_sampling import SMOTE
from sklearn.feature_selection import chi2
fr... |
from .api_baidu import BaiduCrack
from .api_baidu import AsyncBaiduCrack
|
# Generated by Django 3.0.1 on 2020-01-09 07:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('FinaceNote', '0007_auto_20200109_1304'),
]
operations = [
migrations.RenameField(
model_name='upload',
old_name='user_name_o... |
from filemanager.mongodb import (file_collection)
from filemanager.dao.file import FileMongoDBDao
def verify_file_exist(file_id:str):
file_dao=FileMongoDBDao(file_collection)
file=file_dao.get_file(file_id)
if not file:
return False
return True
|
import datetime
import bs4
import requests
from collections import namedtuple
import urllib.parse
from db_db import *
InnerBlock = namedtuple('Block', 'title, anons,full_text,img,date,url')
class Block(InnerBlock):
def __str__(self):
return f'Название: {self.title}\nКраткое описание: {self.anon... |
#coding:utf-8
from django import forms
from .models import SeoData
class SeoDataForm(forms.ModelForm):
class Meta:
model = SeoData
exclude = ()
# fields = ("url", "title_tag", "meta_description", "page_h1")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.