text stringlengths 3.07k 22.1k |
|---|
from __future__ import annotations
from io import BytesIO, IOBase
import json
import os
from contextlib import contextmanager
from typing import TYPE_CHECKING, Callable, Dict, Iterator, List, Optional, Tuple, Type
import sqlalchemy
from commonmodel.base import Schema
from dcp import storage
from dcp.data_format.forma... |
"""Variables and functions needed for generating query batches."""
from dataclasses import dataclass
import random
from typing import Sequence, Tuple
import numpy as np
import torch
from torch import Tensor
from torch.utils.data import Dataset, DataLoader
from torch_geometric.data import Data, Batch
from data.data_ut... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init as init
from ..registry import NECKS
def conv_ws_2d(input,
weight,
bias=None,
stride=1,
padding=0,
dilation=1,
groups=1,
... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Convenience routines for maptlotlib colour bars. Also includes some ParaView
colour maps.
"""
import copy
import matplotlib.ticker
import unittest
import numpy as np
__all__ = \
[
"BoundedLocator",
"SciFormatter",
"cold_and_hot",
"cold_and_hot_whit... |
"""``otf.pretty``: A pretty printing library
=========================================
The library is based on <NAME>'s "strictly pretty" [`pdf
<https://lindig.github.io/papers/strictly-pretty-2000.pdf>`_] article.
The code was modified to add the features from the `QuickC-- implementation
<https://github.com/nrnrnr/... |
#!/usr/bin/env python
import os, pdb
import math
import numpy as np
from scipy import interpolate
from node_graph import Graph
import matplotlib.pyplot as plt
from Features import *
'''
Name: Kymograph.py
Description: Parses general, poles and feature information for a single kymograph and stores the data accordingl... |
from django.shortcuts import render, redirect,reverse, get_object_or_404
# importamos el modelo Element, Category de la app listelement
from listelement.models import Element, Category
# importar paginator
from django.core.paginator import Paginator
# importar vistas genericas
from django.views import generic
# importa... |
#################################################
#created the 04/05/2018 09:52 by <NAME>#
#################################################
#-*- coding: utf-8 -*-
'''
'''
'''
Améliorations possibles:
'''
import warnings
warnings.filterwarnings('ignore')
#################################################
########### ... |
"""
"""
import os
import numpy as np
from argparse import ArgumentParser
from utime.bin.evaluate import (set_gpu_vis,
get_and_load_one_shot_model,
get_logger)
from utime import Defaults
from pprint import pformat
from collections import namedtuple
def ... |
import pandas as pd
from pandas.api.types import CategoricalDtype
import numpy as np
import warnings
from sklearn.preprocessing import OneHotEncoder
def preprocess_data():
warnings.filterwarnings('ignore')
df = pd.read_csv('./data/raw/multiple_choice_responses.csv', header=1)
_ = df.pop('Duration (in seco... |
# spectrum_utils.py
#
# This file is part of scqubits.
#
# Copyright (c) 2019 and later, <NAME> and <NAME>
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
##############################################... |
#@title Apache 2.0 License
#
# Copyright (c) 2019 <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, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Standalone script to create WWM boundary file.
@author: khan
@email: <EMAIL>
"""
import os
import numpy as np
class Boundary(object):
""" SCHISM complient boundary class
There are in general two types of boundary - open and land. This class
contains the in... |
# Copyright (c) 2020, eQualit.ie inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import os
import traceback
import uuid
import eventlet
import redis
from redis import Redis
from pyaml_env import parse_config... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.backends.backend_pdf import PdfPages
import warnings
from metk_util import kcal_to_ki_df, check_datafr... |
"""
A collection of utility functions not yet categorized.
"""
import os
from collections import OrderedDict
import json
import numpy as np
import scipy
import sympy
import qutip
import theano
import theano.tensor as T
def complexrandn(dim1, dim2):
"""Generates an array of pseudorandom, normally chosen, complex... |
#!/usr/bin/python3
import argparse
import gym
import math
import logging
import numpy as np
import datetime
import tensorflow as tf
import gym_fetch_base_motions
from network_models.policy_net import Policy_net
from network_models.discriminator import Discriminator
from algo.ppo import PPOTrain
def argparser():
p... |
from __future__ import division
import json
import numpy as np
import pandas as pd
from scipy import stats
from visigoth.stimuli import Point, Points, PointCue, Pattern
from visigoth import (AcquireFixation, AcquireTarget,
flexible_values, limited_repeat_sequence)
def define_cmdline_params(sel... |
from gc import garbage
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import transforms
from torchvision import models
from tqdm import tqdm
from torchsummary import summary
from torch.utils.tensorboard import SummaryWriter
from mobilen... |
import random
import os
import math
import datetime
from decimal import Decimal
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.db import models
from category.models import Category, Tag
from ckeditor_uploader.fields import RichTextUploadingField
from django.conf imp... |
"""Helpers for association tables."""
import typing
from ... import types
from ...helpers import foreign_key as foreign_key_helper
from ...helpers import peek
from ...helpers import relationship
from ..helpers import iterate
def _requires_association(schemas: types.Schemas, schema: types.Schema) -> bool:
"""
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Лабораторна робота № 6-7
Формування проміжного коду.
Розробити програму формування проміжного коду та послідовності тріад
відповідно до сформованого дерева операцій. Порядок розробки програми та
вимоги до неї:
1. На вхід подається вираз, що містить арифметичні операції та ... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# BSD 3-Clause License
#
# Copyright (c) 2020-2021, <NAME>
# 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 m... |
'''
Funciones relacionadas a pygame para el dibujado de una escena 2D
'''
import video
import pygame
import numpy as np
from config import prm
COLOR_BLACK = (0, 0, 0)
COLOR_WHITE = (255, 255, 255)
class Image:
def __init__(
self,
path,
img_pos,
scaling_factor,
move_rati... |
"""
Manager class: responsible for finding, downloading, or building assets as appropriate
"""
import abc
import functools
import logging
import os
import re
import tempfile
import typing as ty
import urllib.request
from . import exceptions, manifest, util
logger = logging.getLogger(__name__)
class BuildTask(abc.A... |
import re
from pyparsing import (Word, alphanums, delimitedList, OneOrMore, ZeroOrMore,
Forward, Suppress, Group, ParserElement, Keyword,
replaceWith, dblQuotedString, removeQuotes,
SkipTo, LineEnd, printables, Optional, StringEnd)
from pyparsing imp... |
import argparse
import os
import shutil
import torch
from . import params as P
from . import utils
from .experiment import launch_experiment
from .hpsearch import HPSearch
def run_experiment(config, mode, seeds, tokens, hpsearch, hpseeds, checkpoint, restart, branch):
print("\n#### CONFIGURATION: " + config + " ###... |
import math
from weakref import WeakValueDictionary as WVD
from .Graphics.color3f import*
from .Graphics.objects import get_global_objects, get_names
from .Graphics.objects.object2d import Circle, TextCircle, Rectangle, Connection, Pointer, SectionedSphere, coord_to_theta, ClassifierSectionedSphere
def detect_object(... |
from math import ceil
from scimitar import core
import scimitar.core.modules
import scimitar.core.libscimitar
from scimitar.runtime.Utility import RuntimeVersion
from ast import literal_eval
from datetime import datetime
DEFAULT_SCRIPT_FILENAME = "myscript.py"
DEFAULT_SCRIPT_LOCATION = "./"
DEFAULT_EXECUTABLE = "a.out... |
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import sys
import os
import argparse
import pickle
import subprocess
import platform
import time
from multiprocessing import Pool as ProcessPool
from PIL import Image
from isc.io import write_hdf5_descriptors,read_descriptors
import... |
import subprocess
import shlex
import re
class Vcgencmd:
__sources = {
"clock": ["arm", "core", "h264", "isp", "v3d", "uart", "pwm", "emmc",
"pixel", "vec", "hdmi", "dpi"],
"volts": ["core", "sdram_c", "sdram_i", "sdram_p"],
"mem": ["arm", "gpu"],
"codec": ["agif"... |
import importlib
import logging
import os
import sys
import timeit
from pathlib import Path
import click
import requests
import tqdm
from bs4 import BeautifulSoup
from cookiecutter.main import cookiecutter
from dotenv import load_dotenv
logger = logging.getLogger(__name__)
@click.command()
@click.argument(
"day... |
import numpy as np
import random
import copy
import matplotlib.pyplot as plt
# from common.clip import clip_by_grad
from MADDPG_model import Actor, Critic
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.utils import clip_grad_norm
BUFFER_SIZE = int(1e6) # replay buffer size
BATC... |
import os
import re
import subprocess
def make_address(address_item_list):
address = ''
for index in range(len(address_item_list)):
address = address + address_item_list[len(address_item_list) - 1 - index]
address = address.lstrip('0')
return address
def get_address_set(command):
all_lin... |
import os
import sys
import json
import numpy as np
import pandas as pd
import torch
import logging
from models.train_LSTNet import train_lstn
from models.Models import get_moe_optimizers
from recon.learning_moe import MoE_Learner
from evaluation.plot import ts_plot
from evaluation.metrics import compute_level_loss, co... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import h5py
import json
import os
import scipy.misc
import sys
import detectron.utils.segms as segms_util
import detectron.utils.boxes as bboxs_util
from... |
import ffmpy
import gevent
from gevent.pool import Pool
import requests
import os, sys
import time
import tqdm
from .echo_exceptions import HlsDownloaderError
def urljoin(a, b):
# get url relative root path
a = a[:a.rfind('/')+1]
# remove slashes at beginning if needed
while b[0] == '/':
b = b... |
import os
import numpy as np
import keras.backend as K
from rl.core import Agent
from rl.util import *
def mean_q(y_true, y_pred):
return K.mean(K.max(y_pred, axis=-1))
class DiscreteA3CAgent(Agent):
pass
class ContinuousA3CAgent(Agent):
def __init__(self, nb_actions, actor, critic, actor_mean_outpu... |
#!/usr/bin/env python
# Imports to support type annotations
from typing import List, Optional, Union
from GameTypes import ItemType
from GameTypes import DialogType, Direction
from HeroState import HeroState
from MonsterParty import MonsterParty
from Point import Point
class HeroParty:
def __init__(self, main_c... |
#!/usr/bin/env python3
"""
Entrypoint for the interpretation pipeline process, runs the end-to-end
pipeline stages either directly or via Hail Batch(es)
- Data extraction from PanelApp
- Filtering and Annotation of variant data
- Re-headering of resultant VCF
Steps are run only where the specified output does not... |
"""
Following DeepRobust repo
https://github.com/DSE-MSU/DeepRobust
"""
import torch
import numpy as np
import torch.nn.functional as F
import torch.optim as optim
from gcn import GCN
from nettack import Nettack
from utils import *
from dataset import Dataset
from torch_geometric.data import Data
import argparse
from t... |
"""
stanCode Breakout Project
Adapted from <NAME>'s Breakout by
<NAME>, <NAME>, <NAME>,
and <NAME>
YOUR DESCRIPTION HERE
"""
from campy.graphics.gwindow import GWindow
from campy.graphics.gobjects import GOval, GRect, GLabel
from campy.gui.events.mouse import onmouseclicked, onmousemoved
import random
BRICK_SPACING ... |
# Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom.
# Copyright (c) 2021, COSIC-<NAME>, <NAME> 10, bus 2452, B-3001 Leuven-Heverlee, Belgium.
from math import log, floor, ceil
from Compiler.instructions import *
from Compiler.instructions_base import *
from ... |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) <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 re... |
# -*- coding:utf-8 -*-
'''
@Author: LiamTTT
@Project: TCTPreprocess
@File: cvt2voc_PMScope.py
@Date: 2021/9/15
@Time: 上午10:16
@Desc: convert PMScope csv annotation file to voc format with specified hyper params.
'''
import os
import json
import argparse
import random
from time import time
import numpy as np
from tqdm... |
"""
Convert MNIST digits into a number and perform artihmetic operations on the number(s).
"""
import tensorflow as tf
import numpy as np
import os
import mnist_math
import argparse
mnist = tf.keras.datasets.mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
BATCH_SIZE = 500
n_train = 10000
class AddNet... |
import enum
import inspect
import re
import unittest
from dataclasses import dataclass
from textwrap import dedent, indent
from typing import List, Tuple
from unittest.mock import Mock
from bot.bot import Bot, Event
from mailru_im_command_bot import CommandBot, MessageEnv
from mailru_im_command_bot.command_bot import... |
from aurora.pipelines.helpers import initialize_config
from aurora.pipelines.time_series_helpers import calibrate_stft_obj
from aurora.pipelines.time_series_helpers import run_ts_to_calibrated_stft
from aurora.pipelines.time_series_helpers import run_ts_to_stft
from aurora.pipelines.time_series_helpers import validate_... |
import os
import pprint as pp
from collections import OrderedDict, defaultdict
import diff_viewer
import pandas as pd
import streamlit as st
from datasets import load_from_disk
DATASET_DIR_PATH_BEFORE_CLEAN_SELECT = os.getenv("DATASET_DIR_PATH_BEFORE_CLEAN_SELECT")
OPERATION_TYPES = [
"Applied filter",
"Appli... |
import ImageHelper
import scipy.ndimage
import noise
import random
import pygame
from Helper import BLOCK_MATERIALS
import os
class Block:
BLOCK_MATERIAL_TEXTURES = dict()
created_material_textures = False
def __init__(self, x, y, z, block_type='empty', block_material='default'):
self.texture = p... |
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from xgboost.sklearn import XGBClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import MultinomialNB
from sklearn.dummy import DummyClassifier... |
import numpy as np
import pandas as pd
import pymc3 as pm
from abc import ABC, abstractmethod
from dataclasses import dataclass
from .constants import *
from .utils import *
__all__ = ['Damuta', 'DataSet', 'SignatureSet']
_opt_methods = {"ADVI": pm.ADVI, "FullRankADVI": pm.FullRankADVI}
_init_strats = ['kmeans', 'uni... |
"""
A doodle inspired by 8 March 2021 discussion on the Boston Python slack about
how it'd be nice to just see the keys available in an object when you fail to
index something.
This code is specific to dicts, but the approach could probably be generalized
to handle other mapping types. This helper will only succeed in... |
import datetime
import shutil
import sqlite3
import sys
import textwrap
try:
import colorama
colorama.init()
HAS_COLORAMA = True
except:
HAS_COLORAMA = False
SQL_ID = 0
SQL_TODOTABLE = 1
SQL_CREATED = 2
SQL_MESSAGE = 3
HELP_FULL = [
('> toddo', 'Display the todos from the current table'),
('> toddo a... |
"""Module for the SRG evolver.
class SRG
---------
An abstraction for the SRG evolution intended to work like a numerical
integrator. It has the following methods::
srg = SRG(potential, flow_operator_mask_v, flow_operator_mask_k)
srg.evolve(lam)
evolved_potential = srg.get_potential()
srg.replace_pote... |
import decimal
import functionality.solarsystem as solar
import assets.tools as tools
from scenes import simulation
from assets.variables import *
# TODO: Think about button usability and about scaling of all the UI elements, with Screen size
# TODO: Implement inelastic collision
# TODO: Adapt code for resizing eleme... |
#%%
import re
import warnings
from functools import partial
from itertools import islice
from pathlib import Path
from typing import Iterable, Iterator, Optional, Union
import numpy as np
import pandas as pd
import psutil
import typer
import yaml
from logger_tt import logger
from scipy.stats import betabinom as sp_bet... |
#!/usr/bin/env python
import os
import numpy as np
import pandas as pd
import datetime as dt
from numbers import Number
from collections.abc import Sequence, Iterable
def assert_has_keys(d, required_keys, verbosity=0):
"""Asserts that dict `d` contains all keys in Sequence `required_keys`"""
assert isinstanc... |
#!/usr/bin/env python
"""
Manages connection to mysql database, with useful methods to save data to tables
in database.
"""
import os
import socket
import sys
import traceback
from pathlib import Path
import pandas as pd
import yaml
from sqlalchemy import MetaData
from sqlalchemy import create_engine
from sqlalchemy.d... |
import numpy as np
import configparser
import argparse
import os
import time
import cv2
from utils import print_config
import sys
import xlsxwriter
# =============================================================================
# FUNCTIONS
# =========================================================================... |
import os
import pytest
from typing import Tuple
from mock import MagicMock
from lft.app.data import DefaultDataFactory, DefaultData
from lft.app.vote import DefaultVoteFactory
from lft.app.epoch import RotateEpoch
from lft.consensus.messages.vote import Vote
from lft.event import EventSystem
from lft.consensus import ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2016 The Cartographer 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
#
# Un... |
# %%
"""
* USA Counties map: https://commons.wikimedia.org/wiki/File:USA_Counties_with_FIPS_and_names.svg
"""
# %%
import pandas as pd
import numpy as np
import datetime as dt
from math import sin, cos, sqrt, atan2, radians
from bokeh.plotting import figure, show, output_file
from bokeh.sampledata.us_counties import ... |
import pyxel
import constants
from random import *
from enum import Enum
class GameStatus(Enum):
GAME = 0,
Main_UI =1
def define_sound():
pyxel.sound(0).set(
notes="c3e3g3c4c4", tones="s", volumes="4", effects=("n" * 4 + "f"), speed=7
)
pyxel.sound(1).set(
notes="f3 b... |
import re
from genie.metaparser import MetaParser
from genie.metaparser.util.schemaengine import Any, Optional
# ====================
# Schema for:
# * 'show ap summary'
# ====================
class ShowApSummarySchema(MetaParser):
"""Schema for show ap summary."""
schema = {
"ap_neighbor_count": i... |
import pytest
import torch
from torch.testing import assert_allclose
from torch.autograd import gradcheck
import kornia
import kornia.augmentation.functional as F
import kornia.testing as utils # test utils
from test.common import device
import kornia.augmentation.param_gen as pg
class TestPerspective:
def te... |
import sys
import json
import os
#### Variables to update before running
# LOGDIRECTORY: the location on your local machine of the log files, relative to current directory
LOGDIRECTORY = '../../../../Downloads/Playforward/aggregate data 2'
# PRINT_ACTIONS: if True, add list of actions to final data. If False, don't.
P... |
# ------------------------------------------------------------------------------------------------------%
# Created by "<NAME>" at 14:53, 17/03/2021 %
# %
# Email: ... |
import numpy as np
from functools import wraps
import pandas as pd
# from memory_profiler import profile
def lazyproperty(func):
name = '_lazy_' + func.__name__
@property
@wraps(func)
def lazy(self):
if hasattr(self, name):
return getattr(self, name)
else:
valu... |
#!/usr/bin/python
import pyrealsense2 as rs # SDK에 엑세스하기에 필요한 파이썬 바인딩 C++을 제공함
import numpy as np
import socket
import time
import copy
import cv2
import sys
import os
import datetime
from time import sleep
active_flag = True
active_flag_old = None
device_bool = False
goods_bool = True #제품있는지 체크
move_bool = True ... |
#
# FILE: Tilted_Axis.py
# AUTHOR: <NAME> (Sirian)
# PURPOSE: Global map script - Simulates a world with its rotational axis
# tipped over on to its side. This is also a square map.
#-----------------------------------------------------------------------------
# Copyright (c) 2005 Firaxis Games, Inc. ... |
import pytest
import requests_mock
from requests.exceptions import HTTPError
from unittest.mock import patch
from draft import DraftData, HeadToHead, LeagueStats, BASE_URL
@pytest.fixture
def test_draft():
return DraftData(123)
@pytest.fixture
def mock_draft_details():
return {
# Trimmed data
... |
#!/usr/bin/env python
"""
Copyright (c) 2015-2017 <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, ... |
import sys, numpy
from numpy import sin, cos, log10, log2, sqrt, pi
from scipy.special import jv as besselj
sys.path.insert(0,'../Stage_0/')
from conversions import *
from motor_mount_mass import motor_mount_mass as mmmass, spar_mass
from cost_class import dict_accumulation
#===================================... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""Utilities to process the value choice compositions,
in the way that is most convenient to one-shot algorithms."""
from __future__ import annotations
import itertools
from typing import Any, TypeVar, List, cast, Mapping, Sequence, Optional, I... |
"""
Module pywingo provides a high level interface to the
[Wingo](https://github.com/BurntSushi/wingo) window manager. This
includes running commands to manage your windows and workspaces, and
responding to events sent by Wingo.
"""
from configparser import ConfigParser
import json
import os
import os.path
import socke... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# code by </MATRIX>@<NAME>
# =================================================================
# this crawler wiritten to crawl a dataset website http://tbt.testrust.com/
import urllib.request, urllib.parse, urllib.error
import threading
import time, re, os
from bs4 impor... |
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import os
from warnings import warn
from bs4 import BeautifulSoup as BS, CData
from bs4.element import Tag
dummy_tag = Tag(name='NULL')
# Classes
class Extent(object):
"""A class for loading tagged data from XML doc
with surrounding token and tag data"""
def _... |
import sys
import warnings
import os
import copy
import time
from collections import OrderedDict, defaultdict
import torch
import ray
import shutil
import gorilla
from ray.tune.trial import Trial
from ray.tune.schedulers import AsyncHyperBandScheduler
from ray.tune.suggest.hyperopt import HyperOptSearch
from ray.tune i... |
# Copyright The IETF Trust 2019, All Rights Reserved
# Copyright 2018 Cisco and its affiliates
#
# 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... |
import os
import numpy as np
import pandas as pd
import random
import string
from ..poplar.legacy.common_funcs import datetime2stamp,stamp2datetime
orig_time = datetime2stamp([2020,8,24,0,0,0],'America/New_York')
def gen_status():
rv = np.random.random()
if rv<=0.8:
return 0
else:
return 1
def exist_tex... |
#!/usr/bin/python
import argparse
import requests
import getpass
import json
import csv
import base64
import sys
#import helper functions
cemfHelper = __import__("cemf_helper")
settings = cemfHelper.get_cemf_settings()
#create a region dictionary
ce_region = {
"gov-east-2": "AWS GovCloud (US)",
"eu-we... |
# users/views.py
# Django modules
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth.decorators import login_required
# from django.db.models import Q
# fro... |
''' Evaluation scripts for the distant supervision '''
import os
import sys
if os.name == 'nt':
root_path = "/".join(os.path.realpath(__file__).split("\\")[:-2])
else:
root_path = "/".join(os.path.realpath(__file__).split("/")[:-2])
if root_path not in sys.path:
sys.path.append(root_path)
# from sklearn.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 24 10:23:44 2022
@author: dhulls
"""
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_probability as tfp
import time
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, I... |
import torch
import torch.utils.data as data
import os
import json
import copy
import random
from datasets.decoder import decode
from datasets.transform import (random_short_side_scale_jitter,
random_crop, horizontal_flip,
uniform_crop)
from datasets.vide... |
import numpy as np
from collections import defaultdict
import json
import os
from pathlib import Path
import math
def get_iou(truth_mask, detected_mask):
truth_mask = np.array(truth_mask, dtype=bool)
detected_mask = np.array(detected_mask, dtype=bool)
intersection = truth_mask * detected_mask
union = ... |
"""
<plugin key="EunoWallet" name="Eunomoticz" author="Drogert" version="0.0.1">
<params>
<param field="Address" label="IP Address" width="250px" required="true" default="127.0.0.1"/>
<param field="Port" label="Port" width="50px" required="true" default="21333"/>
<param field="Username" labe... |
import numpy as np
import torch
from tqdm import tqdm
import os
from utility.distributed import apply_gradient_allreduce, reduce_tensor
from copy import deepcopy
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
... |
"""
Functionalities for communication between QuickStep and logic flow
"""
import collections
import sys
import subprocess
import json
config_json_file_name = 'Config.json'
with open(config_json_file_name) as config_json_file:
config = json.load(config_json_file)
print(config)
STATIC_DEBUG = config['Debug']['... |
import re
from requests import codes
from streamlink.compat import urlparse, parse_qsl
from streamlink.plugin import Plugin, PluginError, PluginArguments, PluginArgument
from streamlink.plugin.api import http, validate, useragents
from streamlink.plugin.api.utils import parse_query
from streamlink.stream import HTTPS... |
import asyncio
from typing import List
from urllib.parse import urlparse
import requests
from discord.ext import commands
import discord
import config
import storage_manager as storage
from data.data_classes import Event, Badge, User, Entry
from datetime import datetime
bot: commands.Bot = commands.Bot(command_prefix... |
import logging
import os
from collections import OrderedDict
import torch
import util
import detectron2.utils.comm as comm
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog
from detectron2.engine import DefaultTrainer, default_argu... |
"""
This python function is part of the main processing workflow. It will start a job in the Amazon Transcribe service,
using whatever configuration parameters are set. It handles all of the cross-validation of parameters, and takes
into account the audio format - it will then degrade certain feature requests; e.g. i... |
import discord
from discord.ext import commands
from discord.utils import get
import asyncio
import json
import os
import Main
import ConsoleColors as CC
import SimpleJSON
import DaeGal_Utils
Path = "/DaeGal/Data/Guild"
ONE_HOUR = 60 * 60
class GuildUser(commands.Cog):
def __init__(self, client):
self.cl... |
"""Process model specification files or objects."""
import copy
import re
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
from estimagic.optimization.utilities import sdcorr_params_to_matrix
from respy.config import DEFAULT_OPTIONS
from respy.pre_processing.model_checking i... |
#!/usr/bin/python3
import json
import seaborn as sns
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import matplotlib.colors as colors
from scipy.stats import spearmanr
import pylab
import scipy.cluster.hierarchy as sch
from scipy.stats import pearsonr, friedmanchisqu... |
import codecs
import configparser
import os.path
import random
lines = []
mode = "LTF"
name = ""
path = ""
target = 5
def main():
config = configparser.ConfigParser()
config.read('config.ini')
print_intro_message()
print_paths()
load_path()
load_file()
load_mode()
load_target()
... |
# -*- coding: utf-8 -*-
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
import datetime
import logging
import netCDF4 as nc
import numpy as np
import pandas as pd
import pytz
from dateutil import parser
from siphon.catalog import TDSCatalog
logger = logging.... |
from emu.cpu import labeltab, datatab
from emu.instruction import Instruction, BinaryInstruction
def line2val(line):
return Instruction(line).to_binary()[0].value
def line2multi(line):
return map(lambda x: x.value, Instruction(line).to_binary())
def test_to_binary():
assert line2val('add $t1, $t1, $t2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.