content stringlengths 5 1.05M |
|---|
import tkinter
from game.board import Board, Coordinate, SpaceOccupiedError
from player.abstract_player import AbstractPlayer
class TicTacToeGUI:
_BUTTON_WIDTH = 50
_BUTTON_HEIGHT = 50
_WINDOW_WIDTH = 150
_WINDOW_HEIGHT = 250
def __init__(self, player: AbstractPlayer):
# --- Common obje... |
from .sifar_swin import *
|
"""
Coordinate-based meta-analysis estimators
"""
import warnings
import multiprocessing as mp
from tqdm.auto import tqdm
import numpy as np
import nibabel as nib
from scipy import ndimage, special
from nilearn.masking import apply_mask, unmask
from statsmodels.sandbox.stats.multicomp import multipletests
from .kerne... |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import logging
import math
import pytest
import torch
from torch.distributions import constraints
import pyro
import pyro.distributions as dist
import pyro.poutine as poutine
from pyro.contrib.tracking.assignment import MarginalA... |
import discord, asyncio, random
from utils import searches
from utils.image_search import img
from discord.ext import commands
class CringeLatam(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("Module Cringe Latam re... |
import ssl
import socket
import datetime, smtplib
import json
import sys
import random
import requests
def send_notification(daysToExpiration,hostname):
day=str(daysToExpiration)
url = "Paste you slack channel webhook URL"
message = ("Hostname : "+hostname)
title = ("SSL Certificate will expire within ... |
from . import heap_sort
test_subjects = [
heap_sort
]
def test_heap_sort(test_sorting_algorithm):
test_sorting_algorithm(test_subjects)
|
#!/usr/bin/env python
import string
from glob import glob
from xml.etree.ElementTree import ElementTree, tostring
def warn_missing(element):
if element.tag not in action: print '============( %s )============' % element.tag
pass
action = {
'title': lambda element, context: ('\nh%s. %s\n\n' % (context['h... |
import torch
from torch import nn
from lightweight_openpose.modules.conv import conv, conv_dw, conv_dw_no_bn
class Cpm(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.align = conv(in_channels, out_channels, kernel_size=1, padding=0, bn=False)
self.trunk ... |
from django.contrib import admin, messages
from keycloak.exceptions import KeycloakClientError
from requests.exceptions import HTTPError
from django_keycloak.models import (
Client,
OpenIdConnectProfile,
RemoteClient
)
import django_keycloak.services.permissions
import django_keycloak.services.realm
import... |
from pathlib import Path
from .Template import Template
TEMPLATES_DIR = Path(__file__).parent / "templates"
class TemplateDir:
def __init__(self, path: Path = TEMPLATES_DIR):
self.path = path
def get_template(self, name):
path_file = self.path / (name + ".sql")
return Template(path_f... |
import requests
import time
from nose.tools import eq_ as eq
def assert_raises(excClass, callableObj, *args, **kwargs):
"""
Like unittest.TestCase.assertRaises, but returns the exception.
"""
try:
callableObj(*args, **kwargs)
except excClass as e:
return e
else:
if hasa... |
# Write your k-means unit tests here
import numpy as np
from scipy.spatial.distance import cdist
from cluster import (
KMeans,
Silhouette)
import pytest
def test_kmeans():
"""
Unit test for kmeans implementation.
"""
ground_truth = np.array([1, 1, 0, 1, 0, 1])
# Fit model and ... |
'''
ORMObject is an abstract base class for an object can be serialized to and
deserialized from a database row. Subclasses of this class can be initialized
with a database row, and their to_dict method serializes them back to a row.
To use this class, subclass it and set its COLUMNS class attribute to be the
non-id c... |
import inspect, sys
import os
import re
import django
def convert_camel_case_to_hifen(camel_case_string):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', camel_case_string)
return re.sub('([a-z0-9])([A-Z])', r'\1-\2', s1).lower()
def detect_primary_key_field(fields_of_model_class):
return next((fiel... |
""" Main programm
Show wheater data and mamange configuration
To do
- Add message to send with alarm
- Add authentication to allow some users to change values and/or
configuration data.
- Added auth.secret in ini files. Please merge your ini files with them on
http://static.frkb.fr/wdwapp
- Add .ini parameter to... |
# 2017-09-14T03:21:47.070-04:00
# VERSION 3
days = {}
for day in range(7, 12):
timeFrames = []
for hour in range(14, 18):
timeFrames.append(hour)
days[day] = timeFrames
for day, hours in days.items():
if day < 10:
print(f'{{day: "2020-04-0{day}", hours: {hours}}}')
else:
pr... |
import simplejson as json
settings = None
class Settings:
def __init__(self):
if settings is None:
settingsFile = open("settings.json")
self.data = json.load(settingsFile)
settingsFile.close()
def __getitem__(self, item):
return self.data[item]
... |
import asyncio
import sys
try:
import uvloop
except ImportError:
uvloop = None
import pytest
import asyncio_atexit
if sys.version_info >= (3, 7):
asyncio_run = asyncio.run
else:
def asyncio_run(coro):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(coro)
... |
from django.test import TestCase, tag
from django.utils import timezone
from smart_meter.models import GroupMeter, SmartMeter
from smart_meter.tests.mixin import MeterTestMixin
@tag('model')
class TestGroupMeterModel(MeterTestMixin, TestCase):
@classmethod
def setUpTestData(cls):
cls.user = cls.creat... |
import rospy
def can_transform(tf_buffer, target_frame, source_frame, time_):
return tf_buffer.can_transform_core(target_frame, source_frame, time_)[0]
def wait_for_transform(tf_buffer, target_frame, source_frame, timeout):
request_time = rospy.Time.now()
r = rospy.Rate(100)
while rospy.Time.now() <... |
import FWCore.ParameterSet.Config as cms
from Configuration.Geometry.GeometryExtended_cff import *
|
# Generated by Django 3.0.6 on 2020-05-28 18:09
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='customuser',
... |
import panther_event_type_helpers as event_type
def rule(event):
# filter events on unified data model field
return event.udm('event_type') == event_type.ADMIN_ROLE_ASSIGNED
def title(event):
# use unified data model field in title
return '{}: [{}] assigned admin privileges [{}] to [{}]'.format(
... |
# coding: utf-8
# In[1]:
# example of theano library
import theano
from theano import tensor
# declare two symboic floating point scalars
a=tensor.dscalar()
b=tensor.dscalar()
# create a simple symbolic expression
c=a+b
# convert the expression into a callable object that takes (a,b) and computes c
f = theano.funct... |
#!/usr/bin/env python3
from aws_cdk import core
import click
from .environment import Param
from .stack import CtStack
from . import names, aws
stack_props = {
"site_domain": Param("site_domain").get_value(),
"django_secret": Param("django_secret").get_value(decrypt=True),
"db_host": Param("db_host").get... |
import numpy as np
def stringify_vec(vec):
s = ""
for x in vec: s += str(x) + " "
return s
def distance(p1, p2):
pv1 = np.asarray(p1)
pv2 = np.asarray(p2)
return np.linalg.norm(pv1 - pv2)
def multireplace(arr, x, sub_arr):
new_arr = []
for entry in arr:
if (entry == x).all():
... |
import sys, os
from .LocalOptimizer import LocalOptimizer
import numpy as np
class GradientOptimizer(LocalOptimizer):
def __init__(self, n, m, f, g, df, dg, boundary_range, maximizer=True):
super(GradientOptimizer, self).__init__(n, m, f, g, df, dg, boundary_range, maximizer=maximizer)
s... |
import json
import logging
import re
import dateutil.parser
import requests
LOGGER = logging.getLogger(__name__)
# pylint: disable=too-many-instance-attributes
class PureAPI:
"""A class to perform queries through Pure Fitness/Yoga API.
"""
def __init__(self, username, password, region):
"""Cre... |
'''
* 라즈베리파이 센서 키트 Temp & humidity sensor 동작 예제
*
* 본 예제는 온습도 센서에서 수신된 데이터를 터미널 창으로 반복해 출력하는 동작을 합니다.
*
* 사용 소자 : 온습도 센서
* 온습도 센서
* VCC 핀 : 3.3V | GND 핀 : GND
* OUT : GPIO 40번 | BCM : 21
*
* ※ 모듈 연결 시 극성에 주의해 주도록 합니다.
*
* 예제 실행 전 아래 명령어로 Adafruit_DHT 라이브러리를 설치해 주어야 합니다.
* sudo pip3 install Adafruit_DHT
*
* 키트 정보 : ... |
import CryptoDownloadData as coinData
import pandas as pd
from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
coinbase = {'BTC' : {'CoinGeckID' : 'bitcoin'},
'ETH' : {'CoinGeckID' : 'ethereum'},
'BNB' : {'CoinGeckID' : 'binancecoin'},
'USDC' : {'CoinGeckID' : 'usd-coin'},
... |
## Unit 5 Lesson 4 - Button Canvas Interaction
## Computer Programming II - Gavin Weiss
# This program displays the letter being pressed
# on the canvas.
## Libraries
import time
import random
import simpleguitk as simplegui
## Define Global Variables
message = ("Long Live Pierce")
MessageOn = 0
## Define Hel... |
import pathlib
import setuptools
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setuptools.setup(
name="config-reader-ryazantseff",
version="0.0.1",
description="Jso... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
from bert.modeling import BertModel, BERTLayerNorm, ACT2FN
class ConfigurationError(Exception):
"""
The exception raised by any AllenNLP object when it's ... |
from drawquest.tests.tests_helpers import (CanvasTestCase, create_content, create_user, create_group,
create_comment, create_staff, create_quest, create_quest_comment)
from services import Services, override_service
class TestSimpleThing(CanvasTestCase):
def test_basic_a... |
#!/usr/bin/env python
import sys
import numpy as np
import pandas as pd
from frovedis.matrix.dense import FrovedisRowmajorMatrix, FrovedisColmajorMatrix
from frovedis.matrix.crs import FrovedisCRSMatrix
from frovedis.exrpc.server import FrovedisServer
from frovedis.mllib.manifold import TSNE
from scipy.sparse import c... |
import uuid
import decimal
from typing import Union
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError
from vpos.utils import get_calculated_fees
from vpos.validators import PhoneValidator
from vpos.signals import transaction_complete... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect
from .models import Movie, Comment
from .forms import CommentForm
# Create your views here.
def index(request):
return HttpResponse('<h1>Welcome!</h1>')
def movie_detail(request, ... |
import RPi.GPIO as GPIO
import time
# pin numbering
GPIO.setmode(GPIO.BCM)
# choose pin 11 (GPIO 17) for the LED
led = 17
GPIO.setup(led,GPIO.OUT)
# Flash
GPIO.output(led,GPIO.HIGH)
time.sleep(60)
GPIO.output(led,GPIO.LOW)
GPIO.cleanup() |
##############################################################################################
##############################################################################################
## ##
## ## ## ##### ### ... |
from datetime import datetime
from project import db
# ---------------------------------------------------
# User Database Model
# ---------------------------------------------------
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(250), ... |
from flask import render_template
from flask_login import login_required
from app.helpers import api_get
from app import app
@app.route("/top20", methods=["GET"])
def top20():
query = {"filters": []}
top20pages = api_get('top20/pages', query, True)
top20inlinks = api_get('top20/inlinks', query, True)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import annotations
import copy
import os
import re
from typing import Tuple, Union
import networkx as nx
import numpy as np
import pandas as pd
import partridge as ptg
from partridge.config import default_config
from .Logger import WranglerLogger
from .U... |
# -*- coding: UTF-8 -*-
# Copyright (c) 2019 PaddlePaddle Authors. 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
#
... |
# -*- coding: utf-8 -*-
"""X
The Spicy domain for Sphinx.
"""
def setup(Sphinx):
Sphinx.add_domain(SpicyDomain)
from sphinx import addnodes
from sphinx.domains import Domain, ObjType
from sphinx.locale import l_, _
from sphinx.directives import ObjectDescription
from sphinx.roles import XRefRole
from sphinx.u... |
import unittest
from example import app
class appTestCase(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
app.config["TESTING"] = True
def tearDown(self):
pass
def test_get_tasks(self):
response = self.app.get("/api/v0.1/tasks")
self.assertEqu... |
#!/usr/bin/env python3
import os
import datetime
import json
import logging
import cfg
import pandas as pd
from sklearn.datasets.base import Bunch
from sklearn.preprocessing import LabelEncoder
# -----------------------------------------------------------
__logger__ = [None]
def log():
if __logger__[0] is not... |
from flask import request
from sqlalchemy import Column, Integer, String
from .base import Base
class AppAccessLog(Base):
id = Column(Integer, primary_key=True)
refer_url = Column(String(255), comment='当前访问的refer')
target_url = Column(String(255), comment='访问的url')
ua = Column(String(255), comment='访... |
import speech_recognition as sr
import time
import os
import random
from gtts import gTTS
from audioplayer import AudioPlayer
from transformers import pipeline
from googletrans import Translator
context = """My name is Harry. I am 24 years old. I am a male.
My favourite sports are football and basketball. I am curren... |
def duplicates(ls):
if len(ls) != len(set(ls)):
print('It has duplicates')
def duplicates(ls):
for i, e in enumerate(ls):
if e in ls[i+1:]:
print('It has duplicates')
return
# there are many possible solutions...
|
# Generated from 'Events.h'
nullEvent = 0
mouseDown = 1
mouseUp = 2
keyDown = 3
keyUp = 4
autoKey = 5
updateEvt = 6
diskEvt = 7
activateEvt = 8
osEvt = 15
kHighLevelEvent = 23
mDownMask = 1 << mouseDown
mUpMask = 1 << mouseUp
keyDownMask = 1 << keyDown
keyUpMask = 1 << keyUp
autoKeyMask = 1 << autoKey
updateMask = 1 <... |
"""
Agent that creates symlinks to logfiles and embeds metadata in the
file/directory name of the Symlink. Can be used in conjunction with a
log shipping agent (e.g. Fluentd) that watches the directory structure
containing the symlinks. Since all metadata is embedded in the
filename, there is no need to dynamically ge... |
#
'''
Instructions :
#Find the missing letter
Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.
You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.... |
"""
Leetcode #357
"""
class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
"""
for n = 1, you have 9 choices
for n = 2, you have 9*9 choices
for n = 3, you have 9*9*8 choices for unique digits
...
...
for n = 10, you have 9*9*8*7....1 c... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from datetime import datetime
from subprocess import check_output, CalledProcessError
from setuptools import setup, find_packages
from warnings import warn
def version... |
import os
import sys
# README.md
#
# header.md
# list.md -> make_table
# footer.md
headers = list()
updateLog = list()
footers = list()
tables = list()
with open('./markdown/header.md', 'r') as f:
headers = f.readlines()
f.close()
with open('./markdown/footer.md', 'r') as f:
footers = f.readlines()
... |
import curses
import sys
from copy import deepcopy
from board import Board
from game_exception import BoardException, LetterCommandException, InvalidCommandException
from view import display_game, show_cell_nums
# prepare game and run the main loop
def main(stdscr):
set_colors()
if len(sys.argv) > 1:
... |
"""
Progress Bar - Simple and Fast
Refer Doc for more info:
https://github.com/tarunk04/progress-bar-python - Repo
https://medium.com/analytics-vidhya/progress-bar-python-for-jupyter-notebook-f68224955810 - Tutorial
----------------------------------
Simple and easy to use progress bar.
Author : Tarun Kumar
""... |
"""
User Entity Module
"""
# Django
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
class User_Entity():
def insert_one(self, user):
"""Insert a New User"""
if self.get_one_by_username(user["username"]) is not False:
return False
... |
from django.urls import reverse_lazy
from ET.mixins import GroupRequiredMixin
class CustomerRequiredMixin(GroupRequiredMixin):
group_required = 'customer'
login_url = reverse_lazy('cust_login')
|
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtGui import QStandardItem, QStandardItemModel
from PyQt5 import QtCore, QtGui
from UI.ui_sequence import Ui_MainWindow
from database import Data
import functions
import os
class SequenceUI(object):
def __init__(self):
self.window = QMainWindow()
... |
from __future__ import print_function
# TODO move all defs to the top of the file, out of the way of the flow of execution.
# TODO full python3 support will involve installing the adafruit drivers, not using the ones from the repo
import traceback
import argparse
import robot_util
import os.path
import networking
imp... |
def heal(entity, amount_of_hp):
if entity.life + amount_of_hp > entity.max_life:
entity.life = entity.max_life
else:
entity.life += amount_of_hp
def energyup(entity, par):
if entity.mana + par > entity.max_mana:
entity.mana = entity.max_mana
else:
entity.mana += par... |
"""
Original implementation: https://github.com/DPautoGAN/DPautoGAN
Modified by: Amirsina Torfi
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE... |
"""This test's password confirmation in the registration page """
from flaskr import flaskr
def login(client, password, confirm):
return client.post('/register', data=dict(
password=password,
confirm=confirm
), follow_redirects=True)
def test_successful_login(client):
response = login(cli... |
import itertools
import re
import sunfish
################################################################################
# This module contains functions used by test.py and xboard.py.
# Nothing from here is imported into sunfish.py which is entirely self-sufficient
#################################################... |
u = [1, 2, 3]
print(u)
# part a
print(sum(u))
|
# set the matplotlib backend so figures can be saved in the background
import imutils
import matplotlib
# matplotlib.use("Agg")
from keras.callbacks import CSVLogger
from keras.optimizers import Adam
from matplotlib import pyplot
from sklearn.model_selection import train_test_split
from keras.preprocessing.image impo... |
from django.contrib import admin
# Register your models here.
from .models import Movie, Genre, Actor, Director
admin.site.register(Movie)
admin.site.register(Genre)
admin.site.register(Actor)
admin.site.register(Director) |
from django.db import models
# Create your models here.
from keygen.models import Key
class KeyUrlMap(models.Model):
# TODO : Add Integrity Error in save in case two active maps for same key.
key = models.ForeignKey(Key, on_delete=models.CASCADE)
url = models.TextField()
is_active = models.BooleanFi... |
# Import external dependencies
from yaml import load
from random import randint
from ast import literal_eval
# Constants
READINGS_CONFIG = "./data/readings.yaml"
with open(READINGS_CONFIG, "r") as file:
readings = load(file.read())
readings_n = len(readings)
def reading():
read = readings[ra... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
# -*- coding: utf-8 -*-
"""
This module interfaces with proj.4 to produce a pythonic interface
to the coordinate reference system (CRS) information through the CRS
class.
Original Author: Alan D. Snow [github.com/snowman2] (2019)
Permission to use, copy, modify, and distribute this software
and its documentation for ... |
from heapq import nsmallest
from .helperfuncs import (
calculate_distance, calculate_fitness_value,
calculate_total_error, compare_targets,
get_normalize_constants
)
class FitnessAssigner:
@classmethod
def assign_fitness_first(cls, gen):
"""
Assign fitness values for the first ge... |
from tests import PMGLiveServerTestCase
from pmg.models import db, BillStatus
from tests.fixtures import (
dbfixture, BillData, BillStatusData
)
class TestBillsPages(PMGLiveServerTestCase):
def setUp(self):
super(TestBillsPages, self).setUp()
self.fx = dbfixture.data(
BillStatusDa... |
import test262p.x
assert __name__ == "test262m"
|
from populations.population import Population
from populations.individual import Individual
from typing import List
from selections.tournament import tournament
from selections.roulette import roulette
from crossovers.ox import ox
from mutations.rsm import rsm
from utilities.rnd import rndChance
def percentageChance(r... |
from typing import Any
class RingBuffer:
"""A circular FIFO queue that uses a fixed amount of space.
This lets us efficiently queue and dequeue objects in O(1) time,
and let us access objects in O(1) time without having to resize.
The downside is that we CAN'T resize.
* Enqueue: O(1)
* Deque... |
"""
Source code for PyGMT modules.
"""
# pylint: disable=import-outside-toplevel
from pygmt.src.meca import meca
|
#!/usr/bin/python
import sys
import gzip
if len(sys.argv) != 3:
print "USAGE: create-desc.py <db file> <out file>"
sys.exit(1)
input = gzip.open(sys.argv[1])
fp = open(sys.argv[2], 'w')
for line in input:
if line.startswith('>'):
line = line[1:]
fp.write(line)
|
from flask import request
from flask_restplus import Resource
from restapi.api.restplus import api
from restapi.api.business import (create_category, update_category,
delete_category)
from restapi.database.models import Category
from restapi.api.api_model_view import category, category... |
import pytest
from naomi_bot.app.update_branch import update_branch
def test_update_branch():
# Some interaction test for the requests?
assert True |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
"""
Don't forget to append end token for Subtle dataset!!
"""
# Imports for compatibility between Python 2&3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange
import numpy as np
imp... |
import numpy as np
import torch
class Trainer:
def __init__(self, model, criterion, optimizer, config, scheduler=None):
self.model = model
self.criterion = criterion
self.optimizer = optimizer
self.loss = {"train": [], "val": []}
self.epochs = config["epochs"]
self.... |
'''Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. No final,
mostre uma listagem de preços, organizando os dados em forma tabular.'''
produtos = ('Lápis', 1.75, 'Borracha', 2.00, 'Caderno', 15.90, 'Estojo', 25.00, 'Transferidor', 4.20, 'Compasso', 9.99, 'Mochila... |
from Miner import Miner
from Projection import Projection
from datetime import datetime
from datetime import timedelta
import numpy as np
class Reinvestment:
__const1000GHS = 65
__transferFees = 3.5
__planDays = 90
referralProjection = None
def __init__(self, projection, days, minWait=1, minBuy=1,... |
#pylint:disable=no-member
import cv2 as cv
# Read in an image
img = cv.imread('../Resources/Photos/park.jpg')
cv.imshow('Park', img)
#
# Converting to grayscale
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray', gray)
# Blur
blur = cv.GaussianBlur(img, (7,7), cv.BORDER_DEFAULT)
cv.imshow('Blur', blur)
... |
import json
import os
import boto3
import datetime
from urllib.parse import unquote_plus
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
def lambda_handler(event, context):
for record in event['Records']:
... |
# file: runme.py
# Throw a lot of exceptions
import example
t = example.Test()
try:
t.unknown()
except RuntimeError, e:
print "incomplete type", e.args[0]
try:
t.simple()
except RuntimeError, e:
print e.args[0]
try:
t.message()
except RuntimeError, e:
print e.args[0]
if not example.is_pyth... |
missing = type.__new__(
type, "missing", (object,), {"__repr__": lambda self: self.__class__.__name__}
)()
class ResolveError(Exception):
pass
|
#!/usr/bin/env python
import pytest
from sonic_package_manager.constraint import ComponentConstraints
from sonic_package_manager.manifest import Manifest, ManifestError
def test_manifest_v1_defaults():
manifest = Manifest.marshal({'package': {'name': 'test',
'version... |
from awacs.aws import Allow, PolicyDocument, Principal, Statement
from awacs.sts import AssumeRole
from troposphere import GetAtt, Tags, Template
from troposphere.dlm import (
CreateRule,
LifecyclePolicy,
PolicyDetails,
RetainRule,
Schedule,
)
from troposphere.iam import Role
t = Template()
t.set_... |
from flask_unchained import BundleConfig
class Config(BundleConfig):
OAUTH_REMOTE_APP_GITHUB = dict(
base_url='https://api.github.com',
access_token_url='https://github.com/login/oauth/access_token',
access_token_method='POST',
authorize_url='https://github.com/login/oauth/authoriz... |
from torch import nn
import torch.nn.functional as F
import fvcore.nn.weight_init as weight_init
from detectron2.modeling.backbone import FPN, build_resnet_backbone
from detectron2.layers import ShapeSpec
from detectron2.modeling.backbone.build import BACKBONE_REGISTRY
from .resnet_lpf import build_resnet_lpf_backbon... |
'''
join several sub collections' features into one large collection feature
'''
import os
import sys
import logging
from basic.constant import ROOT_PATH
from basic.generic_utils import Progbar
from basic.bigfile import BigFile
logger = logging.getLogger(__file__)
logging.basicConfig(
format="[%(asctime)s - %... |
'''
a template for train, you need to fix your own main function
'''
import sys
sys.path.append('..')
from models.resnet_cbam import resnet18_cbam
from src.xxx_dataloader import xxx_dataloader
from configuration.config_normal import args
import torch
import torch.nn as nn
from lib.model_develop_utils import train_ba... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
import keras
import keras.layers as kl
if __name__ == '__main__':
tlayer = kl.InputLayer(input_shape=(3, 3, 3))
print (tlayer.get_config())
|
#
__version__ = '3.0.5'
|
import logging
import re
from pathlib import Path
from textwrap import dedent
import pkg_resources
class DatabaseError(Exception):
pass
# This schema upgrade mechanism is simplistic and doesn't work well with code merges.
# Alembic would be better though more complex.
schema_version_table = dedent("""
C... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 23 20:27:59 2019
@author: Alex
"""
#INVESTIGATING FREEFALL USING THE EULER METHOD
#-----------------------------------------------------------
#PART A
#-----------------------------------------------------------
import numpy as np
import matplotli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.