text stringlengths 3.07k 12.6k |
|---|
from torchdyn.numerics import odeint, Euler, HyperEuler
import torch
import torch.nn as nn
from dicts import *
import matplotlib.pyplot as plt
class TimoshenkoBeam(nn.Module):
"""
Linear discretization of a high-dimensional Timoshenko Beam
x_dot = Ax + Bu
"""
def __init__(self, A, B, u):
s... |
#!/usr/bin/env python3
import cv2
# from cv2 import aruco
from tqdm import trange
import numpy as np
import os, os.path
from glob import glob
from collections import defaultdict
import pandas as pd
## TODO: rewrite this whole file with aniposelib
from .common import \
get_calibration_board, get_board_type, \
... |
#!/usr/bin/env python3
import requests
import json
import os
import consul
import smtplib
import argparse
from time import sleep
from email.message import EmailMessage
# Default var's values
log_file = '/var/log/consul-alert-manager.log'
smtp_host = 'localhost'
smtp_sender = 'alert-manager@localhost'
smtp_reciever ... |
__author__ = 'jparedes'
from itertools import compress, chain
from numpy import tile, spacing, array
from .similarity_filter import splitListFromSizes
def get_CD(P, C):
"""
Calculation of Confidence Degree
:param P: Matrix of uX
:param C: Binary classes
:return: CD matrix <[number of premises, n... |
import yaml
from glob import glob
from serialization import pprint
from serialization import serialize_to_mp, fetch_or_fail, is_eq, deserialize_loc, serialize_loc
from serialization import (
__SOURCES,
__EXCEL_FILE,
__TYPE,
__ENTITIES,
__PATH,
__DEPS,
__CELL_SOURCES,
__CELL,
__DYNAM... |
#
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyri... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
######################################################################
#
# create_ipa_mapping.py
#
# Given two IPA inventories in JSON (either as dedicated inventory
# files or the input/output sides of mapping files), map the first
# onto the second by use of panphon's p... |
import pandas as pd
from utils.Course import Course
import discord
import xml.etree.ElementTree as ET
import urllib
from urllib.request import urlopen
import traceback
classes_offered = pd.read_csv('data/2020-fa.csv')
classes_offered['Class'] = classes_offered['Subject'] + classes_offered['Number'].astype(str)
class_g... |
"""This module contains data structures for role assignment."""
from enum import IntEnum
from typing import Optional, Protocol
import stp.rc as rc
BIG_STUPID_NUMBER_CONST_FOR_UNASSIGNED_COST_PLS_CHANGE = 9999
class Role:
"""This represents a role, ie. an Optional[rc.Robot]."""
__slots__ = ["robot"]
ro... |
import stanpy as stp
import numpy as np
# todo: define classes, parametrization
def test_gamma_K_function():
EI = 32000 # kNm²
GA = 20000 # kNm²
l = 6 # m
H = 10 # kN
q = 4 # kN/m
N = -1500 # kN
w_0 = 0.03 # m
s = {
"EI": EI,
"GA": GA,
"l": l,
"... |
#!/usr/bin/env python3
#
###############################################################################
# Original Author: <NAME> (http://orcid.org/0000-0001-6497-753X), #
# CIEMAT - Sci-Track Group (http://rdgroups.ciemat.es/web/sci-track),#
# for the EOSC-Synergy project (EU H2020 RI Grant No 85764... |
#!/usr/bin/env python
"""
s3-mix topology
"""
from mininet.cli import CLI
from mininet.net import Mininet
from mininet.topo import Topo
from mininet.node import Node
from mininet.log import setLogLevel, info
from utils import IP, MAC, NETMASK
from utils import IP_SWAT, MAC_SWAT, NETMASK_SWAT
from subprocess import ... |
# Public utility functions and classes. Implement commonly used constants, mathematical functions, etc
import math
import sys
import numpy as np
class PeriodicTable:
def __init__(self):
self.elements = "M H He "\
"Li Be B C N O F Ne "\
"Na Mg Al Si P S Cl Ar "\
"K Ca Sc Ti V Cr Mn F... |
"""
Module for running ARIMA on players
"""
import time
import streamlit as st
import numpy as np
import pandas as pd
import pmdarima as pm
from sklearn.preprocessing import PowerTransformer
def calculate_errors(residuals):
""" Calculates errors based on residuals """
num_residuals = len(residuals)
mfe = (... |
#!/usr/bin/env python
'''finding syntactic and semantic heads. after Johnson heads.h and heads.cc'''
## needs heavy annotation -- esp. left/right head-finding.
import sys
import copy
#from tree import Tree
logs = sys.stderr
from delNoneOfTree.utility import aset, is_punc
SEM = 0
SYN = 1
headtables = { SEM: None,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import stat
import pathlib as pl
from teixml2lib import template_html_prj
import json
__date__ = "31-03-2021"
__version__ = "0.1.3"
__author__ = "<NAME>"
help = """
prjmgr.py prj/<prj.json>
witness_removelog.json
witness_xml.json
witness_syn.json
wit... |
import csv
import re
import argparse
import sys
# Authors: <NAME>, <NAME>
# Date: 1/15/2021
#Revised by <NAME> and <NAME>
class Books:
def __init__(self, title, authors, year):
self.title= title
self.authors = authors
self.year = year
def swap_list_elements(array, index1, index2):
tem... |
"""
Functions relating to Eularian graphs.
This module contains functions relating to the identification
and solution of Eularian trails and Circuits.
"""
import copy
import itertools
import random
import sys
from time import clock
from . import dijkstra, my_math
from .my_iter import all_unique, flatten_tuples
def ... |
#! /usr/bin/env python
#! -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.metrics import accuracy_score, classification_report
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVC
# from sklearn.cross_validation import train_te... |
from datetime import datetime, timedelta
from nose.tools import eq_
from mock import Mock, patch
import amo
import amo.tests
from addons.models import Addon
from users.models import UserProfile
from devhub.models import ActivityLog
from mkt.developers.models import (AddonPaymentAccount, CantCancel,
... |
# Copyright 2014-2016 Insight Software Consortium.
# Copyright 2004-2008 <NAME>.
# Distributed under the Boost Software License, Version 1.0.
# See http://www.boost.org/LICENSE_1_0.txt
import os
import unittest
import platform
import autoconfig
import parser_test_case
from pygccxml import utils
from pygccxml import p... |
import polars as pl
from polars import testing
def test_list_arr_get() -> None:
a = pl.Series("a", [[1, 2, 3], [4, 5], [6, 7, 8, 9]])
out = a.arr.get(0)
expected = pl.Series("a", [1, 4, 6])
testing.assert_series_equal(out, expected)
out = a.arr.first()
testing.assert_series_equal(out, expected... |
'''SMB protocol command-line tools
'''
# import gevent.monkey; gevent.monkey.patch_all()
from pathlib import Path
import logging
import pprint
import click
from .. import toolz as _
from .. import (
parallel, shell, logging, smb,
)
from . import common
log = logging.new_log(__name__)
@click.command()
@common.in... |
import textwrap
import json
import time
import logging
import sys
from jumpscale import j
logger = logging.getLogger('g8core')
class JobNotFoundError(Exception):
pass
class ResultError(RuntimeError):
def __init__(self, msg, code=0):
super().__init__(msg)
self._message = msg
self.... |
from shape import Shape2D
from pyglet.gl import *
## Documentation for Button and OnOffButton
# @brief Module for creating Button and OnOffButton
class Button(object):
## @brief Button module
# @details Create a button with specified position, sizes, text, color, and functions
def __init__(self,x,y,width,heig... |
# -*- coding: utf-8 -*-
import numpy as np
"""This class enables operator overloading for turning python equations into
strings for the .apm model. Each variable type inherits this class. Operations
done on an instance of this class return a new instance to enable chained
operations."""
class GK_Operators:
""""""... |
'''
This module contains SessionMixin, which can be used in RequestHandlers, and
SessionManager, which is the real session manager, and is referenced by the
SessionMixin.
It's mandatory that you set the "cookie_secret" in your application settings,
because the session ID is stored in a secure manner. It's also mandato... |
#############################################
# Created by <NAME> (github : @christiandimaio)
# starting from the code of Professor <NAME>
# v 0.1
from enum import Enum
from math import sqrt
from Model import geolocator
from geopy.distance import geodesic
import logging
class CityDataType(Enum):
Geographical = 1
... |
#!/usr/bin/env python
# coding: utf-8
# 同样使用RNN,本节的改进如下
#
# * 预训练的词向量
# * 不同的RNN结构(LSTM)
# * 多层RNN
# * 正则化
# * 不同的优化器
# ---
# ## 1. 数据准备
#
# 通过预训练词向量初始化每个词
# In[3]:
import torch
from torchtext import data, datasets
import random
import time
SEED = 1234
begin_t = time.time()
torch.manual_seed(SEED)
torch.cuda.... |
__all__ = ['build_timeline_db',
'plot_time_schedule',]
def plot_time_schedule(path_suivi_module, path_time_schedule):
'''Plots time schedule of modules under experiment.
'''
# Standard library import
import datetime
import re
# 3rd party imports
import pandas as pd
... |
# 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.
import os
from typing import Any, Dict
from fairseq import checkpoint_utils
from fairseq.data.legacy.masked_lm_dictionary import MaskedLMDict... |
import os
import ssl
from contextlib import contextmanager
import aiohttp
from pynaja.common.async_base import AsyncCirculatorForSecond, Utils
DEFAULT_TIMEOUT = aiohttp.client.ClientTimeout(total=60, connect=10, sock_read=60, sock_connect=10)
DOWNLOAD_TIMEOUT = aiohttp.client.ClientTimeout(total=600, connect=10, soc... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 16 23:03:51 2017
@author: Christian
"""
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matpl... |
from django.db import models
from django.urls import reverse
from django.conf import settings
from utilties import ChoiceList
from datetime import date
#from . import
# Create your models here.
class Cat(models.Model):
"""猫猫的数据库模型"""
BIRTH_MONTH_CHOICES = ChoiceList([f'{i+1}' for i in range(12)], '春天', '夏天'... |
from typing import Optional
import torch
import torch.nn as nn
from torch.nn import Parameter
from torch.nn import init
import torch.nn.functional as F
import xxhash
import math
import numpy as np
def getMaxNumOfUniqueValue():
max_len = 0
for idx in range(26):
fea_dict = np.load('./input/train_fea_dict... |
import math
import enum
import dataclasses
import collections
from typing import List, Callable, Any, NewType, Union, Iterable, Type
class NatureBuyOrSell(enum.Enum):
buy = enum.auto()
sell = enum.auto()
class CurrencyEnumIdx0(enum.Enum):
"""automatic enum structure that starts with index = 0 """
d... |
"""GSSAPI linebased client/server protocol.
#
# Usage:
#
# Server:
#
# class Echo(gssapiprotocol.GSSAPILineServer):
# def got_line(self, line):
# self.write('echo: ' + line)
#
# class EchoFactory(protocol.Factory):
# def buildProtocol(self, addr): # pylint: disable=C0103
# ... |
from igia.utils import iterline, Bed12
import sys
import argparse
import numpy as np
from bx.intervals.cluster import ClusterTree
from bx.intervals.intersection import IntervalTree
class Cluster(object):
""" Gene cluster """
def __init__(self, cluster_name):
self.name = cluster_name
self.gene_... |
"""
Metric helpers. Adapted from scikit-plot
"""
import numpy as np
from sklearn.preprocessing import LabelEncoder
def cumulative_gain_curve(y_true, y_score, pos_label=None):
"""This function generates the points necessary to plot the Cumulative Gain
Note: This implementation is restricted to the binary class... |
'''
Copyright (c) 2016-2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, s... |
import threading as threading
import sys, time, os, re
import pandas as pd
import xlsxwriter, glob
start_time = time.time()
from modules.main import ArgParse
from modules.logging import Logger
from modules.output import Output
from modules import process as k8s
from modules.load_kube_config import kubeConfig
kubeConfi... |
# pylint: disable=broad-except,logging-fstring-interpolation,logging-not-lazy, dangerous-default-value
"""
File-underlied 2- and 3-value buttones with hardware buttons and LEDs
"""
from sys import stderr
import sys
import logging
from time import sleep
from pathlib import Path
from datetime import timedelta
from _datet... |
# Copyright 2020 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 os
import pandas as pd
import random
import torch
from torch.utils.data import DataLoader
from datasets import Dataset
from mt.trainer.tok.word_tokenizer import WordTokenizer
from mt.trainer.tok.lit_tokenizer import LitTokenizer
from mt.trainer.tok.fastbpe_tokenizer import FastBPETokenizer
from tqdm import tq... |
"""
Plot a deformation mechanism map of quartz.
X-Axis: Homologous temperatures, from 0.2 to 1.0.
Y-Axis: Log10(Theta/Mu) (normalized sheer stress) from 0 to -6.
Z-Axis/Contour: Strain rate from 10^-6 to 10^-15.
"""
import matplotlib.pyplot as plt
from matplotlib import ticker as mticker
from matplotlib import cm
imp... |
from . import fast_ffts
import numpy as np
def fourier_interp1d(data, out_x, data_x=None, nthreads=1, use_numpy_fft=False,
return_real=True):
"""
Use the fourier scaling theorem to interpolate (or extrapolate, without
raising any exceptions) data.
Parameters
----------
dat... |
# Copyright (c) 2018 UAVCAN Consortium
# This software is distributed under the terms of the MIT License.
# Author: <NAME> <<EMAIL>>
# pylint: disable=protected-access
import abc
import typing
import operator
import fractions
import unicodedata
from . import _any
# noinspection PyAbstractClass
class Primitive(_any.... |
""" Given data files in standard format, subsample them by first subsampling surface-mention groups.
This implements the sampling strategy from Mayhew 19 "NER with Partially Annotated Training Data".
In our paper this is called "Non-native Speaker" (NNS) annotation
We do this by first downsampling via surface mention... |
import os
import os.path
import os.path
import schema
import sargasso.separator.options as opts
from sargasso.filter import hits_manager, hits_checker
from sargasso.separator.commandline_parser import CommandlineParser
from sargasso.separator.parameter_validator import ParameterValidator
from sargasso.utils import log... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=import-error,print-statement,relative-import,protected-access
"""Unit tests for name_style_converter.py."""
import unittest
from name_st... |
# -*- coding: utf-8 -*-
import argparse
from pyscaffold.api import Extension, helpers
from pyscaffold.extensions.no_skeleton import NoSkeleton
from pyscaffold.extensions.pre_commit import PreCommit
from pyscaffoldext.markdown.extension import MarkDown
from . import templates
class IncludeExtensions(argparse.Action... |
import os
import bpy
import bpy_extras
import bmesh
import math
from mathutils import Vector, Matrix, Quaternion
from bpy.props import StringProperty, BoolProperty, FloatProperty
from ..utils.utils import get_data_path
from ..rsm.reader import RsmReader
class RsmImportOptions(object):
def __init__(self, should_im... |
from flask import session, request, redirect, url_for, flash, Flask, render_template, render_template_string, Response
from app import app, ALLOWED_EXTENSIONS
import mediapipe as mp
import pandas as pd
import os
import cv2
from werkzeug.utils import secure_filename
from PIL import Image
from src.posture_bois.utils.get_... |
#!/usr/bin/python
"""Mpesa rest API client.
This exposes various mpesa functionalities to developers.
All class functions take in keyword arguments (kwargs) and
response returned is a response object from (python requests).
From this object you can retrieve the response parameters
as text or json.
"""
import base64... |
#!/usr/bin/env python3
import sys
import argparse
parser = argparse.ArgumentParser(description='Merge the segmented, classified plants from each overlapping image together.')
parser.add_argument(
"ortho", help="the path to the orthomosaic"
)
parser.add_argument(
"segments", help="the path to a directory contai... |
'''
train mdn-rnn from pre-processed data.
also save 1000 initial mu and logvar, for generative experiments (not related to training).
'''
import numpy as np
import os
import json
import tensorflow as tf
import random
import time
from vae.vae import ConvVAE, reset_graph
from rnn.rnn import HyperParams, MDNRNN
os.env... |
from __future__ import absolute_import, division, print_function
import numpy as np
from toolz import concatv, drop, interleave
class SimplexPoint(object):
__slots__ = ('stencil', 'stepsize', 'halvings', 'index', 'is_reflect',
'is_doubled', 'simplex_key', 'point_key', 'point')
def __init__(... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import style
from sklearn.preprocessing import StandardScaler,RobustScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report,confusion_matrix
from sklearn.me... |
import json
import os
import pprint
import sys
import warnings
from collections import OrderedDict
from collections.abc import Mapping
import yaml
class OrderedEasyDict(OrderedDict):
def __init__(self, input_dict=None, **kwargs):
"""
EasyDict that remembers the order
:param input_dict: ... |
from azul.chalice import (
AzulChaliceApp,
)
from azul.openapi import (
params,
schema,
)
from azul_test_case import (
AzulUnitTestCase,
)
class TestAppSpecs(AzulUnitTestCase):
def test_top_level_spec(self):
spec = {'foo': 'bar'}
app = AzulChaliceApp('testing', spec=spec)
... |
#!/usr/bin/env python3
import sys
import os
import requests
import time
import const
from os.path import isdir, join
source_dir = sys.argv[1]
target_dir = sys.argv[2]
frequency = "forever"
if len(sys.argv) > 3:
frequency = sys.argv[3]
SYNC_INTERVAL_SECONDS = 5
V1_PREFIX = "spark-"
V2_PREFIX = "eventlog_v2_"
pr... |
from sklearn import datasets as ds
from DSTK.GAM.gam import GAM, ShapeFunction
from DSTK.tests.tests_gam.test_shape_function import _create_partition
from DSTK.GAM.base_gam import load_from_tar
import numpy as np
import os
import shutil
cancer_ds = ds.load_breast_cancer()
data = cancer_ds['data'][:, :20]
labels = 2 *... |
import os
import numpy as np
import tensorflow as tf
from pycocotools.coco import COCO
from sklearn.preprocessing import OneHotEncoder
from sklearn.utils import shuffle
class GetDataIndex:
def __init__(self, label_folder, data_type, img_size, grid_size):
self.label_folder = label_folder
self.dat... |
# 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 agreed to in... |
#!/usr/bin/env python3
import pyglet
from pyglet.window import key
import asyncio
import json
import sys
import itertools
from snake import *
# get a handle to the asyncio event loop
loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()
# define the world
class World:
"""
Keeps track of all of the ... |
# Copyright 2020 Red Hat, Inc.
# 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, s... |
from __future__ import absolute_import
from copy import copy
import logging
from multiprocessing import Process, Queue, Event
from Queue import Empty
import time
from kafka.client import KafkaClient, FetchRequest, ProduceRequest
log = logging.getLogger("kafka")
raise NotImplementedError("Still need to refactor this... |
from __future__ import annotations
from functools import partial
from typing import Hashable, Tuple, List, Union, Optional
import numpy as np
import dask.array as da
import xarray as xr
def _mosaic_base(
arr: np.ndarray,
axis: int,
*,
reverse: bool,
nodata: Union[int, float],
keepdims: bool ... |
import numpy as np
import salem
from combine2d.core.data_logging import load_pickle
from combine2d.core.arithmetics import mean_BIAS, RMSE
from combine2d.core.data_logging import DataLogger
def create_case_table(gdir):
header = 'case,ela,mbgrad,zmax,sca,dx,V,A,hmean,hmax,coordinates\n'
row = '{case:s},{ela_h:d... |
import serial
import time
import numpy as np
from GTac_Data import gtac_data
# import pandas as pd
def data_to_list(data_str):
data_list = [int(idx) for idx in data_str.split(' ')]
return data_list
def data_checkout(ser, n_trunck):
# Input:
# Output: datatype is list
data = [] # 5*4
mxl_rows... |
import contextlib
import os
import sys
import unittest
import unittest.mock as mock
from configparser import NoOptionError
from io import StringIO
import yt.config
import yt.utilities.command_line
from yt.config import _OLD_CONFIG_FILE, CONFIG_DIR, CURRENT_CONFIG_FILE, YTConfigParser
from yt.fields.tests.test_fields_p... |
import json
import os
import pytest
import time
from oidcmsg.key_jar import build_keyjar
from oidcmsg.oidc import AccessTokenRequest
from oidcmsg.oidc import AuthorizationRequest
from oidcendpoint.oidc import userinfo
from oidcendpoint.client_authn import verify_client
from oidcendpoint.oidc.authorization import Aut... |
import requests
import os
import io
import pandas as pd
from datetime import date, timedelta
def creat_folder(folder_name, subfolder_name):
if not os.path.exists(folder_name):
os.makedirs(folder_name)
if not os.path.exists(os.path.join(folder_name, subfolder_name)):
os.makedirs(os.p... |
import copy
from reedsolo import RSCodec, ReedSolomonError
from Chamaeleo.methods.default import AbstractErrorCorrectionCode
class Hamming(AbstractErrorCorrectionCode):
def __init__(self, need_logs=False):
super().__init__(need_logs)
def insert_one(self, input_list):
# calculate the length... |
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
import pickle
from sklearn.metrics import precision_score, recall_score
def pretty_print(*values):
col_width = 13
def format_val(v):
if not isinstance(v, str):
... |
'''Makes gui for password generator'''
try:
import password_generator as generator
IMPORT_CORRECTLY = True
except BaseException:
IMPORT_CORRECTLY = False
from tkinter import Tk, Frame, StringVar, IntVar, Label
from tkinter import Entry, Checkbutton, Button, Menu, TclError
class Application(Frame):
'... |
"""
Fuctions for a process to simulate an alpha.
"""
import argparse
import copy
import importlib
import json
import os
import pickle
from multiprocessing import Process, Queue
import pandas
from thousandaire.constants import DATA_LIST_ALL, OFFICIAL_CURRENCY
from thousandaire.constants import TRADING_CONFIGS
from thou... |
from __future__ import print_function
from __future__ import absolute_import
from .datasource import DataSource
from .det_interface import DetNames
class Step(object):
"""
An object that represents a set of events within
a run taken under identical conditions (also known
as a `calib-cycle`.
"""
... |
from django.views import generic
from django.http import HttpResponse
from django.core import serializers
from gallery.models import Publisher, Post
from gallery import choices
import json
from django.utils import timezone
from datetime import timedelta
from datetime import datetime
class DataVisualisationView(generic... |
import json
import csv
import IPython
import os
import datetime
def flatten_json(json_dict, delim='.'):
flat_json = {}
for i in json_dict.keys():
if isinstance(json_dict[i], dict):
get = flatten_json(json_dict[i], delim)
for j in get.keys():
flat_json[i + delim ... |
#!/Path/to/python
# Flask imports
from flask import Flask, render_template, flash, request, redirect
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from wtforms.widgets import TextArea
#Scientific Computing Package Imports
import pandas as pd
import numpy as np
import scipy
i... |
import numpy as np
from keras.callbacks import TensorBoard
import tensorflow as tf
from .pacman_agent import PacmanEnv, PacmanPlayer
from tqdm import tqdm
class PacmanModel(PacmanPlayer):
# Model definitions can be found in pacman_agent.py
def __init__(self, max_enemies=5, optimizer_lr=0.001, logdir=None):
... |
from __future__ import print_function
import sys
import struct
import six
from pypytools.jitview import Color
from capnpy import ptr
COLORS = [Color.darkred, Color.darkgreen, Color.brown,
Color.darkblue, Color.purple, Color.teal]
def print_buffer(buf, **kwds):
p = BufferPrinter(buf)
p.printbuf(end... |
# This file is part of the Data Cleaning Library (openclean).
#
# Copyright (C) 2018-2021 New York University.
#
# openclean is released under the Revised BSD License. See file LICENSE for
# full license details.
"""Implementation of the datastore class that caches dataset snapshots in
memory.
"""
from dataclasses im... |
# Copyright 2015 The TensorFlow 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... |
from DeviceManagerBase import DeviceManagerBase
import serial_connection as sc
import enum
from time import sleep
dia60mLsyringe = 'S26.59'
diaquerybytes = b'00DIA\r'
ETXbyte = b'\x03'
#ToDo
#add rate change functionality 00RAT11.1MM
#-->sets rate to 11.1 mL/min
'''
Note: if pump addresses are somehow reset, this won... |
#!/usr/bin/env python
# coding: utf-8
import os
import sys
import json
import multiprocessing as mp
WORKING_DIR: str = '/mnt/d/Git/BTC-blockchain-data/stage2/Transformer/test'
WARNING_REC: str = os.path.join(WORKING_DIR, 'warning_rec.txt')
assert(os.path.exists(WARNING_REC))
f_content:str = ''
lines: list[str] = []
... |
def generateWidgetObject(signature: str, account_data: dict, data: dict) -> str:
return {
'merchantAccount': account_data['merchant_account'],
'merchantDomainName': account_data['merchant_domain'],
'merchantTransactionType': 'AUTO',
'merchantTransactionSecureType': 'AUTO',
'o... |
import time
from typing import NamedTuple
from flask import jsonify, request
import toolz.functools as tools
from streaming import create_app
from mcwi.distributions import BrownianMotion
class DistributionParameters(NamedTuple):
type: str
params: dict
class DbConnector:
def __init__(db_type='sqlite')... |
import logging
import socket
import asyncio as aio
from aioouimeaux.device import DeviceUnreachable
from aioouimeaux.device.switch import Switch
from aioouimeaux.device.insight import Insight
from aioouimeaux.device.maker import Maker
from aioouimeaux.device.lightswitch import LightSwitch
from aioouimeaux.device.moti... |
import pygame
import os
import random
from pygame.event import Event
pygame.font.init()
pygame.mixer.init()
WIN = pygame.display.set_mode((500,500)) #Window
pygame.display.set_caption("MARCUS GAME")
... |
"""
Register point clouds to each other
arrays are named like name_abc
abc are subscripts and indicate the what that tensor index refers to
index name conventions:
m: test point index
n: training point index
a: input coordinate
g: output coordinate
d: gripper coordinate
"""
from __future__ impor... |
"""This experiment iterates the hyper parameters for skip-gram models to
evaluate how well the sensor embedding learned through the skip-gram model
fits the layout of the sensors on the smart home floor plan.
During the learning of this sensor embedding model, a k-skip-2-gram model using
noise-contrastive estimation i... |
import os
import sys
import pytest
import shutil
import pickle
import filecmp
import virtool.pathoscope
BASE_PATH = os.path.join(sys.path[0], "tests", "test_files", "pathoscope")
BEST_HIT_PATH = os.path.join(BASE_PATH, "best_hit")
EM_PATH = os.path.join(BASE_PATH, "em")
MATRIX_PATH = os.path.join(BASE_PATH, "ps_matri... |
"""
MIT License
Copyright (c) 2018 AlessioNetti
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, ... |
# __author__ = 'Hochikong'
from keras.models import load_model
from neo4j.v1 import GraphDatabase, basic_auth
from configparser import ConfigParser
from bosonnlp import BosonNLP
from splinter import Browser
from jieba import posseg, add_word, enable_parallel, load_userdict
from ETL import translate
import numpy
import ... |
"""Restricted lists with base-datatype meta-type support
This module is normally used to easily create a baseType
definition for a property like so:
listof_Blarghs = list_types.listof(
name = "listof_Blarghs",
baseType = Blargh,
dataType = "list.Blargh",
)
class X(propertied.Propertied):
blarghs = common.L... |
from toml import load
from datetime import datetime, timedelta
from ast import literal_eval
import logging
from re import compile, search
async def get_sleeper_table(bot, target, got_username):
try:
parsed_toml_global_sleeper = load("sleeper_table.toml")
sleeper_usernames = parsed_toml_global_slee... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
Convert image feature npz's to LMDB
"""
import argparse
import glob
import io
import json
import multiprocessing as mp
import os, sys
from os.path import basename, exists
from cytoolz import curry
import numpy as np
from tqdm import tqdm
import ... |
import os
import os.path as osp
import random
import numpy as np
import torch
from skimage import io
# This code is strongly borrowed from
# Label
# Each satellite image is paired with a mask image for land cover annotation. The mask is a RGB image with 7 classes of labels, using color-coding (R, G, B) as follows.
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.