content stringlengths 5 1.05M |
|---|
from __future__ import print_function, division
import traceback
__author__ = 'panzer'
class RuntimeException(Exception):
def __init__(self, message):
super(RuntimeException, self).__init__(message)
self.name = RuntimeException.__name__
@staticmethod
def print_trace():
traceback.print_exc() |
from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class DeviceZoneRemote(RemoteModel):
"""
Zones defined on a traffic filtering device. On devices that do not natively support zones (e.g., Cisco routers), there is one zone per interface, plus an additional 'intern... |
if __name__ == '__main__':
import sys
import pydart2 as pydart
if len(sys.argv) != 2:
print("Usage: view_skeleton.py [*.urdf/*.sdf]")
exit(0)
skel_path = sys.argv[1]
print("skeleton path = %s" % skel_path)
pydart.init()
print("Pydart init OK")
world = pydart.World(0.0... |
#!/usr/bin/env python3
import numpy as np
import scipy.io as sio
import sklearn.feature_extraction
from pathlib import Path
import argparse
parser = argparse.ArgumentParser(description='Sample patches from figures')
parser.add_argument('--experimentName', default="naturalImages",
help='the folder n... |
import uuid as uuid
from django.db import models
class News(models.Model):
"""
News item contains the necessary information to read out the news.
"""
# External ID, might be textual or number.
external_id = models.CharField(max_length=128)
uuid = models.UUIDField(default=uuid.uuid4)
# Ma... |
__author__ = "Chris Brannon <chris@the-brannons.com>"
__copyright__ = "See the file LICENSE for copyright and license info"
__license__ = "See the file LICENSE for copyright and license info"
__version__ = "0.3"
__email__ = "chris@the-brannons.com"
|
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from collections import defaultdict as dd
import argparse
import gzip
import util
import sys
import os
import logging
import shutil
import struct
import subprocess
import tempfile
import bz2file
def compress(source, target, reference, nointra, delta, inner, pagesize... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
# Written by Ross Girshick
"""This file contain the utils class that can
improve programming efficiency on IPU by popart.
"""
import builtins
import string
import numpy as np
import popart
from _globals import GLOBAL_V, set_batch, get_batch_size, get_anchor_retur... |
import json
import functools
from graphviz import Digraph
def main():
"""
Plots the relationships defined by the JSON files below using Graphviz.
"""
# Read the raw data
relationship_filename = "relationships_by_id.json"
name_map_filename = "ids_to_names.json"
with open(relationship_file... |
import numpy as np
import os
from surfinpy import p_vs_t
from surfinpy import utils as ut
from surfinpy.data import DataSet
import unittest
from numpy.testing import assert_almost_equal
test_data = os.path.join(os.path.dirname(__file__), 'H2O.txt')
class Testp_vs_t(unittest.TestCase):
# Is this needed... |
from minio import Minio
from minio.error import ResponseError
import json
import os
# Request
# {
# "inbox": "aellis_catjump_inbox",
# "outbox": "aellis_catjump_outbox"
# }
def handle(st):
req = json.loads(st)
mc = Minio(os.environ['minio_authority'],
access_key=os.environ['minio_access... |
# -*- coding: utf-8 -*-
import numpy as np
from random import getrandbits
def check_equality(matrix1, matrix2, encoding = None):
'''
Checks to see if 2 matrices are equivalent. If an encoding is specified,
first converts elements in matrix1 using encoding, then checks for equality
with matrix2
Parameters:
matri... |
# Plot the data from the Rpi, read through the "camera_data" topic
import paho.mqtt.client as mqtt
import json
# Connect to the broker
broker_url, broker_port = "192.168.43.210", 1883
client = mqtt.Client()
client.connect(broker_url, broker_port)
# Wrap the commands issuing in a loop
try:
client.loop_start()
... |
########################################################################################
#
# Implement random permutations in the encoder for potentially beneficial
# regularization.
#
# Author(s): Nik Vaessen
########################################################################################
from typing import O... |
"""Little script for exporting BigGAN zs/ys used in data collection."""
import argparse
import pathlib
import shutil
from src.utils import env
from tqdm.auto import tqdm
parser = argparse.ArgumentParser(description='export biggan zs')
parser.add_argument('--data-dir',
type=pathlib.Path,
... |
import log_config_util
from arxivcitationnetwork import ArxivCitationNetwork, format_name_to_id
from collections import defaultdict
log = log_config_util.get_logger("merger")
N = 5 # Number of status updates per loop
def merge_bierbaum_network(citation_network: ArxivCitationNetwork, metadata_aid_to_doi_title):
... |
#!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
#! /usr/bin/env python3
import argparse
import datetime
import json
if __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("manifest", help="Path to app container Manifest")
m = args.parse_args().manifest
print m
with open(m, 'r') as f:
manifest = json.load(f)
pr... |
# 矩阵置零
from typing import List
class Solution:
# 记录0出现的位置,然后再置为0
def setZeroes_1(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
hor, ver = set(), set()
for i in range(len(matrix)):
for j in range(len(... |
from django.core.management.base import BaseCommand
from twiggy_goodies.django import LogMixin
from allmychanges.models import LightModerator
class Command(LogMixin, BaseCommand):
help = u"""Deletes stale light moderators from the database"""
def handle(self, *args, **options):
LightModerator.remove_... |
from collections import defaultdict
#### test expressions
sample1 = "(A & B) & (F | E)"
sample2 = "(A & (B | C)) & (F | E)"
sample3 = "FAKE"
sample4 = "(((A & B) & (C & D)) | 5)"
sample5 = "(A & (B | C)) & (F | E)"
sample6 = "!(A & B) | (C | (D & E))"
sample7 = "!A & B"
sample8 = "!(A & B)"
sample9 = "!(A & B) & !C"... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
一个用来生成各类虚假数据的库
"""
import mimesis
def fake_person():
person = mimesis.Person()
print(person.name())
print(person.full_name())
print(person.age())
if __name__ == "__main__":
fake_person()
|
import sys
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio import SeqIO
import psycopg2
import os
import subprocess
listFile = open(sys.argv[1])
outFile = open(sys.argv[2], 'w')
dbName = sys.argv[3]
table = sys.argv[4]
conn = psycopg2.connect("dbname={0}".format(... |
import base64
import psycopg2
import openerp
from openerp import SUPERUSER_ID
from openerp import http
from openerp.http import request
from openerp.addons.web.controllers.main import content_disposition
import mimetypes
class MailController(http.Controller):
_cp_path = '/mail'
@http.route('/mail/download_a... |
from enum import Enum
from benchmarking import benchmark
class MyEnum(Enum):
A = 1
B = 2
C = 3
@benchmark
def enums() -> None:
a = [MyEnum.A, MyEnum.B, MyEnum.C] * 10
n = 0
for i in range(100000):
for x in a:
if x is MyEnum.A:
n += 1
elif x is ... |
from flask import Flask, redirect,render_template, request
import json
import view_model as vm
app = Flask(__name__)
@app.route("/")
def main_page():
return render_template("index.html",page_title="Pricer")
@app.route("/get_price",methods=['POST'])
def get_price():
dict_args = {}
dict_args['strategy'] = ... |
"""
与类和对象相关的一些BIF:
1.一个类被认为是其自身的子类
issubclass(class,classinfo)
2.classinfo可以是类对象组成的元组,只要class与其中任何一个候选类的子类,则返回True
issubclass(class,classinfo)
"""
class A:
pass
class B(A):
pass
print('--------------------------------------------')
print(issubclass(B, A))
print('-------------------------------------... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# BSD 3-Clause License
#
# Copyright (c) 2020-2022, Faster Speeding
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of sour... |
import hashlib
import pytest
from mock import patch
from flask import url_for
from playhouse.test_utils import assert_query_count
from app import instance_keys, app as realapp
from auth.auth_context_type import ValidatedAuthContext
from data import model
from data.cache import InMemoryDataModelCache
from data.databas... |
"""
MIT License
Copyright (c) 2019 Denis Yarats
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, ... |
from email.utils import formataddr
import requests
from CTFd.utils import get_app_config, get_config
def sendmail(addr, text, subject):
ctf_name = get_config("ctf_name")
mailfrom_addr = get_config("mailfrom_addr") or get_app_config("MAILFROM_ADDR")
mailfrom_addr = formataddr((ctf_name, mailfrom_addr))
... |
import pyvista
pyvista.global_theme.font.label_size = 20
|
from urllib.parse import urlencode
from openpyxl import Workbook
import datetime
import json
import requests
now = datetime.datetime.now()
areaUrls = [
{'url': 'https://hakwon.sen.go.kr', 'areaNm': '서울'},
{'url': 'https://hakwon.pen.go.kr', 'areaNm': '부산'},
{'url': 'https://hakwon.dge.go.kr', 'areaNm': '대구... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from conans import tools
from conans.client.tools.win import get_cased_path
from conans.test.utils.test_files import temp_folder
import os
import platform
from conans.util.files import mkdir
class GetCasedPath(unittest.TestCase):
@unittest.skipUnless(... |
import random
import secrets
import string
import typing
from dataclasses import dataclass, field
from morpfw.crud import Schema
def current_userid(request, data, model):
if data["userid"] is None:
data["userid"] = request.identity.userid
return data["userid"]
def generate_identity(request, data, m... |
import urllib
from googleapiclient import discovery
from PIL import Image
class ImageSearch(object):
CUSTOM_SEARCH_API = 'AIzaSyBFoF4sDsSj6FV8O-cYsyHbU9stfIrACJg'
MENU_PICTURE_CSE = '000057874177480001711:2ywzhtb3u6q'
def __init__(self):
self.service = discovery.build('customsearch',
... |
#!/usr/bin/env python
import telnetlib
import time
TELNET_PORT = 23
TELNET_TIMEOUT = 6
def main():
ip_addr = "184.105.247.70"
username = "pyclass"
password = "88newclass"
telnet_conn = telnetlib.Telnet(ip_addr, TELNET_PORT, TELNET_TIMEOUT)
output = telnet_conn.read_until("sername:", TELNET_TIM... |
# Copyright 2013 mysqlapi authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from unittest import TestCase
from django.conf import settings
from django.test.utils import override_settings
from mysqlapi.api.management.commands import s3
... |
"""Special addresses in hex values"""
IPV4_LOCALHOST = 0x7F_00_00_01 # 127.0.0.1, or 2130706433
IPV6_LOCALHOST = 0x1 # ::1
|
from __future__ import absolute_import, unicode_literals
import unittest
from draftjs_exporter.error import ConfigException
from draftjs_exporter.options import Options
class TestOptions(unittest.TestCase):
def test_str(self):
self.assertEqual(str(Options('unordered-list-item', 'li')), '<Options unorder... |
from pathlib import Path
from typing import Union, List
import torch
import torch.nn.functional as F
from transformers import GPT2LMHeadModel, GPT2Tokenizer, GPT2PreTrainedModel
from transformers.generation_utils import top_k_top_p_filtering, calc_banned_bad_words_ids
from utils import utils
MAX_LENGTH = int(10000) ... |
larg = float(input('Largura da Parede:'))
alt = float(input('Altura da parede:'))
area = larg * alt
tinta = area / 2
print('Sua area de parde tem a dimessão de {} X {} \n se ua area é de {:.2f} m²'.format(larg, alt, area))
print('Para pintar a parde você precisa de {} litro de tinta'.format(tinta)) |
# coding=utf-8
#-----------------------------------------------------------
# IMPORTS
#-----------------------------------------------------------
import language
import messages
from entities import Entity
#-----------------------------------------------------------
# CLASSES
#-------------------------------------... |
from django.contrib import admin
from moduleevaluation.files.models import Document
admin.site.register(Document)
# Register your models here.
|
with open("day-10.txt") as f:
nav_sys = f.read().rstrip().splitlines()
pairs = {
")": "(",
"]": "[",
"}": "{",
">": "<",
}
points = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
}
score = 0
for line in nav_sys:
brackets = []
for char in line:
if char in pairs:
... |
#!/usr/bin/python
#from gpiozero import Button
import signal
import os, sys
import time
#import uinput
from evdev import uinput, UInput, ecodes as e
import RPi.GPIO as gpio
#from smbus import SMBus
DEBUG = False
Debounce = 0.01
R_slider = 4 # uinput.KEY_VOLUMEUP, Right slider
L_slider = 27 # uinput.KEY_VOLUMEDOWN, L... |
# -*- coding: utf-8 -*-
from sqlalchemy.exc import IntegrityError
class MetadataManagerReadError(Exception):
pass
class InvalidMimeTypeError(Exception):
def __init__(self, mimetype):
msg = "Invalid mimetype '%s'" % str(mimetype)
super(InvalidMimeTypeError, self).__init__(msg)
class NoConf... |
import os
import aiohttp
import time
import re
import logging
import glob
import random
from datetime import datetime
from contextlib import asynccontextmanager, contextmanager
from PIL import Image, ImageDraw, ImageFont
from athena_bot import utils
from datetime import datetime, timedelta
logger = logging.getLogger(_... |
# MAKE SURE TO RUN THESE TESTS USING PYTHON3, NOT PYTHON2!
# AS ALWAYS, DO NOT CHANGE THE TESTS!
import subprocess
import sys
import unittest
def runcmd(cmd, input_text=None):
splitcmd=cmd.split()
return subprocess.run(splitcmd, stdout=subprocess.PIPE, input=input_text, check=True)
class HelloTests(unittest.Te... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file acc... |
'''Autonomous driving convolutional neural network example from p. 64 of the book.
Code based on https://github.com/OSSDC/AutonomousDrivingCookbook/tree/master/AirSimE2EDeepLearning'''
from keras.models import Model
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Input, concatenate
from keras.... |
import unittest
from shiny_client import category
import requests
from base_test import ApiResourceTest
from shiny_client import base_client
class TestCategoryListCommand(unittest.TestCase):
RESOURCE_URL = "https://api.zalando.com/categories"
def test_instantiate(self):
base_client.PluginCommandBase... |
import json
import py.path
import pytest
import apypie
@pytest.fixture
def fixture_dir():
return py.path.local(__file__).realpath() / '..' / 'fixtures'
@pytest.fixture
def apidoc_cache_dir(fixture_dir, tmpdir):
fixture_dir.join('dummy.json').copy(tmpdir / 'default.json')
fixture_dir.join('dummy.json')... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
# Copyright: [CUP] - See LICENSE for details.
# Authors: Guannan Ma (@mythmgn),
"""
common function module for cup.net.async
"""
import socket
import struct
from cup.util import misc
__all__ = [
'ip_port2connaddr', 'add_stub2connaddr', 'add_future2connaddr',
'get_... |
from django.db import models
from auth1.models import *
from api.managers import FeedbackManager
# Create your models here.
class Feedback(models.Model):
driver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='driver_feedback')
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
... |
import os
from pathlib import Path # noqa
here = Path(__file__).resolve(strict=True).parent.parent
__all__ = ["__version__"]
with open(os.path.join(os.path.dirname(here), '../VERSION')) as version_file:
__version__ = version_file.read().strip()
|
import numba
import numpy as np
from collections import Counter, defaultdict
class hogImg():
"""example usage:
hog = hogImg(arr=np.random.randint(1, 101, size=(19,19)))
f = hog.do_work()"""
def __init__(self, arr, oriens=6, ppc=(3, 3), cpc=(6, 6)):
self.arr = arr
self.oriens = oriens
... |
"""Setuptools Module."""
from setuptools import setup, find_packages
setup(
name="githubutils",
version="0.1",
packages=find_packages(),
install_requires=['requests'],
# metadata for upload to PyPI
author="Alexander Richards",
author_email="a.richards@imperial.ac.uk",
description="Utili... |
from enum import Enum
from dagster import SolidExecutionResult, execute_solid
from dagster_utils.contrib.data_repo.typing import JobId
from hca_orchestration.solids.load_hca.ingest_metadata_type import ingest_metadata_type
from hca_orchestration.support.typing import HcaScratchDatasetName, MetadataType
class FakeEn... |
from setuptools import setup
setup(
name='django-bootstrap3-datetimepicker',
packages=['bootstrap3_datetime',],
package_data={'bootstrap3_datetime': ['static/bootstrap3_datetime/css/*.css',
'static/bootstrap3_datetime/js/*.js', ]},
include_package_data=True,
... |
'''
Using the global view
=====================
The `addresses` view provides access to all the addresses registered in the DB,
as well as methods to create and remove them::
eth0 = ndb.interfaces['eth0']
# create an address
(ndb
.addresses
.create(address='10.0.0.1', prefixlen=24, index=eth0[... |
#-*-coding:utf-8-*-
#date:2019/01/01
#@title MIT License
#
# Copyright (c) 2017 François Chollet
# Copyright (c) 2018 Joker2770
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software wi... |
# -*- coding: utf-8 -*-
from hashlib import sha1
import hmac
class Pushpad(object):
def __init__(self, auth_token, project_id):
self.auth_token = auth_token
self.project_id = project_id
def signature_for(self, data):
return hmac.new(bytes(self.auth_token.encode()), data.encode(), sha1... |
from .QueuePipe import QueuePipe
import multiprocessing
from multiprocessing import Process, Queue
from typing import List, Tuple, Union, Any
from collections.abc import Callable
import time
import signal
class PayloadProcess:
def __init__(self, payload: Tuple[str, Callable, Tuple, Callable, Tuple, Union[float, N... |
# Generated by Django 3.0.3 on 2020-05-23 12:31
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('main', '0014_auto_20200523_1236'),
]
operations = [
migrations.RemoveField(
model_name='block',
name='id... |
from django.urls import reverse
from django.db import models
class Weight(models.Model):
""" Weight model (measured in kg). """
id = models.AutoField(primary_key=True, editable=False)
datestamp = models.DateField(blank=True, null=True)
weight = models.FloatField(blank=True, null=True)
author = mod... |
from conans import ConanFile, CMake, tools
import os
class SfmlConan(ConanFile):
name = 'sfml'
description = 'Simple and Fast Multimedia Library'
topics = ('sfml', 'multimedia')
url = 'https://github.com/bincrafters/community'
homepage = 'https://github.com/SFML/SFML'
license = "ZLIB"
expo... |
from pathlib import Path
from tempfile import TemporaryDirectory
from urllib.parse import urljoin
import pytest
from django.conf import settings
from snoop import models, walker, views
pytestmark = [
pytest.mark.django_db,
pytest.mark.skipif(not settings.DATABASES, reason="DATABASES not set"),
]
def _collecti... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# this
import utils
def vectorizer(labeled_message, term_voc, doc_voc):
"""
labeled_message: dict
donary with the following fields: {score, id, terms, features}
term_voc : core.TermVocabulary
doc_voc : core.DocVocabulary
returns : dict
vec... |
# -*- coding: utf-8 -*-
"""
@author: Rajesh
"""
from typing import List, Tuple
import imageio
from io import BytesIO
from PIL import Image
import hydra
from omegaconf import open_dict, DictConfig
from typing import Mapping
import numpy as np
import os
import streamlit as st
from dataloader.ufs_data import UnknownTes... |
# finds files that were not successfully converted; when I ran the code,
# this revealed 14, all of which had misformed URLs. I corrected them
# manually and re-ran the import
import os
GML_PATH = './spain_catastre/gml'
if __name__ == '__main__':
for f in os.listdir(GML_PATH):
parts = f.split('.')
... |
#!/usr/bin/env python2
import socket
import struct
import sys
# Monkey patch for:
# - SOCK_SEQPACKET
# - IPPROTO_SCTP
# - bindx
if not hasattr(socket, 'SOCK_SEQPACKET'):
socket.SOCK_SEQPACKET = 5
if not hasattr(socket, 'IPPROTO_SCTP'):
socket.IPPROTO_SCTP = 132
SCTP_BINDX_ADD_ADDR = 1
SCTP_BINDX_REM_ADDR = 2
... |
"""
Capstone Project. Code to run on the EV3 robot (NOT on a laptop).
Author: Your professors (for the framework)
and Yicheng Yang..
Winter term, 2018-2019.
"""
import M2_rosebot
import mqtt_remote_method_calls as com
import time
import m2_gui_delegate
def main():
"""
This code, which must run on ... |
# Copyright 2019 The Feast Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
import torch
import torch.nn as nn
import torch.autograd.Function as F
from seqtalk.binary_neurons import StochasticBinaryActivation
from collections import namedtuple
import numpy as np
TrainingParams = namedtuple('TrainingParams', [
'minibatch_size',
'num_epochs',
'minibatches_per_epoch',
'processor'... |
#!/usr/local/bin/python3
import time
import os
import sys
import socks
import socket
import urllib.request
from log import *
print ('''\033[1;31m \n
_ _
| | (_)
__ _ _ _| |_ ___ _ __ _ _ __
/ _` | | | | __/ _ \| '__| | '_ \
| (_| | |_| | || (_) ... |
"""
Sponge Knowledge Base
Loading knowledge bases
"""
class Trigger1(Trigger):
def onConfigure(self):
self.withLabel("Trigger1, file3").withEvent("e1")
def onRun(self, event):
#self.logger.debug("file3: Received event {}", event)
global eventCounter
eventCounter.get(self.meta.la... |
import logging
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
from pandas_datareader import data
from pandera import Check, Column, DataFrameSchema, Index, errors
portfolio_schema = DataFrameSchema(
{
"Asset": Column(str, allow_duplicates=False),
"Share": Column(in... |
class ShuidiConstants:
"""
Default constants for shuidi
author: weiwei
date: 20210329
"""
IP = '192.168.10.10' # default ip
PORTS = {"server": 5000}
BUFSIZE = 31001
BUFSIZE = 4096 |
# Time-stamp: <2020-01-02 15:18:16 taoliu>
"""Description: SCKMER anndata cmd
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD License (see the file LICENSE included with
the distribution).
"""
# ------------------------------------
# python modules
# ------------------... |
'''
Created on 2013-2-2
@author: Joseph
'''
from PySide.QtUiTools import QUiLoader
from PySide import QtGui
import sys
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
loader = QUiLoader()
widget = loader.load('untitled.ui')
widget.show()
sys.exit(app.exec_()) |
import matplotlib.pyplot as plt
import numpy as np
import pytest
import pdfstream.integration.tools
import pdfstream.integration.tools as tools
from pdfstream.integration.tools import integrate
def test_bg_sub_error():
with pytest.raises(ValueError):
tools.bg_sub(np.ones((2, 2)), np.zeros((3, 3)))
@pyt... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-05-22 11:53
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... |
# -*- encoding: utf-8 -*-
# @File : binary_saver.py
# @Time : 2021/07/09 19:57:12
# @Author : Ming Ding
# @Contact : dm18@mail.tsinghua.edu.cn
# here put the import lib
import os
import sys
import math
import random
import torch
from tqdm import tqdm
import numpy as np
from .base_saver import BaseSaver
... |
class Observer:
_observers = []
def __init__(self):
self._observers.append(self)
self._observables = {}
def observe(self, event_name, callback):
self._observables[event_name] = callback
@property
def observers(self):
return self._observers
class IOEvent:
def ... |
#!/bin/env python
import argparse
import pathlib
import sys
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server
import falcon
from whitenoise import WhiteNoise
font_end = pathlib.Path(__file__).resolve().parents[1] / 'front_end'
talk = falcon.API()
talk = WhiteNoise(
tal... |
import torch as T
from torch.utils.data import Dataset
import numpy as np
import os
import pickle as pkl
def init_pointcloud_loader(num_points):
Z = np.random.rand(num_points) + 1.
h = np.random.uniform(10., 214., size=(num_points,))
w = np.random.uniform(10., 214., size=(num_points,))
X = (w - 111.5)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
import os.path
import pelican_shiori
AUTHOR = 'Siddhant Goel'
SITENAME = 'pelican-shiori'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Europe/Berlin'
DEFAULT_LANG = 'en'
FEED_ALL_ATOM = 'feeds/all.atom.xml'
FEED_ALL_RSS = 'feeds/... |
from psyneulink import *
m1 = TransferMechanism(input_ports=["InputPort A", "InputPort B"])
m2 = TransferMechanism()
c = Composition()
c.add_node(m1, required_roles=NodeRole.INPUT)
c.add_node(m2, required_roles=NodeRole.INPUT)
c._analyze_graph()
lvoc = OptimizationControlMechanism(agent_rep=RegressionCFA,
... |
from django.contrib.admin import site, ModelAdmin
from serveradmin.access_control.models import AccessControlGroup
class AccessControlGroupAdmin(ModelAdmin):
model = AccessControlGroup
filter_horizontal = ['members', 'applications']
site.register(AccessControlGroup, AccessControlGroupAdmin)
|
from direction import all_directions, DEFAULT_DIRECTION
from gamestate import GameState
from snakes.basesnake import BaseSnake
from snakes.utils import get_next_coord, get_dist, get_opposite_direction, get_directions
import random
class ClaustrophobicSnake(BaseSnake):
"""Goes in the direction that leads to a lar... |
#1
C = float(input("Enter a degree in Celsius:"))
F = (9 / 5) * C + 32
print("%.1f Celsius in %.1f Fahrenhrit"%(C,F))
#2
import math
radius = float(input("请输入半径:"))
length = float(input("请输入高:"))
area = radius * radius * math.pi
volume = area * length
print("面积为%.4f"%area)
print("体积为%.1f"%volume)
#3
... |
from paramiko import RSAKey
from paramiko import SSHClient
from paramiko import AutoAddPolicy
import sys
if len(sys.argv) != 3:
print("ERROR! Incorrect number of arguments")
sys.exit(1)
worker_ip = sys.argv[1]
key_file = sys.argv[2]
key = RSAKey.from_private_key_file(key_file)
client = SSHClient()
client.se... |
import clusto_query
class OperatorType(clusto_query.query.QueryType):
def __new__(mcs, cls, *args, **kwargs):
constructed_class = super(OperatorType, mcs).__new__(mcs, cls, *args, **kwargs)
if getattr(constructed_class, "operator_map", None) is not None and \
getattr(constructed_cl... |
from mdpo.po2md import Po2Md
def test_disabled_entries(tmp_file):
po_content = '''#
msgid ""
msgstr ""
msgid "foo"
msgstr "translated foo"
'''
markdown_content = '''# foo
<!-- mdpo-translator Message for translator -->
<!-- mdpo-context Context -->
<!-- mdpo-disable-next-line -->
this should be in disabled... |
from django.db import models
class Event(models.Model):
event_cod = models.CharField('Codigo Identificacion', max_length=200, unique=True)
event_nom = models.CharField('Nombre del Evento', max_length=200)
event_date_init = models.DateField('Fecha de Inicio', auto_now=False, auto_now_add=False, null=True, b... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from detectron2.structures import Instances, Boxes
from .backbone import EfficientDetWithLoss
class EfficientDetModel(nn.Module):
"""Detectron2 model:
https://github.com/zylo117/Yet-Another-EfficientDet-Pytorch
"""
... |
import srt, re
from timecode import Timecode
from datetime import datetime
from coldtype.time.sequence import Sequence, Clip, ClipTrack
def srt_to_frame(fps, st):
tc = Timecode(fps,
srt.timedelta_to_srt_timestamp(st).replace(",", "."))
return tc.frame_number-86400-21600
class SRT(Sequence):
def _... |
print [1, 2, 3]
print [1, 2, 3] + [4, 5, 6]
print ['Hi!'] * 4
print 3 * [1, 2, 3]
a = ["Hello", 2.00, 4, 4 + 5, 2 * 4.9, "World" * 3]
print a
print a * 3
print a + [" world"]
print a[0]
print a[1]
print a[1:3:1]
print a[1:5:1][1:3:1]
|
from .core import SuggestionBox
__red_end_user_data_statement__ = (
"This cog stores data provided to it by command as needed for operation. "
"As this data is for suggestions to be given from a user to a community, "
"it is not reasonably considered end user data and will "
"not be deleted except as r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.