text stringlengths 2 999k |
|---|
from django.core.exceptions import ValidationError
from django.db import models
from .phone_number import PhoneNumber
from .forms import PhoneFormField
class PhoneField(models.CharField):
empty_values = models.CharField.empty_values + [PhoneNumber('')]
def __init__(self, *args, **kwargs):
i... |
from __future__ import absolute_import, division, unicode_literals
import logging
from sqlalchemy import Column, Integer, String
from flexget.event import event
from flexget.manager import Base, Session
from flexget.utils.database import with_session
from flexget.utils.sqlalchemy_utils import table_schema
log = log... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
from insights.tests import context_wrap
from insights.parsers.crypto_policies import CryptoPoliciesBind
from insights.parsers import SkipException
import pytest
CONFIG = """
disable-algorithms "." {
RSAMD5;
DSA;
};
disable-ds-digests "." {
GOST;
};
""".strip()
CONFIG_EMPTY_SECTIONS = """
disable-algorithms "." {
};
d... |
from os import path
ROOT = path.dirname(path.realpath(__file__))
RESULTS_ROOT = path.join(ROOT, 'results')
TEMPLATES_ROOT = path.join(ROOT, 'src', 'core', 'reporting', 'templates')
VERSION = '1.1' |
# Module Imports
from app import utils
from app.elo_params import params
# Package Imports
import lightgbm as lgb
import pandas as pd
import os
import re
import numpy as np
import warnings
from scipy import stats
def get_sample(n_rows):
model_params = params()
sample = pd.read_csv(f'{model_params.folder_pat... |
import ast
from collections import defaultdict
from typing import ClassVar, DefaultDict, FrozenSet, List, Optional
from typing_extensions import final
from wemake_python_styleguide import constants, types
from wemake_python_styleguide.compat.aliases import AssignNodes, FunctionNodes
from wemake_python_styleguide.comp... |
"""
WSGI config for nsp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_... |
import pdf_to_json as p2j
import json
url = "file:data/multilingual/Cyrl.YKG/Sun-ExtA_12/udhr_Cyrl.YKG_Sun-ExtA_12.pdf"
lConverter = p2j.pdf_to_json.pdf_to_json_converter()
lConverter.mImageHashOnly = True
lDict = lConverter.convert(url)
print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True))
|
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.spm.utils import Reslice
def test_Reslice_inputs():
input_map = dict(ignore_exception=dict(nohash=True,
usedefault=True,
),
in_file=dict(mandatory=True,
),
interp=dict(usedefault... |
"""
Neural Net estimattion of cloud effective radius.
"""
from datetime import datetime
from numpy import savez, linspace, ones, where, log
from numpy import c_ as cat
from pyobs.mxd06 import MxD06_L2, MISSING, granules
from pyobs.npz import NPZ
from Aero_ import getaeropbl, getaerolev, revisectp, ... |
"""
Load new packs and multipacks to the database
"""
from argparse import ArgumentParser
from pathlib import Path
import json
import logging
from db_utils import add_pack, add_multipack
if __name__ == "__main__":
logging.basicConfig(
format="%(asctime)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%... |
from ppo import ppo
from env_functions import *
from utils.run_utils import ExperimentGrid
if __name__ == '__main__':
exp_name = 'walker-ppo'
eg = ExperimentGrid(name=exp_name)
eg.add('seed', [10*i for i in range(5)])
eg.add('env_fn', walker_env_fn, '', False)
eg.add('epochs', 600)
eg.add('s... |
# Copyright 2017 Thomas Sterrenburg
#
# Licensed under the MIT License (the License); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at https://opensource.org/licenses/MIT#
import gevent.monkey
from gevent.pool import Pool
import urllib2
# To view the number ... |
from flask import Flask, jsonify, request, abort, make_response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import class_mapper
app = Flask(__name__)
db = SQLAlchemy(app)
app.config.from_object('config.DevelopmentConfig')
def serialize(model):
"""
Transforms a model into a dictionary which can be... |
# coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# 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 applicab... |
# Copyright 2021 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
"""Shared OS X support functions."""
import os
import re
import sys
__all__ = [
'compiler_fixup',
'customize_config_vars',
'customize_compiler',
'get_platform_osx',
]
# configuration variables that may contain universal build flags,
# like "-arch" or "-isdkroot", that may need customization for
# the... |
import struct
class BaseArgon2Params:
DEFAULT_MEM_COST = 16 # 16 MiB, log2 KiB, 2^(N+10) bytes
DEFAULT_TIME_COST = 5 # N iterations
def __init__(self, mem_cost: int, time_cost: int, threads: int, version: int):
self.mem_cost = mem_cost # log2
self.time_cost = time_cost
self.th... |
f = open("size1Mlist.txt")
lines = f.readlines()
num=0
for line in lines:
num+=1
# print line
print num
#print lines[499]
for i in range(232):
fileName='listFiles_jb'+str(i)+'.txt'
filesI=open(fileName, 'w')
for j in range(20):
if(i*20+j<4638):
filesI.write(lines[i*20+j])
filesI.close()
#p... |
import httplib2
import logging
import pandas
from airflow.hooks.base_hook import BaseHook
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
from pandas.io.gbq import GbqConnector, _parse_data as gbq_parse_data
from pandas.tools.merge import concat
logging.getLogger("b... |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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,
... |
import numpy as np
from tomoxtal.utils import cctbx_tools
from tomoxtal.utils import phases as phases_utils
from tomoxtal.pipeline import LocateXtalOrigin
class TestLocateXtalOrigin:
def setup_class(self):
"""
Prepare a few simulated datasets for a P212121 crystal.
"""
args = {... |
''' PROGRAM TO CONSTRUCT A DICTIONARY phone_book WITH :
KEY: NUMBER OF ENTRIES VALUES: (NAME, PHONE NUMBER, EMAIL , ADDRESS)
PERFORM THE FOLLOWING OPERATIONS:
I) ADD A NEW NUMBER TO PHONE BOOK
II) DELETE ENTRY FROM PHONE BOOK.'''
#Given values
values = [("Rashma",8105731555,"rashma@gmail.com","... |
import math
from model import Model
class GazeEstimationModel(Model):
"""
Class for the Gaze Estimation Model.
"""
def __init__(self, model_path, device='CPU', extensions=None, threshold=0.6):
"""
This will initiate Gaze Estimation Model class object
"""
Model.__init__... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
from fairseq.data import BaseWrapperDataset
from shared_lib.utils.helpers.data import reduce_docs
import torch as T
import ... |
import sys
import os
from pythonz.util import PY3K
from pythonz.log import logger
if PY3K:
from urllib.request import Request, urlopen
else:
from urllib2 import urlopen, Request
try:
from resumable import urlretrieve, DownloadError, sha256
except ImportError:
from mmap import mmap as _mmap, ACCESS_RE... |
from django.urls import path
from store import views
urlpatterns = [
path('', views.store, name='store'),
path('detail_view/<int:id>/', views.detail_view, name="detail_view"),
path('update_item/', views.update_item, name="update_item"),
path('cart/', views.cart, name='cart'),
path('checkout/', vie... |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import ctypes
def type_(ctype):
'''
Monkey patching method that creates wrapper types
'''
class GLMeta(type(ctype)):
'''implements gl.type[array_size] array typing'''
def __getitem__(self, other):
return type(ctype).__mul__(self, other)
def __instancecheck__(self, ot... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
import sys
import math
import numpy as np
import matplotlib.pyplot as plt
def debug(s):
print >> sys.stderr, s
def format_e(n):
a = '%E' % n
return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]
hash_sizes = []
inserts = {}
lookups = {}
insert_hashed = {}
lookup_hashed = {}
def parse_fi... |
# FROM: https://github.com/lanpa/tensorboard-pytorch
import torch
import torchvision
import tensorflow as tf
import torchvision.utils as vutils
import numpy as np
import torchvision.models as models
from torchvision import datasets
from tensorboardX import SummaryWriter
import psutil
import torch.nn as nn
import torch... |
import unittest
from xpath_string.two_xpath_addition import TwoXpathAddition
param_list_add_two_xpath_without_contains = [
('//span', '//div', '//span//div'),
('//div|//svg', '//span', '//div//span|//svg//span'),
('//div', '//span|//svg', '//div//span|//div//svg'),
('//div|//span', '//avg|//span', '//... |
def estimate_probability(word, previous_n_gram,
n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0):
denominator = n_gram_counts.get(previous_n_gram, 0)
denominator += k * vocabulary_size
numerator = n_plus1_gram_counts.get(previous_n_gram + ' ' + word, 0)
numerator += ... |
from __future__ import absolute_import, unicode_literals
import os
import subprocess
import sys
import pytest
import virtualenv
def get_src(path):
base, _ = os.path.splitext(path)
if virtualenv.IS_JYTHON and base.endswith("$py"):
base = base[:-3] # strip away Jython ext
return "{}.py".format(b... |
# -*- coding: utf-8 -*-
###############################################################################
#
# GetActivity
# Gets the details of a specific activity in the Fitbit activities database.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the ... |
class Solution:
def naive(self,root,startValue,destValue):
self.adjLs = {}
def recur(tree,LorR,parent=-1):
if tree==None:
return
if startValue in self.adjLs and destValue in self.adjLs:
return
if parent!=-1:
dictval... |
import numpy as np
def domainwall_analytic_solution(A, K, d, n_points):
"""
Computes Neel domain wall magnetisation x component
in absence of an external magnetic field.
"""
x_array = np.linspace(0, d, n_points)
mx_analytic = -np.tanh((x_array - d / 2.) / np.sqrt(A / K))
return mx_analyti... |
"""
Copyright (C) 2018-2020 Intel 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 agreed to i... |
import itertools
import datetime
from unittest import TestCase, skip
from chibi.file import Chibi_path
from chibi.file.temp import Chibi_temp_path
from vcr_unittest import VCRTestCase
from chibi_dl.site.nhentai import Episode, Image
from chibi_dl.site.nhentai.site import Nhentai
class Test_ehentai( TestCase ):
... |
from __future__ import division, print_function, unicode_literals
from astropy.convolution import convolve, convolve_fft
from astropy.convolution import Gaussian1DKernel, Gaussian2DKernel
from scipy.ndimage.interpolation import rotate
from scipy import fftpack
from copy import deepcopy
# Import libraries
from .pynrc_... |
"""
Converts a feature cache into a set of scores. Adds a 'score' field to the
JSON observation and deletes the 'cache' field.
Usage:
cache2score.py <model-file>
[--verbose]
[--debug]
Options:
-h --help Prints this documentation
<model-file> ... |
"""
MIT License
Copyright (c) 2021 Mauro Baladés
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,... |
import taichi as ti
# such small block_dim will cause grid_dim too large for OpenGL...
@ti.archs_excluding(ti.opengl)
def test_parallel_range_for():
n = 1024 * 1024
val = ti.var(ti.i32, shape=(n))
@ti.kernel
def fill():
ti.parallelize(8)
ti.block_dim(8)
for i in range(n):
... |
begin_unit
comment|'# Copyright 2012 Hewlett-Packard Development Company, L.P.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the Lic... |
import numpy as np
import pytest
from mmgen.datasets.pipelines import Compose, ImageToTensor
def check_keys_equal(result_keys, target_keys):
"""Check if all elements in target_keys is in result_keys."""
return set(target_keys) == set(result_keys)
def test_compose():
with pytest.raises(TypeError):
... |
from disco.test import DiscoJobTestFixture, DiscoTestCase
from disco.core import JobError
from disco.util import urlsplit
class ForceLocalTestCase(DiscoJobTestFixture, DiscoTestCase):
scheduler = {'force_local': True}
@property
def input(self):
return ['http://%s' % node
for node, max_... |
from sqlalchemy import union_all
from sqlalchemy.sql import label, literal
from grouper.fe.util import GrouperHandler
from grouper.models import Group, User
class Search(GrouperHandler):
def get(self):
query = self.get_argument("query", "")
offset = int(self.get_argument("offset", 0))
limi... |
from eve.tests import TestBase
import time
class TestRateLimit(TestBase):
def setUp(self):
super(TestRateLimit, self).setUp()
try:
from redis import Redis, ConnectionError
self.app.redis = Redis()
try:
self.app.redis.flushdb()
except... |
# -*- coding: utf-8 -*-
"""
sphinx.domains.ruby
~~~~~~~~~~~~~~~~~~~
The Ruby domain.
:copyright: Copyright 2010 by SHIBUKAWA Yoshiki
:license: BSD, see LICENSE for details.
"""
import re
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx import addnodes
from sphi... |
from deepSI.system_data import System_data, System_data_list, System_data_norm
import deepSI
import numpy as np
import pickle
from secrets import token_urlsafe
import copy
import gym
from gym.spaces import Box
def load_system(file):
"""This is not a safe function, only use on trusted files"""
try:
retu... |
# type: ignore
import databases
import pytest
import sqlalchemy as sa
from pydantic.typing import ForwardRef
from sqlalchemy import create_engine
import ormar
from ormar import ModelMeta
from tests.settings import DATABASE_URL
metadata = sa.MetaData()
db = databases.Database(DATABASE_URL)
engine = create_engine(DATA... |
from manim import *
from manim.utils.testing.frames_comparison import frames_comparison
__module_test__ = "tables"
@frames_comparison
def test_Table(scene):
t = Table(
[["1", "2"], ["3", "4"]],
row_labels=[Tex("R1"), Tex("R2")],
col_labels=[Tex("C1"), Tex("C2")],
top_left_entry=Ma... |
from citywok_ms.file.models import EmployeeFile
from typing import List
from citywok_ms import db
from citywok_ms.utils import ID, SEX
from citywok_ms.utils.models import CRUDMixin, SqliteDecimal
from sqlalchemy import Boolean, Column, Date, Integer, String, Text
from sqlalchemy.ext.hybrid import hybrid_property
from s... |
from backbone import ResNetBackbone, VovNetBackbone
from math import sqrt
import torch
# for making bounding boxes pretty
COLORS = ((244, 67, 54),
(233, 30, 99),
(156, 39, 176),
(103, 58, 183),
( 63, 81, 181),
( 33, 150, 243),
( 3, 169, 244),
... |
import os
import pytest
from analyzer import config
from analyzer.config import DEFAULT_RECIPE_SERVER, RecipeStatsConfig
def test_default_config():
cfg1 = RecipeStatsConfig()
cfg1.make_config()
assert cfg1.RECIPE_SERVER == DEFAULT_RECIPE_SERVER
def test_singleton_config():
cfg1 = RecipeStatsConfig(... |
lis = [{'name': 'Puma', 'age': '73'},
{'name': 'Nike', 'age': '50'},
{'name': 'Wiki', 'age': '26'},
{'name': 'Chrome', 'age': '13'},
{'name': 'Firefox', 'age': '23'},
{'name': 'Samsung', 'age': '50'}]
print('The list is sorted in ascending order by age:')
print(sorted(lis, key=lambda ... |
# The functions detailed below are all translation from Javascript.
# The original code was done by alvaro-cuesta here https://github.com/alvaro-cuesta/townsclipper
# Thank you very much for it !
# IMPORTANT NOTES:
#
# Input looks like base64url but IT IS NOT! Notice the alphabet's out-of-order "w"
# and the swapped "... |
import ipywidgets as widgets
from bqplot.colorschemes import CATEGORY20
from bqplot import Axis, Figure, LinearScale, Lines
from gquant.cuindicator import vortex_indicator as indicator_fun
def get_para_widgets():
para_selector = widgets.IntSlider(min=2, max=60, description="Vortex Indicator")
para_selector_wi... |
##
# File: test_disulfide_bond.py
# Date: 25-Jun-2020 M. Yokochi
#
# Updates:
##
import unittest
import os
import json
from wwpdb.utils.nmr.NmrDpUtility import NmrDpUtility
class TestNmrDpUtility(unittest.TestCase):
def setUp(self):
here = os.path.abspath(os.path.dirname(__file__))
self.data_d... |
import json
import uuid
from models.base import PynamoCrud
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute, NumberAttribute
from models.base import Namespace, Route
from utils.utils import compare
from models.requests import StatusCode, Verb, RouteRequest, NamespaceRequest
from urllib... |
from flask_wtf import FlaskForm
from wtforms import StringField, FileField, SubmitField
from wtforms.validators import DataRequired, Length
from application import db
class PostForm(FlaskForm):
title = StringField("Title", validators=[DataRequired()])
description = StringField("Description", validators=[DataR... |
"""
Estimate the marginal log likelihood of the data under a given model.
"""
import sys
import numpy as np
from scipy.misc import logsumexp
from IPython.parallel.util import interactive
from pyglm.utils.parallel_util import parallel_compute_log_p
def initialize_imports(dview):
""" Import functions req'd for co... |
import copy
import multiprocessing
import os
import time
import unittest
import uuid
import mechanize
from py4web import action, DAL, Field, Session, Cache
from py4web.core import bottle, request, error404
os.environ["PY4WEB_APPS_FOLDER"] = os.path.sep.join(
os.path.normpath(__file__).split(os.path.sep)[:-2]
)
... |
from setuptools import setup, find_packages
with open('README.md', 'r', encoding='utf-8') as f:
long_description = f.read()
with open('requirements/requirements.txt') as f:
requirements = f.readlines()
setup(
name='whist-server',
version='0.0.1',
author='Whist Team',
description='Whist game s... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import time
from collections import deque
from typing import Dict, List
import numpy as np
import torch
from ... |
import logging
import hocort.execute as exe
from hocort.classifiers.classifier import Classifier
logger = logging.getLogger(__file__)
class Kraken2(Classifier):
"""
Kraken2 implementation of the Classifier abstract base class.
"""
def build_index(path_out, fasta_in, threads=1, options=[], **kwargs)... |
import argparse
import glob
import os
import skimage.io
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
from scipy.spatial.distance import euclidean
from functools import partial
from multiprocessing.pool import Pool
import cv2
import pandas as pd
impo... |
# Constants
repo_path = '/Users/aaron/git/gittle'
repo_url = 'git@friendco.de:friendcode/gittle.git'
# RSA private key
key_file = open('/Users/aaron/git/friendcode-conf/rsa/friendcode_rsa') |
import community as cm
import networkx as nx
class Louvain:
"""
Louvain community detection
"""
def __init__(self):
pass
def train(self,networks):
"""
No training actually takes place in this class.
:param networks: list of egonet objects
:return: Prediction... |
from django.core.management.base import BaseCommand
from ...ftp.utils import parse_all_users_files
class Command(BaseCommand):
help = 'Load users files found in ftp user folders'
def handle(self, *args, **options):
try:
parsed_users = parse_all_users_files()
except Exception as ... |
from queue import Queue
import socket
import threading
import re
def parse_seed(data):
pattern = re.compile(".*(\d{2})\\.(\d{2})\\.(\d{4}).*(\d{2}):(\d{2}):(\d{2})", re.MULTILINE | re.DOTALL)
seed = pattern.findall(data)[0]
return int(str.format("{2}{1}{0}{3}{4}{5}", *seed))
max = 101
threads = Queue()
... |
from model.contact import Contact
from selenium.webdriver.support.ui import Select
import re
import time
# Помощник контактов, содержит все вспомогательные методы, которые относятся к работе с контактами
class ContactHelper:
def __init__(self, app): # конструктор, в качестве параметра принимает ссылку на фикстуру... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import atexit
import bisect
import multiprocessing as mp
from collections import deque
import cv2
import torch
from fsdet.data import MetadataCatalog
from fsdet.engine.defaults import DefaultPredictor
from fsdet.utils.video_visualizer import VideoV... |
#!/usr/bin/env python
# Copyright 2018 Jérôme Dumonteil
# Copyright (c) 2009-2010 Ars Aperta, Itaapy, Pierlis, Talend.
#
# 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.apach... |
# Copyright (c) 2018 LG Electronics, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import logging
from aiohttp import web
import webhooks
import rules
import extractions
routes = web.RouteTableDef()
app = web.Application()
# It'd probably be better to namespace this in a v1 file or such?
@routes.post("/webhook/{hook_path}")
async def v1_webhook(request):
"""
A webhook that will accept a m... |
import torch
from torchaudio_unittest.common_utils import PytorchTestCase
from torchaudio_unittest.prototype.emformer_test_impl import EmformerTestImpl
class EmformerFloat32CPUTest(EmformerTestImpl, PytorchTestCase):
dtype = torch.float32
device = torch.device("cpu")
class EmformerFloat64CPUTest(EmformerTes... |
import math
import cv2
import numpy as np
from torchvision import transforms
import matplotlib.pyplot as plt
HEIGHT = 228
WIDTH = 304
def scale_image(img, scale=None):
"""Resize/scale an image. If a scale is not provided, scale it closer to HEIGHT x WIDTH."""
# if scale is None, scale to the longer size
... |
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from api.models import Feedback
from api.modules.feedback.serializers import FeedbackSerializer, FeedbackCondensedSerializer
@api_view(['POST'])
def add_feedback(request):
"""
Add a f... |
import numpy as np
from scipy.sparse import coo_matrix
"""This is all a bunch of stuff copied from sk-learn 0.24.2 but shoving it in
here for compatibility purposes. Some slight modifications were made."""
class ConfusionMatrixDisplay:
"""Confusion Matrix visualization.
It is recommend to use :func:`~sklearn... |
import argparse
import os
import random
import gym
from gym.wrappers import TimeLimit
import numpy as np
import pandas as pd
import yaml
from env_aug import AntEnvAug, HalfCheetahEnvAug, HopperEnvAug, fixedSwimmerEnv
from model import EnsembleGymEnv
from ppo import PPO, Memory
from train_funcs import (collect_data, t... |
"""$ fiona ls"""
import json
import click
from cligj import indent_opt
import fiona
from fiona.fio import with_context_env
@click.command()
@click.argument('input', required=True)
@indent_opt
@click.pass_context
@with_context_env
def ls(ctx, input, indent):
"""
List layers in a datasource.
"""
res... |
#!C:\Users\Kana\Desktop\PROJECT\train-ticket\scriptsForJaeger\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install'
__requires__ = 'setuptools==39.1.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.su... |
import logging
import re
from datetime import timedelta, timezone
import dateutil.parser
from jarr.bootstrap import conf
from jarr.lib.const import FEED_ACCEPT_HEADERS
from jarr.lib.utils import digest, rfc_1123_utc, utc_now
logger = logging.getLogger(__name__)
MAX_AGE_RE = re.compile('max-age=([0-9]+)')
def _extr... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': [... |
#
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
#
# 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 w... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
2020-07-06-extrapolation.py: based on small subsampled DoEs, extrapolate a best
suggested next DoE size and compare this with results from enumerated DoEs.
"""
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from pyprojroot import here
from parse i... |
"""
This file is the template of the scripting node source code in edge mode
Substitution is made in HandTrackerEdge.py
In the following:
rrn_ : normalized [0:1] coordinates in rotated rectangle coordinate systems
sqn_ : normalized [0:1] coordinates in squared input image
"""
import marshal
from math import sin, cos,... |
#!/usr/bin/env python
"""Test the process list module."""
import os
from grr.lib import action_mocks
from grr.lib import aff4
from grr.lib import flags
from grr.lib import flow
from grr.lib import test_lib
from grr.lib.aff4_objects import collects
# pylint: disable=unused-import
from grr.lib.flows.general import proc... |
# Generated by Django 3.2.12 on 2022-03-16 14:37
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hanging_protocols", "0001_initial"),
("algorithms", "0024_algorithm_access_request_handling"),
]
operation... |
from aula29072019.NodePessoa import NodePessoa
class ListaLigada:
def __init__(self):
self.inicio = None
self.fim = None
self.tamanho = 0
def inserirInicio(self, identificacao, nome, cpf):
nodePessoa = NodePessoa(identificacao, nome, cpf)
if(self.inicio == self.fim ... |
# -*- coding: utf-8 -*-
import sys
from time import sleep
from django.core.management.base import BaseCommand, CommandError
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from django.utils import timezone
from apps.posts.models import Post
de... |
# Copyright 2016, Google Inc.
# 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 f... |
import os
from osim.env import Arm2DEnv
import pprint
import numpy as np
env = Arm2DEnv()
if __name__ == '__main__':
observation = env.reset()
env.osim_model.list_elements()
for i in range(3000):
action = env.action_space.sample()
observation, reward, done, info = env.step(action... |
#coding=utf-8
import MySQLdb
import mymail
import time
import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class ActiveUser(object):
"""docstring for ActiveUser"""
def __init__(self):
super(ActiveUser, self).__init__()
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='ro... |
from django.db import IntegrityError
from django.utils.functional import cached_property
from redis.exceptions import ConnectionError, ResponseError
from experiments.models import Enrollment
from experiments.manager import experiment_manager
from experiments.dateutils import now, fix_awareness, datetime_from_timestam... |
# ElectrumSV - lightweight Bitcoin client
# Copyright (C) 2019-2020 The ElectrumSV Developers
#
# 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 limita... |
# -*- coding: utf-8 -*-
from flask import render_template_string
from lektor.admin.modules import dash
from lektor.pluginsystem import Plugin
KEY = ''
TINYMCE_SETTINGS = ''
TEMPLATE = '''
{% extends "dash.html" %}
{% block scripts %}
{{ super() }}
<script src="https://cdn.tiny.cloud/1/{{tinymce_api_key}}/tinymce/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.