content stringlengths 5 1.05M |
|---|
from .model_base import ModelBase
from .xxz import XXZ
from .thirring import Thirring
from .random_heisenberg import RandomHeisenberg, SpectralFoldedRandomHeisenberg
from .dimer_xxz import DimerXXZ
|
import pytest
import tensorflow as tf
from transformer.architecture.attention import MultiHeadAttention
from transformer.architecture.decoder import DecoderBlock, Decoder
from transformer.architecture.feedforward import FeedForward
@pytest.fixture(scope="module")
def decoder_block():
return DecoderBlock(d_model=5... |
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
'''
Settings for ATC_D... |
import unittest
import baloise2homebank
import os
class Baloise2HomebankTest(unittest.TestCase):
out_filename_baloise = "test-output-baloise.csv"
out_filename_cornercard = "test-output-cornercard.csv"
def test_append_to_filename(self):
actual = baloise2homebank.append_to_filename(
"fo... |
__author__ = 'Brenda'
from egat.testset import SequentialTestSet
from webdriver_resource import WebDriverResource
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from egat.execution_groups import execution_group
@execution_group("test6")
class Test6(SequentialTestSet):
d... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@file : __init__.py.py
@Time : 2020/12/3 15:24
@Author: Tao.Xu
@Email : tao.xu2008@outlook.com
"""
def add_order(name):
return {
'ret': 0,
'info': {
'id': 100,
'name': name
}
}
def rename_order(o_id):
return ... |
from xml.etree import ElementTree
from datetime import datetime
import pytz
from corehq.apps.callcenter.indicator_sets import CallCenterIndicators
from corehq.apps.users.models import CommCareUser
from corehq.util.soft_assert import soft_assert
from corehq.util.timezones.conversions import UserTime, ServerTime
from dim... |
#/usr/bin/env python3.4
#
# Copyright (C) 2016 The Android Open Source Project
#
# 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 requir... |
from django.apps import AppConfig
class GlobalvarsConfig(AppConfig):
name = 'globalvars'
|
import os
import s3fs
import pyarrow.parquet as pq
import pandas as pd
import numpy as np
from contextlib import contextmanager
import time
from datetime import timedelta
s3 = s3fs.S3FileSystem()
class TipVars(object):
"""
Features and other variables for the tip prediction task
"""
numeric_feat = [
... |
import json
from robot.libraries.BuiltIn import BuiltIn
import requests
class CustomKeywords:
'''
custom keywords that extend default robot framework and selenium2library's keywords
'''
__version__ = '0.1'
def _make_api_request(self,url,params_list):
"""
make call to given url ... |
import base64
import logging
import os
from contextlib import closing
from io import BytesIO
import pytesseract
import tqdm
from .config import CORPUS_BASEDIR, TESSERACT_BIN
from .utils import mkdir
def pil_to_b64(image):
buffered = BytesIO()
image.save(buffered, format="JPEG")
return base64.b64encode(b... |
import glob
import logging
import os
import random
import cv2
from skimage import io, img_as_float32
from skimage.color import gray2rgb
from sklearn.model_selection import train_test_split
import numpy as np
import tensorflow as tf
from modules_tf.augmentation import AllAugmentationTransform
LOG = logging.getLogger... |
import os
import datetime
import jwt
import requests
from flask import Response
from typing import Optional
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
class SwitcherClient:
"""Switcher Client wraps HTTP request against the Swicther API"""
def __init__(self, api_url:... |
# text outputs still have time stamp, use regex as needed
# removes triplicates
# Convert YouTube subtitles(vtt) to human readable text.
# Download only subtitles from YouTube with youtube-dl:
# youtube-dl --skip-download --convert-subs vtt <video_url>
# To convert all vtt files inside a directory:
# find . -name "*.... |
# Copyright (c) Vera Galstyan Feb 2018
#this loop runs forever
x=1
while x <= 5
print(x)
# we have to add "x += 1" for make it work as we want to |
import os
import pickle
# TODO: make this reusable
from p2p_module.config import dest_server_host, dest_server_port, dest_client_host, dest_client_port, self_client_host, self_client_port, owner_key_file_name, receiver_key_file_name, encryption_file_name, decryption_file_name
from p2p_module.crypto_utils import *
def ... |
#!/usr/bin/env python
###############################################################################
#
# $Id$
#
###############################################################################
# qpid / amqp
import qpid.messaging
import uuid
# enstore imports
import e_errors
# from cache.messaging.messages import MS... |
# Copyright 2016 Autodesk 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 agreed to in writing... |
from utime import * |
platforms = [
[00, 300, 100, 10],
[100, 60, 50, 10],
[100, 100, 50, 10],
[100, 140, 230, 10],
[100, 180, 50, 10],
[130, 300, 200, 10],
[270, 270, 30, 10],
[300, 240, 30, 10],
[340, 200, 30, 10],
[340, 100, 140, 10],
[330, 330, 10, 10],
[330, 370, 30, 10],
[410, 300, 1... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import itertools as it, operator as op, functools as ft
from collections import defaultdict
from contextlib import contextmanager
import sys, inspect, traceback
from . import _pulsectl as c
if sys.version_info.major >= 3:
decodable = bytes
print_err = ... |
""" SungKu Heo, KHU """
# Assign the, Volume, Time length of each sequence, Influent, Controller, etc to 'SBR_model'.
from gym_SBR.envs import buffer_tank2 as buffer_tank
from gym_SBR.envs import SBR_model_batchPID_fbPID as SBR
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.font_manager i... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/core/protobuf/eager_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.proto... |
# EFILTER Forensic Query Language
#
# Copyright 2015 Google 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
#
# Un... |
import ast
from src.upgrade_type_hints.checker import get_future_import_insert_position
import textwrap
import pytest
test_data = [
(
textwrap.dedent(
"""
\"""
A multi-line
doc string
presented
\"""
from typing import List
a: List[int] = ... |
# System
import os
import signal
import random
import multiprocessing as mp
# Third Party
import numpy as np
import scipy.ndimage
import keras.backend as K
import utils as ut
from functools import wraps
def setup_generator(processes=None, batch_size=10, cg=None):
# @wraps(init_worker)
# def init_worker():
... |
from django.core.management.base import BaseCommand
from drf_generator.generator.generator import Generator
class Command(BaseCommand):
help = 'Generates API for database'
def handle(self, *args, **options):
gen = Generator('api')
gen.generate()
|
# число - степень двойки.
i & (i - 1) == 0
# наибольший общий делитель.
def gcd(a, b):
while a:
a, b = b % a, a
return b
def reverse_number(n):
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
return rev
def number_digits_count(n):
length = 0
while n > 0:
... |
# -*- coding: utf-8 -*-
# time: 2019/4/17 下午1:51
from importlib.util import spec_from_file_location, module_from_spec
from pathlib import Path
StatusCode = int
status_codes = {
0: ("SUCC", dict(zh="成功",
en='Success')),
1: ("E_PARAM", dict(zh="参数错误",
en="Parameter e... |
import argparse
import sys
import imageio
from .slitscan import slitscan
def main():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--help', action='help', help='show this help message and exit')
parser.add_argument('--version', action='version', version='%(prog)s 0.3.1')
parser... |
import urllib2
import json
import csv
import time
import datetime
"""
INPUTS:
url: a request url
OUTPUTS:
the data returned by calling that url
"""
def request_data_from_url(url):
req = urllib2.Request(url)
success = False
while success is False:
try:
#open the url
... |
from .custom_driver import client
from .adventures import adventures_thread
from threading import Thread
import platform
import sys
import getopt
from .account import login
import time
from .util_game import close_welcome_screen
from .utils import log, error, warning
from .farming import (
start_farming_thread,
... |
import pandas as pd
import numpy as np
import sqlite3
import matplotlib.pyplot as plt
def get_project_refactor(refactoring_miner):
projects_refactor = {}
for i in refactoring_miner.PROJECT_ID.unique():
aux = {}
for j in refactoring_miner.REFACTORING_TYPE.unique():
faults = len(re... |
#
# Copyright (c) 2018 ISP RAS (http://www.ispras.ru)
# Ivannikov Institute for System Programming of the Russian Academy of Sciences
#
# 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
#
# h... |
# Demo Python String Formatting - Index Numbers
# Also, if you want to refer to the same value more than once, use the index number:
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name)) |
#!/usr/bin/env python
# coding: utf-8
#
# # ETHZ: 227-0966-00L
# # Quantitative Big Imaging
# # February 28, 2019
#
# ## Ground Truth: Building and Augmenting Datasets
#
#
# # Overview
#
# ## Motivation
#
# ## Creating Datasets
# - Famous Datasets
# - Types of Datasets
# - What makes a good dataet?
# - Building your ... |
import pathlib
import os
import subprocess
import logging
CACHE_DIR = pathlib.Path("~/.cache/gitctags").expanduser()
USER_HOME = pathlib.Path.home()
CACHE_DIR.mkdir(parents=True, exist_ok=True)
def find_git(f):
p = pathlib.Path(f)
if not p.exists():
return None
while p != p.parent and p != USER... |
import asyncio
from src.db_analysis_functions import summary_analysis, filter_receipt, filter_status, filter_form
asyncio.get_event_loop().run_until_complete(
summary_analysis(print_results=True, buckets_instead_of_strip=True))
asyncio.get_event_loop().run_until_complete(
summary_analysis(custom_filter=filte... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
"""Handlers for all JSON/REST API routes used by this application."""
######################################################################################
#
# Copyright (c) 2015 Twist Bioscience
#
# File: app/routes/api.py
#
#
#
######################################################################################
i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
markdown 博客模板
【LeetCode】17. Letter Combinations of a Phone Number(Python3)
## Problem
<br>
## Algorithmic thinking
<br>
## Python 3 solution
```py
```
<br>
"""
|
import os
import itertools
from tempfile import mkstemp, TemporaryDirectory as InTemporaryDirectory
import pytest
import numpy as np
import numpy.testing as npt
from scipy.ndimage.measurements import center_of_mass
from fury import shaders
from fury import actor, window
from fury.actor import grid
from fury.decorator... |
import colorsys
import numpy as np
from matplotlib import image
def pca(samples):
"""
:param [in] samples: N-by-M matrix; each row is a M-dimensional sample
NOTE: samples should be normalized: for every dimension, avg = 0 and std = 1
:return (importance, newBases, newCoords)
- importance:... |
from __future__ import print_function
import os
import struct
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from io import BytesIO
CIPHER_BLOCK_CHAIN = AES.MODE_CBC
INIT_VECT_SIZE = 16
DEFAULT_CHUNK_SIZE = 64 * 1024
FILE_LENGTH_FIELD_SIZE = struct.calcsize('Q')
W... |
"""Tests related to the Package object."""
import inspect
import pytest
from dependencies import Injector
from dependencies import Package
from dependencies import this
from dependencies.exceptions import DependencyError
from helpers import CodeCollector
provide_module = CodeCollector()
@provide_module.parametriz... |
from .from_model import SelectFromModel
from .sas import SAS, GroupSAS
from .rfe import RFE, GroupRFE
from .rfe import PermutationRFE, GroupPermutationRFE
from .rfe import ShuffleRFE, GroupShuffleRFE
from .exhaustive import ExhaustiveSelector, GroupExhaustiveSelector
from .genetic import GeneticSelector, GroupGeneticS... |
import pygame
pygame.init()
windowSurface = pygame.display.set_mode([500,400])
music = pygame.mixer.Sound("/Users/chenchaoyang/Desktop/python/Python/Music/Music2.wav")
music.play()
Running = True
while Running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
Running = False
... |
--- docs/conf.py.orig 2019-09-03 16:32:54 UTC
+++ docs/conf.py
@@ -4,7 +4,11 @@ import os
import re
import subprocess
import sys
-from pathlib import Path
+if sys.version_info[0] == 2:
+ from pathlib2 import Path
+else:
+ from pathlib import Path
+sys.path.insert(0, os.path.abspath('../build/lib'))
from vir... |
import datetime
from typing import List
from pytest_cases import fixture
from esque.io.messages import Data
from esque.io.serializers.json import JsonSerializer, JsonSerializerConfig
CET = datetime.timezone(datetime.timedelta(seconds=3600), "CET")
ORIGINAL_TEST_DATA = [
Data(
{
"str_field": ... |
import json
from pandelytics import search
if __name__ == "__main__":
news = search.search("jhu", "Data")
if news:
print(json.dumps(news, indent=4))
|
import os
import asyncio
import logging
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import aiohttp_jinja2
import jinja2
from aiohttp import web
from aiohttp.web_middlewares import normalize_path_middleware
from terial import config
from terial.web import template_funcs, routes
from teri... |
import socket
import logging
import json
import traceback
import importlib
import functools
from . import lib
class Server(object):
def __init__(self, port):
self.connection = None
self.received = ""
self.port = port
# Setup logging.
self.log = logging.getLogger(__name__... |
from boa3.builtin.interop.contract import Contract
from boa3.builtin.type import UInt160
current_height: int = 0
def get_contract(hash: UInt160) -> Contract:
"""
Gets a contract with a given hash
:param hash: a smart contract hash
:type hash: UInt160
:return: a contract
:rtype: Contract
... |
## 2. API Authentication ##
# Create a dictionary of headers containing our Authorization header.
headers = {"Authorization": "token 1f36137fbbe1602f779300dad26e4c1b7fbab631"}
# Make a GET request to the GitHub API with our headers.
# This API endpoint will give us details about Vik Paruchuri.
response = requests.get... |
# -*- coding: utf-8 -*-
"""
Módulo importable
comentarios.ipynb
"""
__author__ = "David Quintanar Pérez"
__credits__ = ["David Quintanar Pérez"]
__version__ = "1.0.0"
if __name__ == "__main__":
print("Hola Mundo!") |
#genbank_utils.py
from Bio import SeqIO
from override import GENE_NAME_OVERRIDE, GENE_PRODUCT_OVERRIDE
# feature tuple indices
LEFT_IDX = 0
RIGHT_IDX = 1
STRAND_IDX = 2
LOCUS_IDX = 3
GENE_IDX = 4
TYPE_IDX = 5
def get_genome_from_genbank(gb_file):
'''
Given a genbank file, return its underlying DNA sequenc... |
from enum import IntEnum
class CustomIntEnum(IntEnum):
@classmethod
def from_value(cls, value: int):
for e in cls:
if e == value:
return e
raise Exception(f"Known {cls.__name__} type: {value}")
class UInt8Enum(CustomIntEnum):
def pack(self) -> bytes:
r... |
import time
from typing import List
from mystic_why.effects.base import PerLedEffect
from mystic_why.core.light import Color, Led
from mystic_why.effects.utils import interpolate_color
class CustomRainbowEffect(PerLedEffect):
def __init__(self, area, color_list: List[Color], interpolation_steps: int = 15, led_co... |
import pathlib
import typing
import datetime
from debug import debug_message, debug_assert
from accounting_objects import Transaction
StringList = typing.List[str]
def check_column_data(column_data : StringList, column_amount : int) :
debug_message(f"{column_data}")
debug_assert(len(column_data) == column_am... |
"""
Copyright: https://github.com/luka1199/geo-heatmap/blob/master/utils.py
"""
import webbrowser
TEXT_BASED_BROWSERS = [webbrowser.GenericBrowser, webbrowser.Elinks]
def isTextBasedBrowser(browser):
"""Returns if browser is a text-based browser.
Arguments:
browser {webbrowser.BaseBrowser} -- A ... |
from .users import UsersListResource # NOQA
from .users import UserResource # NOQA
from .followers import FollowersListResource # NOQA
from .repos import ReposListResource # NOQA
from .repos import RepoResource # NOQA
|
import math
import numpy as np
RADIUS = 6371009 # in meters
def get_centroid(points):
xy = np.asarray(points)
xy = np.radians(xy)
lon, lat = xy[:, 0], xy[:, 1]
avg_x = np.sum(np.cos(lat) * np.cos(lon)) / xy.shape[0]
avg_y = np.sum(np.cos(lat) * np.sin(lon)) / xy.shape[0]
avg_z = np.sum(np.si... |
"""Pavilion Test configurations, like the base Pavilion configuration,
utilize the YamlConfig library to define the config structure. Because of the
dynamic nature of test configs, there are a few extra complications this module
handles that are documented below.
"""
from collections import OrderedDict
import re
impor... |
#!/usr/bin/env python3
"""
prints the dwarfdump runtime from the data in ALLdd.
Not normally used, but useful to find out
which instances have larger amounts of time
spent in dwarfdump.
"""
import sys
import os
import datetime
def isdateitem(rec):
if rec.startswith("=====START"):
return "st"
if rec.s... |
N = int(input())
flag = False
for i in range(1, 10):
if N//i <= 9 and N%i == 0:
flag = True
if flag:
print("Yes")
else:
print("No") |
import os
import sys
import time
from cleanflow.preprocessing import *
from cleanflow.exploratory import Outlier
from pyspark.sql import SparkSession
from pyspark.sql import SQLContext
from pyspark import SparkContext
sc = SparkContext.getOrCreate()
sqlContext = SQLContext(sc)
starttime = time.time()
clusterType = s... |
from __future__ import annotations
from typing import List
import O365.address_book as address_book
from ..attribute import Attribute, NonFilterableAttribute
from ..query import Query, BulkAction, BulkActionContext
from ..outlook.message import Message, FluentMessage
class Contact(address_book.Contact):
"""A c... |
from __future__ import absolute_import, division, print_function
from qtpy import QtCore
from qtpy import PYQT5
from glue.icons.qt import get_icon
from glue.utils import nonpartial
from glue.viewers.common.qt.tool import CheckableTool, Tool
from glue.viewers.common.qt.mouse_mode import MouseMode
from glue.viewers.com... |
#!/usr/bin/env python3
"""Copyright 2020 Anna Eilering."""
from distutils.core import setup
setup(
name='mazes',
version='0.0.3',
author='Anna Eilering',
author_email='nahkki@gmail.com',
url='https://github.com/ananci/programming_mazes_python',
license='LICENSE',
description='Implementation of mazes co... |
#! /usr/bin/env python3
import glob, os, subprocess, sys
sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..')))
import script.common as common
def main():
common.pushd(os.path.join(os.path.dirname(__file__), os.pardir))
classpath = [
common.fetch_maven('org.projectlombok', 'lo... |
def getHistoricalTerminologyDict():
history_terminology = {
"Stone Age": [
"Stone Age",
"prehistoric",
"cave paintings",
"Paleolithic",
"Mesolithis",
"Neolithic",
"stone",
"Old Stone",
"Middle Stone Age",
"New Stone Age",
... |
from utils import prime
from time import time
from functools import lru_cache
lim = 10**7
start = ['3', '7', '109', '673']
@lru_cache(maxsize=2000000)
def check_prime(x):
y = int(x**0.5) + 1
for j in primes:
if j > y:
return True
if x % j == 0:
return False
retur... |
from hackathon.scrapers.base import BaseScraper
class BatuScraper(BaseScraper):
def __init__(self, host_regex):
BaseScraper.__init__(self)
self.__regex = host_regex
def get_good_query_in(self):
return self.__regex + ' AND "finished work item" | "kafka" as ip | count by ip, _sourceHost'... |
from dataclasses import dataclass
from unittest import TestCase
from labby.experiment import (
BaseInputParameters,
BaseOutputData,
Experiment,
)
from labby.experiment.sequence import ExperimentSequence
@dataclass(frozen=True)
class OutputData(BaseOutputData):
pass
@dataclass(frozen=True)
class Inp... |
from FeatureCloud.api.imp.test import helper
from FeatureCloud.api.imp.test.api import controller
from FeatureCloud.api.imp.exceptions import ControllerOffline, FCException
def help():
return (None, """For registering and testing your apps or using other apps, please visit
our
websit... |
# Write your solution here
str = input("Please type in a string: ")
times = int(input("Please type in an amount: "))
print(str * times) |
from . import Commands
from .Error import Error
from .Parse import Parse
def Run(Input):
Output = ''
# parse input into commands
cmds = Parse(Input)
# run every command
for cmd in cmds:
# if the command isnt just ""
if cmd[0]:
try:
Func... |
import argparse
import os
import subprocess
import SimpleITK as sitk
import numpy as np
from nipype.interfaces.ants import N4BiasFieldCorrection
from natsort import natsorted
def ReadImage(file_path):
''' This code returns the numpy nd array for a MR image at path'''
return sitk.GetArrayFromImage(sitk.ReadI... |
# -*- coding: utf-8 -*-
"""Code to sync data from the local SQLite3 DB to the server."""
__author__ = 'Oriol Lanuza Fisas'
__email__ = 'oriol@lanuza.eu'
__copyright__ = 'Copyright © 2017, Oriol Lanuza Fisas'
__license__ = 'UPC'
from glucometerutils import exceptions
from glucometerutils.db_support import db_log
from ... |
from __future__ import print_function
import os.path
import sys
import base64
from jupyter_core.paths import jupyter_data_dir
from notebook.services.config import ConfigManager
cm = ConfigManager()
try:
from urllib.request import urlopen # Py3
from urllib.parse import urljoin
except ImportError:
from urll... |
#!/usr/bin/env python
from setuptools import setup, find_packages, Extension
_blinkt = Extension(
'_blinkt',
include_dirs=['lib'],
libraries=['bcm2835'],
sources=['lib/blinkt.c','blinkt_wrap.c']
)
setup(
name = 'blinkt_c',
version = '0.0.1',
author = "Philip Howard",
author_email = "phil@pimoroni.com",
url ... |
# M Tafaquh Fiddin Al Islami 2020
# TieF AI Tafaquh Fiddin Al Islami Library
# Author: M Tafaquh Fiddin Al Islami
#
# License: MIT
from distutils.core import setup
import setuptools
setup(
name = 'tief', # How you named your package folder (MyLib)
packages = setuptools.find_packages(), # Chose the same... |
def add_me_to_the_queue(express_queue, normal_queue, ticket_type, person_name):
"""
:param express_queue: list - names in the Fast-track queue.
:param normal_queue: list - names in the normal queue.
:param ticket_type: int - type of ticket. 1 = express, 0 = normal.
:param person_name: str - name ... |
########################################################
# DO NOT EDIT THE CODE IN THE SECTION BELOW
########################################################
import sys
numbers = sys.argv[1:]
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
########################################################
# Enter ... |
from syned.beamline.optical_elements.ideal_elements.lens import IdealLens
from wofrysrw.beamline.optical_elements.srw_optical_element import SRWOpticalElement
from vinyl_srw.srwlib import SRWLOptL
class SRWIdealLens(IdealLens, SRWOpticalElement):
def __init__(self,
name="Undefined",
... |
from abc import ABC, abstractmethod
import inspect
from protosc.utils import get_new_level, sig_to_param, Settings
class Pipeline(ABC):
def __init__(self, *pipe_elements):
self._elements = []
for arg in pipe_elements:
if isinstance(arg, BasePipeElement):
self._elements... |
from __future__ import absolute_import, unicode_literals
from django.apps import apps
from django.db.models.signals import m2m_changed, pre_delete
from django.utils.translation import ugettext_lazy as _
from acls import ModelPermission
from acls.links import link_acl_list
from acls.permissions import permission_acl_e... |
from rlcard.utils.logger import Logger
from rlcard.utils import seeding
from rlcard.utils.utils import *
|
# Copyright (c) 2021 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
#
# Unless required by appli... |
"""Display a status bar in each file tab."""
import tkinter
from tkinter import ttk
from porcupine import get_tab_manager, tabs, textwidget, utils
class StatusBar(ttk.Frame):
def __init__(self, tab: tabs.FileTab):
super().__init__(tab.bottom_frame)
self.tab = tab
self.left_label = ttk.Lab... |
import cv2
import pytesseract
pytesseract.pytesseract.tesseract_cmd = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe"
camera = cv2.VideoCapture(1)
nPlateCascade = cv2.CascadeClassifier("cascade classifiers/haarcascade_russian_plate_number.xml")
input_image = './num_plate.jpeg'
def capture_image(src=None):
"""... |
def reshape_y(y):
y = y.reshape(y.shape[0],y.shape[1])
return y |
# coding: utf-8
import unittest
from pysqlbuilder import Table, Query, Rollup, functions as fn, RollupException
__author__ = "Timothy Heys"
__email__ = "theys@kayak.com"
class RollupTests(unittest.TestCase):
table = Table('abc')
def test_mysql_one_groupby(self):
q = Query.from_(self.table).select(
... |
import pytest
from collections import OrderedDict
from jina import Document, DocumentArray, Executor, Flow, Client, requests
from docarray.array.chunk import ChunkArray
class DummyExecutor(Executor):
def __init__(self, mode=None, *args, **kwargs):
super().__init__(*args, **kwargs)
if mode:
... |
from energyquantified import EnergyQuantified
from energyquantified.time import today, Resolution, Frequency, CET
# Initialize client (replace with your API key)
eq = EnergyQuantified(api_key="aaaaaa-bbbbbb-cccccc-ddddddd")
# Curve alternative #1: The curve name for the German wind
# production actuals
curve_name = ... |
#!/usr/bin/env python
"""
docstring
"""
import numpy as np
from keras import Input
from keras.engine import Model
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras import optimizers
from keras.preprocessing.image import I... |
# coding : utf-8
from __future__ import print_function, absolute_import, division, unicode_literals
import sys, logging
import numpy as np
from resfgb.models import ResFGB, LogReg, SVM, get_hyperparams
from scripts import sample_data
dataset = sys.argv[1]
logging.basicConfig( format='%(message)s', level=logging.INFO ... |
from flask import Flask, jsonify
from time import sleep
import requests
import threading
import os
from looper import Looper
app = Flask(__name__)
# instantiate looper object and start background processing
# add this crazy hack, otherwise it will be called twice:
if (app.debug and os.environ.get('WERKZEUG_RUN_MAIN')... |
#coding=utf-8
#author 喻碧城(ybc_123@qq.com)
#svm 特征拼接方法
#env python2.7 numpy1.16.5 opencv4.1.2.30 不用严格遵循这个版本 用别的python版本和包版本,请自行修改差异出
#要更改核函数以及参数请自行更改代码 如果需要加入新的特征提取方法,请保证函数输入为图像输出为定长numpy向量
import cv2
import numpy as np
import random
import os
import sys
#图片resize的目标大小
size = (36,36)
#svm保存文件和读取的文件名
svm_data_name = "sv... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.