content stringlengths 5 1.05M |
|---|
import mysql.connector
import json
import dbconfig as cfg
class DeliveryDAO:
db=""
def __init__(self):
self.db = mysql.connector.connect(
host=cfg.mysql['host'],
user=cfg.mysql['user'],
password=cfg.mysql['password'],
database=cfg.mysql['database']
)
def ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 on 2016-06-23.
# 2016, SMART Health IT.
import os
import io
import unittest
import json
from . import organization
from .fhirdate import FHIRDate
class OrganizationTests(unittest.TestCase):
def instantiate_from(self, filename):
... |
# Copyright 2012 Viewfinder Inc. All Rights Reserved.
__author__ = 'ben@emailscrubbed.com (Ben Darnell)'
from viewfinder.backend.db.test.base_test import DBBaseTestCase
from viewfinder.backend.db.subscription import Subscription
from viewfinder.backend.services import itunes_store
from viewfinder.backend.services.tes... |
# coding: Latin-1
# Copyright © 2018 The Things Network
# Use of this source code is governed by the
# MIT license that can be found in the LICENSE file.
import binascii
import os
MODERN_CIPHER = ("ECDHE-ECDSA-AES256-GCM-SHA384:"
"ECDHE-RSA-AES256-GCM-SHA384:"
"ECDHE-ECDSA-CHACHA20-... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 15:19:38 2021
@author:Yanxiang Lai
"""
import numpy as np
import scipy as sp
import sys
import time
import copy
from numpy import linalg
from scipy import integrate
from scipy import interpolate
from scipy import optimize
import emcee
from emcee impor... |
# -*- coding: utf-8 -*-
# Filter parser
# See the accompanying LICENSE Apache V2.0 file.
# (C) 2021 Engie Digital
#
# vim: set ts=4 sts=4 et tw=78 sw=4 si:
"""
Parse the filter syntax to produce a FilterAST.
See https://www.project-haystack.org/doc/Filters
"""
from datetime import datetime, time
from functools import ... |
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import Group, User
class Command(BaseCommand):
help = 'Creates demo users for the app.'
def add_arguments(self, parser):
parser.add_argument('--group',
help="""Create user on ... |
# Jetfuel Game Engine- A SDL-based 2D game-engine
# Copyright (C) 2018 InfernoStudios
#
# 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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 13:00:03 2018
@author: Khaled Nakhleh
"""
if __name__ == "__main__":
print("\n\tThis file only contains internal functions. Please use main.py to run the program.\n")
exit |
import numpy as np
import theano
import theano.tensor as T
def group_irregular_length_tensors(tensors):
"""
groups a set of irregular length tensors (where the length of the first
axis of each is different) into one large tensor, and also returns
a vector of the lengths of the original tensors (for us... |
import numpy as np
pulse_len = 100
qubit_IF = 50e6
qubit_LO = 2e9
def IQ_imbalance_correction(g, phi):
c = np.cos(phi)
s = np.sin(phi)
N = 1 / ((1 - g ** 2) * (2 * c ** 2 - 1))
return [float(N * x) for x in [(1 - g) * c, (1 + g) * s, (1 - g) * s, (1 + g) * c]]
config = {
"version": 1,
"cont... |
from proteus import *
from proteus.default_p import *
from cylinder import *
from proteus.mprans import RANS2P
name = "momentum"
LevelModelType = RANS2P.LevelModel
coefficients = RANS2P.Coefficients(epsFact=epsFact_viscosity,
rho_0=rho_0,
nu_0=nu... |
import os, time
from photoshop import Session
def App(inputDir, targetImg, userChoseForFinalWidth):
with Session() as ps:
# open the img and ps
ps.app.documents.add(1920, 1080, name="content")
desc = ps.ActionDescriptor
desc.putPath(ps.app.charIDToTypeID("null"), f"{inputDir}/{targe... |
# coding:utf-8
#
# Author: BONFY<foreverbonfy@163.com>
# Github: https://github.com/bonfy
# Repo: https://github.com/bonfy/leetcode
# Usage: Leetcode solution downloader and auto generate readme
#
import requests
import os
import configparser
import json
import time
import datetime
import re
import sys... |
from com.ic_interface import ICInterface, Direction
from mgmt.pos_callculation import Spline, PosCalculation
pos_calc = PosCalculation()
pos_calc.x_rel_to_z_abs_spline
x_rel_new = [i for i in range(25000)]
x_abs_new = [Spline.evaluate(pos_calc.x_rel_to_x_abs_spline, x_rel) for x_rel in x_rel_new]
z_abs_new = [Spline.... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 30 13:00:30 2019
@author: Sampritha H M
"""
import os
import sys
import Utils.common_utilities as utils
os.chdir("..")
os.chdir("data")
file = sys.argv[1]
train_input,train_output,test_input,test_output = utils.json_reader(file)
def solve(inputData):
array = inpu... |
import os
import re
from collections import OrderedDict
from datetime import date, timedelta, datetime
from itertools import groupby, chain
import pendulum
import yaml
from bs4 import BeautifulSoup
from common import VideoProvider, VideoMetadata, TimeCode, adjust_timecode, timecode_to_seconds, PreparedVideoInfo, \
... |
from addressconf import Directions, Streets, States, Regexes
import re
def parse(location):
if Regexes.corner.search(location):
return parse_intersection(location)
else:
return parse_address(location)
def parse_intersection(inter):
match = Regexes.intersection.match(inter)
if not match:
return
match_data =... |
"""
This script combines multiple pickle files into one python source file
containing the symmetry information.
"""
import os
import pickle
import pprint
import numpy as np
def print_dict(d, level):
out = []
out.append("{\n")
for key in sorted(d.keys()):
value = d[key]
if isinstance(value,... |
from .scraping import (
HashtagScraper,
LocationScraper,
Scraper,
)
|
#------------------------------------------------------------------------------
# Copyright (c) 2019, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
#-----------------------------------------------------... |
# from setuptools import setup, find_packages
# import mlc_tools.version
# setup(
# name='mlc-tools',
# version=mlc_tools.version,
# packages=find_packages(),
# long_description="mlc-tools",
# install_requires=[
# 'enum'
# ]
# # entry_points={
# # 'console_scripts':
# # ... |
from fastapi.testclient import TestClient
from sqlmodel import create_engine
from sqlmodel.pool import StaticPool
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/heroes/": {
"get": {
"summary": "Read Heroes",
... |
"""v1.0-rc4-a2
Revision ID: 04b9fb8ffee1
Revises: a6cbb6201d3d
Create Date: 2021-05-01 16:58:29.532726
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '04b9fb8ffee1'
down_revision = 'a6cbb6201d3d'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generate... |
from journalist.utils.reviewbase import ReviewBase
from news.models import Article, Category, Tags, TITLE_MAX_LENGTH, TAG_MAX_LENGTH
from django.utils import timezone
import logging
logger = logging.getLogger(__name__)
class PCGamerReview(ReviewBase):
def __init__(self, category, headers):
super(PCGamerR... |
from collections import namedtuple
from .errors import InvalidACTASpecParameterError
IMMUTABLE_OBJECT_FIELDS = ['actor', 'verb', 'obj', 'meta', 'handler_function']
class ActaSpecBuilder(object):
_actor = ''
_verb = ''
_obj = ''
_meta = {}
_handler_function = None
def __init__(self, actor, v... |
"""PhoNLP Named Entity Recognition Dataset"""
import datasets
import os
_URL = "./"
_TRAINING_FILE = "train.txt"
_DEV_FILE = "dev.txt"
_TEST_FILE = "test.txt"
logger = datasets.logging.get_logger(__name__)
class NerPhoConfig(datasets.BuilderConfig):
"""BuilderConfig for NER datasets"""
def __init__(self, *... |
MEMORY_FRAMES = 25 # results are averaged over this number of frames
YM_PER_PIX = 30 / 720 # meters per pixel in y dimension
XM_PER_PIX = 3.7 / 700 # meters per pixel in x dimension
|
#!/usr/bin/env python
import sys, urllib
def reporthook(*a): print a
for url in sys.argv[1:]:
i = url.rfind('/')
files = url[i+1:]
print url,'->',files
urllib.urlretrieve(url,files,reporthook)
|
from transformers import T5ForConditionalGeneration, T5TokenizerFast
from loguru import logger
class QuestionGenerator:
"""Class loads pipeline for generating questions from text"""
model = T5ForConditionalGeneration.from_pretrained("ThomasSimonini/t5-end2end-question-generation")
tokenizer = T5Tokenizer... |
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Iterable, List, Tuple
import pandas as pd
from snowshu.adapters import BaseSQLAdapter
from snowshu.configs import MAX_ALLOWED_DATABASES, MAX_ALLOWED_ROWS
from snowshu.core.models import DataType, Relation
from snowshu.core.models.re... |
# Generated by Django 3.2 on 2021-05-30 18:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('scrapers', '0011_alter_retsinfosentences_document'),
('documents', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_n... |
from .data_fetcher import DataFetcher, DataWrapper
|
class Solution:
def largestRectangleArea(self, heights) -> int:
ans, stack = 0, []
for i, h in enumerate(heights+[0]):
while stack and heights[stack[-1]] >= h:
height = heights[stack.pop()]
if stack:
width = i - stack[-1]-1
... |
"""main training script."""
import importlib.util
import logging
from pathlib import Path
import einops
import matplotlib.pyplot as plt
import torch
from torch.functional import einsum
from torch.nn.utils.rnn import pack_sequence, pad_packed_sequence, pad_sequence
from pt2.dataloader import create_train_val_dataloade... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 14:19:05 2018
@author: Dennis_van_Gils
"""
import serial
import struct
import matplotlib.pyplot as plt
import numpy as np
import time as Time
SOM = bytes([0x00, 0x00, 0x00, 0x00, 0xee]) # Start of message
EOM = bytes([0x00, 0x0... |
pattern = [i for i in "111211111"]
line = [i for i in "111121111"]
print pattern == line
|
#!/usr/bin/env python3
"""Trains a DQN agent to control the satellite.
By default, it trains on the SatelliteDrag-v0 environment. Supply the script
with an environment name to train on a different environment.
"""
import sys
import os
import yaml
import gym
import tensorflow as tf
from stable_baselines.common.policie... |
import pytest
from pyga.utils.history import *
from pyga.opt.soga import SOGA
from pyga.individual import Individual
class TestGeneralHistory:
@pytest.fixture
def soga(self):
bounds = {
'x0': [0.0, 10.0],
'x1': [0.0, 10.0]
}
soga = SOGA(bounds, n_individuals=... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
app = 'browsepy'
description = 'Simple web file browser'
version = '0.5.6'
license = 'MIT'
author_name = 'Felipe A. Hernandez'
author_mail = 'ergoithz@gmail.com'
author = '%s <%s>' % (author_name, author_mail)
url = 'https://github.com/ergoithz/browsepy'
tarball = '%s/arch... |
"""
Ledger Devices
**************
"""
from functools import wraps
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Tuple,
Union,
)
from ..descriptor import (
MultisigDescriptor,
PubkeyProvider,
)
from ..hwwclient import HardwareWalletClient
from ..errors import (
Actio... |
# Copyright (c) 2020-2021, NVIDIA CORPORATION. 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 require... |
#
# Copyright (c) 2021 Arm Limited and Contributors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""host_tests_toolbox package."""
from .host_functional import reset_dev
from .host_functional import flash_dev
from .host_functional import handle_send_break_cmd
|
from ..common import *
@ti.data_oriented
class VoxlEditBase:
def __init__(self, voxl):
self.voxl = voxl
def __getattr__(self, attr):
return getattr(self.voxl, attr)
|
from os import getenv
from tweepy import OAuthHandler, API
class Twitter:
def __init__(self):
TWITTER_API_KEY = getenv('TWITTER_API_KEY')
TWITTER_API_SECRET = getenv('TWITTER_API_SECRET')
TWITTER_ACCESS_TOKEN = getenv('TWITTER_ACCESS_TOKEN')
TWITTER_ACCESS_SECRET = getenv('TWITTER_ACCESS_SECRET')
... |
#
# Pyserini: Reproducible IR research with sparse and dense representations
#
# 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... |
import torch
import pprint
import argparse
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from torch import nn
import torch.nn.functional as F
from tianshou.policy import PPOPolicy
from tianshou.env import SubprocVectorEnv
from tianshou.trainer import onpolicy_trainer
from tianshou.data import Col... |
import base64
import logging
import requests
import sys
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)
# TODO: Replace this with your cognito domain, remember the region
AUTH_DOMAIN = "some-random-domain-2348472435.auth.eu-central-1.amazoncognito.com"
COGNITO_TOKEN_ENDPOINT = f"https://{ AUTH_DO... |
import unittest, time, sys
# not needed, but in case you move it down to subdir
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_import as h2i
import h2o_browse as h2b
#
# This is a Python test for HEX-1198.
#
# Failing store view during listing.
#
# See https://0xdata.atlassian.net/browse/HEX-1198... |
import numpy as np;
RNG = 256;
def partOne(seq, num_lst, pos, skip):
lst_len = len(num_lst)
curr_pos = pos
skip_size = skip
lengths = seq.split(',')
for leng in lengths:
leng = int(leng.strip())
if leng > lst_len:
continue
rev_end = (curr_pos + leng) % lst_len
if rev_end == 0:
rev_end = lst_len
i... |
"""Provides the wrapper methods to black. Requires black to be on the system path"""
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
from argparse import ArgumentParser
from pathlib import Path
THISDIR = Path(__file__).resolve().parent
def main():
"""Main entry ... |
#! /usr/bin/env python
# This script will make a training database of hashes
import os
import sys
# The following is for ease of development (so I don't need to keep re-installing the tool)
try:
from CMash import MinHash as MH
from CMash.Make import MakeTSTNew
except ImportError:
try:
import MinHash as MH
except ... |
from __future__ import annotations
import logging
import time
from typing import Any, Callable, List
from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario
from nuplan.planning.simulation.planner.abstract_planner import AbstractPlanner
from nuplan.planning.simulation.runner.abstract_runner im... |
import lmdb
import uuid
import random
import time
import pickle
if __name__=='__main__':
with lmdb.open('/tmp/lmdb', map_size=int(1e10), readonly=True) as env:
with open('/home/dan/lmdb_env', 'w') as f:
pickle.dump(env, f)
while True:
time.sleep(1)
# with env.begin()... |
import random
class EpsilonGreedyQPolicy:
def __init__(self, initial_epsilon=1.0, final_epsilon=0.1, max_steps=1000000):
self.initial_epsilon = initial_epsilon
self.final_epsilon = final_epsilon
self.epsilon = self.initial_epsilon
self.max_steps = max_steps
def use_random(s... |
"""
Desafio 078
Problema: Faça um programa que leia 5 valores númericos e guarde em uma lista.
No final, mostre qual foi o maior e o menor valor digitado e as suas
respectivas posições na lista.
Resolução do problema:
"""
valores = [int(input(f'Informe o valor da posição {cont}º: ')) for cont in r... |
# -*- coding: utf-8 -*-
from collections import OrderedDict
from jparse import JParser
jp = JParser()
TEST_CASE1 = [OrderedDict([('A1', 1), ('A2', 2), ('A3', 3)]),
OrderedDict([('A1', [4, 5, 6]), ('A2', 7), ('A3', 'x')])]
TEST_CASE2 = OrderedDict([('A1', [OrderedDict([('B1', 4), ('B2', 5)]),
... |
from typing import Any, Mapping, NamedTuple, Optional
class AssetIn(NamedTuple):
metadata: Optional[Mapping[str, Any]] = None
namespace: Optional[str] = None
managed: bool = True
|
"""
Module for the methods regarding ms projects
"""
import jpype
import jsonpath_ng.ext
import mpxj
from fastapi import APIRouter, File, UploadFile
from datatypes.models import *
from dependencies import *
router = APIRouter(
prefix="/msprojects",
tags=["msprojects"],
dependencies=[]
)
@router.post("/... |
"""Command line wrapper to serve one or more named Bokeh scripts or folders."""
import logging
import os
import re
import pathlib
import tempfile
from typing import Any, Dict, Tuple
import bokeh.server.views
import click
from bokeh.application.application import Application
from bokeh.command.util import build_single_... |
import unittest
from BOMFinder.DataBase.DataBase import DataBase
class TestDataBase(unittest.TestCase):
def setUp(self):
self.data_base = DataBase()
def tearDown(self):
unittest.TestCase.tearDown(self)
def test_add(self):
# Test integers
self.data_base.add(1)
s... |
from django.apps import AppConfig
class DemoAppAuthAppConfig(AppConfig):
name = "selectelhackaton.demoApp"
verbose_name = "SelectelHackaton DemoApp"
|
# encoding: utf-8
class Root:
def __init__(self, context):
self._ctx = context
def test(self, *args):
assert not args
if __name__ == '__main__':
__import__('scaffold').serve(Root)
# GET /test - Should not drop into debugger. (Args should be empty.)
|
from flask import request, abort, jsonify
import json, gzip
from sqlalchemy import or_, and_
import numpy as np
from shared import *
from ..models import *
import StringIO
# Accelerometer Observations upload #
@api.route('/api/v1/accelerometer_observations', methods=['POST'])
@api_auth.requires_auth
def post_accelerom... |
# Copyright 2020 Makani Technologies LLC
#
# 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... |
# -*- coding: utf-8 -*-
"""
/dms/newsboard/views_manage.py
.. enthaelt den View fuer die Freigabe-Ansicht
Django content Management System
Hans Rauch
hans.rauch@gmx.net
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 16.03.2007 Beg... |
import pandas as pd
import datetime
import numpy as np
import sys
sys.path.insert(0,"D:\Python\Test\Codes\My_modules")
import FB_Google
import non_mri
from Summary_dept_map import summary_cities
import FB_adset_type_mapper
def bi_report():
test = summary_cities()
Bang = summary_cities.summary(test, "Bangal... |
import unittest
import smart_match
class TestSmithWatermanGotoh(unittest.TestCase):
def setUp(self):
smart_match.use('Smith Waterman Gotoh')
def test_similarity(self):
self.assertAlmostEqual(float('%.4f' % smart_match.similarity("test string1", "test string2")), 0.9167)
self.assertAl... |
async def main():
from dotenv import load_dotenv
load_dotenv()
from src.client import Client
import os
for token in os.environ.get('DISCORD_SELFBOT_TOKENS').split(';'):
client = Client()
client.loop.create_task(client.start(token, bot=False))
if __name__ == '__main__':
... |
from __future__ import print_function, division, absolute_import
from odin.stats import describe
from sisua.data import get_dataset
from sisua.label_threshold import ProbabilisticEmbedding
# ===========================================================================
# Load dataset
# =================================... |
import os
import pytest
skip_versions = [
"anchore/inline-scan:v0.6.0",
"anchore/inline-scan:v0.5.0",
"anchore/inline-scan:v0.5.1",
]
skip_reason = "Github Advisories not available in this version of Anchore Engine"
class TestNonOsVulnerabilities:
"""
Vulnerability output sample:
GHSA-grmf-... |
#
# Generates 2Dsolang from C.
# requires https://github.com/shinh/elvm
#
ELVM_DIR = "linux-x64-elvm"
try:
import pyjion
pyjion.config(level=2)
pyjion.enable()
except: pass
import os
import argparse
parser = argparse.ArgumentParser(description='Generate 2Dsolang from C')
parser.add_argument('input', help... |
import datetime
import itertools
from collections import namedtuple, OrderedDict
from rest_framework.response import Response
from rest_framework.exceptions import ParseError
from django.views.decorators.http import require_GET
from .serializers import StatusSerializer
from .utils import (pairwise, get_urlquery_ti... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from coremltools.converters.mil.mil import Builder as mb
from coremltools.c... |
def test_new_pybill_obj():
pass
|
from flask_socketio import Namespace, emit
"""
# client example
import socketio
client = socketio.Client()
namespace = "/feeder"
client.connect('http://localhost:8000', namespaces=[namespace])
# correspond with method 'on_message'
client.emit("message", {"foo": "bar"}, namespace=namespace)
client.disconnect()
# c... |
# 实现voxel滤波,并加载数据集中的文件进行验证
import open3d as o3d
import os
import random
import numpy as np
from pyntcloud import PyntCloud
# 功能:对点云进行voxel滤波
# 输入:
# point_cloud:输入点云
# leaf_size: voxel尺寸
def voxel_filter(point_cloud, leaf_size, method='random'):
filtered_points = []
# 作业3
# 屏蔽开始
# 优化版本,主要是 n... |
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import keys
import xlwings
import configs
def get_cmc_ids():
"""Reads https://pro-api.coinmarketcap.com/vi/cryptocurrency/map for a list of cryptocurrency symbols and IDs.
This list c... |
import os
import dropbox
from openpype.api import Logger
from .abstract_provider import AbstractProvider
from ..utils import EditableScopes
log = Logger().get_logger("SyncServer")
class DropboxHandler(AbstractProvider):
CODE = 'dropbox'
LABEL = 'Dropbox'
def __init__(self, project_name, site_name, tre... |
import requests
import time
def timer():
time.sleep(0.36)
def get_numeric_id(id, token, v):
if id.isnumeric():
return id
else:
request = requests.post("https://api.vk.com/method/users.get", data={
"user_ids": id,
"access_token": token,
"v": v}).json()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Thu Oct 31 11:09:38 2019
@author: Jorge palma
MARETEC/Instituto Superior Técnico
Universidade de Lisboa
'''
import sys
import os
import gc
import argparse
import traceback
import time
import datetime
import pandas as pd
import json
import ... |
import os
import environ
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
root = environ.Path(__file__) - 3
env = environ.Env(
DEBUG=(bool, False)
)
env_file = os.path.join(BASE_DIR, ".env")
environ.Env.read_env()
# ... |
# pylint: disable=E1101
import numpy as np
from apdt.ml.utils import batch_norm, layer_norm
try:
import tensorflow as tf
except:
pass
def cnn2d_weight(**kwarg):
'''Construct weight for 2-D CNN.
Parameter
---------
name: str
the variable name scope to be used.
input_dim:... |
from lxml import etree
from scribbler.document import get_document_class_by_name
def parse_document(path):
tree = etree.parse(path)
root = tree.getroot()
result, _ = parse_tree(root)
return result
def parse_tree(root, parent=None):
title = root.tag.title()
root_class = get_document_class_b... |
from django.urls import path
from .views import PostDetailView
urlpatterns = [
path('<slug:the_slug>/',PostDetailView.as_view(),name='post-detail')
]
|
from manage import celery
import os
from requests import post
import xml.etree.ElementTree as ET
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
class FTPError(Exception):
def __init__(self, message):
super(Exception, self).__init__()
# Send E-Mail notification
... |
#Copyright (c) 2021 Kason Suchow
import pygame
import data
class BaseCard(object):
def __init__(self):
self.x = -500
self.y = -500
self.pos = (self.x, self.y)
self.color = None
self.name = ''
self.description = ''
self.attack = 0
self.defense = 0... |
import urllib2
from bs4 import BeautifulSoup
import feedparser
####################################################################
# API
####################################################################
class QTopic:
@staticmethod
def get_follower_count(topic):
url = "https://www.quora.com/" + t... |
from typing import Tuple, Optional
import torch
from torch import nn
from ddiff.layers import (
Residual,
ResnetBlock,
Downsample,
LinearAttention,
PreNorm,
Upsample,
Block,
SinusoidalPositionalEmbedding,
Mish,
)
from ddiff.utils import default
# Gaussian diffusion trainer class
... |
import subprocess
def replace_all(name: str, value: str, file: str = 'local'):
subprocess.run(['git', 'config', '--' + file, name, value], check=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, encoding='utf-8', universal_newlines=True)
def get(name: str, file: str = 'local'):
res = ... |
"""Test runway.config.models.cfngin.__init__."""
# pylint: disable=no-self-use
# pyright: basic
from pathlib import Path
import pytest
import yaml
from pydantic import ValidationError
from runway.config.models.cfngin import (
CfnginConfigDefinitionModel,
CfnginHookDefinitionModel,
CfnginPackageSourcesDefi... |
from dal import autocomplete
from django import forms
from .models import *
class RaceForm(forms.ModelForm):
class Meta:
model = Race
fields = ('__all__')
widgets = {
'race': autocomplete.ModelSelect2(url='race-autocomplete')
} |
import os
import json
import logging
class mock_config:
def __init__(self, attributes):
for k, v in attributes.items():
setattr(self, k, v)
class mock_logger :
def info(self,msg_str):
logging.info(msg_str)
def debug(self,msg_str):
logging.debug(msg_str)
def warning... |
from Core.IFactory import IFactory
from Regs.Block_E import RE990
class RE990Factory(IFactory):
def create_block_object(self, line):
self.re990 = _re990 = RE990()
_re990.reg_list = line
return _re990
|
from django.contrib import admin
from group.models import Group, GroupCommunityPost, GroupNotice, GroupCalendar
admin.site.register(Group)
admin.site.register(GroupCommunityPost)
admin.site.register(GroupNotice)
admin.site.register(GroupCalendar)
|
#
# This file is part of the Ingram Micro CloudBlue Connect Python OpenAPI Client.
#
# Copyright (c) 2021 Ingram Micro. All Rights Reserved.
#
from connect.client.exceptions import ClientError # noqa
from connect.client.fluent import ConnectClient # noqa
from connect.client.rql import R # noqa
|
# -*- coding: utf-8 -*-
'''
Project: Product Aesthetic Design: A Machine Learning Augmentation
Authors: Alex Burnap, Yale University
Email: alex.burnap@yale.edu
License: MIT License
OSS Code Attribution (see Licensing Inheritance):
Portions of Code From or Modi... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import sys
from enum import Enum
from PySide2.QtUiTools import QUiLoader #allows us to load .ui files
#be sure to import any widget that you want to manipulate
from PySide2.QtWidgets import QApplication
from calculatorViewModel import CalculatorViewModel
if __name__ == '__main__':
app = QApplication(sys.argv)
... |
import os
import sys
import requests
import json
from pprint import pprint
# This is so that below import works
sys.path.append(os.path.realpath("."))
import fawkes.utils.utils as utils
import fawkes.constants.constants as constants
def get_oauth_token(base_url, params):
url = base_url + "/services/oauth2/toke... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.