content stringlengths 5 1.05M |
|---|
from vgdl.state import StateObserver, KeyValueObservation
import math
from typing import Union, List, Dict
class AvatarOrientedObserver(StateObserver):
def _get_distance(self, s1, s2):
return math.hypot(s1.rect.x - s2.rect.x, s1.rect.y - s2.rect.y)
def get_observation(self):
avatars = self... |
class _Masked_UniOp(_Masked_UFunc):
"""
Masked version of unary ufunc. Assumes 1 output.
Parameters
----------
ufunc : ufunc
The ufunc for which to define a masked version.
maskdomain : function
Function which returns true for inputs whose output should be masked.
"""
... |
import vnmrjpy as vj
import unittest
import numpy as np
import glob
import matplotlib.pyplot as plt
class Test_varray_to_kspace(unittest.TestCase):
# test form im2D
def test_gems_to_kspace(self):
vj.config['verbose'] = False
gems = glob.glob(vj.config['fids_dir']+'/gems*axial_*')[0]
... |
MAX_TRIES = 7
# TODO Fill constants and fill with desired values
INSTRUCTIONS = (
"Aquí van"
"Aquí van"
)
DISPLAY_MSG = {
'win': 'Ganaste',
'lose': 'Perdiste'
}
ERRORS = {
'letter': 'Inserte una entrada valida'
}
|
import os
from typing import Tuple, Callable
import gym
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from tensorlib import rl
from tensorlib.rl.utils.replay.replay import TransitionReplayBuffer
from tensorlib.rl.utils.replay.sampler import StepSampler
from tensorlib.utils.logx import... |
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path("add-post/", views.add_post_view, name="add-post"),
path("posts/", views.display_posts_view, name="display-posts"),
path("posts/<str:slug>", views.detail_post_view, name="detail-post"),... |
from cbse.req import Req, ReqType, Path
class Doc:
def __init__(self, title: str):
self.reqs = list()
self.title = title
def req(self, id, text: str, req_type: ReqType, trace_filepath: Path = None, trace_function: str = None, function_hash: str = None):
r = Req(id, text, req_type, trac... |
from dsenser import DiscourseSenser
import _pickle as cPickle
senser = DiscourseSenser(None)
senser.train(train_set, dsenser.WANG,
dsenser/data/models/pdtb.sense.model.WangSenser, dev_set)
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Page'
db.create_table(u'pages_page', (
(u'id'... |
#!/usr/bin/env python
__author__ = "bt3"
import urllib2
import urllib
def post_general(url):
values = {'name' : 'Dana Scullt',
'location' : 'Virginia',
'language' : 'Python' }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)... |
#######################################################################################################
# autoComper V1.2 - Date: 17.09.2011 - Created by Jan Oberhauser - jan.oberhauser@gmail.com #
# Creates a ready to start script on the push of a button #
# Check... |
# Standard imports
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pdb
# Initialize global counts
global_success_counter = 0
global_fail_counter = 0
# Common success and fail lists
bool_fail_list = [0, -1, 'True', 'x', 1]
bool_success_list = [False, True]
# MAVE-NN imports
from mavenn.s... |
import numpy as np
import matplotlib.pyplot as plt
from . import head_draw_functions as hdf
import IL
# This guy creates a dataset matrix of dimension resolution x resolution x figNumber using the
# using the "drawFunction" method
def generator(
datasetType,
figure, # which figure are we drawing the dataset w... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 6 09:03:21 2019
@author: leatr
calculate the Intersection Over Union ratio based on specific inputs
Text file must have 8 columns as:
y_1, x_1, y_2, x_2, y_3, x_3, y_4, x_4
which can be obtained by running:
- Get_IOU_coordinates.py over the Plot_origin... |
# Copyright 2021 The WAX-ML 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
#!/usr/bin/env python
import sys
import os.path
import ipaddr
if len(sys.argv) != 2:
print("USAGE: %s <subnets.txt>" % os.path.basename(sys.argv[0]))
sys.exit(1)
for line in open(sys.argv[1], 'r'):
netw = ipaddr.IPv4Network(line.rstrip())
for ip in netw.iterhosts():
print ip
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-08-23 17:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0004_auto_20170816_1841'),
]
operations = [
migrations.AlterModelOpt... |
from flask import request, jsonify
from authlib.integrations.flask_oauth2 import current_token
from realnet_server import app
from .auth import require_oauth
from .models import db, Group, Account, AccountGroup, GroupRoleType
from sqlalchemy import or_
import uuid
def can_account_create_group(account):
return True... |
#!/usr/bin/env python
import os
from collections import defaultdict
class prettyfloat(float):
def __repr__(self):
return '%6.2f' % self
if __name__ == '__main__':
tests = []
with open('regression.out', 'r') as f:
for line in f:
tokens=line.strip().split()
t = tokens[4]
tests.ap... |
from .sections import Sections
|
from setuptools import setup
setup(
name='slacker-asyncio',
version='0.9.61',
packages=['slacker'],
description='Slack API asyncio client based on os\'s slacker',
author='gfreezy',
author_email='gfreezy@gmail.com',
url='http://github.com/gfreezy/slacker-asyncio/',
install_requires=['ai... |
# Set constants for analysis consistency!
# Mass of Sun in grams
Msun_g = 1.989e33
# TNG mass unit in solar masses
Mtng_Msun = 1.0e10
# Megaparsec in cm
Mpc_cm = 3.086e24
# Kiloparsec in cm
kpc_cm = 3.086e21
# km in cm
km_cm = 1.0e5
# Boltzmann constant
kB_erg_K = 1.3807e-16
# Convert keV to erg
kev_2_erg = 1.60... |
import os
from time import time
import itertools
import numpy as np
import pandas as pd
import torch
from torch import nn
from train import run_experiment
if __name__ == "__main__":
np.random.seed(2019)
torch.manual_seed(2019)
print("GPU available: ", torch.cuda.is_available())
configs = {
'... |
""" Build the grid for a transition state search
"""
from phydat import phycon
import automol
import autofile
# Main callable function
def grid_maximum_zmatrices(typ, ts_zma, scan_grids, scan_names, scn_save_fs,
mod_thy_info, constraint_dct,
series='sadpt-maxima'... |
# dependencies
from bs4 import BeautifulSoup as bs
import requests
import pymongo
from splinter import Browser
from flask import Flask, render_template, redirect
from flask_pymongo import PyMongo
import pandas as pd
from webdriver_manager.chrome import ChromeDriverManager
def init_browser():
executable_path = {'ex... |
# Generated by Django 4.0.3 on 2022-03-25 18:39
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Explanation',
... |
# Ivan Carvalho
# Solution to https://dmoj.ca/problem/coci07c1p3
def min_dist(X,Y):
ans = abs(Y[0] - X)
for Z in Y:
ans = min(ans, abs(Z - X) )
return ans
N = int(input())
P = sorted([int(i) for i in input().split()])
A,B = [int(i) for i in input().split()]
C = []
for i in range(N-1):
L = (P[i]+P[i+1])//2
C... |
import os
from flask import Flask, Response, g
from flask.logging import logging
app = Flask(__name__)
app.secret_key = os.urandom(20)
# auth
import auth.flaskAuthProcess
import auth.flaskAuthRefresh
app.register_blueprint(auth.flaskAuthProcess.manager)
app.register_blueprint(auth.flaskAuthRefresh.mana... |
class DAO():
# TODO: define parameters and return values explicitly with comments
def __init__(self):
pass
def close(self):
pass
def peer_beacon(self, peer_id, host, last_seen):
pass
def active_peers(self, since):
pass
def register_peer(self, peer_id, host):... |
import os
from PIL import Image
def folder_to_png(path: str, output_folder: str = "./pngs", cleanup: bool = False):
if os.path.isdir(path):
original_files = os.listdir(path)
for image in original_files:
image_name = image.split(".")[0]
im = Image.open(path + "/" + image)
... |
# -*- coding: utf-8 -*-
MNAME = "utilmy.docs.format"
HELP = """ A simple python module to parse the code and format it based on some rules.
Goal is to normalize all python files with similar structure.
Some rules are
rule 1 - change a line starting with 3 #'s into x #'s where x is 90 by default
if no ... |
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under ... |
"""GPT Nucleus
- Initial stem consists of a combination of token encodings and positional encoding.
- Basically, a uniform sequence of Transformer blocks.
- Each transformer is a sequential combination of a 1-hidden layer MLP block and a self-attention block.
- all blocks feed into a central re... |
import eden_simulator
import sys
filename = sys.argv[1] if len(sys.argv) > 1 else "LEMS_2007One.xml"
print(
"Running a simulation of %s in EDEN v%s"
% (
filename,
eden_simulator.__version__ if hasattr(eden_simulator, "__version__") else "???",
)
)
results = eden_simulator.runEden(filename)... |
# MIT License
# Copyright (c) 2022 Izhar Ahmad
# 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, modify, merge, pu... |
import unittest
from injecta.mocks.Bar import Bar
from injecta.mocks.Foo import Foo
from pyfonycore.bootstrap import bootstrapped_container
class container_init_test(unittest.TestCase): # noqa: N801
def test_basic(self):
container = bootstrapped_container.init("test")
foo = container.get(Foo)
... |
# !/usr/bin/env python3
# ---coding:UTF-8---
print ('hello world')
# 模块
# datetime
from datetime import datetime
now = datetime.now() #获取当前的时间
print ("当前时间为:%s" % now)
# 获取某个指定日期
dt = datetime(2018, 7, 15, 12, 23)
print(dt)
'''
# 导入sqlite3驱动
import sqlite3
# 连接到sqlite3数据库
# 数据库文件是test.db
# 如果数据库不存在,会自动在当前目录创建
co... |
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
class Algorithm:
def __init__(
self,
explainer,
variable,
constant=None,
n_grid_points=21
):
self.explainer = explainer
self._variable =... |
'''
Job Service
'''
import pymongo
from celery import Celery
from pymongo import MongoClient
import datetime
import json
from bson.objectid import ObjectId
import config
class deployment_job_service(object):
'''
Job Service for templates deployment jobs
'''
def __init__(self):
print('Job S... |
import ipaddress
class BitfieldNotSetError(Exception):
pass
class Peer:
def __init__(self, raw_ip_bytes):
self.host = ipaddress.ip_address(raw_ip_bytes[:4])
self.port = int.from_bytes(raw_ip_bytes[4:], byteorder="big")
# are we choking/interested in the peer
self.client_chokin... |
import os
import numpy as np
from PIL import Image
from torch.utils import data
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from torch.autograd import Variable
import torchvision.transforms as transforms
class Dataset(data.Dataset):
"Characterizes a datas... |
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Fonts demo")
text = "The quick brown fox jumps over the lazy dog"
self.label = tk.Label(self, text=text)
self.family = tk.StringVar()
self.family.trace("w", self.set_font)
... |
default_app_config = 'cobra.apps.organization.config.OrganizationConfig'
|
# Copyright 2016 The TensorFlow 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 required by applica... |
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler,Stream,Cursor
import twiiter_secret
from textblob import TextBlob
import tweepy
import pprint
import json
import matplotlib.pyplot as plt
def main():
search_item=input("Enter the term you want to search :")
no_of_searchT=int... |
from flask import Flask
from app import routes
def create_app():
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024
routes.init_app(app)
return app |
"""
Date: Jan 17 2022
Last Revision: N/A
General Notes:
- 176ms runtime (49.44%) and 14.6MB (61.08%)
Solution Notes:
- iterate through the flowerbed and see if there is an available spot to plant the flower
"""
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
available_spo... |
# Generated by Django 3.2.10 on 2022-02-21 08:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("challenges", "0011_challenge_access_request_handling")]
operations = [
migrations.AlterField(
model_name="challenge",
name="requ... |
import rclpy
from rclpy.node import Node
#import sensor_msgs.msg as msg
from std_msgs.msg import UInt8
import time
import Adafruit_PCA9685
import rclpy.qos as qos
class servo_control(Node):
def __init__(self):
super().__init__('servo_control')
profile = qos.QoSProfile()
self.pwm = Adafruit_... |
from unittest import TestCase
from leetcodepy.insertion_sort_list import *
from leetcodepy.utils import linked_lists
solution1 = Solution1()
values1 = (4, 2, 1, 3)
expected1 = linked_lists.from_values(1, 2, 3, 4)
values2 = (-1, 5, 3, 4, 0)
expected2 = linked_lists.from_values(-1, 0, 3, 4, 5)
class TestInsertion... |
import threading
#import RPi.GPIO as GPIO
#import time
#GPIO.setmode(GPIO.BCM)
def setup(trigger, echo):
"""assigning different GPIO pins through threads"""
# trigger = GPIO_TRIGGER
# echo = GPIO_ECHO
# GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
# GPIO.setup(GPIO_ECHO, GPIO.IN)
print 'Trigger: %s' % t... |
#!/usr/bin/env python
"""Select operating system specific implementations of builder."""
import platform
# pylint: disable=unused-import,g-import-not-at-top,g-bad-name
if platform.system() == "Linux":
from grr_response_client_builder.builders import linux
DebianClientBuilder = linux.DebianClientBuilder
CentosC... |
import pytest
import requests
from . import Check, StatusCodeCheck, Result
class TestCheck:
def test_check_parser(self):
conf = {
'type': 'rx.check.StatusCodeCheck',
'name': 'TestCheck',
'expected': 201,
}
chk = Check.parse(conf)
assert chk.name... |
# author: Bartlomiej "furas" Burek (https://blog.furas.pl)
# date: 2021.02.07
# https://stackoverflow.com/questions/66082627/trackingnumber-soup-findinput-name-tracknums-getvalue
from selenium import webdriver
import time
#driver = webdriver.Chrome()
driver = webdriver.Firefox()
# load page with form
driver.get('h... |
import os
import time
import spacy
class Translator:
def __init__(self, inter_threads=1, intra_threads=4, beam_size=4, max_batch_size=50):
self.translator = self.load_translator(inter_threads, intra_threads)
self.tokenizer = Tokenizer('models/bpe')
self.beam_size = beam_size
self.m... |
from static_variables import resolve_static
@resolve_static(static_variables={'expensive_module': None})
def f(value):
if expensive_module is None:
import expensive_module
return expensive_module.function(value)
|
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------
# Copyright Commvault Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... |
def nth_digit_to_n_gives_original_number():
for i in range(100000000):
s = sum([int(x)**int(x) for x in str(i)])
if i == s:
return(i)
def parker_square_attempt():
arr = map(int,"0"*9)
s = sum([i**2 for i in arr])
return s
print(parker_square_attempt()) |
#!/usr/bin/python3
# Copyright 2021. FastyBird s.r.o.
#
# 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... |
#!/usr/bin/env python2
"""A simple test server for DXR, not suitable for production
Use a web server with WSGI support for actual deployments.
"""
from optparse import OptionParser
from os.path import abspath
from dxr.app import make_app
def main():
parser = OptionParser(usage='usage: %prog [options] build-fol... |
from event import Event
from robot.libraries.BuiltIn import BuiltIn
class ScopeEvent(Event):
def __init__(self, scope, action, *args, **kwargs):
self.scope = scope
self.action = action
self.action_args = args
self.action_kwargs = kwargs
if scope == 'current':
su... |
# example dict
data = [
{'type': 'a', 'v1': 'off', 'v2': '1'},
{'type': 'b', 'v1': 'off', 'v2': '1'},
{'type': 'c', 'v1': 'on', 'v2': '1'},
{'type': 'b', 'v1': 'off', 'v2': '2'},
{'type': 'a', 'v1': 'on', 'v2': '2'},
{'type': 'a', 'v1': 'on', 'v2': '3'}
]
def sort_types(my_list, my_key):
n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2022 Jongrae.K
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 r... |
import netaddr
from napalm_yang.jinja_filters.helpers import check_empty
def filters():
return {
"netmask_to_cidr": netmask_to_cidr,
"cidr_to_netmask": cidr_to_netmask,
"normalize_prefix": normalize_prefix,
"normalize_address": normalize_address,
"prefix_to_addrmask": pref... |
from .video_source import VideoSource
from .compute_stream import ComputeStream
|
import os
from datetime import datetime
import torch
from transformers import DetrFeatureExtractor, DetrForObjectDetection, pipeline
from PIL import Image
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
class ObjectDetectionInference:
"""
🤗 Constructor for the object... |
#
# author: Cosmin Basca
#
# Copyright 2010 University of 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 a... |
from datetime import datetime
def write_result_to_txt(path,result,crawler_name="none"):
filename = "spider_{}_{}.txt".format(crawler_name,datetime.now().strftime('%d-%m-%Y'))
path_to_file = "{}/{}".format(path,filename)
file = open(path_to_file,'w+')
for counter,item in enumerate(result):
prin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://ru.wikipedia.org/wiki/Фабричный_метод_(шаблон_проектирования)
from abc import ABC, abstractmethod
class Animal(ABC):
@staticmethod
def initial(animal: str) -> 'Animal':
if animal == 'Lion':
return... |
txt = """G1 F480 X96.117 Y72.633 E0.1089
G1 X97.517 Y71.450 E0.4137
G1 X97.953 Y71.156 E0.5012
G1 X98.286 Y70.977 E0.5640
G1 X98.969 Y70.656 E0.6895
G1 X99.497 Y70.273 E0.7980
G1 X99.713 Y70.080 E0.8462"""
txt_list = txt.split('\n')
txt_lists = [txt.split(' ') for txt in txt_list]
txt_lists = [[float(txt[1:]) for txt... |
import json
import logging
import os
import torch
import pandas as pd
import numpy as np
from typing import Dict, Any
from src.model import MVAE
from src.dataset import OneHotEncoding, Dataset
JSON_CONTENT_TYPE = "application/json"
logger = logging.getLogger(__name__)
def model_fn(model_dir):
device = torch.d... |
from django.conf.urls import url
from . import views
from .models import MoviesFeed
urlpatterns = [
url('^$', views.index, name='index'),
url('^watch/(?P<mid>[0-9]+)$', views.watch, name="watch"),
url('^profile$', views.profile, name="profile"),
url('^random$', views.random_movie, name="random"),
u... |
#!/usr/bin/env python
#from distutils.core import setup
from setuptools import setup,find_packages
# For Testing:
#
# python3.4 setup.py register -r https://testpypi.python.org/pypi
# python3.4 setup.py bdist_wheel upload -r https://testpypi.python.org/pypi
# python3.4 -m pip install -i https://testpypi.python.org/pyp... |
def calculate_gpa():
number_of_subjects = int(input('Enter the number of subjects: '))
#Blank Line
print()
cumulative_credits = 0
gpa_by_credits = 0
subject_names = []
subjects_grade = []
subject_credits = []
for index in range(number_of_subjects):
print... |
from .json_enum import JsonEnum
from .to_json_encoder import ToJsonEncoder |
import sys
from pyspark.sql.functions import pandas_udf, PandasUDFType
from Edge import Edge
from Heap import Heap
class PinkMST():
'''
:param
partitionId:int
pairedData:(list<Point>,list<Point>)
'''
def __init__(self,pairedData=None,partitionId=None,mstToBeMerged=None):
self.leftDat... |
#
# cogs/navi/task/__init__.py
#
# futaba - A Discord Mod bot for the Programming server
# Copyright (c) 2017-2020 Jake Richardson, Ammon Smith, jackylam5
#
# futaba is available free of charge under the terms of the MIT
# License. You are free to redistribute and/or modify it under those
# terms. It is distributed in ... |
from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class Tag(models.Model):
title = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255, unique=True)
user = models.ForeignKey(
... |
import heapq
inf = float('Inf')
def dijkstra(G, s):
n = len(G)
Q = [(0, s)]
d = [inf for i in range(n)]
d[s]=0
while len(Q)!=0:
(cost, u) = heapq.heappop(Q)
for v in range(n):
if d[v] > d[u] + G[u][v]:
d[v] = d[u] + G[u][v]
he... |
from django.contrib import admin
from account.models import Contact, Email, WhatsApp
# Register your models here.
admin.site.register(Contact)
admin.site.register(Email)
admin.site.register(WhatsApp) |
#!/usr/bin/env python3
def get_vertices(wire):
x = y = steps = 0
vertices = [(x, y, 0)]
for edge in wire:
length = int(edge[1:])
steps += length
if edge[0] == "R":
x += length
if edge[0] == "L":
x -= length
if edge[0] == "U":
... |
from datetime import datetime, timedelta
notifications = []
def getNotifications():
return notifications
def clearNotifications():
notifications = []
def addNotification(notification):
if notification["message"]:
notifications.append(notification)
# --------------- time function logic ------... |
from pydantic.main import BaseModel
from .word import Word
class DependencyParse(BaseModel):
start: int
end: int
label: str
word: Word
right: bool
root: bool
|
import abc
import numpy as np
from typing import BinaryIO, Type, Sequence
import io
import yaml
class NormalizeTransform(abc.ABC):
@abc.abstractproperty
def kind(self) -> str:
pass
@abc.abstractmethod
def normalize(self, y: np.ndarray):
pass
@abc.abstractmethod
def denormaliz... |
# flake8: noqa
# Import all APIs into this package.
# If you have many APIs here with many many models used in each API this may
# raise a `RecursionError`.
# In order to avoid this, import only the API that you directly need like:
#
# from .api.annotation_api import AnnotationApi
#
# or import this package, but be... |
import torch
class UtilsModel():
""" Collection of utilities for a model
"""
@staticmethod
def network_inputsize(net):
''' Get the input network size
https://stackoverflow.com/questions/63131273/how-to-get-input-tensor-shape-of-an-unknown-pytorch-model
'''
shape_of_... |
import os
from conf import setting
from db import db_handler
def get_school_list():
school_list = [(index, i.split('.')[0]) for index, i in enumerate(os.listdir(setting.SCHOOL_DB))]
return school_list
def choose_school(school_name):
school = db_handler.load_db('school', school_name)
return school
... |
import os
testDir = os.path.dirname(os.path.realpath(__file__))
sedmlDir = os.path.join(testDir, 'sedml', 'sed-ml')
sedxDir = os.path.join(testDir, 'sedml', 'sedx')
|
# -*- coding: utf-8 -*-
n = int(input())
for i in range(1, n + 1):
if i % 2 == 0:
print("%d^2 = %d" % (i, i**2)) |
# -*- coding: utf-8 -*-
############################################################################
#
# Copyright © 2013 OnlineGroups.net and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this dis... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 - 2020 -- Lars Heuer
# All rights reserved.
#
# License: BSD License
#
"""\
PPM related tests.
"""
from __future__ import unicode_literals, absolute_import
import re
import io
from struct import unpack
import pytest
import segno
try:
range = xrange # noqa
except NameE... |
"""Implementations for torch.nn.functional equivalent for MPC."""
# stdlib
from typing import Optional
from typing import Tuple
from typing import Union
# third party
import numpy as np
import torch
from sympc.grads import GRAD_FUNCS
from sympc.grads import forward
from sympc.session import get_session
from sympc.te... |
import cocotb
import pyuvm
from pyuvm import *
import random
from pathlib import Path
import sys
# All testbenches use tinyalu_utils, so store it in a central
# place and add its path to the sys path so we can import it
sys.path.insert(0, str(Path("..").resolve()))
from tinyalu_utils import TinyAluBfm, Ops, alu_predict... |
import unittest
TRANSIT_SET = ( None, ('1S','1E') , ('2W','2S','2E') , ('3W','3S') ,
('4N', '4E', '4S') , ('5N' , '5E' , '5S' , '5W') , ('6N','6W','6S') ,
('7N' , '7E') , ('8W', '8N', '8E') , ('9W','9N') )
TREASURE_MAP = []
TREASURE_MAP.append('.xx.....xx.....')
TREASURE_MAP.append('..... |
#!/usr/bin/env python3
from typing import Union, Optional
print(Union[int, str] == Union[str, int, int]) # True
print(Optional[int] == Union[int, None]) # True
|
import sys
sys.path.append('/opt')
from common.exception_handler import exception_handler
from airdrop.config import SLACK_HOOK, NETWORK_ID
from common.logger import get_logger
from common.utils import generate_lambda_response, request
from airdrop.application.services.airdrop_services import AirdropServices
from aird... |
"""
Simple event server for Tuesday's THW
This is simplistic event bus setup for doing serverside notebook answer checks
for Tuesday's The Hacker Within Python Olympics.
"""
import os
import json
import time
import uuid
from flask import Flask, request
from flask_cors import CORS
from pymongo import MongoClient
app ... |
from .base_options import BaseOptions
class UtilOptions(BaseOptions):
"""This class includes test options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
parser = BaseOptions.initialize(self, parser) # define shared options
parser.add_argum... |
from typing import Optional
from oddrn_generator.generators import Generator
from oddrn_generator.path_models import BasePathsModel
from oddrn_generator.server_models import AWSCloudModel
class SqsPathsModel(BasePathsModel):
queue: Optional[str]
class Config:
dependencies_map = {"queue": ("queue",)}... |
# -*- coding: utf-8 -*-
import collections
import inspect
from typing import List
import pytest
from py_gql import graphql, graphql_blocking
from py_gql._string_utils import stringify_path
from py_gql.exc import ResolverError
from ._test_utils import assert_sync_execution
HERO_QUERY = """
query HeroNameAndFriends... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.