text stringlengths 1 927k |
|---|
from typing import Literal, Tuple, List, Set
L1 = Literal['test']
L2 = Literal['a', 'b', 5]
tuple_one_literal: Tuple[L1] = ('test',)
tuple_one_literal_incorrect: Tuple[L1] = <warning descr="Expected type 'tuple[Literal['test']]', got 'tuple[Literal['t']]' instead">('t',)</warning>
tuple_union_literal: Tuple[L2] = ('... |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import pickle
from os.path import join as pjoin
from indra.tools import assemble_corpus as ac
from indra.tools.gene_network import GeneNetwork
import process_data, process_r3, process_sparser, process_trips
from rea... |
# SELECT statement, remove unicode characters
import sqlite3
with sqlite3.connect("new.db") as connection:
cursor = connection.cursor()
cursor.execute("SELECT firstname, lastname FROM employees")
rows_iter = iter(cursor.fetchall()) # fetchall gives a list of tuples
for firstname, lastname in row... |
import datetime
import responses
from parameterized import parameterized
from ..utils import CensysTestCase
from .utils import V1_URL
from censys.asm.client import AsmClient
from censys.asm.clouds import format_since_date
TEST_COUNT_JSON = {
"totalAssetCount": 0,
"totalNewAssetCount": 0,
"totalCloudAsset... |
"""
Oracle database backend for Django.
Requires cx_Oracle: http://cx-oracle.sourceforge.net/
"""
from __future__ import unicode_literals
import datetime
import decimal
import re
import platform
import sys
import warnings
def _setup_environment(environ):
# Cygwin requires some special voodoo to set the environm... |
# encoding: utf-8
#
# main.py
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from pytest import mark
from apogee.main import math
class TestMath(object):
"""Tests for the ``math`` function in main.py."""
... |
# DO NOT EDIT THIS FILE!
#
# This file is generated from the CDP specification. If you need to make
# changes, edit the generator and regenerate all of the modules.
#
# CDP domain: Accessibility (experimental)
from __future__ import annotations
from .util import event_class, T_JSON_DICT
from dataclasses import dataclas... |
import numpy as np
from PIL import Image, ImageFilter
class CornerCreator:
"""Create corners with a given curvature from ``0`` to ``1``.
Corners size is defined by ``corner_width``.
Type of corners are defined by ``corner_curvature``:
- ``0``: no corners,
- from ``0`` to ``0.5``: hyperbolic conv... |
# 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 required by applicable law or agree... |
from PyQt5.QtWidgets import (
QGraphicsView,
QGraphicsScene,
QGraphicsPixmapItem
)
from PyQt5 import QtCore
from PyQt5.QtGui import QPixmap, QImage, QColor
class ImageCanvas(QGraphicsView):
""" This class manages the view of the weights. """
def __init__(self):
QGraphicsView.__init__(self)
... |
from st2common.runners.base_action import Action
import json
class FilterCli(Action):
def run(self, cli_result, command, hosts, raw):
results = []
for idx, r in enumerate(cli_result):
if command in r:
output = r[command].replace('\\n', '\n')
if not raw:... |
#!/usr/bin/python
import re
import smbus
# ===========================================================================
# Adafruit_I2C Class
# ===========================================================================
class Adafruit_I2C(object):
@staticmethod
def getPiRevision():
"Gets the version number of ... |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='product-details']/h1",
'price' : "//div[@id='product-price']",
'category' : "//ol[@class='breadcrumb']/li/a",
'd... |
import datetime
import decimal
import Cocoa
from objc._pythonify import OC_PythonFloat
from PyObjCTools import Conversion
from PyObjCTools.TestSupport import TestCase
import objc
class TestConversion(TestCase):
def test_toPythonDecimal(self):
v = Cocoa.NSDecimalNumber.decimalNumberWithString_(u"42.5")
... |
### Variant_Names
alt_name_parse = {}
# Terzan
alt_name_parse = alt_name_parse | {f"Ter{i}": f"Terzan{i}" for i in range(1, 15)}
# Palomar
alt_name_parse = alt_name_parse | {f"Palomar{i}": f"Pal{i}" for i in range(1, 20)}
# Djorg
alt_name_parse = alt_name_parse | {f"Djor{i}": f"Djorg{i}" for i in range(1, 4)}
alt_nam... |
"""
PluralKit API Wrapper
~~~~~~~~~~~~~~~~~~~
A basic wrapper for the PluralKit API.
:copyright: (c) 2021-present Johnystar
:license: MIT, see LICENSE for more details.
"""
__title__ = 'pluralkit'
__author__ = 'Johnystar'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021-present Johnystar'
__version__ = '2021.01.23.... |
import random
import time
import numpy as np
import json
from pettingzoo.tests.all_modules import all_environments
from pettingzoo.classic import gin_rummy_v0
from PIL import Image
import os
import scipy.misc
import sys
import subprocess
def generate_data(nameline,module):
dir = f"frames/{nameline}/"
os.mkdir... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 14 20:21:23 2017
@author: DKIM
"""
#Run 3b- Supporting Functions
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn import feature_selection
seednumber = 319
# load data
start_year = 2014
target_year = 2018
data_train, data_test, features_trai... |
# -*- coding: utf-8 -*-
"""
SwarmOps.utils.jwt
~~~~~~~~~~~~~~
Json Web Token
:copyright: (c) 2018 by staugur.
:license: MIT, see LICENSE for more details.
"""
import hashlib
import hmac
import time
import datetime
import random
import base64
import json
from config import SYSTEM
class JWTExcept... |
"""Add JSON schema table
Revision ID: 022118518e99
Revises: 4fef0af39a20
Create Date: 2019-02-28 07:25:25.613054
"""
# revision identifiers, used by Alembic.
revision = "022118518e99"
down_revision = "4fef0af39a20"
branch_labels = None
depends_on = None
from alembic import op
from sqlalchemy.orm.session import Sess... |
# Copyright (c) 2015-2017 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2015 Florian Bruhin <me@the-compiler.org>
# Copyright (c) 2016 Ashley Whetter <ashley@awhetter.co.uk>
# Copyright (c) 2018 ssolanki <sushobhitsolanki@gmail.com>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.htm... |
"""An implementation of the CASTER model."""
from .base import UnimplementedModel
__all__ = [
"CASTER",
]
class CASTER(UnimplementedModel):
"""An implementation of the CASTER model.
.. seealso:: https://github.com/AstraZeneca/chemicalx/issues/15
""" |
"""
Django settings for record_shop project.
Generated by 'django-admin startproject' using Django 4.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import os... |
"""
References:
https://github.com/lohriialo/photoshop-scripting-python/blob/master/ActiveLayer.py
"""
import photoshop.api as ps
app = ps.Application()
if app.documents.length < 1:
docRef = app.documents.add()
else:
docRef = app.activeDocument
if docRef.layers.length < 2:
docRef.artLayers.add()
ac... |
import numpy as np
buf = raw_input()
a = float(buf.split(" ")[0])
b = float(buf.split(" ")[1])
c = float(buf.split(" ")[2])
delta = (b**2)-(4*a*c)
if delta < 0 or a == 0.0:
print "Impossivel calcular"
else:
x1 = (-b + np.sqrt(delta))/(2*a)
x2 = (-b - np.sqrt(delta))/(2*a)
print "R1 =", format(x1,".5f"... |
from rest_framework import serializers
from assessments.models import Questionnaire, Author
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = '__all__'
class QuestionnaireSerializer(serializers.ModelSerializer):
class Meta:
model = Questionnaire
... |
# Copyright 2018 The TensorFlow Probability 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... |
n = 8
grid = [[['.' for _ in range(n)] for _ in range(n)] for _ in range(n)]
grid[n // 2] = [list(l.strip()) for l in open('input_v2.txt', 'r').readlines()]
dirs = [(x, y, z) for x in [-1, 0, 1] for y in [-1, 0, 1] for z in [-1, 0, 1]]
dirs.remove((0, 0, 0))
def cycle(i, n_new, new_grid):
active_count = 0
for x in... |
from .bot import Client |
#!/usr/bin/env python3
import utils, os, random, time, open_color, arcade
utils.check_version((3,7))
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Sprites Example"
class Emote(arcade.Sprite):
def __init__(self):
super().__init__()
self.frequency = 1 #update every second
... |
# -*- coding: utf-8 -*-
"""
Converts cell separated regular Python scripts to Jupyter notebooks.
With Spyonde, it is possible to use any IDE/editor to create
Jupyter notebooks, presenatations and lecture notes.
"""
# pylint: disable=line-too-long
import argparse
import json
import os
import re
import tokenize
_... |
"""Common pathname manipulations, JDK version.
Instead of importing this module directly, import os and refer to this
module as os.path.
"""
# Incompletely implemented:
# islink -- How?
# ismount -- How?
# splitdrive -- How?
# normcase -- How?
# Missing:
# sameopenfile -- Java doesn't have fstat nor file descriptor... |
import argparse
import time
import pathlib
import warnings
from datetime import datetime
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
from plotting.aggregators import MeanStd, MeanMinMax
from plotting.log_parsers import EvaluationParser
from plotting.plot_test_evaluation import ... |
"""
Django settings for pictures project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib... |
from __future__ import absolute_import
from Component import *
def test_default_values():
""" Tests the initial constructor values """
# Arrange
expected_name = ""
expected_footprint = ""
expected_reference = ""
expected_value = ""
expected_quantity = 1
# Act
component = KiCadComponent()
# Asser... |
import os
from huoguoml.constants import HUOGUOML_DATABASE_FILE, HUOGUOML_DEFAULT_ZIP_FOLDER
class Service(object):
def __init__(self, artifact_dir: str):
self.artifact_dir = os.path.realpath(artifact_dir)
self.zip_dir = os.path.join(self.artifact_dir, HUOGUOML_DEFAULT_ZIP_FOLDER)
if no... |
#!/usr/bin/env python
# Copyright 2019 Google LLC
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import codecs
import math
import os
import re
import sys
import yaml
sys.path.insert(0, os.path.dirname(os.path.abspath(... |
# 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... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 11:41:44 2018
@author: MichaelEK
"""
import os
import argparse
import types
import pandas as pd
import numpy as np
from pdsql import mssql
from datetime import datetime
import yaml
import itertools
import lowflows as lf
import util
pd.options.display.max_columns = 10
... |
# -*- coding: utf-8 -*-
from datetime import datetime
import json, time, ntpath
def loggedIn(func):
def checkLogin(*args, **kwargs):
if args[0].isLogin:
return func(*args, **kwargs)
else:
args[0].callback.default('You want to call the function, you must login to LINE')
r... |
# Generated by Django 3.2.7 on 2021-10-26 21:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('geo', '0005_auto_20211026_1853'),
]
operations = [
migrations.AlterField(
model_name='subregionsrelation',
name='geo... |
from abaqusConstants import *
class Crack:
"""The Crack object is the abstract base type for ContourIntegral and future crack objects.
Attributes
----------
name: str
A String specifying the repository key.
suppressed: Boolean
A Boolean specifying whether the crack is suppressed o... |
import signal
import sys
import threading
from time import sleep
import zmq
context = zmq.Context()
client = context.socket(zmq.REQ)
def signal_handler(signal, frame):
print('shutdown')
sys.exit(0)
def main():
client.connect("tcp://172.18.0.11:5091")
client.send_string("")
# Get the reply.
... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.bitfinex import bitfinex
import hashlib
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import Authe... |
"""
模块库
"""
import inspect
def get_curent_module_classes(module):
"""
获取制定模块的所有类
:param module: 模块
:return: 类的列表
"""
classes = []
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj):
classes.append(obj)
return classes
# print(inspect.getmembers... |
#!usr/bin/env python3
# @File:Scrawl_Xiamimusic.py
# @Date:2018/5/10
# Author:Cat.1
import sys
sys.path.append('..')
import project.Config.config
import project.Scrawl.XiamiMusic.XiamiHelper
from project.Module import ReturnStatus
from project.Module import RetDataModule
import requests, re, json
xiami_search_url_f... |
#!/usr/bin/env python3
from errbot import BotPlugin, botcmd
import telnetlib
class Weatherinfo(BotPlugin):
"""grab short weather informations around the globe
"""
@botcmd(split_args_with=None)
def weather(self, msg, args):
"""(!weather berlin) grab weather information for cities an regions
... |
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from lfs.addresses.models import Address
from lfs.catalog.models import Category
from lfs.catalog.models import Product
import lfs.marketing.utils
from lfs.marketing.models import Topseller
from lfs.marketing.utils impor... |
"""
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
"""
__author__ = 'Danyang'
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
c... |
import torch
import matplotlib.pyplot as plt
import numpy as np
import os
import shutil
from combine2d.core import gis, test_cases
from combine2d.core.utils import NonRGIGlacierDirectory
from combine2d.core.first_guess import compile_first_guess
from combine2d.core.inversion import InversionDirectory
from combine2d.co... |
from __future__ import absolute_import
from sentry.app import quotas
from sentry.api.serializers import Serializer, register, serialize
from sentry.auth import access
from sentry.models import (
Organization, OrganizationAccessRequest, OrganizationOption, Team,
TeamStatus
)
@register(Organization)
class Orga... |
from panda3d.core import *
from panda3d.physics import *
from direct.interval.IntervalGlobal import *
from direct.particles import ParticleEffect, Particles, ForceGroup
from EffectController import EffectController
from PooledEffect import PooledEffect
class IceCream(PooledEffect, EffectController):
def __init__(... |
import dgl
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.multiprocessing as mp
import dgl.function as fn
import dgl.nn.pytorch as dglnn
import time
import argparse
import tqdm
import traceback
from _thread import start_new_thread
fro... |
# Generated by Django 3.1.3 on 2020-12-28 01:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0006_auto_20201228_0142'),
]
operations = [
migrations.AddField(
model_name='user',
name='is_email_verified'... |
# 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 u... |
from torch.testing import assert_allclose
from transformers import AutoModel
from allennlp.common.testing import ModelTestCase
from allennlp.data import Vocabulary
from allennlp_models import vision # noqa: F401
from tests import FIXTURES_ROOT
class TestVEVilbert(ModelTestCase):
def test_model_can_train_save_... |
#!/usr/bin/env python3
from setuptools import setup
with open('requirements.txt') as f:
install_requires = f.readlines()
setup(name='OnionPerf',
version='0.3',
description='A utility to monitor, measure, analyze, and visualize the performance of Tor and Onion Services',
author='Rob Jansen',
... |
from enum import auto
from typing import Any, Callable, Dict, Optional
import torch
import torch.nn.functional as F
from ..config.config import Config, ConfigEnum
from ..data.labels import LabelType
from ..utils.tensor import prepare_tensor
from .quaternion import qconjugate, qmult
MetricFunction = Callable[[torch.... |
from abc import abstractmethod
class Incoming:
tokens = []
@abstractmethod
def dispatch(self, session, buffer_array): raise NotImplementedError |
# -*- coding: utf-8 -*-
from six.moves.urllib.parse import urlencode, parse_qs
import pytest
from sqlalchemy import create_engine, Column, Integer, DateTime, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from flask import Blueprint, ma... |
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th... |
import urllib2
from bs4 import BeautifulSoup
def crawl_web(seed): # returns index, graph of outlinks
print "inside crawl_web"
tocrawl = [seed]
crawled = []
graph = {} # <url>:[list of pages it links to]
index = {}
while tocrawl:
page = tocrawl.pop()
if page not in crawled:
... |
from flask_pymongo import PyMongo
class TeachersMongoDBRepository():
def __init__(self, application):
self.mongo = PyMongo(application)
def create(self, teacher):
uid = self.mongo.db.teachers.insert_one({
"username": teacher.username,
"password": teacher.password
}).inserted_id
teache... |
from pylivetrader.api import order_target_percent, record, symbol
import pandas as pd
def initialize(context):
# The initialize method is called at the very start of your script's
# execution. You can set up anything you'll be needing later here. The
# context argument will be received by all pylivetrader... |
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved.
from .job import GenericImageDatasetJob
__all__ = ['GenericImageDatasetJob'] |
"""
test outputs
"""
from nose.tools import ok_, eq_
from carousel.core.outputs import Output
from carousel.tests import PROJ_PATH
import os
def test_outputs_metaclass():
"""
Test Output Sources
"""
class OutputTest1(Output):
class Meta:
outputs_file = 'pvpower.json'
... |
import psycopg2
from django.db.models import (
CharField,
Expression,
Field,
FloatField,
Func,
Lookup,
TextField,
Value,
)
from django.db.models.expressions import CombinedExpression
from django.db.models.functions import Cast, Coalesce
class SearchVectorExact(Lookup):
lookup_name... |
import torch
import torch.nn as nn
class ConditionalInstanceNorm2d(nn.Module):
"""Conditional Instance Normalization
Parameters
num_features – C from an expected input of size (N, C, H, W)
num_classes – Number of classes in the datset.
bias – if set to True, adds a bias term to the emb... |
import logging
from typing import TYPE_CHECKING
from dask import delayed
from nvtx import annotate
from dask_sql.datacontainer import DataContainer
from dask_sql.physical.rel.base import BaseRelPlugin
from dask_sql.utils import convert_sql_kwargs, import_class
if TYPE_CHECKING:
import dask_sql
from dask_sql.... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.mipav.developer import JistLaminarVolumetricLayering
def test_JistLaminarVolumetricLayering_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True... |
"""Tests for the Device Registry."""
import pytest
from homeassistant.helpers import device_registry
def mock_registry(hass, mock_entries=None):
"""Mock the Device Registry."""
registry = device_registry.DeviceRegistry(hass)
registry.devices = mock_entries or []
async def _get_reg():
return ... |
# -*- coding: utf-8 -*-
"""Crypt_LSTM
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1guzTMibpzWywlckt9xu2gazsb-jifVDG
"""
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import... |
from splinter import Browser
from bs4 import BeautifulSoup
import pandas as pd
import time
def init_browser():
executable_path = {'executable_path': 'chromedriver.exe'}
browser = Browser('chrome', **executable_path, headless=False)
return browser
def marsNews():
browser = init_browser()
url = 'h... |
#! /usr/bin/env python3
fin = open('../../PrependInit/PrependInit.sim/sim_1/behav/result.txt', 'r')
fref = open('ref.txt', 'r')
line_no = 1
lin = fin.readline()
ok = True
while lin:
# 結果を読み込む
results = lin[:-1].split(' ')
tdata = int(results[0], 16)
# 比較する値を読み込み
lref = fref.readline()
if not... |
import numpy as np
from PyCommon.modules.Math import mmMath as mm
import math
import os
import bvh
from scipy.spatial.transform import Rotation
class MakeBvh(object):
def __init__(self):
self.skel = None
self.joint_name = None
def angle2bvh(self):
file_dir = 'data/mocap/movingcam/'
... |
from polynomial import PolynomialP
class QAP:
def __init__(self, circuit):
self.inputs = circuit.inputs
self.L = [PolynomialP.interpolate(l) for l in list(zip(*circuit.L))]
self.R = [PolynomialP.interpolate(r) for r in list(zip(*circuit.R))]
self.O = [PolynomialP.interpolate(o) for... |
# -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from... |
demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2
# %% Do SA
from sko.SA import SA
sa = SA(func=demo_func, x0=[1, 1, 1], T_max=1, T_min=1e-9, L=300, max_stay_counter=150)
best_x, best_y = sa.run()
print('best_x:', best_x, 'best_y', best_y)
# %% Plot the result
import matplotlib.pyplot as plt
import pa... |
def rchop(s, ending):
return s[: -len(ending)] if s.endswith(ending) else s
def lchop(s, beginning):
return s[len(beginning) :] if s.startswith(beginning) else s
def ordinal_en(n: int):
# https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement
return f'{n}{"tsnrhtdd"[(n//10%10!=1)*(n... |
import cgi
import datetime
import urllib
import urlparse
from django.conf import settings
from django.template import defaultfilters
from django.utils.html import strip_tags
from jingo import register
import jinja2
from .urlresolvers import reverse
# Yanking filters from Django.
register.filter(strip_tags)
registe... |
#!/usr/bin/env python3
# Copyright (c) 2016-2019 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 processing of feefilter messages."""
from decimal import Decimal
import time
from test_framework... |
#!/usr/bin/env python
import StringIO
from operator import truth
from Bio import trie
trieobj = trie.trie()
trieobj["hello"] = 5
trieobj["he"] = 7
trieobj["hej"] = 9
trieobj["foo"] = "bar"
k = trieobj.keys()
k.sort()
print k # ["foo", "he", "hej", "hello"]
print trieobj["hello"] ... |
from jax.base.applets.jax_applet import JaxApplet
from jax.base.applets.real_time_plot_applet import RealTimePlotApplet
from jax.base.environments.jax_environment import JaxEnvironment
from jax.base.environments.sinara_environment import SinaraEnvironment
from jax.base.experiments.jax_experiment import JaxExperiment
fr... |
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from dataclasses import dataclass
from datetime import datetime
from functools import partial
from gql.gql.datetime_utils import DATETIME_FIELD
from numbers import Number
from typing import Any, Callable, List, Mapping, Optional
from dataclasses_j... |
"""Tests the activity class and its operations."""
import os
import builtins
from rever import vcsutils
from rever.activity import Activity, activity
def do_tryptophan():
with open('tryptophan.txt', 'w') as f:
f.write('5-HTP\n')
vcsutils.track('tryptophan.txt')
vcsutils.commit("seratonin")
def... |
# -*- Python -*-
#
#
# Jiao Lin <jiao.lin@gmail.com>
#
from . import mcvine, click
@mcvine.group()
def bash():
return
@bash.command()
def complete():
"Instructions for bash complete support"
print("""
To enable bash auto complete for mcvine command, run
$ eval "$(_MCVINE_COMPLETE=source mcvine)"
""")
... |
from __future__ import print_function
import os
import tarfile
import requests
from warnings import warn
from zipfile import ZipFile
from bs4 import BeautifulSoup
from os.path import abspath, isdir, join, basename
class GetData(object):
"""
Download CycleGAN or Pix2Pix Data.
Args:
technique : str
One of:... |
#!/usr/bin/env python
#
# Copyright 2017-present MongoDB, 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 applicab... |
import datetime
import threading
import json
from kafka import KafkaConsumer, KafkaProducer
import time
import logging
import sys
import types
from baskerville.db import set_up_db
from baskerville.models.config import KafkaConfig
from baskerville.models.ip_cache import IPCache
from baskerville.util.elastic_writer impo... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import gym
from a2c_ppo_acktr.distributions import Bernoulli, Categorical, DiagGaussian
from a2c_ppo_acktr.utils import init
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
class Policy(nn... |
"""
Copy this file to config.py and modify as needed.
"""
import os
from os.path import join
import rlkit
"""
`doodad.mount.MountLocal` by default ignores directories called "data"
If you're going to rename this directory and use EC2, then change
`doodad.mount.MountLocal.filter_dir`
"""
# The directory of the project,... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from . import __version__ as app_version
app_name = "meeting"
app_title = "Meeting"
app_publisher = "Frappe"
app_description = "meeting details"
app_icon = "octicon octicon-file-directory"
app_color = "grey"
app_email = "himan@gmail.com"
app_license = "MI... |
# -*- coding: utf-8 -*-
# Scrapy settings for cercanias project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/late... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
__all__ = ["DeviceSafety"]
_resource = _ValueSet.parse_file(Path(__file__).with_suffix(".json"))
class DeviceSafety(ValueSet):
"""
Device safety
Codes used to identify medical devi... |
# Author: Ryan West (ryan.west@sovrin.org)
import json
import rocksdb
import os
from indy import ledger, pool, wallet
from transaction import Transaction
class TxnDoesNotExistException(Exception):
pass
class InvalidLedgerResponseException(Exception):
pass
# TODO: add option to download specific set of txn... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import *
import torch.nn.init as init
import data
from tools.logger import *
from transformer.Models i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import professor,department,education,award_fellowships,award_achievement,experience,project,publication_books,publication_conferences,publication_journals,publication_thesis,student_completed,student_ongoing
from django.contrib import admin
... |
from leetcode_python.src.algorithms.tree.node import Node
class MaximumDepth:
def max_depth(self, root: Node):
if not root:
return 0
left = self.max_depth(root.left)
right = self.max_depth(root.right)
return max(left, right) + 1 |
"""
Runtime functionaly (uses template context).
"""
from cgi import escape as xml_escape
class Undefined(object):
"""Undefined object."""
def __nonzero__(self):
return False
def __unicode__(self):
raise Exception("UNDEFINED")
UNDEFINED = Undefined()
Undefined = None
def Var(name, defaul... |
# Copyright 2018 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.