text stringlengths 1 927k |
|---|
from .standard import *
# from .extend import * |
import unittest
import json
import re
from base64 import b64encode
from flask import url_for
from app import create_app, db
from app.models import User, Role, Post, Comment
class APITestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_conte... |
# Copyright 2018 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
"""
.. moduleauthor:: Chris Bowman <chris.bowman.physics@gmail.com>
"""
from typing import Union, Iterable
from numpy import array, log, pi, zeros, concatenate, float64, where
from numpy.random import normal, exponential, uniform
from itertools import chain
class JointPrior(object):
"""
A class which combine... |
from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
import logging
import warnings
class CertEnrollments(APIClassTemplate):
"""
The CertEnrollments Object in the FMC.
"""
VALID_JSON_DATA = ["id", "name", "type"]
VALID_FOR_KWARGS = VALID_JSON_DATA + []
URL_SUFFIX = "/object/certen... |
import time
import pyautogui
import pygetwindow as gw
import sys
from datetime import datetime
info = open('timing.txt', 'r')
Lines = info.readlines()
count = 0
# Strips the newline character
data = []
for line in Lines:
print(line)
ldata = line.split(',')
data = ldata
print(data)
meeting_id = dat... |
# 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... |
# Future
from __future__ import absolute_import, division, print_function, \
unicode_literals, with_statement
# Standard Library
import random
# First Party
from metaopt.core.arg.arg import Arg
class BoolArg(Arg):
def __init__(self, param, value=None):
super(BoolArg, self).__init__(param=param, valu... |
from django.db import models
from django.utils import timezone
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
created = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['created']
def __str__(... |
# Copyright 2020 EMBL - European Bioinformatics Institute
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by AKM_FAN@163.com on 2017/11/6
"""
工程引导文件
开发运行
数据库创建更新
工程自定义命令
"""
import os
import unittest
# 代码覆盖率测量库
import coverage
# 自定义命令库
from flask_script import Manager
# 数据库表结构迁移库(将model修改同步修改数据库表结构)
from flask_migrate import Migrate, MigrateCommand
COV = coverage.c... |
from FWCore.ParameterSet.VarParsing import VarParsing
import FWCore.ParameterSet.Config as cms
options = VarParsing('python')
options.register('isMC', False,
VarParsing.multiplicity.singleton,
VarParsing.varType.bool,
"Run this on real data"
)
options.register('globalTag', 'NOTSET',
VarParsing.multipl... |
import unittest
class TestClassBase(unittest.TestCase):
"""Test Data"""
def setUp(self):
pass
class TestClassName(TestClassBase):
"""Test block hash"""
def test_func_name(self):
result = ""
expected = "-0.00001234"
self.assertEqual(expected, result)
if __name__ == '_... |
from typing import List, Dict, Tuple
import subprocess
from datetime import datetime
from reporting.common import split_datetime
# Generic utils
def checkout_commit(repo_dir: str, commit: str) -> None:
subprocess.check_call(['git', 'checkout', commit], cwd=repo_dir)
def get_commit_range(repo_dir: str, start_... |
## This file is part of PyANTLR. See LICENSE.txt for license
## details..........Copyright (C) Wolfgang Haefelinger, 2004.
## This file was copied for use with xlwt from the 2.7.7 ANTLR distribution. Yes, it
## says 2.7.5 below. The 2.7.5 distribution version didn't have a
## version in it.
## Here is the contents of... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import absolute_import, division, print_function, unicode_literals
import contextlib
import os
@contextlib.contextmanager
def cwd(dirname):
"""... |
'''
Project Name: InventoryEXT_SMV_GUI - Inventory To Simplified Model View, Code Material Design
Proper Name: Excel Data Inventory To Simplified Model ListView
Version: unknown.beta
Authors: Janrey Tuazon Licas - App Design (Semi)
Sam Matienzo (Database Worker)
GUI Library Used: Kivy
Base Theme: KivyMD (Ma... |
from nitro.async import AsyncOp
from cspace.util.rpc import RPCConnection, RPCStub
from cspaceapps.filetransfer.fileproto import validateResponse, ProtocolError
class FileClient( object ) :
def __init__( self, rpcConn, objectName='FileServer' ) :
self.stub = RPCStub( rpcConn, objectName )
def _doCall(... |
# jsb/eventhandler.py
#
#
""" event handler. use to dispatch function in main loop. """
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.utils.locking import lockdec
from threads import start_new_thread
## basic imports
import Queue
import thread
import logging
import time
## locks
handle... |
# encoding: utf-8
import os
import pastebin
import filesystem
import paths
import settings
def debug_log_contents():
fs = filesystem.RealFilesystem()
return "\n".join([
debug_string_for_file(settings.settings_file_path('config.txt', fs)),
debug_string_for_file(settings.settings_file_path('consoles.txt',... |
from run_pipeline import run_pipeline
from src.type_collector import TypeCollector
from src.type_builder import TypeBuilder
from src.type_checker import TypeChecker
from src.tset_builder import TSetBuilder
from src.tsets_reducer import TSetReducer
from src.tset_merger import TSetMerger
from src.cool_visitor import Form... |
from django.db import models
from django.contrib.auth.models import User
# Token模型 - 用于浏览器扩展
class UserToken(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
token = models.CharField(verbose_name="token值",max_length=250,unique=True)
def __str__(self):
return self.user
... |
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
load(
"//:coursier.bzl",
"add_netrc_entries_from_mirror_urls",
"compute_dependency_inputs_signature",
"extract_netrc_from_auth_url",
"get_coursier_cache_or_default",
"get_netrc_lines_from_entries",
"remove_auth_from_url",
"sp... |
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... |
# -*- coding: utf-8 -*-
from model.user import User
def test_create_user(app, db, json_users, check_ui):
# get current user list from db
user = json_users
old_user_list = db.get_user_list()
app.user.create(user)
# get new user list from db
new_user_list = db.get_user_list()
# add new user
... |
#!/usr/bin/env python
from __future__ import print_function
import re
import json
import fileinput
try:
from urllib import urlopen # Python 2
except ImportError:
from urllib.request import urlopen # Python 3
MAX_WORDS = 200
word_counts = {}
stop_words = set(["a","able","about","across","after","all","almo... |
import os
import shutil
def get_output_path(fn):
out_dir = os.path.join(os.path.dirname(__file__), 'output')
if not os.path.exists(out_dir):
os.mkdir(out_dir)
return os.path.join(out_dir, fn) |
import sys
import os
import shutil
def exit_cli(print_func, message):
print_func("%s" % message)
sys.exit(0)
def display_file(file_name):
"""
Open given file with default user program.
"""
if sys.platform.startswith("linux"):
os.system("xdg-open %s" % file_name)
elif sys.platfor... |
from base_models import (Document, BasePaper, BaseParagraph, BaseMaterial, BaseOperation, BaseDescriptor, BaseProperty,
BaseAmount, BaseCondition, BaseApparatus, BaseConnection)
### PAPER AND PARAGRAPHS ###
class Paper(BasePaper):
structure = dict(BasePaper.structure, **{
'operations'... |
# data associated with an edge can contain a weight
WEIGHT = 'weight'
class AdjacencyViewer:
"""
Provide object to iterate over adjacent nodes.
"""
def __init__(self, mat, i, neighbors):
self.mat = mat
self.i = i
self.neighbors = neighbors
def __getitem__(self, target):
... |
# -*- coding: utf-8 -*-
"""Python wrapper for timsdata.dll"""
import numpy as np
import sqlite3
import os, sys
from ctypes import *
if sys.platform[:5] == "win32":
libname = "timsdata.dll"
elif sys.platform[:5] == "linux":
libname = "libtimsdata.so"
else:
raise Exception("Unsupported platform.")
path = ... |
"""
BLE Client for CoreBluetooth on macOS
Created on 2019-6-26 by kevincar <kevincarrolldavis@gmail.com>
"""
import logging
import uuid
from asyncio.events import AbstractEventLoop
from typing import Callable, Any, Union
from Foundation import NSData, CBUUID
from CoreBluetooth import CBCharacteristicWriteWithRespons... |
from setuptools import setup
setup(
name='firetv',
version='1.1.0',
description='Communicate with an Amazon Fire TV device via ADB over a network.',
url='https://github.com/happyleavesaoc/python-firetv/',
license='MIT',
author='happyleaves',
author_email='happyleaves.tfr@gmail.com',
pac... |
"""
WSGI config for django_travis_setup project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault(... |
"""The Growatt server PV inverter sensor integration."""
from homeassistant import config_entries
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from .const import PLATFORMS
async def async_setup_entry(
hass: HomeAssistant, entry: config_entries.ConfigEntry
) ->... |
from __future__ import unicode_literals
import copy
import datetime
import os
import random
import string
from collections import defaultdict
from boto3 import Session
from jinja2 import Template
from re import compile as re_compile
from collections import OrderedDict
from moto.core import BaseBackend, BaseModel, Clo... |
"""
Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -munleashed_py` python will execute
``__main__.py`` as... |
# Copyright 2016-2018, Pulumi Corporation.
#
# 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 t... |
import logging
import os
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from django.db import transaction
from wagtail.core.models import Page, Site
from wagtailsharing.models import SharingSite
from v1.models import HomePage
logger = logging.getLogger(__name__)
... |
# Copyright 2018 Leonard G. Warden IV
#
# 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 w... |
"""
The multi-reward and probabilistic reward enviroments are the same. You
could simulate a probabilistic reward of 10 units, delivered 50% of the time,
by having a mixture of 10 and 0 unit rewards, or vice versa. The takehome message
from these last three exercises is that the *average* or expected reward is
what mat... |
from setuptools import setup, find_packages
from pathlib import Path
#import versioneer
package_name = 'scanpy_recipes'
req_path = Path('requirements.txt')
with req_path.open() as requirements:
requires = [l.strip() for l in requirements]
with open('README.md', encoding='utf-8') as fin:
readme = fin.read()
... |
class Node:
def __init__(self, val):
self.value = val
self.right = None
self.left = None
self.visited = False
def __str__(self):
r = None if self.right is None else self.right.value
l = None if self.left is None else self.left.value
return f"({self.va... |
#!/usr/bin/python3
from cleverwrap import CleverWrap
import pyttsx
import os
os.environ["HTTPS_PROXY"] = "http://usr_name:pass@proxy:port"
cw = CleverWrap("API_KEY")
a='y'
engine = pyttsx.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[4].id)
rate = engine.getProperty('rate')
engine.s... |
from django import forms
from .models import Event,Attendee
from .utils import generate_event_url
class CreateNewEvent(forms.ModelForm):
class Meta():
model = Event
fields = ['event_name', 'event_type', 'event_url']
widgets = {
'event_type': forms.TextInput(attrs={'class':'form-control ', }),
'event_name'... |
import datetime
import json
from django.contrib import admin
from django.conf import settings
from django.utils import timezone
from .models import CachedTransaction, Memo, IPTracker
from django.utils.safestring import mark_safe
class CachedTransactionAdmin(admin.ModelAdmin):
list_display = ("txid", 'crypto', "c... |
from .base_atari_env import BaseAtariEnv, base_env_wrapper_fn, parallel_wrapper_fn
def raw_env(**kwargs):
mode = 33
num_players = 4
return BaseAtariEnv(game="pong", num_players=num_players, mode_num=mode, **kwargs)
env = base_env_wrapper_fn(raw_env)
parallel_env = parallel_wrapper_fn(env) |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import unittest
from builtins import open
from textwrap import dedent
from pan... |
# Copyright (c) 2016-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import shutil
import signal
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest.mock import MagicMock... |
# Natural Language Toolkit: Punkt sentence tokenizer
#
# Copyright (C) 2001-2013 NLTK Project
# Algorithm: Kiss & Strunk (2006)
# Author: Willy <willy@csse.unimelb.edu.au> (original Python port)
# Steven Bird <stevenbird1@gmail.com> (additions)
# Edward Loper <edloper@gradient.cis.upenn.edu> (rewrite)
#... |
from runner.koan import *
class AboutStrings(Koan):
def test_double_quoted_strings_are_strings(self):
string = "Hello, world."
self.assertEqual(True, isinstance(string, str))
def test_single_quoted_strings_are_also_strings(self):
string = 'Goodbye, world.'
self.assertEqual(Tr... |
from datetime import datetime
import globals
from globals import get_soup, job_insert
from datecleaner import month_to_num
from job import Job
# Alliance for Housing and Healing (Formerly the Serra Project & Aid For Aids)
organization = "Alliance for Housing and Healing"
url = 'https://alliancehh.org/about/jobs/'
orga... |
# encoding: UTF-8
'''
本文件中包含了CTA模块中用到的一些基础设置、类和常量等。
'''
from __future__ import division
print 'load ctaBase.py'
# 常量定义
# CTA引擎中涉及到的交易方向类型
CTAORDER_BUY = u'买开'
CTAORDER_SELL = u'卖平'
CTAORDER_SHORT = u'卖开'
CTAORDER_COVER = u'买平'
CTAORDER_OPEN_REJECT = u'开单拒绝'
CTAORDER_OPEN_FAIL = u'开单失败'
CTAORDER_CLOSE_FAIL = u'平单失败'... |
from datetime import datetime
from pony.orm import *
from model.contact import Contact
from model.group import Group
from pymysql.converters import decoders
class ORMFixture:
db = Database()
class ORMGroup(db.Entity):
_table_ = 'group_list'
id = PrimaryKey(int, column='group_id')
n... |
# coding: utf-8
"""
UltraCart Rest API V2
UltraCart REST API Version 2 # noqa: E501
OpenAPI spec version: 2.0.0
Contact: support@ultracart.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and py... |
# -*- coding: utf-8 -*-
# the __all__ is generated
__all__ = []
# __init__.py structure:
# common code of the package
# export interface in __all__ which contains __all__ of its sub modules
# import all from submodule macd_factor
from .macd_factor import *
from .macd_factor import __all__ as _macd_factor_all
__all__ ... |
from engine.objects.entities.icollidable import ICollidable
from engine.objects.entities.kineticbody import KineticBody
from engine.objects.primitives.drawable import IDrawable
from engine.objects.primitives.icollider import ICollider
from engine.objects.primitives.vector2d import Vector2D, sign
class ElasticBody(Kin... |
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy
from django.core.management.base import BaseCommand
from django.conf import settings
from onadata.apps.logger.models import Instance, XForm
from onadata.libs.utils.model_tools import queryset_iterator
class Command(BaseCom... |
from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
from django.conf import settings as wrapped_settings
from . import default_settings as default_settings
class LazySettings(object):
def __getattr__(self, name):
try:
... |
class PartialParse(object):
def __init__(self, sentence):
"""Initializes this partial parse.
Your code should initialize the following fields:
self.stack: The current stack represented as a list with the top of the stack as the
last element of the list.
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import gae_form as form
import model
# Commons Validators Expressions
vemail = form.regexp("^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$", "Precisa ser um endereco de e-mail válido !.")
vdigito = form.regexp("\d+", "Precisa ser um di... |
import unittest
import json
import mock
import responses
from fbmq.fbmq import Page, LocalizedObj, SUPPORTED_API_VERS
from fbmq import template as Template
class MessengerAPIMock():
GET = responses.GET
PUT = responses.PUT
POST = responses.POST
DELETE = responses.DELETE
METHODS = [responses.GET, re... |
import logging
import random
import warnings
from multiprocessing import cpu_count
import numpy as np
import torch
from transformers import (
WEIGHTS_NAME,
AlbertConfig,
AlbertTokenizer,
BertConfig,
BertTokenizer,
DistilBertConfig,
DistilBertTokenizer,
ElectraConfig,
ElectraTokenize... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Page.site'
db.add_column('pages_page', 'site', self.gf('django.db.models.fields.relate... |
from time import sleep
def spin_the_planet():
print('\u001b[36m', """
_-o#&&*''''?d:>b\\_
_o/'`'' '',, dMF9MMMMMHo_
.o&#' `'MbHMMMMMMMMMMMHo.
.o'' ' vodM*$&&HMMMMMMMMMM?.
,' $M&ood,~'`(&##MMMMMMH\\
... |
x = set()
x.add(12)
print(x)
x.update(["Blue", "Green"])
print(x) |
#!/usr/bin/env python
import re
import fileinput
def this_line_is_useless(line):
useless_es = [
'BEGIN TRANSACTION',
'COMMIT',
'AUTOINCREMENT',
'sqlite_sequence',
'CREATE UNIQUE INDEX',
'PRAGMA foreign_keys=OFF',
]
for useless in useless_es:
if re.se... |
import config
import numpy as np
import tensorflow as tf
def get_tp_fp_fn(a, b):
a = np.equal(a, 1)
not_a = np.logical_not(a)
b = np.equal(b, 1)
not_b = np.logical_not(b)
tp = np.logical_and(a, b).sum().astype(np.float64)
fp = np.logical_and(a, not_b).sum().astype(np.float64)
fn = np.l... |
# Generated by Django 2.0.4 on 2018-08-09 06:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('schedules', '0007_auto_20180719_0054'),
]
operations = [
migrations.AlterField(
model_name='act... |
import glob
import os
import re
import sys
from binascii import a2b_hex
from tornado.httpclient import AsyncHTTPClient
from kubernetes import client
from jupyterhub.utils import url_path_join
# Make sure that modules placed in the same directory as the jupyterhub config are added to the pythonpath
configuration_dire... |
# TensorFlow external dependencies that can be loaded in WORKSPACE files.
load("//third_party/gpus:cuda_configure.bzl", "cuda_configure")
load("//third_party/tensorrt:tensorrt_configure.bzl", "tensorrt_configure")
load("//third_party:nccl/nccl_configure.bzl", "nccl_configure")
load("//third_party/mkl:build_defs.bzl", ... |
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import esb |
import getpass
"""
By default Linux
"""
main_dir = "/storage/emulated/0/"
photos_dir = [main_dir + "DCIM", main_dir + "WhatsApp/Media/WhatsApp Images"]
document_dir = [main_dir + "Download", main_dir + "Documents"]
music_dir = [main_dir + "Download", main_dir + "WhatsApp/Media/WhatsApp Audio"]
video_dir = [main_dir ... |
import argparse
import os
import torch
import torchvision.utils
from tqdm import tqdm
from .vqvae import VQVAE
from .pixelsnail import PixelSNAIL
@torch.no_grad()
def sample_model(model, device, batch, size, temperature, condition=None):
row = torch.zeros(batch, *size, dtype=torch.int64).to(device)
cache = ... |
from __future__ import unicode_literals
import boto
import sure # noqa
from moto import mock_sns_deprecated
from moto.sns.models import DEFAULT_PAGE_SIZE
@mock_sns_deprecated
def test_creating_subscription():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
... |
# -*- coding: utf-8 -*-
# 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, software... |
"""
Created on Mai 10 16:21 2019
@author: nishit
"""
import json
import os
import time
from utils_intern.constants import Constants
from utils_intern.messageLogger import MessageLogger
logger = MessageLogger.get_logger_parent()
class IDStatusManager:
@staticmethod
def read_file():
path = "/usr/src/... |
"""
ID: raadw1
LANG: PYTHON3
TASK: gift1
"""
from collections import OrderedDict
accounts = OrderedDict()
with open('gift1.in', 'r') as fin:
NP = int(fin.readline())
for i in range(NP):
accounts[fin.readline()] = 0
while True:
giver = fin.readline()
if not giver: break
m... |
#
# LibHEOM: Copyright (c) Tatsushi Ikeda
# This library is distributed under BSD 3-Clause License.
# See LINCENSE.txt for licence.
# ------------------------------------------------------------------------
import enum
import sys
import numpy as np
import scipy as sp
import scipy.sparse
import importlib
pylibheom = ... |
from ..EncoderDecoder import encode_notes_list
from ..Attributes import SCALE_DICT
from .Note import Note
class Sheet:
def __init__(self, *args):
if len(args) == 1:
sheet_obj = args[0]
if isinstance(sheet_obj, str):
self._encoded_sheet = sheet_obj
# f... |
import scrapy
import pandas as pd
import os
import requests
from bs4 import BeautifulSoup
class biznewsSpider(scrapy.Spider):
name = "biznews"
def __init__(self, *a, **kw):
super(biznewsSpider, self).__init__(*a, **kw)
path = os.path.join(os.path.expanduser("~"),"Documents","NMRQL","Scrape... |
from sympy.core.numbers import I
from sympy.core.symbol import symbols
from sympy.physics.paulialgebra import Pauli
from sympy.testing.pytest import XFAIL
from sympy.physics.quantum import TensorProduct
sigma1 = Pauli(1)
sigma2 = Pauli(2)
sigma3 = Pauli(3)
tau1 = symbols("tau1", commutative = False)
def test_Pauli(... |
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Driver for controlling the active servo v4 device."""
import time
import hw_driver
class activeV4DeviceError(hw_driver.HwDriverError):
"""Exceptio... |
# Copyright 2016-2022 Blue Marble Analytics LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Provides a service to store ROS message objects in a mongodb database in JSON.
"""
import rospy
import actionlib
import pymongo
import os
import shutil
import subprocess
from mongodb_store_msgs.msg import MoveEntriesAction, MoveEntriesFeedback
from datetime import *
... |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2020 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free... |
import os
import sys
import tempfile
import textwrap
import unittest
import shutil
import subprocess
class PabotOrderingGroupTest(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmpdir)
def _run_tests_with(self, testfile, order... |
import json
import os
import shutil
import unittest
from monty.os.path import which
from pymatgen.io.qchem.outputs import QCOutput
from atomate.qchem.firetasks.critic2 import ProcessCritic2, RunCritic2
from atomate.utils.testing import AtomateTest
__author__ = "Samuel Blau"
__email__ = "samblau1@gmail.com"
module_d... |
# Copyright 2016-2019 The Van Valen Lab at the California Institute of
# Technology (Caltech), with support from the Paul Allen Family Foundation,
# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.
# All rights reserved.
#
# Licensed under a modified Apache License, Version 2.0 (the "License");... |
import connexion
def consumer_id():
return connexion.request.headers.get('X-Consumer-ID') |
from __future__ import absolute_import, division, print_function
from libtbx import easy_pickle
from libtbx.utils import Sorry
import re
import os
from functools import cmp_to_key
from past.builtins import cmp
from six.moves import zip
class result(object):
def __init__(self, dir_name):
self.dir_name = dir_name... |
import pandas as pd
import numpy as np
import plotly
from plotly import graph_objs
class ConflictsListener():
def __init__(self, df):
# time diff to seconds
#df['diff_secs'] = df['time_diff'].dt.total_seconds()
# conflict time diff to seconds
#df['diff_secs_confl'] = np.nan
... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'MonthlyOrder.amount'
db.alter_column(u'recurring_donations_monthlyorder', 'amount', self.... |
# GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either versio... |
import RPi.GPIO as GPIO
import time
from AlphaBot2 import AlphaBot2
TRIG = 22
ECHO = 27
PWM = 50
Ab = AlphaBot2()
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(TRIG,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(ECHO,GPIO.IN)
def Distance():
GPIO.output(TRIG,GPIO.HIGH)
time.sleep(0.000015)
GPIO.output(TRIG,GP... |
import fairing
from fairing.preprocessors.base import BasePreProcessor
from fairing.builders.append.append import AppendBuilder
from fairing.deployers.job.job import Job
from fairing.deployers.tfjob.tfjob import TfJob
from fairing.constants import constants
from fairing.kubernetes import utils as k8s_utils
from fairing... |
"""empty message
Revision ID: 25a0a520d83a
Revises:
Create Date: 2021-11-12 11:45:29.153816
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '25a0a520d83a'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
__al... |
from __future__ import division
import argparse
import numpy as np
import torch
from dim_red.triplet import train_triplet
from dim_red.angular import train_angular
from dim_red.support_func import sanitize
from dim_red.data import load_dataset
if __name__ == '__main__':
parser = argparse.ArgumentParser()
d... |
"""distutils.core
The only module that needs to be imported to use the Distutils; provides
the 'setup' function (which is to be called from the setup script). Also
indirectly provides the Distribution and Command classes, although they are
really defined in distutils.dist and distutils.cmd.
"""
# created 1999/03/01,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.