content stringlengths 5 1.05M |
|---|
from rest_framework import viewsets, mixins, pagination
from disease_classification.serializers import DiseaseClassificationSerializer
from core.models import DiseaseClassification
class DiseaseClassificationViewSet(viewsets.GenericViewSet,
mixins.ListModelMixin,
... |
#
# tokyoS
# www.fabiocrameri.ch/colourmaps
from matplotlib.colors import LinearSegmentedColormap
cm_data = [[0.10387, 0.056805, 0.20243],
[0.99708, 0.99733, 0.84887],
[0.56301, 0.52969, 0.52511],
[0.46223, 0.27624, 0.42457], ... |
# -*- coding: utf-8 -*-
# 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... |
import pytest
from pymeos import GeomPoint
from pymeos.temporal import (TemporalDuration, TBoolInst, TGeomPointInst,
TIntInst, TBoolInstSet, TGeomPointInstSet,
TIntInstSet)
from ..utils import unix_dt
def get_sample_tinstant_set():
tb1 = TBoolInst(True, ... |
from __future__ import with_statement
from functools import wraps
from StringIO import StringIO # No need for cStringIO at this time
import sys
from nose.tools import raises
from fabric.operations import require
#
# Setup/teardown helpers and decorators
#
def mock_streams(*which):
"""
Replaces ``sys.stderr... |
import requests
import sys
import json
from flask import render_template, flash, redirect, request, session
from flask import Flask
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
from python_terraform import *
app = ... |
import fastapi
from fastapi_chameleon import template
from starlette import status
from starlette.requests import Request
from services import episode_service
from services import transcripts_service
from services import shownotes_service
from viewmodels.shared.viewmodel import ViewModelBase
from viewmodels.admin.adm... |
import os
from time import time
import cv2
import numpy as np
import tensorflow as tf
from tensorflow.python.client import timeline
from graph_supervised_wgan_crn_enc_rand_stack_gru import build_multi_tower_graph, build_single_graph_stage_1, build_single_graph_stage_2
from input_pipeline_rand_mix_stack import build_i... |
Production = True
from bin import app
run=app.app.server
if Production:
PORT = 8050
ADDRESS = '0.0.0.0'
if __name__ == '__main__':
app.app.run_server(port=PORT, host=ADDRESS, debug=False, threaded=True)
else:
PORT = 8050
ADDRESS = '0.0.0.0'
if __name__ == '__main__':
app.app.r... |
import math
import torch
import torch.nn.functional as F
from torch.distributions import Transform, constraints
class CouplingTransform(Transform):
r"""
NICE coupling.
dim = d_residue + d_transform
f : batch x d_residue -> batch x (2*d_transform)
"""
domain = constraints.real
codomain = c... |
# -*- coding: utf-8 -*-
from typing import Optional
from pip_services3_expressions.io.IScanner import IScanner
from pip_services3_expressions.tokenizers.IQuoteState import IQuoteState
from pip_services3_expressions.tokenizers.ITokenizer import ITokenizer
from pip_services3_expressions.tokenizers.Token import Token
fro... |
#!/usr/bin/env python
# coding: utf-8
# # 2020 Cyberinfrastructure for Intelligent Water Supply (CIWS) Data Visualization Challenge
# ### Datasets
# * ClassifiedEvents
# * RawData
# #### Import Libraries
# In[1]:
# These libraries are already installed on the Hydroshare Server
import pandas as pd # Data manipu... |
import progressbar as pb
import torch
import time
from sys_monitor import memory_usage_in_megabytes
from ppo_agent import PPOAgent
from model import Actor, Critic
import numpy as np
from collections import deque
def train(env, agent, episodes, max_t, print_every, logger, checkpoints_dir):
widget = ['training loop... |
import re
class Generator:
def __init__(self, link, start, end):
self.link = link
self.start = start
self.end = end
self.validate()
def loop(self):
#Iterates over numbers from start to end
for episode in range(self.start, self.end+1):
#Print out links for all episodes
self.generate(episode)
... |
from flask import json, Flask, render_template, request, Response
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__) # we create an instance of the Flask class with our module name
app.secret_key = "secret key" # for encrypting sessions; don't wor... |
"""
.. module:: view_augmented_images
:synopsis: Example nuts-ml pipeline for viewing augmented image data
"""
from nutsflow import Take, Consume
from nutsml import ViewImageAnnotation, AugmentImage
if __name__ == "__main__":
from cnn_train import load_samples
train_samples, _ = load_samples()
p = 0.... |
# -*- coding: utf-8 -*-
# Copyright 2016 Mirantis, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version... |
#!/usr/bin/env python
from distutils.core import setup
classifiers =[
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Software Development :: Libr... |
import numpy as np
from ..constants import res_path as res
from ..constants import tol_path as tol
def discretize_bezier(points, count=None, scale=1.0):
'''
Arguments
----------
points: (o,d) list of points of the bezier. The first and last
points should be the start and end of the curv... |
"""tests for vak.config.predict module"""
from configparser import ConfigParser
from pathlib import Path
import unittest
import vak.config.predict
import vak.split
from vak.core.learncurve import LEARN_CURVE_DIR_STEM
HERE = Path(__file__).parent
TEST_DATA_DIR = HERE.joinpath('..', '..', 'test_data')
TEST_CONFIGS_PATH... |
import heapq
import fractions
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp % i == 0:
while temp % i == 0:
arr.append(i)
temp //= i
if temp != 1:
arr.append(temp)
if arr == []:
arr.appe... |
"""
This module defines the class that handles the data loading.
"""
import pandas as pd
# Imports for testing
from KGTorrent import config
class DataLoader:
"""
This class stores the MetaKaggle version tables and the foreign key constraints table.
"""
def __init__(self, constraints_file_path, meta_... |
from .inspector import TrioInspector
|
import click
from .iroha_helpers import *
#ASSET COMMANDS#
def new_asset():
asset = click.prompt("New Asset Name")
domain = click.prompt("Domain")
precision = click.prompt("Precision",type=int)
create_new_asset(asset,domain,precision)
def new_asset_transfer(account_id):
src_account_id = click... |
from app import app
def test_app_returns_200():
# Arrange
client = app.test_client()
# client.testing = True
# Act
result = client.get("/")
# Assert
assert result.status_code == 200
def test_app_page_has_expected_text():
# Arrange
client = app.test_client()
# Act
resul... |
# -*- coding: utf-8 -*-
import numpy as np
from collections import deque
from sortedcontainers import SortedDict
class Buffer(object):
# __slots__ = ('types', 'size', 'batches')
def __init__(self, size):
self.size = size
self.clean()
def clean(self):
self.types = {}
self.batches = []
def get_batche... |
#!/usr/bin/python3
"""
---SUPERMARINE---
* Version 0.3b *
-----------------
Create a mixer geometry blockMesh dictionary for use in
The OpenFOAM toolkits.
Date: 07-2017
Author: Gabriel Lemieux (gabriel.lemieux@usherbrooke.ca)
TARGET : MIXER
-- LOG YOUR TWEAKS HERE ------------... |
"""
Space : O(n)
Time : O(n)
"""
class Solution:
def validMountainArray(self, A: List[int]) -> bool:
temp = []
n = len(A)
for i in range(n):
if i == 0:
temp.append('-')
continue
if A[i] - A[i-1] > 0:
temp.append(... |
import json
class Coupon(object):
"""Loose representation of a coupon - no logic.
This is a coupon - you can add it to an Order (order.add_item) and,
if it fits, get some money off your purchase. I think.
This is another thing that's worth exploring - there are some sweet
coupons that would b... |
#
# Collective Knowledge (QR code)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: cTuning foundation
#
cfg={} # Will be updated by CK (meta description of this module)
work={} # Will be updated by CK (temporal data)
ck=None # Will be updated by CK (initialized... |
from ..step import Step
from ..resource import Resource
from ..transform import transform_resource
from ..exception import FrictionlessException
from .. import errors
# NOTE:
# Some of the following step use **options - we need to review/fix it
# The step updating resource might benefit from having schema_patch argum... |
import os, json
import itertools
from tqdm import tqdm
with open('/home/share/liuyibing/vqa/vqa-cp1.0/qa_path/vqacp_v1_train_questions.json', 'r') as fd:
v1_questions_json = json.load(fd)
with open('/home/share/liuyibing/vqa/vqa-cp1.0/qa_path/vqacp_v1_test_questions.json', 'r') as fd:
v1_questions_json2 = json... |
"""Task Definions for the task of ArmPointNav"""
from typing import Dict, Tuple, List, Any, Optional
import gym
import numpy as np
from allenact.base_abstractions.misc import RLStepResult
from allenact.base_abstractions.sensor import Sensor
from allenact.base_abstractions.task import Task
from ithor_arm.ithor_arm_co... |
#Assignment No. 1...............................................
altitude=int(input("Enter the altitude of the plane ="))
if altitude<=1000:
print("Safe for landing")
elif altitude>1000 and altitude<5000:
print("Bring down to 1000")
elif altitude>5000:
print("Turn around")
#Assignment No. 2...... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
"""
Plot bulk fluxes as a time series.
"""
import os, sys
sys.path.append(os.path.abspath('../alpha'))
import Lfun
import zfun
Ldir = Lfun.Lstart()
sys.path.append(os.path.abspath(Ldir['LO'] + 'plotting'))
import pfun
import numpy as np
import matplotlib.pyplot as plt
import pickle
from datetime import datetime, time... |
import utils
import threading
import requests
class PageDownloader:
def __init__(self, request, event_id):
"""
:param requests request:
:param int event_id:
"""
self.request = request
self.event_id = event_id
def download(self, page):
response = self.r... |
"""Page models."""
from flask_babel import lazy_gettext as _
from app.database import DBItem, db
from app.utils.enums import StringEnum
class PageType(StringEnum):
"""Type of the saved location."""
ABOUT = _("About")
RULES = _("Rules")
SUPPORT = _("Support us")
class Page(DBItem):
"""Pages cont... |
# -*- coding: utf-8 -*-
import shutil
import os
import re
import requests
import urllib2
from pprint import pprint
import bs4
from bs4 import BeautifulSoup
import html2text
import time
import argparse
import datetime
from sys import argv
import time
from selenium import webdriver
from selenium.common.exceptions import ... |
import copy
import doctest
import gc
import os
import sys
import unittest
from tempfile import mkstemp
from pympler import refbrowser
from pympler.util.compat import StringIO
class TreeTest(unittest.TestCase):
# sample tree used in output tests
sample_tree = None
TREE_DEP_1 = """
root-+-branch1
... |
# -*- coding: utf-8 -*-
from django_input_collection.views import CollectorView
from . import collection
class PollView(CollectorView):
template_name = "poll.html"
collector_class = collection.PollTemplateViewCollector
|
from typing import *
from ArithmeticExpression import Operations
class ExpressionEvalulator:
"""
A class to safely evaluate `ArithmeticExpression`s, without any kind of security concern,
like which would be the case using eval(), exec() or similar
"""
@staticmethod
def evaluate(expr... |
#!/usr/bin/python
from os import listdir
from os.path import isfile, join
def CamelCase(str):
return str.replace('_', ' ').title().replace(' ', '')
def WriteEnum(file_name, file_base_name, out, is_binding):
out.write('/*\n* Generated by python\n* Any changes to this file will be overwritten by the next python ru... |
from demography.models import CensusLabel
from rest_framework import serializers
class CensusLabelSerializer(serializers.ModelSerializer):
class Meta:
model = CensusLabel
fields = '__all__'
|
from hks_pylib.logger.standard import StdUsers
from hks_pylib.cryptography.ciphers.hkscipher import HKSCipher
from hks_pylib.cryptography.ciphers.symmetrics import NoCipher
from hks_pylib.logger import LoggerGenerator, InvisibleLoggerGenerator, Display
from csbuilder.client import ClientResponser
from _simulator.prot... |
from django.shortcuts import render
from .models import *
from .serializers import *
import json
from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework.reverse import reverse
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagi... |
import torch
import torch.nn.functional as F
def _weighted_cross_entropy_loss(preds, edges):
""" Calculate sum of weighted cross entropy loss. """
# Reference:
# hed/src/caffe/layers/sigmoid_cross_entropy_loss_layer.cpp
# https://github.com/s9xie/hed/issues/7
mask = (edges > 0.5).float()
b,... |
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
import numpy
import unittest
from pyscf import gto
from pyscf import scf
from pyscf import ao2mo
from pyscf.scf import _vhf
mol = gto.Mole()
mol.build(
verbose = 5,
output = '/dev/null',
atom = '''
O 0 0 0
H 0 -0.757 0.587
H 0 0... |
#!/usr/bin/env python3
import argparse
import re
from os.path import basename
def parse():
parser = argparse.ArgumentParser(
description="The normalizer for maxwell protocol in rust."
)
parser.add_argument("--proto_file", required=True,
type=argparse.FileType("r"))
args... |
APPS = [
{
'name': 'ontherecord',
'num_accounts': 3,
'num_assets': 0,
'ledger': 0,
'payload_func': (
lambda x: {
'app': 'ontherecord',
'content': x
}
)
},
{
'name': 'sharetrader',
'num_acc... |
import json
import boto3
import os
import logging
from botocore.exceptions import ClientError
sqs = boto3.resource("sqs")
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def create_response_headers():
"""
Create response headers
"""
headers = {
"Acce... |
from ..rfc6749.errors import OAuth2Error
# https://tools.ietf.org/html/rfc8628#section-3.5
class AuthorizationPendingError(OAuth2Error):
"""The authorization request is still pending as the end user hasn't
yet completed the user-interaction steps (Section 3.3).
"""
error = 'authorization_pending'
c... |
from collections import deque
from typing import List
import os
import numpy as np
import torch
from unityagents import UnityEnvironment
from dqn_agent import Agent
from utils import Experience, device
from model import DQN
class DQNTrainer:
def __init__(self,
env_filename: str,
... |
import sys
from pyspark import cloudpickle
from pyspark.sql.types import BooleanType
import pandas as pd
import numpy as np
from great_expectations.dataset import PandasDataset
def create_suite():
df = pd.DataFrame()
df['num'] = np.random.randint(0, 10, 100)
df['num2'] = np.random.randint(0, 20, 100)
... |
import numpy as np
from skimage import transform, io, img_as_float, exposure
"""
Data was preprocessed in the following ways:
- resize to im_shape;
- equalize histogram (skimage.exposure.equalize_hist);
- normalize by data set mean and std.
Resulting shape should be (n_samples, img_width, img_heigh... |
import numpy as np
import pandas as pd
import seaborn as sns
import pickle
import matplotlib.pyplot as plt
from sklearn import metrics as m
from utils import write_to_file, unpipe
def get_metrics(true_labels, predicted_labels):
acc = np.round(m.accuracy_score(true_labels, predicted_labels),4)
prec = np.round... |
from string import letters, digits
from random import shuffle
def random_monoalpha_cipher(pool=None):
"""Generate a Monoalphabetic Cipher"""
if pool is None:
pool = letters + digits
original_pool = list(pool)
shuffled_pool = list(pool)
shuffle(shuffled_pool)
return dict(zip(original_poo... |
import pytest
from osdu_commons.clients.rest_client import HttpServerException, HttpNotFoundException
@pytest.mark.usefixtures('smds_data')
def test_list_workflows(workflow_client):
workflows = workflow_client.list_workflows()
assert workflows.batch
@pytest.mark.usefixtures('smds_data')
def test_list_workf... |
# coding=utf-8
from __future__ import absolute_import
from .._compat import to_native
HTTP_SEE_OTHER = 303
def get_full_path(request):
"""Return the current relative path including the query string.
Eg: “/foo/bar/?page=1”
"""
path = request.path
if request.query_string:
path += '?' + to... |
import pytest
from widgetastic.widget import View
from widgetastic_patternfly4.ouia import Navigation
TESTING_PAGE_URL = "https://patternfly-docs-ouia.netlify.app/documentation/react/components/nav"
@pytest.fixture
def view(browser):
class TestView(View):
ROOT = ".//div[@id='ws-react-c-nav-ouia']"
... |
from .hash import Hash
from .heap import Heap
from .ordered_archive import Ordered
from .variable_heap import VLHeap
__all__ = ["Hash", "Heap", "Ordered", "VLHeap"]
|
# coding: utf-8
# Copyright 2016 Capital One Services, 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... |
from __future__ import print_function
from crhelper import CfnResource
from pyqldb.driver.pooled_qldb_driver import PooledQldbDriver
from lib.constants import Constants
from lib.sample_data import convert_object_to_ion, SampleData, get_document_ids_from_dml_results
from lib.connect_to_ledger import create_qldb_session... |
# Souffle - A Datalog Compiler
# Copyright (c) 2022 The Souffle Developers. All rights reserved
# Licensed under the Universal Permissive License v 1.0 as shown at:
# - https://opensource.org/licenses/UPL
# - <souffle root>/licenses/SOUFFLE-UPL.txt
import glob
import os
import shutil
from common import *
args = os.sy... |
#! /usr/bin/env python3
# TODO: Standard configuration directory
# TODO: xdg
# TODO: Registrar
# TODO: SSH-like features: known_hosts, host configs
'''
A simple ffmpeg-based SRTP stream setup tool.
Doesn't have any ambitions of dealing with more complex matters such as
conferencing, NAT traversal, codec negotiation,... |
"""create products table
Revision ID: 79f05cc45ebe
Revises: 3d4d62b34ef9
Create Date: 2021-06-28 13:13:13.406920
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '79f05cc45ebe'
down_revision = '3d4d62b34ef9'
branch_labels = None
depends_on = None
def upgrade()... |
# Copyright 2016 NEC Corporation. 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 ... |
import unittest
from aceql.login_url_decoder import LoginUrlDecoder
class MyUrlTest(unittest.TestCase):
@staticmethod
def test_something():
url = "http://localhost:9090/aceql?username=user1&password=password1&database=sampledb"
login_url_decoder: LoginUrlDecoder = LoginUrlDecoder(url)
... |
#!/usr/bin/env python3
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import json
import orjson
import rapidjson
import simplejson
import ujson
LIBRARIES = ("orjson", "ujson", "rapidjson", "simplejson", "json")
DUMP_TO = ("bytes", "string")
def get_version(library: str) -> str:
if library == "json":
ret... |
'''OpenGL extension EXT.shared_texture_palette
This module customises the behaviour of the
OpenGL.raw.GL.EXT.shared_texture_palette to provide a more
Python-friendly API
Overview (from the spec)
EXT_shared_texture_palette defines a shared texture palette which may be
used in place of the texture object palettes... |
# coding=utf-8
# Copyright 2020 HuggingFace Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# coding:utf8
from flask import Blueprint
home = Blueprint("home", __name__)
import backend.app.home.views # import views.py files
|
v3 = 333
def Sum(value1, value2=200, value3=v3):
return value1 + value2 + value3
v3 = 999
print(Sum(10))
|
from __future__ import absolute_import
import numpy as np
from .Node import Op
from .._base import DNNL_LIB
from ..gpu_links import matrix_multiply
from ..cpu_links import matrix_multiply as cpu_matrix_multiply
class MatMulOp(Op):
def __init__(self, node_A, node_B, trans_A=False, trans_B=False, ctx=None):
... |
# -*- coding: utf-8 -*-
#
"""
websocket - WebSocket client library for Python
Copyright (C) 2010 Hiroki Ohtani(liris)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
ve... |
# -*- coding: utf-8 -*-
import time
import clime
import base64
import requests
import traceback
from pprintpp import pprint as pp
_TEST_URL = 'http://localhost'
#_TEST_URL = 'http://crawl.crs.dianhua.cn'
_TEST_PORT = 8080
# GET
_FLOW_TYPE_URL = '{}:{}/crawl/calls/flow_type?tel={}&uid={}'
_VERIFY_SMS_URL = '{}:{}/cr... |
from functools import wraps
from unittest import TestCase
import asyncio
import concurrent
from unsync import unsync
from unsync.unsync import Unfuture
class DecoratorTests(TestCase):
def test_exception(self):
class TestException(Exception):
pass
@unsync
async def error():
... |
import discord
from discord.ext import commands
import sys
import mysql.connector
sys.path.insert(1, '../')
from config import *
sys.path.insert(1, '../constants')
from colors import *
from constants import *
#MySQL stuff
mydb = mysql.connector.connect(
host= sql.host,
user= sql.user,
passwo... |
import logging
from unittest import TestCase
from parameterized import parameterized, param
from hvac import exceptions
from hvac.tests import utils
class TestApprole(utils.HvacIntegrationTestCase, TestCase):
TEST_MOUNT_POINT = 'approle'
def setUp(self):
super(TestApprole, self).setUp()
sel... |
# Copyright (c) 2018 by the parties listed in the AUTHORS file.
# All rights reserved. Use of this source code is governed by
# a BSD-style license that can be found in the LICENSE file.
import numpy as np
import toast.timing as timing
class GlitchFlagger():
def __init__(self, fwhm=5, threshold=4.0, fsample=18... |
from .base import Model, OrderedCollection
from .user import Member, User
from .room import Room
from ..client.constants import Endpoints
from .. import utils
__all__ = ["Message", "MessageCollection", "Conversation", "ConversationCollection"]
def everything_except(iterable, exception):
return filter(lambda o: o ... |
import pysam
import itertools
# longer genes have more reads aligning to them
# so instead of counting reads, estimate a number of copies of each marker
# this should be proportional to species abundance and agree between markers
# ( and also proportional to sequencing depth - we correct that later if calculating CPM ... |
#!/usr/bin/env python3
"""
Testing simple arithmetic FHE operations using the Python Frontend.
"""
from pyabc import *
import logging
def test_simple_arithmetic():
p = ABCProgram(logging.DEBUG)
with ABCContext(p, logging.DEBUG):
def main(a : NonSecretInt, x = 3):
b = (2 * 6) / x
... |
class TimeError(Exception):
""" Raised when creating a TimePeriod that doesn't work""" |
# Copyright 2016-2020, Pulumi Corporation. All rights reserved.
import pulumi
import pulumi_azure_native.authorization as authorization
import pulumi_azure_native.storage as storage
import pulumi_azure_native.synapse as synapse
import pulumi_azure_native.resources as resources
import pulumi_random as random
config =... |
import os
from .base_logger import BaseLogger
class ModelLogger(BaseLogger):
def __init__(self, tb_logger, log_path, cfg):
super().__init__(tb_logger, log_path, cfg)
self.NAME = 'model'
os.makedirs(self.log_path, exist_ok=True)
self.phase = 'train'
self.current_epoch = -1
... |
from django.conf.urls import url
from django.core.exceptions import FieldError
from tastypie.http import HttpBadRequest
from tastypie.resources import ModelResource, ALL_WITH_RELATIONS
def generate_filtering(mdl):
"""Utility function to add all model fields to filtering whitelist.
See: http://django-tastypie.... |
# Generated by Django 2.1.5 on 2019-01-13 05:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cards', '0005_auto_20190110_1422'),
]
operations = [
migrations.AddField(
model_name='card',
name='img_cover',
... |
# -*- coding: utf-8 -*-
"""
gethbvpars:
gets the HBV catchment parameters from a hbv model. It assules the default
parameters are stored in the root (the basin) and that tuned parameters
are stored in each catchment.
syntax:
gethbvpars -p pathtobasin -o outputfilename
"""
import os.path... |
# from __future__ import print_function # for print() in Python 2
from io import open
import sys
import re
import logging
from pysqlformatter.src.formatter import Formatter
from sparksqlformatter import Style as sparksqlStyle
from sparksqlformatter import api as sparksqlAPI
logger = logging.getLogger(__name__)
log_f... |
from Martel import Dispatch
from Bio import Search, StdHandler
class BuildSearch(Dispatch.Dispatcher):
def __init__(self):
Dispatch.Dispatcher.__init__(self,
prefix = "bioformat:",
remap = {
"bioformat:hit": "bioformat:hi... |
# Joint_lap Object (inheret from Joint class)
# Joint_lap object are used to model variable angle lap joint.
import math
from ast import literal_eval
import compas
from compas.datastructures import Mesh
from compas.geometry import Box, Frame, Point, Line, Transformation, Vector
from compas.geometry import Projectio... |
from json import loads
def saeidi_parser(path):
data = loads(open(path, "r").read())
sentences = [
j
for i in [
[sample["text"]]
* len(
[
opinion
for opinion in sample["opinions"]
if opinion["as... |
# The MIT License (MIT)
#
# Copyright (c) 2018 stanwood GmbH
#
# 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, m... |
import numpy as np
import tensorflow as tf
from gym.spaces.discrete import Discrete
from tensorflow_probability.python.distributions import (
Categorical, MultivariateNormalDiag)
from xagents.base import OnPolicy
class A2C(OnPolicy):
"""
Asynchronous Methods for Deep Reinforcement Learning
https://ar... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: diplomacy_tensorflow/contrib/mpi_collectives/mpi_message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message... |
# Distributed with a free-will license.
# Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
# SHT30
# This code is designed to work with the SHT30_I2CS I2C Mini Module available from ControlEverything.com.
# https://www.controleverything.com/content/Humidity?sku=SHT30_I2... |
import json
import unittest
from lakey_finicity.responses import TransactionsListResponse
EXAMPLE_TRANSACTIONS_RESPONSE = '''
{
"found": 250,
"displaying": 2,
"moreAvailable": true,
"fromDate": 1417045583,
"toDate": 1422316026,
"sort": "desc",
"transactions": [
{
"id": 805353,
"amount": -59.56... |
#! /usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, 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:
#
# * Redistributions of source cod... |
import asyncio
import aiohttp
from
class Client:
def __init__(self, addr):
self.addr = addr
async def post(self, path, data):
# XXX: url join
url = f"{self.addr}/{self.path}"
async with aiohttp.ClientSession() as session:
return await session.post(url, data)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.