text stringlengths 38 1.54M |
|---|
import urllib.request
import requests
class HtmlUtil:
def __init__(self, url):
self.url = url
self.suffix = ""
def changeUrl(self,url):
self.url = url
def setSuffix(self,suffix):
self.suffix = suffix
def getPage(self):
req=urllib.request.Request(s... |
#!/usr/bin/env python3
import os
import logging
import signal
import traceback
import zulip
import sys
import argparse
import re
import configparser
from collections import OrderedDict
from types import FrameType
from typing import Any, Callable, Dict, Optional
from matrix_client.errors import MatrixRequestError
fro... |
#########################################
# Triangle - Terrain
#########################################
scl = 30
t = 0
DELAY = 5 * 100
def setup():
size(800, 800)
global w
global h
global cols
global rows
global terrain
w = 1400
h = 1200
cols = w / scl
rows = h / scl
def d... |
from itertools import product
import numpy as np
def mohapatra(a, b):
""" Matrix multiplication for nxn-matrix of positive integers
Inspired by
https://github.com/ShrohanMohapatra/matrix_multiply_quadratic
and reference:
S. Mohapatra, (2018).
"A new quadratic-t... |
from resources.models import Users, Posts, Likes
def menu():
print("MENU")
print("1. Crear usuario")
print("2. Mostrar usuarios")
print("3. Acceder")
print("4. Salir")
selection = input("Ingrese su selección: ")
print("----------------------------------")
return selection
def menu_log():
print("MENU... |
# Count the number of prime numbers less than a non-negative number, n.
# Example:
# Input: 10
# Output: 4
# Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
class Solution:
def countPrimes(self, n: int) -> int:
count = 0
primes = [False for i in range(n+1)]
for ... |
"""
This module includes various AWS-specific functions to stage data in S3 and deal with
messages in SQS queues.
This module relies on the harmony.util.config and its environment variables to be
set for correct operation. See that module and the project README for details.
"""
import boto3
from botocore.config import... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
class UserProfile(models.Model):
USER_CHOICES = (
('1', _('Producer')),
('2', _('Agency')),
('3', _('Client')),
('4', _('Guest')),
)
use... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from videostream import Ui_VideoStream
from developer import DialogDeveloper
from info import DialogInfo
class Ui_MainWindow(object):
def __init__(self):
self.ui = Ui_VideoStream()
self.startBtn =... |
import sys
import json
def hw():
print 'Hello, world!'
def lines(fp):
print str(len(fp.readlines()))
def calculateSentiment(tweet):
terms = tweet.split()
global totalTerms
global termsFreq
for term in terms :
if term in termsFreq.keys():
termsFreq[term] +=1
else:
... |
#!/usr/bin/env python
#encoding=utf-8
import os,sys,time,md5
from unctrlpy.lib import osaBatchLib
from unctrlpy.lib.osaFileRecv import file_recv_main
from unctrlpy.lib import hostSocket
from unctrlpy.lib import osaSysFunc
from unctrlpy.etc.config import SOCKET,FSOCKET,DIRS
from unctrlpy.lib.osaUtil import save_log
'''
... |
import flask
from flask import request, jsonify, Response
import json
import netprog
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['GET', 'POST'])
def root():
return Response(json.dumps({
"status": True,
"message": "Forbidden"
}, indent=4), status=403, mimetyp... |
#!/usr/bin/env python
import imp
import os
import re
ETC_PASSWD_REGEX = (
"(?P<username>[a-z\d_\-.]+):"
"(?P<pw_placeholder>[\d\w]*):"
"(?P<uid>\d+):"
"(?P<gid>\d+):"
"(?P<gecos>.*):"
"(?P<homedir>[/\w \-]+):"
"(?P<shell>[/\w ]+)"
)
ETC_SHADOW_REGEX = (
"(?P<username>[a-z\d_\-.]+):"
... |
from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages
import bcrypt
from.models import *
def index(request):
return render(request, "loginreg.html")
def register(request):
errorsFromValidator = User.objects.registrationValidator(request.POST)
print("ERRORS FROM... |
from collections import Counter
print("Welcome to the Frequency Analysis App")
#List of elements to remove from all text for analysis
non_letters = ['1','2','3','4','5','6','7','8','9','0',' ','.',',','!','?',',','"',"'",':',";",'(',')','%','&','#','$','\n','\t']
#Information for the first key phrase 1
key_phrase_1 =... |
from math import tanh
from typing import Tuple
from bot.data import Request
from bot.model_definitions import Mode, MoodCategory, AffectionCategory
from bot.pattern_recognizer import analyze_input
from bot.logger import logger
# factor 0.2 ensures steady adjustment of bots mood and affection
IMPACT_FACTOR = 0.2
def... |
# -*- coding: utf-8 -*-
"""
Numba function wrapper.
"""
from __future__ import print_function, division, absolute_import
import types
import ctypes
from functools import partial
from itertools import starmap
from numba2.rules import typeof
from numba2.compiler.overloading import (lookup_previous, overload, Dispatche... |
def times_table(num):
n=1
while n<=12:
print(n,"X", num,"=", n*num)
n=n+1
times_table=(9)
|
# 변수의 값을 교환하는 튜플
a,b = 10,20
print("# 교환 전 값")
print("a:", a)
print("b:", b)
print()
# 값을 교환합니다.
a,b = b,a
print("# 교환 한 값")
print("a:", a)
print("b:", b)
print() |
from api_tests.admin_backend import AdminBackendTestCase
import entities
class SimpleTariffTests(AdminBackendTestCase):
def test_tariff_list(self):
tariff_list = self.default_admin_client.tariff.list()
self.assertEqual(tariff_list['total'], len(tariff_list['items']))
def test_tariff_update_re... |
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from eagleEye import create_app
from eagleEye.exts import db
from eagleEye.models import Movie, Cinema, Hall, HallScheduling, Seat, SeatScheduling, Order
app = create_app()
migrate = Migrate(app, db)
manager = Manager(app)... |
class Db:
def __init__(self, dictionary):
self.__dict__ = dictionary
def record(name, dictionary):
globals()[name]=Db(dictionary)
|
import urllib.request
import json
import login
import whichweek
from datetime import date
rawhtml = urllib.request.urlopen("https://cfb-scoreboard-api.herokuapp.com/v1/date/" + whichweek.getweek()["last"][1])
data = json.loads(rawhtml.read().decode("utf-8"))
users = open('users.json', 'r')
userdata = json.loads(user... |
# Generated by Django 2.2.13 on 2021-03-24 18:20
import ckeditor_uploader.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependenci... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 17 15:00:01 2016
@author: Shane Yu
"""
import json
import sys
import re
import os
import operator
filename1 = sys.argv[1] #filename1 is 'question.json'
#filename2 = sys.argv[2] #result of querying KCM model
with open(filename1, 'r') as f1:
JsonStr = f1.read()
JsonOpti... |
import commands,sys
from glob import glob
from configLocal import OUTPUTDIR
from math import ceil
objName = sys.argv[1]
nInRow = 3
status, output = commands.getstatusoutput("find %s/ -name %sCHARTS -print" % (OUTPUTDIR, objName))
ntot = 0
cmd = ""
for chf in output.split('\n'):
print chf
lf = glob("%s/*fits.png" %... |
# Generated by Django 2.0.6 on 2018-06-07 11:00
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dissertation', '0002_dissertation_description'),
]
operations = [
migrations.CreateModel(
name=... |
# -*- coding: utf-8 -*-
__author__ = 'theme'
__date__ = '2017/9/24 下午12:08'
import xadmin
from xadmin import views
from xadmin.plugins.auth import UserAdmin
from .models import UserProfile
class UserProfileAdmin(UserAdmin):
pass
class BaseSetting(object):
# enable_themes = True
use_bootswatch = True
... |
#-*-coding: utf-8-*-
from config import *
import random,time
from googletrans import Translator
def translate_data(html_to_Language,data):
#如果遇到错误就最多重试8次
success_num = 0
while success_num < 8:
try:
ua = random.choice(fake_UserAgent)
translator = Translator(service_urls=[
... |
# encoding=utf-8
from urllib.request import urlopen
from urllib.parse import quote
from urllib.error import HTTPError
from bs4 import BeautifulSoup
import re
import os
import string
import time
import socket
socket.setdefaulttimeout(120)
def getTime():
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
... |
# Generated by Django 2.2 on 2020-02-19 05:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[i... |
#!/usr/bin/env python3
import sys
from pystalkd.Beanstalkd import SocketError
from archiver.connection import Connection
from archiver.backup import Backup
from archiver.job import Job, JobDecoder
from archiver.alert import Email
import settings
import json
import socket
from time import sleep
def send_alert(error):... |
from django.apps import AppConfig
class RetriesConfig(AppConfig):
name = 'retries'
def coolfunction(self, parameter, option=1000):
"""
This is a docstring.
Parameters
----------
option : int, optional, default = 10
Description of the option.
anot... |
import os
import unittest
from unittest import mock
from alligator.backends.sqlite_backend import Client as SQLiteClient
from alligator.constants import ALL
from alligator.gator import Gator, Options
from alligator.tasks import Task
def add(a, b):
return a + b
class CustomBackendTestCase(unittest.TestCase):
... |
#! /usr/bin/env python
'''
Use this script to "install" the TimeClock application.
'''
import os
import sys
import shutil
# Check OS compatibility
WINDOWS = sys.platform == 'win32'
LINUX = sys.platform == 'linux2'
if not (WINDOWS or LINUX):
print "Unknown or unsupported OS. Exiting script."
exit(1)
# Set ... |
#!/usr/bin/env python
import torch
import torch.nn as nn
import torch.utils.data as data
import torchvision
import layers
import argparse
import cnn
import logger
parser = argparse.ArgumentParser()
parser.add_argument('--lr', type=float, default=1e-3)
parser.add_argument('--gamma', type=float, default=0.2)
parser.add... |
# Set
# -------------------------------------
# - It is collection of elements
# - It is unorderer collection of elements
# - It doesn't allow duplicate elements
set = {}
print(set)
set = {1, 2, 3, 4, 5, 6}
print(set)
set = {1, 5, 6, 2, 0, 1, 5}
print(set)
set = {1, 5, "hello"}
print(set)
set.add... |
import pymysql.cursors
import get_config
cfg = get_config.cfg['mysql']
dbConfig = {
'user': cfg['user'],
'password': cfg['password'],
'host': cfg['host'],
'database': cfg['database'],
'cursorclass' : pymysql.cursors.DictCursor
}
def insertTransaction(data):
cnx = pymysql.connect(**dbConfig)
try:
... |
MANAGED_SHOPS_NAMES = ('*****', '****')
TARGET_CUSTOMERS = 1620000
REFERENCE_SHOP_ID = 7559926
MIN_MARKET_SHARE = 0.005 # минимальная доля рынка
MAX_MARKET_SHARE = 0.4 # максимальная доля рынка
MAX_MARKET_SHARE_STOCK = 0.8 # максимальный запас относительно рынка
MAX_SALES_ADJUSTMENT = 0.1 # максимальных шаг изменен... |
# coding: utf-8
def quick_sort(arr):
less = []
more = []
pivot_arr = []
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
for i in arr:
if i < pivot:
less.append(i)
elif i > pivot:
more.append(i)
else:
... |
# -*- coding: utf-8 -*-
# ////////////////////////////////////////////////////////////////失败的版本数组变长以后结果就不对
# class Solution(object):
# def __init__(self):
# pass
#
# def maxProfit(self, prices):
# p = 0
# q = len(prices) - 1
# flag = 0
# if not prices:
# retur... |
"""Tests for surface averaging etc."""
import numpy as np
import pytest
from desc.compute.utils import (
_get_grid_surface,
compress,
expand,
line_integrals,
surface_averages,
surface_integrals,
surface_integrals_transform,
surface_max,
surface_min,
surface_variance,
)
from des... |
from uwupy.generics import CustomUwU
import json
class HttpUwU(Exception):
def uwuHttpError(self, status_code):
exception = "n_" + str(status_code)
if status_code is None:
raise CustomUwU("Status_Code param", "Ooops!", "Needs a big strong error_code")
try:
... |
"""
Project Euler
Problem 39: Integer right triangles
Answer: 840
"""
import math
def integerRightTrianglesWithPerimeterLessThan(maxPerimeter):
"""
Returns a map of perimeter value to integer right triangles with that
perimeter.
"""
perimeterToRightTriangleSidesMap = {}
for a in xrange(1, maxPerimeter - 2):
b... |
import datetime
import glob
import os
import logging
from python_lib import parse
from core_jukebox import os_common, templates
from core_jukebox import jukebox
logger = logging.getLogger(__name__)
class Tape(object):
@classmethod
def from_filepath(cls, filepath):
if not os.path.exists(filepath):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
print('I','love', 'China')
print(100+200)
print('100+200=', 100+200)
print(3>2)
print(True)
print(False)
print('中文字符串')
print(ord('A'))
print(ord('a'))
print(ord('中'))
print(chr(97))
print(b'ABC'.decode('ascii'))
print(b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8'))
#print(b'... |
import sys
sys.path.append("..")
from plugins import *
def analyze_functions(path):
# initilize defination list
defination_list = list()
meta_list = list()
# read the function file
lines = open(path, "r")
# append all the defination lines
for line in lines:
if "def" in line:
... |
from flask import render_template, request, Blueprint
from flaskbook.modelss import Post
main = Blueprint('main', __name__)
@main.route("/")
@main.route("/home")
def home():
stranica = request.args.get('pageee', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=stranica, per_pag... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_not_required
@no_csrf
@login_not_required
def index():
pass |
def add_to_each_line():
newf=""
with open('esdata.json','r') as f:
for line in f:
newf+=line.strip()+",\n"
f.close()
with open('esdata.json','w') as f:
f.write(newf)
f.close() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Tony <stayblank@gmail.com>
# Time: 2019/5/30 12:31
import time
import unittest
import logging
from onion_decorator.qps import qps
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def dummy():
pass
class TestQps(unittest.TestCa... |
from django.contrib.auth.models import Group
from rest_framework import serializers
from users.models import User, Address
class AddressSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Address
fields = ('country', 'city', 'address1', 'address2', 'address3')
class UserSeria... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
print("식수예측 데이콘용 함수와 변수들을 저장한 파일 _ 210717 수정본")
# 밥류 필터용
# a1: 쌀밥류, b1:덮밥국밥류, c1:비빔밥볶음밥류 ,d1: 김초밥류, e1: 국수류
a1 = ["(쌀밥류)", "영양밥", "흑미밥", "오곡밥", "수수밥", "귀리밥", "팥밥", "콩밥", "기장밥", "치자밥", "찹쌀밥"]
b1 = ["(덮밥국밥류)", "카레라이스", "짜장밥", "오므라이스", "잡채밥", "시금치무쌉", "카레소스", "수제비", "커리",... |
"""Permission test views."""
# Pyramid
from pyramid.response import Response
# Websauna
from websauna.system.core.route import simple_route
@simple_route("test_authenticated", permission="authenticated")
def test_authenticated(request):
return Response("<span id='ok'></span>", content_type="text/html")
|
# -*- encoding:UTF-8 -*-
import os
import sys
suite_list = ['pay_test']
reqid = 0
work_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
server_IP = '10.101.70.236'
server_port = 81
smartGW_IP = '10.101.70.247'
smartGW_port = 20001
server_IP2 = '10.101.70.236'
server_port2 = 9046
cloud_serv... |
# import bisect
# t = [2, 4, 6, 8]
# print(t)
# print(bisect.bisect_left(t, 7))
# print(t)
# print(bisect.bisect_left(t, 4))
# print(t)
import mmap
mmap_file = None
## 从内存中读取信息,
def read_mmap_info():
global mmap_file
mmap_file.seek(0)
## 把二进制转换为字符串
info_str=mmap_file.read().translate(None, b'\x00'... |
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
import random
from bindsnet.encoding import BernoulliEncoder
from bindsnet.network import Network
from bindsnet.network.monitors import Monitor
from bindsnet.network.monitors import NetworkMonitor
from bindsnet.analysis.plotting import plot_spi... |
# -- coding:utf-8 --
# filter是筛选器,参数有两个,第一个是函数,第二个是列表,作用是将列表中每个元素执行函数,根据返回值时True or False决定是否保留,删除返回true的值
# 本程序实现删除1-100中的素数
def is_su(m):
fin = False
if(m==1):
fin = True
else:
for i in range(2,m):
if(m%i==0):
fin = True
return fin
l = range(1,101)
print l
print filter(is_su, l)
|
from odoo import api, fields, models, tools, _
from odoo.exceptions import ValidationError
class fedia_pfe_activite(models.Model):
_name = 'fedia_pfe.activite'
_description = "Adhérents Activité"
_parent_name = "parent_id"
_parent_store = True
_rec_name = 'complete_name'
_order = 'complete_name... |
# Generated by Django 2.2.13 on 2020-10-27 00:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mentors', '0002_auto_20201027_0655'),
]
operations = [
migrations.AlterField(
model_name='mentor',
name='cover_phot... |
import os, re
import subprocess
ROOT_PATH = "e:/download/maxcso_v1.12.0_windows/work"
print( ">> Convert CHD to CSO")
def findFile( root, ext ):
return [ f for f in os.listdir(root) if re.match(f'.*\\.{ext}$',f) ]
def toIso( root, path ):
# extractcd -i "#{filepath}" -o "#{dir}\#{name}.cue" -ob "#{dir}\#{name}.bi... |
# SMTP/Text configuration, see https://docs.python.org/3/library/logging.handlers.html
# Example is given for using send grid
mailhost=('smtp.sendgrid.net', 587)
fromaddr='glass@rollingblueglass.com'
toaddrs=['where@domain.com']
credentials=('apikey','GET THIS FROM THEM')
secure=() #This means use TLS
|
from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
'''最长公共前缀
@Note:
纵向比较
'''
if len(strs)==0:
return ''
for j in range(len(strs[0])):
for i in range(1,len(strs)):
if len(... |
from __future__ import with_statement
import os
import pickle
try:
from redis import Redis
except ImportError:
Redis = None
class Cache(object):
def __init__(self):
self._cache = {}
def get(self, k):
return self._cache.get(k)
def set(self, k, v):
self._cache[k] = v
clas... |
from elftools.elf.elffile import ELFFile
from collections import defaultdict
from argparse import ArgumentParser
from util import u16, u32, c_str, hexdump
from indent import indent, iprint
from elf import ElfParser
from core import CoreParser
str_stop_reason = defaultdict(str, {
0: "No reason",
0x30002: "Und... |
from mercury.logic.auth import check_token
from typing import Optional
from fastapi.params import Cookie
from mercury.types.survey import Survey
from mercury.logic.surveys import create_survey, delete_survey, get_all_surveys, get_one_survey
from fastapi.responses import JSONResponse
from fastapi import APIRouter
rou... |
from testing import *
from testing.tests import *
from testing.assertions import *
with cumulative(skip_after_fail=True):
with all_or_nothing(), tested_function_name('compress'):
compress = reftest()
compress('')
compress('a')
compress('aa')
compress('aaa')
... |
from django.apps import AppConfig
class RedactedArchiverConfig(AppConfig):
name = 'plugins.redacted_archiver'
|
import FWCore.ParameterSet.Config as cms
#-------------------------------------------------
#AlCaReco filtering for HCAL HBHEMuon:
#-------------------------------------------------
import HLTrigger.HLTfilters.hltHighLevel_cfi
ALCARECOHcalCalHBHEMuonFilterHLT = HLTrigger.HLTfilters.hltHighLevel_cfi.hltHighLevel.clone(... |
from flask import Flask, render_template
app = Flask(__name__)
# Import CRUD operations and database classes
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Restaurant, Base, MenuItem
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = e... |
class Solution:
def titleToNumber(self, s: str) -> int:
num = 0
for i in range(len(s)-1, -1, -1):
num += (ord(s[i]) - 64) * pow(26, len(s)-1-i)
return num
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="index"),
path('hapus/<str:kode>', views.hapus, name="hapus" ),
path('edit/<str:kode>', views.edit, name="edit" ),
]
|
###### Writer : "Atia"
####Importing Libraries
from urllib.request import Request, urlopen
import pandas as pd
import requests
from bs4 import BeautifulSoup
import os
from PIL import Image
import shutil
os.chdir("/Users/macbook/Documents/pyhton/portfolio/Collecting_Image")
city= "sacramento"
url = "https://www.vis... |
"""
This type stub file was generated by pyright.
"""
import vtkmodules.vtkCommonExecutionModel as __vtkmodules_vtkCommonExecutionModel
class vtkHierarchicalBinningFilter(__vtkmodules_vtkCommonExecutionModel.vtkPolyDataAlgorithm):
"""
vtkHierarchicalBinningFilter - uniform binning of points into a
hierarc... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
... |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from System.Collections.Generic import *
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
def TempIsolateElements(view, items):
... |
import datetime
import csv
import os
import logging
import pathlib
from sql_crawler import cloud_integration
class CrawlerLog(object):
""" Logs the status of the SQL crawler, including websites and queries.
The CrawlerLog keeps track of which websites were explored, how many
queries were f... |
#%%
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision as tv
import matplotlib.pyplot as plt
import os
get_ipython().run_line_magic('matplotlib', 'inline')
#%% [markdown]
# 参考:https://pytorch.org/tutorials/intermediate/spatial_transform... |
f1 = open("leet_message.txt", "r")
msg = f1.read()
f2 = open("translation.txt", "w")
leetMap = {
"4": "A",
"8": "B",
"C": "C",
"D": "D",
"3": "3",
"F": "F",
"G": "G",
"H": "H",
"I": "I",
"J": "J",
"K": "K",
"1": "L",
"M": "M",
"N": "N",
"0": "O",
"P": "P",
"Q": "Q",
"R": "R",
"5": "S",
"7": "T",
"U... |
import os, logging, time
import argparse
from fingerprint import FingerprintDB, AudioFingerprint
logging.basicConfig(level=logging.WARNING)
# paths
# database_path = "../fp_data_dummy/db/"
# query_path = "../fp_data_dummy/query/"
# fingerprint_path = "./fingerprints_dummy/"
# output_file = "./output/output_dummy.txt"
... |
from distutils.core import setup
setup(
name = 'mr-streams',
packages = ['mr_streams'],
version = '0.03',
description= "A wrapper that makes chaining list-comprehensions simpler",
author = "u/caffeine_potent",
author_email= "caffeine-potent@protonmail.com",
url = 'https://github.com/caffein... |
import Nio
import numpy as np
#CONSTANTS
g = 9.81 #m/s**2
EARTH_RADIUS = 6371.0 #km
DEGREES_TO_RADIANS = np.pi/180.0
RADIANS_TO_DEGREES = 180.0/np.pi
#WRF time index
time = 0
#NOTE: in the WRF Users Guide pages 212 and 213 should have all
# WRF perturbation correction equations. (section 5 page 112/113)
def openWR... |
file = open('input.txt')
fileInput = file.readline()
file.close()
namesList = fileInput.replace('\"', '').split(',')
def getScore(name, pos):
score = 0
for letter in name:
score += ord(letter) - 64
return score * (pos + 1)
namesList.sort()
totalScore = 0
for pos, name in enumerate(namesList):
totalScore += get... |
import argparse
import fire
import logging
import sys
from datetime import datetime
from neural_nlp import score as score_function
_logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser()
parser.add_argument('--log_level', type=str, default='INFO')
FLAGS, FIRE_FLAGS = parser.parse_known_args()
loggin... |
import cv2
import numpy as np
def AddText(img, text, x, y):
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (int(x), int(y))
fontScale = 0.5
fontColor = (0,0,255)
lineType = 1
cv2.putText(img,... |
#coding: latin-1
# struct sensortype
# {
# double onYaw; // +4
# double onPitch; // +4 = 8
# double onRoll; // +4 = 12
# float T; // +4 = 16
# float P; // +4 = 20
# double light; // +4 = 24
# int yaw; // +2 = 26
# int pitch; // +2 = 28
# int roll; ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from oj_helper import *
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
if (not secret) or (len(secret) != len(guess)):
return '0A0... |
from django.db import models
from location.models import Location
# Create your models here.
class Character(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
birthplace = models.ForeignKey(Location, related_name='birthplace')
description = model... |
from sys import exit
from pygame import quit
from pygame.event import get, post, Event
from pygame.locals import *
from keyboard import Keyboard
from mouse import Mouse
class EventHandler:
@staticmethod
def pollEvents ():
for e in get():
if e.type == QUIT:
print ("q... |
# 141, Суптеля Владислав
# 【Дата】:「19.03.20」
# 2. Даний рядок, що містить повне ім'я файлу (наприклад, 'C:\WebServers\home\testsite\www\myfile.txt').
# Виділіть з цього рядка ім'я файлу без розширення.
import os
str = "C:\WebServers\home\\testsite\www\myfile.txt"
print("Метод 1 [OS]: \n", os.path.splitext(os.path.bas... |
def user_select():
"""Allow user to select their name."""
users = Employee.select().order_by(Employee.name.desc())
def determine_user():
"""Determine whether active user is existing or new."""
c_s()
print(
"""Welcome, wage slave! Keep reaching for that rainbow!\n
This work log has be... |
import os
import falcon
from falcr.config import getLogger, ROOT
log = getLogger(__name__)
class StaticResource(object):
def __init__(self, filename, content_type):
self.filename = os.path.join(ROOT, filename)
self.content_type = content_type
def on_get(self, req, resp):
... |
# Generated by Django 3.1.4 on 2020-12-23 09:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users_endpoint', '0004_auto_20201223_1205'),
]
operations = [
migrations.AddField(
model_name='user',
... |
import numpy as np
import torch
def PSNR(im,gt,shave_border=0):
"""
im: image with noise,value in [0,255]
gt: GroundTurth image,value in [0,255]
shave_border: the border width need to shave
"""
im_shape = im.shape
gt_shape = gt.shape
if gt_shape != im_shape:
return -1
im... |
import tkinter
from .ctk_canvas import CTkCanvas
from ..theme_manager import ThemeManager
from ..draw_engine import DrawEngine
from .widget_base_class import CTkBaseClass
class CTkEntry(CTkBaseClass):
def __init__(self, *args,
bg_color=None,
fg_color="default_theme",
... |
import os
datas = []
if len(os.popen("tmutil listlocalsnapshotdates").read().split("\n")) == 2:
print("Your system is clean!")
else:
data = os.popen("tmutil listlocalsnapshotdates").read().split("\n")
for d in data:
datas.append(d)
del datas[0]
del datas[-1]
for n in range(len(dat... |
from flask import Flask
from marshmallow import Schema, fields, pre_load, validate
from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy, BaseQuery
ma = Marshmallow()
db = SQLAlchemy()
#PROFILE
class Profile(db.Model):
__tablename__ = 'profiles'
id = db.Column(db.Integer, primary_k... |
# Generated by Django 3.2.2 on 2021-05-31 07:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user_sys', '0003_alter_queryform_des'),
]
operations = [
migrations.CreateModel(
name='LaboratoryBooking',
fields=[
... |
"""WWWairlines URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.