content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
import random
s, t=input(), list(input())
for c in s:
while t[0] != c: t = t[1:] + t[:1]
t.remove(c)
t = list(set(t))
random.shuffle(t)
print(*t, sep='')
print(' \t\n \n \t\t')
|
import pathlib
from .models import ConvTasNet, DCCRNet, DCUNet, DPRNNTasNet, DPTNet, LSTMTasNet, DeMask
from .utils import deprecation_utils, torch_utils # noqa
project_root = str(pathlib.Path(__file__).expanduser().absolute().parent.parent)
__version__ = "0.5.0dev"
def show_available_models():
from .utils.hub... |
"""
Main entry point for `graphql-validate` command-line utility.
This is to enable `python -m graphql-validate` if that is needed for any reason,
normal use should be to use the `graphql-validate` command-line tool directly.
"""
from graphql_validate.cli import cli
cli()
|
#!/usr/bin/env python
from __future__ import print_function
import glob
import io
import os
import subprocess
import sys
import tooltool
PLATFORM_MANIFESTS = {
'Linux': ['browser/config/tooltool-manifests/linux32/*.manifest', 'browser/config/tooltool-manifests/linux64/*.manifest*', 'browser/config/tooltool-manif... |
import random
import numpy as np
import os
from scipy import ndimage
import math
import tensorflow as tf
def clip(image, clip_min, clip_max):
shape = np.asarray(image).shape
for i in range(shape[0]):
for j in range(shape[1]):
for k in range(shape[2]):
if image[i][j][k] > cl... |
from sqlalchemy import (
MetaData,
Table,
Column,
Integer,
NVARCHAR,
DateTime,
Date,
Boolean,
DECIMAL,
)
meta = MetaData()
def upgrade(migrate_engine):
meta.bind = migrate_engine
t = Table(
"administration",
meta,
Column("id", Integer, primary_key... |
import asyncio
loop = asyncio.get_event_loop()
import aiohttp
import datetime
class TelegramAPIError(Exception):
def __init__(self, code, description):
# Error code
self.code = code
# Error description
self.description = description
class UpdateError(Exception):
pass
class ... |
def jogar():
print("*********************************")
print("Bem vindo ao jogo de Forca")
print("*********************************")
print("Fim do jogo") |
from django.contrib import admin
from habitat._common.admin import HabitatAdmin
from habitat.building.models import Module
@admin.register(Module)
class ModuleAdmin(HabitatAdmin):
list_display = ['name', 'status', 'hazard', 'width', 'height', 'length', 'plan', 'capacity']
list_filter = ['status', 'hazard', 'p... |
# Copyright (C) 2016 Nippon Telegraph and Telephone 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 appli... |
# Copyright Rein Halbersma 2020-2021.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import numpy as np
from ..enums import Action, Card, Hand, nC, nH
class BasicStrategyAgent:
"""
... |
from market.models import db, Category
db.session.add(Category(name="Koszykówka - punkty", full_name="Koszykówka - punkty"))
db.session.commit()
# db.drop_all()
# db.create_all()
|
import math
from abc import abstractmethod
from numbers import (Rational,
Real)
from typing import (Any,
Optional,
Tuple,
Union)
from cfractions import Fraction
from reprit.base import generate_repr
from .expression import Expression
fro... |
from csvio.processors import FieldProcessor
from .csv_data import get_csv_reader_writer
result = [
{
"Supplier": "Enormous Apples",
"Fruit": "Apple",
"Origin": "SPAIN",
"Quantity": 2,
},
{
"Supplier": "Enormous Melons",
"Fruit": "Melons",
"Origin": "... |
import subprocess as sp
import multiprocessing as mp
import glob
import os
import gzip
import time
import datetime
import shutil
#Non-Standard
from pyig.backend import split_fasta
from pyig.backend import output_parser
def run_mp_and_delete(manager):
'''main method to run igblast through multiprocessing protocol,... |
import functools
import typing
from collections import defaultdict
from django.core.cache import cache
from site_settings.models import Setting
VALUES_TYPE_MAP = (
(int, 1),
(str, 2),
(bool, 3),
)
CACHE_SETTINGS_KEY = 'settings_%s'
def cached_setting(func):
@functools.wraps(func)
def wrapper(*a... |
"Geocoder app"
from flask import Blueprint
geocoder = Blueprint("geocoder", __name__)
|
"""
"""
import cPickle
import lasagne
import numpy as np
import sys
import theano
BATCH_SIZE = 128
in_text = ""
def gen_data(p, char_to_ix, batch_size = BATCH_SIZE, data = in_text, SEQ_LENGTH = 20, vocab_size=500, return_target=True):
x = np.zeros((batch_size,SEQ_LENGTH,vocab_size))
y = np.zeros(batch_size)
for... |
#!/usr/bin/python
import ldap
import re
import datetime
import sys
flavors = ['org.glite.ce.CREAM', 'org.glite.ce.Monitor', 'org.glite.RTEPublisher', 'org.glite.wms.WMProxy', 'local-data-location-interface', 'SRM']
def convertServiceFlavour(flav):
flav = flav.replace('org.glite.ce.CREAM', 'CREAM-CE')
flav = ... |
# -*- coding: utf-8 -*-
import json
import hashlib
import os
import re
import time
import hashlib
import datetime
os.environ['PYWIKIBOT_DIR'] = os.path.dirname(os.path.realpath(__file__))
import pywikibot
from config import config_page_name # pylint: disable=E0611,W0614
def timeRecord(op, t):
use... |
import sys
import os
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
lib_path = os.path.abspath(os.path.join(sys.path[0], '..'))
sys.path.append(lib_path)
from src.basic_cv_tool import *
'''
This is the test file for project No.1 which consists of all the required
assignments.
'''
image_2_name = '../... |
# -*- coding: utf-8 -*-
import random
from datetime import datetime
from operator import itemgetter
import requests
import time
from pyinstagram.model import Media
from .exceptions import OAuthException, PyInstagramException
from .oauth import OAuth
from .constants import API_URL
from .utils import DESAdapter
class... |
#programador: Diego Franco
#data: 20/10/2019
''' Este programa tem como objetivo facilitar o orçamento de sessoes fotográficas'''
import os
def validaEntrada(string):
entrada = 0
while entrada <= 0:
try:
entrada = float(input(string))
except ValueError:
pass
re... |
# Natural Language Toolkit: Recursive Descent Parser Application
#
# Copyright (C) 2001-2014 NLTK Project
# Author: Edward Loper <edloper@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
A graphical tool for exploring the recursive descent parser.
The recursive descent parser mainta... |
import gzip
from common.utils import *
from common.metrics import *
from aad.aad_base import *
from aad.query_model import *
from aad.aad_loss import *
from aad.forest_aad_detector import *
from aad.loda_aad import *
from aad.precomputed_aad import *
def get_aad_model(x, opts, random_state=None):
if opts.detect... |
from src.video_player import VideoPlayer
from unittest import mock
@mock.patch('builtins.input', lambda *args: 'No')
def test_search_videos_with_no_answer(capfd):
player = VideoPlayer()
player.search_videos("cat")
out, err = capfd.readouterr()
lines = out.splitlines()
assert len(lines) == 5
as... |
import pandas as pd
from urllib.error import HTTPError
from .utils.transform import normalize
make_url = lambda version: f"https://s3.amazonaws.com/files.fred.stlouisfed.org/fred-md/monthly/{version}.csv"
def import_raw_fred(version: str = "current") -> pd.DataFrame:
"""
Takes a version name and imports th... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ******************************************************************************
#
# Project: GDAL utils.auxiliary
# Purpose: OGR utility functions
# Author: Idan Miara <idan@miara.com>
#
# ****************************************************************************... |
from JEDatabase.Core.SQLiteCore import SQLiteCore
SQL = SQLiteCore(db_name=r'StudentSystemData.sqlite', table_name='StudentSystem')
SQL.create_table(
'CREATE TABLE IF NOT EXISTS Account('
'PersonnelNumber VARCHAR(20) PRIMARY KEY ,'
'Password VARCHAR(20))')
SQL.create_table(
'CREATE TABLE IF... |
import pyautogui
import time
#screenWidth, screenHeight = pyautogui.size()
#pyautogui.position()
time.sleep(5) #
for i in range(38):
# fill amount page
pyautogui.click(x=895, y=580, button='left')
pyautogui.typewrite('15\n')
pyautogui.click(x=723,y=656,button='left')
time.sleep(4)
# check out page
pyautog... |
# -*- coding: utf8 -*-
def is_unique(sentence):
""" 1.1 Is Unique: Implement an algorithm to determine if a string has
all unique characters. What if you cannot use additional data structures?
Complexity: O(n) time, O(n) space
"""
h = set([])
for c in sentence:
if c in h:
re... |
"""
Main function for network training using GeoConv
"""
import torch
from torch import optim
from torch.utils.data import DataLoader
import os, argparse
import numpy as np
from model.GeoConvNet import GeoConvNet
from utils.process_data import collate_ball, collect_file, data_reader, PointData
from train import train
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# utils.py --- utils for musicbox
# Copyright (c) 2015-2016 omi & Contributors
import platform
import os
def notify_command_osx(msg, msg_type, t=None):
command = '/usr/bin/osascript -e \'display notification "' + msg
if msg_type == 1:
command += '"sound n... |
# region [Imports]
# * Standard Library Imports ---------------------------------------------------------------------------->
import os
import sys
import json
import pickle
import shutil
import hashlib
import datetime
import configparser
from pprint import pformat
from contextlib import contextmanager
# * Gid Imports... |
import numpy as np
from sklearn import datasets
from sklearn import preprocessing
from sklearn.model_selection import (
GridSearchCV,
RepeatedStratifiedKFold,
)
from sklearn.pipeline import make_pipeline
from .. import GLVQ
def test_shared_memory_glvq():
X, y = datasets.load_iris(return_X_y=True)
m ... |
# Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of ... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import CppHeaderParser
from CppHeaderParser import CppVariable, CppClass, CppMethod, CppEnum
from typing import List, Dict
def gen_variables(variables: List[CppVariable]):
out = []
for var in variables:
string = 'm.attr("{name}") = {name};'
name = var["name"]
if "using" in var["type"]:... |
# Copyright (c) 2021 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 app... |
# Generated by Django 2.1.9 on 2019-06-24 22:49
import django.contrib.postgres.fields
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('rmanager',... |
# coding: utf-8
from __future__ import print_function, division
from gurobipy import Model, GRB, quicksum, LinExpr
import networkx as nx
class Basic_Model(object):
def create_graph(self):
G = nx.Graph()
G.add_nodes_from(range(self.n_vertices))
for v1, v2 in self.edges:
G.add_e... |
import time
import random
start_time = time.time()
random.seed(0)
ROUTES_TO = [random.randint(0, 10000) for n in range(10000)]
ROUTES_BACK = [random.randint(0, 10000) for n in range(10000)]
MAX = 10000
count = 0
current_max = 0
for i in range(len(ROUTES_TO)):
for j in range(len(ROUTES_BACK)):
total = R... |
"""
MIT License
Copyright (c) 2020 xPolar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... |
#!/usr/bin/env python
from math import atan2, sin, cos
from .controller import Controller
class PIDController(Controller):
def __init__(self, trajectory, simulation_data, control_constants, speed_limits):
Controller.__init__(self, trajectory, simulation_data)
self.K_P_V = control_constants['kpv']... |
# -*- coding: utf-8 -*-
# Copyright 2013 Dev in Cachu authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import unittest
from django.db import models as django_models
from .. import models
class ParticipanteTestCase(unittest.TestCase... |
#!/usr/bin/env python3
# Copyright 2022 The IREE Authors
#
# Licensed under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
import stat
import unittest
import tempfile
import os
from common.common_argum... |
from typing import Dict
import pythonbible as bible
# noinspection SpellCheckingInspection
BOOK_IDS: Dict[bible.Book, str] = {
bible.Book.GENESIS: "Gen",
bible.Book.EXODUS: "Exod",
bible.Book.LEVITICUS: "Lev",
bible.Book.NUMBERS: "Num",
bible.Book.DEUTERONOMY: "Deut",
bible.Book.JOSHUA: "Josh"... |
import argparse
import os
from tqdm import tqdm
import torch
import pandas as pd
from pathlib import Path
from models.experimental import attempt_load
from utils.datasets import LoadImages
from utils.general import check_img_size, non_max_suppression, scale_coords
from utils.torch_utils import select_device
parser ... |
# this is a demo of UserFacts which uses files baked into
# /etc/opsmop/facts.d to implement feature flags
from opsmop.core.easy import *
import getpass
USERNAME = getpass.getuser()
class FeatureOne(Role):
def should_process_when(self):
return UserFacts.feature_flags.get('ff01', False)
def set_reso... |
# Copyright 2018-2020 Jérôme Dumonteil
# Copyright (c) 2009-2013 Ars Aperta, Itaapy, Pierlis, Talend.
#
# 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/LI... |
from src.base.solution import Solution
from src.structures.listnode import ListNode
from src.tests.part1.q328_test_odd_even_linkedlist import OddEvenLinkedlistTestCases
class OddEvenLinkedlist(Solution):
def run_test(self, input):
return self.oddEvenList(input)
def gen_test_cases(self):
retur... |
"""Configurações."""
import logging
import os
from functools import lru_cache
from pydantic import BaseSettings
log = logging.getLogger("uvicorn")
class Config(BaseSettings):
"""Modelo de configurações."""
env: str = os.getenv("ENV", "dev")
testing: bool = bool(os.getenv("TESTING", True))
@lru_cac... |
from pydantic import BaseModel
class ProductsSchema(BaseModel):
name: str
description: str
brand: str
price: float
quantity: int
is_active: bool
|
'''
Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
'''
from math import cos, tan, sin, radians
angulo = int(input("Digite um ângulo qualquer: "))
sen = sin(radians(angulo))
cos = cos(radians(angulo))
tan = tan(radians(angulo))
print("Do angulo {} pode... |
# Copyright (c) 2017-2019 Neogeo-Technologies.
# 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... |
# Python
# 生成签名
import hashlib
import hmac
import base64
import sys
sys.path.append("/")
from control import constant
#
appid = constant.appid1
appkey = constant.appkey1
# sha256加密后返回的二进制数据使用base64编码(易微联标准)
def makeSign(key, value):
message = value.encode('utf-8')
sha256_message_dig = hmac.new(key.encode('u... |
"""
#######################
UTILITIES
#######################
"""
import json
import os
from os.path import exists, join
"""
Method that returns data paths and checks whether they really exist
"""
def check_data_path(args):
data_paths = {}
if args.mode == "train":
data_paths["train"] = "data/train_C... |
# Generated by Django 2.2.4 on 2019-08-10 19:19
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migra... |
from utils.epa.sdw_downloader import (SDW_Downloader)
import os
from django.conf import settings
from django.core.management.base import BaseCommand
from utils.epa.sdw_downloader import ( SDW_Downloader )
class Command(BaseCommand):
def handle(self, *args, **options):
target_dir = os.path.join(
... |
import json
import locale
import os
class BabelFish():
def __init__(self,subpath=["resources","app","meta"],lang=None):
localization_string = locale.getdefaultlocale()[0] #get set localization
self.locale = localization_string[:2] if lang is None else lang #let caller override localization
self.langs = ["en"] #... |
from bs4 import BeautifulSoup
from abc import abstractmethod
from IzVerifier.exceptions.IzVerifierException import MissingFileException
class IzContainer():
"""
Abstract class responsible for containing some izpack spec resource.
For example implementers, see:
izconditions (for izpack conditions)
... |
import asyncio
def main():
print("Creating our event loop")
loop = asyncio.get_event_loop()
loop.run_forever()
print("Our Loop will now run forever, this will never execute")
if __name__ == '__main__':
main() |
"""
Collection of exceptions raised by the dnsimple2 package
"""
class InvalidAccountError(Exception):
pass
|
import numpy as np
import scipy.sparse as sp
import properties
from .. import utils
from .base import BaseSimilarityMeasure
class LinearCorrespondence(BaseSimilarityMeasure):
"""
The petrophysical linear constraint for joint inversions.
..math::
\\phi_c({\\mathbf m}_{\\mathbf1},{\\mathbf m}_{\\m... |
import datetime
import jwt
from sqlalchemy import and_
from project.server import app, db, bcrypt
from Crypto.PublicKey import RSA
class User(db.Model):
"""
User Model for storing user related details
"""
__tablename__ = "user"
id = db.Column(db.Integer, primary_key = True, autoincrement = True)
... |
import io
from PIL import Image as PilImage
from typing import Tuple, Type, Union
from .attachments import Thumbnail
from .descriptors import StreamDescriptor
from .helpers import validate_width_height_ratio
from .typing_ import FileLike
def generate_thumbnail(
original_image: Union[FileLike, StreamDescriptor],
... |
def printa(z):
for i in z:
print("".join(i))
print('@')
while(True):
p = int(input())
if(p==0):
break
else:
x = []
i = j = int(p/2)
for k in range(p):
x.append(['O']*p)
x[i][j] = 'X'
printa(x)
x[i][j] = 'O'
a = int... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for dit.npdist.
"""
from __future__ import division
from nose.tools import (assert_almost_equal, assert_equal, assert_false,
assert_raises, assert_true)
from numpy.testing import assert_array_almost_equal
from six.moves import map, zip ... |
from .models import Message, Room
import turbo
@turbo.register(Message)
class MessageBroadcast(turbo.ModelBroadcast):
def on_save(self, message, created, *args, **kwargs):
if created:
message.room.turbo.render(
"chat/components/message.html", {"message": message}
)... |
from http import HTTPStatus
from threading import Thread
from flask import request, current_app, redirect
from flask_restful import Resource
from src.config import config
from src.translators.InstallTranslator import InstallTranslator
from src.utilities.logging import get_logger
class InstallResource(Resource):
... |
#
# Pyserini: Python interface to the Anserini IR toolkit built on Lucene
#
# 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... |
import graphene
from django.contrib.auth import get_user_model
from graphene_django import DjangoObjectType
from insta.models import Profile
class ProfileType(DjangoObjectType):
class Meta:
model = Profile
class UserType(DjangoObjectType):
class Meta:
model = get_user_model()
class Query(g... |
def OcttoBin(n):
if isinstance(n, str) == True:
num = int(n,8)
binnum = bin(num)[2:]
return binnum
else:
strnum = str(n)
num = int(strnum, 8)
binnum = bin(num)[2:]
return binnum
|
# -*- coding: utf-8 -*-
# Third party
from rest_framework import serializers
class DeviceTokenSerializer(serializers.Serializer):
token = serializers.CharField(label='Token', min_length=32, required=True)
|
'''This is an unsupervised ML algo demonstration
Applying the Flat_KMeans clustering algorithms
on the Titanic dataset
Performed by Sahil Chauhan'''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
from sklearn.cluster import KMeans
from sklearn impor... |
NO_ROLE_CODE = ''
TRUSTEE_CODE = '0'
STEWARD_CODE = '2'
TGB_CODE = '100'
TRUST_ANCHOR_CODE = '101'
|
from django.test import TestCase, override_settings
from .models import Trunk, Branch, Leaf
@override_settings(ROOT_URLCONF = 'tests.nested_includes.urls')
class NestedIncludesTestCase(TestCase):
def setUp(self):
self.trunk = Trunk.objects.create(name="Trunk")
self.branch = Branch.objects.create(... |
import argparse
# Showing both short and long argument options
def get_args():
""""""
parser = argparse.ArgumentParser(
description="A simple argument parser",
epilog="This is where you might put example usage"
)
# required argument
parser.add_argument('-x', '--execute... |
import random
import string
from robotpt_common_utils import lists
import re
def random_string(length=8):
letters = string.ascii_lowercase
return ''.join(random.sample(letters, length))
def wildcard_search_in_list(pattern, list_, wildcard_symbol='*'):
list_ = lists.make_sure_is_iterable(list_)
idxs ... |
import numpy as np
from tensorflow.keras.optimizers import Optimizer
from tensorflow.keras import backend as K
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops, control_flow_ops
from .. import utils
class LossDiffAvgMaximization(Optimizer):
"""adapow2.LossDiffAvgMaximization is ... |
from django.conf.urls import url, include
urlpatterns = [
url(r'^account/', include("bmaccounter.api.urls.account", namespace='account-api')),
url(r'^account-group/', include("bmaccounter.api.urls.account_group", namespace='account-group-api')),
]
|
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Code starts here
data=pd.read_csv(path)
loan_status=data.Loan_Status.value_counts()
loan_status.plot(kind='bar')
# --------------
#Code starts here
property_and_loan=data.groupby(['Proper... |
import sys, os, inspect
import os, sys, inspect, inviwopy
path_to_current_folder = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
sys.path.append(path_to_current_folder + "/../")
import envisionpy
import envisionpy.hdf5parser
from envisionpy.network import VisualisationManager
VASP_DIR = pat... |
from pyparsing import *
import act
change = Forward().setParseAction(act.change)
amount = Forward().setParseAction(act.amount)
uptoamount = Forward().setParseAction(act.uptoamount)
an = Forward().setParseAction(act.an)
another = Forward().setParseAction(act.another)
alll = Forward().setParseAction(act.alll)
quantit... |
# Import required libraries
import numpy as np
import pandas as pd
import re
import spacy
import pickle
import time
from datetime import timedelta
pd.set_option('display.max_colwidth', 100)
# Load the largest english language vector collection from Spacy
nlp = spacy.load('en_vectors_web_lg')
# Read train and test d... |
# 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... |
import os
from unittest import TestCase
from helpers.consts import *
from db_methods import db
from .initial_test_data import test_students, test_teachers
class DatabaseMethodsTest(TestCase):
def setUp(self) -> None:
self.db = db
test_db_filename = 'db/unittest.db'
# ensure there is no tr... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import cohesity_management_sdk.models.vault_encryption_key
class CreateRemoteVaultSearchJobParameters(object):
"""Implementation of the 'CreateRemoteVaultSearchJobParameters' model.
Specifies settings required to create a search of a
remote Vault fo... |
#!/usr/bin/env python
# encoding: utf-8
from setuptools import setup
setup(
name='random-wallpaper',
description='Script to maintain a collection of random wallpapers.',
version='1.2',
author='Michael Killough',
author_email='michaeljkillough@gmail.com',
url='https://github.com/mjkillough/ran... |
from textplot.text import Text
from collections import OrderedDict
def test_term_count_buckets():
"""
term_count_buckets() should map integer counts to the list of terms in the
text that appear that many times.
"""
t = Text('aa bb bb cc cc dd dd dd')
assert t.term_count_buckets() == {
... |
from .custom_unet_model import CustomUnetModel
from .satellite_unet_model import SatelliteUnetModel
from .small_unet_model import SmallUnetModel
|
"""
To trace the falcon web framework, install the trace middleware::
import falcon
from ddtrace import tracer
from ddtrace.contrib.falcon import TraceMiddleware
mw = TraceMiddleware(tracer, 'my-falcon-app')
falcon.API(middleware=[mw])
"""
from ..util import require_modules
required_modules = ['f... |
import os
import torch
import pickle
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
from skimage.transform import resize
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from torchvision.transforms import Compose
import warnings
warnings.filterwarnings("ign... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import stripe
from stripe.test.helper import StripeResourceTest
class MetadataTest(StripeResourceTest):
def test_noop_metadata(self):
charge = stripe.Charge(id='ch_foo')
charge.description = 'test'
charge.save()
self.requestor_mock.request.assert_called_with(
'post',
... |
import pandas as pd
import os
import pickle
import collections
import random
import tensorflow as tf
from ampligraph.evaluation import train_test_split_no_unseen
from ampligraph.datasets import load_from_csv
from tqdm import tqdm
filedir = os.path.dirname(__file__)
Input_dir = os.path.join(filedir,'INPUT')
code_desc_f... |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... |
#!/usr/bin/python3
import os
import re
import sys
import urllib.parse
import urllib.request
from pathlib import Path
import xml.etree.ElementTree as ET
import shutil
def fetch(url, target: Path):
if target.exists() and target.stat().st_size > 0:
print(f"Skipped: {url}")
return target
try:
... |
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from tqdm import tqdm
import torch
from Utils.FittingNL3DMM_LossUtils import FittingNL3DMMLossUtils
from NL3DMMRenderer import NL3DMMRenderer
import cv2
from tool_funcs import soft_load_model, convert_loss_dict_2_... |
# Copyright (c) OpenMMLab. All rights reserved.
import random
from tempfile import TemporaryDirectory
import numpy as np
import pytest
import torch
from scipy import stats
from torch import nn
from mmcv.cnn import (Caffe2XavierInit, ConstantInit, KaimingInit, NormalInit,
PretrainedInit, TruncNor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.