content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
#
# Copyright 2020 Soni L.
#
# 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 python
# encoding: utf-8
#
# This file is part of waf-tools.
#
# Copyright (c) 2020, 2021, 2022 Bernardo Fichera <bernardo.fichera@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software")... |
import timeit
def fibonacci(n, cache=None):
if n == 0:
return 1
if n == 1:
return 1
if cache is None:
cache = {}
if n in cache:
return cache[n]
result = fibonacci(n - 1, cache) + fibonacci(n - 2, cache)
cache[n] = result
return result
def fib(n):
a = 1
... |
# coding=utf-8
import torch
import torch.nn.functional as F
from torch import nn
from torchvision.models import *
__all__ = ['PSPNetVGG16', 'PSPNetVGG16BN', 'PSPNetVGG19', 'PSPNetVGG19BN']
class PSPModule(nn.Module):
def __init__(self, in_channels, out_channels=1024, pool_factors=(1, 2, 3, 6), batch_norm=True):... |
"""
This module contains classes for both RSS and Atom feeds. To use these, you'll
need to set up a couple of URL patterns; e.g.
from blargg.feeds import RSSEntriesFeed, AtomEntriesFeed
urlpatterns = patterns('',
(r'^feed/rss/$', RSSEntriesFeed()),
(r'^feed/atom/$', AtomEntriesFeed()),
)
... |
# e.g. image_url -> imageUrl
def camelify(s):
s = list(s)
indices_with_underscore = [i for i, ltr in enumerate(s) if ltr == "_"]
for i in indices_with_underscore:
if i + 1 < len(s):
s[i + 1] = s[i + 1].upper()
return "".join([c for c in s if c != "_"])
def camelify_dict(d):
new... |
__author__ = "Nghia Doan"
__copyright__ = "Copyright 2021"
__version__ = "0.2.0"
__maintainer__ = "Nghia Doan"
__email__ = "nghia71@gmail.com"
__status__ = "Development"
import re
class PostProcessor(object):
"""
PostProcessor receives document and nested objects, described in detailed
here https://stan... |
#
# PySNMP MIB module HP-REF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/michal/.snmp/mibs/HP-REF-MIB
# Produced by pysmi-0.3.4 at Tue Apr 7 12:27:09 2020
# On host LogicAir-MacBookAir.local platform Darwin version 19.4.0 by user michal
# Using Python version 3.7.3 (default, Mar 6 2020, 22:34:30)
#
... |
# Target Sum
# The original problem statement is equivalent to:
# Find a subset of nums that need to be positive, and the rest of them negative, such that the sum is equal to target.
# Let P be the positive subset and N be the negative subset, then we have:
# sum(P) - sum(N) = target
# => 2 * sum(P) = target + sum(P) +... |
#!/usr/bin/python3
# This script is used to generate the apriltag fullmap
for i in range(1, 8): # col
for j in range(1, 10): # row
tag_id = str((i-1)*9+(j-1)) # generate tag_id
# Uncomment this block if origin is at Tag 62
#
# x_offset = round(.93*(7-i), 2) # round to... |
# Faça um programa que calcule o mostre a média aritmética de N notas.
notas = []
while True:
nota = float(input("Digite o valor da nota (caso queira parar tecle 0): "))
notas.append(nota)
if nota == float(0):
notas.pop()
break
media = sum(notas) / len(notas)
print("A média aritmética de... |
def makeChromFilesDict(chromListFileName, outputFilePath, outputFileNameSuffix):
# Make an output file for each chromosome
chromListFile = open(chromListFileName)
chromFilesDict = {}
for line in chromListFile:
# Iterate through the chromosomes and open a separate output file for each
chromFileName = outputFileP... |
"""This file defines extra_tags to use in django html templates."""
from django import template
register = template.Library()
@register.filter(name='extract')
def extract(list, position):
"""Return the element of list 'list' at position 'position'."""
return list[position]
@register.simple_tag
def def_ele... |
# To run the job:
# easypy vxlan_consistency_check_job.py -testbed_file <testbed_file.yaml>
# Description: This job file shows the Genie Vxlan Consistency checker.
import os
from ats.easypy import run
# All run() must be inside a main function
def main():
# Find the location of the script in relation to the job... |
from datetime import datetime, timedelta
from icalendar import Calendar
CAL_IN_PATH = 'path/to/in_cal.ics'
CAL_OUT_PATH = 'path/to/out_cal.ics'
def timedelta_from_frequ(freq_str, cnt):
if freq_str == 'DAILY':
return timedelta(days=cnt)
elif freq_str == 'WEEKLY':
return timedelta(weeks=cnt)
... |
"""
A mechanism for passing the plugin's arguments to the ``chris_plugin_info`` tool.
"""
import argparse
from chris_plugin.types import ChrisPluginType
from dataclasses import dataclass
from typing import Optional, List
@dataclass
class PluginDetails:
"""
Metadata about a *ChRIS* plugin which cannot be infe... |
"""Defines the class that represents running job executions"""
from __future__ import unicode_literals
import datetime
import logging
import threading
from django.utils.timezone import now
from error.models import get_builtin_error, get_unknown_error
from job.execution.tasks.json.results.task_results import TaskResu... |
"""
Utility code taken from:
https://classes.cs.uchicago.edu/archive/2019/winter/30122-1/pa/pa4/index.html
"""
import urllib.parse
import requests
def get_request(url):
'''
Open a connection to the specified URL and if successful
read the data.
Inputs:
url: must be an absolute URL
Outputs... |
""" Retrieves demo call metadata and uploads it into dynamodb table
Assumes metadata for demo files exists in 'demo.rightcall/metadata' s3 bucket location in JSON
format:
{
"demo_metadata":
{"referenceNumber": "3c9153TVd10403", "date": "2019-01-14 14:40:35", "length": 220, "s... |
# Color Schemes for Abaqus/CAE contour plot
# compatible with Abaqus >= 6.14-1
# author: Xiaojun GU
#Greys
from abaqus import *
from abaqusConstants import *
session.Spectrum(name="Greys", colors =(
'#ffffff',
'#f0f0f0',
'#d9d9d9',
'#bdbdbd',
'#969696',
'#737373',
'#525252',
'#252525',
... |
"""
创建自定义类MyRange类,实现下列效果
for number in MyRange(5):
print(number)
"""
class MyRange:
def __init__(self, begin_num=0, end_num=0, step=1):
self.begin_num = begin_num
self.end_num = end_num
self.step = step
self.my_range = (self.begin_num, self.end_num, self.step)
def __iter_... |
kategoriler={'kitap':{'roman', 'şiir', 'çizgiroman', 'hikaye'},
'kulaklık':{'kulakiçi', 'kulaküstü', 'bluetooth', 'spor'},
'oyuncaklar':{'peluş', 'lego', 'arabalar', 'bebekler'},
'müzik':{'yerlialbüm', 'yabancıalbüm', 'çocukalbüm', 'karaoke'},
'film':{'korku', 'dram',... |
from django.urls import path
from .views import UserRegisterView , UserEditView, PasswordsChangeView, ShowProfileView,EditProfilePageView, CreateProfilePageView
# from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('register/',UserRegisterView.as_view(),name='register'),
... |
from pypboy import BaseModule
from pypboy.modules.items import weapons
from pypboy.modules.items import apparel
from pypboy.modules.items import aid
from pypboy.modules.items import misc
from pypboy.modules.items import ammo
import pygame
import config
import datetime
class Module(BaseModule):
label = "ITEMS"
GPIO... |
from importlib import import_module
from pydcop.algorithms import AlgorithmDef, ComputationDef, load_algorithm_module
from pydcop.computations_graph.constraints_hypergraph import \
VariableComputationNode
from pydcop.dcop.objects import Variable
|
import win32gui
import win32api
from win32.lib import win32con
import time
import win32process
import datetime
import win32ui
from tdx import stockListWin
from pc import Mouse
POS_DIFF={
u'系统':[34,9],
u'盘后数据下载':[87,248],
u'同步':[18,57],
u'上传自选股':[20,77]
}
class Menus:
def __init__(self, x, y):
... |
### DDPG Hopper Config ###
env = {"name": "hopper_mlagent", "time_scale": 12.0}
agent = {
"name": "ddpg",
"actor": "deterministic_policy",
"critic": "continuous_q_network",
"gamma": 0.99,
"buffer_size": 50000,
"batch_size": 128,
"start_train_step": 2000,
"tau": 1e-3,
"lr_decay": Tr... |
import localserv
print localserv.serverrunner()
|
with open("input.txt") as x:
card, door = x.read().strip().split("\n")
card, door = [int(n) for n in [card, door]]
csn, dsn = 7, 7
cls, dls = 0, 0
cx, dx = 1, 1
while cx != card:
cx *= csn
cx %= 20201227
cls += 1
for i in range(cls):
dx *= door
dx %= 20201227
print(dx)
|
import pytest
from assertpy import assert_that
import year2015.day03.reader as reader
import year2015.day03.solver as solver
@pytest.mark.parametrize('puzzle, expected',
[('>', 2),
('^>v<', 4),
('^v^v^v^v^v', 2)])
def test_examples_a(puzzle... |
# -*- coding: utf-8 -*-
import numpy as np
import networkx as nx
def get_nx_graph(wds, mode='binary'):
junc_list = []
for junction in wds.junctions:
junc_list.append(junction.index)
G = nx.Graph()
if mode == 'binary':
for pipe in wds.pipes:
if (pipe.from_node.index in junc_l... |
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('requirements.txt') as f:
required_packages = f.readlines()
setup(name='hivemind',
version='0.1',
description='A fork of Bees With Machine Guns to make it useful for more arb... |
import unittest
import numpy as np
from functools import partial
from scipy import stats
import sympy as sp
from pyapprox.univariate_polynomials.quadrature import \
gauss_jacobi_pts_wts_1D, gauss_hermite_pts_wts_1D, \
clenshaw_curtis_pts_wts_1D, leja_growth_rule, \
constant_increment_growth_rule
from pyapp... |
import socket
from typing import Any
from .compat import httplib
from .http import BasePathMixin
class UDSHTTPConnection(BasePathMixin, httplib.HTTPConnection):
"""An HTTP connection established over a Unix Domain Socket."""
# It's "important" to keep the hostname and port arguments here; while there are no... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Munges the output from Standardese to generate the reference API
# docs in the Outcome website
# (C) 2017 Niall Douglas http://www.nedprod.com/
# Created: Dec 2017
from __future__ import print_function
import os, subprocess, shutil, re, sys
items = {
'doc_outcome.md' ... |
class D(dict):
def __getattr__(self, k):
return dict.__getitem__(self, k)
test = D()
|
import shutil
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from typing import List
from snakemake.rules import expand
from cgr_gwas_qc.parsers import sample_sheet
from cgr_gwas_qc.typing import PathLike
from cgr_gwas_qc.workflow.scripts import gtc2plink, plink_merge
def main(
samp... |
"""
Matrix Client
"""
import logging
from .api import MatrixHttpApi
from .errors import MatrixRequestError, MatrixUnexpectedResponse
from .room import Room
logger = logging.getLogger(__name__)
class MatrixClient(object):
"""
The client API for Matrix. For the raw HTTP calls, see MatrixHttpApi.
Args:
... |
from django.urls import path
from django.contrib.auth.decorators import login_required
from .views import ServerInputCreateView, \
ServerInputUpdateView, \
ServerInputDetailView, \
ServerInputListView
app_name = 'serverinput'
urlpatterns = [
path('create/',
login_required(ServerInputCreateVi... |
from utilities import get_binary_mnist_one_batch, format_duration_with_prefix
from timeit import default_timer as timer
import torch
def compute_accuracy(yhat, y):
valid_N = y.shape[0]
return 1 - (torch.round(yhat) - y).abs().sum() / valid_N
# Get training and validation data loaders for classes A and B
dat... |
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from django.conf import settings
from django.db.models import Q
from django.utils import translation, timezone
from django.utils.translation import ugettext as _
from django.utils.translation import... |
import asyncio
asyncio.get_event_loop().run_forever()
# windows run not exit bug |
from .db import db
class Ingredient(db.Model):
__tablename__ = 'ingredients'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), nullable=False)
type_id = db.Column(db.Integer, db.ForeignKey(
"ingredient_types.id"), nullable=False)
created_at = db.Column(db.DateT... |
from ..utils import Object
class LoginUrlInfoOpen(Object):
"""
An HTTP url needs to be open
Attributes:
ID (:obj:`str`): ``LoginUrlInfoOpen``
Args:
url (:obj:`str`):
The URL to open
skip_confirm (:obj:`bool`):
True, if there is no need to show an o... |
"""Ensure there's only one scheduler instancing running."""
import logging
from apscheduler.schedulers import tornado as apscheduler_tornado
from ndscheduler import constants
from ndscheduler import job
from ndscheduler import settings
from ndscheduler import utils
logger = logging.getLogger(__name__)
class Singl... |
from typing import List, Dict
import spvsdkpy as spv
from tool import ctprint
from datetime import datetime
import json
import time
class SubWallet(object):
def __init__(self, pysubwallet: spv.PySubWallet, master_wallet_id):
self._master_wallet_id = master_wallet_id
self._py_subwallet = pysubwalle... |
import datetime
import decimal
import os
import logging
import copy
import json
from tableschema_sql import Storage
from sqlalchemy import create_engine
from tableschema.exceptions import ValidationError
from ...base import ResourceWrapper
from .dumper_base import DumperBase
def jsonize(obj):
return json.dump... |
#MenuTitle: Print about Letterink
# -*- coding: utf-8 -*-
#Edit by Tanukizamurai
__doc__="""
Letterinkに関する設定値を出力します。
"""
font = Glyphs.font
Glyphs.clearLog()
#AngleInDegrees : x軸方向(右)を0°とする回転角度の、マスターからの差分
#MainAxisWidth : 楕円のx軸(横軸)方向の直径の、マスターからの差分
#MinorAxisWidth : 楕円のy軸(縦軸)方向の直径の、マスターからの差分
#ValidForParentMainAx... |
import asyncio
import logging
from athome.api import mqtt
from pylgtv import WebOsClient
WEBOSTV_IP = '192.168.1.131'
TV_TOPIC = 'tv/0'
LOGGER = logging.getLogger(__name__)
g_mute = None
g_volume = None
g_app = None
tv = WebOsClient(WEBOSTV_IP)
async def task_poll(loop):
while True:
try:
c... |
# from django.test import TestCase
# from rest_framework.test import APIClient
# from rest_framework import status
# from django.urls import reverse
# from django.test import TestCase
# import unittest
#
# # Create your tests here.
# # class UnitTest(unittest.TestCase):
# # def test(self):
# #
# # self.asse... |
# Generated by Django 2.1.3 on 2019-02-09 13:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('services', '0006_remove_service_project'),
('apps', '0005_app_project'),
]
operations = [
migration... |
'''
utility functions related to training
'''
from copy import deepcopy
import numpy as np
from causalnex.discretiser import Discretiser
from configs import config as cf
def calculate_splits_chunks(array,
n_splits=cf.n_levels,
remove_nonzero=True):
'''
... |
# Copyright (C) 2021 Freie Universität Berlin
#
# Distributed under terms of the MIT license.
import iotlab_controller.constants
def test_iotlab_domain():
assert hasattr(iotlab_controller.constants, 'IOTLAB_DOMAIN')
|
"""
================
Stimuli Delivery
================
The stimuli delivery consist in a reimplementation of `Brython-Radiant
<https://radiant-framework.readthedocs.io/en/latest/>`_ with some renames and a
preconfigured server.
"""
import os
import sys
import logging
import json
import socket
from radiant.server imp... |
import datetime
import json
import os
import click
AMI_MAP = {
"us-east-2": os.environ.get("AWS_AMI", None),
}
def highlight(x):
if not isinstance(x, str):
x = json.dumps(x, sort_keys=True, indent=2)
click.secho(x, fg='green')
def make_disable_hyperthreading_script():
return """
# disable ... |
import frontend.debug
import frontend.basic
import frontend.fancy
FRONTENDS = {
"debug" : frontend.debug.FrontEnd,
"basic" : frontend.basic.FrontEnd,
"fancy" : frontend.fancy.FrontEnd,
}
|
# -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE... |
import pysam
import sys
import glob
import os
def main(args):
read_partition = {}
read_to_ctgs = {}
fn = "./3-unzip/read_maps/rawread_to_contigs"
rid_to_oid = open("2-asm-falcon/read_maps/raw_read_ids").read().split("\n")
with open(fn) as f:
for row in f:
row = row.strip().spli... |
r""""Contains definitions of the methods used by the _BaseDataLoaderIter workers to
collate samples fetched from dataset into Tensor(s).
These **needs** to be in global scope since Py2 doesn't support serializing
static methods.
"""
import torch
import re
from torch._six import container_abcs, string_classes, int_cla... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import unittest
from cuddlefish.property_parser import parse, MalformedLocaleFileError
class TestParser(unittest.TestC... |
import urlparse
import warnings
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.test.utils import override_settings
import providers
from allauth.tests import MockedResponse, mocked_response
from models import SocialApp
def creat... |
import partio,sys,os
import numpy as np
def partio_uncompress(dirname):
"""Take a folder of compressed .bgeo files and uncompress those files.
This can come in handy because SPlisHSPlasH stores it's particle data
as compressed .bgeo files.
Args:
dirname: Path to a directory of .bgeo files.
... |
from time import sleep
def ajuda(msg):
print('\33[31m' + ("--" * 20) + '\33[m')
print(f"{'Sitema de ajuda dp Python':-^40}")
print('\33[31m' + ("--" * 20) + '\33[m')
print("Buscando dados")
sleep(2)
help(msg)
print("PRONTO!!")
comando = ''
while True:
comando = input("Digite um coman... |
import pytest
from naucse_render.load import read_yaml, _read_yaml
def test_read_yaml(tmp_path):
yaml_path = tmp_path / 'test.yaml'
yaml_path.write_text("""data:
- 1
- 2
- 3
""")
assert read_yaml(tmp_path, 'test.yaml') == {'data': [1, 2, 3]}
def test_read_yaml_uses_cache(tmp... |
# -*- coding: utf-8 -*-
#==========================================
# Title: syntheticFunctions.py
# Author: Binxin Ru and Ahsan Alvi
# Date: 20 August 2019
# Link: https://arxiv.org/abs/1906.08878
#==========================================
import numpy as np
# ==================================================... |
from .config.config import Config
from .termui.alignment import TopLeftAnchor, Dimension, CenterAnchor
from .session import Session
from .termui.bar_graph import BarGraph
from .termui.color import Color, Palette8Bit
from .termui.control import Border, BorderStyle
from .termui.dialog import DialogControl
DefaultAnchor ... |
from __future__ import print_function
import FWCore.ParameterSet.Config as cms
process = cms.Process('CALIB')
process.MessageLogger = cms.Service("MessageLogger",
debugModules = cms.untracked.vstring("*"),
log = cms.untracked.PSet(threshold = cms... |
''' builders/__init__.py
@authon
ashon
@date
2014-08-26 ~
'''
import json
import traceback
class HighchartJsonBuilderException(Exception):
'''
HighchartJsonBuilderException
'''
def __init__(self, code, msg=''):
super(HighchartJsonBuilderException, self).__init__(code)
... |
import importlib
import inspect
import os
import platform
import stat
import sys
from io import BytesIO
from tarfile import TarFile
import cloudpickle
from pkg_resources import find_distributions, DistributionNotFound
from setuptools import sandbox
from hunchsdk.storage_clients.get_storage_client import get_storage_cli... |
from mantid.simpleapi import *
import sys
thisdir = os.path.abspath(os.path.dirname(__file__))
if thisdir not in sys.path:
sys.path.insert(0, thisdir)
def mantid_reduction(nexus_file, binning):
sim=Load(nexus_file)
I_d=ConvertUnits(sim, Target='dSpacing', AlignBins=True)
sum_I_d=SumSpectra(I_d)
h... |
from openpyxl import *
from datetime import *
#No caso desta planilha, este dicionario relaciona numeros com letras referente a coluna
def buscaCol():
#Busca o dia em que o script foi executado e retorna para quem chamou
dia = datetime.today().day
dias = {1: 'C', 2: 'D', 3: 'E', 4: 'F', 5: 'G', 6: 'H', 7: ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
res = []
for i in xrange(numRows):
res.append([1]*(i+1))
for j in xrange(i+1):
if j>0 and j<i:
res[i][j] = res[i-1][j-1]+res[i-1][j]
return res |
print('Manipulating tables')
import astropy.table as table
#from defcuts import *
import math
import numpy as np
indir='/Users/amandanewmark/repositories/galaxy_dark_matter/GAH/'
#if need to rewrite deg_vespa
def my_rad2deg():
datatab = table.Table.read(indir+'vespa_HR_GAMA15.fits')
def rad2deg(data, ra_col):
... |
from sympy import *
from tait_bryan_R_utils import *
x, y, z = symbols('x y z')
px, py, pz = symbols('px py pz')
om, fi, ka = symbols('om fi ka')
point = Matrix([x, y, z, 1]).vec()
position_symbols = [px, py, pz]
orientation_symbols = [om, fi, ka]
all_symbols = position_symbols + orientation_symbols
transformation_m... |
import param
from nick_derobertis_site.common.model import ComponentModel
from nick_derobertis_site.landing.components.carousel.carousel_item.carousel_item_model import CarouselItemModel
class CarouselModel(ComponentModel):
item_models = param.List(class_=CarouselItemModel)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-08 15:47
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("video", "0010_auto_20170908_1007")]
operations = [
migrations.AlterModelOptions(
nam... |
import logging
import traceback
from skyline_functions import get_redis_conn_decoded
from functions.database.queries.base_name_from_metric_id import base_name_from_metric_id
def get_base_name_from_metric_id(current_skyline_app, metric_id):
"""
Returns a metric id for a base_name from the
aet.metrics_mana... |
"""
Afterglow Core: user schemas
"""
from datetime import date, datetime
from typing import List as ListType
from marshmallow.fields import Integer, List, Nested, String
from ... import AfterglowSchema, Boolean, DateTime, Resource
__all__ = ['RoleSchema', 'UserSchema']
class RoleSchema(AfterglowSchema):
id: ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Nov 7, 2015
Don't blink...
@author: Juan_Insuasti
'''
import sys
import datetime
from Model import DataLogger
from Shared import Logger
from Broker import Broker
from Model import Base
from Model import AvgFilter
class Sensor(Base.Base):
def __init__(... |
import unittest
import javabridge
import numpy as np
from TASSELpy.TASSELbridge import TASSELbridge
try:
try:
javabridge.get_env()
except AttributeError:
TASSELbridge.start()
except AssertionError:
TASSELbridge.start()
except:
raise RuntimeError("Could not start JVM")
from TASSEL... |
from mako import cache
from mako import filters
from mako import runtime
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1474925155.284777
_enable_loop = True
_template_filename = 'htdocs/as_choice.mako'
_temp... |
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import os.path
from typing import Dict
import setuptools
MODULE_NAME = "sqlitebiter"
REPOSITORY_URL = f"https://github.com/thombashi/{MODULE_NAME:s}"
REQUIREMENT_DIR = "requirements"
ENCODING = "utf8"
pkg_info: Dict[str, str] = {}
def get_re... |
# -*- coding: utf-8 -*-
# Schedule
SCHEDULE_TIME_DELTA = 30 # in seconds (Minimum value 3 sec)
# InfluxDB
INFLUXDB_HOST = 'localhost'
INFLUXDB_PORT = 8086
INFLUXDB_DB = 'home'
INFLUXDB_NAME = ''
INFLUXDB_PASSWD = ''
# Sensors
SENSOR_LOCATIONS_NA = "N/A"
SENSOR_LOCATIONS = {} # key = sensor.id, value = <your senso... |
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,BooleanField,SubmitField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
username = StringField('Username',validators=[DataRequired()])
password= PasswordField('Password',validators=[DataRequired()])
rememb... |
n, m = map(int, input().split())
arr = [[0] * m for i in range(n)]
for i in range(n):
arr[i][0] = 1
for j in range(m):
arr[0][j] = 1
for i in range(1, n):
for j in range(1, m):
arr[i][j] = arr[i - 1][j] + arr[i][j - 1]
[print(*row) for row in arr] |
import os
import sys
import logging
import threading
from flask import Flask
app = Flask(__name__)
app.config.from_envvar("PEGASUS_METRICS_CONFIG")
# This is required for sessions and message flashing
app.secret_key = os.urandom(24)
import pegasus.metrics.views
import pegasus.metrics.filters
|
import unittest
from exabel_data_sdk.client.api.data_classes.prediction_model_run import PredictionModelRun
class TestModelRun(unittest.TestCase):
def test_proto_conversion(self):
model_run = PredictionModelRun(
name="predictionModels/123/runs/4",
description="Test run",
)... |
from app.lib.model import Model
class Brand(Model):
def __init__(self, get_create_table_query=False):
self._get_create_table_query = get_create_table_query
self.create_table_query = None
if self._get_create_table_query is True:
self.create_table_query = self.get_c... |
import json
import secrets
from botocore.exceptions import ClientError
import moto
import pytest
from deploy import ecr
from utils import create_image_manifest
class TestGetRefTagsForImage:
def test_get_nonexistent_image_is_none(self, ecr_client):
"""
Looking up an image that doesn't exist, in a... |
from random import Random
""" Initial version by Raymond Hettinger (@raymondh)
(http://code.activestate.com/recipes/577684-bloom-filter/) """
class BloomFilter:
"""Space efficient, probabilistic set membership tester.
Has no False Negatives but allows a rare False Positive."""
# http://en.wikipedia.org... |
import torch
from mmf.common.sample import Sample
from mmf.datasets.mmf_dataset import MMFDataset
def iou(anchors, gt_boxes):
"""
anchors: (N, 4) ndarray of float
gt_boxes: (K, 4) ndarray of float
overlaps: (N, K) ndarray of overlap between boxes and query_boxes
"""
N = anchors.size(0)
K =... |
from typing import List
class Solution:
def getarea(self, x, y, grid):
count = 0
if grid[x][y] == 0:
return count
move = [[1,0],[-1,0],[0,1],[0,-1]]
count += 1
grid[x][y] = 0
for k in move:
tmpx = k[0]+x
tmpy = k[1]+y
if... |
#!/usr/bin/env python3
"""
Author : treevooor <treevooor@localhost>
Date : 2021-11-20
Purpose: Bottles of beer song
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Bottles of be... |
# importing required packages
import cv2
import time
# defining video path
video_path = r'C:...'
# open video
camera = cv2.VideoCapture(video_path)
# getting frame per second
fps= int(camera.get(cv2.CAP_PROP_FPS))
print("Fps:", fps)
# in case of video path does not open, any device, which your comp... |
"""Energy supply wrapper
"""
import os
from configparser import ConfigParser
from subprocess import check_output
import numpy as np
import psycopg2
import psycopg2.extras
from smif.model.sector_model import SectorModel
try:
from pyinstrument import Profiler # import to enable profiling
except ImportError:
p... |
""" Image classifier module """
import numpy
from bananas.core.mixins import HighDimensionalMixin
from bananas.utils.arrays import shape_of_array
from bananas.utils.images import crop, normalize
from .base import BaseNNClassifier
from .transfer_learning import TransferLearningModel
class ImageClassifier(TransferLe... |
import pytest
def test_testcase_1():
from sourcecode import SourceCode
from testcase import TestCase
sc = SourceCode(path="./evaluation/gcd.py")
sc.create_file()
test = TestCase(input=[12, 10])
test.execute_test_on(sc)
assert test.get_output() == [2]
def test_testcase_2():
from s... |
import json
import time
import network
import urequests as requests
class Wifi:
wlan = None
SSID = "AmongstUsNet"
PASSWORD = "AmongstUs"
URL = "http://192.168.8.100/"
def __init__(self, parent):
self.parent = parent
# Initialize wlan object
self.wlan = network.WLAN(networ... |
#!/usr/bin/env python
import h5py
import numpy as np
ltype = "chain"
L = 6
filename="alpsraw/spectra.{}.{}.task1.out.h5".format(ltype, L)
spectrum = []
with h5py.File(filename, "r") as f:
for key in f["spectrum"]["sectors"].keys():
sector = f["spectrum"]["sectors"][key]
spectrum += list(sect... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.