content stringlengths 5 1.05M |
|---|
from .optimize import minimize_variational
__all__ = ['minimize_variational']
|
"""This module defines all the Lambda functions to be deployed to AWS.
The function name would be AWS Lambda function name as well. Everything to be
packaged to Lambda must be contained *inside* the function. Module level
imports are for local testing or packaging use only.
Use ``bert.constants.AWS_LAMBDA_FUNCTION`` t... |
#
# this is the app/__init__.py file
#
# the presence of this file, even if empty,
# ... facilitates local imports from one file to another,
# ... including importing app code for testing purposes
#
|
# Log Parser for RTI Connext.
#
# Copyright 2016 Real-Time Innovations, 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
#
# ... |
import colorsys
black = (0,0,0)
white = (1,1,1)
whiteish = (0.9, 0.9, 0.9)
grey = (0.5,0.5,0.5)
darkgrey = (0.32, 0.32, 0.32)
lightgrey = (0.75,0.75,0.75)
red = (1,0,0)
redish = (0.5, 0, 0)
green = (0,1,0)
greenish = (0, 0.5, 0)
blue = (0,0,1)
blueish = (0, 0, 0.5)
darkblue = (0, 0, 0.2)
yellow = (1,1,0)
yellowish =... |
# 335-self-crossing.py
class Solution(object):
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
l = len(x)
if (l < 4): return False
flag = 0 # Is square decreasing
hasBound = 0 # Has previous edge, cannot cross this bo... |
import rospy
from mavros_msgs.msg import PositionTarget
from geometry_msgs.msg import PoseStamped, Point
from arion.offboard import OffboardControl
from arion.subscriber.point_subscriber import PointSubscriber
from arion.subscriber.position_subscriber import CurrentPositionSubscriber
class PositionControlRawNode(Off... |
import json
import os
import slurm
from assertpy import assert_that
from jsonschema import validate
from slurm.pcluster_slurm_config_generator import generate_slurm_config_files
INPUT_SCHEMA = {
"type": "object",
"properties": {
"cluster": {
"type": "object",
"properties": {
... |
# Copyright 2019 The TensorFlow Authors. 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 applic... |
"""
This is the main class and the entry point for the programmer.
It provides a mechanism to treat multiple dictionaries as if they were one
dictionary.
Also provided is the ability to reference parts and still maintain the idea of it
being one dictionary.
With the ability to delete from the dictionary and the abil... |
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import subprocess
class ServerHandler(BaseHTTPRequestHandler):
def _set_headers(self,header='text/html'):
self.send_response(200)
self.send_header('Content-type', header)
self.end_headers()
def do_GET(self):
rt... |
from django.contrib import messages
from django.views.generic import FormView, TemplateView, View
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import logout
from django.utils.translation import ugettext as __
from django.urls import reverse_lazy
from django.http import HttpResponseR... |
import matplotlib.pyplot as plt
from pytrends.request import TrendReq
from datetime import datetime
import json
import pandas as pd
import pprint
# プログラミング言語の人気度を取得
pytrends = TrendReq(hl='ja-JP', tz=360)
kw_list = ["Java","Python","Ruby","Javascript","PHP"]
pytrends.build_payload(kw_list, timeframe='today 5-y', geo='... |
version = "2020-05-27" |
# Copyright (c) 2013-2014 Parallels, 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 ... |
import numpy
import cPickle as pkl
import gzip
def fopen(filename, mode='r'):
if filename.endswith('.gz'):
return gzip.open(filename, mode)
return open(filename, mode)
class TextIterator:
"""Simple Bitext iterator."""
def __init__(self, source, target, label, source_synset, target_synset,
... |
def quicksort(xs):
if len(xs) == 0:
return []
pivot = xs[0]
xs = xs[1:]
left = [x for x in xs if x <= pivot]
right = [x for x in xs if x > pivot]
res = quicksort(left)
res.append(pivot)
res += quicksort(right)
return res
xs = [1, 3, 2, 4, 5, 2]
sorted_xs = quicksort(xs)
|
import numpy as np
import scipy.linalg
import sklearn.metrics
def kernel(ker, X1, X2, gamma):
K = None
if not ker or ker == 'primal':
K = X1
elif ker == 'linear':
if X2 is not None:
K = sklearn.metrics.pairwise.linear_kernel(np.asarray(X1).T, np.asarray(X2).T)
else:
K = sklearn.metrics.pairwise.linear_k... |
import asyncio
from subprocess import call
import os
import dotenv
import aiohttp
import requests
import youtube_dl as ytdl
from apiclient.discovery import build
__BASE_URL__ = "https://www.googleapis.com/youtube/v3"
class BaseYoutubeAPI:
"""Base Youtube API Client.
Handles users credentials API key.
""... |
# Copyright 2015-2018 The NATS 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 applicable law or agreed to in writi... |
"""Delete a kubeflow instance."""
import fire
import json
import logging
import retrying
from googleapiclient import discovery
from googleapiclient import errors
from oauth2client.client import GoogleCredentials
from kubeflow.testing import util
@retrying.retry(stop_max_delay=10*60*1000, wait_exponential_max=60*100... |
import ccobra
import numpy as np
class RandomModel(ccobra.CCobraModel):
def __init__(self, name='Random'):
super(RandomModel, self).__init__(name, ['syllogistic-belief'], ['verify'])
def predict(self, item, **kwargs):
return np.random.choice([True, False])
def predict_rating(self, item, *... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Aladom SAS & Hosting Dvpt SAS
from django.db.models import BooleanField
__all__ = [
'VariableHelpTextBooleanField',
]
class VariableHelpTextBooleanField(BooleanField):
"""Fixes an issue with help_text depending on a variable.
See https://github.com/Aladom/dja... |
# -*- coding: UTF-8 -*-
# in: ProteinDBs with and without decoys, number of samples for simulation and Inspect
# out: FDR-matrix (and several result files)
# Attention: For using Inspect, this script must be called out of the Inspect-directory! The
# "cd /home/franziska/bin/Inspect" command is called be the main routi... |
# =============================================================================
# PROJECT CHRONO - http://projectchrono.org
#
# Copyright (c) 2019 projectchrono.org
# All rights reserved.
#
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file at the top level of the distr... |
# traveling salesman algorithm implementation in jython
# This also prints the index of the points of the shortest route.
# To make a plot of the route, write the points at these indexes
# to a file and plot them in your favorite tool.
import sys
import os
import time
import csv
import java.io.FileReader as FileReade... |
import os
import unittest
from biolinkml.generators.pythongen import PythonGenerator
from tests.test_utils.environment import env
from tests.utils.generatortestcase import GeneratorTestCase
from tests.utils.filters import metadata_filter
from tests.utils.python_comparator import compare_python
class IfAbsentTestCase... |
from dataclasses import dataclass
from itertools import chain
from typing import List, Optional, Iterable
def is_junk_line(line: str):
if line.strip() == "":
return True
if line == "\n":
return True
if "Кубок Европы" in line:
return True
if line.startswith("На главную страницу"... |
import os
import json
import socket
import psutil
from uuid import uuid4
from time import time, sleep
from multiprocessing.connection import Listener, Client
from traceback import format_exc
from qaviton_handlers.try_functions import try_to
# from qaviton_package_manager.conf import ignore_list
from qaviton_package_man... |
# Copyright 2014 Red Hat, 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 a... |
import logging
from os import getenv
LOGGER = None
if LOGGER is None:
LOGGER = logging.getLogger("bs.log")
LOGGER.setLevel(getenv("BS_LOG_LEVEL", "INFO"))
def log(*args, **kwargs):
"""Pass-through to the global LOGGER objects log method."""
LOGGER.log(*args, **kwargs)
def info(*args, **kwargs):
... |
# coding=utf-8
from mongoengine import *
class OnlineCount(Document):
charge_count = IntField(verbose_name=u"充值人数")
online_count = IntField(verbose_name=u"在线人数")
update_time = DateTimeField(verbose_name=u"更新时间")
|
'''
for testing Python snippets
'''
from datetime import datetime
currentSecond= datetime.now().second
currentMinute = datetime.now().minute
currentHour = datetime.now().hour
currentDay = datetime.now().day
currentMonth = datetime.now().month
currentYear = datetime.now().year
f = lambda : (print('hello'),'world')[1... |
import subprocess
import secrets
import getpass
import os
import requests
import urllib.parse
import time
from google.colab import files, drive, auth
from google.cloud import storage
import glob
def connect(LOG_DIR = '/log/fit'):
print('It may take a few seconds for processing. Please wait.')
root_password = s... |
from __future__ import absolute_import, division, print_function
from .version import __version__
from .evaluate import *
|
from pypylon import pylon
class Camera():
def __init__(self):
self.camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
self.converter = pylon.ImageFormatConverter()
self.converter.OutputPix... |
"""
Check that doc/source/reference/general_utility_functions.rst documents
all exceptions and warnings in pandas/errors/__init__.py.
This is meant to be run as a pre-commit hook - to run it manually, you can do:
pre-commit run pandas-errors-documented --all-files
"""
from __future__ import annotations
import ar... |
import io
from setuptools import find_packages
from setuptools import setup
with io.open('README.md', 'rt', encoding='utf8') as f:
readme = f.read()
setup(
name='cranserver',
version='1.0.0',
url='http://github.com/UptakeOpenSource/cran-server',
license='BSD 3-Clause',
maintainer='Troy de Fre... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__doctest_requires__ = {'*': ['matplotlib']}
""" This module contains dictionaries that can be used to set a
matplotlib plotting style.
It is mostly here to allow a consistent plotting style in tutorials,
but can be used to prepare any matplotlib figure.... |
from sklearn.naive_bayes import GaussianNB
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from eye_detector.train.models.decorator import ProbModelDecorator
def bayes(x, y, shape):
return ProbModelDecorator(GaussianNB())
def gauss_rbf(x, y, shape... |
import numpy as np
from vunet.train.config import config
import logging
import gc
from pathlib import Path
logger = logging.getLogger("tensorflow")
def get_max_complex(data, keys=["vocals", "mixture", "accompaniment"]):
# sometimes the max is not the mixture
pos = np.argmax([np.abs(complex_max(data[i])) for... |
import ctypes
from ctypes import (
c_bool, c_char, c_char_p, c_double, c_float, c_int,
c_int8, c_int16, c_int32, c_int64,
c_size_t,
c_uint8, c_uint16, c_uint32, c_uint64,
c_void_p)
import enum
import glob
import os
import sys
from . import library
c_char_p_p = ctypes.POINTER(c_char_p)
c_double_p... |
from __future__ import absolute_import
from require.require import *
|
from setuptools import setup, find_packages
install_requires = [
'opencv-python >= 4.1.0',
'Pillow >= 6.0.0',
'numpy >=1.16.4'
]
setup(
name='imbo',
version='0.1.1',
python_requires='>=2.7',
packages=find_packages(),
include_package_data=True,
author='Nitin Rai',
author_email... |
# -*- coding:utf-8 -*-
__author__ = 'Ren Kang'
__date__ = '2018/3/27 13:32'
import uuid
import hashlib
from django.db.models.signals import pre_save, post_delete, post_save
from django.dispatch import receiver, Signal
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.short... |
import elementary
import evas
import os
class stationWindow(elementary.Box):
def __init__( self, parent ):
#builds a elementary box to accept login information
elementary.Box.__init__(self, parent.mainWindow)
self.ourPlayer = parent.ourPlayer
self.win = parent.mainWindow
se... |
from sys import exit
import argparse
from . import configurator
def main():
c = configurator.Configurator()
def parse_options():
parser = argparse.ArgumentParser(description="Configure Xfce4")
parser.add_argument('theme', help='theme name', choices=c.theme_names, nargs='?')
parser.add_... |
from dataclasses import dataclass
from math import isclose
@dataclass(frozen=True)
class Point:
x: float
y: float
@dataclass(frozen=True)
class Triangle:
a: Point
b: Point
c: Point
def get_area(self) -> float:
"""Computes the area of the triangle abc."""
area = (
... |
#!/usr/bin/env python3
import os
import argparse
import apache_beam as beam
import apache_beam.transforms.window as window
from apache_beam.options.pipeline_options import PipelineOptions
from file2csv.Converter import Converter
def run_pipeline(fixedfile: str, specfile: str, csvfile: str) -> bool:
converter = Co... |
@foo.bar
class C:
pass
|
"""This is the installation toolset for this project."""
from datetime import datetime
from pathlib import Path
from subprocess import Popen, PIPE
from setuptools import setup, find_packages
with open('README.md', 'r') as fh:
long_description = fh.read()
def _build_time():
ctime = datetime.utcnow()
retu... |
import torch
import numpy as np
def compute_cmvn_epoch(opt, train_loader, enhance_model, feat_model):
enhance_model.eval()
feat_model.eval()
torch.set_grad_enabled(False)
##print(enhance_model.state_dict())
enhance_cmvn_file = os.path.join(opt.exp_path, 'enhance_cmvn.npy')
for i, (data) in enume... |
"""
__S1ThenClauseComplete_MDL.py_____________________________________________________
Automatically generated AToM3 Model File (Do not modify directly)
Author: gehan
Modified: Wed Oct 16 11:56:05 2013
__________________________________________________________________________________
"""
from stickylink import *
from ... |
'''
Created on 1.12.2016
@author: Darren
'''
'''
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
Credits:Special thanks to @jianchao.li.fighter for adding this prob... |
import logging
import os
import tempfile
import pytest
from quetz.config import Config, ConfigEntry, ConfigSection, configure_logger
from quetz.dao import Dao
from quetz.errors import ConfigError
@pytest.fixture
def config_extra():
return r"""[users]
admins=["bartosz"]
default_role = "member"
create_default_cha... |
import glob
import os
from more_itertools import ichunked
from PIL import Image
import torch
from torchvision import transforms
import tqdm
from tartangan.utils.fs import maybe_makedirs
from tartangan.trainers.utils import set_device_from_args
from .base import GOutputApp
class InfoGANEncodeImage(GOutputApp):
"... |
"""
Import any enabled modules as specified in the settings.py
file for the project.
"""
import imp
import sys
from django.conf import settings
def import_module(name, globals=None, locals=None, fromlist=None):
# Fast path: see if the module has already been imported.
try:
return sys.modules[name]
... |
from django.shortcuts import redirect
from django.http import HttpResponse
from django.template import loader
from http.server import HTTPStatus
from .User import User
import iotweb.views.urls_and_messages as UM
import requests
import json
def tokens(request, shdw_id):
"""
GET request: renders the token page... |
# -*- coding: utf-8 -*-
"""
This class manages the fetching of stock data and notifications.
"""
import pync
import os, sys, atexit, signal, socket
import time
from stock_config.nasdaq_stock_config import NasdaqStockConfig
class StockNotifier:
PIDFILE = "/tmp/stocknotifier.pid"
LOCALHOST = '127.0.0.1'
... |
import os
import weakref
import numpy as np
from yt.data_objects.index_subobjects.unstructured_mesh import SemiStructuredMesh
from yt.data_objects.static_output import Dataset
from yt.funcs import setdefaultattr
from yt.geometry.unstructured_mesh_handler import UnstructuredIndex
from yt.utilities.file_handler import ... |
from neuron import h
class Cell(object):
""" Interface class to build different types of cells. """
def __init__(self):
""" Object initialization. """
# Neuron cell - to be used as the source of a h.NetCon
self.cell = None
def connect_to_target(self, target, weight: float = 0, de... |
# flake8: noqa
from .version import __version__
default_app_config = 'querybuilder.apps.QueryBuilderConfig'
|
# -*- coding: utf-8 -*-
"""Main module."""
import os
import typing
from pathlib import Path
from urllib.parse import urljoin
import pyperclip
from wand.color import Color
from wand.image import Image
PathLike = typing.Union[str, os.PathLike]
def convert(
img: Image,
size: int,
filename: PathLike,
b... |
from unittest import TestCase
# toolbox imports
from dltb.thirdparty.keras.datasource import KerasDatasource
class TestKeras(TestCase):
def setUp(self):
self.datasource = KerasDatasource('mnist', 'test')
def test_prepare(self):
self.datasource.prepare()
self.assertTrue(self.datasour... |
from .compiler import StaticDigestCompiler
from .digest import StaticDigest
__all__ = ['StaticDigest', 'StaticDigestCompiler']
|
from . import augmenters
__version__ = '0.1.17'
|
import setuptools
import sys
import os
import io
import re
###############################################################################
name = 'veracode-python'
description = 'Python wrapper for the Veracode XML APIs'
install_requires = [
'lxml>=4.4.1',
'python-dateutil>=2.8.1',
'requests>=2.22.0',
... |
from streamz import Stream
import json
import csv
def preprocess_stream(preprocs, stream):
for prep in preprocs:
func = prep["func"]
params = {}
if "parameters" in prep:
params = prep["parameters"]
if func == "lower":
stream = stream.map(str.lower)
return... |
import sqlite3
conexao =sqlite3.connect('livraria.db')
cur=conexao.cursor()
sql="insert into tb_cliente(cpf,nome,idade) values(?,?,?)"
cpf1=input('423')
nome1 = input('Ana')
idade1 = input(23)
cur.execute(sql,(cpf1,nome1,idade1))
conexao.commit()
print("one record added successfully")
cur.close()
conexao.close() |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('crowd_brew'... |
from unittest import TestCase
from uuid import uuid4
from zeroos.core0.client import Client
from loguru import logger
import configparser
import redis
import base64
import json
import redis
logger.add("tf_gateway.log", format="{time} {level} {message}", level="INFO")
class BaseTest(TestCase):
def __init__(self, ... |
import torchvision.models as models
from torchvision import transforms
from PIL import Image
import torch
import json
import os
# mobilenet = models.mobilenet_v2()
# torch.save(mobilenet, 'mobilenet.pt')
def predict_pytorch(model_fname, img):
model = load_model(model_fname)
batch_t = preprocess_image(img)
out = mo... |
#! /usr/bin/env python3
#from numba import jit
from random import choice
# by bar (horizontal):
# a b a c
# or (vertical)
# a b c d
# a e c g
# or (both)
# a b a c
# a d a e
# by segment (horizontal):
# a b a b
# or (vertical)
# a b c d
# a b e f
# or (both)
# a b c a b
# a b d a b
# by phrase:
# a b c... |
import altair as alt
import pandas as pd
def macro_plot(df, goal_df,plot_width=200):
chart1 = alt.Chart(df[df['cat']=='calories']).mark_bar().encode(
alt.Y('cat', title='Calories', axis=alt.Axis(labels=False, ticks=False, titleAngle=0, titlePadding=40)),
alt.X('value', title='', axis=alt.Axis(values... |
from sendbee_api.query_params import QueryParams
class ChatbotActivity(QueryParams):
"""Parameters for turning the chatbot on or off for a conversation"""
conversation_id = 'conversation_id', 'Conversation UUID'
active = 'active', 'Chatbot activity'
class ChatbotActivityStatus(QueryParams):
"""Param... |
from utils.myqrcode import Qrcode
if __name__ == '__main__':
# icon_path = 'icon.jpeg'
# icon_img = Qrcode.convert_local_icon_to_img(icon_path=icon_path)
icon_url = 'http://thirdwx.qlogo.cn/mmopen/vi_32/3IySpcoGTPQu2WbNUGFhq2icLicJpMS1uFdfDWFdE0lv9cjPGeEBors5E6fXqo0ictQlRws1ZwpUTVQS6yDeVsDeQ/132'
ic... |
import pandas as pd
import numpy as np
import copy
import sympy as sp
from sympy import sympify
def get_pivotzeile(copy_tableau, pivot_spalte, anzahl_zeilen):
# soll original Tableau nicht ändern
copy_tableau = copy.deepcopy(copy_tableau)
# wähle Ressourcenverbrauchskoeffizienten der Pivotspalte
pivo... |
"""Environment for training automated vehicles in a mixed-autonomy setting."""
import numpy as np
from gym.spaces import Box
from copy import deepcopy
from hbaselines.envs.mixed_autonomy.envs import AVEnv
from hbaselines.envs.mixed_autonomy.envs.av import CLOSED_ENV_PARAMS
from hbaselines.envs.mixed_autonomy.envs.av i... |
from regression_tests import *
class Test(Test):
settings = TestSettings(
tool='fileinfo',
input='VMProtect-3.4_demo.ex',
args='--json'
)
def test_correctly_analyzes_input_file(self):
self.assertTrue(self.fileinfo.succeeded)
self.assertEqual(self.fileinfo.output['to... |
from logging import handlers
class BufferingSMTPHandler(handlers.SMTPHandler):
"""
BufferingSMTPHandler works like SMTPHandler log handler except that
it buffers log messages until buffer size reaches or exceeds the specified
capacity at which point it will then send everything that was buffered up
... |
"""
Write knitting pattern data to a bitmap file.
---
Based on an example by Anders Holden Deleuran
https://discourse.mcneel.com/t/write-a-bitmap-pixel-by-pixel-in-python/81116/2
Inputs:
Write: Set to True to save the bitmap file.
{item, bool}
PixelData: The knitting pattern pixel dat... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\source\gui_simple_designer.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt... |
# Generated by Django 3.2.8 on 2021-10-06 17:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('recipe_app', '0003_review'),
]
operations = [
migrations.RenameField(
model_name='ingredient',
old_name='measurement',
... |
from glob import glob
from json import dump, load
from pathlib import Path
from random import choice
from re import search
from click import get_app_dir
from inflect import engine
from rich import print
from rich.markdown import Markdown
from rich.panel import Panel
from rich.prompt import Prompt
p = engine()
def d... |
#!/usr/bin/python3
from http.server import BaseHTTPRequestHandler, HTTPServer
from http import cookies
import json
# User table.
users = {}
def addUsers(l):
for u in l:
users[u.get("sub")] = u
# Add numeric user ID.
u["id"] = len(users)
addUsers([
{
"sub": "arthur",
... |
import os
import re
import subprocess
import sys
from setuptools import setup
def get_version(package: str) -> str:
"""Return version of the package."""
path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), package, "__init__.py"
)
with open(path, "r") as file:
source = fil... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from bakery.views import BuildableListView, BuildableDetailView
from .models import Show, Category
# Create your views here.
class HomePageView(BuildableListView):
queryset = Category.objects.filter(display_on_ho... |
from .test_smoothers import * |
"""OpenAPI core licenses models module"""
class License(object):
def __init__(self, name, url=None, extensions=None):
self.name = name
self.url = url
self.extensions = extensions and dict(extensions) or {}
|
"""
Training and evaluating script for part segmentation with PartNet dataset
"""
import os
import sys
import time
import pprint
import psutil
import argparse
import subprocess
import numpy as np
import tensorflow as tf
from sklearn.neighbors import KDTree
FILE_DIR = os.path.abspath(__file__)
BASE_DIR = os.path.dirnam... |
import subprocess
import logging
from ruxit.api.base_plugin import BasePlugin
class SSHConnections(BasePlugin):
def query(self, **kwargs):
if self.config['debug']:
self.logger.setLevel(logging.DEBUG)
self.logger.debug("SSH Connections - Starting Query... \n")
outpu... |
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def DFSUtil(self,v,visited):
visited[v]= True
print v,
for i in self.graph[v]:
... |
from io import BytesIO
from .virtualizedproc import signature
class MixGrabOutput(object):
def __init__(self, *args, **kwds):
self._write_buffer = BytesIO()
self._write_buffer_limit = kwds.pop('write_buffer_limit', 1000000)
super(MixGrabOutput, self).__init__(*args, **kwds)
@signatur... |
import plotly.offline as py
from facebook_data_analysis.tools.helpers import resolve_path
def make_map(coordinates_df):
data = [
dict(
type="scattergeo",
lon=coordinates_df["lon"],
lat=coordinates_df["lat"],
text=coordinates_df["city"] + ", " + coordinates_d... |
import unittest
from django_no_sql.db import aggregates
from django_no_sql.db.database import Database
from django_no_sql.db.managers import Manager
class TestManager(unittest.TestCase):
def setUp(self):
self.db = Database(import_name=__file__)
self.db.load_database()
def test_get(self):
... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.3.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # PubMed search for Gen... |
from data_loader import DataLoader
import tensorflow as tf
import argparse
from utils import get_callbacks_list, get_model_from_id, get_classes, preprocess_image, write_class_on_img
import numpy as np
import cv2
import os
INPUT_SHAPE = (220, 220, 3)
def main(arguments):
cap = cv2.VideoCapture(arguments.video)
... |
from __future__ import absolute_import
import json
import numpy as np
from ..app import app
from . import test_utils
from ...plotting import (reset_output, output_server, push, curdoc, figure)
from ...session import TestSession
from ...models.sources import ServerDataSource
from ...models.ranges import Range1d
from... |
__version__ = "3.8.8"
import pathlib # isort:skip
root = pathlib.Path(__file__).parent # isort:skip
APP_NAME = "SPFY"
import os # isort:skip
import kick # isort:skip
kick.start(APP_NAME.lower()) # isort:skip
from kick import config, logger # isort:skip
Unsplash = None
if config.unsplash.auth.client_id:
... |
import functools
import time
from django.db import connection, reset_queries
def query_debugger(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
reset_queries()
number_of_start_queries = len(connection.queries)
start = time.perf_counter()
result = func(*args, **kwarg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.