content stringlengths 5 1.05M |
|---|
#
# CAMP
#
# Copyright (C) 2017 -- 2019 SINTEF Digital
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
from camp.codecs.yaml import YAML
from camp.commands import Command
from camp.core import Camp
from camp.directori... |
"""
A control model to test whether the models I have developed create any improvement in accuracy
"""
import torch.nn as nn
import torch
import torch.optim as optim
from torchvision import datasets
from torchvision.transforms import ToTensor
from torch.utils.data import DataLoader, random_split
import time
import tor... |
#!/usr/bin/env python3
import sys, os
if __name__ == '__main__':
if len(sys.argv) != 3:
print(sys.argv[0], 'object', 'output')
sys.exit(1)
elif os.path.exists(sys.argv[1]):
with open(sys.argv[2], 'wb') as out:
pass
else:
sys.exit(1)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode PyQt4 tutorial
In this example, we select a font name
and change the font of a label.
author: Jan Bodnar
website: zetcode.com
last edited: October 2011
"""
import sys
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
... |
r"""
Hall-Littlewood Polynomials
Notation used in the definitions follows mainly [Mac1995]_.
REFERENCES:
.. [Mac1995] I. G. Macdonald, Symmetric functions and Hall polynomials, second ed.,
The Clarendon Press, Oxford University Press, New York, 1995, With contributions
by A. Zelevinsky, Oxford Science Publicat... |
import time
import pickle
import asyncio
import warnings
import aiohttp.web
try:
import aioredis
except ImportError:
warnings.showwarning("aioredis library not found. Redis cache client not available")
class BaseStaticBuilder(object):
def __init__(self, expiration: int = 300, base_path: str = None)... |
"""D-Bus type signature."""
from collections import Counter
from . import marshal
from .const import MAX_SIGNATURE_LEN, MAX_NESTING_DEPTH
from .errors import SignatureError
__all__ = ['Signature']
class Signature:
"""A signature.
The signature string will be parsed into a list of complete types.
Each ... |
from django.db import models
from django.contrib.auth import get_user_model
import uuid
class Camera(models.Model):
owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='cameras')
lat = models.DecimalField(blank=True, max_digits=9, decimal_places=6, default=None, null=True)
... |
"""
Test cases for the entity module
To connect to google cloud datastore service from your local
machine, set up the GOOGLE_APPLICATION_CREDENTIALS
environment variable with service account key file
Example:
export GOOGLE_APPLICATION_CREDENTIALS="/code/auth/dev/datastore-service-account.json"
"""
import datetime
... |
from typing import Iterable
from .safe import is_iterable
def test_is_iterable() -> None:
def gen() -> Iterable[None]:
yield
class NoSpecialMethods(object):
pass
class HasIter(object):
def __iter__(self) -> Iterable[int]:
yield 1
class HasGetItemAndLen(object):
... |
from wordbook.domain.repo.translation import Repo
from wordbook.domain.models import Translation
def test_add_translation():
repo = Repo()
translation = repo.add_translation(
Translation(
from_language='en',
into_language='pl',
word='Apple',
ipa='ejpyl',... |
from __future__ import print_function
import numpy as np
import os
class NpzDataset(object):
'''
Write out NPZ datasets one file at a time, with information in filenames
for easy access and data aggregation.
This is a fairly slow way to do things but prevents a lot of the problems
with massive a... |
""" Split protcur.ttl into multiple files with one file per protocol.
"""
import tempfile
import idlib
import rdflib
import htmlfn as hfn
from pyontutils.core import OntResIri, OntGraph
from pyontutils.namespaces import sparc, rdf, owl, ilxtr, TEMP
from sparcur.core import OntId
from sparcur.utils import GetTimeNow
fr... |
# Generated by Django 3.0.2 on 2020-02-04 09:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Cards', '0011_auto_20200203_1715'),
]
operations = [
migrations.AddField(
model_name='question',
name='source',
... |
import pygame,os,sys,random,math,time
from pygame.locals import *
pygame.init()
#some rgb colors
background = pygame.Color(85,50,253)
fontColor = pygame.Color(0,162,232)
green = pygame.Color(0,90,50)
buttonColor=pygame.Color(36,38,123)
white = pygame.Color(255,255,255)
#global variables
count=0
score=0
... |
"""
XLSX data adapter
*****************
This adapter loads data from xlsx tables and transforms it in a dictionary
supported by N2G diagram plugins. Using ``from_dict`` method, this adapter
loads data in diagram plugin.
**Prerequisites**
* `openpyxl <https://pypi.org/project/openpyxl/>`_ >= 3.0.0 library need to be... |
from flask import Flask, render_template, request
from flask_pymongo import PyMongo
# import request_tree
#################################################
# Flask Setup
#################################################
app = Flask(__name__)
#################################################
# Flask Routes
######... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import utils.io as io
class KVIdentity(nn.Module,io.WritableToFile):
def __init__(self):
super().__init__()
def forward(self,x):
K = x
V = x
return K,V
class Ca... |
#!/usr/bin/env python
import unittest
from palo_alto_firewall_analyzer.core import ProfilePackage
from palo_alto_firewall_analyzer.pan_config import PanConfig
from palo_alto_firewall_analyzer.validators.similar_addresses_and_groups import find_similar_addresses_and_groups
class TestSimilarAddressesAndGroups(unittest... |
"""
Copyright 2013 Rackspace
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
dist... |
"""
Problem 18: Maximum path sum I
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 ... |
# Write a procedure, shift, which takes as its input a lowercase letter,
# a-z and returns the next letter in the alphabet after it, with 'a'
# following 'z'.
def shift(letter):
return chr(ord(letter) + 1) if letter != 'z' else 'a'
print (shift('a'))
#>>> b
print (shift('n'))
#>>> o
print (shift('z'... |
"""
Copyright 2007, 2008, 2009 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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... |
import os
import sys
import tempfile
import platform
import venv
env_os = "windows" if platform.system() == "Windows" else "centos7"
env_py = f"py{sys.version_info[0]}.{sys.version_info[1]}"
env_dir = tempfile.TemporaryDirectory(prefix="pyprt-test-venv")
venv.create(env_dir.name, with_pip=True)
bin_segment = "Script... |
# Copyright (c) 2016 by Mike Jarvis and the other collaborators on GitHub at
# https://github.com/rmjarvis/Piff All rights reserved.
#
# Piff is free software: Redistribution and use in source and binary forms
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redist... |
class Token:
def __init__(self, type_, value=None, pos_start=None, pos_end=None):
self.type = type_
self.value = value
if pos_start:
self.pos_start = pos_start.copy()
self.pos_end = pos_start.copy()
self.pos_end.advance()
if pos_end:
... |
import unittest
from neo.rawio.axonrawio import AxonRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
class TestAxonRawIO(BaseTestRawIO, unittest.TestCase, ):
rawioclass = AxonRawIO
entities_to_test = [
'axon/File_axon_1.abf', # V2.0
'axon/File_axon_2.abf', # V1.8
... |
# Generated by Django 3.1.6 on 2021-02-23 17:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('AAA', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='Course',
new_name='Items',
),
migr... |
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from .permissions import PERMISSION_INSTALLATION_DETAILS
link_menu_link = {'text': _('Installation details'), 'view': 'installation:namespace_list', 'icon': 'main/icons/interface_preferences.png', 'permissions': [PERMISSI... |
# -*- coding: utf-8 -*-
from scrapy import signals, Request
from scrapy.http import HtmlResponse #%
from scrapy.exceptions import IgnoreRequest
from django.utils import timezone
import os
import time
import random
from time import time as now
from dateutil.relativedelta import relativedelta
from .keys import START_URL,... |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
This example uses the light sensor on the Circuit Playground, located next to the picture of the
eye on the board. Once you have the library loaded, try shining a flashlight on your Circuit
Playground to watch the number ... |
# Added at : 2016.8.3
# Author : 7sDream
# Usage : A block of bits. In this class, we let each point (including EC)
# as much as possible to meet the color of image in it's position.
from ..common import Bits, one_at, bit_at, BIT_PER_CW
from ..qr.ec import RSEncoder
__all__ = ['BitBlock']
_VS_CACH... |
#!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
from pyscf.pbc.tddft import rks
from pyscf.pbc.tddft import rhf
|
"""File to handle all ffmpeg requests"""
import os
import os.path as osp
import subprocess as sp
import platform
import json
import numpy as np
from kotools import CPUse, GPUse
from .utils import Col
from .io_main import IO
class FF():
"""wrapper class to ffmpeg, ffprobe, ffplay
#TODO inherit VIDI and IO
... |
from dashboard.models import Homework, Notes, Todo
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(Notes)
admin.site.register(Homework)
admin.site.register(Todo) |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
import Ska.quatutil
from Quaternion import Quat
ra1 = 10.
dec1 = 20.
ra2 = ra1 + .5
dec2 = dec1 - .1
roll = 30.
q0 = Quat([ra1, dec1, roll])
def test_radec2eci():
eci = Ska.quatutil.radec2eci(ra1, dec1)
assert np.allclose(ec... |
# RA, 2021-03-17
import unittest
import io
from tcga.utils import Peek
class TestPeek(unittest.TestCase):
def test_no_arg(self):
with Peek():
pass
def test_with_arg(self):
with Peek(print):
pass
def test_callable_empty(self):
with Peek(lambda x: None) as ... |
#-*- coding: UTF-8 -*-
from setuptools import setup, find_packages
from sci_clone import config
with open('requirements.txt') as f:
REQUIREMENTS = f.readlines()
with open('README.md') as f:
LONG_DESCRIPTION = f.read()
setup(
name=config.__name__,
version=config.__version__,
description=config... |
from pathlib import Path
from srsly import json_loads
_here = Path(__file__).parent
meta = json_loads((_here / "meta.json").read_text())
data_path = _here / meta["fullname"]
|
import pytest
@pytest.mark.parametrize("test_app", [{"buildername": "html", "srcdir": "doc_test/broken_links"}], indirect=True)
def test_doc_build_html(test_app):
app = test_app
app.build()
warning = app._warning
# stdout warnings
warnings = warning.getvalue()
assert "Needs: linked need BROK... |
#!/usr/bin/env python
# coding:utf-8
import rospy
import serial
import struct
from std_msgs.msg import Int32
from std_msgs.msg import Float32
def motor_callback(msg):
if not isinstance(msg, Int32): return
# 接受到其他节点发送的数据
pwm = msg.data
# 给下位机发送指令
# 电机的驱动
pack = struct.pack('h', pwm)
data... |
import random
from asyncio import sleep as sl
import discord
from discord.ext import menus
class VotingMenu(menus.Menu):
def __init__(self, bot):
super().__init__()
self.bot = bot
self.bot.owner = (
"[DHRUVA SHAW#0550](https://discord.com/users/571889108046184449/)"
)
... |
from starlette.applications import Starlette
from starlette.authentication import AuthCredentials, AuthenticationBackend, SimpleUser
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.middleware.gzip import GZipMiddleware
from starlette.middleware.sessions import SessionMiddleware
f... |
from .adjacency import *
from .geo import *
from .graph import *
|
#!/usr/bin/python
"""
This is a Python client for the Lastline Analyst API.
The :py:class:`AnalysisClient` class implements the client side of the Lastline Analyst API
methods. It can be imported into Python client code that uses the API.
The client is available at https://analysis.lastline.com/docs/llapi_client/anal... |
#!/usr/bin/env python
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# 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 ... |
class ESC(object):
def __init__(self):
self.currents = []
self.temperatures = []
def update(self):
pass
@property
def data(self):
return {
'currents': self.currents,
'temperatures': self.temperatures
} |
"""
# Isofill (Gfi) module
"""
#
#
# Module: isofill (Gfi) module #
#
# Copyright: 2000, Regents of the University of California #
# This software may not be distributed to others without #
# permission of the author. ... |
class TanBinaryTree:
def __init__(self) -> None:
self.depth = 0
self.a = 1
self.b = 0
self.c = 1
self.left = None
self.right = None
def get_b(seq):
pass
def get_c(seq):
pass
def get_a(seq):
pass
def tan_b(seq):
"""
... |
import hashlib
"""
s="HAHAHA"
digest= hashlib.sha256(s.encode()).hexdigest();
print(digest);
<>
"""
lastNode=""
block0={"name":"", "age":"", "previousHash":hashlib.sha256("000".encode()).hexdigest(), "blockHash":""}
block0['blockHash']= hashlib.sha256(str(block0).encode()).hexdigest()
blockchain= [block0]
def crea... |
# -*- coding: utf-8 -*-
import unittest
import numpy as np
import torch
from comet.metrics import RegressionReport, WMTKendall
class TestMetrics(unittest.TestCase):
def test_regression_report(self):
report = RegressionReport()
a = np.array([0, 0, 0, 1, 1, 1, 1])
b = np.arange(7)
... |
def init_matriz(l, c, matriz):
for k in range(1, l+1):
linha = []
for d in range(1, c+1):
num = int(input(f'Digite o elemento {k}-{d} da matriz: '))
linha.append(num)
matriz.append(linha)
def change_elemento(a1, a2, matriz):
element1 = matriz[a1//10][a1%10]
e... |
#@+leo-ver=5-thin
#@+node:ekr.20090717092906.12765: * @file leoVersion.py
"""
A module holding the following version-related info:
leoVersion.static_date: The date of official releases.
Also used when the git repo is not available.
leoVersion.version: Leo's version number.
"""
#@+<< version... |
# Import General Packages:
import numpy as np
import os
import tensorflow as tf
import warnings
warnings.filterwarnings("ignore")
import time
from functools import partial
# Import User-defined Modules:
from dataset_generation import prepare_data_list, get_data
from deep_learning_models import vgg16_model, vgg19_... |
"""
LeetCode Problem: 300. Longest Increasing Subsequence
Link: https://leetcode.com/problems/longest-increasing-subsequence/
Written by: Mostofa Adib Shakib
Language: Python
Time Complexity: O(n^2)
Space Complexity: O(n)
"""
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
length = len(nums... |
from qt import *
from qtcanvas import *
from treecanvasnode import *
from nodefeaturedialog import *
from translator import translate
from axis import *
import lpath
import math
class FilterExpressionPopup(QLabel):
def __init__(self, parent):
self.super = QLineEdit
self.super.__init__(self, parent)... |
"Helper utility for working with pnpm lockfile"
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load("@bazel_skylib//lib:types.bzl", "types")
load("//js/private:pnpm_utils.bzl", "pnpm_utils")
def gather_transitive_closure(packages, no_optional, direct_deps, transitive_closure):
"""Walk the dependency tree, collecti... |
# Copyright (c) 2016, #
# Author: Amjad Yousef Majid #
# Date: 16/06/2016 #
# All rights... |
from os import listdir
from os.path import isfile, join
import matplotlib.pyplot as plt
import gpxpy
data_path = '../tracks'
data = [f for f in listdir(data_path) if isfile(join(data_path,f))]
lat = []
lon = []
fig = plt.figure(facecolor = '0.05')
ax = plt.Axes(fig, [0., 0., 1., 1.], )
ax.set_aspect('equal')
ax.set_... |
from tests import utils
import bpy
class TestDmExport(utils.XRayTestCase):
def test_export_single(self):
# Arrange
self._create_dm_objects()
# Act
bpy.ops.xray_export.dm_file(
detail_model='tdm1', filepath=self.outpath('test.dm'),
texture_name_from_image_p... |
# Copyright (c) 2016 SUSE. 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 agreed... |
#!/usr/bin/env python
import time
import praw
__all__ = ['PrawOAuth2Mini']
REDIRECT_URL = 'http://127.0.0.1:9999/authorize_callback'
SCOPES = ['identity', 'read']
EXPIRY_DURATION = 3500
class PrawOAuth2Mini:
"""
Creates a `PrawOAuth2Mini` instance. `PrawOAuth2Mini` meant to be
used in the bot and it ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 27 22:14:53 2021
Example workspace demonstrating how to use the optimized Savitzky-Golay filter
@author: Daniel Barnak
"""
import sgfilter
import matplotlib.pyplot as plt
import numpy as np
#%% construct a test signal
randArray = np.random.rand(2000)
xpos = np.arange(0... |
from .._tools import ui_embed
from ._data import *
def success(channel, image, hex_str):
"""
Creates an embed UI containing a hex color message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
image (str): The url of the image to add
hex_str (str): The hex... |
types_dict = {'assessor_book': 'SMALLINT',
'assessor_page': 'SMALLINT',
'assessor_parcel': 'CHAR(3)',
'tract': 'VARCHAR(200)',
'block': 'VARCHAR(50)',
'lot': 'VARCHAR(50)',
'reference_no_old_permit_no': 'VARCHAR(50)',
'pcis_permi... |
"""Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento"""
salario = float(input('Qual o seu salário atual ?'))
aumento = salario*(15/100)
print('Você vai ter um aumento de 15%, ganhará R${}'.format(salario+aumento)) |
import pytest
from api.base.settings.defaults import API_BASE
from osf_tests.factories import ApiOAuth2ScopeFactory, AuthUserFactory
@pytest.mark.django_db
class TestScopeDetail:
def test_scope_detail(self, app):
scope = ApiOAuth2ScopeFactory()
url_scope = '/{}scopes/{}/'.format(API_BASE, scope.... |
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.uti... |
# Listas
meses = ['Enero', 'Febrero', 'Marzo']
# print(meses[1])
# Si usamos posiciones negativas contará de atras hacia adelante
# print(meses[-1])
# Para traer elementos con limites, el primero indica desde donde
# y el segundo hasta que sea menor que
# print(meses[0:2])
# Para agregar elementos a la Lista
meses.... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# -*- coding: utf-8 -*-
###############################################################################
#
# Purpose: Generate GPKG sample file
# Author: Even Rouault <even.rouault at spatialys.com>
#
###############################################################################
# Copyright (c) 2014-2017, Even Roua... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
将训练完成的模型保存
"""
import pickle
from sklearn import svm
from sklearn import datasets
clf = svm.SVC(gamma="scale")
digits = datasets.load_digits()
X, y = digits["data"], digits["target"]
clf.fit(X, y)
# 将模型保存并写入文件
s = pickle.dumps(clf)
with open(... |
class Speaker(object):
def __init__(self):
pass
def say(self, what):
print (what)
def ask(question, answers = []):
"""
answers = -1 : auto press any key (i.e. no questions, all answers accepted)
answers = 0 : auto y/n answers
"""
noChoice = False
if answers == -1:
noChoice = True
elif answers == 0:
... |
# Generated by Django 3.1.1 on 2020-10-30 21:03
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Afiliados',
fields=[
('id', models.AutoFiel... |
def c2f(temp):
convert = (9/5) * temp + 32
return(convert)
def k2c(temp):
return(temp - 273.15)
def k2f(temp):
c = k2c(temp)
f = c2f(c)
return(f)
|
#!/usr/bin/env python
# encoding: utf-8
"""
peer.py
Created by Thomas Mangin on 2009-08-30.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
import unittest
from exabgp.configuration.environment import environment
env = environment.setup('')
from exabgp.configuration.ancient import Configuration
from ... |
# coding: utf-8
from sd_lib.geometry.geometry import Geometry
from sd_lib.geometry.constants import ANY_SHAPE
class AnyGeometry(Geometry):
'''
This is a class for creating and using AnyGeometry for Labels.
'''
@staticmethod
def geometry_name():
return ANY_SHAPE
|
def method_caption(another):
return another()
def add_two_numbers():
return 30 + 77
# print(methodcaption(add_two_numbers))
# print(methodcaption(lambda: 30 + 100))
my_list = [21, 45, 60, 24]
print(list(filter(lambda x: x % 2 == 0, my_list)))
(lambda x: x * 3)(5)
def f(x):
return x * 3
|
from unittest import TestCase
import numpy as np
import sketch.pps_quant
from storyboard.query_cy import CDFSketch
class TestPPSQuantSketch(TestCase):
def test_tiny(self):
np.random.seed(0)
xs1 = np.linspace(0,1,1000)
xs2 = np.linspace(1,2,1000)
gk = sketch.pps_quant.PPSQuantSketc... |
"""
802. Sudoku Solver
https://www.lintcode.com/problem/sudoku-solver/description
DFS搜索顺序优化
"""
class Solution:
"""
@param board: the sudoku puzzle
@return: nothing
"""
def solveSudoku(self, board):
# write your code here
self.dfs(board, self.build_used(board))
def buil... |
import os
from datetime import timedelta
from artifice.scraper.utils import number_of_cores
from artifice.scraper.config.constants import *
ENV = 'production'
DEBUG = False
LOG_LEVEL = 'INFO'
HOST = 'http://127.0.0.1'
LOG_FILE = '/home/ubuntu/log/flask/flask.log'
LOG_FILE = os.environ['LOG_FILE']
AUTH_TOKEN = os.envir... |
import sys
sys.path.append('../keras-rl')
import gym
import numpy as np
import time
from rl.util import load_demo_data_from_file, record_demo_data
from copy import deepcopy
def demonstrate(model, env, nb_steps, data_filepath, nb_max_start_steps=4, start_step_policy=None, verbose=1):
"""
A modified version of t... |
import re
from django.conf import settings
from django.conf.urls.i18n import is_language_prefix_patterns_used
from django.middleware.locale import LocaleMiddleware
from django.utils import translation
from django.utils.translation.trans_real import get_supported_language_variant
referer_language_code_prefix = re.comp... |
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fi... |
# core
import pandas as pd
import numpy as np
# utilities
import sys
import os
import pickle
# utilities v2
from src.experiment.utils import check_pipelines, check_fit_params
from rlearn.model_selection import ModelSearchCV
from rlearn.tools.reporting import report_model_search_results
from sklearn.model_selection i... |
from __future__ import division
import os
import sys
sys.path.append("../eval")
import numpy as np
import scipy.misc
import tensorflow as tf
import argparse
from SfMLearner import SfMLearner
from evaluate_kitti import *
from evaluate_normal import *
from utils import *
def test_image(filename):
mode = 'depth'
... |
import unittest
import strapy as ts
import numpy as np
import pyctmm
class TestStack(unittest.TestCase):
def test_set_length(self):
"""Test that the set_length method produces the correct phase changes.
"""
model = ts.Model()
model.wavelength = 633e-9
model.add_component(... |
def identify_sequence(seq):
differences = [0,0]
differences[0] = seq[1]-seq[0]
differences[1] = seq[2] - seq[1]
if (differences[0] == differences[1]):
print("Arithmetic progression")
else:
print("Geometric progression")
identify_sequence([2,4,7]) |
#import sublime
import sublime_plugin
import SubList
import sublime
import functools
# Eventually this should be end user updatable
corrections = {"bitwdith": "bit-width", "wdith": "width"}
class AutoCorrectCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.run_command("insert", {"charac... |
from dataclasses import dataclass
import logging
from misc import dict_cls
logger = logging.getLogger("discord")
CDN_URL = "https://cdn.discordapp.com"
MESSAGE_LIMIT = 2000
def bitmask(bit: int) -> int:
return 1 << bit
@dataclass
class Channel:
id: str
type: str
guild_id: str = ""
name: str = ... |
# -*- coding: utf-8 -*-
from seaserv import seafile_api
from seahub.utils import EMPTY_SHA1
def list_dir_by_path(cmmt, path):
if cmmt.root_id == EMPTY_SHA1:
return []
else:
return seafile_api.list_dir_by_commit_and_path(cmmt.repo_id, cmmt.id, path)
|
from ._asyncpg_connect import connect
__all__ = ["connect"]
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
def _wrap_instance__resolve(wrapping_functions, instance):
if not hasattr(instance, 'resolve'):
return instance
resolve = getattr(instance, 'resolve')
def _wrap_fun... |
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from .models import Image,Profile
from .forms import ProfileForm, ImageForm, CommentForm
from django.contrib.auth.models import User
# Create your views here.
de... |
'''
Created on 26 juil. 2017
@author: worm
'''
from django.views.generic.list import ListView
from collections import OrderedDict
from snapshotServer.models import TestCaseInSession,\
TestStepsThroughTestCaseInSession
from snapshotServer.views.LoginRequiredMixinConditional import LoginRequiredMixinConditional
cl... |
from .replay_memory import *
from .noise import OrnsteinUhlenbeckActionNoise
from .replay_buffer import ReplayBuffer
|
"""Classical AMG"""
from __future__ import absolute_import
from .classical import *
from .split import *
from .interpolate import *
from .cr import *
__all__ = [s for s in dir() if not s.startswith('_')]
from numpy.testing import Tester
test = Tester().test
|
class TrackletCompleteSet:
def __init__(self, tracklets, id, left_neighbour=None, right_neighbour=None):
self.tracklets = tracklets
self.id = id
self.left_neighbour = left_neighbour
self.right_neighbour = right_neighbour
|
import h5py, pickle
import os, sys, subprocess
import numpy as np
from torch_connectomics.model.loss import *
import torch
from tensorboardX import SummaryWriter
from tqdm import tqdm
from torch_connectomics.utils.skeleton import *
arguments = [sys.executable, '/n/home11/averma/pytorch_connectomics/scripts/testFlux.p... |
from __future__ import print_function
#
# 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.