content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# coding: utf-8
"""
evaluation.py: Code evaluate the results
"""
from utils.data_structure import *
from utils.custom_dataset import CustomDataset
def evalulate_image(prediction, gt_depth_ordering):
with open(gt_depth_ordering) as file:
lines = file.readlines()
n = len(lines)
... |
from django.db import models
# Create your models here.
# thong tin website
class StockInfo(models.Model):
# san
exchange = models.TextField(max_length=10)
# ma chung khoang vd AAA
code = models.TextField(max_length=3)
# ten cua cong ty
name = models.TextField()
# link cong ty
cafef_l... |
#!/usr/bin/env nosetests
# -*- coding: utf-8 -*-
# vim :set ft=py:
from mock import patch, Mock
import nose.tools as nt
from bloscpack import cli
from bloscpack.exceptions import FileNotFound
def test_parser():
# hmmm I guess we could override the error
parser = cli.create_parser()
@patch('os.path.exists'... |
import socket,sys,os
os.system('clear')
host = 'www.dvwa.co.uk'
ip = socket.gethostbyname(host)
open_ports =[]
common_ports = { 21, 22, 23, 25, 53, 69, 80, 88, 109, 110,
123, 137, 138, 139, 143, 156, 161, 389, 443,
445, 500, 546, 547, 587, 660, 995, 993, 2086,
20... |
c = float(input('Entre a temperatura em °C: '))
f = c * 9 / 5 + 32
print('{} °C corresponde a {} °F.'.format(c, f))
input()
|
#!/usr/bin/env python3
import numpy as np
from itypes import File, Path
print()
def test(file, **kwargs):
data = File(f"../data/{file}").read(**kwargs)
cmd = f"File('../data/{file}').read({kwargs}):"
print(f"{cmd:80s} shape={data.shape}, dtype={data.dtype}, min={data.min()}, max={data.max()}")
cmd =... |
"""Named values."""
class NamedValue(object):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return "%r(%s, %s)" % (self.__class__.__name__, self.name, self.value)
def __str__(self):
return self.name
|
import streamlit as st
from src.blockchain_utils.credentials import get_client, get_account_credentials
from src.services.nft_service import NFTService
from src.services.nft_marketplace import NFTMarketplace
from src.repository.nft_repository import NFTRepository
from src.repository.marketplace_repository import NFTMar... |
import numpy as np
from tianshou.data import ReplayBuffer
if __name__ == '__main__':
from env import MyTestEnv
else: # pytest
from test.base.env import MyTestEnv
def test_replaybuffer(size=10, bufsize=20):
env = MyTestEnv(size)
buf = ReplayBuffer(bufsize)
buf2 = ReplayBuffer(bufsize)
obs = e... |
from django.db.models import Count, Avg, Min, Max
from collections import defaultdict
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView, View
from common.models import ReleaseNotes
from common.phylogenetic_tree import PhylogeneticTreeGenerator
from c... |
"""
cclib (http://cclib.sf.net) is (c) 2006, the cclib development team
and licensed under the LGPL (http://www.gnu.org/copyleft/lgpl.html).
"""
__revision__ = "$Revision: 631 $"
from density import Density
from cspa import CSPA
from mpa import MPA
from lpa import LPA
from opa import OPA
from mbo import M... |
# Copyright (c) 2015 Presslabs SRL
#
# 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 writ... |
# 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
# distributed under t... |
import math
import matplotlib.pyplot as plt
points = [(1,3) , (2.3 , 3) , (1.5 , 4.2) , (2.6 , 3.9) , (3,3) , (4,2) , (1.4 , 1.4) , (2,2) , (3.5 , 4),
(7 , 12) , (7,18) , (8.4 , 12.44) , (7.7 , 10) , (10 , 9.4) , (8.8 ,8.8) , (9.2 , 14) , (10,9.8),
(24.6 , 4) , (25 , 5) , (24.9 , 2.39) , (... |
from common import *
os.chdir(EXTERNAL_DIR)
PKGS = env('PKGS', 'all')
ninja_template = read_file(f'{SCRIPT_DIR}/install_deps_{OS_LOWER_CASE}.ninja.in')
write_file(f'install_deps_{OS_LOWER_CASE}.ninja', ninja_template.format(**ENV_PARAMS))
for key, val in ENV_PARAMS.items():
print(f'{key} = {val}')
shel... |
class Affection:
def __init__(self, a_type, value):
self.a_type = a_type
self.value = value
# TODO implement value check mechanism
|
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
url(r'^professional-login/$', auth_views.login, {'te... |
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# justice-platform-service (4.10.0)
# pylint: disabl... |
class PhoneDirectory(object):
def __init__(self, maxNumbers):
"""
Initialize your data structure here
@param maxNumbers - The maximum numbers that can be stored in the phone directory.
:type maxNumbers: int
"""
self.available = {n for n in xrange(0, maxNumbers)}
... |
"""Put user defined tasks in the plugins folder. You can start with
some customizations in this file which is included by default."""
from invoke import task
from ..config import (
TEST_MESSAGE,
SYS_TEST_MESSAGE,
)
@task
def hello(cx):
"""An example custom user task from the plugins."""
print("Hello!... |
from decimal import Decimal
from holobot.sdk.reactive.models import EventBase
from typing import Optional
class SymbolUpdateEvent(EventBase):
def __init__(self, symbol: str, price: Decimal, previous_price: Optional[Decimal]):
if not symbol or len(symbol) == 0:
raise ValueError("The symbol must ... |
##
# Implement idea 2: multi-chromosome version
##
import argparse
parser = argparse.ArgumentParser(prog='impute_otf_multi_chr.py', description='''
Impute parental origin of haplotypes and observed phenotypes.
It takes preloaded phenotypes, covariates, and genotypes
(generated by impute_otf_preload.py)
''... |
from random import random
class Individuo():
def __init__(self, espacos, valores, limite_espacos, geracao=0):
self.espacos = espacos
self.valores = valores
self.limite_espacos = limite_espacos
self.nota_avaliacao = 0
self.espaco_usado = 0
self.geracao = geracao
... |
# import os
import grpc
import time
import spacy
import logging
from concurrent import futures
from servicelayer.rpc.entityextract_pb2 import ExtractedEntity
from servicelayer.rpc.entityextract_pb2_grpc import EntityExtractServicer
from servicelayer.rpc.entityextract_pb2_grpc import add_EntityExtractServicer_to_server ... |
import sys
import os
from perper.model import StreamFlags
from perper.model import State
from perper.model import Context
from perper.services import Serializer
from perper.services import FabricService
from perper.services import PerperConfig
from perper.cache import PerperInstanceData
from perper.utils import PerperT... |
# Copyright 2017 Red Hat, 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.org/licenses/LICENSE-2.0
#
# Unless required by... |
# coding: utf-8
# Copyright 2013 The Font Bakery Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
"""
The #django-dev ticket bot.
"""
from twisted.words.protocols import irc
from twisted.internet import reactor, protocol
from twisted.python import log
import requests
from collections import namedtuple
import os
import re
import sys
ticket_re = re.compile(r'(?<!build)(?:^|\s)#(\d+)')
ticket_url = "https://code.d... |
import ctypes
import sys
import winreg
from ezno_convert.common import here
reg_classes = (
'Word.Document.8',
'Excel.Sheet.8',
'PowerPoint.Show.8',
'Word.Document.12',
'Excel.Sheet.12',
'PowerPoint.Show.12',
'Directory',
# 'Directory\\Background',
)
gui_exe = here.with_name('eznoc-gu... |
# coding=utf-8
from pathlib import Path
from edlm.convert._preprocessor._markdown._images import process_images
from edlm.convert._preprocessor._markdown._include import Context, process_includes
from edlm.convert._preprocessor._markdown._references import process_references
def test_no_include():
ctx = Context(... |
from django.core.management.base import BaseCommand, CommandError
from nbapowerranks.models import Team, Ranking
import json
import re
import sys
class Command(BaseCommand):
help = 'Delete a week\'s data from the DB.'
def add_arguments(self, parser):
parser.add_argument('--week',
actio... |
#===============================================================================================
#Largest palindrome product
#===============================================================================================
#Problem 4
#A palindromic number reads the same both ways. The largest palindrome made from the ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 26 10:22:34 2017
@author: dhingratul
Print elements of a linked list on console
head input could be None as well for empty list
Node is defined as
"""
class Node(object):
def __init__(self, data=None, next_node=None):
self.data =... |
import os
import numpy as np
import obstacle_tower_env
from obstacle_tower_env import ObstacleTowerEnv
from ..common import FrameStack, FrameSkip
from .wrappers import ReducedActionEnv, BasicObstacleEnv, RewardShapeObstacleEnv, BasicObstacleEnvTest
def obstacle_train_env_factory(
index_worker=0, rank=0, frame... |
import os
import pathlib
from .head import replace_head
from .mnistnet import MnistNet
from .cifar_resnet import resnet20, resnet32, resnet44, resnet56, resnet110, resnet1202
from .cifar_vgg import vgg_bn_drop, vgg_bn_drop_100
def model_args(model: str) -> {}:
"""Arguments for torchvision.model constructors"""... |
import www.deferreds as deferreds
from www.handlers.base import BaseHandler
from google.appengine.api import memcache
from google.appengine.ext import deferred
class BaseTaskHandler(BaseHandler):
"""
Provides framework for handling deferred tasks
"""
# the default task result expiration is 1 hour
TASK_EXPIRATI... |
import uvicorn
import subprocess
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from application.initializer import IncludeAPIRouter
from application.main.config import settings
def get_application():
_app = FastAPI(title=settings.API_NAME,
description=settings.... |
import os
from shutil import copyfile
def build(info, site_api):
settings = site_api.get_settings()
partners_json = site_api.get_json('modules/{}/data/partners.json'.format(info['module_name']))
site_api.create_file(info, 'partners.html', '{}/partners.html'.format(settings['output_folder']),
... |
import utils
class Generator(object):
def __init__(self, layouts):
self.layouts = layouts
def run(self, path):
"Begins the template parsing/evaluation and returns the fully evaluated file as a list."
return self.parse_templates(path)
def parse_templates(self, path):
"""
Looks for template syntax on ea... |
f = open('input.txt', 'r')
values = []
for line in f:
if line.strip():
values.append(line.strip())
lens = {0: 6,
1: 2,
2: 5,
3: 5,
4: 4,
5: 5,
6: 6,
7: 3,
8: 7,
9: 6}
# Part 1
easycount = 0
for val in values:
right = val.split('|')[1]
rvals = right.split()
... |
# MIT License
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# Improved by the yongdol503
# 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 with... |
import numpy as np
import cv2
from dst import MassFunction
import tf
from nav_msgs.msg import OccupancyGrid
from geometry_msgs.msg import Quaternion
from std_msgs.msg import Header
from common import occupancy_grid2ndarray
class Map(object):
def __init__(self, dst_universe):
self.origin = None # coords... |
import os
import sys
import time
import glob
import numpy as np
import pickle
import torch
import logging
import argparse
import functools
import random
from maskrcnn_benchmark.modeling.detector.generalized_rcnn import GeneralizedRCNN
from maskrcnn_benchmark.config import cfg
from maskrcnn_benchmark.utils.logger impor... |
from django.contrib import admin
# Register your models here.
from updates.models import Post
admin.site.register(Post) |
from remotelogin.oper_sys.linux.shellcommands import LinuxShellCmds
# TODO: implement base64 upload of base64.sh or write of file on system
class BusyBoxCmds(LinuxShellCmds):
HAS_BASE64 = False
def base64(self, file):
raise NotImplementedError
def base64_encode_to_file(self, file_decoded, base6... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import re
from abc import ABC, abstractmethod
from typing import List, Tuple, Union
from lint.config import LinterConfig
__all__ = ["ILinter"]
class ILinter(ABC):
"""Base class for all the linters"""
def __init__(self, config: LinterConfig) -> None:
... |
A,I=open("inputday20").read().split('\n\n');I,r,l=[[*l.strip()]for l in I.strip().split('\n')],range,len
j,a,C="".join,lambda x:A[int(j([['0','1'][c=='#']for c in x]),2)],[]
E=lambda X,Y:a([I[x][y]if(0<=x<l(I))*(0<=y<l(I[0]))else e for x in r(X-1,X+2)for y in r(Y-1,Y+2)])
p,e=lambda:[[E(a-1,b-1)for b in r(l(I[0])+2)]fo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Small python web application for plotting with Bokeh."""
import base64
import io
from itertools import cycle
import pandas as pd
from bokeh.core.enums import LegendLocation
from bokeh.embed import file_html
from bokeh.io import curdoc
from bokeh.layouts im... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 00:58:53 2018
@author: Lior Reznik
"""
from Tkinter import *
import tkFileDialog
import tkMessageBox
class View:
def __init__(self, main,controller):
self.controller=controller
self.main=main
self.__build
@property... |
from django.contrib import admin
from ltc.controller.models import LoadGenerator, SSHKey
# Register your models here.
admin.site.register(SSHKey)
admin.site.register(LoadGenerator)
|
# coding: utf8
import re
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from collections import defaultdict
import time
def getDomain(url):
url = regexBody.findall(url)[0]
parsed_uri = urlparse( url )
domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
return domain
def co... |
from django.urls import path
from . import views
from core import views as core
from community import views as community
from library import views as library
from ie.urls_baseline import baseline_urlpatterns
from ie.urls_library_baseline import baseline_library_urlpatterns
app_name = "peeide"
# Note: we are loading ba... |
"""Common utilities for AutoEnsemblers.
Copyright 2019 The AdaNet Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unl... |
def main():
n,k,c = map(int,input().split())
s = list(input())
circle = []
for i in range(n):
if s[i] == 'o':
circle.append(i)
pre_number = -c-10
count = 0
front = []
for i in range(len(circle)):
if pre_number+c < circle[i]:
front.append(i)
... |
from __future__ import annotations
import logging
import shlex
from abc import ABC, abstractmethod
from typing import List
from .raw import RawCommand
logger = logging.getLogger(__name__)
__all__ = ["AbstractCommandParser", "ShellCommandParser"]
class AbstractCommandParser(ABC):
"""Base for command parsers.""... |
# Copyright (c) 2022. Harvard University
#
# Developed by Research Software Engineering,
# Faculty of Arts and Sciences, Research Computing (FAS RC)
# Author: Michael A Bouzinier
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
... |
#importing modules to main_code
import matplotlib.pyplot as plt
from functions.function import *
from matplotlib.widgets import Slider,Button # import the Slider widget
print("Welcome !!!")
#print("Enter all the values in the MKS system")
global Phi_m,tox,NA,ND,r,count
#user input
#NA=float(input("Enter the value... |
import unittest
from gingerit.gingerit import GingerIt
class TestGingerIt(unittest.TestCase):
def test(self):
text = 'The smelt of fliwers bring back memories.'
parser = GingerIt()
output = parser.parse(text)
self.assertEqual(
output.get("result"), "The smell of flowe... |
"""
Copyright 2018 Software Reliability Lab, ETH Zurich
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 t... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('mail', '0108_auto_20171130_1004'),
]
operations = [
migrations.AlterModelOptions(
name='relaysenderwhitelist',
... |
# 565. Array Nesting
class Solution:
def arrayNesting2(self, nums):
sets, l = [], [0] * len(nums)
for i in range(len(nums)):
for s in sets:
if nums[i] in s:
l[i] = len(s)
break
if not l[i]:
s = set()
... |
"""
A first simple Cloud Foundry Flask app
Author: Ian Huston
License: See LICENSE.txt
"""
from flask import Flask
from flask import request
import os
import pyhdb
# Downloading pyhdb-0.3.3.tar.gz
import json
import datetime
import Crypto.PublicKey.RSA as RSA
import jws.utils
import python_jwt as jwt
app = Flask(__nam... |
#!/usr/bin/env python
#
# Copyright (c) 2018 SAP SE
# 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
#
# ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-10-01 12:40
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_2020082... |
import string
import os
import json
from pathlib import Path
from vectorian.render.vega import VegaRenderer
from vectorian.render.utils import flow_edges
class MatrixRenderer(VegaRenderer):
_template = None
def __init__(self):
super().__init__()
if MatrixRenderer._template is None:
script_dir = Path(os.pat... |
import asyncio
import os
import traceback
import discord
from discord.ext import commands
from discord import app_commands
from discord.app_commands import AppCommandError, Command, ContextMenu, CommandInvokeError, TransformerError
from extensions import initial_extensions
from utils import cfg, db, logger, GIRContext,... |
import pandas as pd
import math
from generic_operations import get_frequent_ngrams, create_word2vec_model, ngrams, print_to_file, get_proper_string
from nltk.corpus import stopwords
import gensim
from collections import defaultdict
import nltk
import global_variables as v
import global_parameters as p
import sys
def ... |
import os
PG_USERNAME = os.environ.get('PG_USERNAME', 'postgres')
PG_DATABASE = os.environ.get('PG_DATABASE', 'rent_slogan')
PG_PASSWORD = os.environ.get('PG_PASSWORD', '1234')
def connection_url():
return 'postgresql://{}:{}@localhost/{}'.format(PG_USERNAME, PG_PASSWORD,
... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from github.com.metaprov.modelaapi.services.datapipelinerun.v1 import datapipelinerun_pb2 as github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_datapipel... |
import matplotlib
import numpy as np
import pytest
from yt.config import ytcfg
from yt.testing import assert_equal, requires_backend
def test_requires_backend():
backend = matplotlib.get_backend().lower()
other_backends = {"gtkagg", "macosx", "wx", "tkagg"} - {backend}
@requires_backend(other_backends.p... |
# SPDX-License-Identifier: Apache-2.0
import bpy
import os
from xrs import tools as xrs
# Set variables
model_name = xrs.get_filename_no_ext()
model = bpy.data.objects[model_name]
xrs.reset_location_rotation_scale(model)
# Ensure it is the only object selected
xrs.select_object(model)
# Export as an fbx ({model_nam... |
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import (
Cipher, algorithms, modes
)
from bitstring import BitStream, BitArray
def decoder(ct, tag, key, iv):
decryptor = Cipher(
algorithms.AES(key),
modes.GCM(iv, tag),
backend=default... |
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import AbstractBaseUser
from django.db import models
class CustomUserManager(BaseUserManager):
use_in_migrations = True
def create_user(
self, custom_username, custom_email=None, password=None, **extra_fields
... |
import sys
import os
cur_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(cur_dir, os.pardir))
import unittest
import logging
import unishark
from time import sleep
import threading
log = logging.getLogger(__name__)
class MyTestClass5(unittest.TestCase):
@classmethod
def setUpCl... |
"""
Stores live info for the server.
THIS IS NOT SAVED ON THE DB
"""
import logging
import threading
import time
from typing import Dict
import common.mqtt_messages as mqtt_messages
# dictionary mapping coffee machines IDs to last heartbeat timestamp
coffee_machines_last_heartbeat: Dict[str, float] = dict()
... |
# coding: utf-8
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environmen... |
"""
Noeske, K. G., et al. 2007, ApJ, 660, L43
http://arxiv.org/abs/astro-ph/0703056v2
For ssfr, values are corrected as seen in Behroozi et al. 2013 (http://arxiv.org/abs/1207.6105), Table 5, for I (Initial Mass Function) corrections.
"""
import numpy as np
info = \
{
'reference':'Noeske, K. G., et al. 2007, ApJ, ... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# This is just a dummy function to generate some arbitrary data
def getdata():
basecond = [[18, 20, 19, 18, 13, 4, 1],
[20, 17, 12, 9, 3, 0, 0],
[20, 20, 20, 12, 5, 3, 0]]
cond1 = [[18, 19, 18, 19, 20, 15,... |
from .symmetry_net import SymmetryNet
|
import tensorflow as tf
from hotpot.configurable import Configurable
from hotpot.nn.layers import get_keras_initialization, get_keras_activation
def compute_attention_mask(x_mask, mem_mask, x_word_dim, key_word_dim):
""" computes a (batch, x_word_dim, key_word_dim) bool mask for clients that want masking """
... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""
"""
from micropsi_core import runtime as micropsi
import logging
def test_set_logging_level():
assert logging.getLogger('system').getEffectiveLevel() == logging.WARNING
micropsi.set_logging_levels(system='DEBUG', world='DEBUG', nodenet='DEBUG')
asser... |
"""Images vies."""
# Django REST Framework
from rest_framework import viewsets
# Serializers
from .serializers import OriginalImageSerializer
# Models
from .models import (
OriginalImage,
)
class OriginalImageViewset(viewsets.ModelViewSet):
"""docstring for OriginalImageViewset."""
queryset = Original... |
from model import common
import torch.nn as nn
import torch
from model.ConvLSTM import ConvLSTM_Cell
url = {
}
def make_model(args, parent=False):
return EGISR(args)
class Attention(nn.Module):
def __init__(self,args, conv=common.default_conv):
super(Attention,self).__init__()
n_resblocks = ar... |
from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.contrib.admin.helpers import AdminErrorList
from django.shortcuts import reverse
from .models import Funding
from faker import Faker
from faker.providers import internet, profile, python, currency, lorem
from time import ti... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2020-12-10 21:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zadania', '0001_initial'),
]
operations = [
migrations.AlterField(
... |
from .basic import Slice, Sum, Max, Pooled, Binarize
from .util import process_dir
from .audiograph import \
resampled, stft, audio_graph, with_onsets, frequency_adaptive, windowed
|
from bxcommon.messages.bloxroute.ack_message import AckMessage
from bxcommon.messages.bloxroute.block_confirmation_message import BlockConfirmationMessage
from bxcommon.messages.bloxroute.broadcast_message import BroadcastMessage
from bxcommon.messages.bloxroute.get_txs_message import GetTxsMessage
from bxcommon.messag... |
# -*- coding: utf-8 -*-
# Time : 2021/12/23 19:43
# Author : QIN2DIM
# Github : https://github.com/QIN2DIM
# Description:
import multiprocessing
from services.deploy import CollectorScheduler, SynergyScheduler
from services.settings import SCHEDULER_SETTINGS, logger
from services.utils import ToolBox
__... |
"""
generate templatic emails for community proofreading
The LangSci ID of a book is given as the first argument of the command line.
The author name to figure in the subject line is given as the second argument
The list of chapters is found in a file `chapternames` with one entry per line
The matching of communi... |
from abc import ABCMeta, abstractmethod
class ITv(metaclass=ABCMeta):
@abstractmethod
def display(self,channel):
raise NotImplemented()
@property
@abstractmethod
def region(self):
raise NotImplemented()
@region.setter
@abstractmethod
d... |
from PIL.Image import Image
import numpy as np
import torch
from torch.utils.data.dataloader import DataLoader
from accelerate import Accelerator
from datasets import Dataset
from transformers import (
AutoTokenizer,
AutoModelForQuestionAnswering,
default_data_collator,
)
from typing import List, Tuple, Un... |
"""
Copyright (C) 2018-2021 RISE Research Institute of Sweden AB
File: hist.py
Author: anders.holst@ri.se
"""
from math import *
def seconddegree(a, b, c, fmin, fmax):
# solves a x^2 + b x + c = 0, and returns the closest real value in the interval [fmin, fmax]
if a==0.0:
f = -c/b
return ma... |
from ..structures.users import PteroUser
from ..types import _PteroApp
class UserManager:
def __init__(self, client: _PteroApp) -> None:
self.client = client
self.cache: dict[int, PteroUser] = {}
def __repr__(self) -> str:
return '<UserManager cached=%d>' % len(self.cache)
... |
# -*- coding: utf-8 -*-
"""
flask-stormpath
---------------
This module provides secure user authentication and authorization for Flask
via Stormpath (https://stormpath.com/). It lets you log users in and out
of your application in a database-independent fashion, along with allowing
you to sto... |
def fib_gene(n):
current = 0
num1, num2 = 0, 1
while current < n:
num = num1
num1, num2 = num2, num1+num2
current += 1
yield num
return current
if __name__ == '__main__':
F = fib_gene(5)
print(type(F))
while True:
try:
x = next(F)
... |
# Generated by Django 2.1.1 on 2018-09-06 00:27
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
#!/usr/bin/env python3
import sys
import matplotlib
import matplotlib.pyplot as plt
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 12}
matplotlib.rc('font', **font)
matplotlib.use('svg')
plt.rcParams["font.family"] = "Times New Roman"
sizes = [5, 10, 50, 100, 500, 1000, ... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm, t
np.random.seed(1)
#%%
N = 1_0
mu = 5
sd = 2
#%%
x = np.random.randn(N)*sd + mu
#%% Z-CI
mu_hat = x.mean()
sigma_hat = x.std(ddof=1)
z_left = norm.ppf(0.0250)
z_right = norm.ppf(0.9750)
left_ci = mu_hat + z_left*sigma_hat/np.sqrt(N)
ri... |
from collections import Counter
from datetime import datetime, timedelta
import random
import copy
import math
import re
from src.containers import UserDict, UserList, UserSet
from src.decorators import command, event_listener
from src.functions import get_players, get_target, get_reveal_role
from src.messages import ... |
import unittest
import sys
module = sys.argv[-1].split(".py")[0]
class PublicTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
global oculta_letras
undertest = __import__(module)
oculta_letras = getattr(undertest, 'oculta_letras', None)
def test_tipo_exemplo(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.