filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_7810 | """
@name: Modules/House/Lighting/lighting.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2010-2020 by D. Brian Kimmel
@note: Created on Apr 2, 2010
@license: MIT License
@summary: Handle the home lighting system automation.
PyHouse.House.Lighting.
... |
the-stack_0_7811 | # Copyright 2017 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... |
the-stack_0_7812 | # -*- coding: utf-8 -*-
"""Convolutional-recurrent layers.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend as K
from .. import activations
from .. import initializers
from .. import regularizers
from .. import constraints
from .rec... |
the-stack_0_7813 | import asyncio
import json
import logging.config
import os
from types import SimpleNamespace
from aiohttp import web
from utils.middleware import (
app_info_factory,
auth_factory,
data_factory,
logger_factory,
response_factory,
)
import blog.app, homepage.app
# import blog.handler, blog.api
# imp... |
the-stack_0_7815 | import yaml
import torch
import torch.nn as nn
import argparse
import pprint
from typing import List, Dict
from pathlib import Path
from tqdm import tqdm
from torch.utils.data import DataLoader
from model import Generator, Discriminator, Vgg19
from dataset import BuildDataset, noise_generate
from visualize import Vis... |
the-stack_0_7817 | import tensorflow as tf
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras import Sequential
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, roc_auc_score
class TrainingModel:
def __init__(self, input_shape):
self.model = Sequential()
self.... |
the-stack_0_7820 | import torch
import torch.nn as nn
import torch.nn.functional as F
class RelNMS(nn.Module):
def __init__(self, cfg):
super(RelNMS, self).__init__()
self.fg_iou_threshold = 0.7
self.bg_iou_threshold = 0.3
self.nms_threshold = 0.5
self.top_k_proposals = cfg.RELPN.DPN.NUM_DURATION_PROPOSALS
self.anchor = Non... |
the-stack_0_7821 | # Copyright 2020 The HuggingFace Team, the AllenNLP library 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
#
... |
the-stack_0_7822 | from pathlib import Path
import moderngl_window
from moderngl_window import geometry
class Gradient(moderngl_window.WindowConfig):
title = "Gradient"
resource_dir = (Path(__file__) / "../resources").absolute()
aspect_ratio = None
window_size = 720, 720
resizable = False
samples = 16
def ... |
the-stack_0_7823 | from __future__ import unicode_literals
import re
import sys
import six
from botocore.awsrequest import AWSPreparedRequest
from moto.core.utils import (
str_to_rfc_1123_datetime,
py2_strip_unicode_keys,
unix_time_millis,
)
from six.moves.urllib.parse import parse_qs, urlparse, unquote, parse_qsl
import ... |
the-stack_0_7824 | import json
import os
from convlab2.util.multiwoz.state import default_state
from convlab2.dst.rule.multiwoz.dst_util import normalize_value
from convlab2.dst.dst import DST
from convlab2.util.multiwoz.multiwoz_slot_trans import REF_SYS_DA
class RuleDST(DST):
"""Rule based DST which trivially updates new values ... |
the-stack_0_7825 | """Utility functions to handle downloaded files."""
import glob
import os
import pathlib
from hashlib import md5
def get_next_name(file_path: str) -> str:
"""
Get next available name to download file.
Parameters
----------
file_path: str
Absolute path of the file for which next available ... |
the-stack_0_7826 | import pytest
from nyr.interpreter.interpreter import Interpreter
from nyr.parser.parser import Parser
def testUninitializedVariable():
ast = Parser().parse("let x;")
env = Interpreter().interpret(ast)
assert env == {'x': None}
@pytest.mark.parametrize(
("code"), (
pytest.param("let x; let y;", id="seperate... |
the-stack_0_7827 | import abc
import glob
import os
from typing import (Any, Dict, List, Optional)
import importlib
import redis
from pkg_resources import resource_filename
from gtmcore.logging import LMLogger
logger = LMLogger.get_logger()
class DevEnvMonitor(abc.ABC):
"""Class to monitor a development environments for the need... |
the-stack_0_7828 | """Module for encoding and decoding length delimited fields"""
# Copyright (c) 2018-2022 NCC Group Plc
#
# 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 withou... |
the-stack_0_7829 | #!/usr/bin/python
import os
import struct
from collections import OrderedDict
FILE_NAME = "DR.SG0" #change name to extract other file
def showData(f):
f.seek(1)
data = f.read(1)
driverId = struct.unpack("<B",(data))[0]
print("DriverId: {0}".format(driverId))
data = f.read(1)
useWeapons = struct.unpack("<B"... |
the-stack_0_7830 | #!/usr/bin/python
proto = ["ssh", "http", "https"]
protoa = ["ssh", "http", "https"]
print(proto)
proto.append('dns') # adds dns to EOL
protoa.append('dns') # adds dns to EOL
print(proto)
proto2 = [22,80,443,53] # list common ports
proto.extend(proto2) #pass proto2 as arguement to ext method
print(proto)
protoa.append... |
the-stack_0_7831 | import os
from celery import Celery
from django.apps import apps, AppConfig
from django.conf import settings
if not settings.configured:
# set the default Django settings module for the 'celery' program.
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE", "config.settings.local"
) # pragma: no cover... |
the-stack_0_7833 | """
WHAT: A class which which manages the interface with MySQL
WHY: Need to read and write data to MySQL
ASSUMES: MySQL is running per the connection parameters
FUTURE IMPROVEMENTS: Add table upload functions, and DDL creation as required
WHO: SL 2020-08-13
"""
import mysql.connector as mysql
import pandas as pd
from ... |
the-stack_0_7834 | import json
import logging
import sys
import unittest
from handlers.proj_schedule_initializer import lambda_handler
from handlers.proj_schedule_initializer import logger
logging.basicConfig(format='%(asctime)s %(filename)s [line:%(lineno)d] [PID:%(process)d] %(levelname)s: %(message)s',
stream=sys... |
the-stack_0_7835 | # coding: utf-8
"""Example / benchmark for building a PTB LSTM model.
Trains the model described in:
(Zaremba, et. al.) Recurrent Neural Network Regularization
http://arxiv.org/abs/1409.2329
There are 3 supported model configurations:
===========================================
| config | epochs | datasets | valid | ... |
the-stack_0_7837 | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from numpy.testing import assert_allclose
import pytest
from jax import random
import jax.numpy as jnp
import numpyro
from numpyro.contrib.control_flow import cond, scan
import numpyro.distributions as dist
from numpyro.handlers impo... |
the-stack_0_7838 | """
Pytorch models.
"""
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.functional as F
import torch.optim as optim
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from torch.nn.init import xavier_uniform_
import utils
CUDA = torch.cuda.is_available()
class ... |
the-stack_0_7839 | import copy
import datetime
import logging
import traceback
import warnings
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from urllib.parse import urlparse
from great_expectations._version import get_versions # isort:skip
__version__ = get_versions()["version"] # isor... |
the-stack_0_7844 | import argparse
from datetime import datetime
from pathlib import Path
from .. import cli
from ..core.repository import Repository
from ..utils import create_filename
from ..utils import log
from ..utils import output_csv
from ..utils import parse_datetime
def parse_dateto(s):
return parse_datetime(s + ' 23:59:5... |
the-stack_0_7846 | import json
from tornado.web import RequestHandler
__author__ = 'TIF'
class BaseHandler(RequestHandler):
@property
def sched(self):
return self.application.scheduler
def from_body_get_arguments(self):
body = self.request.body
return json.load(body) |
the-stack_0_7848 | '''
Miscellaneous data generator utilities.
Copyright (C) 2018 Pierluigi Ferrari
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... |
the-stack_0_7849 | #! python
"""
Class `CountRunner` to report read status of FL reads,
as well as make abundance report.
"""
import logging
import os.path as op
from .CountingUtils import read_group_file, output_read_count_FL, make_abundance_file
__author__ = 'etseng@pacificbiosciences.com'
log = logging.getLogger(__name__)
class... |
the-stack_0_7850 | #!/usr/bin/python
from collections import OrderedDict
from Qt import QtGui, QtCore, QtWidgets
from NodeGraphQt.constants import (IN_PORT, OUT_PORT,
NODE_WIDTH, NODE_HEIGHT,
NODE_ICON_SIZE, ICON_NODE_BASE,
NODE_SEL... |
the-stack_0_7851 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright (c) 2011 Piston Cloud Computing, Inc
# Copyright (c) 2012 University Of Minho
# (c) Copyright 2013 Hewlett-Pa... |
the-stack_0_7852 | #!/usr/bin/env python3
# Copyright (c) 2015-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.
"""Utilities for doing coverage analysis on the RPC interface.
Provides a way to track which RPC commands... |
the-stack_0_7855 | """
Test message and address parsing/formatting functions.
"""
from email.header import Header
from email.headerregistry import Address
from email.message import EmailMessage, Message
import pytest
from hypothesis import example, given
from hypothesis.strategies import emails
from aiosmtplib.email import (
extrac... |
the-stack_0_7857 | #!/usr/bin/env python3
# Copyright (c) 2015-2018 The Syscoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test behavior of -maxuploadtarget.
* Verify that getdata requests for old blocks (>1week) are dropped
... |
the-stack_0_7859 | import discord
import discord.utils
import discord.ext
import re
import emoji
from redbot.core import commands, Config, bank, checks
class April(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
... |
the-stack_0_7862 | # -*- coding: utf-8 -*-
'''
Control the state system on the minion.
State Caching
-------------
When a highstate is called, the minion automatically caches a copy of the last
high data. If you then run a highstate with cache=True it will use that cached
highdata and won't hit the fileserver except for ``salt://`` lin... |
the-stack_0_7864 | # !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-08-10 21:45:28
# Description:
import os, sys
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
mapping = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
... |
the-stack_0_7866 | import unittest
import atheris
import atheris_libprotobuf_mutator
from atheris import fuzz_test_lib
from google.protobuf import wrappers_pb2
@atheris.instrument_func
def simple_proto_comparison(msg):
if msg.value == "abc":
raise RuntimeError("Solved")
class AtherisLibprotobufMutatorTests(unittest.TestCase):
... |
the-stack_0_7867 | import logging.handlers
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '[%(asctime)s][%(process)d][%(thread)d][%(levelname)-5s][%(filename)s:%(lineno)d][%(funcName)s]: %(message)s',
'datefmt': '%Y/%m/%d %H:%M:%S',
... |
the-stack_0_7868 | from django.urls import path
from . import views
app_name = 'events'
urlpatterns = [
path('', views.EventListView.as_view(), name='all'),
path('<int:pk>/', views.EventView.as_view(), name='details'),
path('<int:pk>/edit/', views.EventUpdateView.as_view(), name='edit'),
path('<int:pk>/attended/', views... |
the-stack_0_7869 | import argparse
from email.mime import image
import os
from tqdm import tqdm
import pandas as pd
import logging
from src.utils.common import read_yaml, create_directories
from src.stage_01_get_data import main as loader_main
from sklearn.metrics import confusion_matrix, f1_score
import numpy as np
import warnings
impor... |
the-stack_0_7870 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
the-stack_0_7871 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# 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... |
the-stack_0_7875 | # cython: auto_cpdef=True
"""Python code for writing AVRO files"""
# This code is a modified version of the code at
# http://svn.apache.org/viewvc/avro/trunk/lang/py/src/avro/ which is under
# Apache 2.0 license (http://www.apache.org/licenses/LICENSE-2.0)
import json
from io import BytesIO
from os import urandom, S... |
the-stack_0_7876 | """
격자의 행과 열의 크기를 입력 받아서,
격자의 왼쪽 위에서 오른쪽 아래로 가는 모든 최단 경로 (shortest grid path)를 d, r로 표시하여 보세요.
Input
같은 줄에 격자(grid)의 행(세로, row)과 열(가로, col)의 크기가 입력됩니다.
Output
격자의 왼쪽 위에서 오른쪽 아래로 가는 모든 최단 경로를 d, r로 표시하여 출력합니다.
출력 순서는 문제의 예와 같게 합니다.
Sample Input 1
3 2
Sample Output 1
dddrr
ddrdr
ddrrd
drddr
drdrd
drrdd
rdddr
rd... |
the-stack_0_7877 | """
_SummaryHistogram_
Histogram module, to be used by the TaskArchiver
to store histograms in the summary.
Created on Nov 16, 2012
@author: dballest
"""
from builtins import str
from WMCore.DataStructs.WMObject import WMObject
class SummaryHistogram(WMObject):
"""
_SummaryHistogram_
Histogram object, ... |
the-stack_0_7879 | import cv2
import numpy as np
from preparation.augmentor import Augmentor
from preparation.utils import get_snake_case, get_class_from_path
import pandas as pd
import os
from multiprocessing.pool import ThreadPool as Pool
from glob import glob
class Processor:
def __init__(self, batch_size, width, height):
... |
the-stack_0_7881 | from django.test import TestCase
# Create your tests here.
import datetime
from django.utils import timezone
from catalog.forms import RenewBookForm
class RenewBookFormTest(TestCase):
def test_renew_form_date_in_past(self):
"""
Test form is invalid if renewal_date is before today
"""
date = datetime.date.t... |
the-stack_0_7882 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
the-stack_0_7883 | import logging
import os
from datetime import datetime
from unittest.mock import Mock
import psycopg2
import pytest
from scrapy.exceptions import NotConfigured
from kingfisher_scrapy.extensions import DatabaseStore, FilesStore
from tests import spider_with_crawler
database_url = os.getenv('KINGFISHER_COLLECT_DATABAS... |
the-stack_0_7884 |
import json
f = open("../../config/add_action.txt")
processors = []
action_map = {}
actions = []
primitive_list = []
primitive_num = 0
parameter_num = 0
primitive_idx = 0
cur_idx = 0
while True:
line = f.readline()
print(line)
if not line:
break
if line == "\n":
continue
l = l... |
the-stack_0_7885 | # Copyright (c) MONAI Consortium
# 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, so... |
the-stack_0_7888 | from __future__ import absolute_import, division, print_function, unicode_literals
import braintree
from postgres.orm import Model
class ExchangeRoute(Model):
typname = "exchange_routes"
def __bool__(self):
return self.error != 'invalidated'
__nonzero__ = __bool__
@classmethod
def fro... |
the-stack_0_7889 | import os
TARGET = os.path.abspath(os.getcwd())
for root, dirs, files in os.walk(TARGET):
for filename in files:
# read file content
with open(os.path.join(root, filename)) as f:
content = f.read()
# replace tag by install path
content = content.replace('$((INSTALDIR))', TARG... |
the-stack_0_7890 | # -*- coding: utf-8 -*-
"""Base exchange class"""
# -----------------------------------------------------------------------------
__version__ = '1.15.45'
# -----------------------------------------------------------------------------
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import NotSuppor... |
the-stack_0_7891 | import itertools
import collections
import numpy as np
class Solver:
'''
Solver class.
'''
def __init__(self, Y, M, epsilon, distance):
'''
Parameters
----------
Y : list<vector>
Finite set of vectors
M : int
Positive int... |
the-stack_0_7893 | import random
import nltk
from nltk.tokenize.treebank import TreebankWordDetokenizer
import random
import base64
import binascii
import cipheydists
import string
import cipheycore
import cipheydists
import base58
import base62
import re
class encipher:
"""Generates encrypted text. Used for the NN and test_genera... |
the-stack_0_7894 | # Copyright 2018 The glTF-Blender-IO 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 by applicable law or agree... |
the-stack_0_7896 | import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class CTCLabelConverter(object):
""" Convert between text-label and text-index """
def __init__(self, character):
# character (str): set of the possible characters.
dict_character = list(character)
sel... |
the-stack_0_7899 | # Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... |
the-stack_0_7900 | # coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class CreateVpcResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): ... |
the-stack_0_7902 | # Main script for inducing LTL contrastive explanations from input set of traces
#
# ARGUMENTS:
# -d [input.json] : json file containing the required input (see README)
#
# OUTPUT:
# output.json : json output containing top-10 induced results
#
#
# Written by Joseph Kim
import argparse
from itertools import pe... |
the-stack_0_7904 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 26 11:08:40 2021
@author: leonl42
Unit test for testing the lowercase conversion in the preprocessing pipeline
"""
import unittest
import pandas as pd
from scripts.preprocessing.lower import Lower
from scripts.util import COLUMN_TWEET
class Lowe... |
the-stack_0_7905 | import os
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
class PlotUtils(object):
@staticmethod
def plot_region(df, x0, x1, y0, y1, text=True):
"""
Plot the region of the mapping space bounded by the given x and y limits.
"""
FS = (10, 8)
... |
the-stack_0_7906 | import numpy as np
import math
from keras.initializers import VarianceScaling
from keras.models import model_from_json
from keras.models import Sequential, Model
#from keras.engine.training import collect_trainable_weights
from keras.layers import Dense, Flatten, Input, Add, merge, Lambda
from keras.optimizers import A... |
the-stack_0_7907 | from __future__ import absolute_import
import socket
from pickle import loads, dumps
from celery import states
from celery.exceptions import ImproperlyConfigured
from celery.tests.case import (
AppCase, Mock, mock_module, depends_on_current_app,
)
class Object(object):
pass
def install_exceptions(mod):
... |
the-stack_0_7908 | """Automatic Domain Randomization (ADR) algorithm
Introduced in:
Akkaya, Ilge, et al. "Solving rubik's cube with a robot hand."
arXiv preprint arXiv:1910.07113 (2019).
"""
import random
from inspect import signature
from typing import Any, AnyStr, Union, Sequence, Optional
import numpy as np
from collections import O... |
the-stack_0_7910 | # Copyright 2020, 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 by applicable law o... |
the-stack_0_7912 | #!/usr/bin/env python3
import os
import sys
import json
from argparse import ArgumentParser
from source.fmp import ProfileFMP
from source.create_sheet import create_excel
data_dir = os.path.join(os.path.dirname(__file__), 'data')
if not os.path.isdir(data_dir):
os.makedirs(data_dir)
def fetch_data_by_symbol(symbo... |
the-stack_0_7913 | import csv
from functools import lru_cache
from pathlib import Path
from typing import Dict
from typing import Iterable
from typing import Optional
from typing import Set
from typing import Tuple
from typing import Type
from typing import Union
import warnings
from django.apps import AppConfig
from django.apps import ... |
the-stack_0_7914 | # Atribuir o valor 1 à variável var_teste
var_teste = 1
# Imprimir o valor da variável
print(var_teste)
# Atribuir o valor 2 à variável var_teste
var_teste = 2
# Imprimir o valor da variável
print(var_teste)
# Exibir o tipo de dados da variável
type(var_teste)
# Atribuir o valor 9.5 à variável var_teste
var_teste ... |
the-stack_0_7916 | # Copyright 2015 Objectif Libre
#
# 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 agr... |
the-stack_0_7917 | """
xterm terminal info
Since most of the Windows virtual processing schemes are based on xterm
This file is intended to be sourced and includes the man page descriptions
Most of this information came from the terminfo man pages, part of ncurses
More information on ncurses can be found at:
https://www.gnu.org/softwar... |
the-stack_0_7918 | # https://github.com/openai/gym/blob/master/gym/envs/classic_control/pendulum.py
# https://mspries.github.io/jimmy_pendulum.html
#!/usr/bin/env python3
import time
import torch
import torch.multiprocessing as mp
import os, sys
print("PyTorch Version", torch.__version__)
current_path = os.path.dirname(os.path.realpath(... |
the-stack_0_7919 | #!/usr/bin/env python
import os
import numpy as np
import gippy as gp
import unittest
import gippy.test as gpt
# from nose.tools import raises
"""
Included are some tests for doing processing in NumPy instead of Gippy,
for doing speed comparisons. To see the durations of each test use:
$ nosetests test --with-tim... |
the-stack_0_7921 | # Copyright 2020 The SQLFlow 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 applicable law o... |
the-stack_0_7922 | class Solution:
def findPeakElement(self, nums: List[int]) -> int:
l,r = 0,len(nums)-1
while l<r:
mid = (l+r)//2
if nums[mid]<nums[mid+1]:
l=mid+1
else:
r=mid
return l
|
the-stack_0_7925 | """Support for Nanoleaf Lights."""
from __future__ import annotations
import math
from typing import Any
from aionanoleaf import Nanoleaf
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_EFFECT,
ATTR_HS_COLOR,
ATTR_TRANSITION,
ColorMode,
LightEntity,
... |
the-stack_0_7926 | from datetime import datetime, timedelta, date
import logging
import traceback
from decimal import *
import json
import calendar
import geojson
import requests
import io
from django.conf import settings
from django.core.urlresolvers import reverse, reverse_lazy
from django.core.exceptions import ValidationError
from dj... |
the-stack_0_7927 | #!/usr/bin/env python3
import sys
import os
import struct
import select
import time
import getopt
import tqdm
import socket
try:
optlist, args = getopt.getopt(sys.argv[1:], 's')
timeout = 0.01
n = 1024
slow = False
for o, a in optlist:
if o == "-s":
slow = True
n ... |
the-stack_0_7928 | """Sensor classes represent modbus registers for an inverter."""
from __future__ import annotations
import logging
from math import modf
from typing import Any, Dict, List, Sequence, Tuple, Union
import attr
_LOGGER = logging.getLogger(__name__)
def ensure_tuple(val: Any) -> Tuple[int]:
"""Return a tuple."""
... |
the-stack_0_7929 | from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer
from hazelcast.protocol.builtin import StringCodec
# hex: 0x0D0900
_REQUEST_MESSAGE_TYPE = 854272
# hex: 0x0D0901
_RESPONSE_MESSAGE_TYPE = 854273
_REQUEST_INITIAL_FRAME_SIZE = REQUEST_HEADER_SIZE
def encode_req... |
the-stack_0_7930 | import gevent
import pytest
import requests
import responses
from eth_keys.exceptions import BadSignature, ValidationError
from eth_utils import decode_hex, keccak, to_canonical_address
from raiden.api.v1.encoding import CapabilitiesSchema
from raiden.exceptions import InvalidSignature
from raiden.network.utils import... |
the-stack_0_7931 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# statistics.py: collect statistic data
#
# Copyright (C) 2014 Politecnico di Torino, Italy
# TORSEC group -- http://security.polito.it
#
# Author: Roberto Sassu <roberto.sassu@polito.it>
#
# This library is free software; you can redistribute it and/or
... |
the-stack_0_7932 | from typing import Any, Optional, Union
from chia.types.blockchain_format.sized_bytes import bytes32
import click
async def show_async(
rpc_port: Optional[int],
state: bool,
show_connections: bool,
exit_node: bool,
add_connection: str,
remove_connection: str,
block_header_hash_by_height: ... |
the-stack_0_7933 | # Copyright 2016 Canonical Ltd
#
# 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, s... |
the-stack_0_7936 | from block_getter import *
from pprint import pprint
import sys
import time
import os
def get_head_to_tail_blocks(tail_block_height, head_block_height, api_interval):
wanted_block_numbers = [block_number for block_number in range(tail_block_height, head_block_height + 1)]
lack_block_numbers = check_lack_blocks(want... |
the-stack_0_7938 | #!/usr/bin/env python3
import argparse
from distutils.util import strtobool
import logging
from espnet.transform.transformation import Transformation
from espnet.utils.cli_readers import file_reader_helper
from espnet.utils.cli_utils import get_commandline_args
from espnet.utils.cli_utils import is_scipy_wav_style
fro... |
the-stack_0_7939 | from collections import OrderedDict
from inspect import Signature, Parameter
from typing import Any
from typing import List
import torch
from nncf.common.graph.definitions import MODEL_INPUT_OP_NAME
from nncf.common.graph.definitions import MODEL_OUTPUT_OP_NAME
from nncf.torch.dynamic_graph.patch_pytorch import regis... |
the-stack_0_7941 | # -*- coding: utf-8 -*-
import logging
import rest_framework_swagger.renderers as rest_swagger_renderers
from django.core import urlresolvers
from zope.dottedname import resolve
logger = logging.getLogger(__name__)
def resolve_swagger_doc(url, method):
resolve_result = urlresolvers.resolve(url)
swaggerdoc... |
the-stack_0_7943 | import artm
import numpy as np
import shutil
import pytest
import warnings
from ..cooking_machine.models.topic_model import TopicModel
from ..cooking_machine.dataset import Dataset, W_DIFF_BATCHES_1
from ..viewers import top_documents_viewer
NUM_TOPICS = 5
NUM_DOCUMENT_PASSES = 1
NUM_ITERATIONS = 10
class TestTop... |
the-stack_0_7948 |
import tifffile
import tqdm
import os
import numpy as np
import sys
import fnmatch
def scandir(path, pat, cb):
for root, dirs, files in os.walk(path):
head, tail = os.path.split(root)
for file in files:
if fnmatch.fnmatch(file, pat):
fn = os.path.join(root, file)
... |
the-stack_0_7949 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: RShirohara
import argparse
import inspect
import sys
import novelconverter
_EXTENSION = (
"markdown",
"ddmarkdown",
"pixiv"
)
def get_args():
_parser = argparse.ArgumentParser(
description=novelconverter.__doc__,
formatter_cla... |
the-stack_0_7950 | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Mike Place <mp@saltstack.com>`
'''
# Import python libs
from __future__ import absolute_import
import copy
import os
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import N... |
the-stack_0_7952 | #!/usr/bin/env python
import sys, time, re
from splunklib.searchcommands import \
dispatch, EventingCommand, Configuration, Option, validators
from libtf.logparsers import TFAuthLog, TFHttpLog, TFGenericLog
import ConfigParser
import os
import StringIO
import subprocess
@Configuration()
class ReaperCommand(Eventi... |
the-stack_0_7954 | import time
import numpy as np
from scipy import optimize
from statsmodels.distributions.empirical_distribution import ECDF
from numba import njit, prange, double, int64, boolean
# plotting
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cyc... |
the-stack_0_7955 | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
"""
Gaussian Process
================
In this example we show how to use NUTS to sample from the posterior
over the hyperparameters of a gaussian process.
"""
import argparse
import os
import time
import matplotlib
import matplotlib... |
the-stack_0_7956 | #!/usr/bin/env python3
# Copyright (c) 2014-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet import RPCs.
Test rescan behavior of importaddress, importpubkey, importprivkey, and
impor... |
the-stack_0_7957 | import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import os
import pdb
from tqdm import tqdm
import argparse
import pandas as pd
import sys
BASE_DIR=os.path.dirname(os.getcwd())
sys.path.append(BASE_DIR)
sys.path.append('/home/tam63/geometric-js')
import torch
import scipy.stats
from scipy.... |
the-stack_0_7958 | import argparse
from utils.helpers import read_lines
from gector.gec_model import GecBERTModel
def predict_for_file(input_file, output_file, model, batch_size=32):
test_data = read_lines(input_file)
predictions = []
cnt_corrections = 0
batch = []
count = 0
for sent in test_data:
batch... |
the-stack_0_7959 |
class BinarySearchTree(object):
class Node(object):
def __init__(self, key, value):
self.left = None
self.right = None
self.key = key
self.value = value
def __repr__(self):
return "Node(key={}, value={}, left={}, right={})".format(self.k... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.