text stringlengths 3.07k 12.6k |
|---|
import torch
import torch.nn as nn
from einops import rearrange
from utils.vit import ViT
class EncoderBottleneck(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, base_width=64):
super().__init__()
self.downsample = nn.Sequential(
nn.Conv2d(in_channels, out_channel... |
#encoding=utf-8
import argparse
import torch
import time
import json
import numpy as np
import math
import random
from torch.autograd import Variable
import torch.nn.functional as F
from config import flags
seed = flags.seed
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
... |
import asyncio
import concurrent.futures
import functools
from http import HTTPStatus as hs
import json
import typing
from conducto.shared import types as t, request_utils
class UserInputValidation(Exception):
# Any exception derived from this should be given a message that is
# understandable to an end-user... |
import numpy as np
import cv2
import imutils
import time
from matplotlib import pyplot as plt
def load_im(fn):
return(cv2.cvtColor(cv2.imread(fn,cv2.IMREAD_UNCHANGED),cv2.COLOR_BGR2RGB))
def rot_border(angle, inxy):
xmax = np.max(inxy[:,0])
xmin = np.min(inxy[:,0])
ymax = np.max(inxy[:,1])
ymin = np.mi... |
#!/usr/bin/env python
from __future__ import division
import txros
from twisted.internet import defer
from mil_misc_tools import text_effects
from sub8 import SonarObjects
from mil_ros_tools import rosmsg_to_numpy
from scipy.spatial import distance
import numpy as np
fprint = text_effects.FprintFactory(
title=... |
import abc
from dataclasses import dataclass, field
from typing import Optional, Union
import sklearn
import sklearn.cross_decomposition
import sklearn.ensemble
import sklearn.linear_model
import sklearn.svm
import xgboost
from apischema import schema
from sklearn.base import BaseEstimator
from typing_extensions impor... |
import numpy as np
from ipso_phen.ipapi.base.ip_abstract import BaseImageProcessor
from ipso_phen.ipapi.tools.csv_writer import AbstractCsvWriter
_01a_EXPERIMENT = "01as_btitom_1810".lower()
class ImageCsvWriter(AbstractCsvWriter):
def __init__(self):
super().__init__()
self.data_list = dict.fro... |
# Level 3 program for driving SCUTTLE and handling other tasks in parallel
# IMPORT EXTERNAL ITEMS
import time
import numpy as np # for handling matrices
import threading # only used for threading functions
import math
# IMPORT INTERNAL ITEMS
import L2_speed_control as sc # closed loop control. Import speed_control f... |
import dataclasses
from datetime import datetime
from typing import List, Optional, Type
from numpy.random import default_rng
from rest_framework.exceptions import ValidationError
from ee.clickhouse.queries.trends.clickhouse_trends import ClickhouseTrends
from posthog.constants import TRENDS_CUMULATIVE
from posthog.m... |
import os
from copy import deepcopy
import numpy as np
from sklearn.decomposition import PCA
from skimage.transform import AffineTransform
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
####################################################
# image transformation method
# Credit: https://github.co... |
# -*- coding: utf-8; indent-tabs-mode: nil; python-indent: 2 -*-
#
# Copyright (C) 2013-2019 <NAME>
#
# This file is part of WaterOnMars (https://github.com/tibonihoo/wateronmars)
#
# WaterOnMars is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as pu... |
import shutil
import json
import os
import requests
import pyperclip
import nbtlib
import urllib.request
import sys
import zipfile
def serverSetup(createdServerName, selectedVersion):
versions = requests.get('http://launchermeta.mojang.com/mc/game/version_manifest.json')
versionsJSON = json.loads(v... |
import asyncio
from urllib import parse
from pyppeteer import launch
import pyppeteer
from colorama import *
import sys
import string
import random
from urllib import parse
import argparse
import time
init()
GREEN = Fore.GREEN
RED = Fore.RED
RESET = Fore.RESET
BLUE = Fore.BLUE
YELLOW = Fore.YELLOW
MAGENT... |
"""
An abstraction class for OpenGL image buffers
For simplicity, we would like to treat an image as a (1D)
list of tuples. In reality, it is a little more complicated
than that, because OpenGL expects the data in a very compact
format. This data structure abstracts all of this so we
can pretend otherwise.
You DO NOT... |
import datetime
import copy
import json
import pickle
from pathlib import Path
from telemetry_f1_2021.packets import HEADER_FIELD_TO_PACKET_TYPE
from telemetry_f1_2021.packets import PacketSessionData, PacketMotionData, PacketLapData, PacketEventData, PacketParticipantsData, PacketCarDamageData
from telemetry_f1_2021.... |
import sys
from py4j.java_gateway import JavaGateway, GatewayParameters, CallbackServerParameters, get_field
import time
import subprocess
class Environment():
actions = ["↖", "↑", "↗", "←", "→", "↙", "↓", "↘", "A", "B", "C", "_"]
# Create the connection to the server
def __init__(self):
self.... |
# coding: utf-8
from Parser import Parser
from operator import mul, add
import typing
# class Number(Parser):
# tokens = (
# "UNIT",
# "PLUS",
# "TIMES",
# "ZERO"
# )
#
# literals = ('(', ')', '+', '*')
#
# # t_PLUS = r'\+'
# # t_TIMES = r'\*'
#
... |
# 21datalabplugin
#import numpy as np
import dates
import pandas as pd
import copy
import numpy
from system import __functioncontrolfolder
import requests
import json
import time
# use a list to avoid loading of this in the model
mycontrol = [copy.deepcopy(__functioncontrolfolder)]
mycontrol[0]["children"][-1]["val... |
import logging
import requests
from django.conf import settings
from django.utils import timezone
from data_ocean.converter import Converter, BulkCreateManager
from data_ocean.downloader import Downloader
from data_ocean.models import Register
from data_ocean.utils import clean_name, change_to_full_name
from location... |
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import re
import gzip
import bz2
import argparse
import shutil
import logging
import itertools
import collections
import functools
from subprocess import Popen, PIPE
from distutils.spawn import find_executable
# 3rd party
from Bio.SeqUtils... |
#!/usr/bin/env python
from pytlscanner import resultsFromCache
from pytlscanner import sslyze_scan
from pymongo import MongoClient
import time
import argparse
from pprint import pprint
from dataclasses import asdict
import json
import sslyze
from sslyze import ScanCommand
import requests
import copy
from datetime imp... |
#!/usr/bin/env python3
import argparse
from pathlib import Path
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from numpy.lib.npyio import save
from tqdm.auto import tqdm
import dns
cmap = "coolwarm"
def main():
parser = argparse.ArgumentParser(... |
import torch
import torch.fft
from torch import nn
# it calculates the biased or unbiased autocorrelation function
# it is simply an implementation of the ACF in terms of pyTorch transformations
# note that there's no parameter to learn here
class AutocorrSeq(nn.Module):
def __init__(self, n_lags, unbiased=False)... |
#!@PYTHON@ -tt
#####
##
## The Following Agent Has Been Tested On:
##
## Model Modle/Firmware
## +--------------------+---------------------------+
## (1) Main application CB2000/A0300-E-6617
##
#####
import sys, re
import atexit
sys.path.append("@FENCEAGENTSLIBDIR@")
from fencing import *
#BEGIN_... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from collections import OrderedDict
from torch.nn import init
class LinearBottleneck(nn.Module):
def __init__(self, inplanes, outplanes, stride=1, t=6, activation=nn.ReLU6):
super(LinearBottleneck, self)... |
#########################################################################################
# Name: <NAME>
# Student ID: 64180008
# Department: Computer Engineering
#
# Assignment ID: A6
#########################################################################################
###################... |
import click
import pyfiglet
from os import name, system
from bookcut import __version__
from bookcut.mirror_checker import main as mirror_checker, settingParser
from bookcut.book import libgen_book_find, book_searching_in_repos
from bookcut.organise import main_organiser
from bookcut.search import choose_a_book
from b... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# Helper function for output on facebook messages archive.
# LICENSE INFORMATION HEADER
__author__ = "<NAME>"
__copyright__ = "Copyleft (c) 2018, <NAME>"
__credits__ = ["<NAME>"]
__license__ = "ApacheV2.0"
__version__ = "0.1.0"
__maintainer__ = "<NAME>"
__email__ = "<EMA... |
import pytest
from matchable.exceptions import NoMatchError
from matchable.match import IsInstance
from matchable.match import Match as match
from matchable.spec import Options, Spec, CopyUpdate, LastSeenWins, Wrapper, WRAPPER_TYPES
@pytest.fixture
def patterns(type_a, type_b, type_c):
return {
type_a: d... |
##################### IMPORT STATEMENTS #####################
# required to view plots on AWS instance - must come first
from typing import List
import matplotlib
matplotlib.use('Agg')
# dependencies
import csv
import cv2
import numpy as np
import random
import matplotlib.pyplot as plt
from sklearn.model_selection imp... |
from typing import Optional, List, Dict, TYPE_CHECKING, Union
from api_call.arium.api.request import asset_list, asset_get, asset_versions, asset_post, asset_rename, asset_copy, \
asset_lock, asset_delete, asset_get_payload_description, asset_update_payload_description, asset_get_data, \
asset_set_description,... |
"""
Fluid particles travelling through a vector field
By <NAME>
"""
import pygame;
import math;
from math import hypot, atan2, sin, cos, pi;
pygame.init();
WIDTH, HEIGHT = 600, 600;
TITLE = "Fluid simulation";
MAX_FPS = 30;
TWO_PI = 2 * pi;
QUARTER_PI = pi / 4;
WHITE = (255, 255, 255);
RED = (255, 0, 0);
BLACK = (0,... |
from typing import IO, Tuple
import logging
from matplotlib.collections import LineCollection
from matplotlib.collections import EllipseCollection
from matplotlib.collections import PathCollection
from matplotlib.path import Path
import numpy as np
import math
from ..ModelBase import Justify, rgb
from ..AbstractPlot... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
pd_clinical_outcome_stats.py
Using the before and after treatment motor scores of Parkison's patients,
this script calculates the motor improvement score and percentage STN activation.
It also performs Wilcoxon signed rank test based on the improvement score and
creat... |
"""
Fortran namelist parser. Converts namelists to Python dictionaries.
Based on https://gist.github.com/krischer/4943658.
Should be fairly robust. Cannot be used for verifying fortran namelists as it
is rather forgiving.
Error messages during parsing are kind of messy right now.
Usage
=====
>>> from namelist impo... |
#!usr/bin/env python3
import numpy as np
import random
from matplotlib import pyplot as plt
class Node:
def __init__(self, location, cost=0, children=[], parent=None):
self.location = location
self.cost = cost
self.children = children
self.parent = parent
def add_child(self, no... |
"""
MIT License
Copyright (c) 2017 <NAME>, <NAME>, <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,... |
from itertools import chain, combinations
from django.http import JsonResponse, HttpResponseNotFound, HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.template.loader import TemplateDoesNotExist
from django.views.decorators.http import require_POST
from badge.registry import B... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in complianc... |
"""
Definition of the ESIM model.
"""
# <NAME>, 2018.
import torch
import torch.nn as nn
from vaa.layers import RNNDropout, Seq2SeqEncoder, SoftmaxAttention, LinerEncoder
from vaa.utils import get_mask, replace_masked
# from allennlp.modules.elmo import Elmo, batch_to_ids
class ESIM(nn.Module):
"""
Implementa... |
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.contrib import messages
import json
from urllib.parse import unquote
from .models import CustomUser, UserRead, Us... |
import hvac
import requests
from jinja2 import Template
from flask import current_app
from ...shared import constants as c
from ...shared.connectors.vault import create_client, get_root_client
from ..models.project import Project
def get_project_client(project_id):
""" Get "project" Vault client instance """
... |
import itertools
from collections import defaultdict
import numpy as np
from .get_atom_properties import getAtomProperties
class Atom:
def __init__(self, element, label, aindex, mass, x, y, z, intensity):
"""
原子类
:param element: 元素符号
:param label: 晶体文件里的原子标签,如C001
:param ... |
from .. import generator
from .. import mhealth_format as mh
import pandas as pd
from pyarrow import csv
import datetime
import os
ACTIGRAPH_TEMPLATE = """------------ Data File Created By ActiGraph GT3X+ ActiLife v6.13.3 Firmware v2.5.0 date format M/d/yyyy at {} Hz Filter Normal -----------
Serial Number: {}
Start ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
import time
import sys
MIN_SAMPLE_SIZE = 100
MAX_SAMPLE_SIZE = 100000
NUM_SAMPLES = 100
sample_sizes = np.linspace(MIN_SAMPLE_SIZE,
MAX_SAMPLE_SIZE,
NUM_SAMPLES,
... |
#!/usr/bin/env python
#########################################################################################
#
# Compute DTI.
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2015 Polytechnique Montreal <www.neuro.polymtl.ca>
# Author: <NAME>
#
# About the l... |
# coding=utf-8
# Copyright 2018 Google LLC & <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 o... |
import datetime
import logging
from .log_analyst.settle_process import SettleInformation
from .log_analyst.settle_process import __get_position_csv_name
from .log_analyst.settle_process import push_positions_and_trades_into_database
from .log_analyst.settle_process import summary_daily_trades
from .check_and_settle.ch... |
from lxml import etree
from xml.sax.saxutils import quoteattr, escape
from functools import partial
from typing import Callable, IO
Matcher = Callable[[str], bool]
Transformer = Callable[[etree.ElementBase], etree.ElementBase]
def eq_matcher(tag_name: str) -> Matcher:
def inner(other: str) -> bool:
retur... |
#!/usr/bin/env python
import xarray as xr
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import argparse as ap
import DUST.plot.plotting as dplot
import pandas as pd
from matplotlib import rcParams
import os
def process_data(ds, method='mean', area=None):
time0 = str(ds.time[0].dt.strftime("%Y")... |
import numpy as np
import collections
import tensorflow as tf
from nltk.tokenize import word_tokenize
from tensorflow.keras import Model, layers
import csv
import re
import pylab
MAX_DOCUMENT_LENGTH = 100
N_FILTERS = 10
HIDDEN_SIZE = 20
EMBEDDING_SIZE = 50
FILTER_SHAPE1 = [20, 256]
POOLING_WINDOW = 4
PO... |
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
from IMLearn.metrics import mean_square_error
from sklearn.model_selection import train_test_split
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRe... |
#!/usr/bin/env python
# encoding: utf-8
from rest_framework import serializers
from rest_framework.serializers import ImageField
from rest_framework.settings import api_settings
from rest_framework.fields import SerializerMethodField
from v1.recipe.models import Recipe, SubRecipe
from v1.recipe_groups.models import T... |
import ast
import html
import json
import logging
import os
import re
import numpy as np
from colorsplash_common.image_ids import ImageIdsTableHelper
from colorsplash_common.rgb import RGBTableHelper
from context import Context
from dotenv import load_dotenv
from exceptions.exceptions import InputError, ColorSplashExc... |
#!/usr/bin/env python3
"""UK Met Office Historical Station Observations."""
from locale import atof
from mrjob.job import MRJob
from mrjob.step import MRStep
from statistics import mean
import os
import re
class Mapper:
"""
Mapper class.
Map data from Met Office Historical Station Observations.
"""
... |
"""Manages Amanda components (plugins and drivers).
Copyright 2018 - <NAME> <<EMAIL>>. Licensed under MIT."""
import os
import importlib
import configobj
import config
import collections
plugins = []
drivers = []
def _import(path):
"Imports and returns the module from the given path."
p = os.path.split(path... |
import argparse
import os
import io
import shutil
import tarfile
from sklearn.model_selection import train_test_split
import wget
from deepspeech_pytorch.data.data_opts import add_data_opts
from deepspeech_pytorch.data.utils import create_manifest
def _format_training_data(root_path,
val_f... |
'''Order resource.'''
from flask import request
from flask_restful import Resource
from api.v2.models.meal_model import Meal
from api.v2.models.order_model import Order
from api.v2.models.user_model import User
from api.v2.helpers.decorators import login_required, admin_required
class DBOrderResource(Resource):
... |
from __future__ import print_function
import socket
import threading
import collections
import numpy as np
STOP_SOCKET = 'stopsocket'
# ('%10s%100s%016d' % (SERIALIZE_VERSION=='1.0', name, length * (sizeof // 8))).encode() + buff[:length * sizeof]
def read_double_vec_1_0(readfunc, verbose=True):
name = readfun... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... |
import torch
from torch.optim import Adam
from torch.utils.data import DataLoader
import torch.nn.functional as F
from einops import rearrange
# data
import sidechainnet as scn
from sidechainnet.sequence.utils import VOCAB
from sidechainnet.structure.build_info import NUM_COORDS_PER_RES
# models
from alphafold2_pytor... |
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
import math
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def build_net(layer_shape, activation, output_activation):
'''build net with for loop'''
layers... |
__author__ = 'HaoBin'
class HashTable():
def __init__(self, size=11):
# 11 because it's a small enough prime
# just initialising...
self.count = 0
self.tablesize = size
self.array = [None] * size
def __len__(self):
return self.count
def load(self):
... |
import json
import os
import sys
from common.course_config import get_course
from common.db import connect_db, transaction_db
from common.oauth_client import create_oauth_client, get_user, is_logged_in, is_staff
from common.rpc.howamidoing import upload_grades as rpc_upload_grades
from common.rpc.secrets import only
f... |
import json
import copy
import arbor as arb
def __make_dicts(jfile):
params = {
"temperature-K": None,
"init-membrane-potential": None,
"axial-resistivity": None,
"membrane-capacitance": None,
}
ions = {}
for ion in {"ca", "na", "k"}:
ions[ion] = {
"init-int-concentration" : None,
"... |
from datetime import datetime
from discord.ext import commands, tasks
from lib.mysqlwrapper import mysql
from lib.rediswrapper import Redis
from prettytable import PrettyTable
import discord
import lib.embedder
import logging
import os
class Maintenance(commands.Cog):
"""Cog for running maintenance task loops
... |
"""
FCN8 class.
Library: Tensowflow 2.2.0, pyTorch 1.5.1
Author: <NAME>
Email: <EMAIL>
"""
from __future__ import absolute_import, division, print_function
import torch
from ..encoders.squeeze_extractor import *
class FCN8(torch.nn.Module):
def __init__(self, n_classes, pretrained_model: SqueezeExtractor):
... |
# -*- coding: utf-8 -*-
"""
Classes related to exposing an interface to the OpenImageDebugger window
"""
import ctypes
import ctypes.util
import platform
import sys
import time
FETCH_BUFFER_CBK_TYPE = ctypes.CFUNCTYPE(ctypes.c_int,
ctypes.c_char_p)
PLATFORM_NAME = platform.... |
import mpmath
from ..distributions import normal
__all__ = ['pearsonr', 'pearsonr_ci']
def pearsonr(x, y, alternative='two-sided'):
"""
Pearson's correlation coefficient.
Returns the correlation coefficient r and the p-value.
x and y must be one-dimensional sequences with the same lengths.
... |
# Generated by Django 3.2.3 on 2021-06-16 19:52
import datetime as dt
from time import sleep
from django.db import migrations, models
from django.db.models.aggregates import Sum
import django.db.models.deletion
from loguru import logger
def translate_spotify_demographic_data(apps, schema_editor):
Podcast = apps... |
"""
make csv file (e.g. vocab_words/babyberta.csv) that contains tokens in a tokenizer configuration file,
alongside their frequency in corpora of interest (e.g. childes, newsela, wikipedia).
A huggingface tokenizers v0.10 configuration file is expected.
"""
import spacy
import json
from pathlib import Path
import pan... |
import sublime
import sublime_plugin
import sys
class AnsibleVaultBase(sublime_plugin.TextCommand):
def __init__(self, view) -> None:
self.view = view
self.ansible_cfg = None
if self.view.window() is not None:
if self.get_setting("site_packages_directory", default=None) is not... |
# -*- coding: utf-8 -*-
'''
bybit-market-maker
------------------------
A very simple market maker bot that relies on the pybit module. Please note
that the bot has very little risk management features. This algorithm is NOT
equivalent to financial advice. Don't be an idiot; use at your own risk!
Documentation can be... |
# coding=utf-8
# Copyright 2020 HuggingFace Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
from torch.utils.data import Dataset
import torch
import numpy as np
from tqdm import tqdm
from collections import Counter
from copy import deepcopy
def load_hotel_review_data(path, sentence_len):
"""
Load Hotel Reviews data from pickle distributed in https://drive.google.com/file/d/0B52eYWrYWqIpQzhBNkVxaV9m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from bson import errors as bson_errors
from bson import json_util, objectid
from flask import Flask, Response, request
from pymongo import MongoClient
import config
import errors
app = Flask(__name__)
app.config.from_object(config.main_config)
if os.environ.... |
#version 1.0 - December 2019
#import packages
import re
import sqlite3
import datetime
#ask the name of the txt file
fname = input("Enter file name: ")
#ask the name of the source file - The name should be written exactly as it is in NexisUni; for instance "de Telegraaf" is correct, "Telegraaf" is not correct
Newspa... |
#!/usr/bin/env python
# Interface to FLIR AX8 camera
import urllib.request
import urllib.parse
Reverse_engineering_notes = '''
wget --post-data 'action=set&resource=.resmon.action.snapshot&value=true' http://192.168.15.6/res.php
wget --post-data 'action=get&resource=.image.services.store.filename' http://192.168.... |
"""
Set of methods to make some common plots for the CNN outputs
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from scipy.spatial.distance import cdist
import scipy.ndimage as nd
def plot_embedding(X, y, num_classes, labels=None, title=None, indice... |
import numpy as np
import exetera.core.persistence as prst
def at_least_one_symptom_v1(assessment_df):
"""
Filter the rows with at least one symptom reported.
:param assessment_df: The assessment dataframe.
:return: A numpy array of bool marking matched rows.
"""
list_symptoms = ['fatigue', '... |
# simulate_sunlight.py - validate the insolation on an oblique sphere
import numpy as np
from scipy import integrate, optimize
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
AXIAL_TILTS = np.linspace(0, np.pi/2, 20)
LATITUDES = np.linspace(0, np.pi/2, 16)
def vector(λ, θ):
return ... |
from socket import socket, MSG_PEEK
from socketserver import TCPServer, BaseRequestHandler, ThreadingTCPServer
from typing import Optional
# Import our protocol specification.
# This is shared between the client and the server to ensure the values stay consistent.
import scuffed_protocol
class MyServerDelegate(BaseR... |
#!/usr/bin/env python3
import argparse
import datetime
from enum import Enum
from gi.repository.GLib import MainLoop, Variant
import pydbus
import sys
from typing import Any, Callable, Dict, List, Literal, Optional, Set, Tuple, Union
def log(*args, **kwargs) -> None:
"""
Write a time-stamped message to an out... |
from __future__ import unicode_literals
import re
from abc import ABCMeta, abstractmethod
from datetime import datetime
from decimal import Decimal
from six import with_metaclass
class Field(with_metaclass(ABCMeta, object)):
def __init__(self, position, length, value=None, tag=None):
self.position = pos... |
"""Generates predictions for closing price of a symbol for 4 next periods"""
import tensorflow as tf
import pandas as pd
import numpy as np
import joblib
import random
from datetime import datetime
import time
import math
from generate_twitter_sentiment import generate_twitter_sentiment
from generate_technical_indicat... |
from __future__ import print_function
import argparse
import binascii
import csv
from itertools import product
import os
import re
import sqlite3
import sys
"""
MIT License
Copyright (c) 2017 <NAME>, <NAME>
Please share comments and questions at:
https://github.com/PythonForensics/PythonForensicsCookbook
or ... |
import logging
import logging.handlers
import os.path
import traceback
from collections import deque
from enum import IntEnum
from logging import DEBUG
LOG_FILE_NAME = 'current.log'
LOG_FOLDER_NAME = 'compipe_logs'
LOG_FILE_PATH = os.path.join(LOG_FOLDER_NAME, LOG_FILE_NAME)
class LOG_COLOR:
HEADER = '\033[95m'
... |
import os
from shutil import rmtree
import pytest
import xarray as xr
from xarray.testing import assert_equal
from pych.pigmachine.interp_obcs import *
from rosypig import ControlField, Simulation
from rosypig.test.test_common import get_pig_grid
from .test_common import get_many_obs, get_single_obs
from ..oidriver imp... |
import torch
from torchsummary import summary
from ...data.loader import FloatDataset, PhaseDataLoader
from .recurrence import RecurrenceLayer
from ..utils import train_model
from sklearn.preprocessing import StandardScaler
import numpy as np
from .._base import ClassifierMixin
torch.backends.cudnn.deterministic = T... |
import uuid
import logging
import asyncio
import aiohttp
import socket
from functools import partial
from aiohttp import web
from collections import namedtuple
from itertools import islice
logger = logging.getLogger(__name__)
Connection = namedtuple('Connection', ('transport', 'channel'))
def limited_as_completed(co... |
import collections
import csv
import logging
import os
import mapdamage
class MisincorporationRates:
def __init__(self, libraries, length):
self.length = length
self.data = {}
for library in libraries:
table_lib = self.data[library] = {}
for end in ("5p", "3p"):
... |
# -*- coding: utf-8 -*-
# python standard
import time
# python extended
import numpy as np
from scipy.integrate import simps
from scipy.fftpack import fft, ifft, fftfreq
from scipy.spatial.distance import cdist
from scipy.sparse import diags
from scipy.linalg import inv
# project
from .kickstart import orthonormal
... |
import numpy as np
import scipy as scipy
from numpy.random import uniform
import scipy.stats
np.set_printoptions(threshold=3)
np.set_printoptions(suppress=True)
import cv2
def drawLines(img, points, r, g, b):
cv2.polylines(img, [np.int32(points)], isClosed=False, color=(r, g, b))
def drawCross(img, center, r, ... |
"""Simulation CLI entrypoint."""
import logging
import sys
from argparse import Namespace
from functools import partial, reduce
from time import time
from typing import Callable, Iterable, Iterator, Optional, Tuple, TypeVar
import numpy as np
from tunable import Tunable
from ...output import Output
from ...parameters... |
"""
Check to see if a single small molecule set of charges is convereged after
a round of IPolQ charge derivation.
This only works for a single restype in the library and resp output files.
Parameters
----------
library : str
sys.argv[1], the library file (OFF format) containing previous charges.
resp_out : str
... |
# -*- coding: utf-8 -*-
import struct
import datetime
from collections import OrderedDict
from pymysql.util import byte2int, int2byte
def iter_bytes_to_string(hash):
if issubclass(hash.__class__, {}.__class__):
for key in hash.keys():
if not issubclass(hash[key].__class__, {}.__class__):
... |
#!/usr/bin/env python
import os
import sys
import json
import csv
from bs4 import BeautifulSoup
from aisikl.app import Application, assert_ops
from fladgejt.login import create_client
from fladgejt.helpers import find_option, find_row
from console import settings
def prihlas_sa():
username = os.environ['AIS_USE... |
import torch
import numpy as np
import sys
sys.path.append("../semi-supervised")
torch.manual_seed(1337)
np.random.seed(1337)
cuda = torch.cuda.is_available()
print("CUDA: {}".format(cuda))
def binary_cross_entropy(r, x):
"Drop in replacement until PyTorch adds `reduce` keyword."
return -torch.sum(x * torch.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import matplotlib.pyplot as plt
import pandas as pd
from lifelines import KaplanMeierFitter
from lifelines.statistics import multivariate_logrank_test
from pamogk import config
from pamogk.data_processor import rnaseq_processor as rp
from pamogk.lib.sutil... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.