text stringlengths 1 927k |
|---|
# Copyright (c) 2005-2014 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# 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 2 of the License, o... |
import _plotly_utils.basevalidators
class ColorbarValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="colorbar", parent_name="scatter.marker", **kwargs):
super(ColorbarValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name... |
# 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
# distributed under t... |
def voto(n):
from datetime import date
global ano
ano = date.today().year - n
if 65 > ano >= 18:
r = 'OBRIGATÓRIO'
return r
if ano < 18:
r = 'NEGADO'
return r
if ano > 65:
r = 'OPCIONAL'
return r
# programa principal
print('-=' * 20)
ano = int(i... |
import inspect
import pickle
import platform
import pytest
import tests.base.develop_utils as tutils
from pytorch_lightning import Trainer, Callback
from pytorch_lightning.loggers import (
TensorBoardLogger,
MLFlowLogger,
NeptuneLogger,
TestTubeLogger,
CometLogger,
WandbLogger,
)
from pytorch_... |
from django import template
register = template.Library()
@register.filter
def package_usage(user):
return user.package_set.all() |
from .student import Student, StudentIterator
from .belt_level import BeltLevel, BeltLookup
from .paperwork import Paperwork |
""" Data generators for training/inference with siamese Keras model.
"""
import warnings
from typing import List, Iterator, NamedTuple
import numpy as np
import pandas as pd
from tensorflow.keras.utils import Sequence
from .typing import BinnedSpectrumType
class SpectrumPair(NamedTuple):
"""
Represents a pa... |
from df import *
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
import colorama
from colorama import Fore
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
colorama.init(convert=T... |
import sys
from flaky import flaky
from .tools import SRC_ROOT, AutomaticBaseTest, ExplicitBaseTest, NO_FILE, NO_LINK_FILE
sys.path.append(SRC_ROOT)
import webdrivermanager # noqa: E402 I001
class GeckoDriverManagerTestsWithAutomaticLocations(AutomaticBaseTest):
DRIVER_MANAGER = webdrivermanager.GeckoDriverMan... |
from functions import *
# Set up a loop where users can choose what they'd like to do.
choice = ''
display_title_bar()
while choice != 'q':
print('\n[1] Run payroll')
print('[2] Get tenant invoices')
print('[3] Email tenant invoices')
print('[4] Get Bank Transactions')
print('[5] Create Documents')
print(... |
# -*- coding: utf-8 -*-
"""Top-level package for Enhance WeRobot."""
__author__ = """Crazygit"""
__email__ = 'crazygit@foxmail.com'
__version__ = '0.1.0' |
# -*- coding: utf-8 -*-
# Copyright 2020 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 o... |
from django.apps import AppConfig
class SalespersontrackerrestConfig(AppConfig):
name = "salespersonTrackerREST" |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
become: dzdosu
short_description: su with Centrify's Direct Authorize
description:
- This become plugins allows your remote/login user to execute commands as another u... |
import numpy as np
# Make sure that caffe is on the python path:
caffe_root = '/home/ubuntu/dev/caffe/'
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
import sys
import argparse
import torch
import torch.nn.init
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variab... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/09_text_generation.ipynb (unless otherwise specified).
__all__ = ['logger', 'TransformersTextGenerator', 'EasyTextGenerator']
# Cell
import logging
from typing import List, Dict, Union
from collections import defaultdict
import torch
from torch.utils.data import Tensor... |
import datetime
import random
import hashlib
basic = {
'一元微积分',
'多元微积分',
'高等微积分',
'几何与代数',
'随机数学方法',
'概率论与数理统计',
'线性代数',
'复变函数引论',
'大学物理',
'数理方程引',
'数值分析',
'离散数学',
'离散数学(Ⅱ)',
'随机过程',
'应用随机过程',
'泛函分析',
'代数编码理论',
'初等数论与多项式',
'应用统计',
'工程图学基础'... |
import unittest
import logging
import tempfile
import random
import os
import shutil
import json
import time
import docker
import platform
from testfixtures import log_capture
from .context import WDL
from unittest.mock import patch
class RunnerTestCase(unittest.TestCase):
"""
Base class for new runner test ca... |
# coding=utf-8
# Copyright 2019 The TensorFlow Datasets 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 appl... |
# -*- coding: utf-8 -*-
"""Project's custom action 'train' test
"""
import json
from django.urls import reverse
from rest_framework import status
from vision_on_edge.azure_parts.models import Part
from vision_on_edge.azure_settings.models import Setting
from vision_on_edge.cameras.models import Camera
from vision_on... |
from flask import Blueprint
from flask import request
from flask import session
from flask import redirect
from flask import url_for
from flask import render_template
from app import db
from app.models import User
from app.models import Token
from app.models import Application
from app.models import ApplicationSecret
... |
# -*- coding: utf-8 -*-
import torch
import random
import inspect
from itertools import islice
def split_corpus(path, shard_size):
with open(path, "rb") as f:
if shard_size <= 0:
yield f.readlines()
else:
while True:
shard = list(islice(f, shard_size))
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: yandex/cloud/containerregistry/v1/repository_service.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import ... |
#
# geomath.py
#
# some geo coordinate math that I found on the internet
#
# kevinabrandon@gmail.com
#
import math
def HeadingStr(heading):
"""
Gives a heading string given the heading float
"""
headstr = "?"
if heading != None:
if heading < 22.5 or heading >= 337.5:
headstr = "N"
elif heading >=22.5 and ... |
"""
The goal of this script is to showcase kernel inference for the task of estimating
the covariance of a random field that exhibits an instationary correlation structure.
This produces a figure showcasing the kernel inference procedure and its uses
as detailed in the case example nr 3 which deals with applications ... |
"""
This module contains functions to read Caltrans PEMS station data and metadata files.
"""
import pandas as pd
import sys
from ..caada_typing import pathlike as _pathlike
def read_pems_station_csv(csv_file: _pathlike) -> pd.DataFrame:
"""Read a Caltrans PEMS daily station .csv file
Parameters
------... |
# This Python file uses the following encoding: utf-8
x = []
N = int(input('Введите размерность матрицы: '))
for i in range(N):
t = list(map(int, input('Введите новую строчку\t').split()))
x.append(t)
print('Исходная матрица ')
for i in range(N):
for j in range(N):
print(' ', x[i][j], sep=' ', end... |
"""
All rights reserved to cnvrg.io
http://www.cnvrg.io
test_prepcsv.py
==============================================================================
"""
import json
import os
import string
import pandas
import random
import numpy as np
### Produce csv file for testing.
rows_num = 25
data = {}
summary = {}
##... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pogoprotos/networking/requests/messages/get_buddy_walked_message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as ... |
import datetime
import logging
import queue
import subprocess
import time
import threading
import flask
import coffeebuddy.facerecognition
cameralock = queue.Queue(maxsize=1)
thread = None
class CameraThread(threading.Thread, coffeebuddy.facerecognition.FaceRecognizer):
def __init__(self):
super().__in... |
import collections
from typing import Optional
import hypothesis
import pytest
from hypothesis import given
from hypothesis import strategies as st
from morello import (
dtypes,
op_pprint,
pruning,
search,
search_cache,
specs,
system_config,
)
from morello.system_config import current_syst... |
#!/usr/bin/env python3
# The original source code of Poincare Embedding can be found in https://github.com/facebookresearch/poincare-embeddings
# This source code is partially modified for the application to HiG2Vec. |
from core.entity.entity_readers.raw_sql_query_reader import RawSqlQueryReader
from core.entity.entity_readers.query_builders.query_filters import StringQueryFilter
from core.entity.entity_readers.model_emulators import ModelEmulator, ModelEmulatorFileField
from .pinwheel_provider import PinwheelProvider
class Pinwhe... |
r"""
Free quadratic modules
Sage supports computation with free quadratic modules over an arbitrary
commutative ring. Nontrivial functionality is available over `\ZZ` and
fields. All free modules over an integral domain are equipped with an
embedding in an ambient vector space and an inner product, which you
can spe... |
lines = 0
ones = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
file = open('input.txt', 'r+')
for line in file.readlines():
lines += 1
for i in range(12):
if line[i] == '1':
ones[i] += 1
file.close()
gamma = ""
epsilon = ""
for i in range(12):
if ones[i] >= lines / 2:
gamma += "1"
... |
from titlegen.gen_title import train, sample
if __name__ == "__main__":
# extract_resnet_features()
train()
sample() |
import pytest
from fastai.gen_doc.doctest import this_tests
from fastai.basics import *
from fastai.metrics import *
from utils.fakes import fake_learner
from utils.text import CaptureStdout
p1 = torch.Tensor([0,1,0,0,0]).expand(5,-1)
p2 = torch.Tensor([[0,0,0,0,0],[0,1,0,0,0]]).expand(5,2,-1).float()
t1 = torch.arang... |
import os
# Pillow
from PIL import Image, ImageFilter
from matplotlib import pyplot
import random
import analyzer_system as ana_sys
# sample: foler
# - dix.jpg
# - onze.jpg
# - cherry.jpg
# - lamp.jpg
# - kid.jpg
# - house.jpg
# - a.jpg
# - douze.jpg
if __name__ == "__main__":
# Obtenir args:... |
import json
import click
from isic_cli.cli.context import IsicContext
@click.group(short_help='Manage authentication with the ISIC Archive.')
@click.pass_obj
def user(ctx):
pass
@user.command()
@click.pass_obj
def login(obj: IsicContext):
"""Login to the ISIC Archive."""
if obj.user:
click.ech... |
from RecoJets.JetProducers.hltPUIdAlgo_cff import *
hltMVAJetPuIdCalculator = cms.EDProducer('MVAJetPuIdProducer',
produceJetIds = cms.bool(False),
jetids = cms.InputTag(""),
runMvas = cms.bool(True),
... |
# loads .env contents
import settings
# use for approximate string matching
import difflib
import pandas as pd
import os, time, sys
import re, json
from urllib.request import urlopen
from datetime import datetime as dt
from slackclient import SlackClient
keys = {
'weatherbot': os.environ['WEATHERBOT_API_KEY'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 6/26/18
@author: Sanjana Kapoor
@author: John Sigmon
Last modified: 6/28/18
"""
import os
import sys
import json
import pickle as pkl
import spacy
import logging.config
from spacy.attrs import ORTH, LEMMA
from spacy.tokens import Doc
logger = logging.ge... |
from pillowtop.logger import pillow_logging
from pillowtop.processors.interface import BulkPillowProcessor, PillowProcessor
class NoopProcessor(PillowProcessor):
"""
Processor that does absolutely nothing.
"""
def process_change(self, change):
pass
class LoggingProcessor(PillowProcessor):
... |
#!/usr/bin/env python
import argparse
import sys
from typing import List
from typed_argparse import TypedArgs
from typing_extensions import Literal
class MyArgs(TypedArgs):
mode: Literal["a", "b", "c"]
def parse_args(args: List[str] = sys.argv[1:]) -> MyArgs:
parser = argparse.ArgumentParser()
parser.... |
from bs4 import BeautifulSoup as bs
import requests
from pytube import YouTube
base = "https://www.youtube.com/results?search_query="
qstring = "tin tức"
r = requests.get(base+qstring)
page = r.text
soup=bs(page,'html.parser')
vids = soup.findAll('a',attrs={'class':'yt-uix-tile-link'})
videolist=[]
for v in vids:
... |
"""Tests for cvejob.filters modules.""" |
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
""" Utilities for Vispy. A collection of modules that are used in
one or more Vispy sub-packages.
"""
from .logs import logger, set_log_level, use_log_le... |
from mjrl.utils.gym_env import GymEnv
from mjrl.policies.gaussian_mlp import MLP
from mjrl.baselines.quadratic_baseline import QuadraticBaseline
from mjrl.baselines.mlp_baseline import MLPBaseline
from mjrl.algos.npg_cg import NPG
from mjrl.algos.behavior_cloning import BC
from mjrl.utils.train_agent import train_agent... |
###############################################################################
# Code by Christoph Aurnhammer, based on #
# https://github.com/pytorch/examples/tree/master/word_language_model #
# Citation: Aurnhammer & Frank (2019), Neuropsychologia. #
... |
#!/usr/bin/env python
"""Test for the ee.imagecollection module."""
from unittest import mock
import unittest
import ee
from ee import apitestcase
class ImageCollectionTestCase(apitestcase.ApiTestCase):
def testImageCollectionConstructors(self):
"""Verifies that constructors understand valid parameters."""... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
i... |
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from utils import utils_sr
import torch
from argparse import ArgumentParser
from utils.utils_restoration import rgb2y, psnr, array2tensor, tensor2array
import sys
from matplotlib.ticker import MaxNLocator
class PnP_restoration():
def __init_... |
from rest_framework import serializers
class ShotSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(max_length=100)
volume = serializers.IntegerField()
degree = serializers.IntegerField(min_value=0, max_value=100)
cost = serializers.Deci... |
from bip_utils.addr.iaddr_encoder import IAddrEncoder
from bip_utils.addr.algo_addr import AlgoAddr
from bip_utils.addr.atom_addr import AtomAddr
from bip_utils.addr.avax_addr import AvaxPChainAddr, AvaxXChainAddr
from bip_utils.addr.egld_addr import EgldAddr
from bip_utils.addr.eth_addr import EthAddr
from bip_utils.a... |
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from .models import House
class HouseSerializer(serializers.ModelSerializer):
serializers.ReadOnlyField()
class Meta:
model = House
fields = [
"id",
"area_unit",
"bath... |
from autosklearn.pipeline.constants import DENSE, UNSIGNED_DATA, INPUT, SPARSE
from autosklearn.pipeline.components.data_preprocessing.rescaling.abstract_rescaling \
import Rescaling
from autosklearn.pipeline.components.base import AutoSklearnPreprocessingAlgorithm
class NoRescalingComponent(Rescaling, AutoSklear... |
# -*- coding: utf8 -*-
from __future__ import unicode_literals
import locale
import os
from django.db.backends.postgresql.client import DatabaseClient
from django.test import SimpleTestCase, mock
from django.utils import six
from django.utils.encoding import force_bytes, force_str
class PostgreSqlDbshellCommandTest... |
# coding=utf-8
# Copyright (c) Facebook, Inc. and its affiliates.
# Copyright (c) HuggingFace Inc. team.
#
# 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... |
#!/usr/bin/env python
"""
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");... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY=os.environ.get('SECRET_KEY') or 'you-will-never-guess' |
from django.conf import settings
# Number of messages to display per page.
MESSAGES_PER_PAGE = getattr(settings,'ROSETTA_MESSAGES_PER_PAGE',10)
# Enable Google translation suggestions
ENABLE_TRANSLATION_SUGGESTIONS = getattr(settings,'ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS',True)
"""
When running WSGI daemon mode,... |
from __future__ import print_function
import string
import logging
import curses # Needed for colours
back = curses.COLOR_WHITE
front = curses.COLOR_BLACK
# Switch for white backgrounds
###back = curses.COLOR_BLACK
###front = curses.COLOR_WHITE
COLORS = [
# Color combinations, (ID#, foreground, background)
... |
# pylint: skip-file
import os
from pathlib import Path
from databases import Databases
from dotenv import load_dotenv
from playhouse.migrate import *
env_path = Path('/var/www/qyapp') / '.env_core'
load_dotenv(dotenv_path=env_path, verbose=True)
databases = Databases()
database_names = databases.get_names()
migrati... |
from flask import render_template
import app.charts as charts
from . import app
@app.route("/")
def search():
return render_template('search.html', title='Search')
@app.route("/dashboard")
def hello():
_dashboard = charts.dashboard.create_charts()
return render_template('base.html',
... |
#!/usr/bin/env python
# coding:utf-8
import tornado.web
import tornado.ioloop
from tornado.options import define, options, parse_command_line
import signal
import threading
import time
def close_server():
from custor.logger import logger
MAX_WAIT_SECONDS_BEFORE_SHUTDOWN = 0
deadline = time.time() + MAX_W... |
#
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
# Copyright (c) 2019-2020, BlazingSQL, 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... |
import logging
from http import HTTPStatus
from typing import Dict, Optional
from urllib.parse import urlencode
import pytest
from django.http import (
HttpResponseBadRequest,
HttpResponseNotAllowed,
HttpResponseNotFound,
)
from django.test import Client
from django.urls import reverse
from pytest_django.a... |
from pathlib import Path
PROJECT_ROOT_FOLDER = Path(__file__).parent.parent
DATA_FOLDER = PROJECT_ROOT_FOLDER / 'data'
SCORES_DATA_FILEPATH = DATA_FOLDER / 'data_clinical_scoring.xlsx'
LYING_VIDEOS_DATA_FOLDER = DATA_FOLDER / 'data_stickfigure_coordinates_lying'
SITTING_VIDEOS_DATA_FOLDER = DATA_FOLDER / 'data_stickfi... |
import random
import pytest
from rotkehlchen.constants.assets import A_BTC, A_ETH, A_EUR, A_USD
from rotkehlchen.fval import FVal
from rotkehlchen.tests.utils.constants import A_BSV, A_DASH, A_IOTA
from rotkehlchen.tests.utils.history import prices
@pytest.mark.skip("https://github.com/rotkehlchenio/rotkehlchen/iss... |
#!/usr/bin/env python
import os
import subprocess
import sys
# Required third-party imports, must be specified in pyproject.toml.
import packaging.version
import setuptools
def process_options():
"""
Determine all runtime options, returning a dictionary of the results. The
keys are:
'rootdir': ... |
import numpy as np
class Subclone:
"""
Initializes a Subclone Population.
:attr label: Either A, B or S
:attr fitness: Current fitness
:attr prop: Current Proportion
"""
def __init__(self, lbl, c, alpha, prop=0.333, parent=None, birthtime=None, color=None):
... |
#!/usr/bin/env python3
# Copyright (c) 2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Run fuzz test targets.
"""
import argparse
import configparser
import os
import sys
import subprocess
impor... |
import re
from typing import Any, Dict
from django.http import HttpRequest
from django.views.debug import SafeExceptionReporterFilter
class ZulipExceptionReporterFilter(SafeExceptionReporterFilter):
def get_post_parameters(self, request: HttpRequest) -> Dict[str, Any]:
filtered_post = SafeExceptionReporte... |
import pytest
import numpy as np
import scipy.sparse as sp
import gust
class TestPreprocessing:
def setup(self):
self.A = sp.csr_matrix(np.array(
[[1. , 0. , 0.5, 0. , 0. ],
[0. , 1. , 1. , 0. , 1. ],
[0.5, 0. , 1. , 0. , 0. ],
[0. , 0. ,... |
# Copyright (c) 2021 PPViT 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 applicable ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by Tong He and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
"""
import os
import numpy as np
class config:
BASE_DIR = '../../../../../../data/fmri_predict_behavior'
CUR_DIR = os.getcwd()
INTER_DIR = os.path.... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from typing import Optional, Dict, List
from cloud_controller.knowledge.model import Statefulness, Component
from cloud_controller.knowledge.user_equipment import UserEquipment
from cloud_controller.middleware.helpers import OrderedEnum
class Compin:
"""
A common base class for managed and unmanaged compins.... |
"""
Author: Gustavo Soares
"""
import math
import pandas as pd
from bloomberg import BBG
from pandas.tseries.offsets import BDay
from datetime import timedelta
class CommFutureTracker(object):
"""
Class for creating excess return indices for commodity futures using data from bloomberg.
A default front-mo... |
from model.contact import Contact
def test_modify_contact_first_name(app):
app.contact.modify_first_contact(Contact(first_name="second first name"))
def test_modify_contact_last_name(app):
app.contact.modify_first_contact(Contact(last_name="second last name")) |
from usaspending_api.common.exceptions import InvalidParameterException
from usaspending_api.search.filters.elasticsearch.filter import _Filter, _QueryType
from usaspending_api.search.filters.elasticsearch.HierarchicalFilter import HierarchicalFilter, Node
from elasticsearch_dsl import Q as ES_Q
class NaicsCodes(_Fil... |
from django.contrib.auth.models import BaseUserManager
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
class MyUserManager(BaseUserManager):
def create_user(self, email, firstname=None, lastname=None, username=None, password=None):
if not email:
... |
pytest_plugins = ["guillotina.tests.fixtures", "guillotina_graphql.tests.fixtures"] |
# Copyright 2012 OpenStack Foundation
#
# 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... |
from unittest import TestCase
from unittest.mock import Mock
import utils
import data
from utils import prepare_data
from tests.mock_data import get_df, get_preproc_config
class TestScaling2d(TestCase):
def setUp(self):
try:
reload(data)
reload(utils)
except NameError:
... |
# To add a new cell, type ''
# To add a new markdown cell, type ' [markdown]'
from vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting
from vnpy.app.cta_strategy.strategies.test_strategy import (
TestStrategy,
)
from datetime import datetime
engine = BacktestingEngine()
engine.set_pa... |
#-------------------------------------------------------------------------------
# !!! cross_val_predict uses stratified split
#-------------------------------------------------------------------------------
# Main concept for testing returned arrays:
# 1). create ground truth e.g. with cross_val_predict
# 2). run vecs... |
#!/usr/bin/python
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
"""
Enlace al problema:
https://leetcode.com/problems/merge-two-sorted-lists/
Si deseas probar la solución sólo tienes que copiar la clase Solution
ya que dicha clase es la que se ejecuta en la plataforma de LeetCode.
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
... |
import json
_jalbums_relinked = """
{
"href": "https://api.spotify.com/v1/artists/1vCWHaC5f2uS3yhpwWbIA6/albums?offset=0&limit=5&include_groups=album,single,compilation,appears_on&market=ES",
"items": [
{
"album_group": "album",
"album_type": "album",
"artists": [
{
"externa... |
import numpy as np
from random import sample
from some_bandits.bandit_options import bandit_args
from some_bandits.utilities import convert_conf, save_to_pickle, calculate_utility
from some_bandits.bandits.Bandit import Bandit
from some_bandits.bandits.Expert import Expert
from statistics import mean
ACTION = 0
REWARD... |
import os
CELERY_BROKER_URL_DOCKER = "amqp://admin:mypass@rabbit:5672/"
CELERY_BROKER_URL_LOCAL = "amqp://localhost/"
CM_REGISTER_Q = "rpc_queue_CM_register" # Do no change this value
CM_NAME = "CM - Heat sources potential"
RPC_CM_ALIVE = "rpc_queue_CM_ALIVE" # Do no change this value
RPC_Q = "rpc_queue_CM_comput... |
import flask_wtf
import wtforms
class LoginForm(flask_wtf.Form):
"""Accepts a nickname and a room."""
name = wtforms.fields.StringField('Name', validators=[wtforms.validators.Required()])
#room = StringField('Room', validators=[Required()])
submit = wtforms.fields.SubmitField('Start') |
# -*- coding: utf-8 -*-
# @Time : 2020-12-25 22:28
# @Author : Di Zhu
import json
import logging
import os
import shutil
import torch
class Params(object):
"""Class that loads hyperparameters from a json file.
Example:
```
params = Params(json_path)
print(params.learning_rate)
params.lea... |
import os
import json
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.config import Config
from starlette.requests import Request
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import HTMLResponse, RedirectResponse
from authlib.integr... |
# 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 Debugedit(AutotoolsPackage):
"""
Debugedit is a set of libraries and programs for crea... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import logging
from schema import And, Optional
from .constants import MASKER_DICT
from ..utils.config_validation import CompressorSchema
from ..compressor import Pruner
__all__ = ['LevelPruner', 'SlimPruner', 'L1FilterPruner', 'L2FilterPruner',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.