text stringlengths 1 927k |
|---|
import json
from authors.apps.authentication.tests.base import BaseTestMethods
from authors.apps.authentication.models import User
from rest_framework.reverse import reverse
from rest_framework import status
class NotificationTests(BaseTestMethods):
def test_create_mail_list(self):
user = self.register_... |
# Copyright (c) 2017, 2018 Jae-jun Kang
# See the file LICENSE for details.
"""Import core names of x2py."""
__version__ = '0.4.3'
from x2py.buffer_transform import BufferTransform
from x2py.builtin_events import *
from x2py.case import Case
from x2py.config import Config
from x2py.coroutine import Coroutine, Corouti... |
#!/usr/bin/env python3
# Copyright (c) 2015-2020 The Beans Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
This checks if all command line args are documented.
Return value is 0 to indicate no error.
Author: @... |
# -*- coding: utf-8 -*-
"""
Display if files or directories exists.
Configuration parameters:
cache_timeout: refresh interval for this module (default 10)
format: display format for this module
(default '\?color=path [\?if=path ●|■]')
format_path: format for paths (default '{basename}')
format_... |
import cv2
import numpy as np
from utils import find_image
image_path = find_image('girls_01.jpg')
img = cv2.imread(image_path)
rows, cols, channel = img.shape
pts_src = np.float32([[50, 50], [200, 50], [50, 200]])
pts_dst = np.float32([[10, 100], [200, 80], [100, 650]])
M = cv2.getAffineTransform(pts_src, pts_dst)... |
"""Constants used throughout the code.
**Links**
* `ADB key event codes <https://developer.android.com/reference/android/view/KeyEvent>`_
* `MediaSession PlaybackState property <https://developer.android.com/reference/android/media/session/PlaybackState.html>`_
"""
import re
import sys
if sys.version_info[0] == 3... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import keras
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import argparse
import gzip
import os
import sys
import time
import os
import math
import numpy
from... |
#!/usr/bin/env python3
from sum_of_divisors import sum_of_divisors
def is_prime(n):
# If N is prime it could only be devided
# to 1 and N, so sum of divisors has to be
# equal to N + 1
return n + 1 == sum_of_divisors(n)
if __name__ == "__main__":
number = int(input("Number: "))
print (is_pri... |
import logging
from typing import Dict, List, Optional, Tuple
import pandas as pd
from autokeras import StructuredDataClassifier, StructuredDataRegressor
from tensorflow.keras import Model
from ._base import BaseImputer
logger = logging.getLogger()
class AutoKerasImputer(BaseImputer):
def __init__(
se... |
import numpy as np
import matplotlib.pyplot as plt
import pickle
import os
from scipy import stats
from HER_mod.rl_modules.tsp import generate_path
from HER_mod.rl_modules.hyperparams import NUM_GOALS, NUM_AGENTS
gd_step_list = [0,2,5, 10, 20, 40]
# NUM_AGENTS = 3
N=200
def get_path_costs(train_pos_agent, train_vel_a... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
# -----------------------------------------------------------------------------
try... |
"""
The ``mlflow.spacy`` module provides an API for logging and loading spaCy models.
This module exports spacy models with the following flavors:
spaCy (native) format
This is the main flavor that can be loaded back into spaCy.
:py:mod:`mlflow.pyfunc`
Produced for use by generic pyfunc-based deployment tools ... |
import random
class Solution:
def __init__(self, head: ListNode):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
"""
self.head = head
def getRandom(self) -> int:
"""
Re... |
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register([Content,Profile,Comment]) |
"""parqueo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
"""Matplotlib distplot."""
import warnings
import matplotlib.pyplot as plt
import numpy as np
from . import backend_show
from ...kdeplot import plot_kde
from ...plot_utils import matplotlib_kwarg_dealiaser
from ....numeric_utils import get_bins
def plot_dist(
values,
values2,
color,
kind,
cumulati... |
from flask import Flask, render_template, request, session,redirect, url_for, escape, request, make_response
app = Flask(__name__)
# configure a chave secreta
app.secret_key = "segredo"
@app.route('/')
def index():
return render_template("index.html")
# use cookies.get(key) instead of cookies[key] to not get... |
n = input('Digite algo: ')
print('É composto por número e letras? ',n.isalnum())
print('É composto somente por letras maiúsculas? ',n.isupper())
print('É composto somente por letras? ',n.isalpha())
print('É composto somente por números? ',n.isnumeric())
print('É um número decimal? ',n.isdecimal())
print('É composto som... |
from random import randrange
from pygame import Rect, draw
from clock import Clock
class Squares:
"""method for malipulating squares in the game"""
def __init__(self, st, status, screen):
self.st = st
self.status = status
self.screen = screen
self.empty_line = ['none' for i in r... |
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponsePermanentRedirect
from djconfig import config
from ..core.utils.views import is_post, post_data
from ..core.utils.paginator import pag... |
from __future__ import annotations
import abc
from alocacao.adapters import repository
from alocacao.config import DEFAULT_SESSION_FACTORY
class AbstractUOW(abc.ABC):
produtos: repository.AbstractRepository
def __enter__(self) -> AbstractUOW:
return self
def __exit__(self, *args):
self.... |
#!/usr/bin/env python
'''Excercise_4 - class9 - Reusable Code'''
def func3():
'''func3 to print simple statement'''
print 'Excercise_4 from class9 - whatever.py'
if __name__ == "__main__":
print 'This is main program from whatever.py file.' |
#coding:utf-8
#访问这个服务器会获得一些'ip:端口'字符串。仅用于测试
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, *args, **kwargs):
self.write('''
<!DOCTYPE html><html>
<head><meta charset="utf-8" />
... |
#!/usr/bin/env python
import threading, logging, time
import io
import avro.schema
import avro.io
import pprint
import kudu
from kudu.client import Partitioning
from kafka import KafkaConsumer
pp = pprint.PrettyPrinter(indent=4,width=80)
twitter_schema='''
{"namespace": "example.avro", ... |
import serial
import serial.tools.list_ports
import numpy as np
import math
import threading
import re
import os
import sys
import time
import matplotlib.pyplot as plt
pwd = os.path.abspath(os.path.abspath(__file__))
father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + "..")
sys.path.append(father_path)
... |
"""
Goal: Provides paginate() function
"""
from sqlalchemy import orm
from olass.models.pagination import Pagination
class BaseQuery(orm.Query):
"""
@see: flask-sqlalchemy/flask_sqlalchemy/__init__.py
"""
def paginate(self, page=None, per_page=None, error_out=True):
"""Returns ``per_page`` it... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from app import celery
from celery.utils.log import get_task_logger
import time
logger = get_task_logger(__name__)
# 定时导入
current_time = str(time.strftime('%Y-%m-%d %H:%M:%S'))
@celery.task(name="task1")
def task1():
print u"定时任务task1:每5秒执行一次" + current_time
# 记录日志
... |
from tkinter.filedialog import askopenfilename
from tkinter import *
import cli
import gettext
window = Tk()
window.title("ofx_to_xlsx")
def close_window():
window.destroy()
def callback():
ofx = askopenfilename()
cli.run(ofx)
gettext.install('ofx_to_xlsx')
t = gettext.translation('gui_i18n', 'locale'... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from emtract.model import Model, ModelType
import pandas as pd
class ModelInference:
MODEL_BASE_PATH = 'build/models/'
DATA_BASE_PATH = './emtract/data/'
def __init__(self, model_type):
if model_type == 'twitter':
self.model = Model(... |
from django.contrib import admin
from .models import *
admin.site.register(Student)
admin.site.register(Homework)
admin.site.register(Assignment) |
import os
import unittest
from django.conf.urls import url
from django.http import HttpResponse
def task(*args, **kwargs):
print('*'*10)
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
urlpatterns = [
url(r'^/ssss/xxx/$', detail),
url(r'^/ssuuu... |
# -*- coding: utf-8 -*-
import os
from flask.ext.script import Manager
from polichart import create_app, polling
from polichart.extensions import db
from polichart.utils import MALE
from flask import url_for
app = create_app()
manager = Manager(app)
@app.context_processor
def override_url_for():
return dict(u... |
'''
@author: MengLai
'''
import os
import tempfile
import uuid
import time
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstacklib.utils.ssh as ssh
import zstackwoodpecker.operations.scenario_operations as scen_ops
... |
import requests
import json
import time
import os
import toml
import zipfile
import csv
import pandas as pd
from datetime import date
from datetime import datetime
import logging
def incident_create(ism_url,ism_key,ism_attachment_url,final_directory,tag_name_list,flag_AH,assignee,assignee_desc,profile_link):
Patch... |
"""
shared options and groups
The principle here is to define options once, but *not* instantiate them
globally. One reason being that options with action='append' can carry state
between parses. pip parses general options twice internally, and shouldn't
pass on state. To be consistent, all options will follow this de... |
# -*- coding: utf-8 -*-
from sst_unittest import *
from sst_unittest_support import *
import os.path
################################################################################
# Code to support a single instance module initialize, must be called setUp method
module_init = 0
module_sema = threading.Semaphore()
... |
# qubit number=3
# total number=10
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collectio... |
# project/tasks/sample_tasks.py
import time
from celery import shared_task
@shared_task
def send_email(email_id, message):
time.sleep(10)
print(f"Email is sent to {email_id}. Message sent was - {message}")
@shared_task
def get_micro_app_status(app):
print(f"La micro app {app}. est UP")
@shared_task
... |
# -*- coding: utf-8 -*-
"""
컴퓨터 비전(Vision)을 위한 전이학습(Transfer Learning)
=======================================================
**Author**: `Sasank Chilamkurthy <https://chsasank.github.io>`_
**번역**: `박정환 <http://github.com/9bow>`_
이 튜토리얼에서는 전이학습(Transfer Learning)을 이용하여 이미지 분류를 위한
합성곱 신경망을 어떻게 학습시키는지 배워보겠습니다. 전이학습에 ... |
from manimlib.imports import *
class StartingScene(Scene):
def construct(_):
e = Text("Manim homework by mp",font="Consolas",color=BLUE)
_.play(Write(e),run_time=3)
_.wait()
_.play(Uncreate(e))
A = Dot().move_to(np.array([0-2,0,0]))
B = Dot().move_to(np.a... |
"""
1027. Longest Arithmetic Subsequence
Medium
Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.
Recall that a subsequence of an array nums is a list nums[i1], nums[i2], ..., nums[ik] with 0 <= i1 < i2 < ... < ik <= nums.length - 1, and that a sequence seq is arithmet... |
#
# MIT License
#
# Copyright (c) 2018 WillQ
#
# 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, publ... |
import copy
import numpy as np
from numpy import log10
import os
from toolz import pipe as p
from tensorboardX import SummaryWriter
import torch
import torch.nn as nn
import numpy as np
import preprocessing as pp
def findParam(model, name_filter):
if callable(name_filter):
fn = name_filter
else:
... |
import json
def handler(event, context):
message_from_publisher = json.loads(event['Records'][0]['Sns']['Message'])
my_param = message_from_publisher['myParamFromConsumerPublisher']
print("👷 Received paramater from ConsumerPublisher: '{0}'".format(my_param))
body = {
"message": "Go Serve... |
import unittest
class NohtmlTest(unittest.TestCase):
pass
if __name__ == "__main__":
unittest.main() |
import os
import csv
import numpy as np
from FAE.FeatureAnalysis.Normalizer import Normalizer
from FAE.DataContainer.DataContainer import DataContainer
from FAE.FeatureAnalysis.Classifier import Classifier
from FAE.Func.Metric import EstimateMetirc
from FAE.FeatureAnalysis.FeatureSelector import FeatureSelector
from FA... |
from .base import *
from .mapping import *
from .community_damage_sampling import *
from .downtime_logistics import *
from .analysis_and_visualization import * |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
DESCRIPTION = "Look up the categorization of a given set of URLs"
class Input:
URLS = "urls"
class Output:
URL_CATEGORIZATION = "url_categorization"
class LookupUrlInput(insightconnect_p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PyHtmlCv is a tool to that can be used to generate HTML CVs from a
simple JSON configuration.
:copyright: (c) 2012-2019 Janne Enberg
:license: BSD
"""
from argparse import ArgumentParser, ArgumentTypeError
import codecs
from datetime import datetime
from jinja2 import... |
try:
import librosa
except ImportError:
# No installation required if not using this function
pass
class AudioLoader:
@staticmethod
def load_audio(file_path):
try:
import librosa
except ModuleNotFoundError:
raise ModuleNotFoundError(
"Missed ... |
import cv2
import numpy
from random import shuffle
from .utils import BackgroundGenerator
from .umeyama import umeyama
class TrainingDataGenerator():
def __init__(self, random_transform_args, coverage, scale=5, zoom=1): #TODO thos default should stay in the warp function
self.random_transform_args = rando... |
#!/usr/bin/env python3
import setuptools
def read(fname):
with open(fname, 'r') as f:
return f.read()
setuptools.setup(
name="smartgadget",
version="0.1",
author="Alberto Sottile",
author_email="alby128@gmail.com",
description=' '.join([
'Interact with a Sensirion SHT31 Smart ... |
'''
Computer vision assignment 4 by Yoseob Kim
A4_compute_descriptors.py
Compute similarity-reflected image descriptors with L1, L2 norm distances by using SIFT descriptors.
* Status: (working on it)
* GitHub Link: https://github.com/pseudowasabi/computer-vision-exercises/tree/master/CV_A4_
'''
import cv2
impo... |
# File: util.py
# Audiophiler utility functions
# Credit to Liam Middlebrook and Ram Zallan
# https://github.com/liam-middlebrook/gallery
from functools import wraps
from flask import session
from audiophiler.models import Tour
def audiophiler_auth(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
... |
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
... |
# The MIT License (MIT)
#
# Copyright (c) 2016 Adam Schubert
#
# 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, mod... |
"""Non-negative matrix and tensor factorization core functions
"""
# Author: Paul Fogel
# License: MIT
# Jan 4, '20
from typing import Tuple
import numpy as np
from .nmtf_utils import EPSILON, sparse_opt
import logging
logger = logging.getLogger(__name__)
# TODO (pcotte): typing
# TODO (pcotte): docstrings (with ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# importing the necessary libraries
# from rasa_core.actions.action import Action
from rasa_sdk import Action
#from rasa_sdk.forms import ( BooleanFormField, EntityFormField, FormAction, FreeTextFormField )
... |
# ----------------------------------------------------------------------
# Label REST API
# ----------------------------------------------------------------------
# Copyright (C) 2007-2021 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Third-party m... |
import logging
import csv
import re
from openpyxl import Workbook
from openpyxl.styles import Font
from tempfile import NamedTemporaryFile
from datetime import datetime
import operator
from django.contrib.auth.models import User
from django.conf import settings
from django.contrib import messages
from django.core.exce... |
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import json
from datetime import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.inspection import inspect
db = SQLAlchemy(sessi... |
import os
''' GENERATE SECRET KEY '''
if not os.getenv('SECRET_KEY'):
# Attempt to read the secret from the secret file
# This will fail if the secret has not been written
try:
with open('.ctfd_secret_key', 'rb') as secret:
key = secret.read()
except (OSError, IOError):
key... |
import time
import cgi
import json
import BaseHTTPServer
import os
from player import Player
HOST_NAME = '0.0.0.0'
PORT_NUMBER = os.environ.has_key('PORT') and int(os.environ['PORT']) or 9000
class PlayerService(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(200)
... |
# Copyright 2021 - Guillaume Charbonnier
# Licensed under the Apache License, Version 2.0 (the "License");
# http://www.apache.org/licenses/LICENSE-2.0
from __future__ import annotations
from typing import Optional, Union
from jsm.models.account_info import IoNatsJetstreamApiV1AccountInfoResponse
from jsm.models.erro... |
import click
from colorama import Fore, Style
class KsmCliException(click.ClickException):
in_a_shell = False
def colorize(self):
if KsmCliException.in_a_shell is False:
return str(self.message)
else:
return Fore.RED + str(self.message) + Style.RESET_ALL
def form... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" VLE data for ethanol-water mixture, isobaric, 1.01 bar """
__author__ = "Yaroslav Kholod"
__copyright__ = "Copyright 2019, The Kettlebell project"
__credits__ = "Yaroslav Kholod"
__license__ = "MIT"
__version__ = "0.1.0"
__maintainer__ = "Yaroslav Kholod"
__email__ = "pret... |
import sys
sys.path.append('..')
import unittest
import random
from armoryengine.ALL import *
class SigningTester(unittest.TestCase):
def testLowSig(self):
sbdPrivKey = SecureBinaryData(b'\x01'*32)
pub = CryptoECDSA().ComputePublicKey(sbdPrivKey).toBinStr()
for i in range(100):
msg = ... |
"""
Unit tests for RNN decoders.
"""
import unittest
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from texar.torch.hyperparams import HParams
from texar.torch.modules.decoders.decoder_helpers import get_helper
from texar.torch.modules.decoders.rnn_decoders import (
Attent... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class DeleteDomainsRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The k... |
import gym
from keras.optimizers import Adam
import traceback
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
from agent.agent57 import ActorUser
from agent.policy import EpsilonGreedy, AnnealingEpsilonGreedy
from agent.memory import PERRankBaseMemory, PERProportionalMemory
from ... |
import numpy as np
import time
import torch
import torch.nn as nn
import os
import visdom
import random
from tqdm import tqdm as tqdm
from cannet import CANNet
from my_dataset import CrowdDataset
if __name__=="__main__":
# configuration
train_image_root='./data/Shanghai_part_A/train_data/images'
train_dma... |
from pandas.core.series import Series
from .config import sample_data
from .context import pandas_ta
from unittest import TestCase
from pandas import DataFrame
class TestCylesExtension(TestCase):
@classmethod
def setUpClass(cls):
cls.data = sample_data
@classmethod
def tearDownClass(cls):
... |
import sys
import numba
args = []
if sys.platform.startswith('win32'):
args += ['-b']
else:
args += ['-m', '-b']
args += ['numba.tests']
if not numba.runtests.main(*args):
print("Test failed")
sys.exit(1)
print('numba.__version__: %s' % numba.__version__) |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import Authenticatio... |
from django.db import IntegrityError
from django.db.models import Q
from django.conf import settings
from django.http import HttpResponse
from django.test import TestCase, override_settings
from django.utils.timezone import now as timezone_now
from zerver.lib import bugdown
from zerver.decorator import JsonableError
f... |
sandwich_orders = ['aaa', 'pastrami', 'bbb', 'pastrami', 'ccc','pastrami']
finished_sandwiches = []
print("\nAll pastrami had been sold!")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
while sandwich_orders:
sandwich_order = sandwich_orders.pop()
print("\nI made your tuna sanwichi... |
from django.contrib import admin
from .models import DataFile, SequencingRun, InterOpFile
# Register your models here.
admin.site.register(DataFile)
admin.site.register(SequencingRun)
admin.site.register(InterOpFile) |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ..preprocess import ROIStats
def test_ROIStats_inputs():
input_map = dict(
args=dict(argstr='%s', ),
debug=dict(argstr='-debug', ),
environ=dict(
nohash=True,
usedefault=True,
),
format1D=dic... |
"""
Tutorial - The default method
Request handler objects can implement a method called "default" that
is called when no other suitable method/object could be found.
Essentially, if CherryPy2 can't find a matching request handler object
for the given request URI, it will use the default method of the object
located de... |
from IPython.display import Image
Image('images/02_network_flowchart.png')
Image('images/02_convolution.png')
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
import time
from datetime import timedelta
import math
from tensorflow.examples.tutoria... |
# coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.... |
#!/usr/bin/env pytest
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test coordinate transformations.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
########################################################... |
"""
The OpenML module implements a python interface to
`OpenML <https://www.openml.org>`_, a collaborative platform for machine
learning. OpenML can be used to
* store, download and analyze datasets
* make experiments and their results (e.g. models, predictions)
accesible and reproducible for everybody
* analyze exp... |
from bos_consensus.util import LoggingMixin
class NoFurtherBlockchainMiddlewares(Exception):
pass
class StopReceiveBallot(Exception):
pass
class BaseBlockchainMiddleware(LoggingMixin):
blockchain = None
def __init__(self, blockchain):
self.blockchain = blockchain
super(BaseBlockc... |
"""
This file defines functions to manipulate user interaction with the web-interface.
Responsible for views related to the models defined in Materials/models.py.
"""
import os
from django.core.paginator import Paginator
from django.http import HttpResponseForbidden
from django.shortcuts import HttpResponse, redirec... |
from .utils import save_features
from .extract_features_faster import extract_feat_faster_start
from .extract_features_multigpu import extract_feat_multigpu_start
from .extract_features_singlegpu import extract_feat_singlegpu_start
from .extract_d2features import extract_feat_d2_start |
# Copyright 2013 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
import glob
import hashlib
import json
import logging
import os
impor... |
def minimum_deletions(string: str) -> int:
current_character = string[0]
count = 0
deletions = 0
for character in string:
if character == current_character:
count += 1
else:
current_character = character
deletions += count - 1
count = 1
... |
from pathlib import Path
from fhir.resources.codesystem import CodeSystem
from oops_fhir.utils import CodeSystemConcept
__all__ = ["v3substanceAdminSubstitution"]
_resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json"))
class v3substanceAdminSubstitution:
"""
v3 Code System substanceAdminSu... |
from pytest import raises
from poetcli.main import PoetCLITest
def test_poetcli():
# test poetcli without any subcommands or arguments
with PoetCLITest() as app:
app.run()
assert app.exit_code == 0
def test_poetcli_debug():
# test that debug mode is functional
argv = ['--debug']
... |
#!/usr/bin/env python
# coding=utf-8
# Copyright © 2017 ButenkoMS. All rights reserved. Contacts: <gtalk@butenkoms.space>
#
# 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... |
"""
Python bindings for GLFW.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import ctypes
import os
import glob
import sys
import subprocess
import textwrap
def _find_library_candidates(library_names,
library_file_exten... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import os
import math
import cereal.messaging as messaging
from common.numpy_fast import clip, interp
from selfdrive.swaglog import cloudlog
from common.realtime import sec_since_boot
from selfdrive.controls.lib.radar_helpers import _LEAD_ACCEL_TAU
from selfdrive.controls.lib.longitudinal_mpc import libmpc_py
from sel... |
# encoding: utf-8
import os
import sys
from os import path as osp
from pprint import pprint
import numpy as np
import torch
from tensorboardX import SummaryWriter
from torch import nn
from torch.backends import cudnn
from torch.utils.data import DataLoader
sys.path.insert(0,os.path.abspath(os.path.dirname(__file__)+o... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2018 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import numpy as np
import numpy.core.numeric as ncn
from numpy import array, zeros, isnan
from pandas import DataFrame
from panda... |
import os
if not os.environ.get('READTHEDOCS', None):
from ._compare import run as compare
from ._correct import run as correct
from ._finder import run as finder
from ._phylogeny import run as phylogeny
# import _stats as stats
from pkg_resources import get_distribution, DistributionNotFound... |
import os
import re
def translate(pat, match_end=r"\Z"):
"""Translate a shell-style pattern to a regular expression.
The pattern may include ``**<sep>`` (<sep> stands for the platform-specific path separator; "/" on POSIX systems) for
matching zero or more directory levels and "*" for matching zero or mo... |
# noqa: D100
from dataclasses import dataclass
from decimal import Decimal
from typing import Optional
@dataclass(frozen=True)
class Country:
"""Represents a country.
Attributes:
id: The ID of the country.
name: The name of the country.
country_code: Alpha-2 codes used by the ISO 316... |
from django.contrib import admin
from .models import Ns, Nvf
class NsModelAdmin(admin.ModelAdmin):
list_display = ["name", "update", "timestamp"]
list_display_links = ["update"]
list_filter = ["update", "timestamp"]
list_editable = ["name"]
search_fields = ["name"]
class Meta:
model =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.