text stringlengths 1 927k |
|---|
from django.urls import path
from . import views
urlpatterns = [
path('', views.upload_page, name='upload_page')
] |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 l... |
import logging
import opentracing
from jaeger_client import Config
def init_tracer(service):
logging.getLogger('').handlers = []
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
config = Config(
config={
'sampler': {
'type': 'const',
'para... |
"""
Shocks is a module that consists of canonical hydrodynamical
equations used for modeling astrophysical plasmas
Classes:
Shocks -- A class that emcompasses a multitude of hydrodynamical
shock equations relevant for plasma calculations.
Functions:
rh_density -- Returns the density jump relation deri... |
from __future__ import absolute_import
from south.db import db
from django.db import models
from smsgateway.models import *
class Migration:
def forwards(self, orm):
# Adding model 'SMS'
db.create_table('smsgateway_sms', (
('id', orm['smsgateway.SMS:id']),
('se... |
#!/usr/bin/python
import argparse
import os
import subprocess
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'archive_path', type=str, default=None, nargs='?')
parser.add_argument(
'--dry', action='store_true', default=False)
args = parser.parse_args()
... |
from opennem.pipelines.nem.opennem import NemwebUnitScadaOpenNEMStorePipeline
from opennem.spiders.nemweb import NemwebSpider
class NemwebLatestPriceSpider(NemwebSpider):
name = "au.nem.latest.price"
start_url = (
"http://www.nemweb.com.au/Reports/CURRENT/Dispatchprices_PRE_AP/"
)
limit = 1
... |
from typing import Union, Optional, List
from unittest import TestCase
import pyarrow as pa
import pandas as pd
import numpy as np
from h1st.schema.schema_validator import SchemaValidator
dummy = lambda: None
class SchemaTestCase(TestCase):
def test_validate_schema(self):
# empty schema
self.ass... |
#!/usr/bin/env python
# Copyright 2016 OpenMarket Ltd
# Copyright 2020 The Matrix.org Foundation C.I.C.
#
# 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/... |
"""
Mask R-CNN
Common utility functions and classes.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
"""
import sys
import os
import logging
import math
import random
import numpy as np
import tensorflow as tf
import scipy
import skimage.color
impo... |
#!/usr/bin/env python
from actions.action import Action
import os
import contextlib
import re
import shutil
__author__ = "Ryan Sheffer"
__copyright__ = "Copyright 2020, Sheffer Online Services"
__credits__ = ["Ryan Sheffer", "VREAL"]
class Copy(Action):
"""
Copy Action
An action designed to copy file/s ... |
from .cdm_attribute_context_type import CdmAttributeContextType
from .cdm_data_format import CdmDataFormat
from .cdm_object_type import CdmObjectType
from .cdm_relationship_discovery_style import CdmRelationshipDiscoveryStyle
from .cdm_status_level import CdmStatusLevel
from .cdm_validation_step import CdmValidationSte... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-18 23:54
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('user', '0025_remove_user_user_todo'),
]
operations = [
migrations.RenameField(
... |
# kombu v4 will come out with the following commit in:
# https://github.com/celery/kombu/commit/010aae8ccf16ad2fa5a9c3d6f3b84b21e1c1677a
# which does the same thing, but this also allows us to not have to enable
# insecure serializers
from datetime import datetime
import msgpack
import six
from kombu.serialization im... |
# Follow every step every server's log has gone through
# Formulate a conclusion
# Also count blocks
# a search function, a 1 file assembler of all log files
import os, glob, sys
import argparse
from datetime import datetime
def main():
# Initialize parser
parser = argparse.ArgumentParser()
# Addi... |
from __future__ import absolute_import
import sys
from sentry_sdk.hub import Hub
from sentry_sdk.integrations import Integration
from sentry_sdk.scope import add_global_event_processor
if False:
from typing import Any
from typing import Dict
class ArgvIntegration(Integration):
identifier = "argv"
... |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import inspect
import re
from logging import getLogger
from pathlib import Path
from typing import Union, List, Optional, Dict
from packit.patches import PatchMetadata
from rebasehelper.helpers.macro_helper import MacroHelper
from rebasehe... |
from setuptools import setup
with open('README.md', 'r') as ld:
long_description = ld.read()
setup_args = dict(
name='guate.division-politica',
use_scm_version=True,
packages=['guate.division_politica'],
include_package_data=True,
author='Darwin Monroy',
author_email='contact@darwinmonroy.... |
# 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 ... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
import RPi.GPIO as GPIO
from time import sleep
from modules import ping_sensor
from modules import motor_board
from modules import control_surfaces
# create controller
gamePad = control_surfaces.XboxController()
# Motor board pins
motor_board.init_motor_pins([7, 11, 13, 15])
# Ping sensor
ping1 = ping_sensor.PingSensor... |
#!/usr/bin/env python
from math import log
x = 2
y = 1000
# get sum of exp of 2 = y
t = y
exp = 0
l = list()
while y > 0:
if y & 1:
l.append(exp)
exp += 1
y >>= 1
# get mult
mult = x # x ^ 1 = x ^ (2^0)
cur_exp = 0
res = 1
for exp in l:
while cur_exp < exp:
mult **= 2
... |
import os
import shutil
import time
from mklib import Task
from mklib.common import relpath
class foo(Task):
default = True
results = ["foo.txt"]
deps = ["bar.txt"]
def make(self):
src = self.deps[0].path
dst = self.results[0].path
self.log.info("cp %s %s", relpath(src), relpat... |
from __future__ import absolute_import
from QPublic import (MarketData) |
import seaborn as sb
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
person = {'finances':[1,2,3,4,5,6,7,8,7,6,5,4,3,2,1,7,4,1,8,5,2,9,6,3,9,8,7,6,5,4,3,2,1,1,9,7,3,8,2,7],
... |
import time
import telebot
import components.config as config
import components.dialogs as dialogs
from components.config import UserState
from components.core import bot, logger
from components.database.dbworker import DatabaseWorker
from components.dialogs import DialogEvent
from data.subject_list import subject_lis... |
#add parent dir to find package. Only needed for source code build, pip install doesn't need it.
import os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0,parentdir)
import gym
from pybullet_en... |
"""
Search space from Efficient Neural Architecture Search (Pham'17)
"""
from __future__ import print_function
from builtins import str
from builtins import range
from builtins import object
from collections import OrderedDict
import tensorflow as tf
import numpy as np
from deep_architect.helpers import tensorflow_ea... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from api.models.utils.distribution import sample_from_discretized_mix_logistic
from api.models.utils.display import *
from api.models.utils.dsp import *
import os
import numpy as np
from pathlib import Path
from typing import Union
class ResBlock(nn.M... |
#
# Copyright (c) dushin.net All Rights Reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the foll... |
"""The tests for the sun automation."""
from datetime import datetime
import pytest
from homeassistant.components import sun
import homeassistant.components.automation as automation
from homeassistant.const import SUN_EVENT_SUNRISE, SUN_EVENT_SUNSET
from homeassistant.setup import async_setup_component
import homeass... |
import os
import sys
from setuptools import find_packages, setup, Extension
try: # for pip >= 10
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
try:
from setuptools_rust import RustExtension
except ImportError:
import subprocess
errno... |
from __future__ import absolute_import
from datetime import timedelta
import pytest
from django.db.models import ProtectedError
from django.utils import timezone
from sentry.models import (
Group,
GroupRedirect,
GroupSnooze,
GroupStatus,
Release,
get_group_with_redirect,
)
from sentry.testuti... |
import importlib
from json import loads
from base64 import b64decode
import sys
import gevent.monkey
gevent.monkey.patch_all()
import gevent
import config
from os import getpid
from requests import post
def fetch(module):
global message
m = importlib.import_module('modules.'+module)
m.go(message)
def ... |
import torch
import numpy as np
from tqdm import tqdm
from sklearn import cluster
#bol_norm True -> Divide by norm of feature
def same_score(v_ortho_dict, features, labels, bol_norm=False):
features = torch.from_numpy(features).cuda()
scores = torch.zeros(features.shape[0])
for indx, feat in enumerate... |
"""doc_finder URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/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-ba... |
from discord.ext import commands
from .root import attach_root
from .base import attach_base
from .system import attach_system
from .region import attach_region
from .friend import attach_friend
from .enemy import attach_enemy
from .unrecognized import attach_unrecognized
from .forum import attach_forum
def attach_co... |
from .driver import ELEMENTS as driverElements
from .profile import ELEMENTS as profileElements
# from . import * |
import configparser
import functools
from os import path
from pathlib import Path
class Config():
"""Config wrapper that reads global config and user config."""
PROJECT_ROOT = path.join(path.dirname(path.realpath(__file__)), '..')
CONFIG_INI = path.join(PROJECT_ROOT, 'config.ini')
HOME_DIR = Path.hom... |
from __future__ import unicode_literals
from django.http import HttpResponse
from django.contrib import messages
from django.views.decorators.http import require_http_methods
from django.shortcuts import render, redirect
from django.utils import timezone
from app.decorators import user_is_authenticated
from app.model... |
"""
Goal - to produce a csv file with temp, gs rep, loom and latency
"""
import os
import pathlib
from pprint import pprint
import numpy as np
from scipy import stats
from scipy.spatial import distance
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import trajectorytools as tt
import trajector... |
# 3.5 Sort Stack
# Write a program to sort a stack such that the smallest items are on top.
# You can use an additional temporary stack, but you may not copy the elements into
# any other data structure such as an array.
# The stack supports the following operations: push, pop, peek, and isEmpty. |
#!/usr/bin/python
from __future__ import unicode_literals
from collections import namedtuple
import copy
import json
import math
import mmap
import os
import re
import struct
import sys
from threading import Lock
import time
from timeit import default_timer
import types
from .decorator import decorate
if sys.versio... |
from __future__ import annotations
from dataclasses import dataclass
import pydub
from sauronlab.core.core_imports import *
class AudioTools:
""" """
@classmethod
def save(
cls, audio_segment: pydub.AudioSegment, path: PathLike, audio_format: str = "flac"
) -> None:
path = Tools.pr... |
"""Submodule for NeuroKit."""
# Aliases
from ..signal import signal_rate as ecg_rate
from .ecg_analyze import ecg_analyze
from .ecg_clean import ecg_clean
from .ecg_delineate import ecg_delineate
from .ecg_eventrelated import ecg_eventrelated
from .ecg_findpeaks import ecg_findpeaks
from .ecg_intervalrelated import ec... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from .models import Profile,OAuthRelationship
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
class UserAdmin(BaseUserAdmin):
inlines =... |
from setuptools import setup
setup(
name="mgxsim",
version="0.0.1",
description="metagenomics utils.",
packages=["mgxsim"],
install_requires = [
"biopython",
"pandas",
],
) |
import os
import cppyy
from .initializor import initialize
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'VERSION')) as fp:
__version__ = fp.read().strip()
initialize('goetia', 'libgoetiaCppyy.so', 'goetia.map')
del initialize
from goetia import goetia as libgoetia
from cppyy import nullptr |
"""
hydrofunctions.typing
~~~~~~~~~~~~~~~~~~~~~
This module contains functions for testing that user input is valid.
Why 'pre-check' user imputs, instead of using standard
python duck typing? These functions are meant to enhance an interactive
session for the user, and will check a user's parameters
before requesting... |
from __future__ import print_function
import mmtbx.model_vs_data
import libtbx.load_env
from six.moves import cStringIO as StringIO
import os.path as op
import os
import sys
def run():
html_dir = libtbx.env.find_in_repositories(relative_path="phenix_html")
dest_dir = op.join(html_dir, "rst_files", "reference")
l... |
import pytest
import allure
from config.credentials import Credentials
from framework.pages.HomePage import HomePage
from infra.screenshot_generator import get_screenshot
from infra.shared_steps import SharedSteps
from infra.string_util import identifier_generator
@allure.title('Test navigation into "New Project" pag... |
from dataset.electric_dataloader import ElectricDataloader
from dataset.preprocessor import Preprocessor
class WrappedDataloader:
def __init__(self, dataloader, func):
self.dataloader = dataloader
self.func = func
def __len__(self):
return len(self.dataloader)
def __iter__(self):... |
# RUN: %PYTHON %s 2>&1 | FileCheck %s
import ctypes
import sys
from mlir.ir import *
from mlir.dialects import builtin
from mlir.dialects import linalg
from mlir.dialects import std
from mlir.passmanager import *
from mlir.execution_engine import *
# Log everything to stderr and flush so that we have a unified strea... |
from pecan import rest
from wsme import types as wtypes
from webdemo.api.controllers.v1 import controller as v1_controller
from webdemo.api import expose
class RootController(rest.RestController):
v1 = v1_controller.V1Controller()
@expose.expose(wtypes.text)
def get(self):
return "webdemo" |
from collections.abc import Callable
import warnings
import numpy as np
from scipy.optimize import fsolve
from ..core import Function, find_roots, ConstantFunction
from ..eigenfunctions import SecondOrderOperator
from ..placeholder import (ScalarFunction, TestFunction, FieldVariable, ScalarTerm,
... |
# -*- 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 'Account'
db.create_table(u'account_account', (
... |
#
# This file is part of LiteX.
#
# Copyright (c) 2021 Franck Jullien <franck.jullien@collshade.fr>
# SPDX-License-Identifier: BSD-2-Clause
import os
import csv
import re
import datetime
from xml.dom import expatbuilder
import xml.etree.ElementTree as et
from litex.build import tools
namespaces = {
"efxpt" : "h... |
# -*- coding: utf-8 -*-
"""
Created April 2019
@author: Amon Millner
This is a module that contains a class that serves as a model
for the totem game built, which is an example of the
Model-View-Controller (MVC) framework.
"""
import pygame, copy
from pygame.locals import *
import random
class TotemModel(object):
... |
"""
Copyright (c) 2021 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
import pytest
import tarfile
import io
import os
from flexmock import flexmock
from pathlib import Path
from osbs.utils import ImageName
fr... |
#!/usr/bin/env python
"""
genome_download: downloading genomes
Usage:
genome_download [options] <accession_table>
genome_download -h | --help
genome_download --version
Options:
<accessin_table> Taxon-accession table (see Description).
Use '-' if from STDIN.
-d=<d> Output dir... |
# -*- coding: utf-8 -*-
from model.contact import Contact
from selenium.webdriver.support.ui import Select
import re
class ContactHelper:
def __init__(self, app):
self.app = app
def fill_contact_form(self, contact):
wd = self.app.wd
# fill contact fields (displayd on home page)
... |
from django.db import models
from django.utils import timezone
from users.models import CustomUser
from primaseru import choices
class StudentStatus(models.Model):
student = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
accepted = models.BooleanField('Diterima', db_index=True, null=True)
maj... |
# *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions... |
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class HighwayNetwork(nn.Module):
def __init__(self, size):
super().__init__()
self.W1 = nn.Linear(size, size)
self.W2 = nn.Linear(size, size)
self.W1.bias.data.fill_(0.)
def... |
# Slixmpp: The Slick XMPP Library
# Copyright (C) 2010 Nathanael C. Fritz
# This file is part of Slixmpp.
# See the file LICENSE for copying permission.
from slixmpp.xmlstream.stanzabase import StanzaBase
from slixmpp.xmlstream.handler import Waiter
class XMLWaiter(Waiter):
"""
The XMLWaiter class is identi... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# File: expreplay.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import numpy as np
from collections import deque, namedtuple
import threading
from tqdm import tqdm
import six
from six.moves import queue
from ..dataflow import DataFlow
from ..utils import *
from ..utils.con... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
from django.core.management.base import BaseCommand, CommandError
from data_ocean.command_progress import CommandProgress
from data_ocean.savepoint import Savepoint
from person.controllers import ConnectorsController, SOURCES
class Command(BaseCommand):
help = '---'
def add_arguments(self, parser):
p... |
# -*- coding: utf-8 -*-
# Copyright © 2012-2013 Roberto Alsina and others.
# 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 t... |
import cv2 as cv
import os
import numpy as np
import pdb
import ntpath
import glob
from Parameters import *
def show_detections_without_ground_truth(detections, scores, file_names, params: Parameters):
"""
Afiseaza si salveaza imaginile adnotate.
detections: numpy array de dimensiune NX4, unde N este numa... |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
# Always prefer setuptools over distutils
from setuptools import setup
# To use a consistent encoding
from codecs import open
from os import path
HERE = path.abspath(path.dirname(__file__))
# Get the long descr... |
computers = int ( input () )
total_computers = computers
total_rating = 0
total_sales = 0
while not computers == 0:
command = int ( input () )
possible_sales = 0
last_digit = command % 10
first_two_digits = command // 10
rating = last_digit
if rating == 3:
possible_sales = first_two_digi... |
# -*- coding: utf-8 -*-
import hashlib, random
def sha(s):
return hashlib.sha256(s).hexdigest()[:16]
def _salt():
return str(random.randint(1,99999999))
def save_point(phash,u):
open('points.txt','a').write('%s:%s\n' % (phash,u))
def check_hash(s):
p = open('points.txt').read().splitlines()
for... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import os
import subprocess
import seedot.config as config
import seedot.util as Util
# Program to build and run the predictor project using msbuild
# The accuracy and other statistics are written to the output file specifi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#############################################
# WARNING #
#############################################
#
# This file is au... |
import csv
import sys
import numpy as np
with open(sys.argv[1]) as modelFile:
modelLoader = csv.reader(modelFile, delimiter=' ')
xs = []
ys = []
zs = []
for lineIndex, line in enumerate(modelLoader):
if len(line) == 0:
continue
if line[0] == 'v':
xs.a... |
import decimal
import hmac
import numbers
import sys
PY2 = sys.version_info[0] == 2
if PY2:
from itertools import izip
text_type = unicode # noqa: 821
else:
izip = zip
text_type = str
number_types = (numbers.Real, decimal.Decimal)
def _constant_time_compare(val1, val2):
"""Return ``True`` if ... |
"""The data store contains offline versions of the data so that you can run a
demo version of the website without the vault keys, or simply develop parts of
the website that don't require actively updated data without having to worry.
This data is used for the actual website when the `USE_MOCK_DATA` config
variable is... |
"""
Functions for exception manipulation + custom exceptions used by PyScaffold to identify
common deviations from the expected behavior.
"""
import functools
import logging
import sys
import traceback
from typing import Optional, cast
if sys.version_info[:2] >= (3, 8):
# TODO: Import directly (no need for conditi... |
#!/usr/bin/env python3
# Copyright (c) 2017-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test HD Wallet keypool restore function.
Two nodes. Node1 is under test. Node0 is providing transactio... |
""" Unit tests for pipelines expressed via dask.delayed
"""
import logging
import sys
import unittest
import numpy
from astropy import units as u
from astropy.coordinates import SkyCoord
from data_models.polarisation import PolarisationFrame
from processing_components.image.operations import export_image_to_fits, ... |
from replit import db
from locales import locales
# ========================================================
# Posts message to discord channel (translated according to channel)
# ========================================================
async def say(channel, message, arguments=None):
message = locales.get(get_chann... |
# Copyright (c) 2020-2021, NVIDIA CORPORATION.
#
# 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... |
# Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Fa... |
"""
sphinxnotes.snippet.builder
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dummy builder for triggering extension.
:copyright: Copyright 2021 Shengyu Zhang.
:license: BSD, see LICENSE for details.
"""
from sphinx.builders.dummy import DummyBuilder
from sphinx.locale import __
class Builder(DummyBuilder):
... |
foo = [1, 2, 3, 4, 6, 9, 10]
def search(arr, item):
for i in arr:
if i == item:
return True
elif i > item:
return False
return False
print(search(foo, 5))
print(search(foo, 9))
print(search(foo, 20)) |
# Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - Mario Lassnig, <mario... |
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from . import RecordStatusEnum
class LinkNote(models.Model):
id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=20
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
class Opty(cirq.PointOptimizer):
def optimization_at(
... |
import logging
import numpy as np
from mjrl.utils.gym_env import GymEnv
from mjrl.utils import tensor_utils
logging.disable(logging.CRITICAL)
import multiprocessing as mp
from multiprocessing import set_start_method
try:
set_start_method('spawn')
except RuntimeError:
pass
import time as timer
import torch
loggi... |
import sys
import time
import pytest
from easyprocess import EasyProcess
python = sys.executable
def test_timeout():
p = EasyProcess("sleep 1").start()
p.wait(0.2)
assert p.is_alive()
p.wait(0.2)
assert p.is_alive()
p.wait(2)
assert not p.is_alive()
assert EasyProcess("sleep 0.3").... |
from api.tests.base import BaseTestCase
class TestUserViews(BaseTestCase):
""" Test Profile views """
def test_get_profile(self):
""" Test can get single user profile """
self.create_user(self.new_user)
response = self.test_client().get('/api/v1/accounts/baduism/profile/')
self... |
# Problem: https://www.hackerrank.com/challenges/py-if-else/problem
# Score: 10 |
import pandas as pd
import numpy as np
#import random as rd
#from sklearn.neighbors import NearestNeighbors
#from scipy.sparse import csr_matrix
# OWN
from cyclorec.data_layers.data_layer import DataLayer
class FFeedbackCm100kLayer(DataLayer):
""" The only difference between this layer and Cm100kLayer is the feed... |
from .callbacks import Callback
from timeit import default_timer
from numbers import Number
import sys
overhead = sys.getsizeof(1.23) * 4 + sys.getsizeof(()) * 4
class Cache(Callback):
"""Use cache for computation
Examples
--------
>>> cache = Cache(1e9) # doctest: +SKIP
The cache can... |
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import resnet
# ============================================================================ #
# Baseline network #
# ====================... |
from sklearn import neural_network
import learners
class ANNLearner(learners.BaseLearner):
def __init__(self,
hidden_layer_sizes=(100,),
activation="relu",
solver='adam',
alpha=0.0001,
batch_size='auto',
learnin... |
# vim: fileencoding=utf-8
# Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Andrey Golovizin
#
# 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... |
# 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
# d... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Build go.html
# ----------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.