text stringlengths 38 1.54M |
|---|
from setuptools import setup
setup(
name = 'TracFeedRabbitMQ',
version = '0.0',
author = 'Nick Piper',
author_email = 'nick.piper@cgi.com',
license = 'Modified BSD License',
packages = ['tracfeedrabbitmq'],
package_data={
'tracfeedrabbitmq': [
'templates/*.html',
... |
import cv2
import glob
import numpy as np
import random
from matplotlib import pyplot as plt
def image_cropping(image):
b = image[:, :, 0]
b1 = b.copy()
hist0, bins = np.histogram(b, 256, [0, 256])
g = image[:, :, 1]
g1 = g.copy()
hist1, bins = np.histogram(g, 256, [0, 256])
r = image[:, :... |
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
categories = (
('residenziale','Residenziale'),
('hotel','Hotel'),
('interni','Interni'),
('ristrutturazione','Ristrutturazione'),
('villa','Villa'),
('commerciale','Commerciale'),
)
cla... |
import sys
import os
import time
import socket
import random
from datetime import datetime
now = datetime.now()
hour = now.hour
minute = now.minute
day = now.day
month = now.month
year = now.year
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
bytes = random._urandom(1490)
os.system("pkg install toilet -y")
os.... |
# encoding=utf8
import sys ,os
sys.path.append(os.getcwd())
from plugins.todoist_cron import add_monthly
from plugins.slack_driver import SlackDriver
add_monthly()
# 初期化
sk = SlackDriver()
# 一応スラックに通知
sk.slack_call( '今月のタスクを追加しました.' )
|
# -*- coding: utf-8 -*-
import scrapy
class LaVanguardiaSpiderSpider(scrapy.Spider):
name = 'la_vanguardia_spider'
allowed_domains = ['https://www.lavanguardia.com/']
start_urls = ['http://https://www.lavanguardia.com//']
def parse(self, response):
pass
|
weekStr = "星期一星期二星期三星期四星期五星期六星期七"
weekId = eval(input("请输入星期数字(1-7):"));
pos = (weekId - 1)*3
print(weekStr[pos: pos + 3]) |
class Movie:
def __init__(self, movie_id, movie_name, year):
self.movie_id = movie_id
self.movie_name = movie_name
self.year = year
self.ratings = []
def __repr__(self):
return {"movie_id": self.movie_id}
def __str__(self):
return F"Movie id: {self.movie_id}... |
import random
import math
import time
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten
from tensorflow.keras.optimizers import Adam
import huskarl as hk
import matplotlib.pyplot as plt
from warehouse_env.warehouse import WarehouseEnv
class ... |
from django.test import TestCase
from django.contrib.auth.models import User
from onreview_app.models import *
class PostsAndCommentsTestCase(TestCase):
user = None
def setUp(self):
self.user = User.objects.create_user(username='tester',
email='tester@tester.com',
... |
from django.shortcuts import render
from django.http import HttpResponseRedirect
import random, string, datetime
from oyo.models import Customer, Manager,Hotel, Bookings, Employee, Rooms
from django.contrib import messages
c=0
h=0
# create a function
def home(request):
return render(request, 'hoome.html')
... |
#!/usr/bin/env python
with open('show_lldp_neighbors_detail.txt') as f:
lines = f.readlines()
found_name, found_port = (False, False)
for x in lines:
if x.startswith('System Name'):
elements = x.split(':')
sys_name = elements[1].strip()
found_name = True
elif x.startswith('Port id'... |
'''Approach #1: Dynamic Programming [Accepted]
Intuition and Algorithm
At the end of the i-th day, we maintain cash, the maximum profit we could have if we did not have a share of stock, and hold, the maximum profit we could have if we owned a share of stock.
To transition from the i-th day to the i+1-th day, we eith... |
# groupby task
def groupby(func, seq):
output = {}
for i in range(0,len(seq)):
funcresult = func(i) # this is made so costly functions are calculated only once per iteration, instead of on every line of code
if funcresult not in output:
output[funcresult] = []
output[funcresult].append(i)
print (o... |
from django import forms
from transaction_period.models import TransactionPeriod
class TransactionPeriodCreateForm(forms.ModelForm):
class Meta:
model = TransactionPeriod
fields = {
'name',
'start_date',
'end_date',
}
widgets = {
'... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Sachin Mane and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import os
from uuid import uuid4
from pathlib import Path
from frappe.model.document import Document
from latte.file_storage.abc import Adap... |
from src.markovchain import Chain
if __name__ == "__main__":
states = ["a", "b" , "c"]
transitions = [[0,1/2,1/2], [1/3,1/3,1/3], [0,1,0]]
c = Chain(states, transitions)
print("Testing Initialization of Chain...")
assert(c.get_states() == ["a", "b", "c"])
assert(c.get_transitions() == {'a': [... |
import logging
import os
from os import listdir, makedirs
from os.path import isfile, isdir, join, exists
import argparse
parser = argparse.ArgumentParser(
formatter_class = argparse.RawDescriptionHelpFormatter,
description = "generate loop selection jobs",
epilog = """Example:\npython loop_selections.py"... |
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
n = len(board)
if not n:
return
m = len(board[0])
if not m:
return
... |
class Container_for_BuildtData():
HPrefix = None
Hydrogens = None
Carbons = None
Bonds = None
prelimBonds = None
correlations = None
redundantAtoms = None
def fillContainer(self,
HPrefix,
Hydrogens,
Carbons,
... |
#Program to create tree from array and traverse Tree with in-order, pre-order and post-order traversal
import sys
class Node():
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def InOrder(root):
if root:
InOrder(root.left)
print(root.value, end=" ")
InOrder(root.righ... |
with open("wp_viaf_proc.txt", "w") as out:
l = 1
with open("wp_viaf.txt") as f:
for line in f:
parts = line[1:-1].split(",")
try:
if parts[3].startswith("'http://viaf.org/viaf/search"):
pass
elif parts[3] == "'http://viaf.org/'"... |
#
# Copyright (c) 2018 Juniper Networks, Inc. All rights reserved.
#
from __future__ import absolute_import
from builtins import str
from builtins import range
import json
import sys
import uuid
sys.path.append('../common/cfgm_common/tests/mocked_libs')
from device_manager.device_manager import DeviceManager
from .test... |
from rest_framework import serializers
from .. import models
from . import file
class JobIDSerializer(serializers.ModelSerializer):
class Meta:
model = models.Job
fields = ('id',)
read_only_fields = ('id',)
class JobSerializer(serializers.ModelSerializer):
input_data = serializers.Pr... |
import json
from configparser import ConfigParser
import ssl
import urllib.request
import sys
from utils import *
from web3 import Web3, HTTPProvider
import http.client
def is_json(myjson):
with open(myjson) as f:
print ("VALIDATING JSON %s" % myjson)
try:
json_object = json.load(f)
excep... |
#from rymodtran import driver_gentape5;
#driver_gentape5();
from rymodtran import driver_readtape7;
driver_readtape7(); |
#check calibration versions
ver1="2."
ver2="3.1"
directory=Configuration.getProperty('var.hcss.workdir')
spireBands=["PSW","PMW","PLW"]
#-------------------------------------------------------------------------------
# RadialCorrBeam
beamProf1=fitsReader('%s//Phot//SCalPhotRadialCorrBeam//SCalPhotRadialCorrBeam_v%s... |
#!/usr/bin/env python3
# -----------------------------------------------------------------------------
# Distributed Systems (TDDD25)
# -----------------------------------------------------------------------------
# Author: Sergiu Rafiliu (sergiu.rafiliu@liu.se)
# Modified: 28 January 2015
#
# Copyright 2012-2015 Link... |
import copy
import random
import tensorflow as tf
import tensorflow_gnn as gnn
from tensorflow_gnn.sampler import subgraph
from tensorflow_gnn.sampler import subgraph_pb2
from google.protobuf import text_format
class TestSubgraph(tf.test.TestCase):
def setUp(self):
super().setUp()
self.subgraph = text_fo... |
import re
arquivo =[]
alfabeto = []
passos = ""
axioma = ""
angulo = ""
regras = []
with open("regras.txt","r") as rkeys:
arquivo = rkeys.readlines()
for token in arquivo:
if token[0] == 'A':
alfabeto = token[4:].split(',')
if token[0] == 'B':
passos = token[4:]
... |
# file
import os
print(os.path.join("Users", "wish-", "python"))
# open, close
st = open("st.txt", "w", encoding="utf-8") # 日本語用
st.write("Hi! from Python")
st.close() |
'''
Created on Oct 9, 2017
This is the main method for the game, to actually run
it and see what the results are
@author: jack
'''
#these have errors but they actually work as well
from chipsReferee import ChipsReferee
from jackPlayer import JackPlayer
from onesPlayer import OnesPlayer
from MaxPlayer import MaxPlaye... |
"""
10- İki dik kenarı girilen dik üçgenin hipotenüsünü hesaplayan algoritma
"""
import math
dik_kenar_1 = eval(input("1. Dik Kenarı Giriniz : "))
dik_kenar_2 = eval(input("2. Dik Kenarı Giriniz : "))
kareleri_toplami = dik_kenar_1 ** 2 + dik_kenar_2 ** 2
print("Kareleri Toplamı :", kareleri_toplami)
print("Hipotenüs... |
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from django.http import Http404
from .models import Album,Song
from django.template import loader
def index(request):
all_albums=Album.objects.all()
#template=loader.get_template('music/index.html')
context={'all_alb... |
# Console Version of the Python Youtube downloader
# App by Renzo Westerbeek - 2014
import pafy
import os
import errno
execfile("general.py") # Includes generalfunctions file
# Gets all the urls from urlfile
def get_download_list(urlfile):
urlfile = open(urlfile, "r")
downloadList = []
for url in urlfile:
downl... |
import jwt
from flask import request, jsonify
from functools import wraps
from my_settings import SECRET_KEY, ALGORITHM
def login_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
"""로그인 데코레이터
Header:
Authorization: 검증이 필요한 토큰
"""
try:
... |
import RPi.GPIO as GPIO
import time
def test():
motor_1a = 11
motor_1b = 13
motor_2a = 3
motor_2b = 5
print "Configuring..."
GPIO.setmode(GPIO.BOARD)
GPIO.setup(motor_1a, GPIO.OUT)
GPIO.setup(motor_2a, GPIO.OUT)
GPIO.setup(motor_1b, GPIO.OUT)
GPIO.setup(motor_2b, GPIO.OUT)
... |
from django.db import models
from userinfo.models import ShowInfo,UserInfo
# Create your models here.
class Classify(models.Model):
cname = models.CharField('类别',max_length=30,null=False)
def __str__(self):
return self.cname
class Meta:
db_table = 'classify'
verbose_name = '类别'
verbose_na... |
#! /usr/bin/python3
import pdb
from infra.common.logging import logger
from apollo.config.resmgr import Resmgr
import apollo.config.agent.api as api
import apollo.config.objects.base as base
import apollo.config.utils as utils
import oper_pb2 as oper_pb2
import types_pb2 as types_pb2
class EventObject(base.ConfigO... |
from libphysics import *
freq = numpify([30, 50, 80, 150, 400, 700, 1e3, 2e3, 3e3, 5e3, 8e3, 12e3, 17e3, 20e3])
Vin = numpify([1.88, 1.87, 1.87, 1.87, 1.87, 1.87, 1.86, 1.85, 1.84, 1.84, 1.83, 1.83, 1.83, 1.83])
Vout = numpify([1.84, 1.84, 1.84, 1.83, 1.78, 1.69, 1.62, 1.1, .838, .556, .374, .265,.206, .182])
fase... |
from bson.objectid import ObjectId
from flask import jsonify, request
import validate
from error import not_found
from res import field,init,mongo
def update_employee():
init()
try:
_json = request.json
field['_firstname']=_json['first_name']
field['_lastname']=_json['last_na... |
#!/usr/bin/env python3
import rospy
from std_msgs.msg import String
from robotis_controller_msgs.msg import StatusMsg
from thormang3_manipulation_module_msgs.msg import KinematicsPose, KinematicsArrayPose
class Main_Graph:
def __init__(self):
rospy.init_node('thormang3_manager', anonymous=False)
r... |
import pygame
from PointVectorSector import *
from Graphics import *
from Map import *
import pygame.gfxdraw
graphics = Graphics([1000, 1000])
ScaleFactor = 100
Offset = Point(-50, -50)
WorldSize = [10, 10]
graphics.DrawGrid(ScaleFactor, WorldSize, Offset)
VectorMap = Map(WorldSize)
IsDragging = False
while True:
... |
import numpy as np
class New_Knowledge:
def __init__(self):
self.number_of_literals = 100
self.percent_match = 100
self.well_formed_formula = None
self.keys = None
self.index_i = None
self.index_j = None
self.completed = False
class resolution_refutation:
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 7 12:25:27 2019
@author: naveenpc
"""
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
start = 0
longest = 0
ans = 0
d = dict()
#cycle through all the elements of the string
#if the character is not ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 10 19:25:15 2020
@author: fhfonsecaa
"""
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model
class Buffer:
def __init__(self):
self.acti... |
import random
import logging
import json
logging.basicConfig(filename='text.log', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
logging.info("getting text file: start")
f = open("list_of_names.txt", "r")
names = f.read()
print(names)
logging.info("getting text file: end")
logging.info("getting... |
import numpy as np
import time
import pygame,sys
from pygame.locals import *
import threading as thrd
import time
plane_data=[[0,0],[0,0],[0,0]]
back_g="bg.jpg"
plane_img=['plane1.png','plane2.png','plane3.png']
################################################################################
# Function de... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
# In[ ]:
from subprocess import check_output
print(check_output(["ls", "../input"]).decode("utf8"))
# In[ ]:
df_gender = pd.read_csv('../input/gend... |
import random
import string
import logging
from .defaults import ZiaApiBase
class VpnCredentials(ZiaApiBase):
MAX_PSK_LEN = 64
def _randomize_psk(self):
psk = ''.join(random.choices(
string.ascii_letters + string.digits, k=self.MAX_PSK_LEN))
LOGGER.debug("RANDOM PSK: {} (PSK Leng... |
import torch.nn as nn
import torch
class BasicBlock(nn.Module):
ex = 1
def __init__(self, inplanes, planes, p, stride=1, shortcut=None):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels=inplanes, out_channels=planes, kernel_size=3, stride=stride, padding=1)
... |
"""
このモジュールをimportするだけで、matplotlib系の出力に日本語フォントが使えるようになります。
使用するフォント名は、環境に合わせて変更してください。
注意1:
seaborn等、matplotlibの見た目を上書きするモジュールをimportする場合は、
その後の行でこのモジュールをimportしてください。
例)
import seaborn as sns
import japanese_font_plt # seabornの後の行でimport
注意2:
うまく表示されない場合は、フォントキャッシュの削除を試してみてください。
手順)
1... |
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from paylane.paylane_rest_client import client
from tweet_account.models import TwitterAccount
from paylane.models import Su... |
n=int(raw_input())
str=map(int,raw_input().split())
ans=1
import math
if 1<=n<=1000 and 1<=len(str)<=1000:
for i in range(len(str)):
ans=(ans*str[i])%(10**9+7)
print ans
|
def get_int():
return int(input())
def get_line():
return input().strip()
def get_ints():
return [
int(i)
for i in input().split()
]
class Heap:
def __init__(self, start, end, left=None, right=None):
self.start = start
self.end = end
self.left = left
... |
# -*- coding=utf-8 -*-
def add_express(money, average_express):
for m in money:
money[m] = money[m] + average_express
return money
def print_info(money):
for m in money.items():
print m[0] + ': ' + str(m[1])
def calculate_money(money, express, actual_cost):
"""
:param money: Dict... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import tempfile
from argparse import ArgumentParser
from contextlib import contextmanager
import semver
from assisted_test_infra.test_infra import utils
@contextmanager
def pull_secret_file():
pull_secret = os.environ.get("PULL_SECRET")
t... |
import boto3
import botocore
import os
import shutil
import pickle
import glob
import logging
from botocore.exceptions import ClientError
def download_directory_from_s3(bucketName, remoteDirectoryNames):
s3_client = boto3.resource('s3', endpoint_url="http://rook-ceph-rgw-nautiluss3.rook")
bucket = s... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 26 13:03:15 2019
@author: she
tutorial from website:
https://github.com/e2nIEE/pandapower/blob/master/tutorials/create_simple.ipynb
"""
##
import numpy as np
import time
import pandapower as pp
import pandapower.networks as pn
#create empty network
net = pp.create... |
# %load q01_read_data/build.py
import yaml
def read_data():
# import the csv file into variable
# You can use this path to access the CSV file: '../data/ipl_match.yaml'
# Write your code here
m = open('./data/ipl_match.yaml', 'r')
data = yaml.load(m)
# return data variable
return data
... |
#!/usr/bin/env python
from pymongo import MongoClient
def main():
client = MongoClient("mongodb", 27017)
db = client["Rewards"]
print("Removing and reloading rewards in mongo")
db.rewards.remove()
db.rewards.insert({"points": 100, "rewardName": "5% off purchase", "tier": "A"})
db.rewards.inse... |
from math import exp, sin
class F:
def __init__(self,a,w):
self.a, self.w= a, w
def value(self,x):
return exp(-self.a*x)*sin(self.w*x)
|
#!/usr/bin/env python
import os
import rospy
import math
import subprocess
from duckietown import DTROS
from std_msgs.msg import String, Float64MultiArray
from duckietown_msgs.msg import BoolStamped, Twist2DStamped, FSMState
from visualization_msgs.msg import Marker, MarkerArray
from simple_map import SimpleMap
from a... |
import os
path_seed = '../src/main/java/com/elmer/leetcode/'
count = 0
pkg_path = {}
for root, pkgs, files in os.walk(path_seed):
for pkg in pkgs:
if (pkg.startswith('t') or pkg == 'offer' or pkg == 'guide'):
pkg_path[os.path.join(root, pkg)] = pkg
if root in pkg_path:
print(pkg_pa... |
import tkinter as tk
from tkinter import *
from tkinter.ttk import Combobox
from data_handle import raw_data, open_instruction
from master_enum import enum_input, enum_filter, enum_output
from command_comm import cmd
from serial_comm import get_port
# https://www.daniweb.com/programming/software-development/code/48459... |
from sort_test_helper import *
def binary_search(arr, n, target):
"""
二分查找法,在有序数组arr中,查找target
如果找到target,返回相应的索引index
如果没有找到target,返回-1
"""
# arr在[left, right]区间查找target
left, right = 0, n-1
while left <= right:
# middle = (left+right) // 2 加法可能导致溢出
middle = left + (rig... |
"""
Analysis dashboards module.
"""
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
import copy
from datetime import datetime, timedelta
import json
import logging
import re
import numpy as np
import pandas as pd
from flask_login import login_required
from flask... |
"""
Suppose there is an array from 1 to N, given a subset we need to find the missing number and the repeating number
==== LOGIC ===
-> generate a dictionary with all elements of the array
-> now start traversing from range 1 till N
-> if the element is not in the dictinary, append it to the missing array
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-11 20:16
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
... |
gapfulNumbers = 0
currentNum = 100
numbers = []
while (gapfulNumbers < 20):
divisor = int(str(currentNum)[0] + str(currentNum)[-1])
if (currentNum % divisor == 0):
gapfulNumbers += 1
numbers.append(currentNum)
currentNum += 1
print(numbers) |
"""
This tool converts output.csv into a GeoJSON blob with each line being a feature
"""
from polyline import *
import json
features = []
with open('output.csv', 'r') as input_file:
for line in input_file.readlines():
row = line.split(',')
obj = { 'type' : 'Feature', 'geometry' : {'type' : 'LineString', 'coordin... |
import csv
f = open('텍스트_형용사_shuffled.csv', 'r', encoding='euc-kr')
f2 = open('텍스트_형용사_notnull.csv', 'w', encoding='euc-kr', newline='')
rdr = csv.reader(f)
wr = csv.writer(f2)
num = 0
for line in rdr:
if len(line[1].lstrip()) == 0:
print("공백 입니다")
elif line[1] == '':
print("공백 입니다")
else... |
// https://leetcode.com/problems/shortest-way-to-form-string
class Solution(object):
def shortestWay(self, source, target):
"""
:type source: str
:type target: str
:rtype: int
"""
p, cnt = -1,1
for c in target:
np = source.find(c, p+1)
... |
# Generated by Django 3.1.6 on 2021-03-26 18:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('BettingApp', '0015_mybet_towin'),
]
operations = [
migrations.AddField(
model_name='mybet',
name='placed',
... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# author: wang121ye
# datetime: 2019/6/15 23:47
# software: PyCharm
class Solution:
def permute(self, S: str) -> list:
S = S.replace('{', '.').replace('}', '.').strip('.')
backup = S.split('.')
backup = [b.split(',') if len(b.split(',')) > 1 e... |
import bisect
import os
import json
import glob
PROBLEM_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
DATA_DIR = f'{PROBLEM_DIR}/data'
RESULTS_DIR = f'{PROBLEM_DIR}/results'
def loadProblems(fn):
ret = {}
fp = open(fn, 'r')
num_isoforms, delta = [int(s) for s in fp.readline().rs... |
import numpy as np
from scipy import sparse
import matplotlib.pyplot as plt
x = np.array([[1,2,3], [4,5,6]])
print("x:\n{}".format(x))
eye = np.eye(4)
print("Numpy array:\n{}".format(eye))
sparse_matrix = sparse.csr_matrix(eye)
print("\nScipy sparse CSR matrix:\n{}".format(sparse_matrix))
data = np.ones(4)
row_ind... |
"""alter_user_table
Revision ID: ba8e21d86b95
Revises: c3a56e94bdb2
Create Date: 2017-10-15 00:39:40.069000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ba8e21d86b95'
down_revision = 'c3a56e94bdb2'
branch_labels = None
depends_on = None
def upgrade():
... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:maike
# datetime:2020/6/25 上午12:27
# Given a binary tree, find its maximum depth.
#
# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
#
# Note: A leaf is a node with no children.
#
# Example:
#
# Giv... |
from nltk.translate.bleu_score import SmoothingFunction, sentence_bleu
import torch
import random
import numpy as np
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Trainer(object):
def __init__(self, model, data_transformer, label, learning_rate, use_cuda, checkpoint_name="model.pt", ... |
import numpy as np
import gam as gg
class bt:
def __init__(self,par):
self.score=0
self.xx=0
self.yy=0
self.w1=par['w1']
self.w2=par['w2']
self.img=par['Img']
self.hmk=par['hmk']
self.pixscr=0
# player velocity, max velocity, downwa... |
def reverseInParentheses(inputString):
_opens = list()
j = 0
_len = len(inputString)
while j < len(inputString):
if inputString[j] == '(':
_opens.append(j)
elif inputString[j] == ')':
i = _opens.pop(len(_opens) - 1)
s = inputString[i + 1:j][::-1]
... |
import requests, json, os, schedule, random, time
from os.path import expanduser
api_key = "d2db1f13aac2f0e04f14847b236dfdc5"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = "Indonesia,Malang" #change with your contry and city
#use minutes
intervals_1 = 30
intervals_2 = 1
intervals_3 = 1
de... |
''' wapp for the following
class Mech with IV:- price
class Bee with IV:- amount
'''
class Mech:
def __init__(self, price):
self.price = price
def __add__(self, other):
res = self.price + other.amount
return res
def __mul__(self, other):
res = self.price * other.amount
return res
class Bee:
def __ini... |
from django.contrib.auth.forms import AuthenticationForm
from django import forms
from . models import Recipe,RecipeDetails
from django.forms import ModelForm
class RecipeForm(ModelForm):
# description = forms.CharField(widget=forms.Textarea)
class Meta:
model = Recipe
exclude = ('owner',)
cla... |
"""
(c) 2019 Network To Code
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distribu... |
from component.appflask import app
from flask import render_template,session,url_for,redirect
from component.contoller import fore
from odm import data
mer,key2,prediction_date,d,series1,color,predictiondat1,mse,instance,predict,d1,predictdat1=fore()
@app.route('/storagelist')
def storagelist():
if not session.get... |
# -*- coding: utf-8 -*-
"""
Listing 2-2. DOTART
"""
import matplotlib.pyplot as plt
import numpy as np
import random
plt.axis([-10,140,90,-10])
plt.axis('off')
plt.grid(False)
plt.arrow(0,0,20,0,head_length=4,head_width=3,color='k')
plt.arrow(0,0,0,20,head_length=4,head_width=3,color='k')
plt.text(15,-3,'x')
plt.te... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import collections
import inspect
import logging
import pathlib
import platform
import sys
import threading
import time
import weakref
from typing import List, Callable, Optional, Any, Mapping, MutableMapping, Iterator
try:
from PySide2.QtCore import ... |
import binascii
import io
import json
import math
from PIL import Image
class PixelImage:
def __init__(self, height: int, width: int, fps : int, frames: list):
self.height = height
self.width = width
self.fps = fps
self.frames = frames
def extract_rect_image(pngio: io.BytesIO, r... |
from collections import deque
# 상어의 이동방향 8방향
dx = [1,-1,0,0,1,1,-1,-1]
dy = [0,0,1,-1,-1,1,1,-1]
n , m = map(int,input().split())
graph = []
for i in range(n):
graph.append(list(map(int,input().split())))
def bfs(tmp):
queue = deque(tmp)
while queue:
x,y = queue.popleft()
#상어가 있는 위치에서 8방... |
import time
n = 20
def brute_force(row, col):
if row == 0 or col == 0:
return 1
return calc_num_paths(row-1, col) + calc_num_paths(row, col-1)
def clever_formula(size):
answer = 2
for i in range(size+1, 2*size):
answer *= i
for i in range(1, size):
answer //= i
return answer
if __name__ == "__main__":
... |
import RPi.GPIO as GPIO
import time
LedPin = 8 # pin11
def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LedPin, GPIO.OUT)
GPIO.output(LedPin, GPIO.HIGH)
def blink():
while True:
GPIO.output(LedPin, GPIO.HIGH) # led on
time.sleep(0.5)
GPIO.output(LedPin, GPIO.LOW) # led off
time.sleep(1)
def destroy():
... |
import datetime
import random
import typing
def get_dates_between_dates(start_date: datetime.date, end_date: datetime.date) -> typing.List[datetime.date]:
assert start_date < end_date
delta = end_date - start_date
return [start_date + datetime.timedelta(days=i) for i in range(delta.days + 1)]
def twr_fo... |
import random
secret_number = random.randint(1,500)
#print(secret_number)
while True:
res = int(input("Enter the secret value between 1 and 500 : "))
if res==secret_number:
print("You Won")
break
else:
print("You loose")
continue |
from flask import session
from db import db
def get_threads(topic_id):
sql = "SELECT thread_title, id, owner_id " \
"FROM thread " \
"WHERE thread.topic_id = :topic_id"
return db.session.execute(sql,
{"topic_id":topic_id}).fetchall()
def get_title(thread_id):
... |
#!/usr/bin/env python3
import numpy as np
import pytest
import skimage
from unittest import mock
from skimage.util import random_noise
from imars3d.backend.corrections.denoise import measure_noiseness
from imars3d.backend.corrections.denoise import measure_sharpness
from imars3d.backend.corrections.denoise import denoi... |
def retFlagChunks() :
x = 'ieee_nitc{Z3u5_UltG4M3r__pirate__Ph4t3_HuR4K3n_J0nQu1L_Azr13L_DR4G0n_Xxxx-----xxxX}'
x = 'Z3u5_UltG4M3r__pirate__Ph4t3_HuR4K3n_J0nQu1L_Azr13L_DR4G0n_Xxxx-----xxxX'
print(len(x))
flagChunks = []
temp = ""
for i in range(len(x)) :
temp += x[i]
if i%8 == 7 :
flagChunks.append(temp)
... |
# Generated by Django 3.1.4 on 2020-12-18 19:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('logistic', '0002_auto_20201218_1229'),
]
operations = [
migrations.AddField(
model_name='city',... |
from sqlalchemy.orm.exc import UnmappedInstanceError
from src.dao.sport_dao import SportDao
from src.models.sport import Sport
import pytest
class TestSportDao:
@pytest.fixture
def create_instance(self):
sport = Sport('Um nome', 'Uma descrição')
return sport
def test_instance(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.