text stringlengths 3.07k 12.6k |
|---|
import pytest
import os
from investporto.portfolio_plan_cli import Portfolio, portfolio_plan
from click.testing import CliRunner, Result
from pathlib import Path
import collections
from investporto.types_and_vars import portfolio_plan_name
file_content = """
etfs:
percentage: 30
subclasss:
big_market_caps:
... |
from pathlib import Path
from typing import Match
from arbeitsstunden.management.commands.utils.data import reduction
from arbeitsstunden.management.commands.utils.data import member, project, project_item, project_item_hour, season, user, Nutzer
from arbeitsstunden.management.commands.utils.import_functions import Ar... |
'''
Note:
- Country ID is an integer [0, n-1], it is unique and every x from [0, n-1]
has is a valid Country ID
'''
# Generic/Built-in Libs
from collections import namedtuple
from enum import Enum
from math import sqrt
import heapq
Solar = namedtuple('Solar', ['country', 'price'])
Cell = namedtupl... |
import typing
from starlette.datastructures import URL
from starlette.middleware.wsgi import WSGIMiddleware
from starlette.routing import Lifespan
from starlette.websockets import WebSocketClose
from .app_types import ASGIApp, EventHandler, Receive, Scope, Send
from .config import settings
from .errors import HTTPErr... |
from collections import namedtuple
import logging
import pprint
import proto.conversation_pb2 as conversation_proto
import pymorphy2
import re
from multiset import Multiset
from node_util import visit_node_with_branch_parent
from operator import itemgetter
from typing import Dict, List
UKR_APOS = "'`’ʼ"
UKR_APOS_REGE... |
from enum import Enum, IntFlag
class Arch(Enum):
""" Limited list of processor architectures """
x86 = 0
x64 = 1
class FriendFlags(Enum):
""" EFriendFlags """
NONE = 0x00
BLOCKED = 0x01
FRIENDSHIP_REQUESTED = 0x02
IMMEDIATE = 0x04
... |
# Author: <NAME> <<EMAIL>>
#
# License: BSD 3 clause
#
# SPDX-License-Identifier: BSD-3-Clause
from typing import Any, Hashable, Optional, Sequence
import xarray as xr
import numpy as np
from scipy import interpolate
def mask_saturated_pixels(arr: xr.DataArray, saturation_value: float = 0) -> xr.DataArray:
"""M... |
import os
from typing import List
import absl
import tensorflow as tf
from tfx import v1 as tfx
from tfx.components.trainer.fn_args_utils import DataAccessor
from tfx.components.trainer.fn_args_utils import FnArgs
import tensorflow_transform as tft
from tfx_bsl.tfxio import dataset_options
_TRAIN_DATA_SIZE = 128
_EVAL... |
from .utils.defaults import default_path_template
from .utils.defaults import default_filename_template
from .utils.defaults import default_latest_filename_template
from .utils import generate_info, is_valid_release
from .utils import update_releases
from .utils import read_releases
from .utils import current_system
fr... |
#!/usr/bin/env python3
from datetime import datetime, timedelta
import telnetlib
import argparse
import json
import time
# ============================================================================
# ==== Utility functions =====================================================
# =====================================... |
import discord
import urllib.request
import requests
import os
async def nb_pages(codeSrc):
''' Function used to count the number of pages in a scan by parsing the web page source code.
codeSrc: type str of an http.client.HTTPResponse object from urllib.request.urlopen().read()
(ex: codeSrc = ... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class FinancialYearOpeningWizard(models.TransientModel):
_name = 'account.financial.year.op'
_description = 'Opening Balance of Financial Year'
company_id = fields.Many... |
#!/usr/bin/env python
import sys, os
import argparse
import subprocess
import time
import shutil
import tempfile
OKAY = 0
def Print(*objects, **kwargs):
sep = kwargs.get('sep', ' ')
end = kwargs.get('end', '\n')
out = kwargs.get('file', sys.stderr)
t = time.strftime('[%F %R:%S] ', time.localtime())
... |
# Create your views here.
from django.shortcuts import render
from django.db.models import Avg, Count, Min, Sum
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status
from django.http import HttpResponse
from django.core import serializers
from dja... |
# -*- coding: utf-8 -*-
from params import Params
from models import representation as models
from dataset import classification as dataset
from tools import units
from tools.save import save_experiment
from loadmydata import *
import itertools
import argparse
import keras.backend as K
from keras.callbacks import Callb... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import expm
def F(n=None, fdim=5, hdim=None, term=None, symbolic=False):
if not symbolic:
return fmat_numeric(n=n, fdim=fdim, hdim=hdim, term=term)
else:
return fmat_symbolic(n=n, fdim=fdim, hdim=hdim... |
import typing as tp
from abc import ABC, abstractmethod
import jax
from elegy import types, utils
from rich.table import Table
from rich.text import Text
REGISTRY: tp.Dict[tp.Type, tp.Type["GeneralizedModule"]] = {}
class ModuleExists(Exception):
pass
class GeneralizedModule(ABC):
@abstractmethod
def ... |
# -*- coding: utf-8 -*-
from tastypie.resources import ModelResource, ALL_WITH_RELATIONS, Resource
from tastypie import fields
from tastypie.authentication import ApiKeyAuthentication, SessionAuthentication
from tastypie.exceptions import ImmediateHttpResponse
from django.http.response import HttpResponse
from django.c... |
import glob
import math
import random
from PIL import Image
from imageio import imread
import numpy as np
import tensorflow as tf
from keras.layers import RandomFlip, RandomRotation
DATA_SETS = {
'dots': "hit-images-final/hits_votes_4_Dots",
'tracks': "hit-images-final/hits_votes_4_Lines",
'worms': "hit-... |
import argparse
import xml.etree.cElementTree as etree
import os
from os import listdir
from os.path import isfile, join
import codecs
import re
from six.moves import html_parser
# Remove empty brackets (that could happen if the contents have been removed already
# e.g. for citation ( [3] [4] ) -> ( ) -> nothing
def r... |
import asyncio
import copy
import random
import sys
#this is a simple one card poker variant AKA war
#http://www.cs.cmu.edu/~ggordon/poker/
numActions = 4
#don't need a context, so this is empty
class _Context:
async def __aenter__(self):
pass
async def __aexit__(self, *args):
pass
def getCo... |
#!/usr/bin/env python3
import json
import os
import urllib
import uuid
from multiprocessing import Process, Queue
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from builtins import KeyboardInterrupt, SystemExit
from apps.crawler.lib.de... |
# -*- coding: utf-8 -*-
"""
@author: HYPJUDY 2019/4/15
https://github.com/HYPJUDY
Decoupling Localization and Classification in Single Shot Temporal Action Detection
-----------------------------------------------------------------------------------
Functions to get train and test data
"""
import numpy as np
impor... |
# coding=utf-8
# Created 2014 by <NAME>
from datetime import datetime
import logging
from google.appengine.ext import ndb
from google.appengine.ext.ndb.model import BooleanProperty, StringProperty, DateTimeProperty, KeyProperty, IntegerProperty
from flask import current_app
from flask_babel import gettext as _, nget... |
"""
Module that contains all of the jobs that the Submitty Daemon can do
"""
from abc import ABC, abstractmethod
import os
from pathlib import Path
import shutil
import subprocess
from . import INSTALL_DIR, DATA_DIR
class AbstractJob(ABC):
"""
Abstract class that all jobs should extend from, creating a comm... |
""" es_runners for initial geometry optimization
"""
import numpy
import automol
import elstruct
import autorun
from mechanalyzer.inf import thy as tinfo
from mechlib.amech_io import printer as ioprinter
from mechroutines.es import runner as es_runner
from mechroutines.es.runner import qchem_params
def remove_imag(g... |
import os
import struct
from io import BytesIO
from PIL import Image
from torch.utils.data import Dataset
from torchkit.data import example_pb2
def read_index_file(index_file):
""" Parse index file, each line contains record_name, record_index, record_offset and label
"""
samples_offsets = []
record_f... |
import shutil
import numpy as np
from keras.models import load_model
from sklearn.externals import joblib
from gensim.models import KeyedVectors
from steps.base import BaseTransformer
from .contrib import AttentionWeightedAverage
class BasicClassifier(BaseTransformer):
"""
Todo:
load the best model ... |
from flask import jsonify, request
from app import db
from app.api import bp
from app.models import Batch,Container,ZoneEntry, BinBatchAssociation, Alert,ProximityAlert, ZoneAlert, BatchAlert, CleanupAlert, InactivityAlert
from app.utils.user_auth import token_auth
from app.models import Role
from app.utils.helpers imp... |
import Queue
import time
import socket
import sys
import random
from threading import Thread
import random
import datetime
class Frame:
def __init__(self, type, num, data):
self.type = type
self.num = str(num)
self.data = data
if (data == None):
# if(type == 'ACK'):
... |
import json
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
from container import Container
from components import *
FONT_AWESOME = "https://use.fontawesome... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2020 Data61, CSIRO
#
# 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 pytest
from blessedblocks.line import Line
from blessed import Terminal
term = Terminal()
def test_parse_dups():
line = Line('{t.green}xy{t.green}z', 3, '^')
print(('\n' + line.display + '{t.normal}').format(t=term))
assert line.plain == 'xyz'
assert line.last_seq == '{t.green}'
def test_pars... |
import torch
import numpy as np
import os
import json
CLASS = {0: 'Negative', 1: 'Positive'}
CLASS2 = {'Negative': 0, 'Positive': 1}
CLASS2D = {0: 'PositiveHigh', 1: 'PositiveLow', 2: 'NegativeHigh', 3: 'NegativeLow'}
def flatten_audio(samples, args):
audio = np.zeros([1, args.sequence_length])
for k, j in ... |
"""
Utils for SVAE.
Note: this code is for research i.e. quick experimentation; it has minimal
comments for now, but if we see further interest from the community -- we will
add further comments, unify the style, improve efficiency and add unittests.
@contactrika
"""
import torch
class SVAEParams():
def __ini... |
from abc import abstractmethod
import os
import hashlib
from enum import *
from TorrentPython.Bencode import *
class MetaInfo(object):
@staticmethod
def parse_torrent(path):
if not os.path.exists(path):
return None
with open(path, 'rb') as f:
source = f.read()
... |
#!/usr/bin/env python3
#from __future__ import unicode_literals
import tweepy
import string
import yaml
import json
# -*- coding: latin-1 -*-
with open("../../secret/key_secret.json") as json_file:
data = json.load(json_file)
access_token_key = data["ACCESS_TOKEN_KEY" ]
access_token_secret = data["ACCESS_T... |
import json
import logging
from argparse import ArgumentParser
from typing import Tuple, Optional, List
import numpy as np
import pandas as pd
from pathlib import Path
from sklearn.datasets import fetch_covtype
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from catboos... |
#!/usr/bin/env python
import pytest
from pprint import pprint
from spells import shells, Spell, beam_to
from json_objects import Object_recursive, Object
from utils import groupby
from transactions import transaction_month
class MonthlyTransactionsSpell(Spell):
def _detect(v):
if type(v) != dict:
... |
"""This module provides the functionality for getting user information from an
LDAP server.
"""
from typing import NamedTuple, Optional
import logging
import ldap # type: ignore
from autorizator.data_types import Login, Password, Role, AuthPIN
from autorizator.user_storage import AbstractUserService, UserStorageErr... |
"""Script for generating data for the analysis."""
from typing import Dict
import ast
from pathlib import Path
import numpy as np
import pandas as pd
import igraph as ig
import joblib
from tqdm import tqdm
from pathcensus import PathCensus
from pathcensus.nullmodels import UBCM
from pathcensus.inference import Inferenc... |
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
import math
from collections import Counter
import queue
sys.setrecursionlimit(10 ** 9)
class TreeNode:
def __init__(self, index, parent):
self.index = index
self.parent = parent
self.edges = []
self.childre... |
from multiprocessing import AuthenticationError
from datetime import datetime, timedelta
import globus_sdk
from tapisservice.logs import get_logger
from tapisservice.tapisflask import utils
logger = get_logger(__name__)
def get_transfer_client(client_id, refresh_token, access_token):
client = globus_sdk.NativeAp... |
from typing import List, Union
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import jwt, JWTError
from datetime import timedelta, datetime
from werkzeug.security import generate_password_hash, ch... |
from __future__ import print_function
from lxml import html
import datetime
import json
import tempfile
import string
import re
import boto3
import traceback
import logging
import os
import requests
sns_client = boto3.client('sns')
s3_client = boto3.client('s3')
logger = logging.getLogger('humble-bundle-canary')
logg... |
"""
Utilities about Boolean networks.
"""
import numpy as np
from ortools.graph import pywrapgraph
class BooleanNetwork:
"""
A Boolean network model for target_gene regulatory networks.
"""
def __init__(self, update_functions):
"""
Initialize a Boolean network with the given Boolean up... |
#!/usr/bin/env python
#coding:utf-8
import binascii
class ELF(object):
"""docstring for ELF"""
def __init__(self, filepath):
super(ELF, self).__init__()
self.filepath = filepath
self.elf32_Ehdr = Elf32_Ehdr()
self.initELFHeader()
def initELFHeader(self):
... |
"""
Unit tests for the App class.
"""
import logging
import os
import sys
import time
import unittest
##
# BOOTSTRAP: BEGIN
#
# Bootstrapping code to ensure we can find all the right modules. All other
# local imports should be done after this block.
##
_path = os.path.realpath(__file__)
sys.path.insert(0, _path[:_pa... |
"""Enumerate values specific to Structured Report IODs."""
from enum import Enum
class ValueTypeValues(Enum):
"""Enumerated values for attribute Value Type.
See :dcm:`Table C.17.3.2.1 <part03/sect_C.17.3.2.html#sect_C.17.3.2.1>`.
"""
CODE = 'CODE'
"""Coded expression of the concept."""
CO... |
from collections import OrderedDict
from timeit import timeit
d1 = OrderedDict(a=1, b=2, c=3, d=4)
d2 = dict(a=1, b=2, c=3, d=4)
print(d1)
print(d2)
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
for k in reversed(d1):
print(k)
for k in reversed(list(d2.keys())):
... |
import pandas as pd
import numpy as np
from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA
sheet_names = pd.ExcelFile("BaseData.xlsx").sheet_names
sheet_name_main_L = [sheet_name for (i,sheet_name) in enumerate(sheet_names) if(i%4==2)]
sheet_name_results_L = [sheet_name for (i,sheet_name) in enumera... |
import networkx as nx
import sys
import logging
try:
import cPickle as pickle
except ImportError:
import pickle
logger = logging.getLogger(__name__)
class GraphIO(object):
def __init__(self, s3_client=None, backfill_obj=None):
self.s3_client = s3_client
self.backfill = backfill_obj
... |
from django.forms import models
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponse
from django.views import View
from xhtml2pdf import context
from django.urls import reverse_lazy
from .models import Purchase
from .... |
import pyaudio
import wave
from pydub import AudioSegment
from pynput.keyboard import Listener
import optparse
log = 0
def banner():
print("\n /$$$$$$ /$$ ")
print(" /$$__ $$ ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class LinearNorm(torch.nn.Module):
def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
super(LinearNorm, self).__init__()
self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
... |
import numpy as np
import dlib
import cv2
import logging
import time
import math
import argparse
from config import *
logging.basicConfig(level=logging.DEBUG,
format="%(levelname)s:%(lineno)d:%(message)s")
class Detector(object):
def __init__(self):
self.detector = cv2.CascadeClassifie... |
# -*- coding: utf-8 -*-
#############################################################################
# Copyright <NAME> <<EMAIL>>
#
# Licensed under the MIT License. See LICENSE file in root folder.
#############################################################################
__author__ = "<NAME> <<EMAIL>>"
__versio... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! Inc. 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.or... |
import os, sys
import numpy as np
import pandas as pd
import time
import pydicom
from glob import glob
def computeSliceSpacing(alldcm):
try:
if len(alldcm)>1:
ds0 = pydicom.dcmread(alldcm[0], force = False, defer_size = 256, specific_tags = ['SliceLocation'], stop_before_pixels = True)
... |
import h5py
import numpy as np
from matplotlib import pyplot as pypl
import itertools
def plot_cross_distribution(dx, dy, dx0, dy0, rmax, ds, filename_png=None):
dx_flat = list(itertools.chain.from_iterable(dx))
dy_flat = list(itertools.chain.from_iterable(dy))
ranges = [[-rmax-0.5, rmax+0.5], [-0.5, rmax+... |
# Copyright 2020 Huawei Technologies Co., Ltd
# 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... |
import logging
import typing as t
from collections import Counter
from functools import cmp_to_key
from gkeep.query import Query
from gkeep.status import status
from gkeep.thread_util import background
from gkeep.util import NoteType, escape
from gkeepapi import Keep, exception
from gkeepapi.node import Label, TopLeve... |
# -*- coding: utf-8 -*-
from __future__ import division
from builtins import range
import numpy as np
from scilpy.tractanalysis.quick_tools import (get_next_real_point,
get_previous_real_point)
def get_streamline_pt_index(points_to_index, vox_index, from_start=True):
... |
# This is the script to run the Streamlit mini-app.
from pickle import TRUE
import streamlit as st
import spacy
from spacy import displacy, load
import re
import csv
# Page title and icon for the browser bar
st.set_page_config(
page_title="NER for SG Locations",
page_icon="🇸🇬",
)
# Makes the app width th... |
import time
import micropython
import machine
from pyb import ADC, I2C, LCD, Pin, delay
micropython.alloc_emergency_exception_buf(100)
# Following values were obtained by experimenting with the moisture sensor
DRY_DIRT = 3163 # Determined by experimenting with the moisture sensor
SOAKING_DIRT = 1630 # Determined by e... |
"""
This module has the code to infer PSF models.
Interface:
classes should be parametrized by, at least, flux and
centroid positions, which should be of type tf.Variable.
TODO:
"""
import math
from astropy.io import fits as pyfits
from lightkurve.utils import channel_to_module_output
import numpy as np
imp... |
#-----------------------------------------------------------------------------
# Name: SGMLParser.py
# Purpose:
#
# Author: <NAME>
#
# Created: 2008/08/07
# RCS-ID: $Id: SGMLParser.py $
# Copyright: (c) 2008
# Licence: All Rights Reserved
#--------------------------------------... |
# Copyright (c) <NAME>, <NAME> and Unlock contributors.
# 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 copyright notice,
# this ... |
import logging
import sqlite3
from datetime import datetime
from typing import Any, List, Optional, Tuple, Union
import workers
logger = logging.getLogger(__name__)
def exec_select(
query: str, parameters: Tuple[Union[str, int], ...] = ()
) -> List[Tuple[Any, ...]]:
assert query.startswith("SELECT")
ass... |
import numpy as np
from math import factorial
def f(p,k,d):
return k[:-1]/(k[1:]+p*d[1:])
# f has one elements rest than the rest
def sumfact(p,beta,r,k,d):
s = np.zeros(len(k)-1)
for j in range(p):
s = s + factorial(p)/factorial(j)*beta[1:]**(p-j-1)*factorial_moment(j,beta,r,k,d)[1:]
... |
import lmfit
from kid_readout.analysis import fitter
import numpy as np
from matplotlib import pyplot as plt
def single_pole(f, fc):
return 1 / (1 + 1j * (f / fc))
def single_pole_noise_model(params, f):
A = params['A'].value
fc = params['fc'].value
nw = params['nw'].value
return A * np.abs(singl... |
import os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
# For replicating the experiments
SEED = 42
import argparse
import time
import random
import numpy as np
import scipy.sparse as sp
import torch
np.random.seed(SEED)
torch.manual_seed(SEED)
from torch import optim
import... |
# this is the exercise 1 of HW3
class PyList(list):
def __init__(self, content=[], size=20):
self.items = [None] * size
self.numItems = 0
self.size = size
for e in content:
self.append(e)
def __contains__(self, item):
for i in range(self.numItems):
... |
import argparse
import os
import sys
from typing import AnyStr, Set
from fileutils import directory_is_empty, duplicate_found, extension_filter_builder, \
path_blacklist_builder, derive_filtered_file_iter, derive_filtered_empty_directory_iter, file_iter, \
empty_directory_iter, FileCandidate, sizeof_fmt
from h... |
"""Infer population parameters along the red giant branch, in bins of LOGG"""
# Standard library
import os
from os import path
import sys
# Third-party
import numpy as np
from schwimmbad import choose_pool
# Project
from hq.log import logger
from hq.script_helpers import get_parser
from helpers import get_metadata,... |
import re
import shutil
import subprocess
import tempfile
from pathlib import Path
from common import check_poplog_commander, run_poplog_commander
from typing import Optional
import pytest
LDD: Optional[str] = shutil.which("ldd")
class TestCommands:
def test_pop11(self):
assert check_poplog_commander("p... |
import numpy as np
import pytest
from sklearn.metrics import f1_score, accuracy_score
from sklearn.model_selection import KFold
from sklearn.pipeline import Pipeline
from sklearn_porter import Porter
#classifiers
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.tree import DecisionTreeClass... |
import math
import numpy as np
import tensorflow as tf
from configs import cfg
from src.dataset import Dataset, load_sick_data
from src.evaluator import Evaluator
from src.graph_handler import GraphHandler
from src.perform_recorder import PerformRecoder
from src.utils.file import load_file, save_file
from src.utils.r... |
'''
R-matrix model
Analyzing 3He(alpha, gamma) data
* capture
* scattering (SONIK)
'''
import numpy as np
from scipy import stats
from brick.azr import AZR
import constants as const
input_filename = __name__ + '.azr'
azr = AZR(input_filename)
azr.ext_capture_file = 'output/intEC.dat'
azr.root... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
deeplabv3
3d deeplabv3-derived model for synthesis or segmentation
Author: <NAME> (<EMAIL>)
Created on: December 31, 2019
"""
__all__ = ['DeepLab3d']
import torch
from torch import nn
import torch.nn.functional as F
from ..learn import *
from .unet_tools import *
... |
"""
File: __init__.py
-----------------
The Flask application endpoints which integrate with Slack to post the stories
in the #stories channel.
"""
import os
from functools import partial
import random
from typing import TypedDict, List, Union
import requests
import sys
from flask import Flask, send_from_directory, r... |
from .token import Token
from .token_type import TokenType
from .errors import ScannerError
def default_error_handler(line, message):
print(f'Line[{line}] Error: {message}')
raise ScannerError('Scanner error')
class Scanner:
def __init__(self, source, report=default_error_handler):
self._source ... |
#!/usr/bin/env python
"""Static site generation for help.rerobots.net
SCL <<EMAIL>>
Copyright (C) 2018 rerobots, Inc.
"""
from datetime import datetime
import sys
from markdown.extensions.toc import TocExtension
from markdown import markdown
PREFIX="""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
... |
from click.testing import CliRunner
import os
import numpy as np
import pytest
def test_per_translation_false_positive_rate():
from orpheum.index import per_translation_false_positive_rate
n_kmers_in_translation = 14
n_total_kmers = 4e7
test = per_translation_false_positive_rate(n_kmers_in_translatio... |
# This module is to be deprecated along with Func.
'''A conditional function is a functional wrapper that describes the
dependence of an about output RF with respect to an input RF or the
by the dependence of a subgroup of RVs with respect to the others.
'''
import collections
from probayes.rv import RV
from probayes... |
import logging
import torch
import torch.nn as nn
import numpy as np
from helperbot.bot import BaseBot
from .rnn_stack import RNNStack
from .embeddings import BasicEmbeddings
class RNNLanguageModel(nn.Module):
def __init__(self, embeddings: BasicEmbeddings, rnn_stack: RNNStack, tie_weights: bool = True):
... |
#!/usr/bin/env python3
"""
Tic Tac Toe for two players.
• 2 players should be able to play the game (both sitting at the same computer)
• The board should be printed out every time a player makes a move
• You should be able to accept input of the player position and then place a symbol on the board.
It has been sugges... |
import argparse
import numpy as np
import tensorflow as tf
import time
import pickle
import maddpg.common.tf_util as U
from maddpg.trainer.maddpg import MADDPGAgentTrainer
import tensorflow.contrib.layers as layers
def parse_args():
parser = argparse.ArgumentParser("Reinforcement Learning experiments for multiage... |
#!/usr/bin/env python3
# This file is part of datacube-ows, part of the Open Data Cube project.
# See https://opendatacube.org for more information.
#
# Copyright (c) 2017-2021 OWS Contributors
# SPDX-License-Identifier: Apache-2.0
import json
import sys
import click
from datacube import Datacube
from deepdiff import... |
from typing import Union, Any, Dict, List
import requests
from requests import HTTPError
from auri.effects import Effect
class AuroraException(Exception):
pass
class Aurora:
"""Wrapper for a single Nanoleaf Aurora device"""
def __init__(self, ip_address: str, name: str, mac: str, auth_token: Union[st... |
import numpy as np
from config import config
import os
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
def saliencyMap(model, inputSignals: np.ndarray, groundTruth: np.ndarray, loss: str, layer: int = -1, normalizeBool: bool = True) -> np.ndarray:
if config['framework'] == 'tensorf... |
import tensorflow as tf
import numpy as np
def kernel_generator(x_gen, size=(36, 64, 1), phase_shifted=False):
"""Generator for sample images (e.g. proxy for MEIs)
This will infer the dimensionality of the latent space to create images, using
a default if there is less
dim1 - orientation
dim2 - ... |
import tensorflow as tf
from tensorflow.contrib import slim
from builders import frontend_builder
import numpy as np
import os, sys
# Use bilinear interpolation to adjust images to a fixed size
def Upsampling(inputs,scale):
return tf.image.resize_bilinear(inputs, size=[tf.shape(inputs)[1]*scale, tf.shape(inputs)[2... |
""" Statistical algorithms for TuneCapsule
Copyright (c) 2021 IdmFoundInHim, under MIT License
"""
import sqlite3 as sql
from datetime import date, timedelta
from collections.abc import Iterable
from .utilities import list2strray, read_rows, sql_array
__all__ = ["cumulative_artist_score", "snapshot_artist_score"]
... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import range
from builtins import int
from builtins import open
from builtins import str
from future import standard_library
from configparser import ConfigP... |
import datetime
import time
from logging import DEBUG, Formatter, StreamHandler, getLogger
from typing import List
import click
from src.db import cruds, schemas
from src.db.database import get_context_db
logger = getLogger(__name__)
logger.setLevel(DEBUG)
formatter = Formatter("[%(asctime)s] [%(process)d] [%(name)s]... |
import numpy as np
import matplotlib.pyplot as plt
import gpflow
def dbtime(X):
x1 = X[:,0]
x2 = X[:,1]
return (x1/2-2)*(x1/2-2)+2 + 2*np.sin(x2)+2*np.sin(x2*2)+5+np.sin(x2/2)+2*np.sin(x2)+2*np.sin(x2*2)+5+np.sin(x2/2)
class Optimize():
def __init__(self, func, start_point, nb_param ):
... |
# coding=utf-8
from abc import ABCMeta, abstractmethod
from descriptor_tools.storage import InstanceStorage, protected
__all__ = ['InstanceProperty', 'DelegatedProperty']
_use_default = object()
def _default_of(argument, default_factory):
if argument is _use_default:
return default_factory()
else:... |
import sys, os
from lxml import etree
from edx_gen import _edx_consts
from edx_gen import _process_html
from edx_gen import _css_settings
import __SETTINGS__
#--------------------------------------------------------------------------------------------------
ALL_LANGUAGES = {'en': 'English'}
#---------------------... |
# -*- coding: utf-8 -*-
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own lic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.