text stringlengths 1 927k |
|---|
import requests
import json
from datetime import datetime
import time
import pandas as pd
from pandas import DataFrame as df
import hmac
import hashlib
from interval_enum import Interval
from order_enum import Order
class BinanceClient:
def __init__(self, api_key, api_secret):
self.key = api_key
... |
from time import sleep
from umqtt.simple import MQTTClient
from machine import Pin
from dht import DHT22
SERVER = 'ip address' # MQTT Server Address (Change to the IP address of your Pi)
CLIENT_ID = 'ESP32_DHT22_Sensor'
TOPIC = b'temp_humidity'
client = MQTTClient(CLIENT_ID, SERVER)
client.connect() # Connect to M... |
from datetime import datetime as dt
from pathlib import PosixPath
from typing import Any, Dict, List, Tuple, Union
# TODO: uncomment after release (causes flake8 to fail)
# from _echopype_version import version as ECHOPYPE_VERSION
from typing_extensions import Literal
ProcessType = Literal["conversion", "processing"]... |
import os, sys
from rpython.rlib import jit
from rpython.rlib.objectmodel import we_are_translated
from errno import EINTR
AUTO_DEBUG = os.getenv('PYPY_DEBUG')
RECORD_INTERPLEVEL_TRACEBACK = True
class OperationError(Exception):
"""Interpreter-level exception that signals an exception that should be
sent to ... |
# 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 u... |
#-----------------------------------------------------------------------------------
# lexer.py
# Lexer for Java programming language in Python
# Reference: https://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html
#-----------------------------------------------------------------------------------
import ply.lex ... |
import hashlib
import random
import string
import time
from django.core.cache import cache
import requests
from common.config import WECHAT_GET_JSSDK_TICKET_URL, WECHAT_GET_ACCESS_TOKEN_URL
class Signature:
"""
Get Wechat JSSDK signature
"""
def __init__(self,url):
self.ret = {
'n... |
def problem124():
LIMIT = 100000
# Modification of the sieve of Eratosthenes
rads = [0] + [1] * LIMIT
for i in range(2, len(rads)):
if rads[i] == 1:
for j in range(i, len(rads), i):
rads[j] *= i
data = sorted((rad, i) for (i, rad) in enumerate(rads))
return ... |
import matplotlib
matplotlib.use("Agg")
import matplotlib.pylab as plt
from math import ceil
import numpy as np
import argparse
from functools import partial
import os
from keras.models import Model, Sequential
from keras.layers import Input, Dense, Reshape, Flatten
from keras.layers.merge import _Merge
from keras.laye... |
import _plotly_utils.basevalidators
class SubplotsValidator(_plotly_utils.basevalidators.InfoArrayValidator):
def __init__(self, plotly_name="subplots", parent_name="layout.grid", **kwargs):
super(SubplotsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import os
import csv
output_path = os.path.join(".", "output", "new.csv")
with open(output_path, "w", newline="") as csvfile:
csvwriter = csv.writer(csvfile, delimiter=",")
csvwriter.writerow(["First Name", "Last Name", "SSN"])
csvwriter.writerow(["Laura", "Raynes", "555-55-5555"]) |
# Copyright (c) 2021 SUSE LLC
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 3 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; witho... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This module contains a method to load mnist data. Based on David Larson work at:
http://g.sweyla.com/blog/2012/mnist-numpy/a
"""
import numpy
import os, struct
from array import array as pyarray
def load_mnist(dataset="training", digits=numpy.arange(10), path="mnist"):... |
# -*- coding: utf-8 -*-
"""
notification resources utils
-------------
"""
import json
from tests import utils as test_utils
PATH = '/api/v1/notifications/'
EXPECTED_NOTIFICATION_KEYS = {
'guid',
'is_read',
'message_type',
'sender_name',
'sender_guid',
'message_values',
}
EXPECTED_LIST_KEYS = {... |
# -*- coding: utf-8 -*-
"""
========================
Notebook styled examples
========================
The gallery is capable of transforming python files into reStructuredText files
with a notebook structure. For this to be used you need to respect some syntax
rules.
It makes a lot of sense to contrast this output r... |
# 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... |
# coding: utf-8
import pprint
import re
import six
class AccessoryLimitVo:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value i... |
while True:
print("e") |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Helpful routines for regression testing."""
from base64 import b64encode
from binascii import hexlify,... |
"""
This file offers the methods to automatically retrieve the graph Kandleria vitulina.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-... |
class NodeSocketInterfaceIntUnsigned:
default_value = None
max_value = None
min_value = None |
from __future__ import print_function, absolute_import
import unittest, math
import pandas as pd
import numpy as np
from . import *
class T(base_pandas_extensions_tester.BasePandasExtensionsTester):
def test_concat(self):
df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'c_2': ['d', 'e', 'f']})
df.engineer('co... |
from dolfin import *
import math, numpy
__all__ = ["edge_residual_indicator", "poisson_indicator", "zz_indicator",
"pb_indicator", "Estimator", "pb_indicator_GO", "pb_indicator_GO_cheap"]
class Estimator(object):
''' object consisting of pairs (N, f(N)) describing convergence of an error or similar '''... |
class AzureBlobUrlModel(object):
def __init__(self, storage_name, container_name, blob_name):
"""
:param storage_name: (str) Azure storage name
:param container_name: (str) Azure container name
:param blob_name: (str) Azure Blob name
"""
self.storage_name = storage_n... |
"""Default configurations for various items in the test framework.
This module imports the following classes:
:class:`webdriver_test_tools.config.browser.BrowserConfig`
:class:`webdriver_test_tools.config.browser.BrowserStackConfig`
:class:`webdriver_test_tools.config.projectfiles.ProjectFilesConfig`
... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018-2019 CERN.
# Copyright (C) 2018-2019 RERO.
#
# Invenio-Circulation is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Module tests."""
def test_version():
"""Test version import."""
... |
#!/usr/bin/env python
#
# Electrum - lightweight ParkByte client
# Copyright (C) 2015 kyuupichan@gmail
#
# 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 witho... |
# ----------------------------------------------------------------------
# Note:
# - This is the Python code used in Script Manager. ##
# Compatible:
# - Win / Mac
# ... |
"""
Contributors can be viewed at:
http://svn.secondlife.com/svn/linden/projects/2008/pyogp/CONTRIBUTORS.txt
$LicenseInfo:firstyear=2008&license=apachev2$
Copyright 2009, Linden Research, Inc.
Licensed under the Apache License, Version 2.0 (the "License").
You may obtain a copy of the License at:
http://www.apa... |
# HASPR - High-Altitude Solar Power Research
# Script to calculate CO2-equivalent offset given generation profiles
# Version 0.1
# Author: neyring
from os import walk
import haspr
from haspr import Result
from haspr import Dataset
import numpy as np
from numpy import genfromtxt
# PARAMETERS #
# path to .csv file of g... |
#!/usr/bin/env python
from os.path import join, dirname, abspath
from setuptools import setup
def read(rel_path):
here = abspath(dirname(__file__))
with open(join(here, rel_path)) as fp:
return fp.read()
def get_version(rel_path):
for line in read(rel_path).splitlines():
if line.startsw... |
"""
60.36%
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
current = hea... |
from unittest import TestCase
from casbin.util.rwlock import RWLockWrite
from concurrent.futures import ThreadPoolExecutor
import time
import queue
class TestRWLock(TestCase):
def gen_locks(self):
rw_lock = RWLockWrite()
rl = rw_lock.gen_rlock()
wl = rw_lock.gen_wlock()
return (rl,... |
import tvm
@tvm.target.generic_func
def mygeneric(data):
# default generic function
return data + 1
@mygeneric.register(["cuda", "gpu"])
def cuda_func(data):
return data + 2
@mygeneric.register("rocm")
def rocm_func(data):
return data + 3
@mygeneric.register("cpu")
def rocm_func(data):
return da... |
import httplib,json
conn = httplib.HTTPConnection("localhost", 8888)
print "Testing with incorrect token - Expected FAIL"
token="qwertyujm-32ddfd-dfdfm-fgfvv"
streamId="1321-1321"
conn.request("GET", "/log?accessToken="+token+"&streamId="+streamId )
r2 = conn.getresponse()
print 'Response Status: '+str(r2.status)
data ... |
# coding: spec
from photons_canvas.points import helpers as php
import pytest
describe "Color":
it "has ZERO":
assert php.Color.ZERO == (0, 0, 0, 0)
it "has WHITE":
assert php.Color.WHITE == (0, 0, 1, 3500)
it "has EMPTIES":
assert php.Color.EMPTIES == (php.Color.ZERO, None)
... |
for u in range(columns):
# for k in range(rows):
# print(map[u][k], end= "\t")
# print() |
"""
Plots the steady-state force coefficients of an inclined flat-plate with
aspect-ratio 2 at Reynolds number 100 for angles of attack between 0 and 90
degrees.
Compares with experimental results reported in Taira et al. (2007).
_References:_
* Taira, K., Dickson, W. B., Colonius,
T., Dickinson, M. H., & Rowley, C. ... |
import urllib.request
import json
import requests
from data.config import *
def youtube_get_information(channel_id):
api_key = YOUTUBE_API_KEY
base_search_url = "https://www.googleapis.com/youtube/v3/search?"
base_video_link = "https://www.youtube.com/watch?v="
first_url = base_search_url + f"key={api... |
# YOLOv5 YOLO-specific modules
import argparse
import logging
import sys
from copy import deepcopy
sys.path.append('./') # to run '$ python *.py' files in subdirectories
logger = logging.getLogger(__name__)
from models.common import *
from models.experimental import *
from utils.autoanchor import check_anchor_order... |
#import matplotlib
#print(matplotlib.__version__)
import tensorflow as tf
print(tf.__version__) |
import argparse
import numpy as np
import os
import sys
import numpy, scipy, sklearn
from model.trainer import Trainer
from misc.utils import Params
from dataset.kaldi_io import FeatureReader, open_or_fd, read_mat_ark, write_vec_flt
from six.moves import range
parser = argparse.ArgumentParser()
parser.add_argument("-g... |
import os
class Config(object):
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
DEBUG = False
SECRET_KEY = os.environ['SECRET_KEY']
DATABASE_URL = os.environ['DATABASE_URL']
SQLALCHEMY_DATABASE_URI = DATABASE_URL
SQLALCHEMY_TRACK_MODIFICATIONS = True
TROPO_API_KEY_TEXT = os.environ.g... |
# Copyright 2018 The TensorFlow 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
#
# Unless required by applica... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... |
import numpy as np
import matplotlib.pyplot as plt
def plot(base_name):
def get_hist(s):
return s["summary"][0]*s["diplo_hist"]
motif = np.load(base_name + "/limited_summits_alignments_motif_summary.npz")
nonmotif = np.load(base_name + "/limited_summits_alignments_nonmotif_summary.npz")
motif_... |
# Copyright 2015 Cloudbase Solutions Srl
# 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
#
# Unless r... |
"""
练习1:在终端中输入一个疫情确诊人数再录入一个治愈人数,
打印治愈比例
格式:治愈比例为xx%
效果:
请输入确诊人数:500
请 输入治愈人数:495
治愈比例为99.0%
"""
confirmed = int(input("请输入确诊人数:"))
cure = int(input("请输入治愈人数:"))
result = cure / confirmed * 100
print("治愈比例为" + str(result) + "%") |
# Generated by Django 2.1.1 on 2018-11-21 00:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('IoT_MaintOps', '0072_auto_20181115_0423'),
]
operations = [
migrations.AlterModelOptions(
name='equipmentinstancedailyriskscore',
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
#!/usr/bin/env python
import sys
from TimeFileMaker import *
if __name__ == '__main__':
USAGE = 'Usage: %s [--sort-by=auto|absolute|diff] AFTER_FILE_NAME BEFORE_FILE_NAME [OUTPUT_FILE_NAME ..]' % sys.argv[0]
HELP_STRING = r'''Formats timing information from the output of two invocations of `make TIMED=1` into ... |
from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 125359744
"""
"""
random actions, total chaos
"""
board = gamma_new(3, 4, 4, 4)
assert board is... |
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS, cross_origin
import requests
from bs4 import BeautifulSoup as bs
from urllib.request import urlopen as uReq
import pymongo
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST... |
for x in range(65, 70):
for y in range(65, x + 1):
print(chr(x), end="")
print() |
# Copyright 2014-present PlatformIO <contact@platformio.org>
#
# 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 applicabl... |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Learning Eligibility in Clinical Trials Using Neural Networks',
author='John James',
license='BSD-3',
) |
# coding: utf-8
#
"""
Mediator module.
This module puts together other modules to implement the program logic.
"""
from __future__ import absolute_import
# Standard-library imports
from argparse import ArgumentParser
from argparse import ArgumentTypeError
import sys
import traceback
# Local imports
from .func import... |
import cgi
import re
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
try:
from html import unescape
except ImportError:
try:
from html.parser import HTMLParser
except ImportError:
from HTMLParser import HTMLParser
unescape = HTMLParser().unescape
from... |
"""
Base settings to build other settings files upon.
"""
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (tryread/config/settings/base.py - 3 = tryread/)
APPS_DIR = ROOT_DIR.path('tryread')
env = environ.Env()
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False)
if READ_DOT_ENV_FILE:
... |
import numpy as np
import argparse
import cv2 as cv
import subprocess
import time
import os
from support import infer_image, show_image
FLAGS = []
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--model-path',
type=str,
default='./model/',
help='The directory where th... |
"""
Sprawdz czy istnieje permutacja danego slowa bedaca palindromem.
"""
# Wersja 1
def znajdz_permutacje(napis, start, koniec, wynik=[]):
if start >= koniec:
if "".join(napis) not in wynik:
wynik.append("".join(napis))
else:
for i in range(start, koniec):
napis[start... |
from __future__ import print_function
from PIL import Image
import os
import os.path
import numpy as np
import sys
import pickle
import torch
import torch.utils.data as data
from itertools import permutations
class VisionDataset(data.Dataset):
_repr_indent = 4
def __init__(self, root, transforms=None, trans... |
# Copyright 2020 LMNT, Inc. 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
#
# Unless required by applicable law or ag... |
'''
Created on Dec 30, 2010
@author: patnaik
'''
from collections import deque
class Queue(object):
def __init__(self, data = None):
if data:
self.internal_queue = deque(data)
else:
self.internal_queue = deque()
def enqueue(self, value):
self... |
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan... |
# coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
# Copyright (c) 2018, 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 Lice... |
import fileinput
suma = sum(float(num) for num in fileinput.input())
if (suma).is_integer():
print(int(suma))
else:
print(suma) |
from redis import Redis
from config.getconfig import getconfig
def conn():
config = config()
rec = getconfig()["redis"]
self.conn = Redis(host=rec["host"],port=int(rec["port"]),db=int(rec['db']))
return self.conn |
# 1876. Утро сороконожки
# solved
boots = input().split(' ')
left_boots = int(boots[0])
right_boots = int(boots[1])
left_legs = 40
right_legs = 40
result = 0
if right_boots >= left_boots:
result = right_boots*2 + left_legs
else:
result = (right_legs - 1)*2 + left_legs + (left_boots - left_legs)*2 + 1
print(re... |
"Callbacks provides extensibility to the `basic_train` loop. See `train` for examples of custom callbacks."
from .data import *
from .torch_core import *
__all__ = ['Callback', 'CallbackHandler', 'OptimWrapper', 'SmoothenValue', 'Stepper', 'annealing_cos', 'CallbackList',
'annealing_exp', 'annealing_linear'... |
class IceCream:
def __init__(self):
self.scoops = 3
def eat(self, scoops):
self.scoops = self.scoops = scoops
def add(self, scoops): |
#!/usr/bin/env python
"""
main.py -- Udacity conference server-side Python App Engine
HTTP controller handlers for memcache & task queue access
"""
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import mail
from google.appengine.api import memcache
from google.appengine.ext ... |
r"""
Forest Posets
AUTHORS:
- Stefan Grosser (06-2020): initial implementation
"""
# ****************************************************************************
# Copyright (C) 2020 Stefan Grosser <stefan.grosser1@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under t... |
from collections import namedtuple
ConvolutionConfig = namedtuple('ConvolutionConfig', ['n_filters', 'kernel_size', 'stride', 'padding'])
PadConfig = namedtuple('PadConfig', ['padding']) |
# -*- coding: utf-8 -*-
# pylint: disable=no-member
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: BSD
|
This file contains the DAL support for many relational databases, including:
- SQLite & SpatiaLite
- MySQL
- Postgres
- Firebird... |
# coding: utf-8
"""
BillForward REST API
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
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... |
"""A nbformat mock"""
__version__ = "4.2.0" |
"""Training on a GPU cluster.
This will train a small dataset on a distributed GPU cluster.
Test owner: krfricke
Acceptance criteria: Should run through and report final results.
Notes: The test will report output such as this:
```
[05:14:49] WARNING: ../src/gbm/gbtree.cc:350: Loading from a raw memory buffer
on CP... |
import json
import os
from typing import Tuple, List, Callable
from core.folders import folders
class RoadStorage:
def __init__(self, path: str = None):
if path is None:
path='test_driving'
self.folder = str(folders.member_seeds.joinpath(path))
os.makedirs(self.folder, exist_... |
#import dicom # some machines not install pydicom
import scipy.misc
import numpy as np
from sklearn.model_selection import StratifiedKFold
import cPickle
#import matplotlib
#import matplotlib.pyplot as plt
from skimage.filters import threshold_otsu
import os
from os.path import join as join
import csv
import scipy.nd... |
#
# 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 -*-
"""
Created on Mon May 10 21:23:13 2021
@author: Administrator
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../')
from utils import SpiderFormat # noqa: E402
from spider_factory import SpiderFactory # noqa: E402
def test_onnxspider():
spider = S... |
SQLALCHEMY_DATABASE_URI = "postgresql:///test_freight"
LOG_LEVEL = "INFO"
WORKSPACE_ROOT = "/tmp/freight-tests"
SSH_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEArvyc+vZVxUjC5ZcFg1VN3jQOCOjO94gwQKFxlz0zOCrCz+Sq\nnWk28YdUpOU016Zinlh4ZZk2136nCKKTMnNMjd6cTTCn5fWomjR+F2CSdaYYpYfO\nNtVnq0SIDUgGmjyPncOGr... |
import unittest
import os
import shutil
import random
import pickle
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import torch.multiprocessing as mp
import torch.dis... |
from util.inputReader import read_as_strings
LENGTH = 12
def part1(list_of_strings):
one_count = [0] * LENGTH
zero_count = [0] * LENGTH
for string in list_of_strings:
for i, val in enumerate(string):
if val == '0':
zero_count[i] += 1
else:
... |
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Histogram1D(Benchmark):
def setup(self):
self.d = np.linspace(0, 100, 100000)
def time_full_coverage(self):
np.histogram(self.d, 200, (0, 100))
def time_small_coverag... |
import unittest
from clayful.exception import ClayfulException
class ClayfulExceptionTest(unittest.TestCase):
def test_clayful_error_constructor(self):
error = ClayfulException(
'Brand',
'get',
400,
{},
'g-no-model',
'my message',
{}
)
self.assertEqual(error.is_clayful, True)
self.asse... |
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 Intel Corporation
#
# 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 app... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
"""
Collapser
=========
"""
from .optimizer import Optimizer
from .utilities import get_mch_bonds, get_long_bond_ids, get_subunits
import mchammer as mch
class Collapser(Optimizer):
"""
Performs rigid-body collapse of molecules [1]_.
Examples
--------
*Structure Optimization*
Using :class... |
import cv2
# frame per second
cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
while True:
ret,frame = cap.read()
frame[200:250,200:250] = frame[100:150,100:150]
frame[100:150,100:150] = [255,255,255]
cv2.imshow("ilkresim",frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .. import Provider as LoremProvider
class Provider(LoremProvider):
word_list = (
'войти', 'монета', 'вскинуть', 'желание', 'экзамен', 'налоговый',
'вытаскивать', 'приятель', 'вздрагивать', 'куча', 'порт', 'точно',
'заплак... |
import scrapy
from scrapy.loader import ItemLoader
from tiki.items import TiviItem
class TikiSpider(scrapy.Spider):
# crawl from tiki
name = "tiki"
allowed_domains = ["tiki.vn"]
start_urls = {"https://tiki.vn/tivi/c5015"}
def parse(self, response):
tks = response.css('div.product-item')
for tk in tks:
l... |
from v1 import artifact as art1
from v2 import artifact as art2
MY_ARTIFACT = [art1.MyArtifact, art2.MyArtifact] |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, 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 Lic... |
import time
import RPi.GPIO as IO
PIN = 4
IO.setmode(IO.BCM)
IO.setup(PIN, IO.OUT)
IO.output(PIN, IO.HIGH)
time.sleep(15)
IO.output(PIN, IO.LOW)
IO.cleanup() |
from historia.utils.id import unique_id
from historia.utils.color import random_country_colors
from historia.utils.store import Store
from historia.utils.timer import Timer
from historia.utils.trading import position_in_range |
#!/usr/bin/env python3
# Copyright 2017 The Imaging Source Europe GmbH
#
# 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 a... |
"""
This package contains all objects managing Tunneling and Routing Connections..
- KNXIPInterface is the overall managing class.
- GatewayScanner searches for available KNX/IP devices in the local network.
- Routing uses UDP/Multicast to communicate with KNX/IP device.
- Tunnel uses UDP packets and builds a static t... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.