text stringlengths 3.07k 12.6k |
|---|
from tkinter import *
from tkinter import messagebox
from modules.Sounds import click
from modules.Credentials import db_connection, bookTable, bid_check
def add_check():
with open(r"counters\addbook.txt", "r") as file:
a = file.read()
return True if a == "1" else False
def add_open():
with open... |
import select
import socket
import sys
from getpass import getpass
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from tinydb import TinyDB, Query
session_key = None
db = TinyDB('log/users.json')
BUFFER_SIZE = 4096
server_public_key = None
RSA_key = RSA.genera... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Markup scoring functions
Created by: <NAME>
License: MIT (see LICENSE for details)
"""
import os, sys, re, logging
log = logging.getLogger()
from bs4 import BeautifulSoup
from bs4.element import Tag
import patterns
# scores for individual tags
element_bias = {
... |
from lxml import html
import requests
from bs4 import BeautifulSoup
import sys
import os
import re
import time
REGEX = '\s*([\d.]+)'
count = 0
#this code prints out information (vulnerability ID, description, severity, and link) for all the vulnerabilities for a given dependency passed in through command line
def usag... |
'''
Created on 4 Sep 2017
@author: ywz
'''
import numpy
import tensorflow as tf
from utils import flatten_tensor_variables
from utils import unflatten_tensors, get_param_values
from utils import get_param_assign_ops, set_param_values
from krylov import Krylov
class Hvp:
def __init__(self):
pass
... |
import unittest
from itertools import product
from ..tools import Path
from ..configuration import transitions, default_case, states, state, transition, case
from ..normalize import normalize_statemachine_config
def count(it, key):
return len([i for i in it if key(i)])
class TestStatemachineStandardizarion(uni... |
'''Generalised multiplication tables'''
import collections
import itertools
import inspect
# table :: Int -> [[Maybe Int]]
def table(xs):
'''An option-type model of a multiplication table:
a tabulation of Just(x * y) values for all
pairings (x, y) of integers in xs where x > y,
and Nothing v... |
#
# Copyright 2018 the original author or 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 applicable law or... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (C) 2019 <NAME> @ The University of Texas at Austin.
# All rights reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# ----------------------------------------------------... |
from __future__ import print_function
import librosa
import librosa.display
from song_classes import Slice, beatTrack
def slicer(song, n_beats=16, duration=0):
'''
Takes in a song and its segments and computes the largest total segment in the dictionary.
To do this it sums up each of the dictionary entrie... |
import multiprocessing
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from .SurvivalTree import SurvivalTree
from .scoring import concordance_index
class RandomSurvivalForest:
def __init__(self, n_estimators=100, min_leaf=3, unique_deaths=3,
n_jobs=None, paralleliz... |
#!/usr/bin/env python
#"""Main entry-point into the 'PyPI Portal' Flask and Celery application.
#
#This is a demo Flask application used to show how I structure my large Flask
#applications.
#
#License: MIT
#Website: https://github.com/Robpol86/Flask-Large-Application-Example
#
#Command details:
# devserver ... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Simple compiler gym tabular q learning example.
Usage python tabular_q.py --benchmark=<benchmark>
Using selected features from Autophase o... |
#!/usr/bin/env python3
import time
import signal
import urllib.request
import requests
import logging
import influxdb
from configparser import ConfigParser
# Global vars.
# CONFIG_FILE_PATH = './mh-data-acquisition.conf' # For dev
CONFIG_FILE_PATH = '/etc/mh-data-acquisition.conf'
db_client = None
running = True
... |
import argparse
import numpy as np
import os
import imutils
import cv2
import random
import operator
# print(cv2.__version__)
from utils.load_images import load_images_multi_thread
def parse_args():
desc = "Dedupe imageset"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--verbose', acti... |
import datetime
import uuid as uuid_object
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.urls import reverse
from django.utils import timezone
from projectroles.models import Project
#: Shortcut to Django User model class.
from projectroles.plugins import ge... |
#!/usr/bin/env python
""" See the file "LICENSE" for the full license governing this code.
Copyright 2011-2021 <NAME>
"""
#adjust pylint for pytest oddities:
#pylint: disable=missing-docstring
#pylint: disable=unused-argument
#pylint: disable=attribute-defined-outside-init
#pylint: disable=protected-access
#pylint:... |
import numpy as np
from typing import Tuple
from IMLearn.learners.metalearners.adaboost import AdaBoost
from IMLearn.learners.classifiers import DecisionStump
from utils import *
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def generate_data(n: int, noise_ratio: float) -> Tuple[np.ndarr... |
import flask
from flask.ext.sqlalchemy import SQLAlchemy
from pgconn import pgconn
app = flask.Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = pgconn
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
userid = db.Column(db.Integer, primary_key=True)
username = db.Column(db.Str... |
"""CRUD :eMixins that can be used in Actions or Views."""
import copy
import json
from django import forms
from django import http
from django.contrib.admin.models import ADDITION, CHANGE, DELETION, LogEntry
from django.contrib.contenttypes.models import ContentType
from crudlfap import html
class CreateMixin:
... |
import os
import sys
import time
import datetime
import copy
import random
import logging
import numpy as np
from tqdm import tqdm
import torch
import torch.optim as optim
import torch.nn as nn
from torch.utils.data import DataLoader, RandomSampler, random_split
from tensorboardX import SummaryWriter
from tracksuite.... |
import json
import os
from contextlib import contextmanager
from glob import glob
from unittest.mock import patch
import pytest
from meterelf import _calibration, _debug, _main, _params
mydir = os.path.abspath(os.path.dirname(__file__))
project_dir = os.path.abspath(os.path.join(mydir, os.path.pardir))
params_fn = ... |
from __future__ import division
from six.moves import range
from cctbx.array_family import flex
class show_observations:
def __init__(self,obs,unobstructed,params,out=None, n_bins=12):
if out==None:
import sys
out = sys.stdout
from libtbx.str_utils import format_value
self.params = params
... |
import os
import re
import sys
import shutil
import hashlib
import requests
from uuid import uuid4
from tempfile import mkstemp, mkdtemp
from contextlib import contextmanager
from subprocess import call, check_output, CalledProcessError, STDOUT
from jinja2 import Template, Environment, meta, StrictUndefined, Undefined
... |
'''
The following model is used to indetify between cat and a dog in a picture
The datasets can be found on kaggle and can be replaced in the placeholder location
We shall be using functional programminig to have flexibility in desingning our model .
'''
from keras.preprocessing import image
import matplotl... |
# Copyright (C) 2018 NTT DATA
# 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 ... |
""" This file contains who configures samba server """
from colorama import Fore, Style
from .logic_actions_utils import create_execute_command_remote_bash, execute_command, install, upload_file, delete_file, create_local_user, restart_service, create_local_group, change_fileorfolder_group_owner, add_user2group
def in... |
import math
import torch
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from torch import nn
from torch.nn import Parameter
# import pdb
import numpy as np
class Conv2d_cd(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1, dil... |
import os
from django.shortcuts import render
from django.http import HttpResponseRedirect, JsonResponse
from django import forms
import json
from collections import defaultdict
import requests
HSE_API_ROOT = os.environ.get("HSELING_API_ROOT", "http://hse-api-web/")
# Create your views here.
def web_index(request):... |
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
import gpflow as gp
def _sample_inducing_tensors(sequences, num_inducing, num_levels, increments):
Z = []
sequences_select = sequences[np.random.choice(sequences.shape[0], size=(num_inducing), replace=True)]
for m in rang... |
"""
Description: This script should download the necessary files from the LIT dataset.
If the download process fails, you must resume the download from the file
where you left off.
Author: <NAME> (<EMAIL>)
November 2020
"""
import requests
import os
from os.path import join as pjoin
import s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Run the main server to get images from the android app and translate to cat, anime or other
Usage:
server.py <ip>
Options:
-h --help Show this screen.
<ip> Ip adress of the rabbitmq server
"""
from __future__ import absolute_imp... |
import os
import csv
import json
import time
import requests
import datetime as dt
import pandas as pd
import datetime as dt
from google.cloud import bigquery
from dotenv import load_dotenv
load_dotenv()
STRAVA_CLIENT_ID = os.getenv('STRAVA_CLIENT_ID')
STRAVA_CLIENT_SECRET = os.getenv('STRAVA_CLIENT_SECRET')
STRAVA_T... |
import asyncio
import re
from sqlalchemy.orm import sessionmaker
import SQLModule
import pandas as pd
# [0:'七彩虹',1:'华硕']
# [0:'京东',1:'苏宁']
# [[库存,折扣,来源,品牌,型号,芯片,显存类型,显存容量,风扇,日期#时间戳年月日,是否节假],[库存,折扣,来源,品牌,型号,芯片,显存类型,显存容量,风扇,日期#时间戳年月日,是否节假]]
# [价格,价格]
async def cleanDataBase(Session_class):
session = Session_clas... |
from builtins import range
from functools import reduce
import numpy as np
""" Factor Graph classes forming structure for PGMs
Basic structure is port of MATLAB code by <NAME>
Central difference: nbrs stored as references, not ids
(makes message propagation easier)
Note to self: use %pdb and %load... |
from typing import List, Optional, Type
from django.contrib.auth.models import User
from django.db.models.base import Model
from django_client_framework.permissions.site_permission import has_perms_shortcut
from logging import getLogger
from django.contrib.auth import get_user_model
from django.core.exceptions import ... |
import numpy as np
import tensorflow as tf
imageData = tf.keras.datasets.cifar10
def normalize(data):
data = data.astype('float32')
# Pixel values between 0 and 255
return data / 255.0
(x_train, y_train), (x_test, y_test) = imageData.load_data()
x_train = normalize(x_train)
x_test = normalize(x_test)
... |
"""Core gameplay constructs"""
from __future__ import annotations
import sys
from enum import Enum
from typing import Iterator, NewType, List, Tuple, Optional
__author__ = "<NAME>"
__copyright__ = "<NAME>"
__license__ = "mit"
Player = NewType('Player', int)
Board = List[List[Optional[Player]]]
class GameStatus(En... |
import csv
import json
import cStringIO
import time
import logging
from flask import make_response, request
from flask.ext.restful import abort
from flask_login import current_user
from redash import models, settings, utils
from redash.wsgi import api
from redash.tasks import QueryTask, record_event
from redash.permi... |
# Copyright (c) 2020 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
from chroma_core.models import PowerControlType, PowerControlDevice, PowerControlDeviceOutlet, validate_inet_address
from chroma_api.authentication import AnonymousAuthe... |
# -*- coding: UTF-8 -*-
import math
import operator
import copy
import pickle
"""
================================================================================
决策树
================================================================================
"""
"""
名称: 创建数据集
用法: dataset, labels =... |
import copy
import random
import time
from math import *
from os import mkdir
import wandb
from matplotlib import pyplot as plt
from sklearn.preprocessing import scale
from torch import optim
from two_thinning.full_knowledge.RL.DQN.train import evaluate_q_values_faster, analyse_threshold_progression
from two_thinning... |
import os
import sys
seed_data = 7
lunarc = int(sys.argv[1])
nbr_params = int(sys.argv[2])
data_set = str(sys.argv[3])
seed = int(sys.argv[4])
# remove disp setting
if lunarc == 1 and 'DISPLAY' in os.environ:
del os.environ['DISPLAY']
if lunarc == 1:
os.chdir('/home/samwiq/snpla/seq-posterior-approx-w-nf-de... |
import os
import PIL
from .utils import import_with_auto_install
pgmpy = import_with_auto_install('pgmpy')
from pgmpy.readwrite import BIFReader
from pgmpy.models import BayesianModel
from pgmpy.factors.discrete import TabularCPD
__all__ = ['load_BN']
def load_BN(name, verbose=False):
if name in list(BIF_FOLD... |
# coding: utf-8
"""
State tasks.
Returns a list of validated tasks for the state.
Their concurrent or parallel actions should be
determined by the core that performs them.
State tasks is a list/tuple:
(
task1(target1),
task2(target2),
task3(target3),
...
)
Each task can have a sequence of its own... |
#!/usr/bin/env python
"""
Set geospatial metadata on a Girder item for an OBJ file.
Requires information from 3 files:
- The OBJ file.
- A text file containing 3 lines with floating point values that indicate a
global (x, y, z), offset.
- A reference GeoTIFF image in the AOI from which to get the source coordinate
... |
import requests
import argparse
import time
import logging
import paramiko
import socket
import sys
import warnings
from printy import printy
warnings.filterwarnings(action='ignore',module='.*paramiko.*')
parser = argparse.ArgumentParser()
parser.add_argument('target',help="Set the address of target BBB host")
parser... |
import unittest
import pycurl
import sys
from StringIO import StringIO
import re
class Weburl():
def __init__(self):
self.URL = ""
def get(self, URL, FOLLOWLOCATION = False):
self.URL = URL
buffer = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, URL)
c.setopt(c.W... |
# -*- coding: UTF-8 -*-
import re
type_mapping = {
'NUM': ['TINYINT', 'SMALLINT', 'INTEGER', 'BIGINT', 'BIT', 'DECIMAL', 'DOUBLE', 'FLOAT', 'NUMERIC'],
'BOOLEAN': ['BOOLEAN'],
'DATE': ['DATE', 'TIME', 'TIMESTAMP'],
'STRING': ['CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR', 'LONGNVARCHAR', 'LONGVARCHAR'],
'... |
from . import spec # as in utils/mk-spec.py > mapzen/whosonfirst/placetypes/spec.py
# This is mostly for efficiency of the moment so I don't have to rewrite
# all the code below (20150807/thisisaaronland)
__PLACETYPES__ = {}
__ROLES__ = {}
for id, details in spec.__SPEC__.items():
name = details['name']
rol... |
# Lint as: python3
#
# Copyright 2020 The XLS 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 applicable law... |
import serial
STATUS_ACK = 0
STATUS_LEN_ERROR = 1
STATUS_DATA = 2
def calculate_crc16(buffer):
"""
Calculate the CRC16 value of a buffer. Should match the firmware version
:param buffer: byte array or list of 8 bit integers
:return: a 16 bit unsigned integer crc result
"""
result = 0
for... |
import numpy as np
from uv_data import UVData
from components import ModelImageComponent
from model import Model
from from_fits import create_model_from_fits_file
from utils import mas_to_rad
from stats import LnLikelihood
from spydiff import import_difmap_model
from scipy.optimize import minimize, fmin
# uv_file = '... |
def main():
import argparse
import os
parser = argparse.ArgumentParser(description='')
parser.add_argument('--cutoff', type=str, help='')
parser.add_argument('--prd', type=str, nargs='*', default='S J F O',
help='The CFI initial letter for each product category to be downloa... |
import re
import json
import spacy
import neuralcoref
import pandas as pd
from spacy.matcher import Matcher
from itertools import groupby
class BaseMerger():
def __init__(self, nlp, ent_type, pos='X'):
self.matcher = Matcher(nlp.vocab)
self.ent_type = ent_type
self.pos = pos
def __call__(self, doc):
matches... |
import sys
import requests
import os
import pandas as pd
import csv
import time
from datetime import datetime
from datetime import timedelta
import emoji
import re
if __name__ == "__main__":
if len(sys.argv) != 2:
print('Usage: ExtractTwitterData <Output_data_file_location>', file=sys.stderr)
exit(... |
import csv
import build_dblp_datatsets
FILE_INPUT = "dblp_data/processed_publications.csv"
PUBLICATIONS_PATH = "dblp_data/processed_publications.csv"
def coauthorship_test():
publications = {}
publications["1"] = {"type": "inproceedings", "year": 2018, "number_of_authors": 5,
"author... |
# Copyright 2019 Google LLC. 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 a... |
# import script
import os, re
import string
import random
import rstr
from random import randint
import argparse
import datetime # for random folder name
parser = argparse.ArgumentParser(description="Setup Folder Structure For Testing (c)DatOneDoe 2018 www.datonedoe.com")
parser.add_argument("-r", "--root_dir", metava... |
import operator
import pandas as pd
import sqlalchemy as sa
import ibis
import ibis.common.exceptions as com
import ibis.expr.operations as ops
import ibis.expr.types as ir
from ibis.backends.base.sql.alchemy import (
fixed_arity,
sqlalchemy_operation_registry,
sqlalchemy_window_functions_registry,
un... |
# https://adventofcode.com/2019/day/5
#
# --- Day 2: 1202 Program Alarm ---
#
# --- Day 5: Sunny with a Chance of Asteroids ---
#
def loadintCode(fname='input'):
with open(fname, 'r') as f:
l = list(f.read().split(','))
p = [int(x) for x in l]
return p
def printIndexValue(L, pos=0):
... |
#@title 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, software
# distribu... |
# Copyright (c) 2019 Horizon Robotics. 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 applicab... |
import glob
import math
import os
import random
import shutil
from pathlib import Path
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset
from tqdm import tqdm
class LoadWebcam: # for inference
def __init__(self, img_size=416):
self.cam = cv2.VideoCapture(0)
self.heig... |
import numpy as np
import time
import torch
from matplotlib import pyplot as plt
from unityagents import UnityEnvironment
def get_training_env(env_file_path, test_mode):
"""
Parameters
----------
env_file_path :
test_mode:
Returns
-------
"""
print("\n\n ", test_mode)
env = U... |
import datetime
import os
import aiohttp
import asyncio
import simplematrixbotlib as botlib
from bs4 import BeautifulSoup
import ehapi
config = botlib.Config()
config.join_on_invite = True
creds = botlib.Creds(
os.environ["HOMESERVER"], os.environ["USERNAME"], os.environ["PASSWORD"]
)
bot = botlib.Bot(creds, con... |
import logging
from typing import NamedTuple, Dict, Optional, Iterable, Tuple, List
from src.tree import TreeNode
class NewickParserResult(NamedTuple):
tree_map: Dict[str, TreeNode]
root: TreeNode
class ParserContext:
END_CHAR = ";"
SPECIAL_CHARS = ":,;()"
def __init__(self, data: str):
... |
""" See detailed analysis about maxout via links below:
https://github.com/Duncanswilson/maxout-pytorch/blob/master/maxout_pytorch.ipynb
https://cs231n.github.io/neural-networks-1/
Detailed descriptions about arch of MaxoutConv:
https://github.com/paniabhisek/maxout/blob/master/maxout.json... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
# http://www.apache.org/licenses/LICENSE-2.0
# or in the "license" file... |
import numpy as np
from scipy import stats
import torch
def test(test_loader, encoder, decoder, critic_x):
reconstruction_error = list()
critic_score = list()
y_true = list()
for batch, sample in enumerate(test_loader):
reconstructed_signal = decoder(encoder(sample['signal']))
reconst... |
import visr_bear
import numpy as np
import numpy.testing as npt
from pathlib import Path
import scipy.signal as sig
from utils import data_path
def do_render(renderer, period, objects=None, direct_speakers=None, hoa=None):
not_none = [x for x in [objects, direct_speakers, hoa] if x is not None][0]
length = no... |
"""
References
* https://github.com/marcopeix/Deep_Learning_AI/blob/master/4.Convolutional%20Neural%20Networks/2.Deep%20Convolutional%20Models/Residual%20Networks.ipynb
"""
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, backend, models, utils
from .util... |
from copy import deepcopy
from typing import OrderedDict
import numpy as np
from typing import Tuple, Callable
from GPy.core.mapping import Mapping
from GPy.core.parameterization import priors
from GPy.kern import RBF
from GPy.models.gp_regression import GPRegression
from ..bayes_opt.causal_kernels import CausalRBF
fro... |
from __future__ import division, print_function
import os
import argparse
import configparser
import logging
definitions = [
# model type default help
('model', (str, 'convnet', "Model: convnet")),
('lseg_filters', (list, [16,32,128], "Number of filters in... |
#!/usr/bin/python3
# -*- coding=utf-8 -*-
#本模块由乾颐堂陈家栋编写,用于乾颐盾Python课程!
#QQ: 594284672
#亁颐堂官网www.qytang.com
#乾颐盾课程包括传统网络安全(防火墙,IPS...)与Python语言和黑客渗透课程!
import sys
sys.path.append('/usr/local/lib/python3.4/dist-packages/PyQYT/ExtentionPackages')
sys.path.append('/usr/lib/python3.4/site-packages/PyQYT/ExtentionPackages')
... |
from AccessControl import ClassSecurityInfo
from Products.ATContentTypes.content import schemata
from Products.Archetypes import atapi
from Products.Archetypes.ArchetypeTool import registerType
from Products.CMFCore import permissions
from Products.CMFCore.utils import getToolByName
from bika.lims.browser import Browse... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Contest Management System - http://cms-dev.github.io/
# Copyright © 2010-2012 <NAME> <<EMAIL>>
# Copyright © 2010-2018 <NAME> <<EMAIL>>
# Copyright © 2010-2012 <NAME> <<EMAIL>>
# Copyright © 2012 <NAME> <<EMAIL>>
# Copyright © 2017 <NAME> <<EMAIL>>
#
# This program is fr... |
#!/usr/bin/env python3
import re
import subprocess
import json
import shutil
from urllib.request import Request, urlopen
from urllib.error import URLError
from distutils.version import LooseVersion
from tempfile import TemporaryDirectory
NODE_EXPORTER_INSTALLED_PATH = '/usr/local/bin/'
NODE_EXPORTER_SERVICE_NAME =... |
from django.http import Http404
from django.contrib import admin
from django.contrib.auth import get_user_model
from django import forms
import json
import re
from ..pagination import paginate
from .http import JsonResponse
from .utils import form_to_schema, get_default_value
FORMS = {}
def clean_form_name(form_nam... |
"""Utility script for inspecting and converting ncl color tables."""
import argparse
import glob
import logging
import os
import subprocess
import tempfile
import matplotlib
matplotlib.use("Agg") # noqa
import matplotlib.pyplot as plt
import numpy as np
import yaml
from jinja2 import Template
from esmvaltool.diag_sc... |
## https://github.com/dsmorgan/yacgb
import boto3
import os
from base64 import b64decode
from ssm_cache import SSMParameterGroup
import logging
import random
import datetime
logger = logging.getLogger(__name__)
def decrypt_environ(enc_environ):
e = os.environ[enc_environ]
# Decrypt code should run once and v... |
import json
from collections import defaultdict
from functools import wraps
import flask_restless
from cereal_lazer import Cereal
from flask import Response, abort
from flask.testing import EnvironBuilder
from pbr.version import VersionInfo
from .helpers import ModelConfiguration
from .render import DataModelRenderer... |
from __future__ import absolute_import
import copy
import yaml
import six
class StyleOption(object):
def __init__(self, name, options):
self.name = name
self.options = options
class Style(object):
def __init__(self, base=None, style=None, hidden_base_style=None):
if style is None:
if base... |
INPUTPATH = "input.txt"
#INPUTPATH = "input-test.txt"
with open(INPUTPATH) as ifile:
raw = ifile.read()
from itertools import count
from typing import NamedTuple
from dataclasses import dataclass
from collections.abc import Sequence
class Instruction(NamedTuple): op: str; a: str; b: str | None = None
from typing... |
import math
from IPython import display
from matplotlib import cm
# from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.logging.set_verbosity(tf.logging.ERROR)
pd.o... |
import socket
import datetime
import imutils
import time
import cv2
import pyautogui
def send_cmd(cmd):
s.send(bytes(cmd, 'utf-8'))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 8787
s.connect((host, port))
status_flag = 0
# minimum area size
min_area = 5000
danger_area =30000
... |
"""Implementation of the breakdown. Used to represent multiple layers with
a fixed width.
"""
from typing import Union
import torch.nn
from torch.nn.utils import parametrize
from elasticai.creator.qat.blocks import Conv2d_block
from elasticai.creator.qat.layers import ChannelShuffle
from elasticai.creator.qat.masks i... |
from max_ent.gridworld.gridworld import Directions
from typing import NamedTuple
import numpy as np
from pathlib import Path
import json
from numpy.lib.arraysetops import setdiff1d
from scipy.spatial import distance
import math
from collections import namedtuple
import seaborn as sns
import matplotlib.pyplot as plt
imp... |
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
import psycopg2
import json
def get_json_data(url):
req = Request(url)
while True:
try:
response = urlopen(req)
except HTTPError as e:
#Will retry
continue
brea... |
import os
import sqlite3
from sqlite3 import Error
import PySimpleGUI as sg
from ReaCombiner import data
from ReaCombiner import gui
conn = None
sql_create_projects_table = """ CREATE TABLE projects (
id integer PRIMARY KEY,
project text NOT NU... |
#!/usr/bin/env python
import sys, os
import argparse
import logging
from pathlib import Path
from filterpicker import __version__, __author__, __date__
from filterpicker import filterpicker as FP
# filter_window(s) longterm_window(s) t_up threshold_1 threshold_2 base
fp_par_defaults = [0.20, 1.0, 0.1, 5, 10, 2]... |
"""
This module contains varous helper functions related to color.
"""
import re
# fmt: off
NAMED_COLORS = {
"white": (0xFF, 0xFF, 0xFF),
"silver": (0xC0, 0xC0, 0xC0),
"gray": (0x80, 0x80, 0x80),
"black": (0x00, 0x00, 0x00),
"red": (0xFF, 0x00, 0x00),
"maroon": (0x80, 0x00, 0x00... |
import mmcv
import numpy as np
import torch
from torch.utils.data import Dataset
from openselfsup.utils import build_from_cfg
from torchvision.transforms import Compose
import torchvision.transforms.functional as TF
from .registry import DATASETS, PIPELINES
from .builder import build_datasource
from .utils import to... |
# coding: utf-8
"""
description: General utility functions / methods
author: <NAME>
"""
__all__ = [
'fix_path',
'set_default_cache_dir',
'clear_cache',
'get_catalog',
'load_from_url',
'extract_nonexisting',
'load_artifact',
'generate_random_string',
'make_archive',
'get... |
"""
Module providing typing utilities on top of those from the typing module
"""
from inspect import getattr_static
from typing import Any, Collection, Dict, FrozenSet, List, Literal, Mapping, Set, Tuple, Type, Union
try:
from typing import get_args, get_origin
except ImportError:
# The current Python version... |
from polyglotdb import CorpusContext
from polyglotdb.syllabification.probabilistic import split_ons_coda_prob, split_nonsyllabic_prob, norm_count_dict
from polyglotdb.syllabification.maxonset import split_ons_coda_maxonset, split_nonsyllabic_maxonset
from polyglotdb.syllabification.main import syllabify
def test_fin... |
import os
from io import StringIO
from typing import Union, Optional
import dash_html_components as html
from pangtreebuild.consensus import simple_tree_generator, tree_generator
from pangtreebuild.consensus.cutoffs import MAX2, NODE3
from pangtreebuild.datamodel.DataType import DataType
from pangtreebuild.datamodel.... |
import time
import numpy as np
import pandas as pd
from scipy import sparse
from joblib import Memory
import matplotlib.pyplot as plt
from scipy.stats.mstats import gmean
from alphacsc.cython import _fast_sparse_convolve_multi
from alphacsc.cython import _fast_sparse_convolve_multi_uv
memory = Memory(cachedir='', ve... |
# Copyright 2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
from jupylet.sprite import Sprite as _Sprite
from jupylet.label import Label as _Label
from jupylet.app import App as _App
import numpy as np
from PIL import Image
FPS = 10
_cell = 32
_app = _App(width=28*_cell, height=16*_cell)
_input = {'key_presses': [], 'clicks': []}
_images = []
_sprites = {}
_texts = {}
_ba... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.