text stringlengths 38 1.54M |
|---|
from troposphere import Output, Export, GetAtt
from stacks.main.resources import lambda_security_group
STACK_NAME = "Main"
lambda_security_group_id_output_name = "LambdaSecurityGroupId"
lambda_security_group_id_export_name = "{}-{}".format(
STACK_NAME, lambda_security_group_id_output_name
)
lambda_secu... |
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from base.models import CachingModel
from base.operation import Operation,ModelOperation
from django.utils.translation import ugettext_lazy as _
from mysite.personnel.models.model_emp import Employee, EmpForeignKey
from mysite.person... |
"""
Root To Node Path In Binary Tree
"""
class BinaryTreeNode:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def inputBST(arr):
if len(arr)==0:
return
midIndex=(len(arr)-1)//2
root=BinaryTreeNode(arr[midIndex])
root.left=inputBST(arr[0:midInd... |
import os
from json import JSONDecodeError
from typing import Text
import requests
from rasa_sdk import Action
from rasa_sdk.events import SlotSet, ActionExecuted, UserUttered
from requests import RequestException
class CommonActionMixin:
"""Mixin with additional action helpers needed by some project actions"""
... |
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
c = 9.716e-15 #Light speed Mpc/s
Hov = 2.26855e-18 #Hubble constant 1/s, 70km/s/Mpc
OM = 0.3
OL = 0.7
Alpha_CO = 1
Name = ['ALESS015.1','ALESS017.1','ALESS022.1','ALESS070.1','ALESS070.1',
'ALESS076... |
import sys
from sqlalchemy import Column, ForeignKey, Integer, String, Boolean
from sqlalchemy.types import PickleType
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class User(Base):
__tablename__ ... |
# -*- coding:utf-8 -*-
'''
Required
- requests
- bs4
Info
- author : "huangfs"
- email : "huangfs@bupt.edu.cn"
- date : "2016.4.13"
'''
import requests
from bs4 import BeautifulSoup
import time
try:
input = raw_input
except:
pass
class JDlogin(object):
def __init__(self,un,pw):
self.headers = {'Us... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2019-01-12 12:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0002_auto_20190112_1106'),
]
operations = [
migrations.AlterField... |
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render, HttpResponse, redirect
# the index function is called when root is visitedcopy
from django.contrib import messages
from django.urls import reverse
# views.py
from django.shortcuts import render, HttpResponse, redirec... |
'''
Created on Feb 4, 2013
@author: steger, jozsef
@organization: ELTE
@contact: steger@complex.elte.hu
'''
from Driver import Driver
from Credential.credentialtypes import UsernamePassword
from httplib2 import Http
class RESTDriver(Driver):
'''
@summary: implements REST driver to fetch using http GET
@c... |
import sys
import glob
import fnmatch
import eHive
from BamQC import BamQC
from ReseqTrackDB import *
class RunVerifyBamId(eHive.BaseRunnable):
"""run VerifyBAMID on a BAM file"""
def fetch_input(self):
hostname = self.param('hostname')
username = self.param('username')
db = self.param... |
from mcpi.minecraft import Minecraft
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier("C:\\Users\\86183\\AppData\\Roaming\\Python\\Python38\\site-packages\\cv2\\data\\haarcascade_frontalface_default.xml")
cap = cv2.VideoCapture(0)
mc = Minecraft.create()
position = mc.player.getPos()
mc.pos... |
from painter import *
import time
def DFS(Map, YStack, YStack_bound, x, y, layer):
if layer == len(x):
return True
global_check = True
for i in range(len(y)):
if YStack[i] != len(y[i]) and YStack_bound[i][YStack[i]] < layer:
global_check = False
break
if not gl... |
from OpenGL.GLUT import *
from gameobject import *
class CharacterObject(GameObject):
def __init__(self, posX, posY, posZ, scaleX=1, scaleY=1, scaleZ=1, rotY=0, r=0, g=0, b=0):
super().__init__(posX, posY, posZ, scaleX, scaleY, scaleZ, rotY)
self.Length = 0
self.width = 0
self.ar... |
from zig import Zig
# all default
'''
host: 127.0.0.1
port: 5000
asset url: /assets
asset folder: assets
template folder: templates
index file: index_flask
'''
app = Zig()
if __name__ == "__main__":
app.run()
|
# from dreal import *
import torch
import torch.nn.functional as F
import numpy as np
import time
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
import matplotlib.animation as animation
from matplotlib.tri import Triangulat... |
class process(object):
i=0
def __init__(self,time):
self.id = process.i
process.i += 1
self.__time = time
def set_clock(self,time):
self.__time = time
def get_clock(self):
return self.__time
# def event(self):
# self.time += 1
# def send(self,t... |
# Generated by Django 3.1.7 on 2021-05-24 14:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sampleapp', '0009_auto_20210519_0641'),
]
operations = [
migrations.AlterModelTable(
name='item',
table='sampleapp_item',
... |
import numpy as np
from sklearn.model_selection import cross_val_score
def IQR_y_outliers(X_data, y_data):
''' aims at removing all rows whose label (i.e. shielding) is considered as outlier.
output:
- X_filtered
- y_filtered
'''
q1, q3 = np.percentile(y_data, [25, 75])
i... |
from sys import stdin
from collections import deque
input = stdin.readline
def bfs(start):
visited = [start]
queue = deque([start])
while queue:
current = queue.popleft()
for search in range(len(adj_matrix[current])):
if adj_matrix[current][search] and search not in visited:
... |
def multiply(x):
return x * x
def add(x):
return x + x
if __name__ == "__main__":
print(multiply(4))
print(add(4))
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 19:10:40 2019
@author: James Xie
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
def circleFind():
img = cv2.imread('Test.jpg',0)
imgcopy = img
if len(img.shape) == 3:
#grayscale the image
img =... |
### Z-test of proportions for hypothesis testing when only summary statistics are provided
## DEPENDANCIES:
## import numpy as np
## import scipy.stats as ss
def Test_of_Proportion(p_hat, p_null, n, alt, alpha):
z = (p_hat - p_null)/(np.sqrt(p_null*(1-p_null)/n))
print("Z-score: %f" % z)
if alt == '=/='... |
from threading import Thread
from time import sleep
WORK = True
def handler(name, sleep_time):
while WORK:
print(f'{name} start to sleep {sleep_time} sec')
sleep(sleep_time)
if __name__ == '__main__':
thread1 = Thread(target=handler, args=('first', 2))
thread2 = Thread(target=handler, a... |
import unittest
from pyunitreport import HTMLTestRunner
from selenium import webdriver
class Home_Page_Test(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path='./chromedriver.exe')
driver = self.driver
driver.get('http://demo-store.seleniumacademy.com/')
... |
import sys, requests # pip install requests
import webbrowser
global nick # varivel nick como global
x = sys.argv # x recebe sys.argv
def ajuda():
print("""
++++++++++++++++++++++++++++++++++++++++++++++++++
+ -all => PROCURA TUDO (exceto o -tu)
+ -f => Facebook
+ -tw => Twitter
+ -i => Instagram
+ -tu =>... |
""" Histograms
- grayscale hist for thresholding
- histogram for white balancing
- histograms for object tracking in images (Camshift Algo)
- HOG and SIFT descriptors
- bag of visual words
- image search engines and machine learning
cv2.calcHist(images , channels, mask , histSize, ranges)
"""
hist = cv2.calcHist([i... |
#!/Users/mrperry/anaconda/bin/python
# This code will create an event count table for ComCat
#
import sys
import datetime as dt
import os
import numpy as np
import urllib2 as urll
import pandas as pd
#
# Define Paths
#
path_RawCounts = '/Users/mrperry/autoComCatQC/M6+_CountCheck/Output/RawCounts/'
path_RawDiff = '/User... |
from __future__ import division, print_function, absolute_import
import tflearn as tf
import speech_data
import numpy as np
from sklearn.cross_validation import train_test_split
def score_model(X, y):
y_predicted = np.array(model.predict(X))
bool_arr = np.argmax(y_predicted,axis=1) == np.argmax(np.array(y),axi... |
import re
fh = open('regex_sum_1171061.txt')
number = 0
count = 0
for line in fh:
for str in re.findall('([0-9]+)', line):
number = number + int(str)
count = count + 1
print('There are ', count, 'values with a sum=', number)
|
import sys
import os
import platform
if platform.system() == 'Windows':
separator = '\\'
else:
separator = '/'
sys.path.insert(0, '/'.join(os.path.dirname(os.path.realpath(__file__)).split(separator)[:-1]) + '/jsoneditor')
import jsoneditor
import requests
# Test dict
jsoneditor.editjson(requests.get('ht... |
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'wanderment.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', in... |
#!/usr/bin/env python
# coding=utf-8
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import zhihu_oauth
setup(
name='zhihu_oauth',
keywords=['zhihu', 'network', 'http', 'OAuth', 'JSON'],
version=zhihu_oauth.__version__,
packages=['zhihu_oauth', 'zhihu_oa... |
from pathlib import Path
import torch
from torch.utils.data import DataLoader, Dataset, Subset
from torchvision import transforms
from PIL import Image
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
import zipfile
import io
from tqdm import tqdm
np.random.seed(2021)
class I... |
from statistics import mean
import pdb
mean ([5, 5, 6, 6, 10])
pdb.set_trace()
nome = str(input("Digite um nome de aluno"))
notas = []
for x in range (0,5):
nota = float(input("digite uma nota:"))
notas.append(nota) |
# Generated by Django 2.2.3 on 2019-07-14 20:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('nps_django', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='pass',
options={'verbose_name_plural': 'p... |
import discord
from discord.utils import get
# utility functions for fig-bot
# returns a list of voice channels of GUILD
def get_voice_channels(guild):
return guild.voice_channels
# returns a list of text channels of GUILD
def get_text_channels(guild):
return guild.text_channels
|
from spylunking.log.setup_logging import test_logger
from celery_connectors.utils import get_percent_done
from tests.base_test import BaseTestCase
log = test_logger(
name='consume-many')
class TestConsumeLargeNumberOfMessages(BaseTestCase):
def test_consuming_large_number_of_messages(self):
# Test... |
# 1단계 new_id의 모든 대문자를 대응되는 소문자로 치환합니다.
# 2단계 new_id에서 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.)를 제외한 모든 문자를 제거합니다.
# 3단계 new_id에서 마침표(.)가 2번 이상 연속된 부분을 하나의 마침표(.)로 치환합니다.
# 4단계 new_id에서 마침표(.)가 처음이나 끝에 위치한다면 제거합니다.
# 5단계 new_id가 빈 문자열이라면, new_id에 "a"를 대입합니다.
# 6단계 new_id의 길이가 16자 이상이면, new_id의 첫 15개의 문자를 제외한 나머지 문자들을 모두 제거합니다.... |
#from firebase import Database
from firebase import firebase
import simulator
handler = firebase.FirebaseApplication("https://smartparking-fbb4c.firebaseio.com/")
data = {
"Request_ID" : "ASDKASJDOKASNCZXKCNOKASD",
"Allocated slot" : "4"
}
import time
allocated = [0, 0, 0, 0]
slots = ['slot1', 'slot2'... |
# Import libraries
import cv2
import numpy as np
import imutils
# import odrive.core
import math
import time
# Import supporting modules
from collections import deque
from imutils.video import FPS
from imutils.video import WebcamVideoStream
# Import other modules
# from prediction import prediction
from tracking.track_... |
# Copyright (c) 2019 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
import matplotlib
import matplotlib.pyplot as plt
import PySide2.QtGui
import freud
# Activate 'agg' backend for off-screen plotting.
matplotlib.use("Agg")
def render(
... |
# encoding:utf-8
"""
使用内部DNS服务器获取域名IP、CNAME、NS和对应的TTL时间
从根域名向下进行查询
作者:程亚楠
时间:2017.8.25
"""
import DNS
import random
import tldextract
from datetime import datetime
from db_manage import get_col
from pandas import Series
timeout = 5 # 超时时间
# server = '222.194.15.253'
target_col = 'white_dns_ttl_top'
col = get_col(t... |
'''
Manage AWS ECR Resources and Stacks
'''
import traceback
from tasks.cloudformation import load_yaml_file
import ecr_deployer as ecr
print('Loading function ....')
def main(configs):
'''
Deploy AWS ECR resources
'''
setup_data = load_yaml_file(configs)
try:
for single_setup_data in set... |
from django import template
from userpage.forms import HeadPortraitUpdateForm
register = template.Library()
@register.inclusion_tag('music/manage/album_bar.html')
def show_albums_bar(all_albums, album=None):
return {'all_albums': all_albums,
'album': album}
@register.inclusion_tag('music/manage/pla... |
import pytest
from tests.classes.mock_classes import MockedConnection
@pytest.fixture
def mock_connection_error(monkeypatch):
connections = {"default": MockedConnection()}
monkeypatch.setattr("helpers.views.connections", connections)
|
import random
import sys
import base64
class Bank:
def intro():
star = '*'*37
print(star)
print('\n')
print('\t WELCOME TO BMS')
print('\t Bank Managemetn System')
print('\n')
print(star)
print('\n')
print('Developed By Avishek Chaudhary')
... |
#!/usr/bin/python
import curses
import sys
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
from random import randint
debug = 0
# Define numbers for the directions
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
NONE = 4
MOVE = 0 # A target to move to
WALL = 1
PLAYER = 2
PRIZE = 3
ENEMY = 4
cl... |
import csv
from collections import namedtuple, defaultdict
import ipdb
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials, SpotifyOAuth
import settings
SpotifyTrack = namedtuple('Track', ['id', 'title', 'artists', 'repr'])
USER_ID = settings.USER_ID
SCOPE = settings.SCOPE
CLIENT_ID = settings.CLIENT_... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import shelve
import sttcontroller
import atexit
import os, sys
from utils import is_connected
from console.models import MessageLog
#~ Initialize Django
sys.path.append('/home/pi/Documents/typiremote')
os.environ['DJANGO_SETTINGS_MODULE'] = 'typiremote.settings'
import ... |
# Core libraries
import webapp2
import os
import jinja2
import logging
# Parsing libraries
import json
import urllib2
# Authentification and databasse libraries
from google.appengine.api import users
from google.appengine.ext import ndb
# Get jinja environment from main
from main import jinja_environment
class ShareH... |
class Solution:
def getHint(self, secret: str, guess: str) -> str:
bulls, cows = 0, 0
cache = {}
for (s, g) in zip(secret, guess):
if s == g:
bulls += 1
continue
cache[s] = cache.get(s, 0) + 1
if cache[s] <= 0:
... |
from collections import namedtuple
from pyffs.core import State
from pyffs.automaton_management import manager
class LevenshteinAutomaton:
def __init__(self, tolerance, query_word, alphabet):
self._automaton = manager.get_for_tolerance(tolerance)
self._word = query_word
self.tolerance = t... |
from graphics.prims2d.rect import Rect
from core.fileServer import fileServer
class Image(Rect):
def onAttach(self):
self.defaultVar("filename",None)
self.material = dict(texture = self.filename, color = (1,1,1))
self.log("attach",self.__dict__)
Rect.onAtt... |
#!/usr/bin/python
'''
Created on Sep 26, 2016
@author: acaproni
'''
import argparse
import cmd
import os
import sys
from IASTools.CommonDefs import CommonDefs
from subprocess import call
from IASTools.FileSupport import FileSupport
def setProps(propsDict):
"""
Define default properties to be passed to all j... |
# Generated by Django 3.1.4 on 2020-12-21 09:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0008_auto_20201221_0757'),
]
operations = [
migrations.AlterField(
model_name='student',
name='social_url',
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from PIL import Image
import os
def cut_image(image,m,n):
width, height = image.size
item_width = int(width / m)
item_height = int(height / n)
box_list = []
for i in range(0,n):
for j in range(0,m):
#print((i*item_width,j*item_width,(i+1)*item_... |
"""The base entity for the scraper component."""
import logging
from abc import abstractmethod
from typing import Any
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.update_coordinator import DataUpdat... |
from collections import deque
import graph as g
graph = g.Graph()
graph = g.populate_graph(graph, g.example_graph2)
def bf_traversal(tree):
'''Breadth-first tree traaversal with loops'''
queue = deque()
queue += [tree.root]
traversed = []
contents = []
while queue:
curre... |
from django.shortcuts import render
# Create your views here.
def index(request):
context = {
'judul':'About',
'subjudul':'everything about you',
}
return render(request,'about/index.html', context) |
import random
max_width = 16
class HashTable:
def __init__(self, size):
self.lt = [None]*size
self.size = size
def insert(self,value):
rem = value%self.size
if self.lt[rem] == None:
self.lt[rem]= list()
self.lt[rem].append(value)
id = len(self.lt[r... |
def kkk():
a=int(input())
b=input()
s=[]
for i in range(a):
s.append(input().split())
if b=="0":s.sort(key=lambda x:int(x[1]),reverse=True)
else:s.sort(key=lambda x:int(x[1]))
for i in range(len(s)):
print(" ".join(s[i]))
def kkk1():
a=list(input())
for i in range(le... |
# -*- coding: utf-8 -*-
import xlrd
class ExcelCtl(object):
def __init__(self, filename):
self.excel_obj = xlrd.open_workbook(filename)
def get_table_by_index(self, sheet_index):
return self.excel_obj.sheet_by_index(sheet_index)
def get_table_by_name(self, sheet_name):
return sel... |
from rest_framework import generics, permissions, renderers, serializers, viewsets
from rest_framework.request import Request
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.permissions import IsOwnerOrReadOnly
class SnippetSerializer(serializers.HyperlinkedModelSeriali... |
import unittest
from unittest import TestCase
from unittest.mock import patch
import json
import os
import re
from usecases.welcome import Welcome
class TestWelcome(TestCase):
def __init__(self, methodName):
super().__init__(methodName)
self.preferences = {'name': 'Jürgen', 'location': 'Stuttga... |
"""JSON Sanitization"""
# clean takes in some string and eleminates escape characters
def clean(someString):
# check if the string is alphanumeric
if str(someString).isalpha():
return True
# check if the string are numbers
|
# Copyright (c) ACSONE SA/NV 2021
# Distributed under the MIT License (http://opensource.org/licenses/MIT).
import tempfile
from pathlib import Path
import pytest
from oca_github_bot.pypi import TwineDistPublisher, exists_on_index
@pytest.mark.parametrize(
"filename, expected",
[
("pip-21.0.1-py3-no... |
"""
Run this script in the Competition Output Root Directory (same directory as logs folder)
Domain:
0 = (New_sporthal)
1 = (Politics)
2 = (WindFarm)
Uncertainty:
0 = Low (1-2)
1 = Medium (3-4)
2 = High (5-6)
"""
from __future__ import print_function
import csv
import os
import xml.etree.ElementTree as ET
""... |
"""
Написать функцию-генератор cycle которая бы возвращала циклический итератор.
"""
def cycle(new_list):
"""функция генератор"""
i = 0
while True:
if i >= len(new_list):
i = 0
yield new_list[i]
i += 1
LIST_1 = [1, 2, 3]
RESULT = cycle(LIST_1)
print(next(RESULT))
prin... |
from __future__ import division
from pylab import *
# define the positions of z, r is variable
def phase(r):
x=[1]
y=[0]
z=[0]
dxdt=[0]
dydt=[0]
dzdt=[0]
t=[0]
dt=0.0001
sigma=10
b=8/3
for i in range(499999):
dxdt.append(sigma*(y[-1]-x[-1]))
... |
'''
实现提示语
'''
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton,QToolTip
from PyQt5.QtGui import QFont
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 设置提示信息的字体
QToolTip.setFont(QFont('微软雅黑',10))
#... |
# %%
import hashlib
import json
import re
from pathlib import Path
import geopandas
import pandas as pd
from IPython.display import display # noqa E401
from constants import CaseTypes, Columns, Locations, Paths
GEO_DATA_DIR = Paths.DATA / "Geo"
CODE = "code"
DATA_DIR: Path = Paths.DOCS / "data"
DATA_DIR.mkdir(exi... |
import numpy as np
from mnist_data_provider import MNIST
from Modules import Fully, Softmax, Cross_entropy, Relu
mnist = MNIST()
# パラメータ
shape = {2, 28, 28, 1}
n_output = 10
s_batch = 10
epsilon = 0.01
lam = 0.0001
gamma = 0.9
f1 = Fully(28*28, 100)
f2 = Fully(100, 10)
rl = Relu()
sm = Softmax()
ce = Cross_entropy(... |
# 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 maxPathSum(self, root):
def _max_dist(root):
global res
if not root:
return 0
... |
# ---
# jupyter:
# jupytext:
# notebook_metadata_filter: all
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.5
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# metadata:... |
import win32con
import win32gui
import datetime
from tkinter import*
from tkinter.font import Font
from typing import Sized, TextIO
import pyttsx3
import os
from tkinter import Label
from tkinter import filedialog, messagebox
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('... |
import discord
from datetime import datetime
from discord import Intents, colour
from discord.ext.commands import Bot as BotBase
from discord import Embed, File
from discord.ext.commands import CommandNotFound
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigg... |
from __future__ import absolute_import
from builtins import object
from zope.interface import implementer
from .interfaces import IFormData
from .data.field import Field
from collections import OrderedDict
import logging
logger = logging.getLogger(__name__)
@implementer(IFormData)
class FormData(object):
def __... |
'''Requests and formates data from the Google Maps API'''
import requests
class Maps:
'''Two methods, one for requesting data and another to find the good data.'''
def __init__(self):
self.lat = 0
self.lng = 0
self.street = ''
self.town = ''
self.adress = ''
se... |
#!/usr/bin/python3
def uppercase(str):
for letter in str:
if ord(letter) >= 97 and ord(letter) <= 122:
letter = chr(ord(letter) - 32)
print("{}".format(letter), end="")
print()
|
"""Routes for files."""
import base64
import json
import logging
import os
from io import StringIO
from typing import List
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status
from fastapi.responses import FileResponse, StreamingResponse
from src.api.routers.dependencies import get_api_key
... |
# Get number of test cases
T = int(raw_input())
# Each test case
for t in range(T):
N = long(raw_input())
current_num = N
checks = [0,1,2,3,4,5,6,7,8,9]
result = 0
counter = 0 #hack
while checks != []:
number_string = str(current_num)
for char in number_string:
if int(char) in checks:
checks.remove(in... |
# encoding=utf-8-sig
import tensorflow as tf
import numpy as np
import datetime
sequence_length = 500
element_size = 300
batch_size = 100
parallel_iterations = 100
time_major = True
cell = tf.nn.rnn_cell.LSTMCell(128)
inputs = tf.placeholder(tf.float32, [sequence_length, batch_size, element_size])
outputs, state = tf.... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 26 21:53:42 2020
@author: JZ2018
"""
import pandas as pd
import numpy as np
df_raw = pd.read_csv('D:/JZR/nba/nba_all.csv')
with pd.option_context('display.max_columns', 40):
print(df_raw.describe(include='all'))
print(df_raw.head())
df_raw.info(verbose=True)
k... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 累计统计分析函数
import pandas as pd
import numpy as np
b = pd.DataFrame(np.arange(20).reshape(4,5), index=['c', 'a', 'b', 'd'])
print('b:\n{0}'.format(b))
print('b.cumsum():\n{0}'.format(b.cumsum()))
print('b.cumprod():\n{0}'.format(b.cumprod()))
print('b.cummin():\n{0}'.forma... |
#
#
# blitem.py
#
#
import json
import re
from unicodedata import normalize
from datetime import datetime
from API.utils import get_config_value
from pymongo import Connection
from bson.objectid import ObjectId
from bson import json_util
class BaseObject(object):
@property
def id(self):
return se... |
""" 2. Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
Sample data : 3, 5, 7, 23
Output :
List : ['3', ' 5', ' 7', ' 23']
Tuple : ('3', ' 5', ' 7', ' 23')
"""
# list and tuple from user
values = input("\nEnter Number for list: ")
... |
import platform
import os
import subprocess
import time
import torch
from pathlib import Path
import pickle
from torchvision import transforms
# Taken from: https://github.com/yunjey/pytorch-tutorial/blob/0500d3df5a2a8080ccfccbc00aca0eacc21818db/tutorials/03-advanced/image_captioning/data_loader.py#L56
def collate_f... |
"""
@author: Wang Yizhang <1739601638@qq.com>
"""
import os
import argparse
from model.trainr import CycleGANTrainr
def get_args():
parser = argparse.ArgumentParser(
"""Train CycleGAN using source dataset and target dataset"""
)
parser.add_argument(
"--logf0s_normalization",
type=... |
'''
Created on Apr 16, 2016
@author: hduser
'''
def solve(s):
winner = s[0]
for i in xrange(1, len(s)):
z = s[i]
if winner + z > z + winner:
winner += z
else:
winner = z + winner
return winner
t = int(raw_input())
for i in xrange(1, t + 1):
s = raw_in... |
import os
import settings
from pdf2image import convert_from_path
DPI = 300
PPM_OUTPUT_PATH = settings.DIR_KHALIL_PPM
JPG_OUTPUT_PATH = settings.DIR_KHALIL_JPG
FILE_PATH = settings.FILE_DATA_RAW_KHALIL
pages = convert_from_path(FILE_PATH, DPI,PPM_OUTPUT_PATH)
for i, p in enumerate(pages):
p.save(os.path.join(JPG... |
from main import *
class Helper(object):
"""docstring parent,*args,*kwargs Helper"""
def __init__(self, parent,*args,*kwargs):
self.dataX = main.dataX
self.sfm = main.sfm
print(self.dataX) |
from rest_framework import serializers
from API.models import WorkoutType
class WorkoutTypeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = WorkoutType
fields = '__all__' |
a_list = [1, 2, 3]
print(sum(a_list))
import random
point1 = random.randrange(1, 7)
point2 = random.randrange(1, 7)
point3 = random.randrange(1, 7)
print(point1, point2, point3)
|
# import os
# import yaml
# class GameControl(object):
# def __init__(self):
# pass
# def save_game(self):
# if not os.path.exists('./save_games'):
# os.makedirs('./save_games')
# save_state = [player, "another item, room, health, etc."]
# filepath = "./save_games/{}.yml".format(player)
# ... |
import os
from subprocess import Popen, call
from typing import Dict
print(os.getcwd())
import xml.etree.ElementTree as ET
def substituteSVG(values):
tree = ET.parse('../resourcen/template.svg')
root = tree.getroot()
namespaces = {'svg': 'http://www.w3.org/2000/svg',
'xlink': "http://... |
# O(2ⁿ⁺ᵐ)
# n = len(string) | m = len(pattern)
class Solution:
def isMatch(self, string: str, pattern: str) -> bool:
cleanPattern = []
for i in range(len(pattern)):
if i == 0 or pattern[i] != "*" or pattern[i - 1] != "*":
cleanPattern.append(pattern[i])
return s... |
from . import IntegrationTestBase
class TestUser(IntegrationTestBase):
def test_password_hashing(self):
"""Passwords are not stored; only their hashes are stored."""
user1 = self.create_users(count=1)
self.sas.flush()
assert user1.password != 'password'
assert user1.salt ... |
from pwn import process
import time
from itertools import product
sleeptime = 0.001
for comb in product(['1', '2', '3', '4'] , repeat = 7):
p = process("./gym")
text = p.recv()
p.sendline(bytes(comb[0], "ascii"))
time.sleep(sleeptime)
text = p.recv()
p.sendline(bytes(comb[1], "ascii"))
time.sleep(sleeptime)
... |
import pygame
import random
from algorithms import Algorithms
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
BAR_HEIGHT_RANGE = (10, 40)
BAR_COLOR_RANGE = (0, 255)
BAR_AMOUNT = 60
pygame.init()
display_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Sorting Algorithm Visualizer")... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.