text stringlengths 1 927k |
|---|
import re
import smtplib
from email.message import EmailMessage
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Union, List, Dict
# for 3.7 we need typing.List, typing.Dict, etc...
RebuiltLogLines = List[str]
ResultData = Union[int, RebuiltLogLines]
PerDayDict = Dict[str... |
""" KibanaSavedObject interface """
from abc import ABCMeta, abstractmethod
class KibanaSavedObject:
__metaclass__ = ABCMeta
def __init__(self, data: dict):
self.data = data
self.type = self._get_type()
self.source = self._get_source()
self.title = self.source['title']
... |
import os
import platform
import tornado.httpserver
import tornado.ioloop
from tornado.options import define, options
def setup():
system = platform.system()
engine_path = os.path.dirname(__file__)
engine_paths = dict([
('Darwin', 'engines/stockfish/Mac/stockfish-7-64'),
('Linux', 'engines... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ctypes import cdll
# dxl_lib = cdll.LoadLibrary("../../c/build/win32/output/dxl_x86_c.dll") # for windows 32bit
# dxl_lib = cdll.LoadLibrary("../../c/build/win64/output/dxl_x64_c.dll") # for windows 64bit
dxl_lib = cdll.LoadLibrary("../../c/build/linux32/libdxl_x86_... |
# Source: https://github.com/carla-simulator/carla
import os
import datetime
import weakref
import math
import numpy as np
import carla
from carla import TrafficLightState as tls
import pygame
from pygame.locals import KMOD_CTRL
from pygame.locals import KMOD_SHIFT
from pygame.locals import K_COMMA
from pygame.l... |
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
import warnings
warnings.warn(
"The azure.quantum.plugins package will be deprecated. \
Please use azure.quantum.cirq and azure.quantum.qiskit instead.")
##
# Copyright (c) Microsoft Corporation. All rights reserved.... |
"""Trigonometric and Hyperbolic Functions"""
from typing import Callable
import numpy
from pipda import register_func
from ..core.contexts import Context
from ..core.types import FloatOrIter
from .constants import pi
def _register_trig_hb_func(name: str, np_name: str, doc: str) -> Callable:
"""Register trigono... |
# coding: utf-8
"""
LogicMonitor REST API
LogicMonitor is a SaaS-based performance monitoring platform that provides full visibility into complex, hybrid infrastructures, offering granular performance monitoring and actionable data and insights. logicmonitor_sdk enables you to manage your LogicMonitor account... |
"""
This module contains utilities for doing coverage analysis on the RPC
interface.
It provides a way to track which RPC commands are exercised during
testing.
"""
import os
REFERENCE_FILENAME = 'rpc_interface.txt'
class AuthServiceProxyWrapper(object):
"""
An object that wraps AuthServiceProxy to record... |
def calc_fuel(mass, recurse=True):
n = mass/3-2
if n <= 0:
return 0
elif recurse:
return n + calc_fuel(n)
else:
return n
def solve(recurse=True):
total = 0
with open('input.txt') as f:
for li in f:
total += calc_fuel(int(li), recurse)
print(total)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 04:56:05 2018
@author: skywalker
"""
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.i... |
import sys
def main():
operations = {
"add": lambda a, b: a + b,
"substract": lambda a, b: a - b,
"multiply": lambda a, b: a * b
}
result = ""
args = []
for i in range(1, len(sys.argv)):
if sys.argv[i] != "undefined":
args.append(sys.argv[i])
if len(args) == 0:
result = "Unspecified method !... |
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='admin@gmail.com',
... |
# Copyright (c) 2016 Intel, 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 ag... |
import base64
import pytest
from neuro_auth_client import User
from platform_secrets.kube_client import KubeClient
from platform_secrets.service import Secret, SecretNotFound, Service
from tests.integration.conftest import random_name
class TestService:
@pytest.fixture
def service(self, kube_client: KubeCl... |
# coding: UTF-8
from __future__ import absolute_import
from datetime import datetime
from flask import current_app
from flask.json import JSONEncoder
from flask.ext.assets import Environment
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class JSONSerializationM... |
import csv
import os
import sqlite3
import sys
import platform
from datetime import datetime
# platform_table maps the name of user's OS to a platform code
platform_table = {
'linux': 0,
'linux2': 0,
'darwin': 1,
'cygwin': 2,
'win32': 2,
}
# it supports Linux, MacOS, a... |
#!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# 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 ... |
import unittest
from app.models import Comments
class CommentTest(unittest.TestCase):
"""
Test Class to test the behaviour of the Comment class
"""
def setUp(self):
"""
Set up method that will run before every Test
"""
self.comment= Comments(opinion = 'testing testing'... |
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import RequestsClient
class TestApiRoot(TestCase):
url = reverse('index')
def test_allows_unauthenticated(self):
response = self.client.get(self.url)
self.assertTrue(response.status_code < 400)
def... |
# -*- coding: utf-8 -*-
# @Author: xiaodong
# @Date : 2021/8/28
import json
def pp(out):
print(json.dumps(out, indent=2, ensure_ascii=False)) |
from __future__ import print_function
from __future__ import division
from ..rasterizer import linear_rasterizer
from ..utils import datanormalize
from .fragment_shaders.frag_tex import fragmentshader
from .vertex_shaders.perpsective import perspective_projection
import torch
import torch.nn as nn
import numpy as np
... |
"""
Example sentences to test spaCy and its language models.
>>> from spacy.lang.uk.examples import sentences
>>> docs = nlp.pipe(sentences)
"""
sentences = [
"Ніч на середу буде морозною.",
"Чим кращі книги ти читав, тим гірше спиш.", # Serhiy Zhadan
"Найстаріші ґудзики, відомі людству, археологи знайш... |
from typing import List, Tuple
import networkx as nx
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from tqdm import tqdm
# Metadata based features
def metadata_features_extractor(
graph: nx.Graph, samples: List[Tuple[str, str]], path: str
) -> np.ndarray:
... |
#!/usr/bin/env python
#
# -------------------------------------------------------------------------------------
#
# Copyright (c) 2016, ytirahc, www.mobiledevtrek.com
# All rights reserved. Copyright holder cannot be held liable for any damages.
#
# Distributed under the Apache License (ASL).
# http://www.apache.org... |
from math import *
from random import*
from pygame import*
x=800
y=600
size= width, height = x, y
screen = display.set_mode(size)
screen.fill((255,255,255))
running=True
while running:
for evnt in event.get():
if evnt.type == QUIT:
running = False
mx,my=mouse.get_pos()#mouse position
... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.contract_type_codes import (
ContractTypeCodes as ContractTypeCodes_,
)
__all__ = ["ContractTypeCodes"]
_resource = _ValueSet.parse_file(Path(__file__).with_su... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2021-06-10 18:12
from __future__ import unicode_literals
from django.db import migrations
import osf.utils.fields
class Migration(migrations.Migration):
dependencies = [
('osf', '0233_auto_20210608_1816'),
]
operations = [
migrati... |
# Contains read interval (diameter) suggestion algorithms
from util.PID import PID
from util.pewma import Pewma
from math import *
import numpy as np
class IntervalSuggestion:
def __init__(self):
pass
def next(self, time, value, t_d):
raise NotImplementedError("next(...) not implemented.")
... |
import arcade
class MyGame(arcade.Window):
def __init__(self, width, height, title, bg_color):
super().__init__(width, height, title)
arcade.set_background_color(bg_color)
self.width = width
self.height = height
self.x = 0
self.y = 0
self.velocity = 1
... |
import re
import uuid
from collections import defaultdict
from datetime import timedelta
from unittest.mock import ANY, MagicMock, Mock, patch
from urllib.parse import urlencode
import graphene
import pytest
from django.contrib.auth.models import Group
from django.contrib.auth.tokens import default_token_generator
fro... |
import mongomock
from unittest.mock import MagicMock
import src.Settings
import src.CharacterDBHandler
import src.Database.DbHandler
import src.CharacterDBHandler
import src.Error.ErrorManager
import discord
import datetime
def test_filldata_and_init_ok():
src.Error.ErrorManager.ErrorManager().clear_error()
... |
from model.group import Group
from random import randrange
def test_delete_some_group(app):
if app.group.count() == 0:
app.group.create(Group(name="test", header="headr", footer="footr"))
old_groups = app.group.get_group_list()
index = randrange(len(old_groups))
app.group.delete_group_by_index... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from networks.network_utils import hidden_init
class MADDPGCriticVersion1(nn.Module):
def __init__(self, num_agents, state_size, action_size, fcs1_units, fc2_units, seed=0):
"""Initialize parameters and build model.
Params
... |
from piplapis.data.utils import Serializable
class AvailableData(Serializable):
children = ('basic', 'premium')
def __init__(self, basic=None, premium=None, *args, **kwargs):
self.basic = basic
self.premium = premium
def to_dict(self):
d = {}
if self.basic is not None an... |
from channels import Group
import ast
from .models import Chat
def ws_add(message):
print('recibida')
message.reply_channel.send({'accept':True})
Group('chat').add(message.reply_channel)
def ws_message(message):
to_model=ast.literal_eval(message.content['text'])
print(to_model)
md=Chat(nome=to_model['nome'],tex... |
import brownie
import pytest
from brownie import ZERO_ADDRESS
from ..addresses import *
def test_lp_pool_override(curve_registry_override):
curve_registry_override.setPoolForLp(
threeCrvPoolAddress, sushiswapLpTokenAddress # random pool
)
override_pool = curve_registry_override.poolByLp(sushiswa... |
# base16-qutebrowser (https://github.com/theova/base16-qutebrowser)
# Base16 qutebrowser template by theova
# Spacemacs scheme by Nasser Alshammari (https://github.com/nashamri/spacemacs-theme)
base00 = "#1f2022"
base01 = "#282828"
base02 = "#444155"
base03 = "#585858"
base04 = "#b8b8b8"
base05 = "#a3a3a3"
base06 = "#... |
import functools
from cumulusci.core.utils import process_bool_arg
from cumulusci.tasks.salesforce import BaseSalesforceMetadataApiTask
from cumulusci.utils import inject_namespace
from cumulusci.utils import strip_namespace
from cumulusci.utils import process_text_in_zipfile
from cumulusci.utils import tokenize_names... |
import cc3d.CompuCellSetup as CompuCellSetup
from .SteeringVolumeFlexSteppables import SteeringVolumeFlexSteppable
CompuCellSetup.register_steppable(steppable=SteeringVolumeFlexSteppable(frequency=1))
CompuCellSetup.run() |
import datetime
import csv
import pprint
#import wx
import DataDictionary
import sys
ModelSpace = 30
RuleSpace = 30
RemarksSpace = 30
class DataLogger(object):
# Open the file to log the data.
def __init__( self, fileName, fPtr,filePath):
self.__fileName = fileName
self.filePtr = fPtr
... |
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2021 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
import debug
import bitcell_base
from tech impor... |
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Most of this work is copyright (C) 2013-2021 David R. MacIver
# (david@drmaciver.com), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may hold copyright, and
# con... |
from distutils.core import setup
with open('README.rst') as file:
long_description = file.read()
setup(
name='pyqt-async',
version='0.1',
py_modules=['pyqt_async'],
url='https://github.com/sashgorokhov/pyqt-async',
download_url='https://github.com/sashgorokhov/pyqt-async/archive/master.zip',
... |
# -*- coding: utf-8 -*-
# Copyright 2014, 2015 OpenMarket 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 applica... |
#
# ----------------------------------------------------------------------------------------------------
# DESCRIPTION
# ----------------------------------------------------------------------------------------------------
#
# --------------------------------------------------------------------------------------------... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Cloudbase Solutions Srl
#
# 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/LICE... |
import shutil
import pytest
def pytest_addoption(parser):
parser.addoption("--database", action="store", help="Path to CheckV's database")
parser.addoption(
"--threads", default=1, type=int, action="store", help="Threads to use"
)
@pytest.fixture
def database(request):
return request.config... |
import pandas as pd
import numpy as np
from bengali_preprocess import Preprocess
import logging
import torch
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from bengali_dataset import BengaliDataset
logging.basicConfig(level=logging.INFO)
"""
For loading Bengali data l... |
""" UserModel
"""
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from db.database import Base
class UserModel(Base):
__tablename__ = "users"
_id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(50), unique=True)
group = Column(S... |
# -*- coding: UTF-8 -*-
# pylint: disable=line-too-long
"""
This module provides functionality to support "async steps" (coroutines)
in a step-module with behave. This functionality simplifies to test
frameworks and protocols that make use of `asyncio.coroutines`_ or
provide `asyncio.coroutines`_.
EXAMPLE:
.. code-bl... |
#!/usr/bin/env python3
# Write a Shannon entropy calculator: H = -sum(pi * log(pi))
# The values should come from the command line
# E.g. python3 entropy.py 0.4 0.3 0.2 0.1
# Put the probabilities into a new list
# Don't forget to convert them to numbers
import math
import sys
if len(sys.argv)== 1:
print('Requires N... |
'''
This is a module containing functions to construct an airfoil
'''
import copy
import numpy as np
from numpy.linalg import lstsq
from scipy import spatial
from scipy.interpolate import interp1d
from scipy.special import factorial
from .naca import naca
import matplotlib.pyplot as plt
class BasicSection():
'... |
import os
import math
import asyncio
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.telepath as s_telepath
import synapse.lib.time as s_time
import synapse.lib.layer as s_layer
import synapse.lib.msgpack as s_msgpack
import synapse.tools.backup as s_tools_backup
import synapse.tests.ut... |
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
def send_welcome_email(name,receiver):
# Creating message subject and sender
subject = 'Welcome to Morrisinsta,for allyour Photo uploads and also get to view your friends photos'
sender = 'morrison.githi... |
from datetime import date
from unittest.mock import Mock
import pytest
from dataactcore.config import CONFIG_BROKER
from dataactcore.utils.responseException import ResponseException
from dataactvalidator.validation_handlers import validationManager
from dataactvalidator.validation_handlers.errorInterface import Error... |
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The NYC3 Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test logic for skipping signature validation on old blocks.
Test logic for skipping signature validation ... |
from django.db import models
from datetime import date
# Create your models here.
class Audit(models.Model):
SYSTEM_CHOICE = (
('ADAS', 'ADAS' ),
('BIW', 'BIW'),
('Chassis', 'Chassis'),
('Exterior', 'Exterior'),
('Interior', 'Interior'),
('Powertrain', 'Powertrain'... |
# Copyright 2011 OpenStack Foundation
# 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 requ... |
# coding: utf-8
"""
NiFi Rest Api
The Rest Api provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, ... |
import os
import click
from dotenv import load_dotenv
from app import create_app
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
@app.shell_context_processor
def make_shell_context()... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^control/event/(?P<organizer>[^/]+)/(?P<event>[^/]+)/statistics/', views.IndexView.as_view(),
name='index'),
] |
#!/usr/bin/env python
"""
Python interface to CUFFT functions.
Note: this module does not explicitly depend on PyCUDA.
"""
import ctypes, platform, sys
# Load library:
_version_list = [6.5, 6.0, 5.5, 5.0, 4.0]
if 'linux' in sys.platform:
_libcufft_libname_list = ['libcufft.so'] + \
... |
#!/usr/bin/python
import sys
import struct
fname = sys.argv[1]
print("open %s" % fname)
pack = open(fname, 'rb')
pack.read(0x54) # Skip the empty padding
file_count = struct.unpack('<I', pack.read(4))[0]
name_len = struct.unpack('<I', pack.read(4))[0]
for i in range(file_count):
name_len = struct.unpack('<I', pac... |
# Copyright (C) 2017 Open Information Security Foundation
#
# You can copy, redistribute or modify this Program under the terms of
# the GNU General Public License version 2 as published by the Free
# Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; wi... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('/opt/ros/melodic/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.path.insert(0, ... |
# publish.py
import asyncio
from asyncapi import build_api_auto_spec
api = build_api_auto_spec('user_events')
channel_id = 'user/update'
message = api.payload(channel_id, id='fake-user', name='Fake User', age=33)
async def publish() -> None:
await api.connect()
await api.publish(channel_id, message)
a... |
from base64 import b64decode, b64encode
from datetime import datetime
from hashlib import md5
import json
import logging
from django.core.exceptions import ImproperlyConfigured
from .conf import settings
from .models import SESSION_TOKEN_KEY, Agent, AgentSettings
logger = logging.getLogger(__name__)
class AgentMi... |
import asyncio
import logging
import yaml
from discord.ext.commands import Bot
from ulfenkarn.dices.cog import Dices
logger = logging.getLogger(__name__)
async def start_bot(config):
bot = Bot(command_prefix="!", description="Warhammer Quest: Cursed City Helper")
bot.add_cog(Dices(bot))
await bot.start... |
#!/usr/bin/env python3
import sys
import argparse
import re
import netaddr
from os import path
from urllib import request
def report_progress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
percent = min(100, percent)
print("\rUpdating: %d%%" % percent, end='', file=sys.stderr)
... |
import torch
import gym
import numpy as np
import argparse
import cv2
import matplotlib.pyplot as plt
from agent_ac import Agent, Policy
from wimblepong import Wimblepong # import wimblepong-environment
import pandas as pd
from PIL import Image
from collections import deque
import os
from torch.utils.tensorboard impor... |
"""
Simple tests for the integration scheme for ProjectedCF (thus far). Doesn't work
as yet, since it tries to import the libraries from *this* folder, rather than
installation (which doesn't work because the fortran code isn't installed.)
"""
import inspect
import os
#LOCATION = "/".join(os.path.dirname(os.path.abspa... |
"""Variáveis que caracterizam o banco de dados"""
import os
__all__ = [
'f_names_train', 'f_names_test', 'ch_names', 'e_dict', 'e_classes',
'n_runs', 'base_folder', 'epoch_train_loc', 'epoch_test_loc', 'raw_folder', 'raw_fif_folder',
'csp_folder', 'features_test_folder', 'features_train_folder', 'originals... |
# This file is part of Ansible Galaxy
#
# Ansible Galaxy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by
# the Apache Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# Ansible Galaxy is distributed in the... |
from d2dstore.manager import BaseManager
class StoreManager(BaseManager):
"""
Custom manager store model
"""
def __init__(self, *args, **kwargs):
super(StoreManager, self).__init__(*args, **kwargs)
def get_query_set(self):
query_set = super().get_queryset()
return query_set |
def sum_arr(n):
res = 0
for x in n:
res += x
return res
nums = [52345, 746587, 98589, 54398, 9348, 45887, 49856]
test = sum_arr(nums)
# sum() is Pythons built in method of adding all the elements in a list
if test == sum(nums):
print("Sum of arr: {}".format(test))
else:
print("Func dosen'... |
# Copyright 2011 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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 ... |
import inspect
from pathlib import Path
from apistar import App, Route
from apistar_sqlalchemy.components import SQLAlchemySessionComponent
from apistar_sqlalchemy.event_hooks import SQLAlchemyTransactionHook
from europython import api, blog
from europython.config import DefaultConfig
TEMPLATES_DIR = Path(__file__).... |
# -*- coding: utf-8 -*-
VERSION = (0, 0, 1) # PEP 386
__version__ = ".".join([str(x) for x in VERSION]) |
# References : https://github.com/erik/alexandra
import sys
import alexandra
import click
import pychromecast
device_name = None
cast = None
app = alexandra.Application()
@click.command()
@click.option('--device', help='name of chromecast device', required=True)
def server(device):
global cast
global devi... |
# Generated by Django 3.1.7 on 2021-03-16 10:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
... |
import unittest
import pyperclip
from user_credentials import User, Credential
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the user class behaviours.
Args:
unittest.TestCase: helps in creating test cases
'''
def setUp(self):
'''
Function to create a user account before ... |
# Copyright 2021 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
# Copyright 2016 Twitter. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
# Copyright (c) 2019 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... |
# coding: utf-8
"""
Galaxy 3.2 API (wip)
Galaxy 3.2 API (wip) # noqa: E501
The version of the OpenAPI document: 1.2.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import openapi_client
from openapi_client.models.tags_page import TagsPage... |
'''OpenGL extension ARB.texture_gather
Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_ARB_texture_gather'
_DEPRECATED = False
GL_MIN_PROGRAM_T... |
import numpy as np
import torch
from torch import nn
from rlkit.policies.base import ExplorationPolicy, Policy
from rlkit.torch.core import eval_np
from rlkit.torch.distributions import TanhNormal
from rlkit.torch.networks import Mlp
from rlkit.torch.modules import Attention, preprocess_attention_input
LOG_SIG_MAX =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: José Sánchez-Gallego (gallegoj@uw.edu)
# @Date: 2021-02-14
# @Filename: reconnect.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
import asyncio
import click
from basecam.exceptions import CameraConnectionError
from ..tools im... |
"""Tests file for Home Assistant CLI (hass-cli)."""
import json
import unittest.mock as mocker
from unittest.mock import ANY
from click.testing import CliRunner
import requests_mock
import homeassistant_cli.autocompletion as autocompletion
import homeassistant_cli.cli as cli
from homeassistant_cli.config import Confi... |
# -*- coding: utf-8 -*-
from .basededatos import BaseDeDatos
class PerAnalisis(BaseDeDatos):
def obtener_uno(self, id_):
"""
Obtiene y retorna un objeto según el id dado.
:param id_: int >= 0
:return: tuple
"""
if id_ >= 0:
id_ = (id_,)
sql ... |
import numpy as np
import random
from kmc.particles import *
epsilon_vaccum = 8.854187e-12 #Permitivity in C/Vm
e = -1.60217662e-19 #Electron charge
kb = 8.617e-5 #Boltzmann constant
hbar = 6.582e-16 #Reduced Planck's constant
###RATES##########################... |
from datetime import datetime
from freezegun import freeze_time
from unittest.mock import Mock
import wrangler.wrangler as w
def test_validate_run_times():
valid_run_times = [
[(11, 23), (0, 0)],
[(1, 2), (23, 59)],
[(0, 60)]
]
for rt in valid_run_times:
conf = Mock(RUN_AT=... |
# A series of example bibtex entries for use in testing of this and third party libraries using wagtail_references.
# These examples were exported from Mendeley Desktop (then internal/nonpublic items anonymised).
article1 = """@article{Clark2017a,
author = {Clark, Thomas and Lueck, Rolf G. and Hay, Alex E. and Davey, ... |
import os
script_path = "C:/Users/Eudes/Documents/scriptTce"
def percorrePastaRetornaListaSQL(caminho):
if not os.path.exists(script_path):
return "Este caminho não Existe."
else:
for diretorio,pasta,listaArquivo in os.walk(caminho):
return [caminho + "/" + x for x in listaArquivo]... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Setup script.
Uses setuptools.
Long description is a concatenation of README.rst and CHANGELOG.rst.
"""
from __future__ import absolute_import, print_function
import io
import re
from glob import glob
from os.path import basename, dirname, join, splitext
from set... |
"""Core routines."""
from .common import Common, DataObject
from .composite import MultiBlock
from .filters import (CompositeFilters, DataSetFilters, PolyDataFilters,
UnstructuredGridFilters, UniformGridFilters)
from .grid import Grid, RectilinearGrid, UniformGrid
from .pyvista_ndarray import pyv... |
import imp
import ssl
import sys
from amqpstorm import AMQPConnectionError
from amqpstorm import UriConnection
from amqpstorm import compatibility
from amqpstorm.tests.utility import TestFramework
from amqpstorm.tests.utility import unittest
class UriConnectionExceptionTests(TestFramework):
@unittest.skipIf(sys.... |
import database_connection
import json
import os
import progressbar
import return_filing
import time
def main():
with open('config.json', 'r') as config_file:
config_data = json.load(config_file)
limit = config_data['load_limit']
directory = config_data['local_xml_storage_directory']
file_list... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.