text stringlengths 1 927k |
|---|
#=====================================================================================================
# SSF/miniSSF info generator v0.09 (2007-12-20) by kingshriek
# Command-line interface script that analyzes SSF/miniSSF files - useful for troubleshooting
# Example uses:
# - checking if sequence data references ... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
here = os.path.dirname(os.path.abspath(__file__))
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to... |
#!/usr/bin/env python3
# Copyright (c) 2014-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.
# Base class for RPC testing
import logging
import optparse
import os
import sys
import shutil
import te... |
#! /usr/bin/env python3
import binascii
import sys
# https://github.com/pvvx/ATC_MiThermometer/issues/186#issuecomment-1030410603
with open(sys.argv[1], 'rb') as f:
firmware = bytearray(f.read(-1))
if firmware[6:8] != b'\x5d\x02':
# Ensure FW size is multiple of 16
padding = 16 - len(firmware) % 16
if ... |
import base64
import time
from os import getenv
from typing import TYPE_CHECKING
from google.cloud import texttospeech
import requests
from flask import abort
if TYPE_CHECKING:
from google.cloud import firestore
BATCH_SIZE = 400
assert BATCH_SIZE < 500
def get_email_from_secret(secret):
ret = requests.get(... |
# This file does a short MCMC analysis under the GTR+I+G model
from phycas import *
filename = getPhycasTestData('green.nex')
blob = readFile(filename)
setMasterSeed(13579)
model.type = 'hky'
model.num_rates = 1
model.pinvar_model = False
model.kappa_prior = BetaPrime(1.0, 1.0)
model.state_freq_prior = Dirichlet((1... |
#!/usr/bin/env python
# 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... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.5.0-beta.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "Lice... |
from sklearn.neighbors import BallTree
import numpy as np
'''
Returns the KNN and distance in meters to the KNN.
Parameters
----------
left_gdf : GeoDataFrame
the target geodataframe; all columns are kept.
right_gdf : GeoDataFrame
the geodataframe that is the subject of the measuremen... |
# Copyright (c) Facebook, Inc. and its affiliates.
import importlib
import numpy as np
import os
import re
import subprocess
import sys
from collections import defaultdict
import PIL
import torch
import torchvision
from tabulate import tabulate
__all__ = ["collect_env_info"]
def collect_torch_env():
try:
... |
# Generated by Django 3.2 on 2022-01-27 08:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cats', '0003_auto_20220126_1548'),
]
operations = [
migrations.AlterField(
model_name='cat',
name='color',
... |
# Ex18.py
# Names, Variables, Code, Functions
#
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2= args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# Ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1:%r, arg2:%r" % (arg1, arg2)
# th... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Life's pathetic, have fun ("▔□▔)/hi~♡ Nasy.
Excited without bugs::
| * *
| . .
| .
| * ,
| .
|
| *
|... |
#
# Autogenerated by Frugal Compiler (2.23.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from datetime import timedelta
from threading import Lock
from frugal.exceptions import TApplicationExceptionType
from frugal.exceptions import TTransportExceptionType
from frugal.middleware import M... |
#!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import socket
import traceback, sys
from binascii import hexlify
import time, os
from socks5 import Socks5Conf... |
import os
token = 'your gitee account token'
period = ['start_date', 'end_date'] # period = ['2022-02-01', '2022-02-24']
sheet1_header = [
'packageName',
'rvPRStatus',
'rvPRUrl',
'rvPRUser',
'created_at'
]
sheet2_header = ['rvPRUser', 'number of PR']
report_header = [sheet1_header, sheet... |
from ..P6_string_compression import compress, uncompress
# Testing the compress function
# --------------------------------
def test_compress_empty():
assert compress('') == ''
def test_compress_one_element():
assert compress('a') == 'a'
def test_compressible_3():
assert compress('aaa') == 'a3'
def... |
#!/usr/bin/env python2
# Copyright (c) 2014-2015 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 test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
# Creat... |
from pydantic import BaseModel
from typing import Optional, List
# TO support creation and update APIs
class CreateAndUpdateComponent(BaseModel):
type: str
hostname: str
URL_access: str
username: str
# TO create components
class Creation(BaseModel):
ctfd: bool
ctfd_type: str
ctfd_... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import unittest
import ray
from ray.rllib import _register_all
from ray.tune import Trainable, TuneError
from ray.tune import register_env, register_trainable, run_experiments
from ray.t... |
"""Tests for the Bond fan device."""
from datetime import timedelta
from bond import DeviceTypes, Directions
from homeassistant import core
from homeassistant.components import fan
from homeassistant.components.fan import (
ATTR_DIRECTION,
DIRECTION_FORWARD,
DIRECTION_REVERSE,
DOMAIN as FAN_DOMAIN,
... |
#!/usr/bin/env python
"""
Copyright 2017-2018 Fizyr (https://fizyr.com)
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 applicabl... |
import unittest
from WallpaperAutomata.Commands.command_bootstrap import CommandBootstrap
class CommandBootstrapTest(unittest.TestCase):
def test_command(self):
CommandBootstrap.create() |
from paystack.models import PayStackCustomer
from .base_api_service import BaseAPIService
class CustomerService(BaseAPIService):
def _create_customer_object(self, user, customer_data, authorization_data):
defaults = {
"user": user,
"email": customer_data["email"],
"aut... |
#!/usr/bin/env python3
"""Sales by Match.
https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup
"""
import math
import os
import random
import re
import sys
import collections
def sockMerchant(n, ar):
socks_per_color ... |
import uuid
from collections.abc import Iterable
from typing import Any, Optional, Sequence, Union
import numpy as np
import scipy
from filterpy.kalman import KalmanFilter
from motpy.core import Box, Detection, Track, Vector, setup_logger
from motpy.metrics import angular_similarity, calculate_iou
from motpy.model im... |
from .fid_evaluator import FIDEvaluator
from .fid_lerp_evaluator import FIDLerpEvaluator
from .knn_evaluator import KNNEvaluator
from .mean_fid_evaluator import MeanFIDEvaluator
from .reconstruction_evaluator import ReconstructionEvaluator |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 26 18:27:13 2017
@author: James Jiang
"""
from hashlib import md5
input = 'ojvtpuvg'
password = ''
counter = 0
while len(password) < 8:
md5_hash = md5((input + str(counter)).encode('utf-8')).hexdigest()
if md5_hash[:5] == '00000':
password += md5_hash[... |
"""
WSGI config for freefolks project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Pedro Antonio Fernández Gómez and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('Noticias Web')
class TestNoticiasWeb(unittest.TestCase):
pass |
# Marcelo Campos de Medeiros
# ADS UNIFIP
# Lista_2_de_exercicios
# 15/03/2020
'''
4 - Faça um Programa que verifique se uma letra digitada é vogal ou consoante.
'''
#variáveis
letra = str(input('Informe uma letra qualquer: ')).strip().upper()
#comparando se a letra é uma vogal ou uma consoante
if letra == 'A' or le... |
from . import ccllib as lib
from .core import check
from .background import comoving_radial_distance, growth_rate, \
growth_factor, scale_factor_of_chi
from .pyutils import _check_array_params, NoneArr
import numpy as np
def get_density_kernel(cosmo, dndz):
"""This convenience function returns the radial kern... |
import os.path
import sys
from setuptools import find_packages, setup
def recursive_files(directory):
paths = []
for (path, _, filenames) in os.walk(directory):
for filename in filenames:
paths.append(os.path.join('..', path, filename))
return paths
if sys.version_info < (3, 6):
r... |
from typing import List, Optional
import numpy as np
import torch
from torchvision import datasets
from torchvision import transforms as T
class AverageMeter(object):
def __init__(self,
name: str,
fmt: Optional[str] = ':f',
) -> None:
self.name = name
self.fmt = fmt
sel... |
from setuptools import setup, find_packages
setup(
name = 'geometric-vector-perceptron',
packages = find_packages(),
version = '0.0.12',
license='MIT',
description = 'Geometric Vector Perceptron - Pytorch',
author = 'Phil Wang, Eric Alcaide',
author_email = 'lucidrains@gmail.com',
url = 'https://github... |
from setuptools import setup, find_packages
import os
# Taken from setup.py in seaborn.
# temporarily redirect config directory to prevent matplotlib importing
# testing that for writeable directory which results in sandbox error in
# certain easy_install versions
os.environ["MPLCONFIGDIR"]="."
# Modified from from se... |
import os
from httprunner_x import context, exceptions, loader, parser, runner
from tests.api_server import gen_md5
from tests.base import ApiServerUnittest, gen_random_string
class TestContext(ApiServerUnittest):
def setUp(self):
loader.load_project_data(os.path.join(os.getcwd(), "tests"))
self... |
import logging
import os
import time
from speech_utils import audio_to_words
from srt_utils import (
words_to_srt, jsonl_to_srt
)
from tempbucket import TemporaryBucket
__all__ = ["main", "cli_main"]
def main(filename_or_gs_path: str, srt_filename,
language_code="en-US", speech_contexts_file=None, prof... |
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides classes for the Piezoelectric tensor
"""
import warnings
import numpy as np
from pymatgen.core.tensors import Tensor
__author__ = "Shyam Dwaraknath"
__copyright__ = "Copyright 2016, The Materials P... |
from __future__ import absolute_import, division, print_function, unicode_literals
import braintree
from postgres.orm import Model
class ExchangeRoute(Model):
typname = "exchange_routes"
def __bool__(self):
return self.error != 'invalidated'
__nonzero__ = __bool__
@classmethod
def fro... |
# -*- coding: utf-8 -*-
""" Utilities
@requires: U{B{I{gluon}} <http://web2py.com>}
@copyright: (c) 2010-2015 Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Softwa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 16:18:55 2020
@author: jlazo
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 26 01:18:22 2020
@author: jlazo
"""
import os
import numpy as np
import cv2
from glob import glob
from sklearn.model_selection import train_... |
class Solution(object):
def XXX(self, n):
dp = [0, 1]
for i in range(n):
dp[i%2] = dp[i%2] + dp[(i+1)%2]
return dp[(n+1)%2] |
def dict_to_float(d):
"""
Converts all strings to floats from a dict
"""
if type(d) is dict:
for key, value in d.items():
if type(value) is str:
try:
d[key] = float(value)
except ValueError:
d[key] = str(value)
... |
# ----------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License
# ----------------------------------------------------------------------
"""Contains the SparseVectorTypeInfoFactory object"""
import os
import re
import... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) Camille Scott, 2019
# File : test_traversal.py
# License: MIT
# Author : Camille Scott <camille.scott.w@gmail.com>
# Date : 08.10.2019
import pytest
from goetia import libgoetia
from goetia.traversal import STATES
from .utils import *
def test_cursor(graph,... |
# Time: O(n * k), n is the number of coins, k is the amount of money
# Space: O(k)
#
# You are given coins of different denominations and
# a total amount of money amount. Write a function to
# compute the fewest number of coins that you need to
# make up that amount. If that amount of money cannot
# be made up by any... |
from .attribute_definitions import (
AbtractAttrDef,
UIDef,
UISeparatorDef,
UILabelDef,
UnknownDef,
NumberDef,
TextDef,
EnumDef,
BoolDef,
FileDef,
)
__all__ = (
"AbtractAttrDef",
"UIDef",
"UISeparatorDef",
"UILabelDef",
"UnknownDef",
"NumberDef",
... |
import json
from datetime import timedelta
from drepr import Graph
from dtran import IFunc, ArgType
class Pihm2CyclesFunc(IFunc):
id = "pihm2cycles_func"
inputs = {
"pihm_data_graph": ArgType.DataSet(None),
"pihm_soil_graph": ArgType.DataSet(None),
"pid_graph": ArgType.DataSet(None),... |
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from astropy import units as u
'''
Meredith Rawls, 2015
Takes masses, radii, and chi2s from an ELC run and makes delta_nu distributions.
Assumes a fixed temperature for each star.
'''
dir = '../../RG_ELCmodeling/9246715/demcmc001/'... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
# The implementation largely follows the design in PyTorch's `torch.distributions`
#
# Copyright (c) 2016- Facebook, Inc (Adam Paszke)
# Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
# Copyright (c)... |
# pylint: skip-file
# type: ignore
# -*- coding: utf-8 -*-
#
# tests.analyses.milhdbk217f.models.test_inductor.py is part of The
# RAMSTK Project
#
# All rights reserved.
# Copyright 2007 - 2017 Doyle Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Test class for the inductor module."""
# Third Party Imp... |
import torch
from torchvision import datasets, transforms
import numpy as np
from os.path import join
from .namers import attack_file_namer
def tiny_imagenet(args):
data_dir = join(args.directory, 'data')
train_dir = join(data_dir, "original_datasets",
"tiny-imagenet-200", "train")
... |
""" DataPanels implementation of Conway's Game of Life
See https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life for details about
the game.
"""
import random
from typing import Tuple, Set, Optional, Union, List
import re
import numpy as np
from kivy.lang.builder import Builder
from kivy.properties import ListPropert... |
# -*- coding: utf-8 -*-
"""Family module for Wikivoyage."""
from __future__ import absolute_import, unicode_literals
__version__ = '$Id: f762c76d91e13629122c6ee944de08a2221cd193 $'
# The new wikivoyage family that is hosted at wikimedia
from pywikibot import family
class Family(family.SubdomainFamily, family.Wikim... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from typing import List, Optional, Tuple
from pants.backend.python.lint.docformatter.rules import DocformatterFieldSet, DocformatterFieldSets
from pants.backend.python.lint.docformatter.r... |
STATUS_TEXT_COLORS = {
"successful":"green",
"unstable":"goldenrod",
"failed":"firebrick",
"broken":"maroon",
"unknown":"grey",
"skip":"cornflowerblue"
} |
#!/usr/bin/env python
#
# Copyright 2015 Google 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 requir... |
"""
Merges the 3 Tesla Dashcam and Sentry camera video files into 1 video. If
then further concatenates the files together to make 1 movie.
"""
import argparse
import logging
import os
import sys
from datetime import datetime, timedelta, timezone
from fnmatch import fnmatch
from glob import glob
from pathlib import Pat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Events, i.e., received packets and their probe requests, are sorted and matched
together to identify two-phase events.
"""
__maintainer__ = "Raphael Hiesgen"
__email__ = "raphael.hiesgen@haw-hamburg.de"
__copyright__ = "Copyright 2018-2021"
from datetime import datet... |
# -*- coding: utf-8 -*-
import unittest
import uuid
from starlette.testclient import TestClient
from src.core.file_functions import open_json, save_json
from src.main import app
client = TestClient(app)
directory_to__files: str = "data"
# api/v1/groups/list?delay=1&qty=10&offset=1&active=true&groupType=approval
cla... |
# Copyright 2015 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... |
# this code is for calculate the VGGloss, which also called percetual loss.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
from typing import Union
import math
class VGG19(nn.Module):
"""
Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, ... |
#!/usr/bin/env python3
#
# Copyright 2021 Graviti. Licensed under MIT License.
#
# pylint: disable=missing-module-docstring,invalid-name
#
# 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... |
from Stack import Stack
class StackOfPlates:
def __init__(self, stackSize):
self.stackSize = stackSize
self.stackList = []
self.stackList.append(Stack())
def push(self, item):
if len(self.stackList[-1]) > self.stackSize:
self.stackList.append(Stack())
self.... |
from common.numpy_fast import clip, interp
from common.realtime import sec_since_boot
from selfdrive.boardd.boardd import can_list_to_can_capnp
from selfdrive.controls.lib.drive_helpers import rate_limit
from selfdrive.car.toyota.toyotacan import make_can_msg, create_video_target,\
... |
# Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... |
import pandas as pd
import numpy as np
import psycopg2
from sqlalchemy import create_engine
import json
import sys
from sklearn.externals import joblib
import os
def run_all():
# connect to postgres
params = json.load(open('/home/ipan/passwords/psql_psycopg2.password', 'r'))
try:
conn = psycopg2... |
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import time
import os
import sys
import json
import pdb
from utils import AverageMeter
def calculate_video_results(output_buffer, video_id, test_results, class_names):
video_outputs = torch.stack(output_buffer)
average_scores = ... |
"""
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site d... |
"""
Generate corpus for the specific category
"""
import argparse
from pathlib import Path
from typing import List
from tqdm import tqdm
from docsim.elas.search import EsResult, EsSearcher
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dataset',
ty... |
"""
Colouring chromosomes by ancestries inferred by a reference panel
"""
from __future__ import absolute_import
import logging
from utils import compute_referencepanel, compute_haplotypes
import sys
import argparse
from cyvcf2 import VCF, Writer
import platform
import resource
import random
from core import hmm
from ... |
from easy_tk.TkMaster import TkMaster
from easy_tk.TkChild import TkChild
from easy_tk.helpers import *
from easy_tk.EasyTk import EasyTk
from easy_tk.EasyTkObject import EasyTkObject |
import sys
try:
import io
import traceback
except ImportError:
import uio as io
traceback = None
class SkipTest(Exception):
pass
class AssertRaisesContext:
def __init__(self, exc):
self.expected = exc
def __enter__(self):
return self
def __exit__(self, exc_type, ex... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: proxyFetcher
Description :
Author : JHao
date: 2016/11/25
-------------------------------------------------
Change Activity:
2016/11/25: proxyFetcher
---------------------------... |
# Copyright (c) 2001-2021 Stefan Marr
#
# 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, di... |
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2018. All Rights Reserved.
# pragma pylint: disable=unused-argument, no-self-use, line-too-long
""" Resilient functions component to execute queries against an LDAP server """
import logging
import json
import re
from resilient_circuits import ResilientComponent, func... |
"""flowchart
Flowchart Library in Python
Copyright 2016 AlphaServ Computing Solutions
"""
from flowchart.chart import FlowChart
from flowchart.version import __version__, __version_info__
__all__ = ['FlowChart', '__version__', '__version_info__'] |
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""This module contains functions and methods that relate to the DataInfo class
which provides a container for informational attributes as well as summary info
methods.
A DataInfo object is attached to the Quantity, SkyCoord, and ... |
# -*- coding: utf-8 -*-
"""
Created on Mon July 24 16:35:13 2017
@author: Maxime PINSARD
"""
import os, sys
os.chdir('C:/Users/admin/Documents/Python/Lasers GUI standalone')
from PyQt5 import QtWidgets
import lasers_core2
if __name__=='__main__':
# just to avoid pyqt5 to quit when an error is rais... |
from flask_mail import Message
from flask import render_template
from . import mail
def mail_message(subject,template,to,**kwargs):
sender_email = evanmwenda@gmail.com
email = Message(subject, sender=sender_email, recipients=[to])
email.body= render_template(template + ".txt",**kwargs)
email.html = re... |
# Copyright (c) 2003-2019 by Mike Jarvis
#
# TreeCorr is free software: 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 condi... |
from tokenizers import Tokenizer, AddedToken, pre_tokenizers, decoders, trainers, processors
from tokenizers.models import BPE
from tokenizers.normalizers import unicode_normalizer_from_str, Lowercase, Sequence
from .base_tokenizer import BaseTokenizer
from typing import Optional, List, Union
class ByteLevelBPEToken... |
"""Configure py.test."""
import json
from unittest.mock import patch
import pytest
from tests.common import load_fixture
@pytest.fixture(name="climacell_config_entry_update")
def climacell_config_entry_update_fixture():
"""Mock valid climacell config entry setup."""
with patch(
"homeassistant.compon... |
"""Utility functions for managing asset structs."""
load("@bazel_skylib//lib:types.bzl", "types")
_TYPICAL_PLATFORMS = ["darwin", "linux"]
_TYPICAL_ARCHES = ["amd64", "arm64"]
def _create(name, platform, arch, version, sha256 = None):
"""Create a `struct` representing a buildtools asset.
Args:
name:... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
tests.unit.pillar_test
~~~~~~~~~~~~~~~~~~~~~~
'''
# Import python libs
from __future__ import absolute_import
import tempfile
# Import Salt Testing libs
from tests.support.unit import skipIf, TestCase
from tests.support... |
#!/usr/bin/env python
import argparse
import atexit
import os
import shutil
import subprocess
import sys
from lib.config import enable_verbose_mode
from lib.util import get_electron_branding, execute_stdout, rm_rf
import lib.dbus_mock
if sys.platform == 'linux2':
# On Linux we use python-dbusmock to create a fa... |
import logging
from typing import Any, Dict, List
from domain.events.table import DomainEvent
logger = logging.getLogger(__name__)
def handle_events(
handlers: Dict[DomainEvent, Any], events: List[Dict[str, Any]]
) -> List[str]:
"""
Primary port defining how incoming events are handled.
`handlers` -... |
import os
from dotenv import load_dotenv
load_dotenv()
paths = {
"datasets_base_path": os.getenv("DATASETS_BASE_PATH", "."),
"output_folder": os.getenv("OUTPUT_FOLDER", ".")
}
categories = [
"pneumonia",
"normal",
"covid-19"
]
databases = [
{
"type": "metadata",
"source": "gi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCU... |
from airflow.hooks.base_hook import BaseHook
from airflow.models import Connection
from pytest_mock import MockFixture
from airfloweset.operators.movielens_operator import MovielensPopularityOperator
def test_movielenspopularityoperator(mocker: MockFixture):
mock_get = mocker.patch.object(
BaseHook,
... |
from django.apps import AppConfig
class DigitalApiConfig(AppConfig):
name = 'digital_api' |
from sklearn.base import BaseEstimator, TransformerMixin
from feature_generation_strategy import MinFeatureGenerationStrategy, MaxFeatureGenerationStrategy, SumFeatureGenerationStrategy, DiffFeatureGenerationStrategy, ProdFeatureGenerationStrategy, DivFeatureGenerationStrategy, AvgFeatureGenerationStrategy, PCAFeatureG... |
# -*-coding:Utf-8 -*
# Copyright (c) 2012 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
htmldocck.py is a custom checker script for Rustdoc HTML outputs.
# How and why?
The principle is simple: This script receives a path to generated HTML
documentation and a "template" script, which has a series of check
commands like `@has` or `@matches`. Each comman... |
import graphene
from simple_api.adapters.graphql.constants import INPUT_CLASS_SUFFIX
from simple_api.utils import ClassStub, Storage
class InputClassStorage(Storage):
def get(self, cls_str, cls):
if cls_str not in self.storage:
self.storage[cls_str] = ClassStub("{}{}".format(cls.__name__, INP... |
# Imports
import torch
from torchvision import datasets, models, transforms # All torchvision modules
import torch.nn as nn # All neural network modules, nn.Linear, nn.Conv2d, Loss functions,..
import torch.optim as optim # For all Optimization algorithms, SGD, Adam,...
import torch.nn.functional as F # All functio... |
import uuid
import click
from rastervision.runner import OutOfProcessExperimentRunner
from rastervision.rv_config import RVConfig
class AwsBatchExperimentRunner(OutOfProcessExperimentRunner):
def __init__(self):
super().__init__()
rv_config = RVConfig.get_instance()
batch_config = rv_co... |
import numpy as np
from bs4 import BeautifulSoup
from sklearn.cluster import KMeans
from math import sqrt
from statistics import mean
from PIL import Image, ImageOps, ImageDraw
import re
import json
import argparse
import os
import uuid
from cdparser import Classifier, Features, LabeledEntry, Utils
import sys
def bui... |
from .compartment_reader import CompartmentReaderVer01 as SonataReaderDefault
from .compartment_writer import CompartmentWriterv01 as SonataWriterDefault
"""
try:
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
nhosts = comm.Get_size()
except Exception as exc:
pass
"""
class C... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.