content stringlengths 5 1.05M |
|---|
"""State class for the WS2801 controller."""
import webcolors
from ledpi_controller.const import WHITE_RGB
class State:
"""WS2801 LED Status"""
def __init__(self, state=None):
"""Initialize the state from a present one."""
self.rgb = state.rgb if state is not None else WHITE_RGB
sel... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Unit tests for the msvs.py file. """
import gyp.generator.msvs as msvs
import unittest
try:
from StringIO import StringIO # Python... |
"""
Configuración del admin de Django
"""
from django.contrib import admin
from django.db import connection
from import_export import fields, resources
from import_export.admin import ImportExportModelAdmin
from .models import Aviso, Cuota, Socio
class SocioResource(resources.ModelResource):
"""
Clase para... |
from typing import List
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from discord import Client, Intents
from discord_slash import SlashCommand, SlashContext, SlashCommandOptionType
from .conf import authtoken, dbpath
from .models import Base, Movie
engine = create_engine(f'sqlite:///{dbpa... |
import numpy as np
import warnings
try:
import pyopencl as cl
PYOPENCL_AVAILABLE = True
except ImportError:
PYOPENCL_AVAILABLE = False
warnings.warn("PyOpenCL is not available on this computer. Can't use \
parallel computing. Please install it to move comptutations \
... |
from . import api_reader
|
import time
import traceback
from bot.event_fetcher import EventFetcher
from bot.event_notifier import EventNotifier
INTERVAL_SEC = 60
NOTIFY_BUFFER_SEC = 60 * 5 # 何分前にイベントを通知するか(ただし最大 INTERVAL_SEC 分ずれます)
class Runner:
def __init__(self) -> None:
self._event_fetcher = EventFetcher()
self._event_... |
class GameFinished(Exception):
pass
|
#!/usr/bin/env python
from random import random
from math import sqrt
from progressbar import ProgressBar, Percentage, ETA, Bar
from camera import Camera
from vector3 import Vec3, dot, unit_vector
from ray import Ray
from hitable import Sphere, HitableList, HitRecord
from material import *
def color(ray_, world, dep... |
from pathlib import Path
from time import time
from typing import List, Hashable
class _DirectedAcyclicSequenceGraphNode:
def __init__(self, node_id):
"""
Represents a node in a DASG.
Contains an ID, a flag indicating whether the node is a leaf and a set of children.
:param int nod... |
# -*- coding: utf-8 -*-
"""
Test the multiprocessing pool for the different proposal methods.
"""
from numpy.testing import assert_array_equal
import pytest
from nessai.proposal import (
AnalyticProposal,
AugmentedFlowProposal,
FlowProposal,
RejectionProposal
)
@pytest.mark.parametrize(
'proposal... |
from templates import py
py.define_package(package='startup')
|
# -*- encoding: utf-8 -*-
"""API routes for reviews."""
from flask import jsonify, request
from flask_login import current_user, login_required
from ceraon.api.v1.meals.api import blueprint as meal_api
from ceraon.constants import Errors, Success
from ceraon.errors import BadRequest, Forbidden, NotFound, Precondition... |
""" Encoder approximation by Kernel Ridge Regression
@author: Soufiane Mourragui
This modules train a Kernel Ridge Regression (KRR) on a pair of samples
(x_hat) and embeddings (z_hat) using two possible implementations:
- scikit-learn: deterministic, but limited in memory and time efficiency.
- Falkon: stoch... |
import pytest
@pytest.fixture
def the_raven() -> str:
with open("tests/fixtures/the_raven.txt", "r") as stream:
return stream.read()
|
"""
Chi extension
Print the backbone chi angle for each residue in the structure.
Chi angle is determined by the coordinates of the N, CA, CB (if
available), and CG/OG/SG atoms (if available).
Author: Todd Dolinsky
"""
__date__ = "17 February 2006"
__author__ = "Todd Dolinsky"
import os,sys,insp... |
import torch
import torch.nn as nn
from tqdm import tqdm
#from models import SimpleDecoder, SimpleEncoder, SimpleStyleEncoder
from utils import NUMBER_PERSONS
from losses import standard_style_loss
class ConcatBlock(nn.Module):
def __init__(self, input_size, output_size):
super(ConcatBlock, self).__init__... |
from ._VOCODInputFormatSpecifier import VOCODInputFormatSpecifier
from ._VOCODOutputFormatSpecifier import VOCODOutputFormatSpecifier
|
#!/usr/bin/python
import os
from nbgrader.exchange.abc import (
ExchangeFetchAssignment as ABCExchangeFetchAssignment,
)
from .exchange import Exchange
class ExchangeFetchAssignment(Exchange, ABCExchangeFetchAssignment):
def _load_config(self, cfg, **kwargs):
if 'ExchangeFetch' in cfg:
se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import numpy as np
import matplotlib
matplotlib.use('GTKAgg')
from matplotlib import pyplot as plt
from koheron import connect
from drivers import Spectrum
host = os.getenv('HOST','192.168.1.100')
client = connect(host, name='spectrum')
driver = Spe... |
import os
import sys
import math
from util_tool import *
def generate_files(path):
files = search_directory(path,'voc')
for file_name in files:
generate_file(path,file_name)
def generate_file(path,voc_file):
feature_vector_file = voc_file.replace('voc','vec')
feature_vector_handle = open(feature_vector_file,'w... |
from app import app
import os
#from app.login_manager import require_login
#@app.context_processor
#def injectGlobalData():
#currentUser = require_login()
#lastStaticUpdate = str(max(os.path.getmtime(os.path.join(root_path, f))
# for root_path, dirs, files in os.walk('app/static')
# ... |
from flask import request
from lib import es
import web.util.tools as tools
def get(p):
# load role
role_id = p['nav'][-1]
p['role'] = es.get(p['host'], 'core_nav', 'role', role_id)
if not p['role']:
return tools.alert('not valid role id - {}'.format(role_id))
# delete
es.delete(p['hos... |
import i2c_bus
import unit
hub_addr = [0x40, 0x50, 0x60, 0x70, 0x80, 0xA0]
class Pbhub:
def __init__(self, port, addr=0x61):
self.addr = addr
self.i2c = i2c_bus.easyI2C(port, self.addr)
self._available()
def _available(self):
if self.i2c.available() or self.i2c.available()... |
import conpy, mne # Import required Python modules
# Define source space on average brain, morph to subject
src_avg = mne.setup_source_space('fsaverage', spacing='ico4')
src_sub = mne.morph_source_spaces(src_avg, subject='sub002')
# Discard deep sources
info = mne.io.read_info('sub002-epo.fif') # Read information a... |
import numpy as np
'''
def random_colors(N):
np.random.seed(1)
colors = [tuple(255 * np.random.rand(3)) for _ in range(N)]
return colors
def apply_custom_mask(image, mask, color, mode='inner', alpha=0.5):
for n, c in enumerate(color):
if mode == 'inner':
image[:, :, n] = np.where... |
""" """
# Django
from django.views.generic import View
from django.views.generic import DetailView as BaseDetailView
from django.contrib.admin.utils import flatten
# Mixins
#from hydra.mixins import MultiplePermissionRequiredModelMixin
# Hydra
from .base import get_base_view
from hydra.shortcuts import get_urls_of_si... |
from twocaptcha import TwoCaptcha
from scrapy import Selector
from src.core.request import RequestHandler
from src.core.captcha import CaptchaHandler
from src.core.logging import log
from src.settings import SPIDERS_SETTINGS, CAPTCHA
from src.utils.format import format_cpf
from src.utils.extract import extract_set_coo... |
import argparse
import yaml
import copy
import collections
def matches(item, exclude):
for key, value in exclude.items():
if item[key] != value:
return False
return True
def is_excluded(item, excludes):
for exclude in excludes:
if matches(item, exclude):
return Tr... |
import sys
stack_history = {}
profile_stats_time_excluding_children = {}
profile_stats_time_including_children = {}
profile_stats_calls = {}
timed_function_stack = []
if sys.implementation.name == "micropython":
import utime
def timed_function(f, *args, **kwargs):
myname = str(f).split(' ')[1]
... |
from . import clidriver
if __name__ == "__main__":
clidriver.main()
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2016 Ganael Laplanche, OVH <ganael.laplanche@corp.ovh.com>
#
# 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:/... |
################################################################################
#
# MIT License
#
# Copyright (c) 2018 Advanced Micro Devices, Inc.
#
# 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 S... |
import json
import cv2 as cv
import random
def parse_json_file(file_path, image_shape, label):
ids = []
names = []
bboxs = []
scores = []
with open(file_path, "r") as f:
data = json.load(f)
objs = data["objs"]
for obj in objs:
x = int(obj["bbx"]["x"] * image_shape[1])
... |
#!/usr/bin/env python3
# used to test the script call from clf
import os
import sys
# get environment variables
vars = { v:os.environ.get(v) for v in os.environ if v.startswith("CLF_") }
with open('/tmp/myfile.txt', 'w') as f:
print(sys.argv, file=f)
print(vars, file=f)
try:
assert sys.argv[1:] == ['one'... |
import asyncio
from utils.utilities import call_later
class TimedSet(set):
def __init__(self, iterable=None, loop=None):
if not iterable:
super().__init__()
else:
super().__init__(iterable)
self._loop = loop
self._tasks = []
async def _remove_element(... |
"""
LeetCode Problem: 654. Maximum Binary Tree
Link: https://leetcode.com/problems/maximum-binary-tree/
Language: Python
Written by: Mostofa Adib Shakib
Time Compplexity: O(n^2)
Space Complexity: O(n)
"""
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if not nums:
... |
#coding:utf-8
import tensorflow as tf
from model import ShowAndTell
import keras
import os
import keras.backend as K
import numpy as np
K.set_learning_phase(0)
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("weight_path", "./keras_weight/weights_full.h5", "Weights data path")
tf.app.flags.DEFINE_string(... |
import pickle
import tkinter as tk
from tkinter import filedialog
from sandcraft.config import *
from sandcraft.grid import Grid, px_to_cell
from sandcraft.painter import Painter
from sandcraft.particle_data import *
from sandcraft.particle import Particle
from sandcraft.gas import Gas
def print_state_message(screen,... |
# -*- coding: utf-8 -*-
import requests
import threading
import json
from time import time, sleep
from pprint import pprint
from .rpc_client import RpcClient
#https://core.telegram.org/bots/api
class Api(object):
BOT_WAIT = 1
limit = 10 # кол во сообщий для бота в апдейте
DEL_DELAY = 25 # удаляем сообщени... |
from io import BytesIO
from typing import Any, Dict, Optional, Union
import httpx
from ...client import Client
from ...models.post_user_job_multipart_data import PostUserJobMultipartData
from ...types import File, Response
def _get_kwargs(
*,
client: Client,
multipart_data: PostUserJobMultipartData,
) -... |
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QGridLayout, QLabel, QLineEdit, QToolButton, QPushButton)
from PyQt5.QtCore import Qt
class Login(QWidget):
def __init__(self):
super().__init__()
self.bodyLayout = QGridLayout()
# 欢迎登陆图书馆系统标题
self.titleTe... |
# +
import numpy as np
import torch
class Flake:
def __init__(self):
self.o = [[0, 0, 0]]
pass
@property
def coordination(self):
return len(self.coo)
def _coo(self, o=False):
t = type(self.coo)
if t == list:
coo = self.coo
elif t == np.ndar... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup
from io import open
def readme():
with open('README.rst', encoding='utf-8') as f:
return f.read()
setup(name='pyTelegramBotAPI',
version='3.2.0',
description='Python Telegram bot api. ',
long_description=readme()... |
import sys
from decimal import Decimal
import pytest
import pytest_mock
import yaml
from mock import MagicMock, call
from pathlib import Path
from dhalsim.python2.entities.control import AboveControl, BelowControl, TimeControl
from dhalsim.python2.generic_plc import GenericPLC
@pytest.fixture
def magic_mock_network... |
from collections import deque
import os
class Card():
def __init__(self, inputfile = 'inputPhase1.txt'):
self.infile = open(inputfile,'r')
def __del__(self):
self.infile.close()
def read(self):
temp = self.infile.readline()
return temp if temp!='' else None
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Dictionary of Acquia Cloud API resources."""
import abc
import typing
from acapi2.exceptions import AcquiaCloudNoDataException
from acapi2.resources.acquiadata import AcquiaData
class AcquiaList(AcquiaData, dict):
def __init__(self,
base_uri: st... |
"""A collection of shared utilities for all encoders, not intended for external use."""
from abc import abstractmethod
from enum import Enum, auto
import pandas as pd
import numpy as np
import sklearn.base
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.exceptions import NotFittedError
from typin... |
import typing
import hashlib
from debug import debug_assert
from json_file import json_register_writeable, json_register_readable, json_read, json_write
StringHashMap = typing.Dict[int, str]
PerTypeHashMap = typing.Dict[type, StringHashMap]
unique_hash_map : PerTypeHashMap = {}
def register_unique_hash(hash_code : ... |
"""
Classic task, a kind of walnut for you
Given four lists A, B, C, D of integer values,
compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l]
is zero.
We guarantee, that all A, B, C, D have same length of N where 0 ≤ N ≤ 1000.
"""
from itertools import product
from typing import List
... |
#! /usr/bin/env python
"""Sample script for APDU error checking.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
This file is part of pyscard.
pyscard is free software; you can redistribute it and/or modify
it under the terms of the... |
#!/usr/bin/env python3
# coding: utf-8
#
# Usage:
# Author: viking(auimoviki@gmail.com)
import sys
sys.path.append('.')
import logging
from nce import NceCorpus
logging.basicConfig(level=logging.DEBUG)
batch_size = 32
bptt = 35
num_label = 100
rootdir='./data/ptb/'
corpus = NceCorpus('%s/train.txt'%rootdir, '%... |
from environments import SimulatorKinovaGripper, MultiPointReacher
from visualservoing.state_extractory import StateExtractor
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import MovieWriter, FFMpegWriter
from mpl_toolkits.mplot3d import Axes3D
import torch
import glob
#HELPER FUNCTION... |
import itertools
import typing
import random
from collections import defaultdict
import torch
class ImbalancedDatasetSampler(torch.utils.data.sampler.Sampler):
"""
Artificially samples classes from a multiclass dataset and create an imbalance according
to the specified imbalance ratio (IR = n_first_clas... |
# Lint as: python3
# Copyright 2019, The TensorFlow Federated 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... |
import os
import sys
from dotmap import DotMap
import opto
import opto.data as rdata
from opto.opto.classes.OptTask import OptTask
from opto.opto.classes import StopCriteria, Logs
from opto.utils import bounds
from opto.opto.acq_func import EI, UCB
from opto import regression
import pandas as pd
import numpy as np
im... |
import datetime
import imutils
import time
import sqlite3
import cv2
import os
import logging
# https://www.pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/
# https://www.pyimagesearch.com/2015/06/01/home-surveillance-and-motion-detection-with-the-raspberry-pi-python-and-opencv/... |
##
## This file is maintained by Ansible - CHANGES WILL BE OVERWRITTEN
##
from __future__ import absolute_import
from galaxy.jobs.mapper import JobMappingException
log = logging.getLogger(__name__)
# fix for until we switch to yaml config
log.setLevel(logging.DEBUG)
RESOURCE_KEY = 'small_resource'
RESOURCES = {
... |
from django.urls import path
from .views import NotificationAPIView, SubscribeAPIView, UnSubscribeAPIView
app_name = 'notifications'
urlpatterns = [
path('notifications/', NotificationAPIView.as_view(), name='notification'),
path('notifications/subscribe/', SubscribeAPIView.as_view(), name='subscribe'),
p... |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.response import Response
from rest_framework.test import APIClient
from core.models import User as UserModel
CREATE_USER_URL = reverse('user:create')
ME... |
# Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados de cada pessoa em um dicionário e todos os dicionários em uma lista. No final, mostre:
A) Quantas pessoas foram cadastradas
B) A média de idade
C) Uma lista com as mulheres
D) Uma lista de pessoas com idade acima da média.
|
import inspect
import os
from functools import lru_cache
from os.path import dirname, join
import pycred
@lru_cache(maxsize=1)
def get_pycred_dir():
return dirname(inspect.getfile(pycred))
@lru_cache(maxsize=1)
def get_doc_dir():
path = get_pycred_dir()
if path.startswith('/opt/venvs/pycred'):
... |
import collections
import io
import os
import tempfile
from django.conf import settings
from django.core.files.storage import FileSystemStorage
import sass
from transformfiles.manifest import transformfiles_manifest
class OperationNotAllowed(Exception):
def __init__(self, *args, **kwargs):
self.args = a... |
from django.contrib.sitemaps import Sitemap
from ..models import Category, Question
class FAQCategoriesSitemap(Sitemap):
changefreq = "never"
priority = 0.5
def items(self):
return Category.objects.all()
class FAQQuestionsSitemap(Sitemap):
changefreq = "yearly"
priority = 0.5
... |
from finrl_meta.data_processors.processor_alpaca import AlpacaProcessor
from finrl_meta.data_processors.processor_baostock import BaostockProcessor
from finrl_meta.data_processors.processor_wrds import WrdsProcessor
from finrl_meta.data_processors.processor_binance import BinanceProcessor
from finrl_meta.data_processor... |
import json
from django.core.exceptions import ValidationError
from django.urls import reverse
from rest_framework import serializers
from rest_framework import status
from rest_framework.test import APITestCase
from url_shortener.models import URL
from url_shortener.shortener import ShortURL
def create_url(url):
... |
import pytest
from pytest import fixture, raises
skip = pytest.mark.skip
xfail = pytest.mark.xfail
import random
from dataclasses import dataclass, field, InitVar
from SCE.src import cats, patterns, words
from SCE.src.rules import *
# Mocks
@dataclass
class MockPattern(Pattern):
elements: list = field(init=False... |
import torch
import numpy as np
import trimesh
import os
from trimesh.util import array_to_string
from mesh2tex import geometry
from torchvision.utils import save_image
class Generator3D(object):
def __init__(self, model, device=None):
self.model = model
self.device = device
def generate_ima... |
from os import makedirs
from os.path import dirname
from pathlib import Path
def mkdir(path, *args, exist_ok=True, **kwargs):
makedirs(str(path), *args, exist_ok=exist_ok, **kwargs)
return path
def mkpar(path, *args, **kwargs):
if isinstance(path, Path):
path.parent.mkdir(exist_ok=True, parents=T... |
import unittest
from unittest.mock import Mock
import numpy as np
from lib.network import Network
class NetworkTest(unittest.TestCase):
def setUp(self):
self.network = Network(2, 2)
def test_define_model(self):
self.network.define_model()
self.assertNotEqual(self.network.model, None)
... |
# Copyright 2014
# The Cloudscaling Group, 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... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import orchestra.models.fields
class Migration(migrations.Migration):
dependencies = [
('payments', '0001_initial'),
]
operations = [
migrations.Alte... |
# host need to be public ip of the virtual machine,
# which can be seen by 'ip addr'
HOST_VM = '10.0.2.15'
HOST_GOD = '192.168.1.115'
LOCALHOST = 'localhost'
HOST_1001 = '125.217.226.161'
HOST_SCUT = '202.38.213.72'
PORT_5555 = 5555
PORT_8080 = 8080
PORT_80 = 80
|
# 响应状态码、响应头、响应体
# 1. 发起请求 requests.[method](url) 返回响应对象
# 2. resp.status_code 响应状态码
# resp.headers 响应头
# resp.content 字节码数据
# resp.text 字符串
import requests
resp = requests.get('http://www.baidu.com')
status_code = resp.status_code
print(f'响应状态码:{status_code}')
headers = resp.headers # 字典
print('响应头')
print(head... |
#!/usr/bin/env python
#
# Copyright 2011 Google Inc. All Rights Reserved.
"""Command to create a codebase for a MOE project."""
__author__ = 'dbentley@google.com (Daniel Bentley)'
from google.apputils import app
from google.apputils import appcommands
import gflags as flags
from moe import base
from moe import db_c... |
class Movie():
""" Representation of a movie, designed be used with fresh_tomatoes.py """
def __init__(self, movie_name, movie_poster_image_url, movie_trailer_url):
""" Contructor with the arguments required to use fresh_tomatoes.py """
# Ensure instance variable names are consistent with fresh_tomatoes.py
se... |
import logging
import pickle
from lenskit.algorithms import hpf
import pandas as pd
import numpy as np
from pytest import mark
import lk_test_utils as lktu
try:
import hpfrec
have_hpfrec = True
except ImportError:
have_hpfrec = False
_log = logging.getLogger(__name__)
simple_df = pd.DataFrame({'item'... |
from abc import abstractmethod
import numpy as np
from seizures.prediction.PredictorBase import PredictorBase
from sklearn.ensemble import ExtraTreesClassifier
class XtraTreesPredictor(PredictorBase):
""""
A simple application of RandomForestClassifier
@author: Shaun
"""
def __ini... |
from collections.abc import Iterable, Iterator
class FibonaIterator(Iterator):
def __init__(self, n):
self.__a = 0
self.__b = 1
self.__n = n # 获取多少个
self.__index = 0 # 当前索引
def __next__(self):
if self.__index < self.__n:
self.__index += 1
# 生成... |
import sys
from Python.src.ByteManip import *
from collections import Counter
# "etaoinsrhldcumfpgwybvkxjqz ETAOINSRHLDCUMFPGWYBVKXJQZ.?!1234567890" # standard default
# "etaoin srhldcumfpgwybvkxjqzETAOINSRHLDCUMFPGWYBVKXJQZ0123456789.?!" # higher space & numeral preference
# The frequency string was made a parameter ... |
import unittest
from terminalone import t1types
class TestT1Types(unittest.TestCase):
def test_strpt(self):
date_one = '2016-11-07T09:07:57'
date_two = '2016-11-07T09:07:57+1000'
date_three = '2016-11-07T09:07:57+01:00'
dt_one = t1types.strpt(date_one)
dt_two = t1types.str... |
from .pypi_name_mapping import main as main_pypi_name_mapping
def main(args):
"""Run all the mapping updaters"""
main_pypi_name_mapping(args)
|
from settings import *
import os ,pyautogui
pwdpath=os.getcwd()
if not os.path.exists(f'{pwdpath}/profiles/{person}'):
os.makedirs(f'{pwdpath}/profiles/{person}')
pwdpath=os.getcwd()
import numpy as np
import cv2
from frontal_face import *
cap=cv2.VideoCapture(video_source_number)
cap.set(cv2.CAP_PROP_BUFFERSIZE,1)... |
from abc import ABC, abstractmethod
class Exporter(ABC):
"""
Abstract Exporter to be implemented by exporters with distinct modes (e.g., s3, jbdc)
"""
@abstractmethod
def read_databases(self):
pass
@abstractmethod
def export_datacatalog(self):
pass
@abstractmethod
... |
def find_word(board, word):
# write your code here
if not word: return True
R = len(board)
if not R: return False
C = len(board[0])
visited = [[False] * C for _ in xrange(R)]
def fit(r, c, word, idx):
visited[r][c] = True
if idx == len(word)-1:
# print 'fit', r, c, word, idx
return True
else:
f... |
# Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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... |
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
# views视图就是一个python函数,用来处理网络请求,承上启下的中间人
# views中需要首先在urls中设置路由
from Book.models import BookInfo, PeopleInfo
def test(request):
"""
第一个参数必须是httprequest类型的对象,包含了所有请求信息
并且返回值是一个httpresponse的对象,包含给请求者的相... |
from subprocess import check_output
from records_mover.logging import register_secret
from db_facts.db_facts_types import DBFacts
def lpass_field(name: str, field: str) -> str:
if field == 'notes':
field_arg = '--notes'
elif field == 'username':
field_arg = '--username'
elif field == 'pass... |
from flask import request
from marshmallow import Schema, fields
from urllib.parse import urlencode
from schemas.post import PostSchema
from schemas.dm import DmSchema
from schemas.comment import CommentSchema
class PaginationSchema(Schema):
class Meta:
ordered = True
links = fields.Method(serialize='g... |
# from distutils.core import setup
from setuptools import setup
# read the contents of your README file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name = 'Similarit... |
#!/usr/bin/python
# Copyright 2012 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
#
# Unless required by applic... |
# 实现proxy-crawler
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.executors.pool import ProcessPoolExecutor
from queue import Queue
from core.check import checker
from core.fetch import Fetcher
from handler.config import Config
from handler.logger import Logger
from handler.proxy import... |
# Copyright 2019, Google LLC.
#
# 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... |
#!/usr/bin/python3
# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
import face_recognition
import pickle
import time
import cv2
# Initialize 'currentname' to trigger only when a new person is identified.
currentname = "unknown"
# Determine faces from encodings.pickl... |
import re
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def urlify_external_links(value):
"""
Template will take all URL based text and create a <a></a> html associated with it.
"""
# Regex taken from:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version_info__ = ('2', '0', '0')
__version__ = '.'.join(__version_info__)
|
# flake8: noqa
from . import matplotlib, plotly
from .base import *
|
# coding=utf-8
# Copyright 2019 Google LLC
# 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 ... |
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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/lice... |
# Copyright 2015: Mirantis 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 b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.