text stringlengths 3.07k 22.1k |
|---|
import collections
import functools
import getpass
import glob
import io
import itertools
import json
import logging
import sys
import click
import click.types
import romp._core
import romp._matrix
import romp._version
logger = logging.getLogger(__name__)
# https://github.com/pallets/click/pull/1278
class Choice(... |
# coding=utf-8
import tensorflow as tf
import tensorflow.contrib as tc
import gpu_env
from .common import dropout, dense, get_var
def single_rnn_cell(cell_name, num_units, is_train=None, keep_prob=0.75):
"""
Get a single rnn cell
"""
cell_name = cell_name.upper()
if cell_name == "GRU":
c... |
"""
A python module for working with songsheets. Songsheets (or leadsheets) are simple sheets
showing a song's lyrics, chords, progression patterns and other metadata.
`chordpro <https://en.wikipedia.org/wiki/ChordPro>`_ is an existing standard serving a similar purpose.
Why another implementation? A few reasons:
- c... |
'''
This problem was asked by Twitter.
Problem statement:
==================
You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API:
- record(order_id): adds the order_id to the log
- get_last(i): gets the ith last elemen... |
import torch
import torch.nn as nn
from torch.nn import functional as F
# from transformers import BertModel, BertTokenizer
from transformers import AutoConfig
from transformers import AutoModelWithLMHead
from src.utils import load_embedding
import logging
logger = logging.getLogger()
class BertTagger(nn.Module):
... |
import os
import random
import argparse
import time
import torch
import torch.optim as optim
import torch.nn as nn
from torchvision import models
from torchvision.utils import save_image
from tqdm import tqdm
from datasets.mvtec import MVTecDataset
from datasets.preprocessing import generate_image_list, augm... |
import numpy as np
import pandas as pd
import itertools
import collections
def findDuplicates(N, L, MOI):
'''
This function takes as an input the number of cells (N), the library size (L)
and the average MOI for the virus and returns the number of duplicate cells.
'''
n_tags_per_cell = np.random.po... |
#
# Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list o... |
# -*- mode: python; coding: utf-8 -*
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 3-clause BSD License
import os
import numpy as np
from astropy import units
from astropy.coordinates import Angle, EarthLocation
import pytest
from pyuvdata import UVData
from scipy.special import j1
import ... |
# 50m maps of all states (10m Alaska shape)
import os
import sys
import argparse
# Global variables
xd_width, xd_height = 1200, 900
base_dir = '/Users/monad/Work/data'
cult10m_dir = os.path.join(base_dir, '10m_cultural', '10m_cultural')
phys10m_dir = os.path.join(base_dir, '10m_physical')
cult50m_dir = os.path.join... |
try:
import yaml
except:
print('PyYAML not installed')
try:
import rethinkdb as r
except:
print('rethinkdb not installed')
import collections
import numbers
import re
import types
from datetime import datetime
from pathlib import Path
from rethinkdb import ql2_pb2
from . import test_definitions
from... |
import sys
from collections import OrderedDict
import torch
from torch.autograd import Function
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
import numpy
def conjugate_gradient_block(A, B, x0=None, tol=1e-2, maxit=None, eps=1e-6):
"""
Solve the linear system A X = B usin... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import os
import re
import runpy
import sys
# debugpy.__m... |
__author__ = 'saeedamen' # <NAME>
#
# Copyright 2016 Cuemacro
#
# 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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 18 13:45:53 2021
@author: qwang
"""
import os
import random
os.chdir('/home/qwang/pre-pico')
from tqdm import tqdm
import pandas as pd
import json
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from transformers import ... |
#-------------------------------------------------------------------------------------------------#
# NAME: ibm_db_tools.py #
# #
# PURPOSE: This fi... |
import matplotlib
matplotlib.use("PS")
import modin.pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighbo... |
# -*- coding: utf-8 -*-
'''
This module will take raw CPAP data as an input, and export it to JSON as an
output.
Example
-------
$ python cpap_extraction.py 38611.000 .
Extracts the raw CPAP data from 38611.000 to a new file called
38611_extracted.JSON
Attributes
----------
SOURCE : path
The SOURCE data file... |
import unittest
import numpy as np
class TestInputFunctions(unittest.TestCase):
def test_ramp(self):
"""Test functions.ramp"""
from pysd import functions
functions.time = lambda: 14
self.assertEqual(functions.ramp(.5, 10, 18), 2)
functions.time = lambda: 4
self.a... |
import re
import six
from deploy_config_generator.errors import VarsParseError, VarsReplacementError
from deploy_config_generator.utils import yaml_load
from deploy_config_generator.template import UnsafeText
EOF_TOKEN = None
NEWLINE_TOKEN = '\n'
SKIP_TOKENS = ('\r', )
WHITESPACE_TOKENS = (' ', '\t')
VAR_END_TOKENS =... |
from __future__ import print_function, division
import sys
import glob
import os
import pandas as pd
import numpy as np
from random import shuffle
from serviceCourse.parsers import read_fasta
def get_first_sequence(input_fasta):
input_sequence = ""
for header, comment, sequence in read_fasta(input_fasta):
... |
"""
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions ... |
import argparse
from collections import OrderedDict
from pathlib import Path
from utils import Collection, DisjointSet
CORRECT_A = 'correct_A'
INCORRECT_A = 'incorrect_A'
PARTIAL_A = 'partial_A'
SPURIOUS_A = 'spurious_A'
MISSING_A = 'missing_A'
CORRECT_B = 'correct_B'
SPURIOUS_B = 'spurious_B'
MISSING_B = 'missing_B... |
"""
functional utils for audio feature extraction
Written for audax by / Copyright 2022, <NAME>
"""
import jax
import warnings
import math
from jax import numpy as jnp, lax
from typing import Optional, Callable, Any
from .stft import stft
from .helpers import batch_pad
def _hz_to_mel(freq: float, mel_scale: str = "h... |
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import tg
from tg.util import *
from tg.configuration.utils import get_partial_dict
from nose.tools import eq_, raises, assert_raises
import os
from tg.controllers.util import *
from tg.util.dates import get_fixed_timezone, utctz, parse_datetime
from tg.... |
# Copyright 2018 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 pytest
from pyecore.ecore import *
import pyecore.ecore as Ecore
def test_ecore_URI():
assert Ecore.nsURI == 'http://www.eclipse.org/emf/2002/Ecore'
def test_get_existing_EClassifier():
assert Ecore.getEClassifier('EClass')
def test_get_nonexisting_EClassifier():
assert not Ecore.getEClassifier... |
import numpy as np
# Some code is copied or adapted from the Meep code at https://github.com/smartalecH/meep/blob/jax_rebase/python/adjoint/filters.py
class morph:
def __init__(self,size,margin_size=np.zeros((2,2)),proj_strength=10**6):
self.size = size # physical size in the row and column directions
... |
"""
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distrib... |
# -*- coding: utf-8 -*-
def test_import():
import pyftdc
assert 0 == 0
diagnostics_file = './diagnostic.data_40/metrics.2021-07-22T17-16-31Z-00000'
def test_parse():
import pyftdc
# Create a parser object
p = pyftdc.FTDCParser()
status = p.parse_file(diagnostics_file)
assert status == 0... |
###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: <EMAIL>
##
## This file is part of VisTrails.
##
## "Redistributio... |
from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
import json
import os
import time
import datetime
import pytz
import subprocess as sp
import arxiv
import hashlib
from trans_api.trans_util import trans, debug_msg, DEBUG_FILE
from .ad... |
import sys
import timeit
from copy import deepcopy
fname = '../input/day17/input.txt'
part1 = True
if len(sys.argv) > 1 and sys.argv[1] == '2':
part1 = False
lines = []
with open(fname) as fh:
lines = fh.readlines()
lines = list(map(lambda s: s.strip(), lines))
def pprint(m, layer=False, hyper=False):
... |
from __future__ import print_function, division, absolute_import #, unicode_literals # not casa compatible
from builtins import bytes, dict, object, range, map, input#, str # not casa compatible
from future.utils import itervalues, viewitems, iteritems, listvalues, listitems
from io import open
from future.moves.urllib... |
#
# Copyright 2020-2021 Xilinx, 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 ... |
# exceptions.py
# Copyright (C) 2006, 2007 <NAME> <EMAIL>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""exception classes"""
import traceback, sys, re
class MakoException(Exception):
pass
class RuntimeException(MakoException):
... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
#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... |
#!/usr/bin/env python3
import argparse
import xml.etree.ElementTree as ET
from svg.path.parser import _tokenize_path
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, <NAME>"
__license__ = "MIT"
__status__ = "Development"
__version__ = "0.1.0"
description = """
Normalize SVG files so that the OP-1 understand... |
# This file is part of the Python aiocoap library project.
#
# Copyright (c) 2012-2014 <NAME> <http://sixpinetrees.blogspot.com/>,
# 2013-2014 <NAME> <<EMAIL>>
#
# aiocoap is free software, this file is published under the MIT license as
# described in the accompanying LICENSE file.
"""This module implem... |
# Copyright 2020 TerraPower, 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 writi... |
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 <NAME> and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free... |
import sys
from akari.utils import loadDB, commit_changes
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QIcon, QColor, QFont, QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QListWidget, QListWidgetItem, QListView, QHBoxLayout, QVBoxLayout, QAbstractItemView, QMenu, QInputDialog, QL... |
from __future__ import print_function
import argparse
import logging
import os
import time
import numpy as np
# disable gpu training for this example
os.environ["CUDA_VISIBLE_DEVICES"] = ""
import paddle
import paddle.fluid as fluid
from paddle.fluid.executor import global_scope
import reader
from network_conf impo... |
"""
Work with the MDS Provider JSON Schemas.
"""
import os
import jsonschema
import requests
import mds.geometry
import mds.github
from .versions import UnsupportedVersionError, Version
STATUS_CHANGES = "status_changes"
TRIPS = "trips"
SCHEMA_TYPES = [ STATUS_CHANGES, TRIPS ]
class Schema():
"""
Represen... |
import abc
import random
import json
from .models import Match as mMatch, Profile
#interface kolejki FIFO
class QueueI(abc.ABC):
@abc.abstractmethod
def len(self):
pass
@abc.abstractmethod
def pop(self):
pass
@abc.abstractmethod
def push(self, value):
pass
@abc.abstr... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Appier Framework
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Appier Framework.
#
# Hive Appier Framework is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apach... |
# -*- coding: utf-8 -*-
# Copyright 2016 Yelp 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 ag... |
#!/usr/bin/env python3
#
# Copyright (c) 2018 <NAME> <<EMAIL>>
# SPDX-License-Identifier: MIT
#
# Tool for splitting multi-word pronunciations
#
# In our project, many of the original recordings are multi-word phrases
# such as “jeu savess prender”. Typically (and rather unusually for
# recorded speech), each word is s... |
import os
import time
from PIL import Image
from skimage import color, io
from gevent.pywsgi import WSGIServer
from werkzeug.utils import secure_filename
from flask import Flask, request, render_template, url_for
from wallgen import (
NbyNGradient,
genDiamond,
genHexagon,
genIsometric,
g... |
# Copyright (c) 2020 Mobvoi Inc. (authors: <NAME>, <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/LICENSE-2.0
#
# Unless required by applicable... |
import os
import subprocess
import urllib.request
from PySide2 import QtCore, QtGui
from PySide2.QtCore import QFile
from PySide2.QtGui import QIcon, QColor
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QMessageBox, QVBoxLayout, QSizePolicy, QFileDialog, QPushButton, QDialog, QWidget, QLabel
fr... |
import os
import sys
import numpy as np
from pypinyin import Style, lazy_pinyin
from data import PUNCS
yunjiaos = {
"0":["a", "ia", "ua", "va", "üa"],
"1":["e", "o", "uo", "ie", "ue", "üe", "ve"],
"2":["u"],
"3":["i", "ü", "v"],
"4":["ai", "uai"],
... |
#!/usr/bin/env python
import sys
import random
import pickle
import locale
import argparse
import warnings
import scipy
import numpy as np
import pandas as pd
from sklearn.model_selection import (train_test_split,
GridSearchCV,
RandomizedSearchC... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ##... |
#!/usr/bin/env python
from shapely.geometry import Polygon, MultiPolygon, LineString
import shapely.validation
import numpy as np
from matplotlib import collections as mc
import pylab as pl
import csv
import math
import time
current_milli_time = lambda: int(round(time.time() * 1000))
def angle_to(source, dest):
... |
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
# Author: <NAME> <<EMAIL>>
"""
Defines a Particle-Swarm optimization engine.
"""
import typing as ty
from numpy.random import uniform, get_state, set_state
import numpy as np
from decorator import decorator
from copy import deepcopy
from aiida import orm
from ..... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def _L2_loss_mean(x):
return torch.mean(torch.sum(torch.pow(x, 2), dim=1, keepdim=False) / 2.)
class CKE(nn.Module):
def __init__(self, args,
n_users, n_items, n_entities, n_relations,
user_pre_embed=None, ... |
""" DQL language parser """
from pyparsing import (
CharsNotIn,
Combine,
Group,
Keyword,
OneOrMore,
Optional,
Regex,
StringEnd,
Suppress,
Word,
ZeroOrMore,
delimitedList,
oneOf,
printables,
quotedString,
restOfLine,
)
from .common import (
filename,
... |
###########################
### IMPORT DEPENDENCIES ###
###########################
from typing import Sequence
import cv2
import numpy as np
import os
from matplotlib import pyplot as plt
import time
import mediapipe as mp
import tensorflow as tf
import streamlit as st
from PIL import Image
import tempfil... |
import argparse
import os
import timeit
from importlib import import_module
import numpy as np
import tensorflow as tf
from attacks.minmax import minmax_eot
from utils import *
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", default="cifar", type=str, help="dataset: mnist/cifar")
parser.add_argume... |
# coding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License... |
#Written by <NAME> Email:<EMAIL>
from __future__ import print_function
import argparse
import cv2
import numpy as np
import os
import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import matplotlib.pyplot as plt
from data import BaseTransform, VOC_300, VOC_512, COCO_300, COCO_512
fro... |
import os
import torch
import torch.nn as nn
import logging
import time
import random
import numpy as np
from torch.nn.parallel import DistributedDataParallel as DDP
from lib.models.builder import build_model
from lib.models.losses import CrossEntropyLabelSmooth, \
SoftTargetCrossEntropy
from lib.dataset.builder i... |
#!/usr/bin/env python
from joshua.intervaltree import Interval, IntervalTree
from joshua.intervalforest import IntervalForest
import pandas as pd
import pyprind
class DataFrameInterval(Interval):
def __init__(self, idx, df, *args, **kwargs):
Interval.__init__(self, *args, **kwargs)
self.idx = idx... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 13 13:12:05 2020
@author: <NAME>
@Professor: <NAME>
"""
# %% Exercise 1 - Graficos em escala logaritmica
# ============================================================================
print('\nExercise 1 - Graficos em escala logaritmica\n',
'----------... |
import fcntl
import contextlib
import os
import tempfile
import subprocess
import shutil
import csv
import sys
try:
import cPickle as pickle
except ImportError:
import pickle
import six
import joblib
import yaml
import numpy as np
from . import utils
if utils.config["json"]["use_simplejson"]:
import sim... |
from dotenv import load_dotenv
load_dotenv()
import os, re, json, unicodedata
import tweepy
from tweepy import Stream,OAuthHandler
from datetime import datetime, timedelta
import nltk
# nltk.download('stopwords')
from nltk.corpus import stopwords
stop_words = stopwords.words('spanish')
from nltk.tokenize import Twe... |
import logging
import pytest
import sdmx
from sdmx import message
from sdmx import model as m
from sdmx.model import DataSet, DataStructureDefinition, Dimension, Key, Observation
from sdmx.writer.xml import writer as XMLWriter
log = logging.getLogger(__name__)
@pytest.fixture
def dsd():
dsd = DataStructureDefi... |
# Copyright 2021 <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
#
# 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... |
import numpy as np
import pytest
import numpy.testing as npt
from pulse2percept.implants.base import ProsthesisSystem
from pulse2percept.implants.bvt import BVT24, BVT44
@pytest.mark.parametrize('x', (-100, 200))
@pytest.mark.parametrize('y', (-200, 400))
@pytest.mark.parametrize('rot', (-45, 60))
@pytest.mark.parame... |
# -*- coding: utf-8 -*-
"""
routes.py
~~~~~~~~~
application routes
"""
from json import JSONDecodeError
import requests
from requests.exceptions import HTTPError
from mailchimp3 import MailChimp
from mailchimp3.helpers import get_subscriber_hash
from flask import Blueprint, current_app, jsonify, render_tem... |
# Copyright 2021 The Cirq Developers
#
# 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 ... |
import numpy as np
import pandas as pd
from sklearn import preprocessing, linear_model, metrics
import gc; gc.enable()
import random
import time, datetime
from sklearn.neural_network import MLPRegressor
from sklearn.linear_model import TheilSenRegressor, BayesianRidge
from sklearn.ensemble import BaggingRegressor
from... |
# Copyright 2017 Canonical Ltd.
# Licensed under the LGPLv3, see LICENCE file for details.
import abc
from collections import namedtuple
from ._error import (
ThirdPartyCaveatCheckFailed,
CaveatNotRecognizedError,
VerificationError,
)
from ._codec import decode_caveat
from ._macaroon import (
Macaroon,... |
# Copyright 2018 <NAME>, <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/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
import json
import logging
import os
import time
import pytest
import yaml
from ocs_ci.framework import config
from ocs_ci.framework.pytest_customization.marks import (
deployment, destroy, ignore_leftovers
)
from ocs_ci.ocs import constants, ocp, defaults
from ocs_ci.ocs.exceptions import CommandFailed, CephHeal... |
import os
import requests
import json
import logging
import typing
import db_access.db as db
import subprocess
from config import tusc_api_cfg, wallet_cfg
logger = logging.getLogger('root')
logger.debug('loading')
DefaultErrorResponse = {"error": "Something went wrong, please contact tusc support"}
InternalServerErro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Licensing Information: You are free to use or extend these projects for
# education or reserach purposes provided that (1) you retain this notice
# and (2) you provide clear attribution to UC B... |
from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
from __future__ import with_statement
import tw2.core as twc
import testapi
import itertools
import os
import webob as wo
import contextlib
from nose.tools import raises, eq_
from sieve.operators import ass... |
import numpy as np
from numpy.testing import assert_array_equal
from tempfile import mkstemp
from nose.tools import assert_true, assert_equal, assert_less, assert_greater
from sklearn.datasets import load_digits, load_iris
from pystruct.models import GridCRF, GraphCRF, BinaryClf
from pystruct.learners import OneSlack... |
from __future__ import print_function
import msgpackrpc # pip install msgpack-rpc-python
import numpy as np # pip install numpy
class MsgpackMixin:
def __repr__(self):
from pprint import pformat
return "<" + type(self).__name__ + "> " + pformat(vars(self), indent=4, width=1)
def to_msgpack(sel... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 14:51:38 2020
@author: haukeh
"""
#%%Import of required packages
import numpy as np
import pandas as pd
import os
import sys
import plotly.graph_objs as go
from plotly.offline import plot
#%% Function to read results csv files
def read_csv(scen, param):
df = pd.r... |
"""Methods calculating E[Y] and E[Y^2] (and therefore also Var[Y]) over prior predictive distribution for Poisson Matrix Factorization."""
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability import distributions as tfd
import warnings
def _make_tf(v):
retur... |
import torch
import numpy as np
def center_form(segments):
""" convert (left, right) to (center, width) """
return torch.cat([(segments[:, :1] - segments[:, 1:]) / 2.0,
segments[:, 1:] - segments[:, :1]], dim=1)
def point_form(segments):
""" convert (centor, width) to (left, right)... |
import functools
import hashlib
import inspect
import json
import logging
from typing import List, Dict, Tuple, Iterator
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from recsys import config
from recsys.config import DEVICE
from recsys.types import... |
from math import atan, atan2, cos, pi, sin, tan
import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
from numfoil.legacy.panel.thick_functions import airfoil, make_panels, normals
# chow pg 160
class ThickPanelledAirfoil:
def __init__(self, Naca="2422", n_panels=10):
self.n_panels = n_... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 3.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... |
#!/usr/bin/env python
import os
import time
import cv2
import numpy as np
import pybullet as p
import matplotlib.pyplot as plt
import tensorflow as tf; tf.compat.v1.enable_eager_execution()
from ravens.models import Attention, Regression
from ravens import cameras
from ravens import utils
class RegressionAgent:
... |
import sys
sys.path.append('core')
import argparse
import os
import os.path as osp
import cv2
from glob import glob
from PIL import Image
import numpy as np
import torch
import torch.utils.data as data
from torchvision.transforms import CenterCrop
from raft import RAFT
from utils import flow_viz
from utils.utils imp... |
# -*- coding: utf-8 -*-
# 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, softwar... |
from __future__ import print_function
import sys, pandas, argparse
import xml.etree.cElementTree as et
import pickle as pkl
import time
sys.path.append('../')
from models.pipeline import *
from models.classifier import *
from models.transformer import *
def load_copa(filepath=None):
xml_tree = et.parse(filepath... |
'''
<NAME> - PHYS265 FINAL PROJECT
SIMULATION OF THE MAXWELL'S DEMON
File: main.py
This program produces a visual simulation of the Maxwell's demon.
Imagine you have two chambers with gas molecules of different energy. The chambers are connected by a door, controlled by a demon.
The demon opens and shuts the... |
# -*- coding: utf-8 -*-
"""
hss_app.milenage
~~~~~~~~~~~~~~~~
This module implements the Milenage algo set as per
3GPP TS 35.206 V9.0.0 (2009-12).
"""
import hmac
import random
from collections import namedtuple
from Crypto.Cipher import AES
AMF_DEFAULT_VALUE = bytes.fromhex("8000")
INITIALIZATION_... |
# -*- coding: utf-8 -*-
from argparse import Namespace
from inspect import getfullargspec
from clustertools import Experiment
from clustertools import Monitor
from clustertools.test.util_test import TestComputation, __EXP_NAME__, prep, \
purge
from nose.tools import assert_equal, assert_raises, with_setup
from no... |
# region Imports and setting matplotlib backend
# Import functions from PyQt5 module (creating GUI)
from PyQt5.QtWidgets import QMainWindow, QApplication, QVBoxLayout, \
QHBoxLayout, QLabel, QPushButton, QWidget, QCheckBox, \
QComboBox, QSlider, QFrame, QButtonGroup, QRadioButton
from PyQt5.QtCore import Qt
... |
"""Functions for clustering sequences before input.
This includes computing a distance matrix using MinHash, and
clustering that matrix.
"""
import ctypes
from collections import defaultdict
import logging
import multiprocessing
from multiprocessing import sharedctypes
import operator
import numpy as np
from scipy.c... |
import urllib.request
import glob
from .. import parsers
import timeit
import gzip
import zipfile
import shutil
import os
import csv
import xml.etree.ElementTree as ET
import time
import resource
import sys
import gc
import traceback
from datetime import datetime
result_dir = "./ssxtd/benchmarks/results/"
working_dir ... |
#!/usr/bin/env python3
import argparse
import struct
from enum import IntEnum
from panda import Panda
from panda.python.uds import UdsClient, MessageTimeoutError, NegativeResponseError, SESSION_TYPE,\
DATA_IDENTIFIER_TYPE, ACCESS_TYPE
# TODO: extend UDS library to allow custom/vendor-defined data identifiers withou... |
import PyIng
import tflite_runtime.interpreter as tf_lite
import numpy as np
import re
import pickle
from pkg_resources import resource_filename
WORD_INDEX_PATH = resource_filename('PyIng', "data/word_index.pckl")
MODEL_PATH = resource_filename('PyIng', "data/output_model.tflite")
def parse_ingredients(ingredients):... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 13:28:33 2021
@author: RPL 2020
"""
from tensorflow.keras.models import Sequential,load_model
from tensorflow.keras.layers import Dense
from tensorflow.keras.losses import MeanSquaredError
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import devic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.