text stringlengths 38 1.54M |
|---|
# Generated by Django 3.2.4 on 2021-06-20 11:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0012_auto_20210611_0144'),
]
operations = [
migrations.AddField(
model_name='order',
name='canceled',
... |
import datetime
import decimal
import ipaddress
import uuid
import pytest
from pysandra import constants, exceptions, messages
from pysandra.constants import Consistency, Events, Opcode, SchemaChangeTarget
from pysandra.core import SBytes
from pysandra.types import Row
def test_messages_response_create_bad():
w... |
import os
from PyTabParser import ByteReader, TabException
from abc import ABC, abstractmethod
class BaseGuitarproTab(ABC):
def __init__(self, file_path):
if not os.path.exists(file_path):
raise Exception(f'[{file_path}] does not exist')
if not os.path.isfile(file_path):
raise Exception(f'[{fi... |
import asyncio
from typing import NoReturn
from gloop.models.remote_player import RemotePlayer
class RemoteParty(list):
async def broadcast(self, message: str) -> NoReturn:
player: RemotePlayer
for player in self:
await player.send(message)
async def multicast(self, emitter: Re... |
import datetime
import time
import random
from flask import request
import data_handler
import bcrypt
def from_timestamp_datetime(user_questions):
for question in user_questions:
question['submission_time'] = datetime.datetime.fromtimestamp(int(question['submission_time'])).strftime('%Y-%m-%d %H:%M:%S')
... |
from pymongo import MongoClient
class MongoHandler:
def __init__(self):
self.__client = MongoClient(
'mongodb://admin:admin123@ds215563.mlab.com:15563/?authSource=berman_monitoring&authMechanism=SCRAM-SHA-1&retryWrites=false')
self.db = self.__client.berman_monitoring
|
#
#
#
def find_device(vc,vop,arg):
vn = 'mr_chooser_list' # vn: view name
vid_type = VID_TYPE_NAME
return view_list_op(vc,vn,vid_type,vop,arg)
#
#
#
def is_mr_chooser_list(vc,vop):
vn = 'mr_chooser_list' # vn: view name
vid_type = VID_TYPE_NAME
return view_op(vc,vn,vid_type,vop,vpa... |
from typing import List, Optional
from django.conf import settings
from django.template.loader import render_to_string
from subscribe.models import Subscribe, Letter
# from .models import News
SUBSCRIPTION_CODE = 'news'
SITE_DOMAIN = getattr(settings, 'SITE_DOMAIN', 'localhost:8000')
#
# def create_subscription_let... |
#funcion de saludo.
def saludar():
print ("Hola, bienvenido a mi primer programa de funciones!")
#Funcion de multiplicacion.
def multi():
print("Escribe un numero: ")
numX = int(input())
print("Escribe un segundo numero: ")
numY = int(input())
result = numX * numY
print ("El resultado de la multiplic... |
import numpy as np
import pandas as pd
import warnings
from .sniffer import CSVSnifferList
from .helpers_ui import *
# ******************************************************************
# helpers
# ******************************************************************
def sniff_settings_csv(fname_list):
... |
from pandas import read_csv
reader = read_csv('clean2.csv', chunksize=50001)
for chunk in reader:
print(chunk)
|
import torch
from .base_optimizer import Optimizer
class Adagrad(Optimizer):
def __init__(self, model_params, lr=1e-3, momentum=0.9):
super(Adagrad, self).__init__(model_params, lr, momentum)
self.acc_sqr_grads = [torch.zeros_like(p) for p in self.model_params]
@torch.no_grad()
def ste... |
from django.conf.urls import url
from . import views
from django.contrib.auth import views as authViews
urlpatterns=[
url(r'^signup/$',views.signup,name='signup'),
url(r'^login/$',views.login_user,name="login.html"),
url(r'^logout/$',authViews.logout,{'template_name':'userauth/logout.html'}),
]
|
from django.db import models
from django_serializable_model import SerializableModel
class User(SerializableModel):
email = models.CharField(max_length=765, blank=True)
name = models.CharField(max_length=100)
# whitelisted fields that are allowed to be seen
WHITELISTED_FIELDS = set([
'name',
... |
import tempfile
import os
SLACKVIEWER_TEMP_PATH = os.path.join(tempfile.gettempdir(), "_slackviewer")
|
from flask import abort, Flask, jsonify, request
import json
SOURCE = 'raw_content/items.json'
TARGET = 'contents/items.json'
records = read_raw_records()
id_counter = records[0]['id']
objects = load_objects()
app = Flask(__name__)
@app.route('/record', methods=['GET'])
def get_next_record():
"""Respond with t... |
from torch_snippets import stem, logger, os, unzip_file, P
from torch_snippets.registry import Config, AttrDict, registry
from fastai.vision.all import *
import torch_snippets
from auto_train.classification.custom_functions import *
from auto_train.classification.timmy import create_timm_model
from auto_train.common i... |
# -*-coding:utf-8-*-
from pymongo import MongoClient
from scrapy import Item
class MongoDBPipeline:
def open_spider(self, spider):
db_uri = spider.settings.get('MONGODB_URI', 'mongodb://localhost:27017')
db_name = spider.settings.get('MONGODB_DB_NAME', 'scrapy_default')
self.db_client = Mo... |
import json
import r2pipe
global FILE
FILE = "nuevo"
def main():
addr_int = []
r2file = open_file()
aaanal_file(r2file)
export_int_file(r2file)
addr_int = import_int_file()
extract_eax(r2file, addr_int)
def open_file():
ff = r2pipe.open(FILE)
return ff
def aaanal_file(ff):
ff.cmd("aaa")
def export_int_... |
def solution(S, P, Q):
min_factors = []
for p, q in zip(P, Q):
sequence = S[p:q+1]
if 'A' in sequence:
min_factors.append(1)
elif 'C' in sequence:
min_factors.append(2)
elif 'G' in sequence:
min_factors.append(3)
elif 'T' in sequence... |
INVALID_ARGUMENT = 'invalid argument'
UNKNOWN = 'unknown'
NOT_FOUND = 'not found'
SERVER_UNAVAILABLE = 'service unavailable'
HEALTH_CHECK_ERROR = 'health check failed'
class TRError(Exception):
def __init__(self, code, message, type_='fatal'):
super().__init__()
self.code = code or UNKNOWN
... |
#The insult machine!
import random
#Lol wow! Just having fun here
#Pretty simple program idea
#Getting familiar with the random module
insult_list1 = ['greasy','ludicrous', 'vicious', 'dozy', 'idiotic', 'imbecilic', 'pointless', 'mindless', 'moronic']
insult_list2 = ['piece']
insult_list3 = ['close', 'close-graine... |
import requests
import random
import re
from lxml import html
import execjs
from generate_function import generate_eid, generate_d
session = requests.Session()
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
... |
number = int(input("Enter a number, and I will tell you all of that numbers' divisors: "))
divisor_list = []
for n in range(1, number+1):
if(number % n == 0):
divisor_list.append(n)
print(divisor_list) |
#7/31/14
#Determine whether a number (N) is prime or not
#We only have to check numbers up to the integer square root of N.
import math
#This determines whether n is prime
#INPUT - a number to check
#OUTPUT - Ture if it is prime or False if is is not
def is_prime(n):
is_it_prime = True #We start with an assumpt... |
import os
from keras.utils.np_utils import to_categorical
import cv2
from keras.preprocessing import image
from keras.preprocessing import image
import json
import params
import numpy as np
import random
def prep_image(filepath, train_dir):
filename = os.path.basename(filepath)
jsonData = json.load(open(file... |
from django.db import models
# Create your models here.
class Designation(models.Model):
id=models.AutoField(primary_key=True)
type=models.CharField(max_length=50)
objects = models.Manager()
class Station(models.Model):
id=models.AutoField(primary_key=True)
contact=models.IntegerField()
addres... |
## solution1 .DFS
def riverSizes(matrix):
visited = [[False for _ in matrix[0]] for _ in matrix]
sizes = []
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if not visited[row][col]:
if matrix[row][col] == 1:
currentSize = calculateSize... |
"""
For this to work you have to install pdfkit and wkhtmltopdf see:
https://github.com/JazzCore/python-pdfkit
VERY IMPORTANT:
IN LINUX a bug had to be solved by patching the pdfkit library:
Had to install xvfb:
sudo apt-get install xvfb
And then add 'xvfb-run' infront of the wkhtmltopdf command inside the library do... |
# coding:utf-8
####################################################
#//E:/wamp/www/application/pycharm/phantomjs-2.1.1-windows/phantomjs-2.1.1-windows/bin/phantomjs.exe E:/wamp/www/application/pycharm/project1/Rendering.js 354
import sys
import re
import urllib
import urllib2
from bs4 import BeautifulSoup
f... |
# --- Day 21: RPG Simulator 20XX ---
# Little Henry Case got a new video game for Christmas. It's an RPG, and he's stuck on a boss.
# He needs to know what equipment to buy at the shop. He hands you the controller.
#
# In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes ... |
from tkinter import *
class Window (Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master=master
self.init_window()
def init_window(self):
self.master.title("GUI")
self.pack(fill=BOTH, expand=1)
# quitButton = Button(self, text="Quit"... |
a=int(input("enter a number:"))
if a>0:
print("positive number")
elif a==0:
print("0")
else:
print("negative number")
|
import numpy as np
import cv2
import random
cap = cv2.VideoCapture('rally2.mpg')
fgbg = cv2.BackgroundSubtractorMOG(1, 1, 0.9, 25)
while(cap.isOpened()):
ret, frame = cap.read()
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#hsv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
b,g,r = cv2.split(frame)
... |
http://docs.scipy.org/doc/scipy/reference/scipy-optimize-modindex.html
scipy
scipy.cluster
scipy.cluster.hierarchy
scipy.cluster.vq
scipy.constants
scipy.fftpack
scipy.fftpack.convolve
scipy.integrate
scipy.interpolate
scipy.io
scipy.io.arff
scipy.io.netcdf
... |
class Node:
def __init__(self,key,val):
self.key = key
self.val = val
self.children = []
self.color = None
def addChild(self,c):
self.children.append(c)
class Graph:
def __init__(self):
self.vertices = {}
def addVertex(self,key,val):
n = Node(... |
import pandas as pd
def parseData(filename, outfilename=None):
if filename.endswith('.xlsx'):
data = pd.read_excel(filename)
elif filename.endswith('.csv'):
data = pd.read_csv(filename)
else:
raise Exception('File Type Not Supported: file should be xlsx or csv')
df_key = ['ye... |
rows = int(input())
bus = []
answer = "NO"
for row in range(rows):
seats = input()
if "OO" in seats and answer == "NO":
seats = seats.replace("OO", "++", 1)
answer = "YES"
bus.append(seats)
if answer == "YES":
print(answer)
for row in bus:
print(row)
else:
p... |
import signal
from threading import Event
from types import FrameType
from django.core.management.base import BaseCommand
class DaemonCommand(BaseCommand):
def _setup_exit_event(self): # pragma: no cover
exit = Event()
def _quit(signo: int, frame: FrameType | None):
exit.set()
... |
from Automatos import Automato
class EpsilonTransicao(Automato):
def __init__(self, automato):
super(EpsilonTransicao, self).__init__()
self.Estados = automato.Estados
self.Alfabeto = automato.Alfabeto
self.Finais = automato.Finais
def imprimir(self):
return supe... |
import enum
__all__ = ("FrequencyDbName",)
class FrequencyDbName(str, enum.Enum):
DAILY = "daily"
EASTER = "easter"
IRREGULAR = "irregular"
MONTHLY = "monthly"
ONCE = "once"
WEEKLY = "weekly"
XDAYS = "xdays"
YEARLY = "yearly"
def __str__(self) -> str:
return str.__str__(s... |
# 떡볶이 떡 만들기
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
rice_cakes = list(map(int, input().split()))
rice_cakes.sort()
def binary_search(target, rice_cakes):
start = 1
end = rice_cakes[-1]
answer = 0
while start <= end:
mid = (start + end) // 2
length = 0
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/11/13 15:23
# @Author : Zhangyp
# @File : response_jsonify.py
# @Software: PyCharm
# @license : Copyright(C), eWord Technology Co., Ltd.
# @Contact : yeahcheung213@163.com
"""返回的数据json序列化"""
from flask import jsonify
# 查询消息
def res_jsonify(data):
... |
from jinja2 import Environment, FileSystemLoader, select_autoescape
JINJA_ENV = Environment(
loader=FileSystemLoader('templates'),
autoescape=select_autoescape(['html', 'xml'])
)
NAME = 'Connor Wallace'
WEBSITE = 'cowalla.me'
|
import os
import chainer
from chainer.datasets import mnist
from chainer import iterators
from chainer import optimizers
from chainer import training
from chainer.training import extensions
from fw.base_trainer import base_trainer
class chainer_trainer(base_trainer):
def __init__(self):
super(chainer_tr... |
from texture_builder import TextureBuilder
from texture import Texture
from palette import Palette
from folder import Folder
import os.path
from functools import partial
from PyQt5.QtCore import QDir
from PyQt5.QtGui import QImage, QPalette, QPixmap
from PyQt5.QtWidgets import (QAction, QFileDialog, QLabel,
QM... |
# -*- coding:utf-8 -*-
'''
@author: leisun
@contact: leisun98@gmail.com
@file: eng_K-STATE_parser.py
@time: 11/19/18 2:18 PM
'''
from utils.connection import *
import time
from db.operateSql import People, connect_db
db_url = "mysql+pymysql://root:123456@localhost/sc"
session = connect_db(db_url)
def getInf... |
# @Time : 2020/3/15 13:20
# @Author : AeishenLin
# @File : useCombobox.py
# @Describe: 使用列表框
# 列表框:(Listbox) 可供用户单选或多选所列条目以形成人机交互。
# 列表框控件的主要方法:
# 方法 功能描述
# curselection() 返回光标选中项目编号的元组,注意并不是单个的整数
# delete(起始位置,终止位置) 删除项目,终止位置可省略,全部清空为delete(0,END)
# ... |
import timeit
from adk.knapsack import record_best, Item
def trials():
"""
Search small space to determine input set to knapsack that offers greatest
difference between dynamic programming and approximate. Once computed, use
these values in adk.book.chapter11.py
"""
# 83 250 4 2 457
... |
from netCDF4 import Dataset
from netCDF4 import num2date
import datetime as dt
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import sys
import os
from matplotlib import rc
# rc('text', usetex=True)
for path_file in sys.... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MyPlugin.ui'
#
# Created: Mon Mar 20 16:04:46 2017
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attri... |
#@+leo-ver=5-thin
#@+node:ekr.20101110092851.5812: * @file ../plugins/initinclass.py
#@+<< docstring >>
#@+node:ekr.20101112180523.5421: ** << docstring >>
""" Modifies the Python @auto importer so that the importer
puts the __init__ method (ctor) into the body of the class node.
This makes it easier to keep the insta... |
factor = int(input())
counter = int (input())
multiple = factor * counter
mylist = []
for num in range(factor, multiple +1, factor):
mylist.append(num)
print(mylist) |
from django.views import generic
from django.urls import reverse_lazy
from django.utils import timezone
from django.contrib.auth import decorators
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from ..forms import NewHourlyRateForm, NewUserForm, NewStaffForm, ResetPasswordForm, EditConfi... |
#! usr/bin/env python3
t=int(input().strip())
for i in range(t):
m=int(input().strip())
n=int(input().strip())
arr=list(map(int,input().split()))
temp=[i for i in arr]
indexdict=dict()
for i in range(len(arr)):
if not arr[i] in indexdict:
a=[]
a.append(i)
... |
"""
HTML Page module.
"""
import polyglot.text
import re
import parsel
import selectolax.parser
import sys
class HtmlPage:
def __init__(self, html):
self.html = html
self.selector = parsel.Selector(text=self.html)
self.alpha_numeric_regex = re.compile('[\W_]+', re.UNICODE)
def __str__... |
"""
332. Reconstruct Itinerary
Medium
1265
792
Add to List
Share
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order.
All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there a... |
from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
driver = webdriver.Chrome('/Users/quatre/PycharmProjects/Bogo_hackathon/chromedriver')
driver.implicitly_wait(3)
# TODO: 불러오기가 끝났으니 제품명을 싸그리 크롤링... |
"""
Alexandra Triampol
6/21/16
This code creates a greeting that uses user input
such as their full name, age, and favorite ice cream.
"""
# takes in user input for the greeting
fullName = input("What is your first and last name?: ")
age = input("How old are you? (if you don't mind me asking): ")
iceCream = input("Wh... |
import html
with open('processed_ingredients.txt', 'r') as infile:
with open('strings.xml', 'w') as outfile:
outfile.write("<string-array name=\"master_ingredients\">\n")
for line in infile:
htmlStuff = html.escape(line.strip())
words = htmlStuff.split(' ')
... |
with open('phone_data.txt', 'r') as file:
phone_numbers = file.read().splitlines()
# change lines to dictionaries
def parse(line):
"str -> dict"
line = line.replace("-", "")
if len(line) > 10:
line = line[1:]
new_dict = {'area': line[:3],
'exchange': line[3:6],
... |
import pandas as pd
import pandas.io as web
import numpy as np
def HA(df):
df["HA_Close"] = (df["Open"] + df["High"] + df["Low"] + df["Close"])/4
ha_o = df["Open"] + df["Close"]
df["HA_Open"] = 0.0
HA_O = df["HA_Open"].shift(1) + df["HA_Close"].shift(1)
df["HA_Open"] = np.where(df["HA_Open... |
# This file should be used to store all of the magic numbers
# so that it is easy to modify them.
c_puct = 1 # This controls how much exploration happens in the MCST |
#!/usr/bin/python3
# (C)2014 L0j1k@L0j1k.com
"""Perform a variety of byte-level operations on files or strings.
optool.py [file1] [file2]
-> xor file1 with file2
optool.py -b [bytes1] [file1]
-> xor bytes1 with file1
optool.py [file1] -b [bytes1]
-> xor file1 with bytes1
optool.py -B [bytes1] [bytes2]
-> xor bytes1 wi... |
from gmail import GMail, Message
from random import randint
sickness_list = ["trĩ", "đau bụng", "tiêu chảy", "thương hàn"]
i = randint(0, len(sickness_list) - 1)
#1. Select a sickness randomly
sickness = sickness_list[i]
html_template = '''
<p>Chào sếp,</p>
<p style="padding-left: 30px;">Ngày mai em b... |
# -----------------------------
# Using the PdfFileWriter Class
# -----------------------------
from PyPDF2 import PdfFileWriter
pdf_writer = PdfFileWriter()
page = pdf_writer.addBlankPage(width=72, height=72)
print(type(page))
from pathlib import Path # noqa
with Path("blank.pdf").open(mode="wb") as output_file... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from slack_g_cal.parse import JSON
from .datetime_ import WitDatetimeContainer
class MessageResponse(JSON):
""" Container wrapping responses from the Message API """
def __init__(self, **res_json):
self.datetime_keys = ['datetime']
... |
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import sys
import time
import json
import subprocess
import argparse
from framework.print.buffer import Print... |
import pickle
from flask import Flask, request
app = Flask(__name__)
@app.route('/get_tf-idf', methods=['GET'])
def print_square():
recieved_docs = request.get_json(force=True)['sents']
tf_idf_matrix = tf_idf.transform(recieved_docs).toarray().tolist()
return {'output': tf_idf_matrix}
if __name__ == "_... |
from collections import deque
squares = [1, 4, 9, 16, 25]
# slice operators return a new copy of the list on which the operator was invoked
var = squares[:]
print "squares[0] was not changed: " + str(squares)
# the concat operator can be used to append a list to another list
l1 = [1, 2]
l2 = [3, 4]
print "concat lis... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright (c) 2014, Battelle Memorial Institute
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistrib... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import logging
LEVEL = logging.INFO
LOGFILE, LOGFILEMODE = '', 'w'
HANDLERS = [logging.StreamHandler(sys.stdout)]
if LOGFILE:
HANDLERS.append(logging.FileHandler(filename=LOGFILE, mode=LOGFILEMODE))
logging.basicConfig(format='%(asctime)s %(levelname)-8s ... |
words = ['Grapes','Mango','Tabel','Apple','Cricket','Republic','Elephant','College','Traveller','Achieve','Beleiver','America','Indi','Facebook','Birthday','Monsoon','Movies','Finished','Process','Untitled','Script','Project']
def labelSlider():
global count,sliderWords
text = 'Welcome to typing speed In... |
from django.urls import path
from .views import EmpresaCreate, EmpresaUpdadte
urlpatterns = (
path('novo', EmpresaCreate.as_view() , name = 'create_empresa'),
path('editar/<int:pk>', EmpresaUpdadte.as_view() , name = 'update_empresa'),
)
|
# Created by: Gavin Zhou
# Created on: Oct 12 2017
# Created for: ICS3U
import ui
tax = 0.13
def calculate_touch_up_inside(sender):
pizza_size = view['pizza_size_textfield'].text
topping = view['amount_topping_textfield'].text
if pizza_size == 'large':
pizza_size_cost = 6
e... |
from .api import goods_jingfen_query
from .api import goods_promotiongoodsinfo_query
from .api import goods_query
|
def getHint(index):
hints = ["11 players.", "Tired and very far.", "Yellow ball and racket.", "The sport from china.", "Shuttlecock."]
return (hints[index])
def getAnswer(index):
answers = ["soccer", "marathon", "tennis", "tabletennis", "badminton"]
return (answers[index]) |
from time import process_time as pt
def runtime(function):
time = pt()
function()
print(f'Runtime: {pt() - time} seconds')
|
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
from torchvision.datasets import CIFAR10
import torchvision.transforms as transforms
import torch.optim as optim
import torch.nn as nn
from torch.utils.data import DataLoader
from architecture import CNN
# The o... |
from __future__ import print_function
from RegOptim.image_utils import check_for_padding
from RegOptim.utils import get_subset
from RegOptim.utils import save_params, import_func
from RegOptim.optimization.pipeline_utils import create_exp_folders, create_template, \
pad_template_data_after_loop
import numpy as np
... |
#int(a,b,c)
print("Введите числа для обмена")
a=input()
b=input()
c=a
a=b
b=c
print(a,b) |
# Generated by Django 2.1.5 on 2019-05-25 18:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('settings', '0007_auto_20190525_2015'),
]
operations = [
migrations.CreateModel(
name='SocialUrl',
fields=[
... |
'''
Script to plot PPSD data based in
https://docs.obspy.org/tutorial/code_snippets/probabilistic_power_spectral_density.html
'''
import os
import glob
from obspy.signal import PPSD
from obspy.imaging.cm import pqlx
from parameters_py.config import (
OUTPUT_FIGURE_DIR,TIME_OF_WEEKDAY_DAY,TIME_OF_WEEKDAY_START_H... |
import os
try:
while True:
print(" FUS RO DA!!")
os.system('cls')
except KeyboardInterrupt:
os.systme("Pause")
|
from WealthStream import app
from flask import render_template
@app.route("/")
def index():
return render_template('index.html')
@app.after_request
def add_header(r):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
... |
import os
import sys
import argparse
import optparse
import platform
import pkgutil
UNIX_DIR_FALLBACK = '~/.config'
WINDOWS_DIR_VAR = 'APPDATA'
WINDOWS_DIR_FALLBACK = '~\\AppData\\Roaming'
MAC_DIR = '~/Library/Application Support'
def iter_first(sequence):
"""Get the first element from an iterable or raise a Va... |
class xPaths(object):
keys = ['rank', 'company', '3-yr growth', 'revenue', 'industry', 'state', 'metro', 'years']
view_per_page_input = '//*[@id="show_input"]'
scroll_down = '//*[@id="show_input"]/div[3]'
two_hundred_per_page = '//*[@id="show_input"]/div[3]/div[6]'
more_columns = '//*[@id="column_he... |
import dataclasses
import json
import logging
from typing import List
import pyfuse3
import pyfuse3_asyncio
from telethon.hints import Entity
from telethon.tl import types
from telethon.utils import get_display_name
from tqdm import tqdm
from .tgclient import TelegramFsClient
from .tgvfs import TelegramFsAsync
from .... |
import os
import sys
print("CPU:{}".format(os.cpu_count()),end=',')
print("RECLIMIT:{}".format(sys.getrecursionlimit()),end=',')
print("EXEPATH:{}".format(sys.executable),end=',')
print("ENDIAN:{}".format(sys.byteorder),end=',')
print("UNICODE:{}".format(sys.maxunicode))
|
# -*- coding: utf-8 -*-
from odoo import fields, models, api
from collections import namedtuple
from odoo.exceptions import UserError
from odoo.tools.float_utils import float_compare
import re
#Bugget Expense Report
class Bex(models.Model):
_name = 'budget.expense.report'
_inherit = ['mail.thread']
_orde... |
class SignalPoint(object):
def __init__(self):
self.lat = 0.0
self.lon = 0.0
self.sig = 0.0
def new_point(self, lat, lon, sig):
self.lat = lat
self.lon = lon
self.sig = sig
def print_point(self):
print str(self.lat) + " " + str(self.lon) + " " + str(... |
"""terraform_to_ansible/cli.py"""
import argparse
from terraform_to_ansible.release import __package_name__, __version__
def cli_args():
"""Console script for terraform_to_ansible."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--ansibleHost",
help="Use private or public IPs"... |
import logging
import numpy as np
import sys
import topi.nn
import tvm
from tvm import autotvm
def bitpack(Anp, dtype="uint32"):
A = tvm.placeholder(Anp.shape, name="A", dtype=str(Anp.dtype))
B = topi.nn.bitpack(A, 1, 1, 1, dtype)
s = tvm.create_schedule(B.op)
fn = tvm.build(s, [A, B], "llvm -mcpu=core... |
# External Libraries
import bcrypt
from quart import abort, request
# Sayonika Internals
from framework.models import Mod, User, ModAuthor
from framework.objects import jwt_service
class Authenticator:
"""
Class for checking permissions of users, and hashing passwords.
"""
@classmethod
async def... |
arr = list(map(int, input().split(' ')))
k = int(input())
arr.sort()
count = 0
print(arr)
for i in range(len(arr)):
if(arr[i]<k):
count += 1
for j in range(i+1,len(arr)):
if((arr[i]*arr[j])<k):
count += 1
else:
break
else:
break
... |
# 定义苹果的单价 8.5/斤
price = 8.5
# 2. 挑选苹果(7.5斤)
weight = 7.5
# 3. 计算付款金额
money = weight * price
# 只要买苹果,就返5元
money = money - 5
print(money) |
#!/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import json
import tornado.ioloop
import tornado.websocket
import do_sql
from tornado.web import url
class BaseHandler(tornado.web.RequestHandler):
cookie_username = 'username'
def get_current_user(self):
userna... |
import demistomock as demisto # noqa
import ExpanseRefreshIssueAssets
EXAMPLE_INCIDENT = {
'CustomFields': {
'expanseasset': [
{'assettype': 'Certificate', 'assetkey': 'fakeMD5', 'id': 'id-old-certificate'},
{'assettype': 'IpRange', 'assetkey': 'fakeIPRange', 'id': 'id-old-iprang... |
#python是动态语言,根据类创建的实例可以任意绑定属性,给实例绑定属性的方法是通过实例变量,或者通过self变量
class Student(object):
def __init__(self,name):
self.name=name
s=Student('Bob')
s.score=90
#在编写程序的时候,千万不要对实例属性和类属性使用相同的名字,因为相同名称的实例属性将会屏蔽掉类属性,但是当你删除实例属性后,再使用相同的名称
#访问到的是类属性
|
class Solution:
# @param {character[][]} board
# @return {void} Do not return anything, modify board in-place instead.
def bfs(self, x, y, board):
m = len(board)
n = len(board[0])
if board[x][y] != '0': return
board[x][y] = '*'
queue = [(x, y)]
d = [[-1, 0], [... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.