text stringlengths 3.07k 22.1k |
|---|
'''
=====
Distributed by: <NAME> SCAI Lab (MIT Liscense)
- Associated publication:
url: http://aimsciences.org//article/id/3a9f3d14-3421-4947-a45f-a9cc74edd097
doi: https://dx.doi.org/10.3934/fods.2020019
github: https://github.com/zabaras/deep-turbulence
=====
'''
from pprint import pprint
from dataclasses import data... |
'''
Boilerplate codes to run several experiments in parallel.
'''
from anchor_sets import KMerChain
from anchor_strat import AnchorStrategy, sequence_mer_iterator
from anchor_sets_bit import CompactKMerChain, load_shared_partial_SA, BitCoverageChecker
from anchor_strat_bit import CompactAnchorStrat
from anchor_ds_v... |
import os
import io
import datetime
import json
import numpy as np
import nextcord
import matplotlib.pyplot as plt
plt.style.use("dark_background")
from requests import Request, Session
from dotenv import load_dotenv
load_dotenv()
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
#################
# API CALL HACK #
######... |
import os
import json
from base64 import b64encode
try:
from urlparse import urlunparse
except ImportError:
from urllib.parse import urlunparse
from azure.storage.blob import PublicAccess, ContentSettings
from azure.common import AzureMissingResourceHttpError, AzureHttpError
from dtoolcore.storagebroker imp... |
import argparse
import json
import sys
import threading
import time
import adafruit_dht
from awscrt import io, mqtt, auth, http, exceptions
from awsiot import mqtt_connection_builder
from getmac import get_mac_address as gma
from gpiozero import LightSensor, MotionSensor, LED
from MQ import MQ
# Author: <NAME>
# V2 ... |
import sys
import numpy as np
import pandas as pd
import json
import time
### Inputs ###
#
# configuration : {
# arguments : { [name:string] : string}
# }
#
# dataStream : {
# data : {
# object: {
# data : {
# Headers : ["tss" , "tse", "input", "param1", ..."paramN"],
# ... |
import math
import re
import random
import itertools
from functools import reduce
from io import StringIO
import ujson as json
from ase.atoms import Atom, Atoms
from ase.io.vasp import read_vasp
from ase.spacegroup import crystal
import spglib
def detect_format(string):
"""
Detect CIF or POSCAR
checkin... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... |
import logging
import random
import time
import sys
import keyring
from datetime import datetime
from microstrategy_api.task_proc.executable_base import ExecutableBase
from microstrategy_api.task_proc.object_type import ObjectSubType
from microstrategy_api.task_proc.status import Status
from microstrategy_api.task_p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SLM Training and Decoding
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import six
import logging
import os
import random
import subprocess
import numpy as np
import torch
import to... |
import os
import httplib2
import json
import requests
import random
import string
from app.helpers.helpers import (normalize, allowed_file, get_user_id,
create_user, get_user_info)
# Import flask dependencies
from flask import session as login_session
from flask import (Blueprint, ren... |
import numpy as np
import pandas as pd
from expand_columns import expand_columns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import RidgeCV, LassoCV, ElasticNetCV
import random
from collections import defaultdict
def chunks(l, n):... |
"""
[summary]
[extended_summary]
"""
# region [Imports]
# * Standard Library Imports ---------------------------------------------------------------------------->
import os
from io import BytesIO
from random import randint
from typing import List, Union
from inspect import getmembers
from datetime import datetime, t... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import torch
import numpy as np
import matplotlib.pyplot as plt
import cv2
import operator
import PIL
import os
import requests
from mpl_toolkits.mplot3d import Axes3D
from PIL import Image
from torchvision import transforms as T
from scratchai import utils
__all__ = ['thresh_img', 'mask_reg', 'mark_pnt_on_img', 'l... |
import numpy as np
import tensorflow as tf
from . import coords
from . import beams as tvbeams
FLOAT_TYPE = tf.float64
COMPLEX_TYPE = tf.complex128
# Define constants
C = 299792458. # speed of light in m/s
freq_ref = tf.constant(100.e6, dtype=FLOAT_TYPE) # Hz
phase_fac = tf.constant(2.*np.pi, dtype=FLOAT_TYPE)
ZERO ... |
from .bitcoin.address import Address
from .bitcoin.helper import TXIN_LIST
from .bitcoin.privkey import Privkey
from .bitcoin.signer import Signer
from .bitcoin.verifier import Verifier
from .dircrawler.datamodder import DataModder
from .dircrawler.filemodder import FileModder
from .utils.commoncmd import CommonCmd as ... |
from app import db, login_manager
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from flask import session
SCRelationship = db.Table('sc_relationship', db.Model.metadata,
db.Column('student_id', db.Integer, db.ForeignKey('students.... |
#!/usr/bin/env python3
from typing import List
from lark import Lark, Transformer
import networkx as nx
import os
from ...utils import untype_string
from .. import Parser
from ...validators import Validator
dm_parser = Lark(open(os.path.join(os.path.dirname(__file__), "grammar.lark"), "r"))
class DotMotifTransfor... |
# vim: sw=4:ts=4:et:cc=120
#
# various utility functions
#
import datetime
import logging
import os, os.path
import re
import saq
from saq.constants import *
import pytz
CIDR_REGEX = re.compile(r'^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(/[0-9]{1,2})?$')
CIDR_WITH_NETMASK_REGEX = re.compile(r'^[0-9]{1,3}\.[0-... |
from tqdm import tqdm
from hashlib import md5
from pathlib import Path
from src.utils.params import (
Tokens,
TokenBasedSpan,
CharBasedSpan,
Label,
)
from typing import Dict, List, Tuple
from flashtext import KeywordProcessor
from logging import getLogger
from .abstract_model import NERModel, NERModelCo... |
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Real time animation of Wythoff construction with pyglet and glsl
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code exported from <NAME>'s excellent shadertoy program at
"https://www.shadertoy.com/view/Md3yRB"
Matt's program ... |
#!/usr/bin/env python3
# (c) University of the Witwatersand, Johannesburg on behalf of the H3ABioinformatics Network Consortium
# 2016-2018
# Licensed under the Creative Commons Attribution 4.0 International Licence.
# See the "LICENSE" file for details
import pandas as pd
import sys
import numpy as np
import glob
i... |
# ##########################################################
# FlatCAM: 2D Post-processing for Manufacturing #
# File Author: <NAME> (c) #
# Date: 09/29/2019 #
# MIT Licence #
# ############################... |
import os
from random import shuffle
import random
import shutil
jex_path = "eurovoc"
config_dir = "config_splits"
classifiers_dir = "classifiers_splits"
results_dir = "results"
SEEDS = [110, 221]
def create_splits(directory):
if not os.path.exists(os.path.join(jex_path, directory, "workspace", "splits")):
... |
from django.urls import reverse_lazy
from django.forms.models import modelformset_factory
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect, render
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django... |
#main.py
from tkinter import*
from tkinter import ttk
from tkinter import messagebox
import os
import cv2 as cv
import numpy as np
from mss import mss
import pyautogui
from enum import Enum
import time
class Checker:
def __init__(self, path, logger, scriptPath = None):
self.m_logger = logge... |
#! /usr/bin/env python
import khmer
import numpy as np
from khmer.khmer_args import optimal_size
import os
import sys
# The following is for ease of development (so I don't need to keep re-installing the tool)
try:
from CMash import MinHash as MH
except ImportError:
try:
import MinHash as MH
except ImportError:
... |
from Core.HookWindow import GetPixelColor, LocateCenterImage, LocateImage
BattlePositions = [0, 0, 0, 0]
PlayersBattlePositions = [0, 0, 0, 0]
MapPositions = [0, 0, 0, 0]
StatsPositions = [0, 0, 0, 0]
GameWindow = [0, 0, 0, 0]
Player = [0, 0]
SQMs = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
SQMsSizes = [0... |
import matplotlib.pyplot
import numpy
def errorize(observation, error):
"""
Adds error to the observation.
:param observation: original observation
:param error: error probability
:return: errored observation
"""
errored = observation
for i in range(len(errored)):
if numpy.rand... |
# Copyright 2021, The TensorFlow Federated 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 o... |
import numpy as np
from ray.rllib.models import ModelCatalog
from ray.rllib.models.tf.misc import get_activation_fn
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.tf.visionnet_v1 import _get_filter_config
from ray.rllib.policy.rnn_sequencing import add_time_dimension
from ray.rllib.utils imp... |
import os.path as osp
import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid, Reddit, PPI
import torch_geometric.transforms as T
from torch_geometric.nn import SplineConv, SAGELafConv, SAGEConvCorrect
import math
import numpy as np
import time
from sklearn.metrics import classificat... |
"""Command Line Interface to opyd objects"""
import time
import functools
import sys
import warnings
from contextlib import contextmanager, closing
from operator import attrgetter
from io import StringIO
import collections
import IPython
from IPython.utils.coloransi import TermColors as tc
from ophyd import (Epics... |
"""
Loss Development
================
"""
import numpy as np
import pandas as pd
import copy
import warnings
from sklearn.base import BaseEstimator, TransformerMixin
from chainladder import WeightedRegression
from chainladder.core import IO
class DevelopmentBase(BaseEstimator, TransformerMixin, IO):
@staticmethod... |
from JumpScale import j
class Domain:
def __init__(self, name, cuisine, serial=1, ttl=None, content="",
max_hosts=2, a_records={}, cname_records={}, ns=[]):
"""
@name = full domain name to be created or to edit
@content = string with json of entire zone file to replace or... |
# <NAME>
# 4/4/2019 / 9/4/2019
import random
# Klasinn Hermann hefur eiginleikana líf, vopn og afl
class Hermann:
def __init__(self, l, v, a): # Skilgreini líf, vopn og afl með smiði
self.lif = l
self.vopn = v
self.afl = a
def __str__(self):
vopn = ""
if self.vopn == ... |
#
# 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 agreed to in writing, software
# ... |
# -- coding: utf-8 --
# Copyright 2018 <NAME> <<EMAIL>>
"""
Helper functions to handle spectras.
"""
def get_substance_peaks(substance, negative=True):
import os
import sqlite3
DB_PATH = os.path.join(os.path.abspath(os.path.join(__file__,"../..")),"data", "elements.db")
conn = sqlite3.connect(DB_PATH... |
from data import load_corpus
from model1a import BERTTrainer
from model1e import BERT1E
from model1f import BERT1F
from bertutil import MyBertTokenizer, PhraseAlignmentDataset, prepare_input_dual, warmup_linear
import numpy as np
from tqdm import tqdm, trange
import os, random, logging, argparse, sys
import torch
from ... |
#!/usr/bin/env python3
from kubernetes import client, config
from tabulate import tabulate
from pathlib import Path
import os
import logging
import coloredlogs
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument(
"--debug", help="enable DEBUG logging mode", default=False, action="st... |
#!/usr/bin/env python3
"""Serialize and deserialize object graphs from/to JSONables."""
import collections
import typing
# yapf: disable
from typing import (
Iterable, List, Mapping, MutableMapping, Optional, Pattern, Set,
Tuple, Union)
# yapf: enable
class Type:
"""Represent a type of mapry values."""
... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 17 17:38:17 2020
@author: wuest
"""
import numpy as np
from timeit import Timer
import copy
class CGR():
"""
Creates a container for CGR coordinates with attributes related to the alphabet of the sequence,
coordinates of alphabet, specifying fo... |
# python
import os
import argparse
import random
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import pickle as pk
# pytorch
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision import datasets
# 3rd-party utils
from torch.utils.tensorboard import... |
import maya.cmds as cmds
import maya.mel as mel
import maya.OpenMaya as om
import rsTools.utils.openMaya.transform as transform
import rsTools.utils.openMaya.deformer as defUtils
import rsTools.utils.transforms.transforms as tUtils
import rsTools.utils.data.string as sUtils
import rsTools.utils.openMaya.matrix as mUtil... |
#!/usr/bin/env python
"""Manage archiving of data."""
import sys
import os
import getpass
import click
from dtool import (
DataSet,
Project,
DtoolTypeError,
NotDtoolObject,
)
from arctool import __version__
from arctool.utils import (
README_SCHEMA,
readme_yml_is_valid,
new_archive_datase... |
import torch
import numpy as np
import torch.nn as nn
import math
import argparse
from torch import optim
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup, track_running_stats=False),
nn.ReLU(inplace=True)
)
def con... |
import discord, asyncio
from core.database import Servers
from core.embeds import Embeds
from core.files import Data
commands = discord.ext.commands
class BumpSetup(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.config = Data("config").yaml_read()
self.settings = Data("settin... |
# Copyright (c) <NAME>.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory.
import ray
import os
import sys
import math
import random
import time
import ctypes as ct
import multiprocessing as mp
from multiprocessing import Process
from numpy.random import Generato... |
# Copyright 2020 The FedLearner Authors. 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 applica... |
## MINE_binary_search.py -- attack a network and update constant c with binary search
##
## author: <NAME>
import sys
import tensorflow as tf
import numpy as np
BINARY_SEARCH_STEPS = 9 # number of times to adjust the constant with binary search
MAX_ITERATIONS = 10000 # number of iterations to perform gradient descen... |
"""
这个文件提供一步一步实现 Canny 边缘检测的代码(仅供学习使用)
使用 CS 131 hw2 的模板
在 demo 中会给出调用库实现的方法
"""
import numpy as np
def conv(image, kernel):
""" An implementation of convolution filter.
This function uses element-wise multiplication and np.sum()
to efficiently compute weighted sum of neighborhood at each
pixel.
... |
"""Utility functions relating to bus creation"""
import logging
import os
import sys
import threading
import weakref
from functools import partial
from typing import Union, Mapping, Type, List, Optional, Callable
from lightbus import Schema
from lightbus.api import ApiRegistry
from lightbus.client.docks.event import E... |
"""A script to perform serious benchmarking of broadcasted ops
Usage: First run pytest and output benchmarked data. Then run this script as main,
to generate results.
1. pytest -k broadcasting_profile --benchmark-autosave --benchmark-json ./output.json -v
2. python test_run_full_broadcasting_profile.py ./output.json
... |
# Creation: Saturday December 5th 2020
# Author: <NAME>
# Contact: <EMAIL>
# <EMAIL>
# --------
# Copyright (c) 2020 <NAME>
import re
import unidecode
from datetime import datetime
def apply_font(message, font="bold"):
"""Change the font of a string text.
Args:
message (str): Message to ch... |
import spacy
from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
import re, os, string
from itertools import permutations, combinations
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from... |
#!/usr/bin/env python3
import numpy as np
import random
import math
from scipy import signal
import imageio
from skimage import segmentation as seg
import matplotlib.pyplot as plt
from PIL import Image
from skimage import transform
from collections import Counter
from scipy import signal, ndimage
from skimage import mo... |
# -*- coding: utf-8 -*-
"""Digital Marketplace Notify integration."""
from typing import Dict, NamedTuple, Optional
import logging
from flask import current_app
from notifications_python_client import NotificationsAPIClient
from notifications_python_client.errors import HTTPError
from dmutils.email.exceptions import... |
import numpy as np
from scipy.linalg import expm
import pymctdh.units as units
from .optools import matel
from .cy.wftools import norm,inner
def lanczos(A, nel, nmodes, nspfs, npbfs, ham, uopips, copips, spfovs, nvecs=5,
return_evecs=True):
"""
"""
# thing to store A tensors
V = np.zeros(n... |
def keep_one_mRNA_with_same_stop_codon_position(f):
output = []
nameset = set()
with open(f, 'r') as FILE:
for line in FILE:
if line[0] == '#':
output.append(line.strip())
else:
s = line.strip().split('\t')
if s[6] ==... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
from threading import Lock
from Utils import Utils
try:
from NaptListener import NaptListener
from NaptListener2 import NaptListener2
from NaptRelay import NaptRelay
from NaptConnection import NaptConnection... |
import json
import discord
from discord.ext import commands
from ext.config import save_config, check_config
from ext.confirmer import ConfirmerSession
bot = commands.Bot('')
pronouns_list = ['❤️ he ❤️', '🧡 him 🧡', '💛 she 💛', '💚 her 💚', '💙 they 💙',
'💜 them 💜', '🖤 it 🖤', '🤍 its 🤍', '🤎 an... |
# -*- coding: utf-8 -*-
__author__ = 'fyabc'
# Standard libraries.
from copy import deepcopy
from functools import partial
# Dependent libraries.
import pygame
# Local modules.
from config.gameConfig import CELL_SIZE, AllColors, FPS_MAIN, GAME_SCREEN_SIZE
from shift.utils.basicUtils import hitTestByDistance
from shi... |
# master_controller.py
# aspireDb master storage controller
# The Concept of a master in this usecase is a mutable directory that contains
# one index.json file that keeps a record of new and deleted directories from the
# master directory
#---------------------------- DEPENDENTS -----------------------------------... |
import os
import datetime
import numpy as np
from tqdm import tqdm
from osgeo import gdal
import sys
sys.path.append('.')
from core.utils.data_utils.image_io_utils import load_image, get_image_info, save_to_image_gdal, save_to_image
from core.utils.vis_utils import plot_segmentation
from core.configures import COLOR_M... |
""" Extract pose from the PIPA dataset
"""
from __future__ import print_function
from __future__ import division
import numpy as np
import cPickle as pickle
import skimage.io
import skimage.transform
import cv2
import tensorflow as tf
import sys
sys.path.append('.')
from CPM import cpm
import PIPA_db
import argparse... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, os.path
import re
import sys
import tarfile
import copy
import sys
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '4'
import textwrap
import numpy as n... |
"""
Implementation of a labeled property graph.
"""
# ===================================
# TODO: Number of relationships a node has
# TODO: Number of nodes that have a given relationship
# TODO: Number of nodes with a relationship
# TODO: Number of nodes with a label
# TODO: Traversals:
# - Depth first
# - Breadth-fi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
"""
Alexa Devices Sensors.
For more details about this platform, please refer to the documentation at
https://community.home-assistant.io/t/echo-devices-alexa-as-media-player-testers-needed/58639
"""
import datetime
import logging
fro... |
#!/usr/bin/env python
"""
Client to communicate with RabbitMQ and extension of
Population which add parallel computing capabilities.
"""
import json
import pika
import queue
import threading
import time
import uuid
import ast
from .populations import Population, Flock,GridPopulation
import pymongo
db_client=pymongo.Mo... |
# -*- coding: utf-8 -*-
import os
import time
from auger_cli.utils import request_list, download_remote_file, wait_for_object_state
from auger_cli.constants import REQUEST_LIMIT
from auger_cli.api import clusters
from auger_cli.api import orgs
from auger_cli.api import cluster_tasks
from auger_cli.api import experim... |
from flask import Flask,redirect, url_for, request
from random import *
import time
from .. import Application
from .. import Profit_Calculator
from .. import Risk_Calculator
from operator import add
from functools import reduce
import csv
def initialize():
global min_higher_line_rsi
global max_higher_line_rs... |
from random import choice
from emoji import add_emoji
bot_name = "Walkie"
def unkown():
response = [
"...",
"Uhm...",
"Uhh...",
"Could you re-phrase that?",
"Could you say that again, but like... differently?",
"I don't really understand what you're saying.",
... |
import os
import sys
import time
import re
import logging
import traceback
import argparse
from yaml import full_load, dump
DEFUALT_DEPLOY_MODE = "single"
IDC_NAS_URL = "//172.16.70.249/test"
MINIO_HOST = "minio-test.qa.svc.cluster.local"
def parse_server_tag(server_tag):
# tag format: "8c"/"8c16m"/"8c16m1g"
... |
# -*- coding: utf-8 -*-
"""
FHWwallDesignSCR
This script finds the value of the force required to mantain stability of a
slope (Preqd), maximizing the failure surface's angle (alpha) and the d/H
relation (xi). Additionally, calculates the safety factor of the sliding
wedge that was found by the FHWA's simplified meth... |
from tkinter import *
from tkinter import scrolledtext
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter
import serial
import threading
import time
import os
def displayInfo():
j=... |
"""Module to facilitate a generic interface to running long tasks in separate
threads.
"""
# Copyright 2018 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apach... |
from asist.utility import power_spectrum
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.signal import detrend
from scipy.stats import beta
from sustain_drag_2020.irgason import read_irgason_from_toa5, rotate
from sustain_drag_2020.udm import re... |
"""
evaluate.py
~~~~~~~
Functions for evaluating drifting detection and report classification results.
"""
import os
os.environ['PYTHONHASHSEED'] = '0'
from numpy.random import seed
import random
random.seed(1)
seed(1)
from tensorflow import set_random_seed
set_random_seed(2)
import sys
import logging
import copy
i... |
from flask_unchained.string_utils import snake_case
from sqlalchemy import func as sa_func, types as sa_types
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import RelationshipProperty
from ..sqla.column import Column
from ..sqla.relationships import foreign_key
from ..sqla.types import BigIn... |
#!/usr/bin/env python
import argparse
import os
import time
from datetime import datetime
from os.path import expanduser, join
import sys
import cv2
import numpy as np
from rpiv2 import Camera
from jetbot import Robot
import pyzbar.pyzbar as pyzbar
from enum import Enum
class QRCodeDetector(Enum):
ZBAR = 1
OPE... |
"""
Declaration module (internal)
This module contains some tools used for extracting information out of
function and type declarations.
TODO: Implement parsers for some of the C++ symbol manglers in order to
query them for specific attributes or type information.
"""
import function as fn, database as db
impo... |
###############################################################################
# TODO: remove this block once https://github.com/bluesky/ophyd/pull/959 is
# merged/released.
from datetime import datetime
from ophyd.signal import EpicsSignalBase, EpicsSignal, DEFAULT_CONNECTION_TIMEOUT
def print_now():
return date... |
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.pipeline import Pipeline
from sklearn.externals import joblib
from nltk import WordNetLemmatizer
from nltk.corpus import stopwords as sw
from nltk.corpus import wordn... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2019, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2019. UChicago Argonne, LLC. This... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
def __init__(self, latent_dim, img_shape):
super(Encoder, self).__init__()
self.img_shape = img_shape
def block(in_feat, out_feat, normalize=True):
layers = [nn.Lin... |
# ===============================================================================
# Copyright 2012 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LI... |
from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union, cast
from cache import volatile_cache
from constants import creep_base_full_upgrader, rmem_key_planned_role_to_spawn, role_builder, role_hauler, \
role_spawn_fill, role_upgrader, roleobj_key_base, roleobj_key_num_sections, roleobj_key_role, target... |
# -*- coding: utf-8 -*-
from grafo import Grafo
from grupo import Grupo
import time
# método de ordenação quick-sort, utilizado para ordenar as arestas em forma decrescente
def quickSortAux(vetor, esquerda, direita):
i = esquerda
j = direita
pivo = vetor[int((j + i) / 2)][2]
while i <= j:
whil... |
# -*- coding: utf-8 -*-
"""The sub module of slogviz, that parses log files and returns logfileclasses.logfile objects.
Exported functions:
readin(file) -- Reads in a file and returns a logfileclasses.logfile object.
"""
import platform
import re
import datetime
import time
import json
import sqlite3 as lite
import ... |
from csv import *
from random import randint
from termcolor import colored, cprint
def isPrime(numberUpTo):
"""<NAME>
This will see whether it is prime or not
Input- Number to check
Output- Whether it is prime True or False"""
if numberUpTo == 0: #1 and 0 will come... |
#!/usr/bin/env python
import csv
from datetime import datetime
from collections import defaultdict, namedtuple
debug = False
def parse_table_version(fname):
# Filenames need to look like path/blah/UserTable_MRMS_v<version>.csv
return fname.split('S_v', 1)[1].replace('.csv', '')
def parse_file(fname):
tab... |
import torch
import numpy as np
import random
import utils.dlc_practical_prologue as prologue
from torch.utils.data import Dataset, DataLoader
def load():
'''Load the data in the format required by the project from the prologue file given
Returns : tuple
tuple[0]: train
tupl... |
import os
import discord
from keep_alive import keep_alive
from replit import db
import datetime
import smtplib
import random
import hashlib
my_secret = os.environ['TOKEN']
client = discord.Client()
greetings = [
['Bonjour ', 'French'],
['Zdravstvuyte ', 'Russian'],
['Nǐn hǎo ', 'Chinese'],
['Hi ', 'English... |
def test_either_do():
from category import Either, EitherDo, Left, Right
@Either.do
def left_context() -> EitherDo[Exception, int]:
one = yield from Right[Exception, int](1)()
two = 2
three = yield from Left[Exception, int](Exception())()
return one + two + three
assert... |
import asyncio
from unittest import mock
import pytest
from multidict import CIMultiDict, CIMultiDictProxy
from yarl import URL
import aiohttp
from aiohttp import web, web_reqrep
from aiohttp.test_utils import TestClient as _TestClient
from aiohttp.test_utils import TestServer as _TestServer
from aiohttp.test_utils i... |
#!/usr/bin/env python
# coding: utf-8
# DWD_hist_weather.py
#
# (c) 2021 <NAME>
#
# Dieses Modul importiert Daten aus dem umfangreichen OpenData-Angebot
# des Deutschen Wetterdienstes (DWD) in ein Pandas-Dataframe.
#
# Regionalität
#
# Die Auswahl der Wetterstationen erfolgt hier nach Bundesländern. Auf
# Grundlage de... |
import os
import struct
import logging
import threading
import collections
import synapse.glob as s_glob
import synapse.common as s_common
import synapse.eventbus as s_eventbus
import synapse.lib.atomic as s_atomic
import synapse.lib.config as s_config
import synapse.lib.msgpack as s_msgpack
import synapse.lib.atomfi... |
import concurrent
import contextlib
import itertools
import logging
import os
import pickle
import statistics
import time
from abc import ABC, abstractmethod
from functools import wraps
import math
import numpy as np
import scipy.fft as fft
import torch
from pyinsect.collector.NGramGraphCollector import (
ArrayGra... |
from talon.voice import Word, Context, Key, Rep, RepPhrase, Str, press
from talon import app, ctrl, clip, ui
from talon_init import TALON_HOME, TALON_PLUGINS, TALON_USER
import string
import time
from .utils import parse_word, surround, text, sentence_text, word, parse_words, spoken_text, select_last_insert, insert
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.