content stringlengths 5 1.05M |
|---|
from os import environ
from app import AppFactory
from log import configure_root_logger_level
configure_root_logger_level()
ENVIRONMENT = environ.get("ENV", "local")
lambda_handler = AppFactory(ENVIRONMENT).create_handler()
if __name__ == "__main__":
lambda_handler({}, None)
|
from itertools import chain
from lib_bgp_simulator import Announcement
class ROVPPAnn(Announcement):
__slots__ = ["holes", "blackhole", "temp_holes"]
def __init__(self, *args, blackhole=False, **kwargs):
"""Inits ann and adds blackhole and invalid subprefixes"""
self.blackhole = blackhole
... |
# Copyright 2020 Open Source Robotics Foundation, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 12 03:03:16 2020
@author: Asus
"""
import pandas as pd
from matplotlib import pyplot as plt
plt.style.use('seaborn')
data = pd.read_csv('data.csv')
ids = data['Responder_id']
ages = data['Age']
bins = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
plt.hi... |
# Generated by Django 2.2.2 on 2019-12-15 00:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('exercises', '0004_auto_20191213_1741'),
]
operations = [
migrations.AlterField(
model_name='ses... |
__all__ = ["mainwindow_meat"] |
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2014 by Armin Ronacher.
:copyright: (c) 2014 by Niclas Moeslund Overby.
:license: BSD, see LICENSE for more details.
"""
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
a... |
# PAD = 0
# UNK = 1
# BOS = 2
# EOS = 3
#
# PAD_WORD = '<blank>'
# UNK_WORD = '<unk>'
# BOS_WORD = '<s>'
# EOS_WORD = '</s>'
PAD = 0
BOS = 1
EOS = 2
UNK = 3
PAD_WORD = '<pad>'
BOS_WORD = '<sos>'
EOS_WORD = '<eos>'
UNK_WORD = '<unk>'
NODE_FIX = '1*NODEFIX'#'1*NODEFIX'
MIN_LR = 1e-6 |
# Copyright (c) 2019 Graphcore Ltd. All rights reserved.
import numpy as np
import torch
from op_tester import op_tester
import popart
def test_gemm_basic(op_tester):
A = np.random.rand(2, 4).astype(np.float32)
B = np.random.rand(4, 6).astype(np.float32)
C = np.random.rand(2, 6).astype(np.float32)
_te... |
{
"targets": [
{
"target_name": "<(module_name)",
"sources": [
"src/qt.cpp",
"src/QtGui/qapplication.cpp",
"src/QtGui/qwidget.cpp",
"src/QtGui/qmainwindow.cpp",
"src/QtGui/qlabel.cpp",
"sr... |
'''===========================================
1. Adjust the parameters
2. Adjust rnum, which will become the name of the file
==========================================='''
import os
import numpy as np
import dynalysis.basics as bcs
import dynalysis.classes as clss
from itertools import combinations
from dynalysis.ge... |
# Copyright 2018 Google 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 applicable law or a... |
from config import Config
import cv2
import numpy as np
import keyboard
import time
from utils.custom_mouse import mouse
from template_finder import TemplateFinder
from ui_manager import detect_screen_object, ScreenObjects, center_mouse
from utils.misc import wait, trim_black, color_filter, cut_roi
from inventory impor... |
# !/usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this wo... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
__a... |
""" 52 - Faça um programa que leia um número inteiro e diga se ele é ou não um número primo."""
n = int(input('Informe um número: '))
cont = 0
for c in range(1, n + 1):
if n % c == 0:
print('\33[34m', end=' ')
cont += 1
else:
print('\33[31m', end=' ')
print(f'{c}', end=' ')
print(f'... |
#!/usr/bin/env python
# coding: utf-8
from .idbase import IDBase
def _idx(n):
try:
n = int(n)
except ValueError:
raise ValueError('index i and j must be int or int-str but: {n}'.format(n=n))
if not (0 <= n <= 99):
raise ValueError('index i and j must be 0~99, but: {n}'.format(n... |
from flask import Flask
app = Flask(__name__)
from webapp import controller, model
|
import json
import multiprocessing as mp
import os
import random
import shutil
import socket
import struct
import time
from contextlib import ContextDecorator
from os.path import join
import msgpack # type: ignore
import pytest
from mosec.coordinator import PROTOCOL_TIMEOUT, STAGE_EGRESS, STAGE_INGRESS, Coordinator
... |
import sys
import gzip
import argparse
import pyngs.sam as sam
def process_tags(instream, outstream, tags, samtags, sep=":"):
"""Add tags to the alignment."""
reader = sam.Reader(instream)
writer = sam.Writer(outstream, reader.header)
for alignment in reader:
# get the values fr... |
import kerastuner
import numpy as np
import tensorflow as tf
from tensorflow.python.util import nest
from autokeras import meta_model
from autokeras import tuner
from autokeras import utils
from autokeras.hypermodel import graph
from autokeras.hypermodel import head
from autokeras.hypermodel import node
class AutoMo... |
from abc import ABC, abstractmethod
class Figure(ABC):
def __init__(self, name, *args):
self.name = name
self.args = args
def __str__(self):
return f"Figure name: {self.name}\n" \
f"Parameters:{', '.join(str(arg) for arg in self.args)}\n" \
f"Area: {self.... |
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
#User Manager
class UserManagerProfile(BaseUserManager):
def create_user(self,username,email,date_of_birth,password=None):
if not username:
raise ValueError("users must have an usernam... |
from pathlib import Path
from flask import Flask, render_template, request, redirect, url_for, jsonify, json, make_response, send_file
from flask_pymongo import PyMongo
import logging
from logging.config import dictConfig
import boto3
from werkzeug.datastructures import FileStorage
import asobann
from asobann.store i... |
from django.apps import AppConfig
class FinalConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'final'
|
#!/usr/bin/env python
# coding: utf-8
# In[28]:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def splitPlusMinus(x, index=0):
N = len(x)
vector = np.asarray(np.zeros(N))
error = np.asarray(np.zeros(N))
for i in range(index, N+index):
value = x[i].split(u'\xb1')
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 28 11:23:26 2017
@author: rickdberg
Create maps
"""
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy
# define cartopy crs for the raster, based on rasterio metadata
crs = ccrs.PlateCarree()
# create figure
ax = plt.axes(projection=crs)
ax.s... |
example = list([1,2,3]) #two ways to make list
primes = [2,3,5,7,11,13]
primes.append(17)
primes.append(19)
# for i in example:
# print(i)
#! list preserve order
print(primes[0])
print(primes[3])
print(primes[-1])
print(primes[2:5:2]) #! [Start:Stop:Increase Index by]
#You can insert multiple data types into li... |
from error import Error
class Parser:
def __init__(self, tokens):
self.tokens = iter(tokens)
self.advance()
def raise_error(self):
raise Error('Syntax error')
def advance(self):
try:
self.current_token = next(self.tokens)
except StopIteration:
... |
from models.node import Node
from models.bst import BST
# from models.hotel import Hotel
class AVL(BST):
@staticmethod
def max(x_height, y_height):
return x_height if x_height > y_height else y_height
@staticmethod
def get_height(point: Node):
if point is None:
return -1
... |
from mininet.util import dumpNodeConnections
from mininet.log import info
from time import sleep
def AttackConnectivityTest(net):
server = net.get('server')
host = net.get('host')
server.cmd("python3 tests/ipv6-httpserver.py &")
info("Node Connections:\n")
dumpNodeConnections(net.hosts)
info("... |
from pydantic import create_model, ValidationError, validator
def username_alphanumeric(cls, v):
assert v.isalnum(), 'must be alphanumeric'
return v
validators = {
'username_validator':
validator('username')(username_alphanumeric)
}
UserModel = create_model(
'UserModel',
username=(str, ...)... |
""" **Description**
Test unit models.
**Example**
::
pytest --capture=no --verbose
**License**
`BSD-3C. <https://github.com/larryturner/diamondback/blob/master/license>`_
© 2018 - 2021 Larry Turner, Schneider Electric Industries SAS. All rights re... |
from typing import ClassVar, Dict, List, Type, TypeVar, Union
import attr
from attr.validators import instance_of
from ics.converter.component import ComponentMeta
from ics.grammar import Container
from ics.types import ExtraParams, RuntimeAttrValidation
PLACEHOLDER_CONTAINER = Container("PLACEHOLDER")
ComponentType... |
import logging
try:
from io import StringIO
except ImportError: # python2
from StringIO import StringIO
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.contrib.auth import get_user_model
from django.core.... |
import json
import asyncio
from contextlib import contextmanager, asynccontextmanager
from roy.utils.tasks import TasksManager, register
from .settings import SETTINGS
from .tasks import DeployTasks
class DeployTasksManager(TasksManager):
def __init__(self):
super().__init__()
self.debug = Fal... |
#
# __init__.py
#
# Copyright (C) 2010 Red Hat, 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.
#
# This program... |
# -*- coding: utf-8 -*-
###################################################################################
# Copyright (C) 2019 SuXueFeng GUN
###################################################################################
import logging
from odoo import api, fields, models, _
from odoo.exceptions import UserError... |
from django.test import TestCase
from dojo.tools.acunetix.parser import AcunetixParser
from dojo.models import Test
class TestAcunetixParser(TestCase):
def test_parse_without_file(self):
parser = AcunetixParser()
findings = parser.get_findings(None, Test())
self.assertEqual(0, len(findings... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import torch
from PIL import Image
from executables.guiclient.utilities import DiceCoeff, rgb_segment
from neodroid.utilities.messaging_utilities.neodroid_camera_extraction import (
extract_neodroid_camera,
)
__author__ = "Christian Heider Nielsen"
impor... |
import torch
from sklearn.model_selection import StratifiedKFold
class Sampler(object):
"""Base class for all Samplers.
Every Sampler subclass has to provide an __iter__ method, providing a way
to iterate over indices of dataset elements, and a __len__ method that
returns the length of the returned ite... |
import math
from functools import partial, lru_cache
from typing import Optional, Dict, Any
import numpy as np
import torch
from ding.torch_utils import one_hot
num_first_one_hot = partial(one_hot, num_first=True)
def sqrt_one_hot(v: torch.Tensor, max_val: int) -> torch.Tensor:
"""
Overview:
Sqrt t... |
import ctypes
import dll
class Time(ctypes.Structure):
_fields_ = [("year", ctypes.c_int),
("month", ctypes.c_int),
("day", ctypes.c_int),
("hour", ctypes.c_int),]
class Location(ctypes.Structure):
_fields_ = [("latitude", ctypes.c_float),
... |
def recommend_clothes(wind_speed, temp, condition):
wind_speed = int(wind_speed)
temp = int(temp)
if wind_speed >= 5:
is_wind_strong = True
else:
is_wind_strong = False
if temp < -5:
temp = "cold"
elif -5 <= temp < 15:
temp = "warm"
elif temp >= 15:
... |
from .authorize_client import AuthorizeClient
from .database import Database
from .delegated import Delegated
from .enterprise import Enterprise
from .get_token import GetToken
from .logout import Logout
from .passwordless import Passwordless
from .social import Social
from .users import Users
|
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
import sys
n, m = map(int, sys.stdin.readl... |
import numpy as np
import bpy
from mathutils import Vector
from bpy.types import Panel
from bpy.props import (
BoolProperty,
EnumProperty,
FloatProperty,
IntProperty,
StringProperty
)
from bpy.types import WindowManager
#from NACAgen import NACA4digits... |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField, validators
from wtforms.validators import DataRequired, Length, Email, EqualTo
class RegistrationForm(FlaskForm): #DataRequired = can't be null
username = StringField('Username', validators=[DataRequired(), val... |
import tensorflow as tf
from time import time
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.callbacks import TensorBoard
import os, glob
import nltk... |
#!python3
"""
Classes for representing a Bundle (a set of objects given to an agent) and an Allocation (a matching of bundles to agents).
An Allocation is the output of a fair allocation algorithm.
The objects are used mainly for display purposes.
Programmer: Erel Segal-Halevi
Since: 2021-04
"""
from typing import... |
my_dict = {'real': 6, 'imag': 8}
print(complex(**my_dict))
|
"""
test_functions.py
Author: Praveen Prabhakar KR
Email: praveenp@msu.edu
Module contains the tests for functions module.
"""
import pytest
import numpy as np
from .. import functions as fn
def test_sinewave():
"""
Test for sinewave function in the functions module.
"""
time = np.arange(0, 10, 1/... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ("id", "title", "author", "content", "created", "modified")
list_filter = ("title",)
search_fields = ("title",)
|
class SourceInitError(Exception):
"""Error during source initialization.
This can be used to have a clearer message, where not traceback gets
displayed.
"""
|
class Solution:
"""
@param n: a number represent year
@return: whether year n is a leap year.
"""
def isLeapYear(self, n):
# write your code here
if n %4 ==0 and n %100 !=0:
return True
if n % 400 == 0 :
return True
return False |
#!/usr/bin/env python
# This is a horrible script, but cpack is rather bad
# and won't let us merge Debug+Release on windows.
import os
import sys
import subprocess
import shutil
shutil.rmtree('build_pkg', ignore_errors=True)
version = None
with open('VERSION', 'r') as f:
version = f.read().strip()
ARCH = sys.ar... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
numpy 学习
"""
from __future__ import print_function
import numpy as np
a = np.arange(2, 14).reshape((3,4))
# a:[[ 2 3 4 5]
# [ 6 7 8 9]
# [10 11 12 13]]
print('a:', a)
print('np.argmin(a):', np.argmin(a)) # 最小元素索引
print('np.argmax(a):', np.argmax(a)) ... |
import xlwt
from datetime import date
from company_info_API import CompanyInfoAPI
from dataDB import DBTable
class DataWorker:
def __init__(self, webapi, dbapi):
self.webapi = webapi
self.dbapi = dbapi
def insert_or_update_info(self, target_list):
db_list = self.dbapi.get_companycode_... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import tasks.micro.small_comp as small_comp
from tasks.competition.tests.helpers import task_messenger
from core.serializer import IdentitySerializer
cla... |
# Generated by Django 3.2.13 on 2022-04-29 09:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("warehouse", "0024_rewrite_order_line_relations"),
]
operations = [
migrations.AddField(
model_name="preorderreservation",
... |
# Copyright 2016 Curtis Sand
#
# 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 writi... |
# -*- coding: utf-8 -*-
"""Release data for the PyOOMUSH project."""
# Name of the package for release purposes.
name = 'PyOOMUSH'
version = '0.1'
description = "A Python Object-Oriented MUSH server."
long_description = \
"""
PyOOMUSH provides collaboratitive creation of a fully programmable
virtual world both usin... |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE
from __future__ import absolute_import
import sys
import json
import pytest
import numpy
import awkward1
def test():
example = awkward1.Array([[{"x": 1, "y": []}, {"x": 2, "y": [1, 1]}], []])
cache = {}
virtualar... |
# -*- coding:utf-8 -*-
import urllib.request
import urllib.error
from datetime import datetime,date,timedelta
from data import recent_confirmed as week
#driver = webdriver.Chrome('c:/chromedriver/chromedriver.exe')
#driver.implicitly_wait(2)
#driver.get('http://ncov.mohw.go.kr/bdBoardList_Real.do?brdId=1&brdGubun=11&... |
"""
This module determines finite difference coefficients for uniform and
non-uniform grids for any desired even accuracy order.
Most important function:
coefficients(deriv, acc=None, offsets=None, symbolic=False)
to calculate the finite difference coefficients for a given derivative
order and given accuracy order ... |
from marshmallow import Schema, fields, post_load
from Houdini.Crumbs import SchemaObject, SchemaObjectCollection
class Furniture(SchemaObject):
pass
class FurnitureSchema(Schema):
Id = fields.Integer(load_from="furniture_item_id")
Type = fields.Integer(load_from="type")
Cost = fields.Integer(load_fro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
``$pop`` 操作符在array update中的功能是: 移除列表中的最后一个或第一个元素。(使用
1/-1标识符区分两者)
ref: https://docs.mongodb.com/manual/reference/operator/update/pop/
"""
from learn_mongodb.db_test import col
from sfm.decorator import run_if_is_main
@run_if_is_main(__name__)
def remove_last_item()... |
# coding: utf-8
import json
import os
import sqlite3
from textwrap import dedent
from time import time as current_time
def bootstrap(path, dbname):
"""Create SQLite database model we use to store collected data.
last_measures table aims to keep a track of the last collected values
(for some metrics, not... |
chromatic_scale = (
('A',),
('A#','Bb'),
('B'),
('C',),
('C#','Db'),
('D',),
('D#','Eb'),
('E',),
('F',),
('F#','Gb'),
('G',),
('G#','Ab')
)
enharmonic_notes = (
('A#', 'Bb'),
('C#', 'Db'),
('D#', 'Eb'),
('F#', 'Gb'),
('G#', 'Ab'),
)
chord_qualities =... |
#!/usr/bin/env python
from job_registry import base
import importlib
import uuid
import shutil
import os
import subprocess
import math
import json
import numpy as np
import itertools as it
from rdkit import Chem, RDLogger
from rdkit.Chem import AllChem, ChemicalForceFields
import qml
from qml.kernels import get_global_... |
import time
import discord
import os
from discord.utils import get
from discord.ext import commands
client = commands.Bot(command_prefix=".")
TOKEN = os.getenv("TOKEN")
originalRoles = '''cozy: #eeadad
sunrise: #d8b2d4
bright: #e9cd87
clover: #89cf95
cloud: #8dbfdb
sunset: #a7a2de
anonymous: #596d90
'''
dreamRoles =... |
import higlass as hg
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from clodius.tiles.format import format_dense_tile
def create_bed_vector_tileset(
bedlike_filepath: str,
chromsizes_filepath: str = None,
uuid: str = None,
aggregator: callable = np.mean,
log_scale: bool =... |
N = int(input())
matrix = []
for i in range(N):
matrix.append(list(map(int, input().split())))
for i in range(N):
for j in range(N):
if i < j :
matrix[i][j],matrix[j][i] = matrix[j][i],matrix[i][j]
for i in range(N):
for j in range(N//2):
matrix[i][j],mat... |
import pickle
import time
import os
import re
import platform
def detect_platform():
p = 'Unknown'
if platform.platform().find('Windows') != -1:
p = 'Windows'
elif platform.platform().find('Linux') != -1:
p = 'Linux'
return p
def ensure_dir_exist(directory, show_info = True):
exist... |
from fed_recon.benchmark.mini_imagenet import MiniImagenet
from torch.utils.data.dataloader import DataLoader
images_path = "/home/user/data/miniImageNet/images"
hold_out_bool = True
base_val_bool = True
miniImagenet = MiniImagenet(
images_path, hold_out_bool=hold_out_bool, base_val_bool=base_val_bool
)
print(f... |
# Generated by Django 3.0.1 on 2020-07-09 18:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nomnom', '0016_auto_20200703_2049'),
]
operations = [
migrations.AlterField(
model_name='ingredientset',
name='amoun... |
import taichi as ti
import taichi_glsl as ts
from .Grid import Grid, GRIDTYPE
from utils import Wrapper
@ti.data_oriented
class CellGrid(Grid):
"""
wrapper for data on cell center (e.g. pressure, curl)
- F -
F C F
- F -
"""
def __init__(self,
data_field: ti.template(),
... |
from setuptools import setup
setup(
name='bvn',
packages=['bvn'],
version='0.1',
license='MIT',
description='A Greedy Birkhoff-Von Neumann Decomposition',
author='Brandon Trabucco',
author_email='brandon@btrabucco.com',
url='https://github.com/brandontrabucco/bvn',
download_url='https://... |
from math import pow
print(int(pow(sum(range(101)), 2) - sum(map(lambda x: pow(x, 2), range(101)))))
|
"""
cmd feature
Adds a commandline to the GUI that can be used to trigger all available backend commands
"""
from fwk import common
import re
from PyQt5 import QtWidgets,QtCore
class cmd(common.Feature):
enabled = True
name = "cmd"
def __init__(self, app):
super().__init__(app) #app is now our p... |
import datetime
import numpy as np
from scipy.interpolate import interp1d
from nrc_spifpy.input.binary_file import BinaryFile
from nrc_spifpy.input.spec.buffer import Buffer
from nrc_spifpy.input.spec.image import AssembledImageRecordContainer
from nrc_spifpy.input.spec.housekeeping import add_housekeeping_variables,... |
import os
import traceback
from typing import Optional, Dict, Any
import requests
from anubis.utils.logging import logger
def get_github_token() -> Optional[str]:
# Get GITHUB token from environment
token = os.environ.get("GITHUB_TOKEN", None)
# If we could not get the token, log and return None
i... |
# Assignment-3.2
############
# In Built filter function
# Input the paramaters
print("\r")
print("-> Input")
number = int(input("-> Insert a number : "))
num_list = list(range (1,number+1))
even_number = list (filter (lambda x :(x%2==0), list (filter (lambda y: (y%5==0) ,num_list ))))
odd_number = l... |
#
# population.py
# gapminder
#
import pandas as pd
from owid.catalog import Dataset, Table
from owid.walden import Catalog
from etl.steps.data.converters import convert_walden_metadata
def run(dest_dir: str) -> None:
walden_ds = Catalog().find_one("gapminder", "2019-12-10", "population")
ds = Dataset.cr... |
import numpy as np
class SortedBuffer(object):
def __init__(self, size=int(2e4), ob_space=None, beta=0.001):
self.size = size
self.ob_shape = ob_space.spaces['image'].shape
self.ob_dim = 1
for dim in self.ob_shape:
self.ob_dim *= dim
self.data = None
self... |
import numpy as np
import torch
import torch.nn as nn
import os
from vPlaneRecover.model_util import *
# from apex import amp
from vPlaneRecover.tsdf import SEM_INS_MAP
# The plane detection branch, where three semantic categories (floor, ceiling, wall) are distinguished.
# The code is inspried by https://github.com/y... |
import speech_recognition as sr
recognizer = sr.Recognizer()
def listen():
try:
with sr.Microphone() as source:
print("ghost waiting")
recognizer.adjust_for_ambient_noise(source, duration=1)
print("ghost listening")
recorded_audio = recognizer.listen(sourc... |
from .. import xray_io
class SlideWindowItem(object):
def __init__(self, offset, triangles_count, vertices_count):
self.offset = offset
self.triangles_count = triangles_count
self.vertices_count = vertices_count
def import_slide_window_item(packed_reader):
reserved = packed_reader.ge... |
import os
import slrm
for city, state in [('vancouver', 'bc'), ('toronto', 'on'), ('stanford', 'ca'), ('seattle', 'wa')]:
cmd = 'python myscript.py --city {} --state {}'.format(city, state)
slurm_kwargs = {'account': 'cse', 'partition': 'cse-gpu'}
slrm.launch(cmd, slurm_kwargs, dout=os.path.join('jobs', '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 22:40:13 2020
@author: arti
"""
import pandas as pd
list_data = ['2020-08-04', 3.14, 'ABC', 2.7818, True]
print(type(list_data))
sr = pd.Series(list_data)
print(sr)
print(sr[1])
idx = sr.index
val = sr.values
print(idx)
print('\n')
print... |
from Instrucciones.TablaSimbolos.Instruccion import Instruccion
from Instrucciones.TablaSimbolos.Tipo import Tipo_Dato, Tipo
from Instrucciones.TablaSimbolos.Simbolo import Simbolo
from Instrucciones.TablaSimbolos.Tabla import Tabla
from Instrucciones.Excepcion import Excepcion
from Instrucciones.Retorno import Retorno... |
# -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... |
from django.conf.urls import url
from . import views
from django.urls import path
from .views import SignUpView
from django.views.generic.base import TemplateView
app_name = "rental_app"
urlpatterns = [
url(r'home', views.home, name='home'),
path('', TemplateView.as_view(template_name='home.html'), name='home... |
# Problem 2 - Paying Debt Off in a Year
# (15/15 points)
# Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months.
# By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that ... |
import boto3
import os
_session = boto3.session.Session()
region_name = _session.region_name
AWS_REGION = os.getenv("AWS_REGION", region_name)
S3_ENDPOINT_URL = os.getenv("S3_ENDPOINT_URL", None)
DYNAMODB_ENDPOINT_URL = os.getenv("DYNAMODB_ENDPOINT_URL", None)
# S3
s3_client = boto3.client('s3', region_name=AWS_REG... |
# # Comparing Multinomial and Gaussian Naive Bayes
#
# scikit-learn documentation: [MultinomialNB](http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html) and [GaussianNB](http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html)
#
# Dataset: [Pima Indians ... |
from django.db import models
import idutils # for DOI validation: https://idutils.readthedocs.io/en/latest/
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from django.core.validators import MaxValueValidator, MinValueValidator
from django.contrib.auth import ge... |
import tensorflow as tf
def do_mixup(x, mixup_lambda):
"""
Mixup x with a circular permutation of x using a lambda vector
Parameters
----------
x : (batch_size,)
mixup_lambda : (batch_size,)
Returns
-------
(batch_size, ...)
"""
shape_x = tf.shape(x)
shap... |
from minicps.devices import PLC
from utils import *
import time
PLC201_ADDR = IP['plc201']
P201 = ('P201', 2)
class PP201(PLC):
def pre_loop(self, sleep=0.1):
print 'DEBUG: p201 enters pre_loop'
time.sleep(sleep)
def main_loop(self):
print 'DEBUG: p201 enters main_loop'
count = 0
while count<=PLC_SAMPL... |
import argparse
import json
import os
from pathlib import Path
import pandas as pd
import yaml
from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
from models import get_model
from training_utilities import (
df_to_list_samples,
batch_generator,
label_mapping_from_df,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.