text stringlengths 3.07k 22.1k |
|---|
from ChessBoard import *
from ChessView import ChessView
from main_tf2 import *
import tkinter
def real_coord(x):
if x <= 50:
return 0
else:
return (x-50)//40 + 1
def board_coord(x):
return 30 + 40*x
class ChessGame:
board = None #ChessBoard()
cur_round = 1
game_mode = 1... |
""".. Ignore pydocstyle D400.
===============
Elastic Indices
===============
Main two classes
.. autoclass:: resolwe.elastic.indices.BaseDocument
:members:
.. autoclass:: resolwe.elastic.indices.BaseIndex
:members:
"""
import copy
import logging
import threading
import elasticsearch_dsl as dsl
from elas... |
#!/usr/bin/python3
__author__ = "NIU"
import happybase as hb
import redis
import time
import psycopg2
pool = redis.ConnectionPool(host='192.168.1.39', port=6379, db=3)
r = redis.Redis(connection_pool=pool)
def printTime():
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
d... |
# Copyright (c) 2021, 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... |
import numpy as np
import random,numpy,pdb
import itertools as it
__doc__ = '''parameter space implementation for simulated annealing'''
def reflect(p,a,b):
'''force p to be on the interval [a,b] using reflective boundaries'''
if p < a:p = a + (a - p)
if p > b:p = b - (p - b)
return p
de... |
import numpy as np
import pytest
from pyjackson import deserialize, serialize
from pyjackson.errors import DeserializationError, SerializationError
from ebonite.core.analyzer.dataset import DatasetAnalyzer
from ebonite.core.objects.dataset_type import (DatasetType, DictDatasetType, ListDatasetType, PrimitiveDatasetTyp... |
from collections import OrderedDict
from itertools import zip_longest
from typing import Iterable, Sequence, Tuple, Union
from lxml import etree
from requests import Response
from requests_toolbelt.multipart.decoder import BodyPart
from rets.errors import RetsParseError, RetsApiError, RetsResponseError
from rets.http... |
"""Package providing reddit class mixins."""
from json import dumps
from ....const import API_PATH
from .editable import EditableMixin
from .fullname import FullnameMixin
from .gildable import GildableMixin
from .inboxable import InboxableMixin
from .inboxtoggleable import InboxToggleableMixin
from .messageable import... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2016 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
import uuid
from datetime import datetime
from sqlalchemy import Integer, DateTime, Boolean, String
from sqlalchemy import Column, MetaData, Table, ForeignKey, select
from sysinv.open... |
import errno
import os
import time
class PWMError(IOError):
"""Base class for PWM errors."""
pass
class PWM(object):
# Number of retries to check for successful PWM export on open
PWM_STAT_RETRIES = 10
# Delay between check for scucessful PWM export on open (100ms)
PWM_STAT_DELAY = 0.1
... |
from __future__ import print_function, unicode_literals
import datetime
import fnmatch
import hashlib
import json
import os
import os.path
import re
import time
import requests
from six import string_types, text_type
from six.moves.urllib.parse import quote
from egnyte import exc, configuration
JSON_HEADERS = {'con... |
import argparse
import numpy as np
import chainer
from chainer import report, training, Chain, datasets, iterators, optimizers, cuda, Reporter, report_scope
import chainer.functions as F
import chainer.links as L
from chainer.training import extensions
from chainer.datasets import tuple_dataset
import matplotlib.pypl... |
from django.conf import settings
from django.db import transaction
from django.db.models import Prefetch
from django.shortcuts import render, get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework... |
#!/usr/bin/env python3
import os
import sys
################################################################################
# Help Menus #
################################################################################
def help():
print("""
`mas... |
# Script adapted from https://github.com/neherlab/SVVC/blob/master/src/create_allele_counts.py
# original author: <NAME>
import numpy as np
nuc_alpha = np.array(["A", "C", "G", "T", "-", "N"], dtype="S1")
def sam_to_allele_counts(
sam_fname,
qual_min=30,
max_reads=-1,
max_isize=700,
VERBOSE=0,
)... |
import binascii
import logging
import struct
from elftools.elf.elffile import ELFFile
from ForwardingUnit import ForwardingUnit
from Ram import Ram
from cpu_types import Ops, gib, pad, sign_extend, unsigned, Funct3, Aluop, Success, Fail
# from support import Regfile
from Instruction import Instruction
class Stage:... |
from __future__ import absolute_import, division, print_function
from libtbx import adopt_optional_init_args
import gltbx
import gltbx.util
from gltbx.gl import *
from gltbx.glu import *
from PyQt4.QtOpenGL import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from scitbx import matrix as mat
import math
from s... |
# Copyright (C) 2015-2019 <NAME>
# SPDX-License-Identifier: Apache-2.0
from collections import deque
import numpy
import dolfin
from ocellaris.utils import timeit, split_form_into_matrix, create_block_matrix
from .coupled_equations import define_dg_equations
class SimpleEquations(object):
def __init__(
s... |
import os
import sys
import json
import warnings
__all__ = ['DataStore']
#
# fields
#
class Field(object):
def __init__(self, name=None, primary_key=False):
self.type = None
self.name = name
self.primary_key = primary_key
def __getstate__(self):
return {
'type': s... |
# -------------------------------------------------------------------------
#
# Part of the CodeChecker project, under the Apache License v2.0 with
# LLVM Exceptions. See LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# ---------------------------------------------------... |
"""
* The MIT License
*
* Copyright 2020 The OpenNARS authors.
*
* 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,... |
from logging import getLogger
from os.path import join
from typing import List, Dict, Optional, Union, Tuple
from fastapi import APIRouter, Depends, Body, Query, UploadFile, File
from pydantic import Field
from starlette.background import BackgroundTask
from starlette.responses import FileResponse
from starlette.statu... |
# Copyright 2017 Mycroft AI 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 writin... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Terminal ... |
"""
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015 <NAME>
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
htt... |
from __future__ import division, print_function
import torch.nn as nn
from . import mmd
from torch.utils.tensorboard import SummaryWriter
import torch
from torch.distributions.uniform import Uniform
from torch.autograd import Variable
import matplotlib.pyplot as plt
class Morphing(nn.Module):
#TEST
def forwar... |
import cbsodata
import math
import pandas
import matplotlib.pyplot as plt
from functools import reduce
from pathlib import Path
from sklearn.preprocessing import MinMaxScaler
def download(identifier: str):
"""Download a dataset from the CBS odata portal."""
# Prepare download directory
download_director... |
import curses
import time
import copy
import random
random.seed(0)
debug = False
HEIGHT = 20
WIDTH = 10
BEGIN_X = 0
BEGIN_Y = 0
START_X = 3
START_Y = -2
block_l = [[1, 1, 1, 1]]
block_o = [[1, 1],
[1, 1]]
block_t = [[0, 1, 0],
[1, 1, 1]]
block_s = [[0, 1, 1],
[1, 1, 0]]
block_z = [[1... |
"""
The BIGMACC script.
"""
import os
import pandas as pd
import time
import logging
logging.getLogger('numba').setLevel(logging.WARNING)
import shutil
import cea.config
import cea.utilities
import cea.inputlocator
import cea.demand.demand_main
import cea.resources.radiation_daysim.radiation_main
import cea.bigmacc.co... |
"""Visualize the data."""
from typing import Union, Any
import numpy as np
from matplotlib.axes import Axes
from numpy import ndarray
__all__ = [
'auto_label',
'auto_text',
'normalize',
'plot_line',
'plot_fit',
'shift',
'text_position',
'set_minor_tick'
]
_LABELS = {
"xy": (r"Q ($... |
from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple
import torch
from classy.data.data_drivers import (
QASample,
SentencePairSample,
SequenceSample,
TokensSample,
)
from classy.data.dataset.base import batchify
from classy.data.dataset.hf.base import HFBaseDataset
from classy.util... |
from .test_deep import _skip_if_no_pytorch, _skip_if_no_tensorflow
# pylint: disable=import-error
def test_tf_keras_mnist_cnn():
""" This is the basic mnist cnn example from keras.
"""
_skip_if_no_tensorflow()
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models i... |
# --------------------------------------------------------------------------------------
# Copyright 2020-2021 by Oculy Authors, see git history for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# --------------------------... |
"""
Elasticsearch Query Result Transform
"""
from collections import defaultdict
from biothings.utils.common import dotdict, traverse
class ResultTransformException(Exception):
pass
class ESResultTransform(object):
''' Class to transform the results of the Elasticsearch query generated prior in the pipel... |
import os, re, json, requests
from transformers import T5ForConditionalGeneration, T5Tokenizer, MBart50TokenizerFast, RobertaTokenizer
# import tensorflow as tf
import numpy as np
import cv2
from PIL import Image
from keras.models import model_from_json
import projects.javalang_tokenizer as javalang_tok
BASE_DIR = os.... |
from enum import Enum
from .definition import (
GraphQLArgument,
GraphQLEnumType,
GraphQLEnumValue,
GraphQLField,
GraphQLList,
GraphQLNamedType,
GraphQLNonNull,
GraphQLObjectType,
is_abstract_type,
is_enum_type,
is_input_object_type,
is_interface_type,
is_list_type,
... |
from collections import Counter
import os
import os.path as op
import re
import warnings
import dandischema
from fscacher import PersistentCache
import h5py
import hdmf
import numpy as np
import pynwb
from pynwb import NWBHDF5IO
import semantic_version
from . import __version__, get_logger
from .consts import (
m... |
#from __future__ import absolute_import, division, print_function
import datetime
import json
import time
import glob
import gzip
import os
from multiprocessing import Pool
import pandas as pd
from config import *
import openbadge_analysis as ob
import openbadge_analysis.preprocessing
def group_by_hour():
"""
... |
"""Implements a malicious block that can be inserted at the front on normal models to break them."""
import torch
import math
from statistics import NormalDist
from scipy.stats import laplace
class ImprintBlock(torch.nn.Module):
structure = "cumulative"
def __init__(self, data_shape, num_bins, connection="l... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, tools, models, _
from odoo.exceptions import UserError, ValidationError
class UoMCategory(models.Model):
_name = 'uom.category'
_description = 'Product UoM Categories'
name = ... |
import heapq
import time
import asyncio
import openai
import os
from pathlib import Path
from loguru import logger
from dotenv import load_dotenv
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
openai.api_key = os.getenv("OPENAI_API_KEY")
MAX_SEARCH_DOCUMENT_QUANTITY = 200
async def set_api_key(api_ke... |
"""Assignment - Blocky
=== ===
<NAME> and <NAME>
Department of Computer Science,
University of Toronto
=== Module Description ===
This file contains the Block class, the main data structure used in the game.
"""
from typing import Optional, Tuple, List
import random
import math
from renderer import COLOUR_LIST, TE... |
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
import warnings
import numpy as np
from pandas.core.tools.datetimes import _unit_map
import cudf
from cudf._lib.scalar import as_scalar
from cudf._lib.strings.char_types import is_integer as cpp_is_integer
from cudf.core import column
from cudf.core.index import as_inde... |
#!/bin/python3.6
# author: <NAME>
from collections import defaultdict
from typing import Callable
from utils import ord_triples
class SelfNamingDict(defaultdict):
def __init__(self, cb, name=None):
super().__init__()
self.name = name
self.callback = cb
def __missing__(self, key):
... |
"""Commutation functions and actuarial notations
The ``LifeTable`` Space includes Cells to calculate
commutation functions and actuarial notations.
``LifeTable`` is parameterized with
``Sex``, ``IntRate`` and ``TableID``. ``TableID`` and
``Sex`` are used in :py:func:`qx` below to identify
the mortality rates to be app... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, <NAME> (@kbreit) <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '... |
from typing import Callable
from Shared import send_task, recv_task, tcp_send
import asyncio
try:
import SharedData
except ImportError:
from os import getcwd
from sys import path
path.append(getcwd() + "/..")
import SharedData
DEBUG = False
# TODO: change to logging instead of print
# TODO: cha... |
# -*- coding: utf-8 -*-
#
# Copyright © 2013 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""Unit Testing widget."""
from __future__ import with_statement
# Standard library imports
import copy
import os.path as osp
import sys
# Third party imports
from qt... |
import torch
import torch.nn
import torch.nn as nn
import torch.nn.functional as F
from transformers import BertModel, BertTokenizer
class LayerNorm(nn.Module):
"Construct a layernorm module (See citation for details)."
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
... |
"""
Description: This script generates figures for paper
(Fig5, varying alpha)
"""
import argparse
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
# import seaborn as sns
import matplotlib.pyplot as plt
from utils.networkx_operations import *
import numpy as np
import pandas as pd
import pickle
from numpy i... |
import os
import cv2
import torch
from torchvision import transforms as T
from maskrcnn_benchmark.modeling.detector import build_detection_model
from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
from maskrcnn_benchmark.structures.image_list import to_image_list
from maskrcnn_benchmark.config import... |
import director.vtkAll as vtk
from director import vtkNumpy as vnp
from director.shallowCopy import shallowCopy
import numpy as np
class DebugData(object):
def __init__(self):
self.append = vtk.vtkAppendPolyData()
def write(self, filename):
writer = vtk.vtkXMLPolyDataWriter()
writer.... |
"""The Test file for The New Parser (Grammar Classes)."""
import pytest
import logging
from sqlfluff.parser.grammar import (OneOf, Sequence, GreedyUntil, ContainsOnly,
Delimited, BaseGrammar, StartsWith)
from sqlfluff.parser.segments_base import ParseContext
from sqlfluff.... |
from __future__ import division
import argparse, time, logging, os, math
import numpy as np
import mxnet as mx
from mxnet import gluon, nd
from mxnet import autograd as ag
from mxnet.gluon import nn
from mxnet.gluon.data.vision import transforms
import gluoncv as gcv
gcv.utils.check_version('0.6.0')
from gluoncv.dat... |
#!/usr/bin/env python3
"""
atcsecdemo v0.1a sample code for using api to add atc security test cases.
"""
# standard imports
import sqlite3, json, time, sys, pprint, os, http.server, uuid, datetime
from urllib.parse import quote, unquote
from subprocess import PIPE, Popen
sys.path.append('akaconda_lite')
import akaco... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# --------------------------------------
# @Time : 2020/11/01
# @Author : <NAME>
# @Email : <EMAIL>
# @File : train.py
# @Description : train demo for lanenet
# @IDE: PyCharm Community Edition
# --------------------------------------
import os
import cv2
import t... |
from __future__ import print_function
import os
import torch
import torch.nn.functional as F
import numpy as np
import math
#for single depth [stable version]
def depthToNormal(depthmap,
device,
K,
thres,
img_size
):
# defau... |
#!/usr/bin/env python3
import sys
import os
import re
import math
import argparse
import subprocess
from snakemake.utils import read_job_properties
##############################
# Helper functions
##############################
def _get_default_partition():
"""Retrieve default partition for cluster"""
if "{{... |
"""
Selection functions implementation that are used by Evolutionary Algorithms.
Code is basing on information from:
'Introduction to Evolutionary Computing. Second edition.' <NAME>., <NAME>.
"""
__all__ = ["SelectionType", "SELECTION_FUNCTIONS", "SELECTION_ADDITIONAL_PARAMS", "SELECTION_ADDITIONAL_PARAMS_LIMITS",
... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2021 <NAME> <<EMAIL>>
#
# 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
# ... |
from panel.io.callbacks import PeriodicCallback
import param
import panel as pn
pn.extension(comms="vscode")
import toml
from confluent_kafka import KafkaError, KafkaException, Producer as _Producer, Consumer as _Consumer
from confluent_kafka.admin import AdminClient as _AdminClient, NewTopic
import sys
import logging... |
# Copyright 2016 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.
import contextlib
DEPS = [
'depot_tools/bot_update',
'depot_tools/gclient',
'file',
'gsutil',
'recipe_engine/path',
'recipe_engine/platform',
... |
import json
import os
import unittest
from unittest import mock
import requests
import testing.postgresql
from console import app
from console import db
from console import logger
from console import views
from console.helpers.exceptions import ClientError, ServiceError
from console.models import SurveyResponse, crea... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import errno
import hashlib
import logging
import os
import re
import sys
import yaml
from django.conf import settings
from django.utils.functional import Promise
from django.utils.encoding import (
force_bytes, force_text
)
from django.utils.translation import ugettext_lazy as _
from mayan.apps.common.class_mix... |
#!/usr/bin/env python3
import shutil, os, argparse, sys, stat, time
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), "setUpScripts"))
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), "pyUtils"))
from genFuncs import genHelper
from utils import Utils
from color_text impor... |
"""
Copyright 2017 <NAME>, <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... |
import os
import math
import numpy
import torch
import torch.fft
from PIL import Image
def compare_t60(a, b, sr=86):
try:
a = a.detach().clone().abs()
b = b.detach().clone().abs()
a = (a - a.min())/(a.max() - a.min()) # normalization
b = (b - b.min())/(b.max() - b.min())
t_... |
from hachoir.stream import InputSubStream
from hachoir.core.tools import humanFilesize, humanDuration
from hachoir.core.memory import limitedMemory
from hachoir.subfile.data_rate import DataRate
from hachoir.subfile.output import Output
from hachoir.subfile.pattern import HachoirPatternMatching as PatternMatching
from ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import torch
from torch import nn
from torchocr.networks.CommonModules import ConvBNACT, SEBlock
class ResidualUnit(nn.Module):
def __init__(self, num_in_filter, num_mid_filter, nu... |
import datetime
import time
import discord
from discord.ext import commands
import identifier
from identifier import error_embed_builder, success_embed_builder, warning_embed_builder
from main import InviteMonitor
class Setting(commands.Cog):
"""SetUp the bot"""
def __init__(self, bot):
self.bot = ... |
"""
**Organization Module**
*NDB. Class Definitions for Managing Organizations Data*
ndb. Database Class to handle Organizational Data related
to Memberships & Affiliates Management API , the Models will saves
the data to GCP DataStore.
Also Contain all validator classes rel... |
"""
Tencent is pleased to support the open source community by making Tencent ML-Images available.
Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy o... |
"""
Crypto Lab Library - RSA Library
This contains all of the functions to deal with the most common RSA attacks
and also the utilities required to do that.
<NAME> <<EMAIL>>
LGPLv3 or Later (2019 - 2020)
"""
#This does the hard work of actually getting you the plaintext back via the
# common modulus attack. All you ... |
"""
AIRR Data Representation Schema
"""
# Imports
import sys
import yaml
import yamlordereddictloader
from pkg_resources import resource_stream
class ValidationError(Exception):
"""
Exception raised when validation errors are encountered.
"""
pass
class Schema:
"""
AIRR schema definitions
... |
# Copyright 2020 The Pigweed 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
cmd = __import__("sys").modules["pymol.cmd"]
class ExprShortcut(cmd.Shortcut):
'''
Expression shortcut for iterate/alter/label with "s." prefix
setting autocompletion.
'''
def interpret(self, kee, mode=0):
if not kee.startswith('s.'):
return cmd.Shortcut.interpret(self, kee, mod... |
'''Functions for building SLR parser tables.'''
import sys
from collections import deque
from core import ContextFreeGrammar as CFG, Marker
END_MARKER = Marker('$')
def first_sets(G):
'''Compute the first sets for the variables in a grammar. Return a pair
whose first element is a dictionary mapping variables... |
# coding=utf-8
# Copyright 2018 The Batfish Open Source Project
#
# 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 requi... |
import warnings
import networkx as nx
import pandas as pd
def read_edgelist(edgelist_filename, keep_optional=False):
"""
Read an edgelist table into a pandas dataframe
Args:
edgelist_filename (str): filename of edgelist. See cpp.py for more details.
keep_optional (Boolean): keep or discar... |
from numpy import array
from opentrons.trackers.pose_tracker import (
update, Point, change_base
)
from opentrons.robot import robot_configs
from opentrons.data_storage import database
from opentrons.trackers.pose_tracker import absolute
from opentrons.config import feature_flags as ff
import logging
log = loggi... |
import pandas as pd
import numpy as np
from pandas import to_datetime
from datetime import timedelta
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.arima_model import ARIMA
from arch import arch_model
import matplotlib.pyplot as plt
import os
import datetime
import time
import anomalies.config as c... |
# Use edge detection for various things
from PIL import Image
import collections
import random
from .pixel import *
#TODO - normalize threshold to the overall contrast of the image?
#TODO - dynamic threshold based on brightness / contrast measure in each part of the image
# -> Darker parts of the image tend to have a... |
# -*- coding: utf-8 -*-
"""Module for handling jinja2 and MicroPy Templates."""
import json
from itertools import chain
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from micropy.logger import Log
from .checks import TEMPLATE_CHECKS
class Template:
"""Base Template Builder Class.
... |
from ctypes import cdll, CFUNCTYPE, c_char_p, c_void_p, c_bool, POINTER, c_int, c_uint, c_uint64
from wtpy.WtCoreDefs import WTSTickStruct, WTSBarStruct, BarList, TickList
from wtpy.SessionMgr import SessionInfo
from wtpy.wrapper.PlatformHelper import PlatformHelper as ph
from wtpy.WtUtilDefs import singleton
impo... |
import os
from PIL import Image, ImageDraw, ImageFont
from petrovich.settings import STATIC_ROOT
class DemotivatorText:
def __init__(self, text, font_size, color, padding, margin, available_width):
self.text = text
font_path = os.path.join(STATIC_ROOT, 'fonts/TimesNewRoman.ttf')
self.fon... |
""" Native python implementation of a text parser for reading GST input files. """
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 wi... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import copy
import shutil
import time
import subprocess
import argparse
import json
import gc
import cv2
import numpy as np
import math as m
from Imports.util_video import FileVideoGrab
from Imports.util_video import FrameStamps
from Impor... |
import os
import torch
import gpytorch as gp
from tqdm.auto import tqdm
import wandb
from pathlib import Path
from timeit import default_timer as timer
from gpytorch_lattice_kernel import MaternLattice, RBFLattice
from utils import set_seeds, prepare_dataset, EarlyStopper
class SimplexGPModel(gp.models.ExactGP):
... |
#!/usr/bin/env python3
from datetime import datetime
from pathlib import Path
# import re
import sys
from lxml import html # type: ignore
from lxml.etree import SubElement # type: ignore
# from lxml.html import Element # type: ignore
# Order Paper
import html_chunk_tool_cmd_with_class_warning as op # type: ignor... |
import base64
import os.path as op
from io import BytesIO
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
import nibabel as nib
import numpy as np
from dipy.segment.mask import median_otsu
from nipype.utils.filemanip import save_json, load_json
def reorient_array(data, aff):
# rearrange... |
import collections
import numbers
import random
import cv2
import numpy as np
from PIL import Image
from . import functional as F
__all__ = [
"Compose",
"Lambda",
"ToTensor",
"Normalize",
"ToGray",
"GaussianBlur",
"RandomNoise",
"RandomBrightness",
"RandomContrast",
"RandomShi... |
#!/usr/bin/python
import argparse
import logging
import time
import sys
from custom_exceptions import GeneralPogoException
from api import PokeAuthSession
from location import Location
from pokedex import pokedex
from inventory import items
def setupLogger():
logger = logging.getLogger()
logger.setLevel(logg... |
# Just for fun.
#
#http://effbot.org/tkinterbook/tkinter-classes.htm
#
# <NAME>
# <EMAIL>
# MESHLAB, UH Manoa
import tkinter as tk
import logging, time, sys
from functools import partial
from serial import Serial
from common import get_logger_name, get_flash_id, read_vbatt
from common import serial_port_best_guess, sav... |
# Copyright (C) 2013 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... |
"""
Functions to assist in parallel processing with Python 2.7.
* Memory-friendly iterator functionality (wrapping Pool.imap).
* Exit with Ctrl-C.
* Easy use of n_jobs. (e.g. when n_jobs == 1, processing is serial)
* Similar to joblib.Parallel but with the addition of imap functionality
and a more effective way of h... |
# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
# MIT License
#
# Copyright (c) 2021 <NAME>
#
# 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 res... |
#!/usr/bin/env python
# encoding: utf-8
import os
import sys
import json
import numpy as np
import pandas as pd
import _pickle as pk
from scipy.stats import mode
from ai_hub import inferServer
real = os.path.exists("/tcdata")
hist = None
hpoi = 0
hpos = []
fail = set()
t1 = 0.4 if real else 0
t2 = 0.9
# 加载模型,需要返回一个模型... |
import json
import os
from unittest.mock import patch
import requests
import rdflib
from viapy.api import ViafAPI, ViafEntity, SRUResult, SRUItem
FIXTURES_PATH = os.path.join(os.path.dirname(__file__), 'fixtures')
class TestViafAPI(object):
def test_get_uri(self):
assert ViafAPI.uri_from_id('1234') ==... |
"""Open API links support.
Based on https://swagger.io/docs/specification/links/
"""
from copy import deepcopy
from difflib import get_close_matches
from typing import Any, Dict, Generator, List, NoReturn, Optional, Sequence, Tuple, Union
import attr
from ...models import Case, Endpoint
from ...stateful import Direc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.