text stringlengths 3.07k 22.1k |
|---|
# Copyright 2019 British Broadcasting Corporation
#
# 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... |
import sys
import argparse
import re
import bs4
from bs4 import BeautifulSoup
sys.path.append('./')
def latex_escape(text, abbrev=False):
if len(text) != 0:
if abbrev:
tmp_text = '.~'.join(text.split('. '))
if tmp_text[-1] == '~':
text = tmp_text[0:-2]
... |
# -*- coding: utf-8 -*-
# Copyright © 2021 <NAME>
# SPDX-Identifier: MIT
from enum import IntEnum
from typing import List, Optional, Sequence, Tuple, Union
import numpy as np
from PIL import Image
from PIL.Image import Image as PILImage
from fdlite import ArgumentError, CoordinateRangeError, InvalidEnumError
f... |
#---------------------------------------------------------------------
# IDA Windows Debuger Hider
#
# Auther: iweizime
#
# This IDA plugin aims to hide IDA Windows Debuger from the
# processes being debugged.
#
#---------------------------------------------------------------------
import idaapi
import idc
import keys... |
import glob
import logging
import multiprocessing
import os
import time
import matplotlib.cm
import numpy as np
import tensorflow as tf
from PIL import Image
from lib_yolo import yolov3
def colorize(img, vmin=None, vmax=None, cmap='plasma'):
# normalize
vmin = tf.reduce_min(img) if vmin is None else vmin
... |
#!/usr/bin/env python3
"""Check multiple types of links on a compiled website
Meant to run from cli.
Example:
test_links.py "images" -s "public" -p 6 -f "monitoring-in-the-cloud-ebook.md"
"""
from itertools import chain
import multiprocessing
from optparse import OptionParser
import os
import re
import sys
from b... |
import pytest
import sys
import funcsigs
import numpy as np
from numpy import testing
from matplotlib import pyplot as plt
sys.path.append('/pymoc/src/pymoc/modules')
from psi_thermwind import Psi_Thermwind
from pymoc.utils import make_func
@pytest.fixture(
scope="module",
params=[
{},
{
... |
import io
import os
import re
import sys
import numpy as np
import numpy.random as random
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from utils import tools
match_newline_pattern = re.compile('\n+')
def load_word_vecs... |
import pandas as pd
from sklearn import linear_model
from imputena.simple_imputation.linear_regression import get_imputed_row
import logging
def srmi(data=None, sample_size=10, imputations=3, regressions='available'):
"""Performs sequential regression multiple imputation on the data.
Several (parameter imputa... |
# Contains some rudimentary (physical-space) models for testing PCE
# approximations. All these functions support the syntax output = f(p), where p
# is a d-dimensional vector, and output is a vector whose size is the dimension
# of the model output.
import numpy as np
from scipy import sparse
from scipy.sparse import... |
import itertools
import luigi
from luigi.contrib.external_program import ExternalProgramTask
from luigi.contrib.docker_runner import DockerTask
from os import path
from wespipeline import utils
from wespipeline.vcf import VariantCalling
from wespipeline.reference import ReferenceGenome
class VcftoolsCompare(External... |
import unittest
import keras
import numpy as np
from keras import Model, Input
from keras.backend import random_normal
from keras.layers import Conv2D, MaxPooling2D, Add, UpSampling2D, Lambda, Activation, Reshape, TimeDistributed, Flatten, \
Dense
from tensorflow import Tensor
from tensorflow.python import RandomN... |
from typing import Any, Awaitable, Callable, Iterable, TypeVar
from expression.collections import seq
from expression.core import (
MailboxProcessor,
Nothing,
Option,
Some,
TailCall,
TailCallResult,
compose,
match,
pipe,
tailrec_async,
)
from expression.system import AsyncDispos... |
# coding: utf-8
## Trains a One vs. Rest SVM classifier on the fisher vector video outputs.
import os, sys, collections, random, string
import numpy as np
from tempfile import TemporaryFile
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC
from sklearn import svm
from sklearn.multiclass import ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 07:16:34 2018
@author: <NAME>
title: calib_main
"""
#%% Imports
from load_pupil import load_pupil
from build_val import build_val
from plot_results import plot_Grid_2D
from plot_results import plot_mask
from plot_results import plot_calib
from pix2deg im... |
#!/usr/bin/python
# Title: Demo of ggspeak
# Author: <NAME>
# Last updated: 2015-09-01
#
# Graph by voice.
import speech_recognition as sr
import unicodedata
import os
import pandas as pd
from copy import copy
from Graphic_mpl import Graphic
from jellyfish import levenshtein_distance as ld
from nltk.corpus import sto... |
r"""Exhaustively searches the best permutations for all possible observations.
This is a policy that exhaustively searches the best permutations for all
possible observations. This method is very slow and should only be used for
testing purposes. The complexity of this method is O((n*p)**t), where n is the
number of p... |
from django.db import models
from django.db import utils
import datetime
import hashlib
import re
class BadSequenceError(Exception):
def __init__(self,why):
self.why = why
def __str__(self):
return repr(self.why)
class Giraffe_Mappable_Model(models.Model):
"""
This is an abstract cla... |
import citysimtoenergyplus
from eppy import modeleditor
from lxml import etree
import os
import polygons
from decimal import Decimal
idd_path = os.path.join('testing', 'Energy+.idd')
modeleditor.IDF.setiddname(idd_path)
def construct_empty_idf():
from StringIO import StringIO
idf = modeleditor.IDF(StringIO(... |
# OpenGym CartPole-v0
# -------------------
#
# This code demonstrates use a full DQN implementation
# to solve OpenGym CartPole-v0 problem.
#
# Made as part of blog series Let's make a DQN, available at:
# https://jaromiru.com/2016/09/27/lets-make-a-dqn-theory/
#
# author: <NAME>, 2016
import random, numpy... |
"""Provides the ANTLR4 listener class for producing formatted .per output."""
from enum import Enum, auto
from .perparse import PERParser, PERListener
from .comment_spooler import CommentSpooler
class FormattedPERListener(PERListener):
"""An ANTLR4 listener for AoE2 .per AI files that writes formatted rules to a... |
from datetime import date
from onegov.ballot import Election
from onegov.ballot import ElectionCompound
from onegov.ballot import Vote
from onegov.election_day.collections import SearchableArchivedResultCollection
from onegov.election_day.models import ArchivedResult
from pytest import fixture
from tests.onegov.electio... |
import os, time, pygame
from pygame.locals import *
from song import Song
""" Setup """
# Change to project root directory
if 'assets' not in os.listdir():
os.chdir('../')
pygame.init()
pygame.mixer.init()
clock = pygame.time.Clock()
FPS = 120
WIDTH, HEIGHT = 1280, 720
fullscreen = False
if fullscreen:
W... |
# ============================================================================ #
# Abgabe Projektarbeit Einführung ins Programmieren mit Python
# Namen
# <NAME>, Mat.Nr. 1652774
# - benötige Note für dieses Projekt
from typing import *
import sys
import pygame
import random
from src.bot import Bot
from src.che... |
#!/usr/bin/en python
import datetime
import os
import unittest
TODO_FILENAME = 'todo.txt'
DONE_FILENAME = 'done.txt'
PROJECT_PREPEND_STRING = '@'
class ToDo(object):
def __init__(self, data_path):
self.data_path = os.path.expanduser(data_path)
self.todotxt_path = os.path.join(self.data_path, TOD... |
#-*- coding: utf-8 -*-
import apache_beam as beam
import csv
import json
import os
from apache_beam.io.gcp.bigquery_tools import parse_table_schema_from_json
def preProcessing(fields):
fields = fields.replace("$","")
json_data = json.loads(fields)
if "press_date" not in json_data :
json_data["press_... |
"""
Run MESS calculations
"""
import os
import numpy
import automol
import mess_io
from lib.submission import run_script
from lib.submission import DEFAULT_SCRIPT_DCT
# OBTAIN THE PATH TO THE DIRECTORY CONTAINING THE TEMPLATES #
CUR_PATH = os.path.dirname(os.path.realpath(__file__))
# Set paths to MESS jobs
de... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from nose.tools import assert_equals, assert_raises
import numpy as np
from ..data.particles import *
from ..decay import leptonic as lp
from ..decay import two_pions as tp
from ..decay import two_kaons as kk
from ..decay import multimeson as mm
from ..d... |
#!/usr/bin/python
from queue import Queue
import logging
import re
import canros
import pyuavcan_v0 as uavcan
import rclpy
from rclpy.node import Node
from rclpy.exceptions import ParameterNotDeclaredException
import rcl_interfaces
from rcl_interfaces.msg import ParameterValue, ParameterType
try:
import constants
... |
# Servirtium: Service Virtualized HTTP
#
# Copyright (c) 2019, <NAME> and committers
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistribution... |
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
# simple probability distance
DIST_PROB = 1
# simple normalized probability distance
DIST_PROB_NORM = 2
# simple out of place distance
DIST_OUT_OF_PLACE = 4
# distance between model and query mapper
distance_mapper ... |
"""Initial configuration setup.
Index
-----
.. currentmodule:: nanoqm.workflows.initialization
.. autosummary::
initialize
split_trajectory
API
---
.. autofunction:: initialize
.. autofunction:: split_trajectory
"""
__all__ = ['initialize', 'read_swaps', 'split_trajectory']
import fnmatch
import getpass
impo... |
from main_app.models import (
Source,
Century,
Indexer,
Notation,
Provenance,
RismSiglum,
Segment,
)
import lxml.html as lh
from django.core.validators import URLValidator
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.management.base import BaseComma... |
import torch
import torch.nn as nn
import numpy as np
def get_activation(name, inplace=True):
if name == 'relu': return nn.ReLU(inplace)
if name == 'lrelu': return nn.LeakyReLU(0.2, inplace=inplace)
if name == 'tanh': return nn.Tanh()
if name == 'sigmoid': return nn.Sigmoid()
def get_normalization(na... |
import copy
from dataclasses import dataclass, field, is_dataclass # noqa: F401
from contextlib import contextmanager, ExitStack
from pathlib import Path
from typing import (Any, Callable, Dict, Iterator, Optional, Protocol,
Sequence, Type, TypeVar, Union)
from omegaconf import MISSING, DictCon... |
from flask import current_app, session, render_template, request, jsonify, abort, g
from info.utils.common import login_request
from . import news_blue
from info.models import User, News, Category, Comment
from info import constants, db
from info.utils.response_code import RET
@news_blue.route('/')
def index():
"... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from numpy.testing import assert_equal, assert_allclose
import pytest
from astropy import units as u
from ..._utils.examples import make_example_dataset
from ..pixcoord import PixCoord
@pytest.fixture(scope='session')
def wcs():
co... |
"""
Test if we can recover the leveldb from OSD after where all leveldbs are
corrupted
"""
import logging
import os.path
import shutil
import tempfile
from tasks import ceph_manager
from teuthology import misc as teuthology
log = logging.getLogger(__name__)
def _push_directory(path, remote, remote_dir):
"""
... |
import sqlite3
import os
import re
import sys
from pkg_resources import resource_filename
from PySide6.QtWidgets import QApplication, QMainWindow, QDialog, QSizePolicy, QTableWidgetItem
from PySide6.QtSql import QSqlDatabase, QSqlQuery
from PySide6.QtGui import QIcon
from sqlite3 import Error
from stinde... |
import enum
import logging
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, List, NamedTuple, Optional
from .conditions import render
from .exceptions import MissingObjects, TransactionTokenExpired
from .models import unpack_from_dynamodb
from .signals import object_deleted, objec... |
import collections
import numpy as np
import torch
import torch.optim as optim
from torchvision import transforms
from retinanet import model
from retinanet.dataloader2 import CSVDataset, collater, Resizer, AspectRatioBasedSampler, Augmenter, \
Normalizer
from torch.utils.data import DataLoader
from retinanet ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import math
from typing import Optional, Callable, List, Tuple, cast
import torch
import nni.retiarii.nn.pytorch as nn
from nni.retiarii import model_wrapper
def make_divisible(v, divisor, min_val=None):
"""
This function is taken from... |
#!/usr/bin/env python
"""<NAME>'s implementation of End-to-End Memory Networks, refactored."""
from itertools import chain
import tensorflow as tf
import numpy as np
from ..nn import NeuralNetworkModel, default_runstep
from ..data_loader import DataLoader, Batcher, one_hot_encode
class MemNet(NeuralNetworkModel):
... |
#!/usr/bin/env python3
"""Generates LaTeX, markdown, and plaintext copies of my resume."""
import argparse
import os
import re
from copy import copy
from time import localtime, strftime
import yaml
from git import Repo
from jinja2 import Environment, FileSystemLoader, StrictUndefined
__author__ = [
'<NAME> <... |
#!/usr/bin/env python
"""Quantize function.
"""
import ctypes
import datetime
import logging
from os.path import abspath, dirname
import torch
import numpy as np
from numba import cuda
from quant_impl import fake_quantize
_USE_GFPQ_QUANT_LIB = (torch.cuda.device_count() <= 1)
class GFPQParamSt(ctypes.Structure):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
flaskies.queriesdemo
====================
Demo ``request.args`` handlings in :mod:`jinja2` templates
----------------------------------------------------------
.. ::
Copyright: (c) 2017 by <NAME>.
Licence: BSD-3-Clause (see LICENSE for more details)
* new tests... |
#
# MODULE FOR UTILITY FUNCTIONS
#
# Terminate program on exception
import sys
# Handling file paths
import pathlib
# Matrix multiplication and trigonometric functions
import numpy as np
# Used for flooring numbers
import math
# Purpose: logging
import logging
# Used for raising argparse.ArgumentTypeError
impor... |
# -*- coding: utf-8 -*-
#Copyright (c) 2020 <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 restriction, including without limitation the rights
#to use, copy, modify, merge, p... |
from . import unet
import torch
import torch.nn as nn
import torch.nn.functional as F
import logging
class RegNet_single(nn.Module):
'''
Groupwise implicit template CNN registration method.
Parameters
----------
dim : int
Dimension of input image.
n : int
Number of image in t... |
#!/usr/bin/python3
"""
Copyright (c) 2020 LG Electronics Inc.
SPDX-License-Identifier: MIT
"""
from __future__ import print_function
import argparse
import collections
import getpass
import json
import logging
import os
import subprocess
import tempfile
BRANCH = "honister"
REPO_DIR = os.path.join(tempfile.gettempdi... |
import eneel.utils as utils
import eneel.load_strategies as load_strategies
from concurrent.futures import ProcessPoolExecutor as ProcessExecutor
import os
import eneel.printer as printer
from time import time
from datetime import datetime
import eneel.config as config
import logging
logger = logging.getLogger("main... |
from typing import Tuple
from IMLearn.metalearners.adaboost import AdaBoost
from IMLearn.learners.classifiers import DecisionStump
from utils import *
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from IMLearn.metrics import accuracy
output_path = "C:\\Alon\\Studies\\IML\\Exercise 4\\Grap... |
import numpy as np
import scipy.stats as sps
import pytest
from contextlib import contextmanager
from surmise.emulation import emulator
from surmise.calibration import calibrator
##############################################
# Simple scenarios #
##############################################
... |
from find_most_common_color import find_most_common_color
from PIL import Image
from numpy import amax, where, array, zeros, append
from pprint import pprint
import timeit
class Sprite():
def __init__(self, label, x1, y1, x2, y2):
""" All arguments (except self) MUST be strictly positive integers
... |
def inverter_posicoes(numero):
"""
Esta função inverte os valores de número inteiro no espaço delimitado pelos separadores de
unidades do sistema decimal. Por exemplo, se for enviado o número:
4, a função retorna 4
34, a função retorna 43
234, a função retorna 432
4.56... |
import matplotlib.pyplot as plt
# 导入数据集生成工具
import numpy as np
import seaborn as sns
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers, Sequential, regularizers
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams["font.size"] = 16
plt.rcP... |
# SPDX-License-Identifier: BSD-3-Clause
from operator import itemgetter
from typing import (
AbstractSet, Any, Callable, Collection, Generic, Iterable, Iterator, List,
Optional, Type, TypeVar, Union, cast, overload
)
from typing_extensions import Protocol
from softfab.databaselib import DBRecord, Database, R... |
import copy
from datetime import datetime
from multiprocessing import Queue
import os
import time
import numpy as np
import pandas as pd
import tensorflow as tf
from tentacle.board import Board
from tentacle.config import cfg
from tentacle.game import Game
from tentacle.tree_node import TreeNode2
from tentacle.utils i... |
import copy
import json
import posixpath
import sys
import warnings
from pathlib import Path
from typing import Any, Dict, IO, Iterator, List, Optional, Union
from jsonschema import Draft4Validator, RefResolver, ValidationError
from pkg_resources import resource_filename
from semantic_version import Version
from slice... |
import numpy as np
import hcipy as hp
import astropy.constants as const
import astropy.units as u
from astropy.io import fits
from ...field import Field, CartesianGrid, SeparatedCoords
from ...util import set_units, make_properties
from ...config import simulation_units, default_units
from ...models import convolve_to... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
VO Queries
"""
from astroquery.query import BaseQuery
from . import conf
from . import utils
__all__ = ['Registry', 'RegistryClass']
class VoBase(BaseQuery):
"""
Base class for all VO queries.
"""
def try_query(self, url, retries=... |
import requests as reqs
import json
import csv
import re
import time
import getopt
from datetime import datetime as dt
from bs4 import BeautifulSoup as soup
import bar_chart_race as bcr
import pandas as pd
import getopt
import subprocess
#import multiprocessing
#import threading
import asyncio
import httpx
#import scra... |
"""
https://github.com/hyves-org/p2ptracker
Copyright (c) 2011, <NAME>
MIT license: http://www.opensource.org/licenses/MIT
This module implements the rest methods possible on a transfer resource
"""
import logging
import hashlib
from p2ptracker import bencode, utils
from flask import make_response, Response, jsonify,... |
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score, roc_auc_score
from joblib import Parallel, delayed
from sklearn.metrics import accuracy_score
def convert_predictions_2d(y_pred):
if type(y_pred) is list:
y_pred = np.array(y_pred)
if len(y_pred.s... |
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import render
from .models import Profile,User,InterventionRecord,Flag,Tag
from .serializers import ProfileSerializer,UserSerializer,UserRegSerializer,InterventionSerializer,FlagSerializer,TagSerializer
from rest_frame... |
import torch
import torch.nn.functional as F
from utils.warp_utils import euler2mat, quat2mat
def sample_pix_coord(img_width: int, img_height: int, device="cpu", batch: int = 0):
r1 = torch.arange(0, img_height, device=device)
r2 = torch.arange(0, img_width, device=device)
ones = torch.ones(img_height, im... |
# -*- coding: utf-8 -*-
"""
Teeny tiny grab-bag functions
"""
import numpy as np
from scipy import ndimage
def savefig(fname, fig, dpi=300, no_png=False, no_svg=False, figsize=None,
**kwargs):
"""
Saves `fig` to `fname` as png and svg
Parameters
----------
fname : str
Path to... |
"""Module defining Machinery, Species and ProcessingMap classes."""
# python 2/3 compatibility
from __future__ import division, print_function, absolute_import
# global imports
from collections import namedtuple
from scipy.sparse import (
csr_matrix, csc_matrix, lil_matrix, coo_matrix, hstack, eye
)
import nu... |
#! /usr/bin/env python
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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/LICEN... |
# -*- coding: utf-8 -*
import pywikibot as pb
import json
import re
import datetime as dt
import time
now = dt.datetime.now()
bn = pb.Site("bn","wikipedia")
r = pb.data.api.Request
ISO = "%Y-%m-%dT%H:%M:%SZ"
is_no_ref = re.compile('<\/ *ref>|\{\{ *sfn *\|')
ref_space = re.compile("<\/ref>\s+<ref")
p_ref = re.compile("(... |
"""speaker.py"""
import wave
import os
import threading
import base64
import warnings
from pidevices.devices import Actuator
import alsaaudio
import time
# to add cases etc ...
class SpeakerError(Exception):
""" Speaker custom exception class """
pass
class Speaker(Actuator):
RETRY = 5
SAMPLE_WIDTH... |
# Capstone Python bindings, by <NAME> <<EMAIL>>
import arm, arm64, mips, x86
__all__ = [
'Cs',
'CsInsn',
'cs_disasm_quick',
'cs_version',
'CS_API_MAJOR',
'CS_API_MINOR',
'CS_ARCH_ARM',
'CS_ARCH_ARM64',
'CS_ARCH_MIPS',
'CS_ARCH_X86',
'CS_MODE_LITTLE_ENDIAN',
'CS_MODE... |
''' Python question by HackerRank
TODO 1:
Ms. <NAME> is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse.
Formula used: Average = sum of distinct heights / total number of distinct heights
Input Format:
The fir... |
#!/usr/bin/env python3
# Copyright 2018-2020, Wayfair GmbH
#
# 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... |
""" Tools to extract and process the frames from input data
Main function:
* :py:func:`extract_frames`: Extract all the frames under a root directory
Functions:
* :py:func:`find_tiles`: Find all the tiles under the input directory
* :py:func:`extract_single_frames`: Extract all the frames for a single tile
Extract... |
import logging
logging.getLogger('tensorflow').disabled = True
logging.getLogger('matplotlib').disabled = True
import re
import numpy
from numpy import testing
numpy.random.seed(0)
from tensorflow.random import set_seed
set_seed(2)
from sklearn.metrics import roc_auc_score
from nose.tools import eq_, assert_less, as... |
#!/usr/bin/env python
import datetime
import os
import re
import subprocess
import sys
import types
sys.path.insert(0, "%s/work/mutant/ec2-tools/lib/util" % os.path.expanduser("~"))
import Cons
import Util
sys.path.insert(0, "%s/work/mutant/ec2-tools/lib" % os.path.expanduser("~"))
import BotoClient
def main(argv)... |
#!/usr/bin/env python
class Tools(object):
def __init__(self):
pass
def createDir(self, path):
'''
Creates the specified directory if not exists.
'''
import errno, os
# create dir
try:
if not os.path.isdir(path):
os.makedirs(... |
#!/usr/bin/env python
import numpy as np
import sklearn as sk
import sklearn.linear_model
from sklearn.impute import SimpleImputer, KNNImputer
from volcanic.exceptions import InputError
rng = np.random.default_rng()
def call_imputer(a, b, imputer_strat="simple"):
if imputer_strat == "simple":
imputer = ... |
import os
from scipy.optimize import minimize_scalar
import tensorflow as tf
import numpy as np
from tensorflow.keras.optimizers import Adam, SGD, Adagrad, Adamax, Ftrl, Nadam, RMSprop
from tensorflow.keras.metrics import (Accuracy as AccuracyTfKeras, BinaryAccuracy, CategoricalAccuracy,
... |
import sys
import traceback
from telegram import Update
from telegram.ext import MessageHandler, CommandHandler, CallbackContext, Filters, CallbackQueryHandler, \
ConversationHandler
from telegram.utils.helpers import mention_html
import static.consts as consts
import src.keyboard as keyboard
import src.database... |
#!/usr/bin/env python3
# Copyright (C) Alibaba Group Holding Limited.
"""Multi-view test a video classification model."""
import numpy as np
import os
import pickle
import torch
import json
import utils.bucket as bu
import utils.checkpoint as cu
import utils.distributed as du
import utils.logging as logging
import ... |
from musket_core import datasets, generic_config
import numpy as np
import keras
import tensorflow as tf
import lightgbm
import os
class OutputMeta:
def __init__(self, shape, owner):
self.output_meta = True
self.model = owner
class Log():
def __init__(self):
pass
def get(sel... |
import json
import random
import numpy as np
import pytest
import torch
from ai_traineree.types.dataspace import DataSpace
from ai_traineree.utils import (
condens_ndarray,
serialize,
str_to_list,
str_to_number,
str_to_seq,
str_to_tuple,
to_numbers_seq,
to_tensor,
)
from conftest impor... |
import copy
import numpy as np
from PySide2.QtCore import QItemSelectionModel, QObject, Signal
from PySide2.QtWidgets import (
QComboBox, QLineEdit, QSizePolicy, QTableWidgetItem
)
from hexrd.constants import chargestate
from hexrd.material import Material
from hexrd.ui.periodic_table_dialog import PeriodicTabl... |
import sys
from geopy.distance import vincenty
from polyline.codec import PolylineCodec
import urllib.parse
import http.client
import json
import time
from configparser import ConfigParser
import logging
from collections import namedtuple
import pdb
Forcast = namedtuple('Forcast', ['location', 'time', 'summary', '... |
import oommfc as oc
import discretisedfield as df
import numpy as np
import matplotlib.pyplot as plt
import colorsys
plt.style.use('styles/lato_style.mplstyle')
mu0 = 4 * np.pi * 1e-7
def convert_to_RGB(hls_color):
return np.array(colorsys.hls_to_rgb(hls_color[0] / (2 * np.pi),
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script demonstrates:
* Creating a Matérn FEM approximation model in 2 dimensions.
* Generate samples from this model.
* Compute correlation (and compare with theoretical correlation).
* Conditional distribution give observations of two points.
... |
import os
import socket
import pytoml
import inspect
import sys
from importlib import util
os.environ["LC_ALL"] = "en_US.UTF-8"
def tcpPortConnectionTest(ipaddr, port, timeout=None):
conn = None
try:
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if timeout:
conn.settime... |
from collections import OrderedDict
from tensorflow.keras.utils import model_to_dot
class Node:
def __init__(self, layer_name, layer_type):
self.layer_name = layer_name
self.layer_type = layer_type
self.layer_attr = {}
self.src = []
self.dst = []
def add_src(self, ... |
import numpy as np
from typing import Callable, Tuple, Union
def attributes_check(metric):
# https://towardsdatascience.com/5-ways-to-control-attributes-in-python-an-example-led-guide-2f5c9b8b1fb0
attr = metric.__dict__
if "perturb_func" in attr:
if not callable(attr["perturb_func"]):
... |
import socket
import sys
import threading
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QPropertyAnimation, Qt, QTimer
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMainWindow, QApplication, QListView,QPushButton
from Client.Bubble.LabelBubble import MessageDelegate, MessageModel, USER_ME, USE... |
import json
import logging
import random
from datetime import datetime, timedelta
from enum import Enum
from os import path
import botskeleton
import pycountry
import requests
HERE = path.abspath(path.dirname(__file__))
WEATHER_ROOT = "http://api.openweathermap.org/data/2.5/weather"
class WeatherbotSkeleton():
... |
#!/usr/bin/python3
import copy
import itertools as it
import os
import unittest
import unittest.mock as mock
import plato_pylib.plato.parse_tbint_files as parseTbint
import plato_pylib.plato.private.tbint_test_data as tData
import plato_fit_integrals.core.coeffs_to_tables as tCode
class TestIntegralHolder(unittest.... |
import torch
import torch.nn as nn
import numpy as np
from mmdet.datasets.transforms import ImageTransform
from collections import OrderedDict
from ..apis.inference import _prepare_data
from mmdet.ops.dcn.modules.deform_conv import DeformConv
from apex.parallel import SyncBatchNorm
custom_operator_list = [DeformConv,... |
"""
Component to track electricity tariff.
For more details about this component, please refer to the documentation
at http://github.com/dgomes/home-assistant-custom-components/electricity/
"""
import logging
from homeassistant.components.sensor import (
ATTR_LAST_RESET,
DEVICE_CLASS_MONETARY,
STATE_CLASS... |
# -*- coding: utf-8 -*-
"""Query Gaia for GCs.
Retrieve the data from the Gaia archive (all sources satisfying the
maximum distance from cluster center and a simple parallax cut). Source
data for each cluster is stored in a separate numpy zip file:
"data/[cluster_name].npz". Additionally, the table for computing the
... |
from functools import lru_cache
import numpy as np
from numpy import cos, exp, pi, sin, sqrt
def identity(dim):
"""
Returns an identity matrix with a given dimension
"""
return np.diag(np.ones(dim, dtype="complex128"))
def pauli(normalized=True):
if normalized:
c = 0.5
else:
... |
#!/usr/bin/python
#
# Given a UID and a file containing a GPG key, generate the
# corresponding OPENPGPKEY DNS record in presentation format.
#
# Tested with gnupg 1.x and 2.x.
#
import os, sys, time, getopt, email.utils, errno
import tempfile, shutil, subprocess, threading, binascii, base64, hashlib
from tempfile im... |
# -*- coding: utf-8 -*-
"""
Tests for pyftpsync
"""
import io
import json
import os
import sys
import unittest
from ftplib import FTP
from pprint import pprint
from urllib.parse import urlparse
from ftpsync.metadata import DirMetadata
from ftpsync.synchronizers import (
BiDirSynchronizer,
Downl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.