text stringlengths 2 999k |
|---|
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
tree = Flask(__name__, static_url_path='/static')
tree.config.from_object('config')
db = SQLAlchemy(tree)
import palm_tree.coconut_1.controller_1
|
#!/usr/bin/python
DOCUMENTATION = '''
---
module: ec2_asg_target_groups
short_description: Configure target groups on an existing auto scaling group
description:
- Configure the specified target groups to be attached to an auto scaling group
- The auto scaling group must already exist (use the ec2_asg module)
ver... |
import discord
from discord.ext import commands
from Cogs.BaseCog import BaseCog
from Util import ReactionManager
class ReactionHandler(BaseCog):
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
await ReactionManager.on_reaction(self.bot, payload... |
## @file
# This is an XML API that uses a syntax similar to XPath, but it is written in
# standard python so that no extra python packages are required to use it.
#
# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available un... |
#!/usr/local/miniconda2/bin/python
# _*_ coding: utf-8 _*_
"""
@author: MarkLiu
@time : 17-7-28 下午4:26
"""
import os
import sys
module_path = os.path.abspath(os.path.join('..'))
sys.path.append(module_path)
import pandas as pd
from conf.configure import Configure
result_files = os.listdir('./model_results/')
resu... |
"""Run limitation for products
Revision ID: bb5278995f41
Revises: 150800b30447
Create Date: 2018-03-01 15:38:41.164141
"""
# revision identifiers, used by Alembic.
revision = 'bb5278995f41'
down_revision = '150800b30447'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgr... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 applic... |
from code.util.db import Submission, User, Contest
from code.generator.lib.htmllib import *
from code.generator.lib.page import *
import logging
from operator import itemgetter
from code.util import register
import time
import operator
def correctLog(params, user):
contest = Contest.getCurrent() or Contest.getPast... |
from demo_utils.generic_demo import Demo
from demo_utils.general import SUPPORTED_DATASETS
# import ipywidgets as widgets
from demo_utils.learning import get_model
from demo_utils.general import get_data
from demo_utils.learning import get_sampling_model_scores
from demo_utils.learning import get_non_sampling_model_sco... |
'''
Given an "out" string length 4, such as "<<>>", and a word,
return a new string where the word is in
the middle of the out string, e.g. "<<word>>".
'''
def make_out_word(out, word):
return out[:2] + word + out[-2:]
# make_out_word('<<>>', 'Yay') → '<<Yay>>'
# make_out_word('<<>>', 'WooHoo') → '<<WooHoo>>'
# ... |
# Generated by Django 2.2.7 on 2019-11-15 12:37
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Accident',
... |
# Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn', 'boromir', 'legolas', 'gimli', 'gandalf']
# Use filter() to apply a lambda function over fellowship: result
result = filter(lambda member: len(member)>6, fellowship)
# Convert result to a list: result_list
result_li... |
import json
import yaml
import pytest
from hello_world import lambda_function
@pytest.fixture()
def apigw_event():
""" Generates API GW Event"""
return {
"servicename":"hackservice",
"namespace":"stratos",
"body": '{ "test": "body"}',
"resource": "/{proxy+}",
"reques... |
# TensorFlow external dependencies that can be loaded in WORKSPACE files.
load("//third_party/gpus:cuda_configure.bzl", "cuda_configure")
load("//third_party/gpus:rocm_configure.bzl", "rocm_configure")
load("//third_party/tensorrt:tensorrt_configure.bzl", "tensorrt_configure")
load("//third_party/nccl:nccl_configure.b... |
# Copyright 2018 The Forseti Security 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 ap... |
import torch,os
import torch.nn as nn
import torch.utils.data as data
from netp import unetpp
import torch.optim as optim
from torchvision.transforms import Compose, CenterCrop, Normalize
from torchvision.transforms import ToTensor, ToPILImage
from torchvision.utils import save_image
import PIL.Image as pimg
... |
import gym
from universe import envs, spaces
from universe.wrappers import gym_core_sync
from universe.wrappers.action_space import SafeActionSpace
from universe.wrappers.gym_core import GymCoreAction, GymCoreObservation, CropAtari
from universe.wrappers.blocking_reset import BlockingReset
from universe.wrappers.diagn... |
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class AmazonReviewsScrapingItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
|
import tensorflow as tf
import os
import zipfile
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
DESIRED_ACCURACY = 0.999
!wget --no-check-certificate \
"https://storage.googleapis.com/laurencemoroney-blog.appspot.com/happy-or-sad.zip" \
-O ... |
#A = [1, 3, 6, 3, 2, 3, 6, 8, 9, 5]
A = [2, 1, 1]
#A = [2, 3, 1, 1, 4]
'''
counter = 0
mid_max = A[0]
for i in range(1, n-1):
if mid_max >= n-1:
counter += 1
break
mid_max = max(A[i+1:A[i]+1])
'''
counter = 0
mid_max = A[0]
n = len(A)
i = 0
while i < n:
#print(mid_max, ":",n-i)
print(A[i... |
from __future__ import annotations
import asyncio
import h2
import h11
import pytest
import wsproto
from hypercorn.asyncio.tcp_server import TCPServer
from hypercorn.config import Config
from .helpers import MemoryReader, MemoryWriter
from ..helpers import SANITY_BODY, sanity_framework
@pytest.mark.asyncio
async d... |
from django.utils.version import get_version
VERSION = (3, 2, 8, 'final', 0)
__version__ = get_version(VERSION)
def setup(set_prefix=True):
"""
Configure the settings (this happens as a side effect of accessing the
first setting), configure logging and populate the app registry.
Set the thread-local... |
import argparse
import os
import json
import running_utils
def main():
# read the parameter argument parsing
parser = argparse.ArgumentParser(
description='Create a list of experiments')
parser.add_argument('nas_dir', help="the path of the shared nas folder")
parser.add_argument('done_filename... |
# Kivy
from kivy.app import App
from kivy.lang import Builder
# Kivy MapView
from kivy.garden.mapview import MapView, MapMarkerPopup
# Kivy properties
from kivy.properties import NumericProperty, StringProperty
class Content(MapView):
def build(self):
return self
class POIMarkerPopup(MapMarkerPopup):
... |
# Copyright 2016 Huawei, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-07 04:42
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0017_delete_region'),
]
operations = [
migrations.Add... |
import math
import time
import numpy as np
import torch
from transformers import BertTokenizer, BertModel, BertConfig, BertForMaskedLM
from transformers import GPT2Tokenizer, GPT2LMHeadModel
import random
from nltk.tokenize.treebank import TreebankWordDetokenizer
from InfillingModels import RerankingLM
from helper impo... |
#!/usr/bin/env python
"""
This is a test module for finding prime numbers.
"""
_course = 'Python Programming'
def is_prime(n):
is_prime = True
def is_divisible(n,divisor):
if n<2*divisor: return False
if n%divisor==0: return True
else:
divisor += 1
re... |
"""
Gateway module - this module should be ignorant of Oscar and could be used in a
non-Oscar project. All Oscar-related functionality should be in the facade.
"""
import logging
from django.conf import settings
from django.core import exceptions
from paypal import gateway
from paypal.payflow import codes, models
l... |
from lxml import html as lhtml
from urllib import urlopen
from twisted.internet import defer, reactor
from eizzek.lib.decorators import plugin
URL = 'http://stackoverflow.com/'
TAG_URL = 'http://stackoverflow.com/questions/tagged/%s'
@plugin(r'^stackoverflow ?(?P<limit>\d+)? ?(?P<tag>[a-zA-Z0-9\+\#\-\.]+)?$')
def ... |
#!/usr/bin/env python
# Copyright (c) 2013-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from __future__ import division,print_function,unicode_literals
import biplist
from ds_store import DSStore... |
""" This module provides way to convert a Python value into an ast. """
import gast as ast
import numpy as np
import numbers
# Maximum length of folded sequences
# Containers larger than this are not unfolded to limit code size growth
MAX_LEN = 2 ** 8
class ConversionError(Exception):
""" Exception raised whe... |
import pytest
pytestmark = [pytest.mark.django_db]
@pytest.fixture(autouse=True)
def set_main_website(settings):
settings.FRONTEND_URL = 'https://test.mocked'
def test(mixer):
course = mixer.blend('products.Course', slug='tst-slug')
assert course.get_absolute_url() == 'https://test.mocked/courses/tst-... |
"""
Migration script to add the tool_versions column to the repository_metadata table.
"""
import datetime
import logging
import sys
from sqlalchemy import Column, MetaData, Table
# Need our custom types, but don't import anything else from model
from galaxy.model.custom_types import JSONType
now = datetime.datetime... |
# -*- coding: utf-8 -*-
"""CIT vector classifier.
Continuous Interval Tree aka Time Series Tree (TST), base classifier originally used
in the TimeSeriesForest interval based classification algorithm.
"""
__author__ = ["Matthew Middlehurst"]
__all__ = ["ContinuousIntervalTree"]
import math
import sys
import numpy as... |
from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "SRI"
addresses_name = (
"2021-03-09T23:18:28.806724/South Ribble polling_station_export-2021-03-09.csv"
)
stations_name = (
"2021-03-09T23:18:28.806724/South Rib... |
from setuptools import setup, find_packages
import os
import shutil
# Change this to True if you want to include the tests and test data
# in the distribution.
include_tests = False
try:
# This deals with a bug where the tests aren't excluded due to not
# rebuilding the files in this folder.
shutil.rmtree... |
# -*- coding: utf-8 -*-
# (c) 2019 Andrew Piechocki <apiechocki@dunlapcodding.com>
import logging
from uspto.oac.document import UsptoOfficeActionCitationsDocument
from uspto.util.client import UsptoGenericBulkDataClient, download_and_print
logger = logging.getLogger(__name__)
class UsptoOfficeActionCitationsClient(U... |
#!/usr/bin/env python
# coding:utf-8
#2015-8-22, because i can't find stable and fast relay server ( or i will need to
#buy a vps for myself ), so i pause this project
#todo: -relay server-
# | |
#socks5 - client1 client2 - socks5 relay
#ok todo todo ok
... |
import boto3
exceptions = boto3.client('application-autoscaling').exceptions
ConcurrentUpdateException = exceptions.ConcurrentUpdateException
FailedResourceAccessException = exceptions.FailedResourceAccessException
InternalServiceException = exceptions.InternalServiceException
InvalidNextTokenException = exceptions.I... |
# Copyright (c) 2011 Zadara Storage Inc.
# Copyright (c) 2011 OpenStack Foundation
# Copyright 2011 University of Southern California
# 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
#
... |
import pytest
from asynctest import mock as async_mock
from aries_cloudagent.connections.models import connection_target
from aries_cloudagent.connections.models.diddoc import (
DIDDoc,
PublicKey,
PublicKeyType,
Service,
)
from aries_cloudagent.messaging.base_handler import HandlerException
from aries_... |
from collections import namedtuple
def struct(*keys):
class _structBase:
# __slots__ = keys
def __init__(self, **kwargs):
self.__dict__.update((k, None) for k in keys if k not in kwargs)
self.__dict__.update(kwargs)
return _structBase
class StageInfo(struct('code', 'i... |
"""Utilities related to importing modules and symbols by name."""
import importlib
import os
import sys
import warnings
from contextlib import contextmanager
from importlib import reload
from kombu.utils.imports import symbol_by_name
#: Billiard sets this when execv is enabled.
#: We use it to find out the name of th... |
"""
websocket - WebSocket client library for Python
Copyright (C) 2010 Hiroki Ohtani(liris)
This library 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 Software Foundation; either
version 2.1 of the L... |
constants.physical_constants["quantum of circulation times 2"] |
from .region import Region
from .attack_attribute import AttackAttribute
from .monster_type import MonsterType
from .collab import Collab
class EnemySkillInstance:
def __init__(self, enemy_skill_id, ai, rnd):
self.enemy_skill_id = enemy_skill_id
self.ai = ai
self.rnd = rnd
def to_json... |
import nltk
#
# User stemmer to nomalize text
#
class IndexedText(object):
def __init__(self, stemmer, text):
self.mText = text
self.mStemmer = stemmer
self.mIndex = nltk.Index((self.stem(word), i)
for (i, word) in enumerate(text))
def concordance(sel... |
from django.contrib import admin
from .models import Group, GroupUser
class GroupUserInline(admin.TabularInline):
model = GroupUser
raw_id_fields = ('user',)
class GroupAdmin(admin.ModelAdmin):
raw_id_fields = ('users',)
ordering = ('name',)
list_display = ('name', 'rules', 'notes')
inlines... |
import os, sys
sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics.context import *
from nodebox.graphics import *
# Generates sculptures using a set of mathematical functions.
# Every iteration adds a certain value to the current coordinates.
# Rewriting this program to use transforms is left as an exe... |
# coding=utf-8
# Copyright 2021 The Uncertainty Baselines 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 ap... |
"""
This is the main entrypoint of code.
"""
import sys
import lib.summary as summary
import lib.aws_comprehend as aws_comprehend
import requests
IDENTITY={}
try:
IDENTITY = json.loads(requests.get('http://169.254.169.254/latest/dynamic/instance-identity/document').json())
except Exception as ex:
IDENTITY={
"v... |
"""Coverage controllers for use by pytest-cov and nose-cov."""
import contextlib
import copy
import functools
import os
import random
import socket
import sys
import coverage
from coverage.data import CoverageData
from .compat import StringIO
from .embed import cleanup
class _NullFile:
@staticmethod
def wri... |
from itertools import combinations
with open("input", "r") as f:
inp = list((map(int, f.read().rsplit())))
def sum_array(inp, i, r):
return [i+j for i, j in combinations(inp[i-25 : i], r)]
def first_invalid(inp):
for i in range(25, len(inp)):
if inp[i] not in sum_array(inp, i, 2):
r... |
#!/usr/bin/env python
'''
A solution to a ROSALIND bioinformatics problem.
Problem Title: Computing GC Content
Rosalind ID: GC
Rosalind #: 005
URL: http://rosalind.info/problems/gc/
'''
from scripts import ReadFASTA
def max_gc_content(seq_list):
gc_content = lambda seq: sum([100.0 for base in seq if base in ('G',... |
"""
WSGI config for jacob_game_34449 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/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJA... |
import asyncio
import ipaddress
import logging
import random
import signal
import traceback
from pathlib import Path
from typing import Any, Dict, List
import aiosqlite
from dnslib import A, AAAA, SOA, NS, MX, CNAME, RR, DNSRecord, QTYPE, DNSHeader
from chinilla.util.chinilla_logging import initialize_logging
from ch... |
from . import api, Hikari, exceptions
import requests,logging,os,sys,json,asyncio
import heapq
class Fracture(Hikari.Hikari):
def __init__(self,*args, **kwargs):
return super().__init__()
|
import numpy as np
rslt_binomial_0 = np.array([
0, 6.618737, 0.004032037, 0.01433665, 0.01265635, 0.006173346, 0.01067706])
rslt_binomial_1 = np.array([
0, 1.029661, 0.02180239, 0.07769613, 0.06756466, 0.03156418, 0.05851878])
rslt_binomial_2 = np.array([
0, 0.1601819, 0.07111087, 0.2544921, 0.2110318, 0... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^setting', views.setting),
url(r'^gradebook', views.gradebook),
url(r'^syllabus', views.syllabus),
url(r'^problem/(?P<problem_id>[0-9]+)/$', views.problem),
url(r'^problemlist/$', views.problem_list),
url(r'^problem/$', views.problem_list... |
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Factory method for easily getting imdbs by name."""
__sets = {}
fr... |
class NoSuchPointError(ValueError):
pass
class Point(tuple):
"""
A point on an elliptic curve. This is a subclass of tuple (forced to a 2-tuple),
and also includes a reference to the underlying Curve.
This class supports the operators ``+``, ``-`` (unary and binary) and ``*``.
:param x: x c... |
"""Definition of the road.sections module.
Collect classes and functions which should be included in the road.sections module.
If these imports are rearranged cyclic imports may occur. To prevent this:
isort:skip_file
"""
from collections import defaultdict
class ID:
"""Container of all class ids.
Every k... |
# --------------
import pandas as pd
from collections import Counter
# Load dataset
data = pd.read_csv(path)
print(data.isnull().sum())
data.describe()
# --------------
import seaborn as sns
from matplotlib import pyplot as plt
sns.set_style(style='darkgrid')
# Store the label values
label = data['Activity']
sns.... |
import numpy as np
import random
from nltk.corpus import wordnet as wn
import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('action', '', '')
def get_word(vocab=None, action = None, this_word=None):
if FLAGS.action == 'no_up' and action == 2:
return vocab.word2id(this_word)
... |
"""
Same as fork-server.py, but use the Python signal module to avoid keeping
child zombie processes after they terminate, instead of an explicit reaper
loop before each new connection; SIG_IGN means ignore, and may not work with
SIG_CHLD child exit signal on all platforms; see Linux documentation for more
about the r... |
from djmodels.core.management.base import BaseCommand
class Command(BaseCommand):
def add_arguments(self, parser):
subparsers = parser.add_subparsers()
parser_foo = subparsers.add_parser('foo')
parser_foo.add_argument('bar', type=int)
def handle(self, *args, **options):
self.... |
#!/usr/bin/env python
"""Configuration parameters for the data stores."""
from grr.lib import config_lib
config_lib.DEFINE_integer("Datastore.maximum_blob_size",
15*1024*1024,
"Maximum blob size we may store in the datastore.")
config_lib.DEFINE_string("Datastore.s... |
import datetime
from unittest import mock
import jwt
import pytest
from lms.models import GradingInfo, HGroup
from lms.resources import LTILaunchResource
from lms.resources._js_config import JSConfig
from lms.services import ConsumerKeyError, HAPIError
class TestJSConfig:
"""General unit tests for JSConfig."""
... |
# -*- coding: utf-8 -*-
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time, unittest
def is_alert_present(wd):
try:
wd.switch_to_alert().text
return True
except:
return False
class test_authentication_... |
import btk
import unittest
import numpy
class ForcePlatformTypesTest(unittest.TestCase):
def test_ForcePlatformType1(self):
pf = btk.btkForcePlatformType1()
self.assertEqual(pf.GetType(), 1)
self.assertEqual(numpy.all(pf.GetOrigin() == numpy.zeros((3,1))), True)
self.assertEqual(pf.... |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from sanic.request import Request
from sanic.response import BaseHTTPResponse
from asyncio import CancelledError, sleep
from enum import Enum
from sanic.compat import Header
from sanic.exceptions import (
He... |
# -*- coding: utf-8 -*-
# copy fom wikipedia
zh2Hant = {
'呆': '獃',
"打印机": "印表機",
'帮助文件': '說明檔案',
"画": "畫",
"龙": "竜",
"板": "板",
"表": "表",
"才": "才",
"丑": "醜",
"出": "出",
"淀": "澱",
"冬": "冬",
"范": "範",
"丰": "豐",
"刮": "刮",
"后": "後",
"胡": "胡",
"回": "回",
"伙": "夥",
"姜": "薑",
"借": "借",
"克": "克",
"困": "困",
"漓": "漓",
"里": "里",
"帘... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
"""Summary
"""
from importlib import import_module
import os
from glob import glob
import sys
import re
from dash import html
from dash import dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
from collections import OrderedDict
from app import app
import docstring_parse... |
from .schemas import FileExtSchema, FileCliSchema, FileKioskSchema, \
FileProbeResultSchema, FileSuricataSchema
from .models import FileExt, FileWeb, FileCli, FileKiosk, FileProbeResult, \
FileSuricata
# Factory helpers for FileExt
file_ext_schemas = {
FileExt.submitter_type: FileExtSchema,
FileWeb.su... |
from os.path import realpath, dirname
import json
def get_config(name):
path = dirname(realpath(__file__)) + '/configs/' + name + '.json'
with open(path, 'r', encoding='utf-8') as f:
return json.loads(f.read())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutHashes in the Ruby Koans
#
from runner.koan import *
class AboutDictionaries(Koan):
def test_creating_dictionaries(self):
empty_dict = dict()
self.assertEqual(dict, type(empty_dict))
self.assertDictEqual({}, empty_dict)
... |
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import json
import logging
import os
import uuid
from azure.common import AzureHttpError
from msrestazure.azure_exceptions import CloudError
from c7n.utils import reset_session_cache
from c7n.config import Config
from c7n.policy import Po... |
#
# Toolbar.py -- Tool bar plugin for the Ginga fits viewer
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import os.path
from ginga.misc import Widgets, Bunch
from ... |
from __future__ import absolute_import
import unittest
from doubles.lifecycle import teardown, verify
def wrap_test(test_func):
def wrapper():
test_func()
verify()
return wrapper
class TestCase(unittest.TestCase):
def __init__(self, methodName='runTest'):
super(TestCase, self).... |
import re
import goodreads_api_client as gr
import json
import urllib.request
import yaml
from tqdm import tqdm
from bs4 import BeautifulSoup
def audible(url):
"""Add book details from Audible.com webpage.
"""
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, features="html.parser... |
import os
from os.path import join as path_join
from options import RuntimeOpts
from os_utils import *
def setup_runtime_template(env: dict, opts: RuntimeOpts, product: str, target: str, host_triple: str, llvm: str=''):
BITNESS = ''
if any(s in host_triple for s in ['i686', 'i386']):
BITNESS = '-m32... |
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun"
print "Yay! Printing."
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
|
#!/usr/bin/env python3
# Copyright (c) 2014-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.
"""Test the wallet keypool and interaction with wallet encryption/locking."""
from test_framework.test_fr... |
from contextvars import ContextVar
from typing import TYPE_CHECKING, TypeVar
T = TypeVar("T")
if TYPE_CHECKING:
def bind_contextvar(contextvar: ContextVar[T]) -> T:
raise NotImplementedError
else:
def bind_contextvar(contextvar):
class ContextVarBind:
__slots__ = ()
... |
#!/usr/bin/python
# hirez_pixel_track.py
# Author: Andrew Kenneth Melkonian
# All rights reserved
def highResPX(ref_ntf_path, search_ntf_path, ref_dem_path, search_dem_path, pairs_dir, resolution, utm_zone, bounds_txt_path, num_proc, search_size, ref_size, step_size, dem_grd_path):
import os;
assert os.path.exi... |
# @l2g 1739 python3
# [1739] Building Boxes
# Difficulty: Hard
# https://leetcode.com/problems/building-boxes
#
# You have a cubic storeroom where the width,length,and height of the room are all equal to n units.
# You are asked to place n boxes in this room where each box is a cube of unit side length.
# There are how... |
from .user import User, get_user # noqa: F401
from .flight import Aircraft, Location, Flight, Ticket # noqa: F401
|
import gin
from tensorflow.keras import applications
from tensorflow.compat.v1.keras.layers import BatchNormalization
from thin.models import resnet
EfficientNetB0 = gin.configurable(applications.EfficientNetB0, module='tf.keras.applications')
EfficientNetB1 = gin.configurable(applications.EfficientNetB1, module='tf... |
from __future__ import absolute_import
from rest_framework.serializers import CharField
from .base import DynamicField
class DynamicLinkField(
CharField,
DynamicField
):
def __init__(self, **kwargs):
self.iframe = kwargs.pop('iframe', False)
return super(DynamicLinkField, self).__init__(*... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... |
from brain import Brain, ToyBrain
import tensorflow as tf
from bot import Bot
import numpy
import os
class TFBrain(Brain):
DUALCOPYFREQ = 1000
SESS = None
WRITER = None
MERGER = None
SESS_HOLDERS = 0
# https://stats.stackexchange.com/questions/200006/q-learning-with-neural-network-as-functio... |
"""
Objective
Today, we're discussing data types. Check out the Tutorial tab for learning materials and an instructional video!
Task
Complete the code in the editor below. The variables , , and are already declared and initialized for you. You must:
Declare variables: one of type int, one of type double, and one of... |
# Copyright (c) 2017 Arup Pty. Ltd.
# Distributed under the terms of the MIT License.
"""Methods for Independent storms.
"""
import numpy as np
from .utils import least_squares
def peaks_over_threshold(max_storm_gusts, no_years, min_threshold=None, max_threshold=None):
"""Build a function that estimates the gus... |
# Copyright 2018 Contributors to Hyperledger Sawtooth
#
# 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 ... |
import xml.etree.ElementTree as ET
from nltk.tokenize import sent_tokenize
import csv
def jig2tsv(jigFile, tsvFile):
tree = ET.parse(jigFile)
root = tree.getroot()
wf = open(tsvFile, 'w')
wtr = csv.writer(wf, delimiter='\t', doublequote=False, escapechar='\\', quoting=csv.QUOTE_MINIMAL)
for document in root:
do... |
#from django.db import models #возможно потребуется разкоментить
import email
from pyexpat import model
from django.conf import settings
from django.db import models
from django.utils import timezone
###Модель продуктов###
class Products(models.Model):
product_name = models.CharField(max_length=150)
price = m... |
#!/usr/bin/python
# https://code.google.com/codejam/contest/2845486/dashboard
# projectile motion
import math
G = -9.8
N = int(input().strip())
for i in range(N):
V, D = input().strip().split()
V, D = int(V), int(D)
A = math.asin((D / (V ** 2)) * G) / 2
print('Case #%d: %f' % (i + 1, abs(180 * A / math.pi)))
|
"""Module with abstractions for VHDL types."""
from collections import OrderedDict
from .expressions import expr
def _count_and_offset_to_high_and_low(count, offset):
high = expr(offset) + expr(count) - 1
low = str(offset)
return high, low
class _Base():
"""Base class for abstracting VHDL types.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.