text stringlengths 1 927k |
|---|
#
# Copyright (c) 2021 Citrix Systems, 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... |
from __future__ import unicode_literals
import datetime
import os
import subprocess
from django.utils.lru_cache import lru_cache
def get_version(version=None):
"Returns a PEP 386-compliant version number from VERSION."
version = get_complete_version(version)
# Now build the two parts of the version num... |
"""
Write a Python program to check whether two given lines are parallel or not.
Note: Parallel lines are two or more lines that never intersect. Parallel Lines are like railroad tracks that never intersect.
The General Form of the equation of a straight line is: ax + by = c
The said straight line is represented in a l... |
# -*- coding: utf-8 -*-
import os
import fnmatch
import re
import codecs
import logging
import json
from pyquery import PyQuery
log = logging.getLogger(__name__)
def process_mkdocs_json(version, build_dir=True):
if build_dir:
full_path = version.project.full_json_path(version.slug)
else:
fu... |
# Copyright 2019 The FastEstimator 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 appl... |
from unittest import TestCase
class TestNew(TestCase):
pass |
from __future__ import division
import logging
from nanpy.i2c import I2C_Master
from nanpy.memo import memoized
import time
log = logging.getLogger(__name__)
def to_s16(n):
return (n + 2 ** 15) % 2 ** 16 - 2 ** 15
class Bmp180(object):
"""Control of BMP180 Digital pressure sensor (I2C)
calculation i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2014-2020 by Paweł Tomulik <ptomulik@meil.pw.edu.pl>
#
# 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, in... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: volume.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.protobuf impo... |
import functools
from spaceone.api.core.v1 import tag_pb2
from spaceone.api.identity.v1 import project_group_pb2
from spaceone.core.pygrpc.message_type import *
from spaceone.identity.model.project_model import Project
from spaceone.identity.model.project_group_model import ProjectGroup
from spaceone.identity.info.role... |
"""
Tests of create functions
"""
from django.test import TestCase
from evennia.utils.test_resources import EvenniaTest
from evennia.scripts.scripts import DefaultScript
from evennia.utils import create
class TestCreateScript(EvenniaTest):
def test_create_script(self):
class TestScriptA(DefaultScript):
... |
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='tracardi-zapier-webhook',
version='0.6.0.1',
description='This plugin calls zapier webhook.',
long_description=long_description,
long_description_content_type="text/markdown",
author='... |
from django.core.management.base import BaseCommand
from app.models import Player, PlayerRole, Spectator, Moderator, most_recent_game
class Command(BaseCommand):
help = 'Prints a list of all zombie emails'
def handle(self, *args, **options):
game = most_recent_game()
spectators = Spectator.o... |
import os
from conans import ConanFile, CMake, tools
class DecoTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake", "cmake_find_package_multi"
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def test(self):
... |
#!/usr/bin/env python
# This program is optimized for Python 2.7.
import socket
def get_remote_machine_info():
remote_host = 'www.python.org'
try:
print "IP address of %s: %s" %(remote_host,socket.gethostbyname(remote_host))
except socket.error, err_msg:
print "%s: %s" %(remote_host, err_ms... |
"""
DynamoDB操作用基底モジュール
"""
import boto3
from boto3.dynamodb.conditions import Key
import logging
from datetime import (datetime, timedelta)
# ログ出力の設定
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class DynamoDB:
"""DynamoDB操作用基底クラス"""
__slots__ = ['_db', '_table_name']
def __init__(self, t... |
import warnings
import numpy as np
import pandas as pd
from collections import Counter
from sklearn.datasets import make_classification
from sklearn.utils import check_X_y
from sklearn.utils import Bunch
from sklearn.preprocessing import LabelEncoder
from imblearn.under_sampling.prototype_selection import RandomUnder... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
from yacs.config import CfgNode as CN
# -----------------------------------------------------------------------------
# Convention about Training / Test specific parameters
# ------------------------------------------------------------... |
"""
#Trains a ResNet on the CIFAR10 dataset.
"""
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRa... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-03 06:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0013_auto_20160903_0624'),
]
operations = [
migrations.AlterField(
... |
#!/usr/bin/env python
#===========================================================================
#
# Plot Ray details for KDP analysis
#
#===========================================================================
import os
import sys
import subprocess
from optparse import OptionParser
import numpy as np
import mat... |
import subprocess, os, glob, GlobalUtils, InstallUtil, Platform
from JsonUtil import *
from menu import cmenu
yes = set(["yes", "y"])
home = os.getenv("HOME")
JSON_LOCATION = home + "/.instpakg"
DEFAULT_JSON = JSON_LOCATION + "/DEFAULT.json"
jsonInstall = ""
markedInstall = []
markedRepo = []
markedCommand = []
def i... |
"""Adapter to wrap the rachiopy api for home assistant."""
import logging
from typing import Optional
from homeassistant.const import EVENT_HOMEASSISTANT_STOP, HTTP_OK
from .const import (
KEY_DEVICES,
KEY_ENABLED,
KEY_EXTERNAL_ID,
KEY_FLEX_SCHEDULES,
KEY_ID,
KEY_MAC_ADDRESS,
KEY_MODEL,
... |
from tweet_handler import Tweet, POI
import paras
from random import *
from time import time, ctime
from collections import defaultdict
import numpy as np
from sys import platform
import multiprocessing
from multiprocessing import *
from functools import partial
import cPickle as pickle
class IO:
def __init__(self... |
import sys
from src.Exchange import Exchange
if __name__ == "__main__":
exchange = None
if len(sys.argv) == 2:
if sys.argv[1] == "debug":
# Exchange outputs using debug mode.
exchange = Exchange(debug="dump")
elif sys.argv[1] == "none":
# Exchange won't outp... |
#!/usr/bin/env python3
from templates import login_page
print(login_page()) |
(lambda __print, __g, __y: [[[[[(lambda __after: (sys.stdout.write('Tell me the flag and I will let you know if you are right: '), [(lambda __after: (__print('WRONG'), (exit(0), __after())[1])[1] if (len(pw) != 19) else __after())(lambda: [(lambda __after: (__print('WRONG1'), (exit(0), __after())[1])[1] if (int(('0x' +... |
"""
Provides logging utilities.
"""
import argparse
import difflib
import os
from dataclasses import dataclass
import sys
from types import TracebackType
from typing import Any, Optional, Type, cast
import fora
@dataclass
class State:
"""Global state for logging."""
indentation_level: int = 0
"""The cur... |
from .buyback_auth import CashBuybackAuthorizations, ShareBuybackAuthorizations
from .earnings import EarningsCalendar
from .equity_pricing import USEquityPricing
from .dataset import DataSet, Column, BoundColumn
__all__ = [
'BoundColumn',
'CashBuybackAuthorizations',
'Column',
'DataSet',
'Earnings... |
import asyncio
import aiohttp
import async_timeout
import atexit
import re
import json
from .. import exception
from ..api import _methodurl, _which_pool, _fileurl, _guess_filename
_loop = asyncio.get_event_loop()
_pools = {
'default': aiohttp.ClientSession(
connector=aiohttp.TCPConnector(limit=10),
... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=unused-wildcard-import
# pylint: disable=wildcard-import
from devil.android.sdk.dexdump import * |
from django.contrib.admin import ModelAdmin, register
from pypro.videos.models import Video
@register(Video)
class VideoAdmin(ModelAdmin):
list_display = ('titulo', 'slug', 'creation', 'vimeo_id')
ordering = ('creation',)
prepopulated_fields = {'slug': ('titulo',)} |
# Copyright (c) 2001-2005 Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.trial import unittest
from twisted.words.xish import xmlstream
class XmlStreamTest(unittest.TestCase):
def setUp(self):
self.errorOccurred = False
self.streamStarted = False
self.streamEnded = Fa... |
# MIT License
#
# Copyright (c) 2018 Haoxintong
#
# 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, p... |
import torch
from .eval_reid import eval_func
def euclidean_dist(x, y):
m, n = x.size(0), y.size(0)
xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n)
yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t()
dist = xx + yy
dist.addmm_(1, -2, x, y.t())
dist = dist.clamp(min=1e-12).sqrt()... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
from decimal import Decimal
from typing import Any, Iterable, List, Mapping, MutableMapping
class DataTypeEnforcer:
"""
Transform class was implemented according to issue #4841
Shopify API returns price fields as a string and it should be conve... |
# -*- coding: utf-8 -*-
"""
melenium
~~~~~~~~
Routine automation.
"""
#----------------------------------------------------------------------------- |
# -*- coding: utf-8 -*-
"""
Example controller for SSE (server-side events) with gevent.
Builds on the simple SSE controller.
"""
import sys
import time
import gevent.queue
from tg import expose, request, response
from tg import url
from tg.decorators import with_trailing_slash
from eventstream import EventstreamCo... |
## imports
import os, time
import numpy as np
import matplotlib.pyplot as plt
# package imports
from . import utilities
def scoringErrors( coco_analyze, oks, imgs_info, saveDir ):
loc_dir = saveDir + '/scoring_errors'
if not os.path.exists(loc_dir):
os.makedirs(loc_dir)
f = open('%s/std_out.txt'%... |
import distutils.ccompiler
import os
import random
import subprocess
"""
These classes allow a test to see if source code with the C compiler actually
compiles.
"""
DEFAULT_COMPILER = distutils.ccompiler.get_default_compiler()
C_EXTENSION = ".c"
def create_file_with_rand_name(source):
cur_dir = os.getcwd()
... |
#!/usr/bin/env python3
# Copyright (c) 2010 ArtForz -- public domain half-a-node
# Copyright (c) 2012 Jeff Garzik
# Copyright (c) 2010-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.
"""Bitcoin test... |
import networkx as nx
class VivadoCell(object):
def __init__(self, id, name, refType, pins, netStr, drivepinStr):
self.id = id
self.name = name
self.refType = refType
self.pins = pins
self.netStr = netStr
self.drivepinStr = drivepinStr
self.drivepins_fromOth... |
## for this one, change the order between relu and batch
import tensorflow as tf
import numpy as np
from io_Cosmo import *
import hyper_parameters_Cosmo as hp
import time
from numpy import linalg as LA
def weight_variable(shape,name):
W = tf.get_variable(name,shape=shape, initializer=tf.contrib.layers.xavier_initia... |
from faker_e164.providers import E164Provider
import factory
from apps.twilio_integration.models import PhoneNumber, ReceivedMessage
from apps.users.tests.factories import UserFactory
faker = factory.Faker._get_faker()
faker.add_provider(E164Provider)
class PhoneNumberFactory(factory.DjangoModelFactory):
class ... |
# base16-qutebrowser (https://github.com/theova/base16-qutebrowser)
# Base16 qutebrowser template by theova and Daniel Mulford
# Black Metal (Burzum) scheme by metalelf0 (https://github.com/metalelf0)
base00 = "#000000"
base01 = "#121212"
base02 = "#222222"
base03 = "#333333"
base04 = "#999999"
base05 = "#c1c1c1"
base... |
__version__ = "2.1.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
import os
PHOTOLOGUE_APP_DIR = os.path.dirname(os.path.abspath(__file__)) |
'''
Tests for intuition.core.configuration
'''
import unittest
from nose.tools import raises
import dna.test_utils as test_utils
import pandas as pd
import intuition.core.configuration as configuration
from dna.errors import DynamicImportFailed
from intuition.errors import InvalidConfiguration
class ConfigurationUti... |
# -*- coding: utf-8 -*-
#
# author: oldj
# blog: http://oldj.net
# email: oldj.wu@gmail.com
#
def get_max_size(data):
max_w = 0
max_h = 0
for hit in data:
w = hit[0]
h = hit[1]
if w > max_w:
max_w = w
if h > max_h:
max_h = h
return max_w + 1, m... |
import io
import json
import warnings
from typing import (
Any,
AsyncIterator,
BinaryIO,
Dict,
List,
Mapping,
MutableMapping,
Optional,
Union,
overload,
)
from typing_extensions import Literal
from .jsonstream import json_stream_list, json_stream_stream
from .utils import clean... |
import base64
import hashlib
def encode_base64(input: bytes, charset: str = "utf-8") -> str:
file_bytes = base64.encodebytes(input)
return str(file_bytes, charset)
def calculate_md5(input: bytes) -> str:
return hashlib.md5(input).hexdigest() |
# -*- coding: utf-8 -*-
"""This code is a part of Hydra Toolkit
.. module:: hydratk.translation.lib.network.rpc.client.en.messages
:platform: Unix
:synopsis: English language translation for RPC client messages
.. moduleauthor:: Petr Rašek <bowman@hydratk.org>
"""
language = {
'name': 'English',
'ISO-... |
import torch
import torch.nn as nn
from torch.nn.init import kaiming_normal_
from models import model_utils
class FeatExtractor(nn.Module):
def __init__(self, batchNorm=False, c_in=3, other={}):
super(FeatExtractor, self).__init__()
self.other = other
self.conv1 = model_utils.conv(batchNorm... |
"""Generate langauge specific loaders for a particular SALAD schema."""
import sys
from io import TextIOWrapper
from typing import (
Any,
Dict,
List,
MutableMapping,
MutableSequence,
Optional,
TextIO,
Union,
)
from . import schema
from .codegen_base import CodeGenBase
from .exceptions i... |
SWX ADVISORY
STATUS: TEST
DTG: 20200625/1605Z
SWXC: SWPC
ADVISORY NR: 2020/29
NR RPLC: 2020/28
SWX EFFECT: GNSS MOD
OBS SWX: 25/1605Z HNH HSH E180 - W180
FCST SWX +0 HR: 25/2300Z NO SWX EXP
FCST SWX +15 HR: 26/0500Z NO SWX EXP
FCST SWX +12 HR: 26/1100Z... |
import subprocess as sp
def run(cmd, output=None, stdout=None, status=None):
result = sp.run(
cmd,
stdout = sp.PIPE,
stderr = sp.PIPE,
universal_newlines = True # result byte sequence -> string
)
if status:
return result.returncode
elif result.returncode != 0:
... |
"""mytestsite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.basic
~~~~~~~~~~~~~~~~~~~~~
Lexers for BASIC like languages (other than VB.net).
:copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from testflows._core.contrib.pygments.lexer import... |
from onnx_tf.handlers.frontend_handler import FrontendHandler
from onnx_tf.handlers.handler import onnx_op
from onnx_tf.handlers.handler import tf_op
from .math_mixin import ReductionMixin
@onnx_op("ReduceSum")
@tf_op("Sum")
class ReduceSum(ReductionMixin, FrontendHandler):
@classmethod
def version_1(cls, node, ... |
import unittest
from exprail.classifier import Classifier
from exprail.grammar import Grammar
from exprail.parser import Parser
from exprail.source import SourceString
class WsClassifier(Classifier):
"""Classify alphabetic characters and whitespaces"""
@staticmethod
def is_in_class(token_class, token):
... |
#
# Copyright 2020-2021 Lars Pastewka
# 2020-2021 Antoine Sanner
#
# ### MIT license
#
# 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 limitat... |
#!/usr/bin/python
#
# Copyright 2013 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 b... |
from typing import List, Dict, Callable
from datetime import datetime
from recognizers_text.utilities import RegExpUtility
from ..utilities import DateUtils
from ..base_holiday import BaseHolidayParserConfiguration
from ...resources.french_date_time import FrenchDateTime
class FrenchHolidayParserConfiguration(BaseHo... |
from pid import PID
from lowpass import LowPassFilter
from yaw_controller import YawController
import rospy
GAS_DENSITY = 2.858
ONE_MPH = 0.44704
class Controller(object):
def __init__(self, vehicle_mass, fuel_capacity, brake_deadband, decel_limit,
accel_limit, wheel_radius, wheel_base, steer_ra... |
import psycopg2
import psycopg2.extras
import pandas as pd
import os
import time
from pathlib import Path
from dotenv import load_dotenv
def read_only_connect_aws():
env_path = 'env_readonly.env'
load_dotenv(dotenv_path=env_path)
host = "bikeshare-restored.cs9te7lm3pt2.us-east-1.rds.amazonaws.com"
por... |
import pytest
from docker.errors import APIError
from requests.exceptions import ConnectionError
from compose.cli import errors
from compose.cli.errors import handle_connection_errors
from compose.const import IS_WINDOWS_PLATFORM
from tests import mock
@pytest.yield_fixture
def mock_logging():
with mock.patch('c... |
from speedtest import Speedtest
# debugmode
debugmode = 0
st = Speedtest()
# debug
if debugmode:
print(f'Download: {st.download()}')
print(f'Upload: {st.upload()}')
st.get_best_server([])
print(f'Ping: {st.results.ping}')
# functons
def get_upload_speed():
print('UPLOAD SPEED: Wait a few seconds... |
# Aula 19 Dicionarios. É assim que tratamos os dicionarios
pessoas = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22}
print(pessoas['nome'])
print(pessoas['idade'])
print(pessoas['sexo'])
print(f'{pessoas["nome"]} tem {pessoas["idade"]} anos') # Utilizar aspas duplas para a localização [" "]
print(pessoas.keys()) ... |
from django.test import TestCase
# Create your tests here. |
#!/usr/bin/env python
import rospy
import sys
import socket
import struct
from time import sleep
from threading import Thread
from nav_msgs.msg import Odometry
from tf.broadcaster import TransformBroadcaster
from robucar_driver.msg import SimpleRobotData
__author__ = "Ilyas M Abbas (ily4s.abbas@gmail.com)"
class ... |
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import unittest
import geojson
class FeaturesTest(unittest.TestCase):
def test_protocol(self):
"""
A dictionary can satisfy the protocol
"""
f = {
'type': 'Feature',
'id'... |
from django.contrib.auth import get_user_model
from rest_framework import serializers
class Parent(object):
def __init__(self, func):
self.func = func
def set_context(self, serializer_field):
self.value = serializer_field.queryset.get(
pk=self.func(serializer_field.context))
... |
import os
import random
from PIL import Image
from .base_dataset import BaseDataset, get_transform
from .image_folder import make_dataset
class UnalignedDataset(BaseDataset):
"""
This dataset class can load unaligned/unpaired datasets.
It requires two directories to host training images from domain A '... |
import re
import pickle
import logging
import networkx
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2019, 1, 1),
'email': ['airflow@exampl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Backend management.
Creating new backends
---------------------
A new backend named 'foo-bar' corresponds to Python module
'tracetool/backend/foo_bar.py'.
A backend module should provide a docstring, whose first non-empty line will be
considered its short descripti... |
"""
Test basic functionality for loading Earth relief datasets.
"""
import numpy as np
import numpy.testing as npt
import pytest
from pygmt.datasets import load_earth_relief
from pygmt.exceptions import GMTInvalidInput
def test_earth_relief_fails():
"""
Make sure earth relief fails for invalid resolutions.
... |
#!/usr/bin/python
# SPDX-License-Identifier: LGPL-2.1-or-later
from __future__ import print_function
import argparse
import dbus
import dbus.exceptions
import dbus.mainloop.glib
import dbus.service
import time
import threading
try:
from gi.repository import GObject # python3
except ImportError:
import gobje... |
'''
Manipulando Data e Hora
Python tem um módulo built-in para se trabalhar com data e hora chamado datetime
'''
import datetime
print(dir(datetime))
# Retorna a data e hora corrente
print(datetime.datetime.now())
# datetime.datetime(YYYY, MM, DD, Hour, Minute, Second, microsecond)
print(repr(datetime.datetime.now... |
import os
import math
def print_simulated_annealing(start, goal, parent_list, optimal_path_cost, string_to_matrix_mapping, number_states_explored):
if optimal_path_cost > 0:
print("Goal found successfully.")
else:
print("Goal NOT found")
print("Start state: ")
print_configuration(star... |
# encoding: utf-8
import logging
import sys
from pprint import pprint
import six
import click
from six import text_type
import ckan.logic as logic
import ckan.plugins as plugin
from ckan.cli import error_shout
log = logging.getLogger(__name__)
@click.group(name=u'user', short_help=u'Manage user commands')
@click.... |
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='pystok-fdw',
version='0.0.1',
author=u'Jan Waś',
license='MIT',
packages=['pystok-fdw']
) |
import pytest
import wave.data.likeness as likeness
class TestLikenessFDS:
def testRoundedLikenessFDS(self):
likeness_instance = likeness.WaveLikeness(
base=[i for i in range(64)],
comparison=[0 for i in range(64)],
ceiling=64
)
assert 31.46 == likeness_... |
import os
from srdatasets.datasets import TaFeng
from srdatasets.utils import __warehouse__
def test_download_and_trandform():
rawdir = __warehouse__.joinpath("TaFeng", "raw")
os.makedirs(rawdir, exist_ok=True)
tafeng = TaFeng(rawdir)
tafeng.download()
assert all(rawdir.joinpath(cf).exists() for ... |
# DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#368. Largest Divisible Subset
#Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subse... |
import cv2
import time
import numpy
import random
from multiprocessing import Process
from multiprocessing import Queue
from picamera.array import PiRGBArray
from picamera import PiCamera
#hacked from:
#https://software.intel.com/articles/OpenVINO-Install-RaspberryPI
#https://opencv2-python-tutroals.readthedocs.io/en/... |
#!/usr/bin/env python
"""
Copyright 2015 Reverb Technologies, 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 require... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 16:45:42 2019
@author: ASUS PC
"""
from flask import Flask, render_template, Response
import time
from threading import Lock, Thread
import queue
import socket
from threading import Thread
# emulated camera
from camera3 import Camera
# Raspberry Pi camera modul... |
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from math import exp
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
return gauss/gauss.sum()
def create_window(window_size,... |
"""
MIT License
Copyright (c) 2020-present phenom4n4n
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, pub... |
# -*- coding: utf-8 -*-
# Copyright 2010-2021, Google Inc.
# 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 source code must retain the above copyright
# notice, this... |
from gym_minigrid.minigrid import *
from gym_minigrid.roomgrid import RoomGrid
from gym_minigrid.register import register
class BlockedUnlockPickup(RoomGrid):
"""
Unlock a door blocked by a ball, then pick up a box
in another room
"""
def __init__(self, seed=None):
room_size = 6
s... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import Insufficient... |
import abc
import typing
class BaseInputFeed(abc.ABC):
"""
"""
def __init__(self, model, batch_size):
self.model = model
self.batch_size = batch_size
@abc.abstractmethod
def get_train_batch(self):
"""Defien a batch feed dictionary the model needs for training, each sub cl... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
# Graph Conv and Relational Graph Conv
import itertools
import torch
from typing import List, Union
import dgl
import torch.nn as nn
import torch.nn.functional as F
from allennlp.common import FromParams
from allennlp.common import Registrable
from allennlp.modules.encoder_base import _EncoderBase
from allennlp.module... |
if carro == 'Peugeot':
c = 50
elif carro == 'C3':
c = 60
elif carro == 'Cruze':
c = 70
elif carro == 'CRV':
c = 75
else:
print('O carro digitado não está cadastrado no nosso sistema. Verifique se está digitado corretamente ou comunique a empresa.')
return #ou pode usar sys.exit() se quiser acaba... |
# flake8: noqa
import csv
def model_name(table_name):
if table_name in ["vtm", "vpi", "vmp", "vmpp", "amp", "ampp", "gtin"]:
return table_name.upper()
else:
return "".join(tok.title() for tok in table_name.split("_"))
def quote(s):
assert '"' not in s
return '"' + s + '"'
with open... |
# 위장
"""
def solution(clothes):
def dfs_left(s, idx):
if idx == half:
left.append(s)
return
dfs_left(s, idx + 1)
dfs_left(s * values[idx], idx + 1)
def dfs_right(s, idx):
if idx == len(values):
right.append(s)
return
dfs_... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Project: Azimuthal integration
# https://github.com/silx-kit/pyFAI
#
# Copyright (C) 2019 European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)
#
# Permission is hereby granted... |
from django.apps import AppConfig
class DriversConfig(AppConfig):
name = 'drivers' |
from flask_restx import Namespace
task_api = Namespace(
'task',
description='Internal APIs for background task processing') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.