text stringlengths 38 1.54M |
|---|
import csv
import json
csvfile = open('failed_inspections.csv', 'r')
all_failed = []
for row in csv.DictReader(csvfile):
all_failed.append(row)
masterviolations = []
for row in all_failed:
vx = [v.strip() for v in row['Violations'].split('|')]
for v in vx:
if v != '':
txt, comments = v.... |
# Generated by Django 2.0.7 on 2018-08-08 13:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('purelms', '0013_auto_20180808_0213'),
('dashboard', '0002_mycourses_course'),
]
operations = [
migrations.RenameModel(
... |
from django.conf.urls import url
from project.apps.core.views import (
HomeView, PostListView, OAuthPostListView, LogoutRedirectView)
urlpatterns = [
url(r'^$', HomeView.as_view(), name='home'),
url(
r'^user/(?P<user_id>[0-9]+)/posts/$',
PostListView.as_view(), name='post_list'
),
... |
import sys
sys.path.append('build')
import AvTrajectoryPlanner as av
import math
planner = av.Planner(av.AvState(0,0,0,0,0), av.AvState(5,1,0,0,0), av.AvParams(1.0,1.0,0.5,4, 3), av.Boundary([av.Point(0.5,0.5), av.Point(-0.5, 0.5), av.Point(-0.5, -0.5), av.Point(0.5, -0.5)]), av.SolverParams(6, 0.01, 0.1, 3, True, Tru... |
#!/usr/bin/python
import networkx as nx
from networkx.readwrite import json_graph
import mkit.inference.ip_to_asn as ip2asn
import mkit.inference.ixp as ixp
import mkit.ripeatlas.parse as parse
import mkit.inference.ippath_to_aspath as asp
import os
import pdb
import settings
import json
import glob
msms = []
def pars... |
import pytest
import pandas as pd
import pandas.util.testing as pdt
import os
import sys
import logging
sys.path.append(os.path.abspath('./src'))
from train_model import data_filter
logging.basicConfig(level=logging.DEBUG, filename="test_logfile", filemode="a+",
format="%(asctime)-15s %(levelname)-... |
#!/usr/bin/python
v1=45
v2=56
res=v1&v2
print "Result of & operation is ",res
res=v1|v2
print "Result of | operation is ",res
res=v1^v2
print "Result of ^ operation is ",res
res=~v1
print "Result of ~v1 operation is ",res
res=~v2
print "Result of ~v2 operation is ",res
res=v1<<1
print "Result of V1<<1 operation is ",re... |
# -*- coding: utf-8 -*-
import os
import subprocess
from datetime import datetime
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from tools.express import models as express_models
from mall import models as mal... |
# Make a Dictionary of four words and take input from the user
print("Enter The Word")
dict = {"Cat": "Pussy", "Bat": "Vampire", "Dog": "Bark", "Hat": "Cap"}
inp = input()
print(dict.get(inp))
|
class Solution(object):
def minimumDeleteSum(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: int
"""
m = len(s1) + 1
n = len(s2) + 1
result = [[0]*n for i in range(m)]
for i in range(1, m): result[i][0] += result[i-1][0] + ord(s... |
from ola.ClientWrapper import ClientWrapper
import array
"""Python 2 script to test operation of PAR lights with the DMX interface."""
def DmxHandler(status):
if status.Succeeded():
print('Success!')
else:
print('Error: ' + status.message)
if __name__ == '__main__':
#Write to the 1st 8 ch... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-09-18 18:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('djiffy', '0003_extra_data_revisions'),
('footnotes... |
import graphene
from sagas.ofbiz.schema_base import ModelBase
from sagas.ofbiz.schema_queries_g import *
from sagas.ofbiz.runtime_context import platform
class TestingTypeInput(graphene.InputObjectType):
testing_type_id = graphene.String()
description = graphene.String()
class CreateTestingType(graphene.Mutat... |
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
if not s: return False
s=s.strip()
res=signs=eE=dot=False
for c in s:
if '0'<=c<='9':
res=signs=True
elif c=='.' and not dot:
... |
##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
#https://www.tutorialspoint.com/python/python_command_line_arguments.htm
#https://www.cyberciti.biz/faq/python-command-line-arguments-argv-example/
#http://www.diveintopython.net/scripts_and_streams/command_line_arguments.html
# An example of sending command line arguments to your python program.
import sys
import subp... |
import pygame
class Board:
def __init__(self, width, height):
self.width = width
self.height = height
self.board = [[0] * width for i in range(height)]
self.left = 60
self.top = 40
self.cell_size = 30
def set_view(self, left, top, cell_size):
self.left ... |
import cv2
# video = cv2.VideoCapture(0)
faceCascade = cv2.CascadeClassifier("C:\\Python\\Python38\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_default.xml")
src_image = cv2.imread("manutd.jpg")
gray_image = cv2.cvtColor(src_image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces_rects = f... |
###
### Copyright (C) 2002-2003 Ximian, Inc.
###
### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU General Public License, version 2,
### as published by the Free Software Foundation.
###
### This program is distributed in the hope that it will be useful,
### but... |
import pytest
from time import sleep
from typing import List, Tuple, Dict
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
fro... |
empty_list = [] # Create an empty list
empty_list.append(10) #using an index won’t work until the items are added
ages = [19, 21, 20] # A named list with comma separated values
student1_details = [20, "Michael Brennan", 77.5] # Lists can hold a variety of data types
student2_details = [33, "Mairead Gallagher", 65]
cla... |
# stworz pakiet matematyka
# w nim stworz moduly: algebra i geometria
# w module algebra stworz funkcje mnozaca liczbe a przez b
# w module geometria stworz funkcje obliczajaca pole trapezu (1/2 * (a + b) * h)
#
# zaimportuj modul algebra jako algebra i geometria jako geometria (uzyj as)
# przy uzyciu funkcji z t... |
#!/usr/bin/env python
import rospy
from enum import Enum
from std_msgs.msg import Int64, Header, Byte
from std_srvs.srv import SetBool
import math
from geometry_msgs.msg import PoseStamped, TwistStamped, Vector3, Quaternion
from mavros_msgs.msg import Altitude, ExtendedState, HomePosition, State, \
... |
#!/usr/bin/env python
import sys, os
import numpy as np
from plotROCutils import addTimestamp, addDirname, addNumEvents, readDescription
#----------------------------------------------------------------------
def findHighestEpoch(outputDir, sample):
import glob, re
fnames = glob.glob(os.path.join(outputDir, ... |
# coding=utf-8
from pytest_bdd import (
scenario
)
@scenario('../features/accidental_delete_usual_case.feature',
'Execute Digito-SimulateS3ObjectsAccidentalDeleteTest_2020-04-01 to to accidentally delete files in S3 '
'bucket')
def test_accidental_delete_usual_case():
"""Create AWS resour... |
from __future__ import print_function
import socket
import datetime
import random
import threading
import unicast as u
import FIFOMulticast as f
class node():
def __init__(self, ID = -1, IP = "", PORT = 0, SOCKET = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ):
self.RECEIVED = []
self.DESTIN... |
#!/usr/bin/python3
from scapy.all import *
def spoof_reply(pkt):
if(pkt[2].type == 8):
print("Creating spoof packet...")
dst = pkt[1].dst
src = pkt[1].src
ttl = pkt[1].ttl
id_IP = pkt[1].id
seq = pkt[2].seq
id_ICMP = pkt[2].id
'''
If we wa... |
#
# functions to process file loading and data manipulation
import datetime
import os
import numpy as np
import pandas as pd
def list_files(path,ext):
# returns a list of names (with extension, without full path) of all files
# in folder path ext could be '.txt'
#
files = []
for name in os.listd... |
import json
class TargetserversSerializer:
def serialize_details(self, targetservers, format, prefix=None):
resp = targetservers
if format == "text":
return targetservers.text
targetservers = targetservers.json()
if prefix:
targetservers = [
... |
"""
ID: ten.to.1
TASK: numtri
LANG: PYTHON3
"""
class TriNode:
def __init__(self, val):
self.value = val
self.right = None
self.left = None
f_in = open("numtri.in", "r");
f_out = open("numtri.out", "w")
R = int(f_in.readline())
nodes = []
for i in range(0, R):
nodes.append(list(map(TriNode, map(int, f... |
from app.config import host,port, database, user, password
import psycopg2
connection = psycopg2.connect(user= "ylgcuwgqfktndd",
password= "5cb7fdab06b8649f26b9b46f97cae5c38d6c1c0b7c3bf466509a46914bb4a9a0",
host= "ec2-18-214-195-34.compute-1.amazonaws.co... |
from GenericElement import GenericElement
from WaveguideJunction import WaveguideJunction
from WaveguideElement import WaveguideElement
from Utils import toSI as SI
import numpy as np
from matplotlib import pyplot as plt
from scipy.constants import c as c0
a = SI("8.636mm")
l = SI("100.0mm")
dd = SI("1mm")
f_c = 0.5*c... |
"""
This enables us to call the minions and search for a specific role
Roles are set using grains (described in http://www.saltstat.es/posts/role-infrastructure.html)
and propagated using salt-mine
"""
import logging
# Import salt libs
import salt.utils
import salt.payload
log = logging.getLogger(__name__)
def get_... |
import sys
import SendData
def lireFichier (emplacement) :
fichTemp = open(emplacement)
contenu = fichTemp.read()
fichTemp.close()
return contenu
def recupTemp (contenuFich) :
secondeLigne = contenuFich.split("\n")[1]
temperatureData = secondeLigne.split(" ")[9]
temperature = float(tempera... |
import numpy as np
from gym.envs.mujoco import mujoco_env
from gym import utils
NXO_DOF = 9
def mass_center(model):
mass = model.body_mass
xpos = model.data.xipos
return (np.sum(mass * xpos, 0) / np.sum(mass))[0]
class NextageEnv(mujoco_env.MujocoEnv, utils.EzPickle):
def __init__(self):
mujo... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on Aug 15, 2010
@author: Wang Yuanyi
'''
#please change follow 2 row by your family numbers google account
Admin = '@gmail.com'
Users = ['@gmail.com','@gmail.com']
TEST = False
from wiwikai.faccbk import TransPurposeCategory, TransAccount, Payee, \
trans_typ... |
from unittest import TestCase
# https://github.com/georgezlei/algorithm-training-py
# Author: George Lei
import algorithm_prep as algo
import algorithm_prep.classic.sort as sort
class TestSort(TestCase):
def test_bubble_sort(self):
self.assertTrue(algo.test(sort.bubble_sort, sort.test_cases))
def test_insert_... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
# Put the parameters used in simulation
nb_robots_choices = range(1,21)
nb_candidates = 4
nb_classes = 80
nb_robots_further_check = 4
semantic_descriptors = []
robots_verified = []
bow_data = np.zero... |
'''
Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand.
Example 1:
Input: hour = 12, minutes = 30
Output: 165
Example 2:
Input: hour = 3, minutes = 30
Output: 75
Example 3:
Input: hour = 3, minutes = 15
Output: 7.5
Example 4:
Input: hour = 4, minut... |
import hashlib
def md5_string(string):
return hashlib.md5(string.encode('utf-8')).hexdigest()
def sha256_string(string):
return hashlib.sha256(string.encode('utf-8')).hexdigest()
hash1 = sha256_string('id0-rsa.pub')
hash2 = md5_string(hash1)
print(hash2)
|
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name = models.CharField(max_length=32,unique=True,null=False)
pwd = models.CharField(max_length=32)
email = models.EmailField(null=True)
phone = models.CharField(max_length=11,null=True)
def __str__(... |
import numpy as np
from scipy.sparse import coo_matrix
import pyspark
from pyspark.ml.recommendation import ALS as spark_ALS
from pyspark.sql.types import StructType, StructField, FloatType, IntegerType
class ALS:
def __init__(self, n_features=10, lam=0.1, n_jobs=1, max_iter=10, n_blocks=1, tol=0.1):
self.n... |
"""
docstring in functions
"""
# docstring in function without argument
def foo():
"""
the description of this function
:return:
"""
print("Yes, we entered the function of foo()")
# call a function
foo()
print("Good bye!")
# docstring in function with arguments
def add(num1, num2):
"""
t... |
from .base_cheque_class import BaseCheque
class LeumiParser(BaseCheque):
TYPE_NUMBER = 10
TYPE_NAME = 'leumi'
@classmethod
def parse(cls, gray_img):
return super()._parse(
gray_img,
match_telephones_with_persons=False
)
#
# {'first_person_id': first_per... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 17 12:00:45 2020
@class: COMP469
@author: Cristian Aguilar
@Title: Homework 1: 8-puzzle BFS
"""
import timeit
from copy import deepcopy
class Node():
def __init__(self, data):
self.data = data
self.children1 = []
self.parent = None
... |
# Import Moduls
try:
import os
except ImportError:
print ("\033[31m[-] You Don't Have os Module")
try:
import requests
except ImportError:
print ("\033[31m[-] You Don't Have requests Module")
try:
import sys
except ImportError:
print ("\033[31m[-] You Don't Have sys Module")
# Banner Function
de... |
"""
Jhonatan da Silva
Last Updated version :
Sun Feb 5 11:02:55 2017
Number of code lines:
61
"""
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import bokeh.plotting as bp
from matplotlib import style
import numpy as np
import random
#style.use('fivethirtyeight')
class gradient... |
#!/usr/bin/env python3
#
##
# @file fe.py
# @brief Determine the file format given an example .rdi file.
# @author Matthew McCormick (thewtex)
# @version
# @date 2009-05-21
# Public Domain
import sys
from optparse import OptionParser
import os
import logging
logging.basicConfig(level = logging.CRITICAL)
fe_logger = ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 18:31:02 2020
@author: keisuke
"""
if __name__ == '__main__':
try:#メッセージボックスがなければエラーが出せない
import tkinter as tk
from tkinter import messagebox as mbox
except:
raise Exception('エラー:tkinterがインポートできません。')
if __name__ == '__main__':
win... |
from meerkat_abacus.pipeline_worker.process_steps import ProcessingStep
from meerkat_abacus import model
from meerkat_abacus import util
class SendAlerts(ProcessingStep):
def __init__(self, param_config, session):
self.step_name = "send_alerts"
alerts = session.query(model.AggregationVariables).fi... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-14 19:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
import scoremanager.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.urls import reverse_lazy
from django.views.generic.edit import FormView
from django.views.generic import DetailView, TemplateView
from django.forms ... |
from django.contrib import admin
from .models import Usuario
from .forms import CreateUsuarioForm
# Register your models here.
class UsuarioAdmin(admin.ModelAdmin):
pass
admin.site.register(Usuario, UsuarioAdmin)
|
# basic08.py
import glob, csv, sys, os
dir = os.path.dirname(os.path.realpath(__file__))
input_path = dir + '/'
file_counter = 0
print(glob.glob(os.path.join(input_path, 'sales_*')))
for input_file in glob.glob(os.path.join(input_path, 'sales_*')):
total_row = 1
with open(input_file, 'r', newline='') as csv_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.utils import formats, dateparse, timezone
from .models import Period, Traineeship, Student
from django.core.exceptions import ValidationError
from datetime import datetime, d... |
import json
import logging
import requests, hashlib
from requests import RequestException
from urllib.parse import urlencode
from dquant.config import cfg
from dquant.constants import Constants
from dquant.markets.market import Market
class OkexFutureRest(Market):
def __init__(self, meta_code):
base_cur... |
#!/usr/bin/python
def get_squares_gen(n):
for x in range(n):
yield x**2
squares=get_squares_gen(4)
print(squares)
print(next(squares))
print(next(squares))
print(next(squares))
print(next(squares))
print(next(squares))
#print(list(get_squares_gen(10)))
|
"""Helper methods to talk with the notifications backend"""
import uuid
import requests
def set_path_prefix(base_path):
"""Set up the paths to use"""
if base_path is None:
raise RuntimeError("No base path passed")
global __APPLICATION_PREFIX
global __BUNDLES_PREFIX
global event_types_pre... |
from Robot import Robot
import argparse
# Create parser for putting robot in experiment mode
gs_parser = argparse.ArgumentParser(description='Specify the mode of the computer -> Experiment(1), Demo(0)')
gs_parser.add_argument('-e',
'--experiment',
action='store_true',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from layer import NeuralLayer
import theano.tensor as T
class Softmax(NeuralLayer):
def __init__(self):
super(Softmax, self).__init__("softmax")
def compute_tensor(self, x):
return T.nnet.softmax(x) |
import cv2
import numpy as np
net_torch=cv2.dnn.readNetFromTorch("./data/torch_enet_model.net")
net_tensorflow = cv2.dnn.readNetFromTensorflow("./data/tensorflow_inception_graph.pb")
|
def is_isogram(string):
result = False
string = string.replace("-", "").replace(" ", "").lower()
if len(string) == len(set(string)):
result = True
return result
|
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'TypeVideoFeatured'
db.create_table('video_typevideofeatured', (
('id', sel... |
from aiohttp.web import get, post, Response, json_response, HTTPBadRequest, HTTPForbidden
from aiohttp import FormData
from json import loads
from io import BytesIO
class NotAllowed(HTTPForbidden):
def __init__(self, ip):
super().__init__(text="Only localhost and whitelisted IP's can access the admin route... |
import unittest
class Memory:
def __init__(self, a):
self.a = list(map(int, a.split(',')))
self.last = {}
for i in range(len(self.a) - 1):
self.last[self.a[i]] = i
def iterate(self):
x = self.a[-1]
i = len(self.a) - 1
if x in self.last:
y... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 22 11:17:33 2021
@author: bb339
Raspberry pi
get api key at https://timezonedb.com/api
"""
import requests
import time
import board
import neopixel
import sys
import datetime
sys.path.append(r"/home/pi/.local/lib/python3.7/site-packages/")
import multiprocess
from mul... |
import sys
import os
import pandas as pd
import plotly.graph_objs as go
import tarfile
import pickle
import plotly as py
import shutil
from sklearn import svm
from ipywidgets import interactive
from src.models.train_model import genome_svm_selection
from IPython.display import display
from src.data.rfam_db import rfam_... |
from collections import defaultdict
import json
import gzip
import pandas as pd
import numpy as np
import itertools
from utils import *
from sklearn import preprocessing
def create_time_series_data(df):
"""
:param df: dataframe with time-series
:return: temporal sequences, target sequence
"""
df =... |
# coding:utf-8
#!/usr/bin/python
# ========================================================
# Project: project
# Creator: lilyluo
# Create time: 2020-04-25 12:42
# IDE: PyCharm
# =========================================================
# Definition for a binary tree node.
from collections import deque, defaultdict
fr... |
from django.db import models
class Airport(models.Model):
code = models.CharField(max_length=20, primary_key=True)
name = models.CharField(max_length=200)
city = models.CharField(max_length=200)
latitude = models.DecimalField(max_digits=10, decimal_places=6)
longitude = models.DecimalField(max_digi... |
import pytest
from eikon.tools import check_for_int, check_for_string, is_list_of_string, is_string_type, tz_replacer
def test_check_for_int():
check_for_int(parameter=5, name="Maffay")
with pytest.raises(ValueError):
check_for_int(parameter="Peter", name="Maffay")
def test_check_for_string():
... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm, Normalize
import sys
import time
from multiprocessing import Pool
import cProfile
import pstats
from rnns import utils, image_utils
from gmm_placing import gaussian, collect_data, heatmap, placing_utils
class GMMSequencePredict... |
import volar, pprint, ConfigParser, unittest
class TestAdvAccountInfo(unittest.TestCase):
"""
Validates the site data returned via the volar.sites() function for type and expected value.
Also tests searching, sorting, and the bounds of pages
"""
def setUp(self):
# load settings
c = ConfigParser.ConfigParser... |
import grafo_lista
import grafo_matriz
grafo_orientado = False
while True:
print('___________________________')
op = int(input('[1] Lista\n[2] Matriz\nOpção: '))
print('\n___________________________')
if op == 1:
grafo = grafo_lista.grafo_lista(6, grafo_orientado)
break
elif op == 2:
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-05-06 13:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat_room', '0001_initial'),
]
operations = [
migrations.RemoveField(
... |
def getGroup(arr):
group = dict()
for letter in zip(arr, arr[1:]):
c = ''.join(letter).upper()
if c.isalpha():
group[c] = group.get(c, 0) + 1
return group
def solution(str1, str2):
group1 = getGroup(str1)
group2 = getGroup(str2)
intersection = 0
union = 0
fo... |
import pygame
from src import Config
from src.Game import *
import menu
def main():
#Dimensiones de la pantalla
display = pygame.display.set_mode((
Config['game']['width'],
Config['game']['height']
))
#Titulo
pygame.display.set_caption(Config['game']['caption'])
menus = menu.Me... |
import speech_recognition as speech_recog
import subprocess
def startDecod():#преобразование звука в текст
subprocess.call(['ffmpeg', '-i', 'new_file.ogg', '-c:a', 'pcm_s16le', 'new_file.wav','-y'])
sample_audio = speech_recog.AudioFile('new_file.wav')
recog = speech_recog.Recognizer()
with sample_a... |
#coding: utf-8
import os
template = 'aermod.inp'
def generate_from_template(template):
pass
|
"""
-- Wrapper class for applying a selected regularizer on either
the weight matrix W or the jacobians (coming)
-- All methods expect symbolic or shared variables
"""
import theano.tensor as T
# TODO: Add Jacobian regularizers (contractive autoencoder)
class Regularizers():
def __init__(self, reg_op):
... |
# Import required modules
import numpy as np
import tensorflow as tf
import torch
import gym
import matplotlib.pyplot as plt
import argparse
import os
from gym.spaces import Discrete, Box
from tf_utils import *
from spg_tf import *
from spg_torch import *
E = '[ERROR]'
I = '[INFO]'
TF = 'tensorflow'
PT = 'pytorch'
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @param x, an integer
# @return a ListNode
def partition(self, head, x):
h1 = ListNode(-1)
h2 = ListNode(x)
... |
from abc import ABC
from datetime import datetime
from typing import Union, Tuple, Any, Iterable
class FieldException(ABC, Exception):
def __init__(self, key: str, *, error_msg: str = None):
super().__init__(f"Field (Key: {key}) - {error_msg}")
class FieldReadOnly(FieldException):
def __init__(self,... |
import numpy as np #numpy ライブラリをnpという名前で導入
import cv2 #OpenCV ライブラリを導入
img = np.zeros((500,500,3), np.uint8) #img 変数を 500*500*3 の大きさにし, 0で初期化
for y in range(50,550,100):
for x in range(50,550,100):
img = cv2.circle(img,(x,y),50,(y/2,0,255),-1)
cv2.imshow('imgame',img) #画面表示
cv2.waitKey(0) #キーボード入力を待つ
cv2.de... |
# -*- coding: utf-8 -*-
"""Exceptions for the :mod:`pybel.struct.pipeline` module."""
__all__ = [
"MissingPipelineFunctionError",
"MetaValueError",
"MissingUniverseError",
"DeprecationMappingError",
"PipelineNameError",
]
class MissingPipelineFunctionError(KeyError):
"""Raised when trying to... |
from mfcc_hdf5 import train_gen, val_gen
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.callbacks import EarlyStopping, ModelCheckpoint
import numpy as np
import pickle
import math
def main():
print('Building model...')
model = Sequential()
model.add... |
# 遞迴求最大公因數 gcd(a,b)
def gcd(a, b):
return a if b==0 else gcd(b, a%b) # 三元運算子等於 return b==0 ? a : gcd(b,a%b)
def main():
print('gcd(a,b)')
a = int(input('a = '))
b = int(input('b = '))
G = gcd(a,b)
print('result = ',G)
main() |
# импортируем библиотеку sqlalchemy и некоторые функции из нее
# импортируем пользовательский класс User
# импортируем datetime
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from users import User
from datetime import datetime
# базовый... |
#get input
t=int(raw_input())
for i in range(1,t+1):
temp=raw_input()
resstr="0000000000"
reslist=list(resstr)
done=0
for n in range(1,101):
temp2=int(temp)*n
string=str(temp2)
for l in range(0,len(string)):
pos=string[l]
reslist[int(pos)]=... |
# Generated by Django 3.0.8 on 2020-07-30 16:51
from django.db import migrations
import django_countries.fields
class Migration(migrations.Migration):
dependencies = [
('users', '0002_profile'),
]
operations = [
migrations.AddField(
model_name='profile',
name='co... |
#!/usr/bin/python3
import threading
import time
import baostock as bs
import pandas as pd
result = pd.DataFrame()
class myThread (threading.Thread):
def __init__(self, threadID, stocks, startDay, endDay, lastTradeDay):
threading.Thread.__init__(self)
self.threadID = threadID
self.stocks =... |
target = 2020
rows = []
with open('input.txt') as f:
for row in f:
rows.append(row)
valid = 0
valid2 = 0
for row in rows:
sections = row.split(' ')
lower = int(sections[0].split('-')[0])
upper = int(sections[0].split('-')[1])
letter = sections[1][0]
text = sections[2]
# p1
num ... |
from django.contrib import admin
from twits.models import Person
@admin.register(Person)
class AuthorAdmin(admin.ModelAdmin):
pass
|
#!/usr/bin/env python
# coding=utf-8
from myBiSeNet import *
import numpy as np
model = create_BiSeNet(2)
x = np.asarray([np.random.rand(321, 321, 3)])
y = np.asarray([np.ones((321, 321, 3))])
print(x.shape, y.shape)
model.fit(x, y, epochs = 40, batch_size = 1)
|
import numpy as np
import random
import math
from numpy import linalg as LA
X_Cours = np.array([[1, 2, 1], [1, 0, -1], [1, -2, -1], [1, 0, 2]])
t_Cours = np.array([1, 1, -1, -1])
X_ET = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])
t_ET = np.array([-1, -1, -1, 1])
X_XOR = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])
t_XO... |
# Generated by Django 2.1.2 on 2018-11-02 18:59
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pages', '0001_initial'),
]
operations = [
migrations.RemoveField(
... |
from msa_sdk.variables import Variables
from msa_sdk.msa_api import MSA_API
from msa_sdk.order import Order
from msa_sdk import util
dev_var = Variables()
dev_var.add('name', var_type='String')
dev_var.add('device.0.target', var_type='Device')
dev_var.add('version', var_type='String')
dev_var.add('additional_device', ... |
import smtplib
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
def mailing(bot):
sendEmail = "이메일 주소"
recvEmail = "이메일주소"
password = "비밀번호"
smtpName = "smtp.naver.com"... |
import math
import struct
import sys
class Vertex:
"""docstring for ClassName"""
x = 0
y = 0
z = 0
def Convert(self):
self.Homograph()
self.Viewport()
def Homograph(self):
self.x = (camera.z * self.x) / (camera.z - self.z)
self.y = (camera.z * self.y) / (camera.z - self.z)
def Viewport(self):
#ori... |
# -*- coding: utf-8 -*-
import os
import sys
from flask import Flask, render_template, redirect, request
from flask_session import Session
from handlers import depends as depends_handler
from handlers import blog as blog_handler
from handlers import mfdf as mfdf_handler
app = Flask(__name__, static_url_path='/static'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.