content stringlengths 5 1.05M |
|---|
from django.contrib import admin
from ..models import DocumentImage
class DocumentImageAdmin(admin.StackedInline):
"""
Admin Interface to for the DocumentImage module.
Inheriting from `admin.StackedInline`.
"""
model = DocumentImage
search_fields = ["name"]
fields = ["name", "image", "im... |
import six
import pytz
import datetime
from django.utils.encoding import smart_text
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
class RecursiveField(serializers.Serializer):
"""
Field for recursive tree scaling with set depth.
many=True should be passed
... |
from django.views.generic import TemplateView
from django.views.decorators.cache import never_cache
from rest_framework import viewsets
from rest_framework import generics
from django.shortcuts import render
from .models import Message, MessageSerializer, Todo, TodoSerializer
# Serve Vue Application
index_view = ne... |
import os
import imageio
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import load_mnist as mnist
# See http://lyy1994.github.io/machine-learning/2017/04/17/RBM-tensorflow-implementation.html
def weight(shape, name='weights'):
return tf.Variable(tf.truncated_normal(shape, stddev=0.1... |
'''
Autor: Lázaro Martínez Abraham Josué
Titulo: leergramatica.py
Versión: 1.0
Fecha: 6 de diciembre de 2020
'''
def informacion(nombre):
'''Obtiene la información de la gramatica de los archivos
Parámetros
nombre: nombre del archivo que contiene la información de la gramática
return ... |
# Copyright 2015 0xc0170
#
# 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, soft... |
"""
Day 18
"""
from typing import List, Union
import operator
def convert(day_input: List[str]) -> List[List[str]]:
"""Return each input token in a separate position"""
return [line.replace('(', '( ').replace(')', ' )').split() for line in day_input]
def eval_infix(expr: List[str]) -> str:
"""Evals expr s... |
# Generated by Django 2.0.3 on 2018-07-26 21:26
import apps.core.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reddit', '0004_auto_20180726_1519'),
]
operations = [
migrations.AddField(
model_name='post',
... |
# Copyright 2011 OpenStack Foundation
# 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 requ... |
import uuid
import json
import health_inspector
g_client = None
CATEGORY_WORKER = 4
HEALTH_INSPECTOR_MODULE_ID = uuid.UUID('4e5f74d0-4705-11ec-abd0-e12370ec4fc6')
def init(client, **kwargs):
"""
:param client:
:param kwargs:
:return:
"""
global g_client
g_client = client
return True
... |
import hashlib
import logging
import random
import time
import uuid
from website.db.subclassing import SubfieldBase
from website.views.fields import MultiSelectFormField
from django.core import exceptions
from django.db import models
from django.db.models import SlugField, ManyToManyField
from django.utils.text import... |
from problems.vrp.problem_vrp import VRPDataset
from problems.vrp.problem_vrp import CVRP
import time
import torch
data = VRPDataset( size=10)
problem = CVRP()
start = time.time()
distance_matrix = torch.cdist(data[1]["loc"], data[1]["loc"], p=2.0, compute_mode='use_mm_for_euclid_dist_if_necessary')
neighbors = tor... |
from taichi._lib import core as ti_core
# ========================================
# real types
# ----------------------------------------
float16 = ti_core.DataType_f16
"""16-bit precision floating point data type.
"""
# ----------------------------------------
f16 = float16
"""Alias for :const:`~taichi.types.pri... |
__version__ = "v2022.05.26"
|
import unittest
from rts.core.thr import Thread
from rts.core.pts import ParaTaskSet
from rts.sched import bcl_mod
class BCLTestCase(unittest.TestCase):
""" Tests for `bcl.py`."""
def test_two_thread(self):
thread_param1 = {
'id': 11,
'exec_time': 4,
'deadline': 1... |
# -*- coding: utf-8 -*-
import unittest
import eduid_userdb.element
import eduid_userdb.exceptions
from eduid_userdb.orcid import OidcAuthorization, OidcIdToken, Orcid
__author__ = 'lundberg'
token_response = {
"access_token": "b8b8ca5d-b233-4d49-830a-ede934c626d3",
"expires_in": 631138518,
"id_token": {... |
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
# Create your models here.
class Sns(models.Model):
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='user')
text = models.TextField(blank=True)
image = models.ImageFiel... |
import pandas as pd
def generate_countryDB(country_name:str):
''' Generates a csv database with all cities of a defined country.
Args:
country_name (str): Country name in english, not abbreviated.
Returns:
df_col (pandas.DataFrame):
Writes: A csv file with the cities of the specifie... |
from flask import render_template,redirect,url_for,request,abort
from . import main
from flask_login import login_required,current_user
from ..models import User,Comment,Pitch,Upvote,Downvote
from .form import Updateprofile,Topicform,CommentForm
from .. import db
@main.route('/')
def index():
return render_tem... |
from datasets import load_dataset
def print_dict(d: dict, name: str = None):
if name is not None:
s = f'===== {name} ====='
print(s)
for k, v in d.items():
print(f'{k} = {v}')
if name is not None:
print(''.join(['=' for _ in range(len(s))]))
|
from flask import Flask, render_template, jsonify, request, session, redirect, flash
import crud, more_crud
import model
import json
import api
import os
def make_dict_books_a_shelf(user, shelf):
current_user = crud.get_user_by_username(user)
if shelf == "all":
books_on_shelf = crud.return_all_book... |
#!/usr/bin/python
# coding:utf-8
#赤外線遮断レーザーを利用
#起動するとコンソールに処理結果を表示。
#Ctl + Cで終了
#
import RPi.GPIO as GPIO
from time import sleep
#pin番号
pin = 10
#GPIO.setmode(GPIO.BCM)
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN)
try:
while True:
if GPIO.input(pin) == GPIO.HIGH:
print("1:not blocked")
... |
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
import numpy as np
def bar_charts():
plt.style.use('seaborn')
# can be further fine-tuned; either 0.5 from start or I include baseline model
labels = ['DSC', 'D2V', 'RASC']
all_means = [0.244, 0.120, 0.486, ]
low_means = [0.... |
#!python3
import openpyxl, string, sys
if __name__ == "__main__":
start = sys.argv[1]
blank = sys.argv[2]
wb = openpyxl.load_workbook(sys.argv[3])
sheet = wb.get_sheet_by_name('Sheet')
alphabet = string.ascii_uppercase
newwb = openpyxl.Workbook()
newsheet = newwb.get_active_sheet()
... |
"""
This file lists all the global variables that are used throughout the project.
The two major components of this file are the list of the datasets and the list of the models.
"""
"""
This is where we keep a reference to all the dataset classes in the project.
"""
import medical_ood.datasets.MNIST as MNI... |
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
from setuptools import setup
import re
def requirements(filename):
with open(filename) as f:
lines = f.read().splitlines()
c = re.compile(r'\s*#.*')
return filter(bool, map(lambda y: c.sub('', y).strip(), lines))
setup(
name=... |
"""
This file contains the Models that represent tables in the system's database
and helper functions to interact with the tables.
"""
from capstoneproject.models.fields import *
from capstoneproject.models.models import *
from capstoneproject.models.querysets import *
from capstoneproject.models.db_queries import *
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
import models
# Register your models here.
admin.site.register(models.Student)
admin.site.register(models.Course)
admin.site.register(models.SC)
|
#!/usr/bin/env python
import sys
import threading
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
from cgi import urlparse
#enable threaded server
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
pass
#custom handler for getting routes
class PrimeHandler(B... |
from django.core.exceptions import ObjectDoesNotExist
from metrics.models import Metric, MetricValue
from metrics import handlers
from metrics.jira import request_jira_api
import celery
from datetime import timedelta
from django.conf import settings
import logging
log = logging.getLogger(__name__)
@celery.task()... |
import numpy as np
from gym.spaces import Box
import warnings
import gym_electric_motor as gem
from ..random_component import RandomComponent
from ..core import PhysicalSystem
from ..utils import set_state_array
class SCMLSystem(PhysicalSystem, RandomComponent):
"""
The SCML(Supply-Converter-Moto... |
from bs4 import BeautifulSoup
import urllib.request
import sys
LAST_PAGES = 3
def getLastPages():
for index in range(0,LAST_PAGES):
print(index)
url = f"https://sanidad.castillalamancha.es/ciudadanos/enfermedades-infecciosas/coronavirus/notas-prensa?page={index}"
urllib.request.urlretriev... |
'''
attenuation after VNA is 30dBm
attenuation after SMF is 40dBm
one amplifier in use 30dBm gain
'''
from __future__ import print_function
import qt
import shutil
import sys
import os
import time
# from future import print_function
from constants import *
def generate_meta_file():
metafile ... |
"""Stop condition for DiviK.
stop.py
Copyright 2018 Spectre Team
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 o... |
# Generated by Django 2.1.2 on 2018-10-09 16:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0004_auto_20181009_1950'),
]
operations = [
migrations.RemoveField(
model_name='company'... |
import os
import hvac
import json
import requests
__all__ = [
"VaultutilpyError",
"MissingEnvVar",
"AuthTokenRetrieval",
"SecretNotFound",
"TokenFileNotFound",
"in_cluster_client",
"in_cluster_secret",
]
class VaultutilpyError(Exception):
pass
class MissingEnvVar(VaultutilpyError):
... |
#
# Copyright 2021 Lukas Schmelzeisen
#
# 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 ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Han Xiao <artex.xh@gmail.com> <https://hanxiao.github.io>
import random
from datetime import datetime
import numpy as np
import zmq
from zmq.utils import jsonapi
class BertClient:
def __init__(self, ip='localhost', port=5555, output_fmt='ndarray'):
self.soc... |
# Copyright (c) 2011-2020 Eric Froemling
#
# 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, publish,... |
''' Tests for yarals.protocol module '''
import json
import pytest
from yarals import protocol
@pytest.mark.protocol
def test_diagnostic():
''' Ensure Diagnostic is properly encoded to JSON dictionaries '''
pos_dict = {"line": 10, "character": 15}
pos = protocol.Position(line=pos_dict["line"], char=pos_d... |
import sys
import os
sys.path.append('../utils')
from load import *
from msdi_io import *
from KbyK import *
from skimage.feature import hog
from skimage.color import rgb2gray
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
#msdi_path = '/home/mrb8/Bureau/M2/SAM/projet_v2/datas/msdi'
c... |
def inc(x):
def incx(y):
return x + y
return incx
# 函数柯里化
# 使用inc函数来构造各种版本的inc函数
# 1. 把函数当做变量来使用,关注描述问题而不是怎么实现,这样让让代码更易读
# 2. 因为函数返回里面的函数,所以函数关注的是表达式,关注的是描述这个问题,而不是怎么实现这个事情
inc1 = inc(2)
inc2 = inc(5)
print(inc1(2))
print(inc2(5))
|
# Simple test to ensure that we can load the xapian module and exercise basic
# functionality successfully.
#
# Copyright (C) 2004,2005,2006,2007,2008,2010,2011,2015 Olly Betts
# Copyright (C) 2007 Lemur Consulting Ltd
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the ... |
"""
Implementation of the 'pathological photo-z PDF estimator,
as used in arXiv:2001.03621 (see section 3.3). It assigns each test set galaxy
a photo-z PDF equal to the normalized redshift distribution
N (z) of the training set.
"""
import numpy as np
from ceci.config import StageParameter as Param
from rail.estimatio... |
# KicadModTree 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 3 of the License, or
# (at your option) any later version.
#
# KicadModTree is distributed in the hope that it will be useful,
# bu... |
"""
Creates an HTTP server with basic websocket communication.
"""
import argparse
from datetime import datetime
import json
import os
import traceback
import webbrowser
import tornado.web
import tornado.websocket
import tornado.escape
import tornado.ioloop
import tornado.locks
from tornado.web import url
import method... |
"""
Handles data retrieval from KEGG.
Version: 1.1 (October 2018)
License: MIT
Author: Alexandra Zaharia (contact@alexandra-zaharia.org)
"""
import urllib2
import sys
import os
import re
from CoMetGeNeError import CoMetGeNeError
from os.path import exists, isdir, basename
from ..definitions import PICKLE_EC, PICKLE_... |
#!/usr/bin/env python3
import sys
import os
def print_usage():
print("HAL plugin template generator")
print(" usage: new_plugin <name>")
print("")
print("Sets up the directory structure and respective files in the current directory:")
print("<name>/")
print(" |- include/")
print(" | |- fac... |
#
# Copyright (c) 2016-2022 Deephaven Data Labs and Patent Pending
#
""" This module defines the data types supported by the Deephaven engine.
Each data type is represented by a DType class which supports creating arrays of the same type and more.
"""
from __future__ import annotations
from typing import Any, Sequen... |
import runpy
#from distutils.core import setup, Extension
from setuptools import Extension, find_packages, setup
from setuptools.command.build_py import build_py
# Third-party modules - we depend on numpy for everything
import numpy
# Obtain the numpy include directory. This logic works across numpy versions.
try:
... |
import gzip
import re
import os
import time
from sys import argv
import concurrent.futures
import glob
# Keep track of when the script began
startTime = time.time()
char = '\n' + ('*' * 70) + '\n'
# Input file or list of files
inputFile = argv[1]
pathToFiles = argv[2]
numCores = int(argv[3])
if pathToFiles.endswith("... |
# -*- coding: UTF-8 -*-
from flask import Blueprint
rcmd_ws = Blueprint("rcmd_ws", __name__, static_folder="static",
template_folder="templates")
import genuine_ap.rcmd.views
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 17:31:25 2020
read and write soil parameters for SUMMA
@author: jimmy
"""
import pandas as pd
def parseSoilTBL(fname):
# fname = '/home/jimmy/phd/Extra/HydroCourse/Week03/code/pbhmCourse_student/2_process_based_modelling/settings/plumber/UniMich... |
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def show_hp(unfiltered, timestamps, cutoff, fs, order=5):
b, a = butter_highpass(cutoff, fs, order)
# Frequency response graph
w, h = freqz(b, a, worN=8000)
plt.subplot(2,... |
import numpy as np
from .arg_init import init_arg
from .fault_analyzer_decorator import FaultAnalyzerDecorator
class FaultAnalyzerCartoBase(FaultAnalyzerDecorator):
def __init__(self, comp, **kwargs):
super().__init__(comp, **kwargs)
self.coord_name = init_arg("coordinates_name", kwargs)
... |
from random import randint
def generate_data_item(i: int) -> float:
return 1.12 * randint(-i * randint(0, 50), 100)
def fill_data(data):
for i in range(len(data)):
data[i] = generate_data_item(i % 10)
return data
def find_max_index(data):
max_value = data[0]
max_index = None
for i in range(len(data)... |
import numpy as np
from scipy.io import wavfile
import os,joblib,time
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
os.environ['TF_FORCE_GPU_ALLOW_GROWTH']='true'
#import tensorflow.keras.backend as K
#K.set_floatx('float16')
from keras.models import load_model
import pandas as pd
from sklearn.preprocessing impor... |
from django.urls import path,re_path
from products.views import products_list_1,product_item,featured_item
urlpatterns = [
path('', products_list_1,name='query'),
path('', products_list_1,name='query1'),
re_path('(?P<pk>[-@\w]+)/', product_item),
]
|
from .tools import websocket_token_from_session_key
def websocket_token(request):
token = websocket_token_from_session_key(request.session.session_key)
if token:
return {'websocket_token': token}
else:
return {'websocket_token': ''} |
import json
from RDS import ROParser
import logging
import os
from lib.upload_zenodo import Zenodo
from flask import jsonify, request, g, current_app
from werkzeug.exceptions import abort
from lib.Util import require_api_key, to_jsonld, from_jsonld
logger = logging.getLogger()
@require_api_key
def index():
req =... |
"""
Function to a Form
------------------
Converts function signatures into django forms.
NOTE: with enums it's recommended to use the string version, since the value will be used as the
representation to the user (and generally numbers aren't that valuable)
"""
import enum
import inspect
import re
import typing
fro... |
"""The :mod:`paddy.Default_Numerics` module contains functions for numeric
problems.
Routine listings
----------------
eval_numeric(object)
polynomial(object)
poly(x,seed)
trig_inter(x,seed)
mse_func(target, output)
gramacy_lee()
See Also
--------
:mod:`paddy.Paddy_Runner`
Notes
-----
The background information... |
import komand
from .schema import QuarantineInput, QuarantineOutput
from komand.exceptions import ConnectionTestException
# Custom imports below
class Quarantine(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='quarantine',
description='Quara... |
from Restaurante9_10 import Restaurant
r1 = Restaurant('La Cazuela', 'mexicana')
r1.desc()
r1.abierto()
|
from typing import Any, Optional
import urwid
from ..attributed_text_widget import ATWidget
from ..markup import AT
from .edit_widgets import EditWidget
from .euph_config import EuphConfig
from .launch_application import launch
from .room_widget import RoomWidget
__all__ = ["SingleRoomApplication", "launch_single_ro... |
#!/usr/bin/env python3
#-*-coding:utf-8-*-
"""
Trajectory evaluator for pure LiDAR-based chain SLAM, cartographer and GMapping
"""
import os
import csv
import argparse
import numpy as np
import matplotlib.pyplot as plt
from sys import argv
from numpy.linalg import svd, det
all_method_names = ("cartographer", "ch... |
import numpy as np
def evaluate(submission, correct):
"""Checks if two grids (submitted and correct) are the same.
Args:
submission (list, numpy array): The submitted grid. If it is
a list, it will be converted to a numpy array.
correct (list, numpy): The ground truth grid. If it ... |
#
# Copyright (C) 2016 Codethink Limited
#
# 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 agre... |
import json
from policyuniverse.expander_minimizer import minimize_statement_actions
BAD_ACTIONS = {
"*",
"s3:*",
}
def policy(resource):
if resource["Policy"] is None:
return True
iam_policy = json.loads(resource["Policy"])
for statement in iam_policy["Statement"]:
# Only check... |
from __future__ import print_function
# Converting Day to Seconds
day_num = int(input("Input number of days: "))
sec_in_day = day_num * 24 * 60 * 60
print ("There are {0} seconds in {1} day(s)".format(sec_in_day, day_num))
hours_num = int(input("Input number of hours: "))
sec_in_hour = hours_num * 60 * 60
print ("The... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
ext_modules = [
Extension("voxelize",
sources=["voxelize.pyx"],
libraries=["m"] # Unix-like specific
)
]
setup(
ext_modules=cythonize(ext_modules)
)
|
#!/usr/bin/env python3
#
# Simple utility to generate a credentials config file as we update the main credentials.json
#
#
import json
with open( 'credentials.json', 'r') as jsonfile:
full = json.load( jsonfile );
sample = dict()
for service,one in full.items():
servicedict = dict()
for ... |
# Copyright (c) 2020 6WIND S.A.
# SPDX-License-Identifier: BSD-3-Clause
import asyncio
import functools
import logging
from typing import Any, Callable
from libyang.data import DNode
from _sysrepo import ffi, lib
from .errors import SysrepoError, check_call
from .util import c2str, is_async_func
LOG = logging.getL... |
from django.db import models
class MigrationScripts(models.Model):
app = models.CharField(max_length=255)
applied_on = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=255)
|
#
# Copyright (c) 2019-2020 Carnegie Mellon University
# All rights reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
"""Utility functions for object detection providers"""
import os
import shutil
from pathlib import Path
import requests
from logzero import logger
from tqdm import tqdm
# Registry to track availa... |
"""This python script contains the libraries and functions needed to run the other two ML py scripts in this folder.
"""
# load libraries necessary for both offline and live ML scripts
import argparse
import numpy as np
import pandas as pd
from datetime import timedelta
from datetime import datetime
import math
# ML M... |
# -*- coding: utf-8 -*-
""" Utilities, specific to the PointDetector stuff. """
import os
import copy
import cv2
def write_annotated_image(input_image, ids, image_points, image_file_name):
"""
Takes an input image, copies it, annotates point IDs and writes
to the testing output folder.
"""
image ... |
# Copyright 2019 The Dreamer Authors. Copyright 2020 Plan2Explore 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... |
#! /usr/bin/env python3
import os
import sys
import stat
import math
from mule_local.JobMule import *
jg = JobGeneration()
############################################################
# Settings that will stay the same for reference & test jobs
############################################################
# run simu... |
# -*- coding: utf-8 -*-
import os
import glob
import subprocess
import unittest
testfile = map(lambda f: f.strip('.s'), glob.glob('tests/*.s'))
def get_expect_output(testfile):
with open('%s.expected' % testfile, 'rb') as f:
return f.read()
def get_exec_output(testfile):
return subprocess.check_o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-07-17 17:01
# @Author : Iceyhuang
# @license : Copyright(C), Tencent
# @Contact : iceyhuang@tencent.com
# @File : visualize_cifar.py
# @Software: PyCharm
# @Version : Python 3.7.3
# 用于将cifar10的数据可视化
import os
import pickle
import numpy as np
from sci... |
import requests_mock
import requests
from os import path
import sys
import unittest
from pandas import DataFrame as df, Timestamp
from alpaca_trade_api.alpha_vantage import REST
import pytest
import os
cli = REST(os.getenv("ALPHAVANTAGE_API_KEY"))
# def endpoint(params=''):
# return 'https://www.alphavantage.co... |
import os
import shlex
import subprocess
from pt_helper import Command
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
REPLAY_SH = """
#!/bin/bash
# Replay the shell session recording that is in the same directory as this script
SCRIPT_DIR=$(dirname ${BASH_SOURCE[0]})
scriptreplay --log-out "${SCRIPT_DIR}/std... |
# -*- coding: utf-8 -*-
#
# Database upgrade script
#
# RLP Template Version 1.1.0 => 1.1.1
#
# Execute in web2py folder after code upgrade like:
# python web2py.py -S eden -M -R applications/eden/modules/templates/RLP/upgrade/1.1.0-1.1.1.py
#
import datetime
import sys
#from s3 import S3DateTime
#from gluon.storage i... |
from abc import abstractmethod
from typing import Any, Optional, List, Mapping, Sequence, Type, Union, Dict
from sqlalchemy.orm import DeclarativeMeta, ColumnProperty
from sqlalchemy.sql import insert, Insert, Select
from ..query import CRUDQuery
from .base import BaseProvider
from .select_provider import SelectProvide... |
"""
Main module that starts RabbitMQ connection and publishes ArtifactPublished
events
"""
import logging
import signal
import sys
import os
import json
from eiffelactory import artifactory
from eiffelactory import config
from eiffelactory import eiffel
from eiffelactory import rabbitmq
from eiffelactory import utils
... |
import datetime as dt
from mongoengine import *
from .user import User
class Scheduling(EmbeddedDocument):
DEFAULT_TYPE = 'daily'
TYPES = (DEFAULT_TYPE, 'weekdays', 'weekends', 'weekly', 'monthly')
user = ReferenceField(User, required=True)
type = StringField(required=True, default=DEFAULT_TYPE, cho... |
# Create a data set using features extracted by librosa.
import multiprocessing
from os import path
import pickle
import common
from dbispipeline.utils import prefix_path
import librosa
import numpy as np
import pandas as pd
DATA_PATH = prefix_path("audio_data", common.DEFAULT_PATH)
def extract_features(song_path):... |
__author__ = 'matt'
from copy import deepcopy
from os.path import join, split, exists
import numpy as np
from .cvwrap import cv2
from chumpy.utils import row, col
from .utils import wget
def get_earthmesh(trans, rotation):
from .serialization import load_mesh
from copy import deepcopy
if not hasattr(get... |
load("@npm//@bazel/typescript:index.bzl", "ts_library")
load("@npm//jest-cli:index.bzl", _jest_test = "jest_test")
def ts_test(name, srcs, deps, data = [], jest_config = "//:jest.config.js", **kwargs):
"A macro around the autogenerated jest_test rule, by the incomparable @spacerat"
lib_name = name + "_lib"
... |
from cm.base import ObjectBase, StatusBase
from cm.db import Connection
from cm import config, error, cookie, i18n
import re, sha, time, binascii, urlparse
_password_generator = None
def get_password_generator():
global _password_generator
if _password_generator is None:
_password_generator = Passwor... |
__source__ = 'https://leetcode.com/problems/sequence-reconstruction/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/sequence-reconstruction.py
# Time: O(n * s), n is the size of org, s is the size of seqs
# Space: O(n)
#
# Description: 444. Sequence Reconstruction
#
# Check whether the original sequence or... |
import json
import FulcrumApplicationToSalesforceObject as fts
from fulcrum import Fulcrum
_sfdcPrefix = 'f_'
_sfdcUsername = "your.salesforce@username.com"
_sfdcPassword = "yourSalesforcePassword"
_sfdcToken = "yourSalesforceSecurityToken"
_sfdcSandbox = True
_fulcrumXApiToken = "yourFulcrumAPIToken"
#The specific Fu... |
import inspect
import sys
import argparse
import shlex
class OptionError(Exception):
pass
def prompt_str(prompt, regex=None, default=None, loop=True):
return input(prompt)
def prompt_list(prompt, sep=',', loop=True):
pass
def prompt_bool(prompt='y/n? ', default=None, loop=True):
q = raw_input(pro... |
from d6tflow.tasks import TaskData
from d6tflow.targets.torch import PyTorchModel
class PyTorch(TaskData):
"""
Task which saves to .pt models
"""
target_class = PyTorchModel
target_ext = '.pt'
|
import unittest
from prob_distrs import Bernoulli
from prob_distrs import Binomial
class TestBernoulliClass(unittest.TestCase):
def setUp(self):
self.bernoulli = Bernoulli(0.4)
def test_initialization(self):
self.assertEqual(self.bernoulli.p, 0.4, 'p value incorrect')
self.assertEqual... |
import unittest
from pathlib import Path
from .. import *
class GameTestCase(unittest.TestCase):
def test_generate_turn(self):
pass #TODO
def test_init01(self):
g = game.Game(num_systems=100)
self.assertEqual(len(g.systems), 100)
def test_init02(self):
g = game.Game(x=0, ... |
compras = ('Arroz', 10.89, 'Feijão', 8.76, 'Tomate', 4.32,
'Sal', 3.50, 'Farinha', 6.43, 'Guarana', 3.43,
'Batata', 5.40, 'Detergente', 2.30, 'Maionese', 4.60)
print('=-=' * 13)
print(f'{"LISTAGEM DE PREÇOS":^37}')
print('=-=' * 13)
for c in range(0, len(compras)):
if c % 2 == 0:
print... |
import numpy as np
import pandas as pd
from . import gpabase as b
class TohokuGPA(b.GPACalcModule):
'''
GPA calculation method (Cumulative) of Tohoku University since March 3, 2020.
For details: https://www.tohoku.ac.jp/japanese/studentinfo/education/01/education0110/015_2.pdf (Japanese)
'''... |
import abc
import numpy as np
import mujoco_py
from rllab.core.serializable import Serializable
from sandbox.ours.envs.sawyer.mujoco_env import MujocoEnv
import copy
class SawyerMocapBase(MujocoEnv, Serializable, metaclass=abc.ABCMeta):
"""
Provides some commonly-shared functions for Sawyer Mujoco envs that... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.