text stringlengths 2 999k |
|---|
# Copyright 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Umpire utility classes."""
import filecmp
import functools
import logging
import os
import stat
from twisted.internet import defer
from cros.factory... |
from datetime import datetime
from sqlalchemy import Column, Integer, DateTime, String, ForeignKey
from sqlalchemy.orm import Session
from app import Base_Model
from app.models.dto.address_dto import AddressDTO
from app.utils.session import session_hook
class Address(Base_Model):
__tablename__: str = "address"
... |
# Generated by Django 3.0.4 on 2020-06-04 10:17
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('product', '0038_auto_20200515_2128'),
migrations.swappable_depe... |
import os
import cv2
import glob
import numpy as np
from PIL import Image
import torch
import torchvision
from torch.utils import data
from torchvision import transforms
import torch
from torch import nn
import torchvision
import torch.nn.functional as F
def get_char_dict():
char_dict = {}
char_dict["pad"] = ... |
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('books/', views.BookListView.as_view(), name='books'),
path('leaveform/', views.leaveformview, name='leaveformview'),
path('book/<int:pk>', views.BookDetailView.as_view(), name='book-de... |
# 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
# d... |
from Tools.Log import Log
from twisted.internet import threads, reactor
from threading import Lock
class ThreadedRequest(object):
# Pythons HttpConnection (used by googles python client api) is not thread safe
# We have to use locking to ensure serialized requests
_lock = Lock()
def __init__(self, query, callback... |
from corehq.apps.accounting.models import BillingAccount, DefaultProductPlan, SoftwarePlanEdition, Subscription
from corehq.apps.commtrack.models import CommtrackActionConfig
from corehq.apps.custom_data_fields.models import CustomDataFieldsDefinition, CustomDataField
from corehq.apps.domain.models import Domain
from c... |
# Automatically created by: scrapyd-deploy
from setuptools import setup, find_packages
setup(
name = 'project',
version = '1.0',
packages = find_packages(),
entry_points = {'scrapy': ['settings = feed.settings']},
)
|
# The examples in this file come from the Flask-SQLAlchemy documentation
# For more information take a look at:
# http://flask-sqlalchemy.pocoo.org/2.1/quickstart/#simple-relationships
from datetime import datetime
from swift_api.database import db
class Post(db.Model):
id = db.Column(db.Integer, primary_key=Tr... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from shareRes.models import *
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# Create your views here.
def sendEmail(request):
checked_... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from . import __version__ as app_version
app_name = "forex"
app_title = "Forex"
app_publisher = "FinByz"
app_description = "Managing Forex Exposure"
app_icon = "octicon octicon-pulse"
app_color = "green"
app_email = "info@finbyz.com"
app_license = "MIT"
... |
from datetime import datetime
from datetime import timedelta
import pandas as pd
from utility.datafilepath import g_singletonDataFilePath
from exploredata.timeslot import singletonTimeslot
import os.path
class prepareGapCsvForPrediction:
def __init__(self):
return
def run(self):
self.gener... |
from __future__ import annotations
from typing import TYPE_CHECKING
from sila2.client import SilaClient
from .controlloopservice import ControlLoopServiceFeature, InvalidChannelIndex
if TYPE_CHECKING:
from .controlloopservice import ControlLoopServiceClient
class Client(SilaClient):
ControlLoopService: ... |
""" General purpose functions """
import hashlib
import re
from typing import Sequence
LOGGING_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
def hash_from_strings(items: Sequence[str]) -> str:
""" Produce a hash value from the combination of all str elements """
item_text = '+|+'.join(items).encode('utf... |
"""
Django settings for umabot_main project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import o... |
# -*- 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.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationE... |
#!/usr/bin/python
#
"""
Virtual superclass for all devices
Homepage and documentation: http://dev.moorescloud.com/
Copyright (c) 2013, Mark Pesce.
License: MIT (see LICENSE for details)
"""
__author__ = 'Mark Pesce'
__version__ = '0.1a'
__license__ = 'MIT'
class Device:
def __init__(self, dev):
self.dev = dev
... |
from ggdtrack.eval import eval_prepped_tracks_joined
from ggdtrack.mot16_dataset import Mot16
cachedir='/lunarc/nobackup/projects/lu-haar/ggdtrack/cachedir.1/'
print('Linear')
datasets = [Mot16("data", fold=fold, cachedir=cachedir) for fold in range(4)]
eval_prepped_tracks_joined(datasets)
print('NNModelSimpleMLP1')... |
from . import views
from django.urls import path
urlpatterns = [
path('', views.PoemList.as_view(), name='home'),
# path('<slug:slug>/', views.PoemDetail.as_view(), name='poem_detail'),
path('<slug:slug>/', views.post_detail, name='poem_detail')
] |
import asyncio
from asyncio.events import AbstractEventLoop
import json
import logging
import zlib
from aiohttp import ClientSession, ClientWebSocketResponse
from ..cert import Cert
from ..hardcoded import API_URL
from ..net_client import BaseClient
class WebsocketClient(BaseClient):
"""
implements BaseClie... |
from sklearn.datasets import load_iris
from sklearn import preprocessing
import matplotlib.pyplot as plt
import numpy as np
from random import sample
plt.style.use('seaborn-whitegrid')
def get_bin(x, n):
return format(int(x), 'b').zfill(n)
class DataPlotter:
@staticmethod
def plot_original_data(data1,... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-06-19 18:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('goods2', '0012_auto_20180619_1732'),
]
operations = [
migrations.AlterField... |
from discord import Embed
from discord.ext.commands import Cog, command
from config.globals import message_color, extensions
from utils.checks import is_developer
from utils.generators import generate_footer
class Reload(Cog):
category = "system"
def __init__(self, client):
self.client = client
... |
from __init__ import *
from util import *
rtagroot = sys.argv[1]
pathdata = os.environ["PCAT_DATA_PATH"] + '/data/outp/'
listrtagdata = fnmatch.filter(os.listdir(pathdata), rtagroot)
numbcnfg = len(listrtagdata)
for k, rtag in enumerate(listrtagdata):
print 'Processing %s...' % rtag
pathoutprtag = retr_pathou... |
import numpy as np
import scipy.integrate
from krylov import krylov_prop
from eom import cmfeom_spfs
from optools import precompute_ops
from cy.wftools import (overlap_matrices,compute_density_matrix,
invert_density_matrix,compute_projector)
from meanfield import compute_meanfield_mats
from copy... |
try:
import unittest
except ImportError:
import django.utils.unittest as unittest
from django_dynamic_fixture import G
from django_condition_chain.models import Condition, Chain, ChainElement
return_arg = lambda x: x
return_true = lambda: True
return_false = lambda: False
class ConditionTestCase(unittest.... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Project,Rating,Profile
from pyuploadcare.dj.forms import ImageField
class SignUpForm(UserCreationForm):
username = forms.CharField( widget=forms.TextInput(attrs={"class":... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dark_tooth_29082.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
rai... |
# 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... |
# testando reatribuicao
a = 10
a = "hello world" |
# from random import sample
# import click
# from starfox.quotes import QUOTES
# @click.command()
# @click.argument('character')
# def main(character):
# qs = QUOTES[character.lower()]
# q = sample(qs, k=1)[0]
# print(f'{character.upper()} - "{q}"')
from random import sample
import click
import questiona... |
# Copyright (c) 2021, Cosumar Digital Factory and Contributors
# See license.txt
# import frappe
import unittest
class TestAccidenttype(unittest.TestCase):
pass
|
# Copyright (c) 2014 Scopely, Inc.
# Copyright (c) 2015 Mitch Garnaat
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanyin... |
#!/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.
#
# Test mulitple rpc user config option rpcauth
#
from test_framework.test_framework import BitcoinTestFrame... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RSva(RPackage):
"""Surrogate Variable Analysis.
The sva package contains functions... |
import pickle
import traceback
from collections import Counter
from glob import glob
from pathlib import Path
from dpu_utils.utils import load_jsonl_gz
from .ts import code2identifiers, code2paths, code2paths4py, code2sexp
# JGD for alon_encoder
def paths2tokens(paths):
paths = [path.split(',') for path in path... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module for getting information about the server. """
from asyncio import create_subprocess_exec as asyncr... |
# 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
__a... |
import sys
import logging
import argparse
import re
from lexer import Lexer
from pseudoc import config
from pseudoc import parser
log = logging.getLogger(__name__)
PASS_NAME = re.compile(r"[A-Za-z_0-9.]+")
PARAM_NAME = re.compile(r"[A-Za-z_][A-Za-z_0-9.]*")
PARAM_VALUE = re.compile(r"[^,()]+")
def parse_passes_sp... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'pos_epson_printer_restaurant',
'version': '1.0',
'category': 'Sales/Point of Sale',
'sequence': 6,
'summary': 'Epson Printers as Order Printers',
'description': """
Use Epson Printers... |
from __future__ import absolute_import
import unittest
import six
from bandwidth import client
from bandwidth import _client_classes
if six.PY3:
from unittest.mock import patch
builtins = 'builtins'
else:
from mock import patch
builtins = '__builtin__'
class ClientTests(unittest.TestCase):
def ... |
"""[Practice: Light Switch]
Variable name class name
("instance")
ice = Ice)
Constructor
class ice:
def __init__(self):
boby
"""
class Light:
def toggle(self):
print("Toggle on and off")
self.on = not self.on
def __init__(self):
self... |
# Copyright (c) Facebook, Inc. and its affiliates.
import typing as ty
# pyre-fixme[21]: Could not find module `torcharrow._torcharrow`.
import torcharrow._torcharrow as velox
from torcharrow.dispatcher import Device
from torcharrow.dtypes import DType
from torcharrow.icolumn import IColumn
from torcharrow.scope impor... |
# -*- coding: utf-8 -*-
from openerp.addons.stock.tests.common import TestStockCommon
from openerp.tools import mute_logger, float_round
class TestResupply(TestStockCommon):
def setUp(self):
super(TestResupply, self).setUp()
self.Warehouse = self.env['stock.warehouse']
# create 2 WH, BIG ... |
import pytest
import scryptlib
from scryptlib.types import *
contract = '''
struct Thing {
int someNumber;
OtherThing[2] otherThings;
}
struct OtherThing {
bytes someBytes;
int[3] numbers;
}
contract NestedStructs {
... |
#!/usr/bin/env python
#
# rts_package documentation build configuration file
#
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document wi... |
from .labelme_annotation import Shape, ShapeHandler, LabelMeAnnotationParser, \
LabelMeAnnotation, LabelMeAnnotationHandler |
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
def test():
assert gcd(21, 6) == 3
assert gcd(99, 11) == 11
assert gcd(11, 21) == 1
print 'pass'
if __name__ == '__main__':
test()
|
''' SGPA_graph.py '''
import tensorflow as tf
## Computation graph for SGPA
def build_SGPA_graph(X, layers_width, n_samples, n_basis):
KL = 0
Z = tf.expand_dims(tf.tile(tf.expand_dims(X, 0), [n_samples, 1, 1]), 2)
for h, n_out in enumerate(layers_width[1:]):
# Hidden layer
if(h < len(layers... |
from math import ceil, floor
FNAME = 'submit'
HASH_LEN = 16
def main():
output = ''
for p, problem in enumerate(load_input(), 1):
output += 'Case #%d: %s\n' % (p, solve(*problem))
with open('%sOutput' % FNAME, 'w', encoding='iso-8859-1') as fp:
fp.write(output)
def load_input():
with open('%sInput' % FNAME, ... |
# Copyright 2016 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... |
"""Tests for the pysmartthings package."""
|
# -*- coding: utf-8 -*-
import json
import threading
from plexapi import log
class AlertListener(threading.Thread):
""" Creates a websocket connection to the PlexServer to optionally receive alert notifications.
These often include messages from Plex about media scans as well as updates to currently runn... |
#!/usr/bin/env python
######################################################.
# Testing QCORR with pytest #
######################################################.
import os
import glob
import pytest
from definitions_testing import analysis,single_point
# saves the working directory
path_analy... |
#!/usr/bin/env python3
## import Paramiko so we can talk SSH
import paramiko
import os
## shortcut issuing commands to remote
def cmdissue(command_to_issue):
ssh_stdin, ssh_stdout, ssh_stderr = sshsession.exec_command(command_to_issue)
return ssh_stdout.read()
sshsession = paramiko.SSHClient()
############# IF ... |
from flask import Blueprint
auth=Blueprint("auth",__name__)
from . import views
from . import errors |
# create a mapping of state to abbreviation
2 states = {
3 'Oregon': 'OR',
4 'Florida': 'FL',
5 'California': 'CA',
6 'New York': 'NY',
7 'Michigan': 'MI'
8 }
9
10 # create a basic set of states and some cities in them
cities = {
12 'CA': 'San Francisco',
13 'MI': 'Detroit',
14 'FL': 'Jacksonville'
15 }
16
17 # add so... |
get_context = lambda x: None
|
from part2 import compute_answer
def test_compute_answer_sample():
lines = [
"Player 1 starting position: 4",
"Player 2 starting position: 8",
]
expected = 444356092776315
actual = compute_answer(lines)
assert actual == expected
def test_compute_answer_full():
with open("../d... |
"""The kostal component.""" |
import graphene
from dagster import check
from dagster.core.definitions.events import AssetKey
from dagster.core.host_representation import (
InstigationSelector,
RepositorySelector,
ScheduleSelector,
SensorSelector,
)
from dagster.core.scheduler.job import JobType
from ...implementation.external impor... |
"""
Unit test for zookeeper plugin
"""
import unittest
import mock
from treadmill.plugins import zookeeper
class ZookeeperTest(unittest.TestCase):
@mock.patch('kazoo.client.KazooClient')
def test_connect_without_connargs(self, kazooClientMock):
zkurl = 'zookeeper://foo@123:21'
zookeeper.conne... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2014 Peter Oliver <ansible@mavit.org.uk>
#
# This program 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
# (at your o... |
#!/usr/bin/env python
# Copyright (C) 2006 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser Ge... |
#!/usr/bin/env python3
"""Script to compare output of [Core]NEURON runs.
This utility is used to compare the results of different NEURON and CoreNEURON
runs and determine whether or not they are consistent with one another.
Positional arguments are of the form testname::type1::path1[::type2::path2]...
Typical usage... |
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.template import loader
from django.urls import reverse
from .models import Question, Choice
# def index(request):
# latest_question_list = Question.objects.order_by('-pub_date')[... |
import numpy as np
import warnings
def steer_to_harmonics_mtx(harmonics, angles=None, even_phase=True):
'''Compute a steering matrix
This maps a directional basis set onto the angular Fourier harmonics.
Parameters
----------
harmonics: `array_like`
array specifying the angular harmonics ... |
import numpy as np
import statsmodels.discrete.discrete_model as dm
# fits data onto a negative binomial distribution by approximately maximizing
# the parameters
def fit_nbinom(x):
print("Fitting total read count to negative binomial distribution...")
params = dm.NegativeBinomial(x, np.ones_like(x)).fit(maxi... |
import _plotly_utils.basevalidators
class DtickValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(
self, plotly_name="dtick", parent_name="histogram.marker.colorbar", **kwargs
):
super(DtickValidator, self).__init__(
plotly_name=plotly_name,
parent_name=... |
from typing import TYPE_CHECKING
from enum import Enum
from ..types import TealType, require_type
from ..ir import TealOp, Op, TealBlock
from .leafexpr import LeafExpr
from .expr import Expr
from .maybe import MaybeValue
from .int import EnumInt
from .global_ import Global
if TYPE_CHECKING:
from ..compiler import... |
"""Algorithms for sampling from the unit simplex."""
import numpy as np
import sys
def naive_sampling(n, N=1):
"""Sample from an n-dimensional simplex using a naive algorithm.
This is a naive sampling procedure that will not result in
samples being drawn uniformly from the n-simplex. However,
it is ... |
"""
a lstm-a2c with context
context input is added to the linear layer of A2C
"""
import torch
import torch.nn as nn
from models.A2C import A2C_linear
from models._rl_helpers import pick_action
# constants
N_GATES = 3
# output format is either discrete (e.g. action selection) or continuous
OUTPUT_FORMAT = ['discrete',... |
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
left = 0
right = 0
freq = {}
max = 0
while(right < len(s)):
pass
|
# -*- coding: utf-8 -*-
import scrapy
import json
import base64
from locations.items import GeojsonPointItem
class RalphLauren(scrapy.Spider):
name = "ralph_lauren"
allowed_domains = ["www.ralphlauren.com"]
start_urls = (
'https://www.ralphlauren.com/Stores-ShowCountries',
)
def parse(self... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime as DT
import cherrypy
import htpc
from cherrypy.lib.auth2 import require, member_of
import requests
import urllib
import logging
from json import loads, dumps
from htpc.helpers import fix_basepath, get_image, striphttp
class Sonarr(object):
def __init... |
"""
Simple classification with XGBoost.
"""
from section1_video5_data import get_data
from sklearn import model_selection
from xgboost import XGBClassifier
import numpy as np
seed=123
# Load prepared data
X, Y = get_data('../data/video1_diabetes.csv')
# Build our single model
c = XGBClassifier(random_state=seed)
re... |
import math
import StringIO
import types
__pychecker__ = 'no-returnvalues'
WS = set([' ', '\t', '\r', '\n', '\x08', '\x0c'])
DIGITS = set([str(i) for i in range(0, 10)])
NUMSTART = DIGITS.union(['.', '-', '+'])
NUMCHARS = NUMSTART.union(['e', 'E'])
ESC_MAP = {'n': '\n', 't': '\t', 'r': '\r', 'b': '\x08', 'f': '\x0c'}
R... |
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Transform a roidb into a trainable roidb by adding a bunch of metada... |
from sqlalchemy import (
Column,
Date,
ForeignKey,
Integer,
String,
Unicode,
Boolean
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm.exc import NoResultFound
... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
import numpy as np
from .executor import Executor
def eval_numerical_grad(f, feed_dict, wrt, h=1e-5):
wrt_val = feed_dict[wrt]
grad = np.zeros_like(wrt_val)
it = np.nditer(wrt_val, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
ix = it.multi_index
old_val = wrt_... |
#!/usr/bin/env python
# ROS node libs
import time
import numpy as np
import rospy
import torch
# from geometry_msgs.msg import Quaternion, Pose, Point, Vector3
from pyquaternion import Quaternion
from google.protobuf import text_format
from sensor_msgs.msg import PointCloud2
from std_msgs.msg import Header, ColorRGBA... |
# --------------------------------------------------------
# Camera sample code for Tegra X2/X1
#
# This program could capture and display video from
# IP CAM, USB webcam, or the Tegra onboard camera.
# Refer to the following blog post for how to set up
# and run the code:
# https://jkjung-avt.github.io/tx2-camera-wi... |
from dataclasses import dataclass
import torch
import torch.nn as nn
import torch.nn.functional as F
@dataclass
class Config:
entity_dim:int=200
relation_dim:int=200
emb_dropout_rate:float=0.3
hidden_dropout_rate:float=0.3
feat_dropout_rate:float=0.2
emb_2D_d1:int=10
emb_2D_d2:int=20
n... |
# Import Keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Activation, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from keras.layers.normalization import BatchNormalization
from ... |
"""Helper functions."""
import string
from enum import Enum
from typing import Any, Dict, List, Set, Tuple, Union
TRUTH_TEXT = frozenset(("t", "true", "y", "yes", "on", "1"))
FALSE_TEXT = frozenset(("f", "false", "n", "no", "off", "0", ""))
PROTECTED_KEYS = frozenset(("secret", "password", "passwd", "pwd", "token"))... |
#!/usr/bin/env python
#
# Copyright (c) 2012, Dave Eddy <dave@daveeddy.com>
# 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
#... |
#!/usr/bin/env python3
T = int(input())
digits = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"]
def find_number(number):
for digit in range(0, len(digits)):
try:
new_number = str(number)
for c in digits[digit]:
index = new_number.i... |
# !/usr/bin/python
# -*- coding:utf-8 -*-
# ***********************************************************************
# Author: Zhichang Fu
# Created Time: 2018-08-25 11:08:53
# Version: 1.0.3 changed by 2018-12-09
# 1.Add two tables combined with join operator.
# ****************************************************... |
#
# Copyright 2019 EPAM Systems
#
# 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 a... |
# 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... |
import pytest
import sys
sys.path.append("..")
import talon as TALON
@pytest.mark.unit
def test_compute_alignment_coverage():
""" Computes what fraction of the read is actually aligned to
the genome by excluding hard or soft-clipped bases."""
MD = "MD:Z:10A3T0T10"
SEQ = "GGGGGGGGGGTGGGAATGGGGG... |
import math
import torch
import torch.distributed as dist
from torch.utils.data.sampler import Sampler
from collections import defaultdict
from utils.misc import logging_rank
class RepeatFactorTrainingSampler(Sampler):
"""
Similar to DistributedSampler, but suitable for training on class imbalanced datasets
... |
from os import environ
from typing import Optional
from pydantic import BaseSettings
class Settings(BaseSettings):
AKASHI_COMPANY_ID: Optional[str] = environ.get('AKASHI_COMPANY_ID')
SLACK_BOT_TOKEN: Optional[str] = environ.get('SLACK_BOT_TOKEN')
SLACK_CHANNEL_ID: Optional[str] = environ.get('SLACK_CHANN... |
# 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
__a... |
import sys
import json
import time
import logging
import pathlib
from typing import Dict
import requests
class EdgarSession():
"""
Overview:
----
Serves as the main Session for the
`EDGARClient`. The `EdgarSession` object
handles all the requests made to EDGAR.
"""
def __init__(self... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyNeurora(PythonPackage):
"""A Python Toolbox for Multimodal Neural Data Representation An... |
class HelloModel:
def __init__(self):
self.text = '<h2>Hello World!</h2>'
def getText(self):
return self.text
|
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
if m == 0 or matrix == [[]]:
return False
for i in range(m):
if matrix... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.