text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
'''
## Course Project
##
'''
import graph_properties as gp
from pylab import *
import networkx as nx
# --------------------------------------------
# Base code
# --------------------------------------------
def get_unique_fn(path):
import time
timestr = time.strftime("%Y%m%d_%H%M%S")... |
class Event:
def __init__(self, name, required_experience):
self.name = name
self.required_experience = required_experience
def print(self):
print(self.name + " requires " + self.required_experience);
class InterdisciplinaryEvent:
def __init__(self, base_event):
self.name ... |
from pathlib import Path
class Site:
def __init__(self,source,dest,parsers = None):
self.source = Path(source)
self.dest = Path(dest)
self.parsers = parsers or []
def create_dir(self, path):
directory = self.dest / path.relative_to(self.source)
directory.mkdir(parents ... |
class Solution(object):
def search_insert(self, nums, target):
"""
Naive solution 40 ms
:type nums: List[int]
:type target: int
:rtype: int
"""
for i, num in enumerate(nums):
if num == target:
return i
# if target not in... |
from office365.runtime.queries.delete_entity_query import DeleteEntityQuery
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
from office365.runtime.resource_path import ResourcePath
from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation
from office3... |
import imgpr as ip
image = ip.image.openImage("example.png")
x = ip.placeholder(shape=image.shape[:2])
y = ip.layers.warping(x, (400, 400), ip.warp.sphere, fix_color=(200, 200, 200))
with ip.Session() as sess:
output = sess.run(y, feed_dict={x : image})
ip.image.showImages([[image, output]])
|
from sys import argv
# read the WYSS section for hoe to run this
script, first, second, third = argv
print("the script is called:", script)
print("your first variable is:", first)
print("the second variable is:", second)
print("the third variable is:", third)
first = input("please give first variable:")
second = in... |
# 국토교통부 아파트매매 실거래 데이터 수집
# - 지역코드
# - 법정동
# - 거래일
# - 아파트명
# - 지번
# - 전용면적
# - 층
# - 건축년도
# - 거래금액
import PublicDataReader as pdr
# Open API 서비스 키 설정
serviceKey = "OPEN API SERVICE KEY HERE"
# 국토교통부 실거래가 Open API 인스턴스 생성
molit = pdr.Transaction(serviceKey)
# 지역코드 조회
bdongName = '분당구'
codeResu... |
s, c, x = 0, 1, 1
while c <= 39:
s += c/x
c += 2
x *= 2
print('{:.2f}'.format(s)) |
from django.shortcuts import render
def main(request):
return render(request,"main.html")
def analyze(request):
return render(request, "analyze.html", {"output":request.FILES})
|
"""
using MSIS Fortran executable from Python
"""
from __future__ import annotations
from pathlib import Path
import subprocess
import logging
import typing as T
import shutil
import numpy as np
import h5py
import xarray
from . import cmake
def msis_setup(p: dict[str, T.Any], xg: dict[str, T.Any]) -> xarray.Datase... |
import numpy as np
import gain
import math
import matplotlib.pyplot as plt
def UCB(T, J, nb_machines) :
s = [0] * nb_machines #nombre de fois où le bras k a été joué
regret = [0]
moy = [0] * nb_machines
B = [0] * nb_machines
a = 0 # On suppose que le gain théorique de la machine ne sera jam... |
'''
Flirt
'''
from selenium import webdriver
from time import sleep
# import xlrd
import random
import os
import time
import sys
sys.path.append("..")
# import email_imap as imap
# import json
import re
# from urllib import request, parse
from selenium.webdriver.support.ui import Select
# import base64
import Chrome_d... |
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import emart.views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Exa... |
alphabet="abcdefghijklmnopqrstuvwxyz"
def removechar(string,idx):
return string[:idx]+string[idx+1:]
def removedupli(mystring):
newstr=""
for ch in mystring:
if ch not in newstr:
newstr=newstr+ch
return newstr
def removeMatches(mystring,removestring):
newstr=""
for ch in mystring:
if ch not in removestr... |
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
Lab 5 - AR Markers
"""
########################################################################################
# Imports
########################################################################################
import sys
import cv2 as cv
import numpy... |
import boto3
import json
import cv2
# Document
documentName = "7_screen.png"
# Read document content
with open(documentName, 'rb') as document:
imageBytes = bytearray(document.read())
img = cv2.imread('messi5.jpg', |
from flask import Flask
from rest.controllers.estudante import app as estudante_controller
from rest.controllers.disciplina import app as disciplina_controller
from rest.controllers.usuario import app as usuario_controller
from rest.models.model import db
app = Flask(__name__, template_folder='templates')
#SQLite é... |
import hexchat
import pushbullet
__module_name__ = "pushbullet"
__module_version__ = "1.0"
__module_description__ = "Send messages via Pushbullet"
CONFIG_APIKEY = 'pushbullet_api_key'
def pushb(word, word_eol, userdata):
""" Hook for /pushb command in HexChat"""
api_key = hexchat.get_pluginpref(CONFIG_APIKE... |
"""
https://leetcode.com/problems/set-matrix-zeroes/
Medium
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.
You must do it in place.
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Input: matrix = [[0,1,2,0],[3,4,5,2... |
import os, shutil, re
def str2time(text):
h, m, s = text.split(':')
return int(h) * 3600 + int(m) * 60 + float(s)
def get_error_log(lines):
error_log = []
prev_end_time = 0
prev_line = ''
for idx, line in enumerate(lines):
try:
# Validate Style
if line.startswit... |
#!/usr/bin/python
from sklearn import preprocessing
from numpy import genfromtxt, savetxt
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn import preprocessing, svm
from sklearn.preprocessing import OneHotEncoder
from sklearn.externals import joblib
import random
import sys
def Ran... |
class Meta(object):
def __init__(self,name,base,subcls):
print(self,name,base,subcls)
Base=Meta('','','')
class Test(Base):
prop1='hello'
|
from paste.deploy import appconfig
from pylons import config
from gwhiz.config.environment import load_environment
conf = appconfig('config:' + '/home/kgraehl/gwhiz.com/development.ini')
load_environment(conf.global_conf, conf.local_conf)
from gwhiz.model import *
|
from collections import defaultdict
paragraph = """The rat sat in a tar pit today. I gave him a tip then. I wished on a star for no rats tonight."""
pretty_words = [single_word.lower() for single_word in set(paragraph.split())]
testdir = defaultdict(list)
word_comparison = defaultdict(list)
for word in pretty_words... |
filename = 'PA_final.txt'
filename1 = 'PA_final1.txt'
filename2 = 'PR_final1.txt'
with open(filename) as f:
data = f.read()
data = data.split('\n')
f1 = open(filename1,'w')
f2 = open(filename2,'w')
for num in range(0,len(data)):
if(num%6 < 3):
f1.write(data[num])
f1.write('\n')
else:
... |
#! /usr/bin/python
import sys
def read_list(utt2spk_file):
"""
convert utt2spk to dictionary, {utt_id:spkr_id}
"""
fin = open(utt2spk_file)
utt_dict = {}
for i in fin:
utt_id = i.strip().split(' ')[0]
spkr_id = i.strip().split(' ')[-1]
utt_dict[utt_id.strip()] = spkr_... |
import math
class Neuron():
def __init__(self):
self.x = []
self.w = []
self.sum = 0
self.y = 0
def add_weights(self, *args):
self.w.extend(args)
def add_x(self, *args):
self.x.extend(args)
def summator(self, b=0):
for i in range(len(self.x)):... |
"""Model class template
This module provides a template for users to implement custom models.
You can specify '--model template' to use this model.
The class name should be consistent with both the filename and its model option.
The filename should be <model>_dataset.py
The class name should be <Model>Dataset.py
It im... |
__author__ = 'mehdi'
import numpy as np
import csv
from Comparision import Calculations
class IO:
def __init__(self, file_address, isshareprice):
try:
self.text_data = np.loadtxt(file_address,
delimiter=',',
dty... |
import logging
import sys, os
import re
import argparse
labelSize = 20
legendSize = 20
titleSize = 36
def drawLine(xList, yList, resultFile, legends = None, xLabel = None, yLabel = None, title = None, colorList = None, opacity = 0.6, xRange = None, yRange = None, marker = "o"):
import matplotlib
#matplotlib.use('... |
# -*- coding: utf-8 -*-
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.common.action_chains import Actio... |
import os
import subprocess
from backbone.nodes import node
from backbone.logger import logger
from backbone.report import report
from backbone.format import format
os.environ["PYTHONPATH"] = os.getcwd()
import sys
import ast
def get_nodes_by_type(ty):
list = []
for element in ast.literal_eval(sys.argv[1]) :
... |
import sys
import os
f = open("C:/Users/user/Documents/python/ant_re/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
from queue import Queue
h,w = map(int,input().split())
c = [[0] * w for _ in range(h)]
sx,sy,gx,gy = 0,0,0,0
for i in range(h):
c[i] = list(input())
for j in range(w):
... |
import numpy as np
import pandas as pd
from tensorflow.keras.losses import binary_crossentropy, mse
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization, GlobalAveragePooling2D, Input, Concatenate
from tensorflow.ker... |
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLineEdit, \
QListWidget, QListWidgetItem, QAbstractItemView, QMessageBox
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtCore import Qt as qtC
from pyswip import Prolog
import spacy
import nltk
import random
import sys
import signal
signal.signal... |
from PIL import Image
img=Image.open('sal.png')
img.show() |
import shutil
import os
dirpath = os.getcwd()
files = os.listdir()
# sort all files first by extension
sort_files = sorted(files, key=lambda x: os.path.splitext(x)[1])
# only non folders
zz = []
for x in range(len(sort_files)):
if os.path.splitext(sort_files[x])[1] != '':
zz.append(sort_files[x])
n ... |
def prefill(n, v=None):
try:
return [v] * int(n)
except (TypeError, ValueError):
raise TypeError('{} is invalid'.format(n))
|
class A:
name = None
age = None
height = None
def __init__(self):
self.name = 'test'
self.age = 2
def func(self):
print(self.height)
def func_2(self):
a = 888
self.to_be_defined(a)
def to_be_defined(self, a):
pass |
def hello():
print("hello")
# Hope this works and creates a pull request |
def factorial(n):
return None if n <0 else (1 if n<2 else n * factorial(n-1))
'''
In mathematics, the factorial of integer 'n' is written as 'n!'. It is equal to
the product of n and every integer preceding it. For example: 5! = 1 x 2 x 3 x 4 x 5 = 120
Your mission is simple: write a function that takes an integ... |
# Francesca Mastrogiuseppe 2018
import numpy as np
import scipy
import matplotlib.pyplot as plt
from dsn.util.fct_integrals import *
#### #### #### #### #### #### #### #### #### #### #### #### #### #### #### #### #### #### #### ####
### Solve mean-field equations
### Non-trivial solutions, solved through iteration
... |
# Copyright 2009-2010, BlueDynamics Alliance - http://bluedynamics.com
from zope.interface import (
Interface,
Attribute,
)
class ISoupAnnotatable(Interface):
"""Marker for persisting soup data.
"""
class ISoup(Interface):
"""The Container Interface.
"""
id = Attribute(u"The id of thi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0003_remove_guest_email'),
]
operations = [
migrations.CreateModel(
nam... |
import matplotlib.pyplot as plt
speaker_results = open('F:\Projects\Active Projects\Project Intern_IITB\Vowel Evaluation (Speaker Wise Data)\\Vowel_Evaluation_V5_Speaker_Based.csv', 'r')
sr = speaker_results.read()
# print sr
list_data = sr.split('\n')
# print list_data
list_data.pop(0)
list_data.pop(-1)
list_data.pop... |
/home/joey/Documents/robots/solveRobots.py |
from collections import OrderedDict
from unittest import TestCase
from pyjsonnlp.tokenization import ConllToken, segment, surface_string, subtract_tokens
test_text = """That fall, two federal agencies jointly announced that the Russian government "didn't direct recent compromises of e-mails from US persons and instit... |
class Player:
def __init__(self,name, position):
self.name = name
self.hand = []
self.isNextPlayer = False
self.isStarter = False
self.position = position
self.hasPlacedCard = False
self.winBidding = False
self.wantBiddingMore = False
self.gai... |
import sys
import os
"""
Open a partition file, and add an A after each G[...]
to select median gamma rates instead of mean.
Then output the new partitions into another file
"""
if (len(sys.argv) != 3):
print("usage: python add_median.py input_part output_part")
sys.exit(1)
input_part = sys.argv[1]
output_part = ... |
import tensorflow as tf
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from pandas import read_csv
from sklearn.preprocessing import MinMaxScaler
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from tensorflow.contrib imp... |
"""cost functions for camera optimization
Lin Sun
May 16 2019
"""
import math
from utils import utils
from cost_functions import cost_curve
"""
cost functions can be divided into:
current quality functions (node cost)
transfer functions (edge cost)
duration function (hops cost)
"""
FRAMEX = 1024
FRAMEY = 768
FR... |
from collections import deque
from tkinter import *
def key_pressed(event):
global body
if event.keysym == 'Up':
head = [body[0][0], body[0][1] - 10, body[0][2], body[0][3] - 10]
elif event.keysym == 'Down':
head = [body[0][0], body[0][1] + 10, body[0][2], body[0][3] + 10]
elif... |
#!/usr/bin/env python
from __future__ import division
"""Tests of code for summarizing taxa in an OTU table"""
__author__ = "Rob Knight"
__copyright__ = "Copyright 2011, The QIIME Project"
#remember to add yourself if you make changes
__credits__ = ["Rob Knight", "Daniel McDonald", "Antonio Gonzalez Pena",
... |
def longestWord(words):
words.sort();
return words
words = ["rac","rs","ra","on","r","otif","o","onpdu","rsf","rs","ot","oti","racy","onpd"]
print longestWord(words)
print words |
__author__ = 'Elisabetta Ronchieri'
import unittest
from tstorm.tests.atomic import atomics
from tstorm.tests.load import loads
from tstorm.tests import utilities
def ts_storm_get_transfer_protocols(conf, ifn, dfn, bifn, uid, lfn):
s = unittest.TestSuite()
s.addTest(loads.LoadsTest('test_storm_get_transfer_pr... |
def fibonacci(n):
if n == 0 or n == 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10))
def fibonacci_v2(n):
a = 0
b = 1
if n < 0:
print("Incorrect input")
elif n == 0:
return 0
elif n == 1:
return b
else:
... |
import commands
import parameters
import subprocess
class Jarvis:
def __init__(self):
pass
def say(self, phrase):
print('"' + phrase + '"')
def listen(self):
phrase = input("> ")
return phrase
def process(self, phrase):
"""
Execute actions depending o... |
#!/usr/bin/env python3
import dadi
import matplotlib
import pylab
import numpy
from dadi import Numerics, Inference
def plot_1d_comp_multinom(model, data, fig_num=None, residual='Anscombe',
plot_masked=False):
"""
Mulitnomial comparison between 1d model and data.
model: 1-dimen... |
import math
co = float(input('Comprimento do cateto aposto: '))
ca = float(input('Comprimento do cateto adiacente: '))
hi = math.hypot(co, ca)
print(f'A hipotenusa vai midir {hi:.2f}')
|
import requests
import sys
import getopt
import re
from termcolor import colored
def banner():
print "\n***************************************"
print "* SQlinjector 1.0 *"
print "***************************************"
def usage():
print "Usage:"
print " -w: url (http:... |
#!/usr/bin/env python2.7
"""A visualisation of playback progress using a bar."""
from progress.bar import Bar
class NullBar(Bar):
"""Use an empty bar if in debug mode."""
def __init__(self):
"""Do nothing on initialisation."""
pass
def next(self, n=1):
"""Do nothing on update."... |
import asyncio
from typing import Deque
from unittest.mock import Mock
import pytest
from .context import ZergBot, Composer
@pytest.mark.asyncio
async def test_updates_multiple_bots():
one_bot = ZergBot(Deque([]))
two_bot = ZergBot(Deque([]))
bots = [one_bot, two_bot]
composer = Composer(bots)
... |
import pygame
import pytmx
from pytmx.util_pygame import load_pygame
from com.wwa.main.wwa import Wwa
MAP_MENU_BACKGROUND_TMX = "../map/menu_background.tmx"
PIC_MENU_PNG = '../pic/menu.png'
HATICON_PNG = '../pic/haticon.png'
pygame.init()
class GameMenu():
def __init__(self, screen, items, bg_color=(0, 0, 0),... |
a=int(input("請輸入一個度數:"))
if a<=120:
print("Summmer months:"+str(2.1*a))
print("Non-Summmer months:"+str(2.1*a))
elif a>=121 and a<=330:
print("Summmer months:"+str(120*2.1+(a-120)*3.02))
print("Non-Summmer months:"+str(120*2.1+(a-120)*2.68))
elif a>=331 and a<=500:
print("Summmer months:"+str(120*... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import os.path
import math
from PyQt4 import QtCore, QtGui
QtCore.Signal = QtCore.pyqtSignal
import vtk
from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
class VTKFrame(QtGui.QFrame):
def __init__(self, parent = None):
sup... |
# -*- coding: utf-8 -*-
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
"""Color tools for plotting."""
from __future__ import division
from itertools import izip, product
import operator
import numpy as np
import matplotlib as mpl
from .. import _colorspaces as cs
from .._data_obj import cellname, isfactor... |
from django.urls import path
from salvados.views import ListarSalvados, InsertarSalvado, EditarSalvado, BorrarSalvado
urlpatterns=[
path('salvados', ListarSalvados.as_view(), name='salvados_list'),
path('salvados/new', InsertarSalvado.as_view(), name='insertar_salvado'),
path('salvados/edit<int:pk>', Edita... |
import redis
if __name__ == '__main__':
client =redis.Redis(host="10.73.11.21", port=10000)
aa=client.execute_command("info")
print aa
|
from src.CNF import ClauseSet
class Decision:
def __init__(self,cs:ClauseSet):
return |
from elasticsearch import Elasticsearch
es = Elasticsearch()
host = "localhost"
port = 9200
index = "python"
type = "class1"
# get the document id separately
es.update(index=index,id="50FeTG0BsY0arHYik7Pa",body={"doc": {"mini-version": 7.2 }})
|
#!/usr/bin/python3
def area(width, height):
return width * height
def welcome(name):
print("welcome",name)
welcome("Runoob")
w, h = 4, 5
print("width =", w, "height =", h, "area =",area(w, h)) |
#!/usr/bin/env python
# coding=utf-8
"""This is the main module of the project where the algorithm is executed."""
_author__ = "L. Miguel Vargas F."
__copyright__ = "Copyright 2015, National Polytechnic School, Ecuador"
__credits__ = ["Mani Monajjemi", "Sika Abarca", "Gustavo Scaglia", "Andrés Rosales"]
__license__ =... |
annee = 1
somme = 100
interet = 4.3/100
while annee<20:
annee = annee+1
gain = somme*interet
somme = somme+gain
print (somme) |
# -*- coding: utf-8 -*-
# vi: sts=4 et sw=4
from controller import Controller
from jsonrpc.proxy import JSONRPCException
class Address(object):
'''A Bitcoin address. Bitcoin properties of an address (for example its
account) may be read and written like normal Python instance attributes
(foo.account... |
from django.db import models
# Create your models here.
#Product
class Product(models.Model):
category = models.ForeignKey('Category', related_name='products', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveInte... |
import os
import typing
import logging
import textwrap
import configparser
from .logginglib import log_debug
from .logginglib import log_error
from .pylolib import path_like
from .logginglib import get_logger
from .pylolib import human_concat_list
from .pylolib import get_datatype_human_text
from .datatype import Data... |
import os
import sys
import subprocess
import shutil
import time
import concurrent.futures
import fam
sys.path.insert(0, 'scripts')
sys.path.insert(0, os.path.join("tools", "trees"))
sys.path.insert(0, os.path.join("tools", "msa_edition"))
import saved_metrics
from run_mrbayes import MrbayesInstance
import experiments ... |
from django.conf.urls.defaults import *
from piston.resource import Resource
from devmgr.api.handlers import *
# TODO: CSRF protection currently disabled...fix this!
# The below is stolen from Taedium, maybe I can use that
"""
class CSRFDisabledResource(Resource):
def __init__(self, **kwargs):
super(self.__class>... |
from models import User
from sqlalchemy.engine import create_engine
from sqlalchemy.orm import sessionmaker
import traceback
from utils import strToToken
from settings import db_url
def isUserAuthenticated(session, username, password):
token = None
try:
user = session.query(User).filter(User.username... |
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
X, y = datasets.make_regression(n_samples=100, n_features=1, noise=20, random_state=4)
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2, random_state =1234)
... |
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework import viewsets
from .serializers import *
from .models import *
def index(request):
return HttpResponse("Hello, world. You're at the ProtoRoute index.")
class RouteGuideViewSet(viewsets.ModelViewSet):
queryset = Rout... |
from loader import dp
from keyboards.inline.herou1 import hero
from keyboards.inline.pow import power
from keyboards.inline.agi import agility
from keyboards.inline.netral import neutral
from keyboards.inline.intel import intelligence
from keyboards.inline.prost import easy
from keyboards.inline.items import item
from ... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family'] = 'STSong'
fig = plt.figure(figsize=(12, 8), dpi=100)
N = 100000
h = 0.1
m = 1.82781*10**8
X_P = 3.3*10**6
d = 16.5
C_b = 0.8580
B = 45.0
L = 280.0
S = 19556.1
p = 1.02473*10**3
v = 1.05372*10**(-6)
m_x = 4.799*10... |
import networkx as nx
from collections import defaultdict
file = "Day6/inputnaomi.txt"
with open(file,'r') as f:
data = f.readlines()
f.close()
G = nx.Graph()
# Construct directed graph A->B if A directly orbited by B
for row in data:
src,dst=row.strip().split(')')
G.add_edge(src,dst)
def BFS(start... |
# pihsm: Turn your Raspberry Pi into a Hardware Security Module
# Copyright (C) 2017 System76, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at y... |
"""
使用模块实现单例模式
"""
class Singleton(object):
def foo(self):
pass
singleton = Singleton() |
import pygame
from pygame.locals import *
from itertools import cycle
import random
import numpy as np
import cv2
import sys
import os
os.environ['SDL_VIDEODRIVER'] = 'dummy' # Run Headless Pygame environment
"""## Load Game Resources"""
def getHitmask(image):
"""returns a hitmask using an image's alpha."""
... |
import unittest
from katas.kyu_7.katastrophe import strong_enough
class StrongEnoughTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(strong_enough(
[[2, 3, 1], [3, 1, 1], [1, 1, 2]], 2), 'Safe!')
def test_equals_2(self):
self.assertEqual(strong_enough(
... |
from django.contrib import admin
from .models import *
# Register your models here.
class ProductAdmin(admin.ModelAdmin):
search_fields = ('title', 'description', 'specification')
admin.site.register(Brand)
admin.site.register(Products, ProductAdmin)
admin.site.register(Reviews)
admin.site.register(BuyCart)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('analyst', '0003_auto_20150405_2031'),
]
operations = [
migrations.AddField(
model_name='dataset',
na... |
import os
import sys
import glob
import shutil
import ntpath
import subprocess
from pathlib import Path
from zipfile import ZipFile
pkg_root = os.getenv("GITHUB_WORKSPACE")
if not pkg_root:
pkg_root = os.getcwd()
dest_root = os.path.join(pkg_root, 'public')
#clear out the assets folder
shutil.rmtree(os.path.j... |
#!/usr/bin/env python3
# Create a program that generates random sequences in FASTA format
# Each name should be unique
# Length should have a minimum and maximum
# GC% should be a parameter
# Use assert() to check bounds of command line values
# When creating sequences, append and join
# Command line:
# python3 rand_s... |
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from shop import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.cart_checker, name='cartChecker'),
path('home', views.home, name='home'),
path... |
import torch
import transformers
import turbo_transformers
from turbo_transformers.layers.utils import convert2tt_tensor, try_convert, convert_returns_as_type, ReturnType
import time
cfg = transformers.BertConfig()
model = transformers.BertModel(cfg)
model.eval()
torch.set_grad_enabled(False)
intermediate = torch.qua... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=150... |
import numpy as np
import scipy.sparse
import imgpr.utils as utils
from .model import FusionModel
delta = [(1, 0), (-1, 0), (0, 1), (0, -1)]
delta8 = [(1, 0), (-1, 0), (0, 1), (0, -1), (-1, -1), (-1, 1), (1, -1), (1, 1)]
def is_edge(x, y, mask):
if mask[x, y] == 0:
return 0
ret = 0
for dx, dy in ... |
#!/usr/bin/env python3
#
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# 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
#
# ... |
def clear_all_table():
clear_table(table_info)
clear_table(table_propertys)
clear_table(table_processes)
clear_table(table_services)
clear_table(table_programs)
clear_table(table_computers)
clear_table(table_hardwares)
def clear_all_wigets():
global selected_pc
selected_pc = ""
... |
"""Support for Vista Pool switches"""
import logging
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.const import CONF_USERNAME
from .vistapool_entity import VistaPoolEntity
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(hass, config, async_a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.