text stringlengths 2 999k |
|---|
import asyncio
import json
import logging
import traceback
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
import aiohttp
from joker.rpc.util import wrap_http_handler
from joker.server.outbound_message import NodeType
from joker.server.server import ssl_context_for_server
from joker.ty... |
import unittest
import filte.indicator_filter as indicator_filter
class TestIndicatorFilter(unittest.TestCase):
def test_make_previous_quarter(self):
this_quarter = '20190331'
pre_quarter = indicator_filter.make_previous_quarter(
this_quarter)
self.assertEqual(pre_quar... |
#! /usr/bin/env python
import smtplib, sys, datetime, time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import datetime, glob, os
EMAIL_EDITOR_FROM = "dft-no-reply@evidenceproject.eu"
EMAIL_EDITOR_FROM_NAME = "EVIDENCE Project: Forensics Tools Catalogue - Editor"
EMAIL_EDITOR_UP... |
import torch
import torch.nn.functional as F
def invariance_loss(z1: torch.Tensor, z2: torch.Tensor) -> torch.Tensor:
"""Computes mse loss given batch of projected features z1 from view 1 and
projected features z2 from view 2.
Args:
z1 (torch.Tensor): NxD Tensor containing projected features from... |
default_app_config = "transactional_mail.apps.TransactionalMailConfig" |
import mock
import MySQLdb
import unittest2
from thanatos.questions import inventory
class SlotsQuestionTestCase(unittest2.TestCase):
def setUp(self):
self.mock_db_connection = mock.Mock(spec=MySQLdb.connection)
def test_class_initializes(self):
""" Simply test we can create an instance o... |
#-------------------------------------------------------------------------
# The Azure Batch Apps Python Client
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... |
from setuptools import setup, find_packages
import os
import pgcryptoauth
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
README = read('README.rst')
setup(
name='django-pgcryptoauth',
version=pgcryptoauth.__version__,
description='Django hasher for pgcrypto enco... |
"""
Advances in Financial Machine Learning, Marcos Lopez de Prado
Chapter 2: Financial Data Structures
This module contains the functions to help users create structured financial data from raw unstructured data,
in the form of tick, volume, and dollar run bars.
These bars are used throughout the text book (Advances ... |
#!/usr/bin/python
# Filename: analyzer.py
"""
A event-driven analyzer abstraction,
including low-level msg filter and high-level analyzer
Author: Yuanjie Li
"""
"""
Analyzer 2.0 development plan
Step 1: A query() interface with SQLlite
- Backward compatability with Analyzer 1.0
Step... |
from django.test import TestCase
from .models import ShopItem, Colour, ShopItemFacetGroup
from .utils import check_counts
class TestModelSignals(TestCase):
def setUp(self):
self.f = ShopItemFacetGroup()
self.f.watch_model(ShopItem)
self.red = Colour.objects.create(name="red")
self... |
from setuptools import setup, find_packages
import setuptools
from setuptools.extension import Extension
from distutils.command.build_ext import build_ext as DistUtilsBuildExt
NAME ='deepforest'
VERSION = '0.3.4'
DESCRIPTION = 'Tree crown prediction using deep learning retinanets'
URL = 'https://github.com/Weecology/D... |
# coding: utf-8
# Copyright 2019, 2020 IBM 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... |
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
from .googlehomenotifier import GoogleHome, get_googlehomes
|
def solve():
n = int(input())
A = list(map(int,input().split()))
A.sort()
m = n//2
mid = A[m]
print(abs(A[0] - mid) + abs(A[0]-A[-1]) + abs(A[-1]-mid))
if __name__ == '__main__':
for t in range(int(input())):
solve() |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from loguru import logger
import os
import sys
import numpy as np
import torch
import torch.nn.functional as F
from .. import FairseqDatase... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup
needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv)
pytest_runner = ['pytest-runner >=4.0,<5dev'] if needs_pytest else []
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()... |
import os
import subprocess
os.remove("pspamm.h") if os.path.exists("pspamm.h") else None
os.remove("pspamm.cpp") if os.path.exists("pspamm.cpp") else None
os.remove("pspamm2.h") if os.path.exists("pspamm2.h") else None
os.remove("pspamm2.cpp") if os.path.exists("pspamm2.cpp") else None
include_guard = """#ifndef PS... |
# Copyright 2019 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... |
# Generated by Django 3.0.3 on 2020-04-12 23:33
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0008_auto_20200412_1929'),
]
operations = [
migrations.AlterField(
... |
from compare import comp_unidim,comp_multivar,comp_sys_solv
from functions import g,gpp,gp,h,H
"""
the numbers of the 10 operations for unidimensional optimization:
1: usfs
2: usas
3: bf
4: bs
5: halv
6: Fibo
7: golden
8: Newton-Rapson
9: Quasi-Newton
10: Secant
"""
comp_unidim(g,-3,5,[0,1,2,3])
comp... |
"""
Django settings for ChemiRegV2Django project.
Generated by 'django-admin startproject' using Django 2.0.2.
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/
"""
imp... |
from asyncio import create_task, get_running_loop, Queue
from asgiref.compatibility import guarantee_single_callable
from django.conf import settings
def asgi3_to_asgi2(app):
def _wrapped_as_asgi2(scope):
async def _inner(receive, send):
return await app(scope, receive, send)
return ... |
"""Elastic nuclear recoil rates, spin-independent and spin-dependent
"""
import numpy as np
import numericalunits as nu
from scipy.interpolate import interp1d
from scipy.integrate import quad
import wimprates as wr
export, __all__ = wr.exporter()
__all__ += ['ATOMIC_WEIGHT']
ATOMIC_WEIGHT = dict(
Xe=131.293,
... |
#!/usr/bin/env python3
import argparse
import sys
import os
import time
import logging
import unittest
import copy
import queue
import concurrent.futures
import multiprocessing
from collections import deque
from operator import itemgetter
from pprint import pprint
import numpy as np # [y, x] or [height, width]
log... |
from django.conf.urls import url, patterns
from .views import (
my_tickets_view,
create_project_view,
update_project_view,
project_view,
create_ticket_view,
update_ticket_view,
delete_ticket_view,
project_list_view,
)
urlpatterns = patterns(
'',
url(r'^projects/$', project_lis... |
import os
import sys
import time
from contextlib import contextmanager
import pendulum
import pytest
from dagster import pipeline, repository, solid
from dagster.core.definitions.decorators.sensor import sensor
from dagster.core.definitions.job import JobType
from dagster.core.definitions.sensor import RunRequest, Ski... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: sns_sqs_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 _message
from google.protobuf import reflection a... |
# Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import logging
from slackclient import SlackClient
from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
from awx.main.notifications.base import AWXBaseEmailBackend
logger = logging.getLogger('awx.main.notificati... |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Support for ALL_ALL.xml format used by Igoogle plug-ins in Google Desktop.'''
import StringIO
import re
import xml.sax
import x... |
#
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
from . import PYQT6, PYQT5, PythonQtError
if PYQT6:
from PyQt6.sip import *
elif PYQT5:
from PyQt5.sip import *
else:
raise PythonQtError("Currently selected Qt binding does no... |
#!/usr/bin/python
import unittest
import math
from planegeometry.structures.points import Point
from planegeometry.structures.segments import Segment
from planegeometry.algorithms.geomtools import orientation
from planegeometry.algorithms.geomtools import angle3points
from planegeometry.algorithms.geomtools import fin... |
# solution.py
import sys
from utils import validate_call, parser, term_splitter
from polynomial import (
Polynomial,
Term
)
def main():
validate_call(sys.argv)
my_list = parser(sys.argv[1])
term_list = []
for elem in my_list:
term = term_splitter(elem)
term_list.append(Term(term))
function = Polynomial... |
import contextlib
import threading
default_app_config = 'olympia.core.apps.CoreConfig'
_locals = threading.local()
_locals.user = None
_locals.remote_addr = None
def get_user():
return getattr(_locals, 'user', None)
def set_user(user):
_locals.user = user
def get_remote_addr():
return getattr(_loc... |
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import hashlib
import os
import shutil
import numpy as np
import rasterio
from rasterio.transform import Affine
from rasterio.crs import CRS
SIZE = 64 # image width/height
np.random.seed(0)
meta =... |
import pdf_to_json as p2j
import json
url = "file:data/multilingual/Latn.EKK/Mono_16/udhr_Latn.EKK_Mono_16.pdf"
lConverter = p2j.pdf_to_json.pdf_to_json_converter()
lConverter.mImageHashOnly = True
lDict = lConverter.convert(url)
print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True))
|
from __future__ import annotations
from typing import Callable
from typing import NoReturn
from ...base import BaseEstimator
import numpy as np
def default_callback(fit: Perceptron, x: np.ndarray, y: int):
pass
class Perceptron(BaseEstimator):
"""
Perceptron half-space classifier
Finds a separating... |
"""
Copyright (c) 2014-2015-2015, The University of Texas at Austin..
All rights reserved.
This file is part of BLASpy and is available under the 3-Clause
BSD License, which can be found in the LICENSE file at the top-level
directory or at http://opensource.org/licenses/BSD-3-Clause
"""
from .co... |
import math
import numpy as np
import random as rn
# import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
class wideAndDeep(object):
"""
初始化参数
"""
def __init__(self, learning_rate, feature_length, embedding_length, batch_size, hidden_layer):
self.learning_rate = l... |
# encoding: utf-8
"""
graceful.py
Created by Thomas Mangin on 2012-07-17.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
from struct import pack
from struct import unpack
from exabgp.protocol.family import AFI
from exabgp.protocol.family import SAFI
from exabgp.bgp.message.open.capability.capability i... |
import wx
from wx.lib.agw.floatspin import FloatSpin, EVT_FLOATSPIN
""" Classes representing FDF values and wx widgets for them
"""
class FDFValue(object):
widgets = None
_value = None
def Enable(self, value):
for widget in self.widgets:
widget.Enable(value)
class BoolValue(FDFVa... |
#!C:\Users\Simbatronix\PycharmProjects\planetary-api\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '... |
# DADSA - Assignment 1
# Reece Benson
import json
import random
from math import ceil, floor
from classes import Player
from classes import Season
from classes import Tournament
from classes import Round
from classes import Match
class Handler():
# Define the variables we will be using
app = None
prize_mo... |
import pylab
import os
import numpy as np
import librosa
import imagehash
from PIL import Image
import operator
import pickle
import soundfile as sf
import matplotlib.pyplot as plt
import librosa.display
# TODO:
# - implement protected variables?
# - rectify similarity index value *IMPORTANT*
# - increase simila... |
#/*
# * Copyright (C) 2017 - This file is part of libecc project
# *
# * Authors:
# * Ryad BENADJILA <ryadbenadjila@gmail.com>
# * Arnaud EBALARD <arnaud.ebalard@ssi.gouv.fr>
# * Jean-Pierre FLORI <jean-pierre.flori@ssi.gouv.fr>
# *
# * Contributors:
# * Nicolas VIVET <nicolas.vivet@ssi.gouv.fr>
... |
# AutoEncoders
# Importing the libraries
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
#Configs
train_file = '../datasets/Escamb_wtdata_train_alarm_86400.csv.gz'
exclude_columns... |
# -*- coding: utf-8 -*-
#
# dsenum documentation build configuration file, created by
# sphinx-quickstart on Thu Aug 6 13:54:36 2020.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... |
from decimal import Decimal
import time
import logging
import asyncio
import pandas as pd
from typing import List, Dict, Tuple
from hummingbot.core.utils.async_utils import safe_ensure_future
from hummingbot.core.clock import Clock
from hummingbot.core.data_type.limit_order import LimitOrder
from hummingbot.core.data_t... |
# Copyright 2019, OpenTelemetry 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 applicable law or agreed to i... |
# $Id: __init__.py 7984 2016-12-09 09:48:27Z grubert $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
This is the Docutils (Python Documentation Utilities) package.
Package Structure
=================
Modules:
- __init__.py: Contains component base cl... |
#!/usr/bin/env python3
# Copyright (c) 2015-2018 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 block processing."""
import copy
import struct
import time
from test_framework.blocktools import ... |
from __future__ import annotations
class TokenParser:
"""
Parses tokens from a string passed to StringArgs.
"""
def __init__(self) -> None:
self._string: str = ""
self._cursor: int = 0
self._current: str | None = None
self._next_: str | None = None
def parse(self,... |
from passlib.context import CryptContext
from trackme.config import Configuration
from trackme.tracking.types.user import UserInput
config = Configuration()
hash_manager = CryptContext(schemes=[config.HASH_ALGO], deprecated="auto")
def hasher(user: UserInput) -> str:
return str(hash_manager.hash(f"{user.name}{... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) Copyright 2011-2015 HP Development Company, L.P.
#
# 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, or
# (at... |
import os
os.system("python train.py --dataroot .\\datasets\\font --model font_translator_gan --name test_new_dataset --no_dropout --batch_size 128 --style_channel 10") |
from dipsim import multiframe, util
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.patches as patches
import os; import time; start = time.time(); print('Running...')
import matplotlib.gridspec as gridspec
# Main input parameters
col_labels = ['Geometry\n(NA${}_{\\textrm{ill}}$ ... |
import sys
# FIX only prints last run
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open("logfile.log", "w")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
#this flush method is ne... |
"""
MIT License
Copyright (c) 2020 NaveenKumar
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, d... |
"""
WSGI config for socialdistribution project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('D... |
import urllib.parse
from odoo.http import request
from odoo.addons.http_routing.models.ir_http import slug
class JSONTypes():
@staticmethod
def productJSON(name, item_id, code, price, attribute_line_ids, variants, configurable_children,
size_attribute_name, color_attribute_name, host_odoo... |
from fro._implementation.chompers import abstract
class AlternationChomper(abstract.AbstractChomper):
def __init__(self, chompers, significant=True, name=None):
abstract.AbstractChomper.__init__(self, significant, name)
self._chompers = list(chompers)
def _chomp(self, state, tracker):
... |
from pymyorm.database import Database
from config import db
from models.admin import Admin
from models.admin_role import AdminRole
if __name__ == '__main__':
Database.connect(**db)
exists = Admin.find().select('a.*').alias('a') \
.join(table=AdminRole.tablename, alias='r', on='a.role = r.id') \
... |
#Desafio33
#Faça um programa que leia 3 números
#e mostre qual é o maior e qual é o menor.
n1=int(input('Digite o primeiro número: '))
n2=int(input('Digite o segundo número: '))
n3=int(input('Digite o terceiro número: '))
#Vereficando o menor número
menor=n1
if n2<n1 and n2<n3:
menor= n2
if n3<n1 and n3<n2:
men... |
#!/usr/bin/env python
import sys
import random
from datetime import datetime, timedelta
time_format = "%Y-%m-%d %H:%M:%S"
time_start = datetime.strptime("2018-04-13 16:35:21", time_format)
random.seed(datetime.now())
while True:
line = sys.stdin.readline()
if not line:
break
time_start = tim... |
"""Implement the interface for messages."""
from pyavreceiver.response import Message
class TemplateMessage(Message):
"""Implement the message representation and parsers."""
|
# Copyright 2021 Google LLC.
#
# 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 conditions and the following disclaimer.
#
#... |
"""Module for trying to find card info and write them to card_info"""
import json
import pandas as pd
import numpy as np
from collections import defaultdict
PATHBASE = "../card_info/specifics/"
def get_card_quality(df):
df["DrawQualityNew"] = (2*pd.to_numeric(df["Cards"], errors='coerce')).fillna(0).astype(np... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-12 20:17
from __future__ import unicode_literals
from django.db import migrations
import image_cropping.fields
class Migration(migrations.Migration):
dependencies = [
('CMS', '0011_auto_20180410_1429'),
]
operations = [
mi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crm', '0021_auto_20170110_1159'),
]
operations = [
migrations.AlterModelOptions(
name='organization',
... |
x = 0
while x <= 10:
y = 0
print()
print("======", "table of", x, "======")
print()
while y <= 10:
print(x, "*", y, "=", x * y)
y += 1
x += 1
|
##########################################################################
#
# Copyright (c) 2013-2015, John Haddon. 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 ... |
from datetime import datetime
import os
import unittest
from dmi_open_data import DMIOpenDataClient, ClimateDataParameter
class TestClient(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.client = DMIOpenDataClient(api_key=os.getenv("DMI_CLIMATE_DATA_API_KEY"))
def test_observations(sel... |
#!/usr/bin/python
#
# Copyright 2011 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 required by... |
import os
from django import VERSION as DJANGO_VERSION
BASE_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3',
}
}
SECRET_KEY = 'fake-key'
INSTALLED_APPS = (
'linaro_django_pagination',
)
if DJANGO_VERSION >= (1, 8):
... |
# -*- coding: utf-8 -*-
"""
Part of the astor library for Python AST manipulation.
License: 3-clause BSD
Copyright 2012 (c) Patrick Maupin
Copyright 2013 (c) Berker Peksag
"""
__version__ = '0.4'
from .codegen import to_source # NOQA
from .misc import iter_node, dump, all_symbols, get_anyop # NOQA
from .misc imp... |
TIMEZONE = "America/Costa_Rica"
DEBUG = False |
import os
def checkFileName(fileObj,ignore_file_name):
# 读取忽略规则
ignore_file_path = os.path.join(os.getcwd(), ignore_file_name)
f4 = open(ignore_file_path, 'r', encoding='utf-8')
line_ignore_all_str = f4.readlines()
is_ignore = False
for line_ignore in line_ignore_all_str:
# 去掉\n
... |
#!/usr/bin/env python
#coding: utf-8
import argparse
import sys
import unicodedata
def zen_han(char):
res = unicodedata.east_asian_width(char)
if res == 'F' or res == 'W':
return True
else:
return False
def make_tategaki(sents, return_len, gyo_h=0):
tategaki_script = []
for i in... |
#!/usr/bin/python
# Classification (U)
"""Program: elasticsearchstatus_get_node_status.py
Description: Unit testing of get_node_status in
elastic_class.ElasticSearchStatus.
Usage:
test/unit/elastic_class/elasticsearchstatus_get_node_status.py
Arguments:
"""
# Libraries and Global Var... |
a = int(input('Primeiro valor: '))
b = int(input('Segundo valor: '))
c = int(input('Terceiro valor: '))
# Verificar quem é menor.
menor = a
if b < a and b < c:
menor = b
if c < a and c < b:
menor = c
# Verificando quem é o maior.
maior = a
if b > a and b > c:
maior = b
if c > a and c > b:
maior = c
pr... |
import argparse
import json
import numpy as np
import torch
import os
from matplotlib import cm, pyplot as plt
from tensorboardX import SummaryWriter
from torch import optim
from torch.nn.utils import clip_grad_norm_
from torch.utils import data
from tqdm import tqdm
import data as data_
import nn as nn_
import utils... |
from testfixtures import LogCapture
from twisted.internet import defer
from twisted.trial.unittest import TestCase
from scrapy import Request, Spider
from scrapy.utils.test import get_crawler
from tests.mockserver import MockServer
class LogExceptionMiddleware:
def process_spider_exception(self, response, excep... |
"""Color palettes in addition to matplotlib's palettes."""
from matplotlib import cm, colors
# Colorblindness adjusted vega_10
# See https://github.com/theislab/scanpy/issues/387
vega_10 = list(map(colors.to_hex, cm.tab10.colors))
vega_10_scanpy = vega_10.copy()
vega_10_scanpy[2] = '#279e68' # green
vega_10_scanpy[4... |
import pytest
from rafs import RafsMount, RafsConf, RafsImage, Backend, Compressor
from nydus_anchor import NydusAnchor
from workload_gen import WorkloadGen
from distributor import Distributor
from utils import logging_setup, Size, Unit
import verifier
import random
from nydusd_client import NydusAPIClient
import time
... |
from functools import partial
class Pipe:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
_methods = {">>": "__rrshift__", "|": "__ror__", "^": "__rxor__"}
def pipeliner(operator):
if operator not in {">>", "|", "^"}:
... |
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class EmailBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
UserModel = get_user_model()
try:
user = UserModel.objects.get(email=username)
... |
"""
ASGI config for pbiblisite project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SE... |
# *******************************************************************************
# Copyright (C) 2021 INAF
#
# This software is distributed under the terms of the BSD-3-Clause license
#
# Authors:
# Ambra Di Piano <ambra.dipiano@inaf.it>
# *******************************************************************************... |
#!/usr/bin/python
#
# This examines all noise diode firings in an HDF5 file and compares the timestamp
# of each firing with one derived from the rise in recorded power.
#
# Ludwig Schwardt
# 8 February 2011
#
import time
import optparse
import pickle
import numpy as np
import katdal
# Helper routines
def contigu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
smorest_sfs.modules.users.resource
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
用户的资源模块
"""
from typing import Dict, List
from flask.views import MethodView
from flask_jwt_extended import current_user
from flask_sqlalchemy import BaseQuery
from loguru import... |
from nyaggle.version import __version__
|
import torch
from torch.nn.quantized.modules.utils import ReferenceableQuantizedModule
from . import subgraph_rewriter_FORKED_DO_NOT_USE
from .graph_module import QuantizedGraphModule
from .quantized_fusion_patterns_and_replacements import get_fbgemm_patterns_and_replacements
from .match_utils import is_match
from .mat... |
import os
import os.path
import jinja2
QUAYPATH = os.getenv("QUAYPATH", ".")
QUAYDIR = os.getenv("QUAYDIR", "/")
QUAYCONF_DIR = os.getenv("QUAYCONF", os.path.join(QUAYDIR, QUAYPATH, "conf"))
QUAY_LOGGING = os.getenv("QUAY_LOGGING", "stdout") # or "syslog"
QUAY_SERVICES = os.getenv("QUAY_SERVICES", [])
QUAY_OVERRID... |
from plark_game.classes.pelicanAgentFixedSBs import PelicanAgentFixedSBs
import jsonpickle
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Pelican_Agent_Any_Size(PelicanAgentFixedSBs):
def __init__(self):
super(Pelican_Agent_Any_Size, self).__init__()
def getActi... |
import sys
import os
import glob
import shutil
import datetime
assert 'pymel' not in sys.modules or 'PYMEL_INCLUDE_EXAMPLES' in os.environ, "to generate docs PYMEL_INCLUDE_EXAMPLES env var must be set before pymel is imported"
# remember, the processed command examples are not version specific. you must
# run cmdcach... |
import pygame
from pygame.time import get_ticks
from Globals import SPACER
from Globals import FONT_SIZE
from Globals import BG_COLOR
from Color import Color
# ===================================================================================
class Displayable:
""" Display a static entity on the screen. """
... |
# -*- coding: utf-8 -*-
#
# WeatherPlugin E2
#
# Coded by Dr.Best (c) 2012-2013
# Support: www.dreambox-tools.info
# E-Mail: dr.best@dreambox-tools.info
#
# This plugin is open source but it is NOT free software.
#
# This plugin may only be distributed to and executed on hardware which
# is licensed by Dream Multimedia... |
import pdb
INTEGER = "INTEGER"
PLUS = "PLUS"
MINUS = "MINUS"
MUL = "MUL"
DIV = "DIV"
OPAR = "OPAR"
CPAR = "CPAR"
EOF = "EOF"
class Token(object):
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
return "Token({}, {})".format(self.type, self.value... |
"""
load_route.py
Load route points from url.
"""
from datetime import datetime
import urllib2
from flask import abort
from pykml import parser
def load_route(url):
"""Load route from provided URL."""
obj = urllib2.urlopen(url)
res = obj.read()
kml_str = ""
for line in iter(res.splitlines()):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.