text stringlengths 3.07k 12.6k |
|---|
#THIS MEANS WAR
from .Base import Object,Rotatable,Owned
from Lib import Img,Vector
from .Machines.Base import Machine,FixedMachine
from Game.Registry import add_recipe
from Game.Research import add_recipesearch
from Game import FX
from Engine.Items import Placeable,MultiSlot,Slot,ammos,resources
from .Machines import ... |
# coding: utf-8
'''
This utilitary intends to monitor changes made in the SciELO Title Manager
catalog.
'''
import argparse
import os
import logging
import time
import hashlib
import random
import json
from io import BytesIO
from isis2json import isis2json
from xylose.scielodocument import Journal
from articlemetarpc... |
import base64
import hashlib
import json
import re
from datetime import datetime
import pytz
from dateutil import parser
from connaisseur.exceptions import (
InvalidTrustDataFormatError,
NoSuchClassError,
NotFoundException,
ValidationError,
WrongKeyError,
)
from connaisseur.trust_root import Trust... |
# -*- coding: utf-8 -*-
"""
A set of functions to check and correct strand alignment. If a variant is not
alignable it is removed. Alignment is required before running imputation.
The module requires Shapeit2 and Plink to be installed:
- Shapeit2 is used to check the strand alignment
- Plink is used to flip SNPs that... |
from pygame import *
from random import randint
mixer.init()
font.init()
font1 = font.SysFont('Arial', 50)
font2 = font.SysFont('Arial', 70)
win_width = 1024
win_height = 800
x1 = 512
y1 = 650
score = 0
lost = 0
Next = False
window = display.set_mode((win_width,win_height))
display.set_captio... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you m... |
import argparse
from timeit import default_timer as timer
import os
import time
import torch
import torch.optim as optim
from torch.backends import cudnn
from torch.autograd import Variable
import torchvision.utils as vutils
from tqdm import tqdm
from utils import one_hot_encode, capsnet_training_loss, ca... |
from asyncio import create_subprocess_shell as asyncrunapp
from asyncio import sleep
from asyncio.subprocess import PIPE as asyncPIPE
from os import remove
from platform import python_version
from telethon import events, version
from telethon.tl.types import MessageEntityMentionName
from uniborg.util import admin_cmd... |
import logging
import numpy
import pandas as pd
from covidactnow.datapublic.common_fields import CommonFields
from libs.datasets import data_source
from libs.datasets import dataset_utils
from libs.us_state_abbrev import US_STATE_ABBREV
from libs.datasets.common_fields import CommonIndexFields
_logger = logging.getLo... |
"""
MagCollectionOperator: Queries Microsoft Academic Knowledge API and stores the responses on S3.
The pickle file is a list of JSONs where every JSON object is the API response corresponsing to a paper.
Every pickle contains a maximum of 1,000 objects (that's the maximum number of
papers we can retrieve from MAG ... |
"""
Aggregate data over time ranges for each position
Winds: bin directions, bin velocities, calculate value counts of each combination
Precipitation: bin precipitation, value counts for bins
Temperatures: calculate daily max and min, calculate means and SDs of these
Set `DATA_DIR` and `test` to try out.
pyth... |
from hobbs import *
from nltk.parse.chart import BottomUpLeftCornerChartParser
import nltk
r = ["Himself", "himself", "Herself", "herself",
"Itself", "itself", "Themselves", "themselves"]
p = ["He", "he", "Him", "him", "She", "she", "Her",
"her", "It", "it", "They", "they",'he','He']
def convert_to_treebank(se... |
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import datetime, time, requests
import Configuration as cfg
import home.SQLTabHome as SQLTabHome
import home.FBTabHome as FBTabHome
import home.CustomMessageMgmt as CustomMessageMgmt
class TabHome(QWidget):
def __init__(self, tray... |
#!/usr/bin/env python
import os
import re
import time
import json
import argparse
import requests
import logging
import boto3
import zipfile
from submit_job import main as submit_job
from hysds.celery import app
from email import policy
from email.parser import BytesParser
# create order_granule.log
LOG_FILE_NAME = '... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""View functions for maintenance"""
# pylint: disable=invalid-name
# pylint: disable=no-else-return
import re
from logging import getLogger
from ggrc.maintenance import maintenance_app
from ggrc import d... |
import numpy as np
import utils.utils_load_data as dh
class HeuristicInitializer:
"""
data is a numpy array of all the cells normalized marker data
"""
def __init__(self, node_type, gate_data_axes_ids, pos_data, neg_data,
num_gridcells_per_axis=20, consider_all_gates=False, greedy_f... |
#!/usr/bin/env python
# ~*~ coding: utf-8 ~*~
# >>
# © Vivint, inc. 2017
# blake, afjr-sprinklers
# <<
from gevent.monkey import patch_all
patch_all()
import os
import time
import logging
from datetime import datetime
from flask import Flask, render_template, jsonify, abort, redirect, url_for, flash, request
from... |
import pandas as pd
import numpy as np
import random
import sys
from tabulate import tabulate
'''
Reads the .csv file into a Pandas dataframe.
'''
def read_csv_into_dataframe(filename):
return pd.read_csv(filename)
'''
Takes in a dictionary correlating first names with "M" (if the name is
commonly a male name), an... |
# Copyright 2020 Adap GmbH. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
###############################################################################
#
# Copyright (C) 2012-2014 Tavendo 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://ww... |
import gc
import io
import math
import os
import time
from collections import deque
from multiprocessing import Pool
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from scipy.optimize import curve_fit
from sklearn.preprocessing import StandardSca... |
from django.http import HttpResponseRedirect
from django_mako_plus import view_function
from formlib import Formless
from django import forms
from account.models import User
from django.contrib.auth import authenticate, login
from catalog import models as cmod
from django_mako_plus import view_function
from django.cont... |
import pprint as pp
import random
from utils import data_helper
from common import distance
from clustering.clustering import BaseClustering
"""K-means is often referred to as Lloyd’s algorithm. In basic terms, the algorithm has three steps. The first step chooses the initial centroids, with the most basic method bei... |
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Li... |
"""
Formatting package of creatorUtils.
"""
import os
import hashlib
import math
import sys
import time
from creatorUtils.compat.types import *
#Constants
LITTLE = True # Marker for little endian
BIG = False # Marker for big endian
##-------------------STRING-------------------##
def divide(strin... |
# -*- coding: utf-8 -*-
import os
import re
import htmlentitydefs
import requests
from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from datetime import datetime
from pybars import Compiler
from HTMLParser import HTMLParser
# Takes a response (e.g. from Wordpre... |
from typing import Iterable, List
from loguru import logger
from sqlalchemy import Column, ForeignKey, Integer, String, create_engine, delete
from sqlalchemy.orm import Query, Session, declarative_base, relationship
from sqlalchemy.sql import Delete
Base = declarative_base()
class MyBase:
def __repr__(self) -> ... |
import contextlib
import os
import sqlite3
import tempfile
import unittest
from wcpan.drive.core.cache import (
ReadOnly,
ReadWrite,
Cache,
CacheError,
)
from wcpan.drive.core.test import PseudoManager
from wcpan.drive.core.util import create_executor, get_utc_now
class TestTransaction(unittest.TestC... |
#!/usr/bin/env python3
from enum import Enum
import json
from os.path import join
from absl import app
from absl import flags
from absl import logging
from tqdm import tqdm
FLAGS = flags.FLAGS
flags.DEFINE_string('data_root', '', 'root directory for data.')
flags.DEFINE_string('table_file', '', '')
flags.DEFINE_str... |
from enum import Enum
import kgprim.ct.models as ctmodels
import kgprim.ct.repr.mxcommon as common
class CoordinatesConvention(Enum):
rotationOnTop = 0
translationOnTop = 1
class VectorType(Enum):
motion = 0
force = 1
block_bottom_left = (slice(3,6),slice(0,3))
block_bottom_right= (slice(3,6),slice... |
# coding:utf-8
"""
post.py
~~~~~~~
Post Model
"""
from datetime import datetime
from markdown import markdown
from random import seed, randint
import bleach
import forgery_py
from flask import url_for,flash
from fine import db
from .tag import Tag
from .user import User
from fine.exceptions import Vali... |
"""The kraken integration."""
from datetime import timedelta
import logging
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from .const import DATA_UPDATED, DOMAIN
_LOGGER = logging.getLogger(__name__)
SCAN... |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ config.py ]
# Synopsis [ configurations ]
# Author [ <NAME> (Andi611) ]
# Copyright [ Copyleft(c), NTUEE, NTU, Taiwan ]
"""*********************************... |
import os
import sys
import json
import logging
import argparse
import uuid
import time
from shutil import copyfile
import shure
import offline
import tornado_server
APPNAME = 'micboard'
CONFIG_FILE_NAME = 'config.json'
FORMAT = '%(asctime)s %(levelname)s:%(message)s'
config_tree = {}
gif_dir = ''
group_update_l... |
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# justice-platform-service (4.10.0)
# pylint: disabl... |
import re
import datetime
import time
# define SQLITE_OK 0 /* Successful result */
# define SQLITE_ERROR 1 /* SQL error or missing database */
# define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
# define SQLITE_PERM 3 /* Access permission denied */
# define SQLITE_ABORT... |
"""The decision forest module holds implementations of decision forests (random forests)."""
import numpy as np
from tensorflow.contrib.learn.python.learn.estimators import estimator
from tensorflow.contrib.learn.python.learn import metric_spec
from tensorflow.contrib.tensor_forest.client import eval_metrics
from tenso... |
import copy
import pytest
from datasette.app import Datasette
@pytest.mark.asyncio
async def test_dashboard_views(datasette):
dashboards = datasette._metadata["plugins"]["datasette-dashboards"]
for slug, dashboard in dashboards.items():
response = await datasette.client.get(f"/-/dashboards/{slug}")
... |
"""Specialize graphs according to the types of their arguments."""
from collections import defaultdict, Counter
from .dtype import Type, Function, Dead, Unknown
from .infer import Context, GraphInferrer, ANYTHING, Inferrer
from .ir import GraphCloner, is_apply, is_constant, Constant, \
succ_deeper, Graph
from .pr... |
#!/usr/bin/python
import itertools
import os
import fnmatch
import re
import sys
import argparse
import ninja_syntax
import gcc
import llvm
import msvc
# --- util functions
def flags(*iterables):
return ' '.join(itertools.chain(*iterables))
def get_files(root, pattern):
pattern = fnmatch.translate(pattern)... |
import cv2
import numpy as np
import time
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
def sse(array1, array2):
return np.sum(np.power(array1.astype(np.float32) - array2.astype(np.float32), 2))
def mse(array1, array2):
return np.mean(np.power(array1.astype(np.float32) - array2.ast... |
"""
This module contains a list of utilities related to console.
"""
from __future__ import print_function
from select import select
import subprocess
import logging
import math
import sys
import os
log = logging.getLogger("mth.utils")
def execute(command, suppress_errors=False, out=subprocess.PIPE, io_mode="w+"):
... |
import pdal
import json
import geopandas as gpd
from pyproj import Transformer
from .logs import log
from shapely.geometry import Polygon, Point
import os
if (not os.path.isdir('./logs')):
os.mkdir("./logs")
logs_path = "./logs/get_data.logs"
if not os.path.exists(logs_path):
with open(logs_path, "w"):
... |
import numpy as np
import pandas as pd
from keras.utils import to_categorical
from scipy.signal import butter, lfilter
# @sp - remove unused imports
from imblearn.over_sampling import SMOTE
def conv_arrays_to_df(train_x, train_y, params):
n_steps = train_x.shape[2] # number of samples per 30 seconds
train_y... |
# Name: rabbitmq-collectd-plugin - rabbitmq_info.py
# Author: https://github.com/phrawzty/rabbitmq-collectd-plugin/commits/master
# Description: This plugin uses Collectd's Python plugin to obtain RabbitMQ
# metrics.
#
# Copyright 2012 <NAME>
# Copyright 2014 <NAME>
# Licensed under the Apache License, Version 2.0 (the... |
import glob
import os
import torch
import matplotlib.pyplot as plt
from datetime import datetime
from torchvision.utils import save_image
import constants
import train_utils
import box_utils
import threading
import random
import numpy as np
from adversary import attack_batch
def save_and_upload_image(tensor, save_path... |
from typing import List
from typing import Union
import pandas as pd # type: ignore
from tnl.ast import Module
from tnl.ast import Transform
from tnl.ast import Test
from tnl.ast import AliasBlock
from tnl.ast import HeaderBlock
from tnl.ast import ValueBlock
from tnl.ast import AliasRule
from tnl.ast import HeaderR... |
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... |
import torch
from torch.utils.data import Dataset
from torchvision import transforms
import os
import pandas as pd
import numpy as np
class ToTensor(object):
"""Transform the numpy array to a tensor."""
def __init__(self, dtype=torch.float):
self.dtype = dtype
def __call__(self, input):
... |
import json
import traceback
import aiohttp
import cogs.utils.context as context
import cogs.utils.permission_checks as permissions
from discord import Color, Embed
from discord.ext import commands, menus
class Source(menus.GroupByPageSource):
async def format_page(self, menu, entry):
embed = Embed(
... |
#!/usr/bin/env python
# Copyright (c) 2015
#
# All rights reserved.
#
# This file is distributed under the Clear BSD license.
# The full text can be found in LICENSE in the root directory.
import json
import os
import re
import sys
from string import Template
try:
from collections import Counter
except:
from... |
import jax.numpy as jnp
from matplotlib import pyplot as plt
from numpy.linalg import inv
# Local imports
from jsl.experimental.seql.environments.base import make_evenly_spaced_x_sampler
from jsl.experimental.seql.environments.sequential_data_env import SequentialDataEnvironment
from jsl.experimental.seql.utils impor... |
import requests
import os
import pandas as pd
from collections import OrderedDict
from sqlalchemy import create_engine
from sqlalchemy import insert, select
from sqlalchemy import Column, ForeignKey, Integer, String, Boolean, LargeBinary
from sqlalchemy.orm import sessionmaker, registry
from sqlalchemy.orm import relat... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from utils.utils_metrics import evaluate
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
def fit_one_epoch(model_train, model, loss_history,... |
from __future__ import annotations
__all__ = [
"addFont",
"ENTRY_POINT",
"font",
"icon",
"IconFont",
"IconFontMeta",
"IconOpts",
"Animation",
"pulse",
"spin",
]
from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
from ._animations import Animation, pulse, spin
from ... |
import json
from enum import Enum
import requests
from openpyxl import Workbook
columnnames = ["编号", "中文名", "英语名", "类别", "法术力费用",
"异能", "稀有度", "攻防", "现开", "轮抓", "构筑"]
raritytranslation = {"common": "普通",
"uncommon": "非普通", "rare": "稀有", "mythic": "秘稀"}
class Languages(Enum):
... |
"""
An example implementation of STROBE. Doesn't include the key tree.
Copyright (c) <NAME>, Cryptography Research, 2016.
I will need to contact legal to get a license for this; in the mean time it is
for example purposes only.
"""
from __future__ import absolute_import
from KeccakF import KeccakF
# #Q_ tmp
import... |
import os
from random import randint
import logging
import csv
import contextlib
from uuid import uuid4
from datetime import datetime, timedelta
from tornado.options import define, options
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.queues import PriorityQueue
import models
define('host', d... |
import contextlib
import json
from unittest.mock import patch
import pytest
from sm.engine.db import DB
from sm.rest import api
from sm.rest.databases import MALFORMED_CSV, BAD_DATA
from sm.rest.utils import ALREADY_EXISTS
from .utils import create_test_molecular_db
GROUP_ID = '123e4567-e89b-12d3-a456-426655440000'
... |
import biom
from numpy import arange
from pandas import DataFrame
from pandas.testing import assert_frame_equal
import pytest
from qurro._rank_utils import filter_unextreme_features
from qurro.generate import biom_table_to_sparse_df, process_input
from qurro.tests.test_df_utils import get_test_data as get_test_data_2
... |
"""
Tests for the Dan Jacobson ORNL Arabidopsis stored queries.
"""
import json
import time
import unittest
import requests
import os
import glob
import yaml
from test.helpers import get_config, assert_subset, modified_environ
from test.stored_queries.helpers import create_test_docs
from importers.djornl.parser import... |
import os
import numpy as np
import pandas as pd
from scipy import sparse
from scipy.sparse import csr_matrix, csc_matrix
from tqdm import tqdm
import scipy
from scipy.sparse.linalg import eigsh
from scipy.sparse import coo_matrix
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.svm import LinearSVC
... |
import torch
def get_jacobian_loop(module, x, nout, jcb_bz=1, return_out=False):
"""function to compute Jacobian of output of one module wrt. the input in a
mini-batch manner based on torch autograd, reference:
1. https://pytorch.org/docs/stable/_modules/torch/autograd/functional.html#jacobian
:para... |
import numpy as np
import lsst.sphgeom as sphgeom
# Add some missing functionality from sphgeom
# See LSSTDESC.Coord for definitions of these
def _dsq(pt1, pt2):
return (
(pt1.x()-pt2.x())**2
+ (pt1.y()-pt2.y())**2
+ (pt1.z()-pt2.z())**2
)
def _cross(pt1, pt2):
return (
pt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Script pro generaci playlistu z OTA služby O2TV
# ***********************************************
# Script je odvozen z Kodi addon service.playlist.o2tv,
# který byl vytvořen z původního addon autora <NAME>.
import os
import time
import urllib3
import common as c
im... |
#
# this module was originally written by xfnw.
# (c) xfnw/lickthecheese <<EMAIL>>
#
import config
import common, importlib, out, os, time
import traceback
import pprint
import restart as _restart
modname = "admin"
async def dump(self, chan, source, msg):
"""
dump the contents of self to a file
for debu... |
from __future__ import print_function
from P13pt.mascril.measurement import MeasurementBase
from P13pt.mascril.parameter import Sweep, String, Folder, Boolean
from P13pt.mascril.progressbar import progressbar_wait
from P13pt.drivers.bilt import Bilt, BiltVoltageSource, BiltVoltMeter
from P13pt.drivers.anritsuvna import... |
import logging, os, glob, re
from pathlib import Path
__doc__ = "The file_selection module provides multiple supporting functions for interaction with files"
__all__ = [
"get_newest_file_from_directory",
"get_file_list_from_directory",
"return_file_list_if_directory",
"check_file_name_ending",
]
def... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pickle
import string
import numpy as np
from gensim.models import word2vec, Word2Vec
from keras.preprocessing.sequence import pad_sequences
def build_tag2id(tags, tag2id_filepath):
"""
Build the dictionary mapping from tag to id
:param tags: the BIO t... |
"""
This script auto-inlines images, Javascript, and CSS.
It also resolves iframes to depth MAX_DEPTH (3 by default).
"""
import base64
import functools
import logging
import re
import requests
import sys
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
from mitmproxy import http, ctx
f... |
"""SVCLASSIFIER training worker processes"""
import logging
import datetime
import shutil
import tempfile
from pathlib import Path
import re
import aiohttp
import ai_training as ait
import ai_training.training_process as aitp
from embedding.text_classifier_class import EmbeddingComparison
from embedding.word2vec_cli... |
#!/usr/bin/env python
import asyncio
import bisect
import collections
import itertools
import os
import sys
from progressbar import ProgressBar, AnimatedMarker, Timer, Bar, Percentage, Widget
import pgpy
from pgpy.packet import Packet
from pgpy.types import Exportable
ascfiles = [ os.path.abspath(os.path.expanduser... |
# pylint: skip-file
# type: ignore
from asyncio import coroutine
from . import exceptions
from . import templatenodes as nodes
from . import environment
from . import interpolatedstr
from . import expression
from .platform import bs4
from .utils import delayedupdater
class RenderFactory:
AVAILABLE = {}
@cla... |
import argparse
from typing import Callable
import tensorflow as tf
import tensorflow_addons as tfa
from dataset import load, Split
from nfnet import NFNet, nfnet_params
NUM_CLASSES = 1000
NUM_IMAGES = 1281167
def parse_args():
"""Parse command line arguments."""
ap = argparse.ArgumentParser()
ap.add_... |
from typing import List, Union
import numpy as np
from quara.loss_function.weighted_relative_entropy import (
WeightedRelativeEntropy,
WeightedRelativeEntropyOption,
)
from quara.math.entropy import (
relative_entropy_vector,
gradient_relative_entropy_2nd_vector,
)
from quara.math.probabil... |
#
import numpy as np
import vampyre
from ebmrPy.inference.ebmr import EBMR
from ebmrPy.inference.iridge import IRidge
import collections
def fit_ebmr_base(X, y, prior = 'point', grr = 'mle',
grid = np.array([0.001, 1.0, 2.0, 3.0, 4.0]),
ignore_convergence = True):
# EBMR does not add i... |
from django.core.management.base import BaseCommand, CommandError
import re
import requests
import pprint
from pokemon_api.models import Pokemon, Stats, EvolutionChain
URL_EVOLUTION = "https://pokeapi.co/api/v2/evolution-chain/"
URL_POKEMON = "https://pokeapi.co/api/v2/pokemon/"
class Command(BaseCommand):
help ... |
from __future__ import division, print_function, absolute_import
import numpy as np
# Expansion of polar term
aij = np.array([[0.3043504, 0.9534641, -1.1610080],
[-0.1358588, -1.8396383, 4.5258607],
[1.4493329, 2.0131180, 0.9751222],
[0.3556977, -7.3724958, -12.281038],
... |
#!/usr/bin/env python3
# coding: utf-8
# SPDX-License-Identifier: Apache-2.0
# Copyright 2019 AntiCompositeNumber
# 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/l... |
from dataclasses import dataclass, field
from typing import Dict, List, NamedTuple, Tuple
from covid_shared import workflow
from covid_model_seiir_pipeline.lib import (
utilities,
)
class __RegressionJobs(NamedTuple):
regression: str = 'beta_regression'
hospital_correction_factors: str = 'hospital_corre... |
import collections
import inspect
from abc import ABC, abstractmethod
from typing import Callable, Optional, Dict, List, Any
import attrs
from databutler.datana.generic.corpus.code import DatanaFunction
from databutler.datana.generic.corpus.processing.base_processor import DatanaFunctionProcessor
from databutler.pat ... |
# coding: utf-8
# # 113th Congress as News Commentators on Twitter
#
# In this project I am answering the following questions:
#
# * Who are the most active news commentators among senators and congressmen ?
# * Which news got the most attention by the politicians ?
# * How many news (of 7376) are commentated by de... |
import _compat_pickle
import inspect
import json
import pkgutil
import pickle
import sklearn
import sys
from pathlib import Path
from ..utils import try_get_attr
# handle pickle white list file
WL_FILE = str(Path(__file__).parent.joinpath(
'pk_whitelist.json').absolute())
class _SafePickler(pickle.Unpickler, o... |
import re
from datetime import datetime
from subprocess import Popen, PIPE, TimeoutExpired
from textops import find
import os
import time
from enum import Enum
from termcolor import colored
class LogSeverity(Enum):
SUCCESS = "Success"
WARNING = "Warning"
INFO = "Info"
ERROR = "Error"
FATAL = "Fat... |
from __future__ import division
import os
from os.path import abspath, expanduser, join, dirname, pardir
from yaml import load as load_yaml
from ngs_utils.config import load_yaml_config, fill_dict_from_defaults
from ngs_utils.file_utils import verify_file, verify_module, adjust_path
from ngs_utils.logger import info, ... |
"""Deep Q learning graph
The functions in this file can are used to create the following functions:
======= act ========
Function to chose an action given an observation
Parameters
----------
observation: object
Observation that can be feed into the output of make_obs_ph
stochastic: bool... |
from __future__ import unicode_literals
from django import forms
from django.db.models.functions import Lower
from django.utils.translation import ugettext_lazy as _
from tracpro.charts import filters
from tracpro.contacts.models import Contact
from tracpro.polls.models import Poll, Question
from .models import Base... |
import json
import facilities
import pandas as pd
import projects
import users_and_facilities
import users_and_projects
# Todo: address pandas warning w/out silencing
pd.options.mode.chained_assignment = None
# Define years over which compliance data will be considered and where to find it
reporting_periods = ['2013... |
import json
# import os.path
import os
import boto3
import email
from botocore.exceptions import ClientError
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
BUCKET_NAME = os.environ.get('s3_buc... |
from __future__ import print_function
import paddle
import paddle.fluid as fluid
from paddle.fluid import core
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.dygraph.layer_object_helper import LayerObjectHelper
from paddle.fluid.initializer import Normal, Constant, NumpyArrayInitializer... |
import pyaudio
import wave
import numpy as np
import matplotlib.pyplot as plt
import pickle
import threading
from tkinter import *
from xython import xylophuck
import scipy.signal
class streamHandler():
def __init__(self,format=pyaudio.paInt16,channels=1,rate=44100,io=True,chunk=1):
self.p = pyaudio.PyAud... |
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from torchvision.utils import save_image
import im2mesh.common as common
try:
import open3d as o3d
except:
print("Warning: failed to import open3d, some function may not be used. ")
def visualize_data(data, data_ty... |
from argparse import ArgumentParser
def none_or_default(x, default):
return x if x is not None else default
class HyperParameters():
def parse(self, unknown_arg_ok=False):
parser = ArgumentParser()
# Enable torch.backends.cudnn.benchmark -- Faster in some cases, test in your own environment
... |
from django.core.exceptions import ValidationError as DjangoValidationError
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.settings import api_settings
from salesman.... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Dataset available at: https://www.kaggle.com/c/house-prices-advanced-regression-techniques
def get_cat_num_columns(data):
categorical_columns = list()
numerical_columns = list()
for column in data.columns:
... |
import os
import numpy as np
from astropy.table import Table
from src.Data import Data
from kndetect.utils import get_data_dir_path
def ztf_ob_type_name(type_no: int):
"""
Retuens the type name in string for the type numbers in the ZTF dataset.
Parameters
----------
type_no: int
type nu... |
from dataclasses import dataclass
from typing import List
import aiohttp
from tastyworks.models.order import Order, OrderPriceEffect
@dataclass
class TradingAccount(object):
account_number: str
external_id: str
is_margin: bool
is_closed: bool
account_type_name: str
nickname: str
opened_a... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from config import cfg
def count_trainable_parameters(model):
""" to count trainable parameters """
return sum(p.numel() for p in model.parameters() if p.requires_grad)
class double_conv(nn.Module):
""" implements two Conv-BatchNorm bloc... |
"""
Data Simulation for Anfis Sandbox
"""
import numpy as np
# from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_regression
from .markov_process import MRS
from .star_process import STAR
import matplotlib.pyplot as plt
plt.rcParams['... |
#!/usr/bin/env python
__version__ = "0.0.1"
import math
from array import array
from argparse import ArgumentParser
from PIL import Image
RGB_COLOR_COUNT = 256
GRAYSCALE_COLOR_COUNT = 256
def get_int_from_rgb(rgb):
if isinstance(rgb, tuple):
red = rgb[0]
green = rgb[1]
blue = rgb[2]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.