content stringlengths 5 1.05M |
|---|
from sqlalchemy import Column, String, Integer
from core.database import Base
# All the enums are defined in response_plan_validator.py
class ResponsePlan(Base):
"""
Response plan table
"""
__tablename__ = "response_plan"
internal_id = Column(Integer, primary_key=True, nullable=False)
respons... |
# Copyright 2020 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""Tree-structure description generator for structured API endpoints
The Dorest project
:copyright: (c) 2020 Ichise Laboratory at NII & AIST
:author: Rungsiman Nararatwong
"""
import os
from importlib import import_module
from typing import List
from .describe import Endpoint
def walk(branch: str, reduce: bool = F... |
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
import logging
log = logging.getLogger(__name__)
import os
from threading import Event
from cassandra.cluster import Cluster
try:
from ccmlib.cluster import Cluster as CCMCluster
from ccmlib import common
except ImportError ... |
from typing import Tuple, NewType, Optional, Dict, Callable, Any, Union, List
import pygame
import pygame.gfxdraw
from pygame.locals import Rect
from pygame.surface import Surface
from pygame.sprite import Sprite
from sprites import TextSprite, PressRect
from sprites import RichSprite, SimpleSprite, adjust_rect
from ... |
from __future__ import annotations
from prettyqt import core
from prettyqt.qt import QtCore
from prettyqt.utils import bidict
PROCESS_EVENT_FLAGS = bidict(
all=QtCore.QEventLoop.ProcessEventsFlag.AllEvents,
exclude_user_input=QtCore.QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents,
exclude_socket_noti... |
"""
Various model interfaces.
"""
class Model(object):
"""Base model class."""
def predict(self, X):
"""Predict score for X.
Parameters
----------
X : array_like of shape = [n_samples, n_features]
The input samples.
Returns
-------
y : ar... |
from pynq import DefaultIP
from pynq import DefaultHierarchy
from pynq import Xlnk
import numpy as np
class QPSKRx(DefaultHierarchy):
def __init__(self,
description,
pkt_dec=32,
pkt_sync=128,
pkt_rrc=512,
pkt_out=16):
""... |
import asyncio
import datetime
import discord
import config
import sys
import traceback
from discord.ext import commands
# from classes.InfoFiles import all_prefixes
class Bot(commands.Bot):
def __init__(self, **kwargs):
super().__init__(
command_prefix=config.global_prefix, **kwargs
)... |
import unittest
import pytest
from snucovery.cli import Arguments
class TestCli(unittest.TestCase):
def test_init_args(self):
args = Arguments()
self.assertTrue(str(args.parser.print_help()))
self.assertIsInstance(args, object)
|
# MIT License: Copyright (c) 2021 Lorenzo Loconte, Gennaro Gala
from deeprob.spn.structure.leaf import Leaf
from deeprob.spn.structure.node import Node, Sum, Product, bfs
from deeprob.spn.utils.filter import collect_nodes, filter_nodes_by_type
def compute_statistics(root: Node) -> dict:
"""
Compute some stat... |
import datetime
from sqlalchemy import Table, Column, ForeignKey
from sqlalchemy.orm import mapper, relationship
from sqlalchemy.types import Integer, Date
from stockprophet.db import metadata
from stockprophet.db.model.stock import Stock
class StockMetadata(object):
__table__ = None
def __init__(self,
... |
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Lice... |
import sys
import csv
import numpy as np
import matplotlib.pyplot as plt
allgraph = {}
if len(sys.argv) <= 2:
dataset = 'natural-disasters-by-type'
else:
dataset = sys.argv[2]
with open('resources/' + dataset + '.csv') as csvDataFile:
csvReader = csv.reader(csvDataFile)
next(csvReader)
for row in csvReader:
c... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 05 11:34:28 2016
@author: Pedro Leal
"""
import math
from optimization_tools import plot_generations
filename = "opt_data.txt"
n_generation = 50
outputs_plotted = ['theta']
output_constrained = ['theta']
g1 = lambda x: True if x < 0. else False
g = [g1]
p1 = lambda x... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Aplicações distribuídas - Projeto 2 - net_client.py
Grupo: ad007
Números de aluno: 50006, 50013, 50019
"""
# zona para fazer importação
from sock_utils import create_tcp_client_socket, receive_all
import socket as s
import struct
import pickle
# definição da classe serv... |
"""
This module defines the Variable class which represents Variables and their values in
Source classes.
"""
from typing import Optional, TYPE_CHECKING
import logging
if TYPE_CHECKING:
from lemonspotter.core.type import Type
class Variable:
"""
This class represents any C variable for source code gener... |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# TODO: pass ft_cse to use fine-tuned feature
# TODO: pass fine_steps -1 to use fine samples
from absl import flags, app
import sys
sys.path.insert(0,'')
sys.path.insert(0,'third_party')
import numpy as np
from matplotlib import pyplot as plt
impor... |
from widely.bucket import get_current_or_specified_bucket
def domains(arguments):
"""
Displays a list of domains for the current or specified sitename.
Usage: widely domains [--site <SITENAME>]
"""
bucket = get_current_or_specified_bucket(arguments)
print('=== {0} Domain Names'.format(bucket.... |
from manage_users.AnsibleUsers import AnsibleUsers # noqa
from manage_users import script_helpers # noqa
from manage_users.exceptions import ( # noqa
DuplicateUserError,
NoSuchUserError,
SSHKeyNotFoundError,
)
__author__ = 'geokala- https://github.com/geokala'
__version__ = '2.0.1'
"""
This module i... |
from telegram import Update
from telegram.ext import CallbackContext, ConversationHandler, CommandHandler, MessageHandler, Filters, Updater
from db import DBConnector
from utils import send_like_product
EAT_1, EAT_2 = range(2)
def eat_0(update: Update, _: CallbackContext):
update.message.reply_text('What do you... |
from .modules import *
from .functional import elementwise_add, l2_norm |
# Library Imports
import nextcord, json
from nextcord.ext import commands
# Custom Imports
from Functions.Embed import *
from Views.Roles import RoleView
from Views.Ranks import RankView
# Options from Json
with open('Config/Options.json') as RawOptions:
Options = json.load(RawOptions)
# Roles Class
class Roles(... |
import cv2
import numpy as np
# Grayscale + Otsu's threshold
image = cv2.imread('1.jpg')
original = image.copy()
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Find lines
minLineLength = 10
... |
# The greatest common divisor of two positive integers is the largest integer that divides each of them without remainder. For example,
#
# gcd(2, 12) = 2
#
# gcd(6, 12) = 6
#
# gcd(9, 12) = 3
#
# gcd(17, 12) = 1
#
# Write an iterative function, gcdIter(a, b), that implements this idea. One easy way to do this is to be... |
"""Script to create the piece and occupancy classification datasets from the input dataset of images.
.. code-block:: console
$ python -m chesscog.transfer_learning.create_dataset --help
usage: create_dataset.py [-h]
Create the piece and occupancy classification datasets.
optional argument... |
import os
import operator as op
from b_extract_patent import extract
def check_if_personal(inventor_list, company_list):
companys = set(company_list)
for inventor in inventor_list:
if inventor in companys:
return True
return False
def fetch_author_org(inventor_list, company_list):
... |
from .user_home_handler import UserHomeHandler # noqa
from .base_handler import BaseHandler # noqa
from .register_container_handler import RegisterContainerHandler # noqa
from .admin.admin_home_handler import AdminHomeHandler # noqa
|
from __future__ import print_function
import torch
import torch.utils.data as data
from torchvision import transforms
import os
import random
from PIL import Image
import numpy as np
import ipdb
import pickle
from pycocotools import mask as maskUtils
import lintel
import time
from torch.utils.data.dataloader import def... |
from __future__ import absolute_import
from maya import cmds
from PySide2 import QtWidgets
from . import maya
from .. import manager
UPDATE_MODEL = manager.Action.UPDATE_MODEL
IGNORE_UPDATE = manager.Action.IGNORE_UPDATE
RELOAD_MODEL = manager.Action.RELOAD_MODEL
class Manager(maya.Manager):
display_name = 'F... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2019 Snowflake Computing Inc. All right reserved.
#
from sqlalchemy import Column, Integer, MetaData, Sequence, String, Table, inspect
def test_table_name_with_reserved_words(engine_testaccount, db_parameters):
metadata = MetaData()
test_ta... |
# -*- coding: utf-8 -*-
"""CredicxoMLtest.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1-S80UL_brQzSJkoEE29Y3ILhLVcktFBB
"""
# Import all neccessar libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pathlib i... |
import os
import numpy as np
import matplotlib.pyplot as plt
from PyQt5 import QtWidgets
import ana_cont.continuation as cont
from gui.pade_ui import Ui_MainWindow
from gui.gui_backend import RealFrequencyGrid, InputData, TextInputData, OutputData
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
"""The Ma... |
import logging
import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.exceptions import PreventUpdate
from dash.dependencies import Input, Output, ALL
_label = None
_layout = html.Div([
html.Div(id='message')
])
def layout():
return _layout
def callbacks(app, fsc,... |
import os
import md5
import re
print "Please enter the password key you would like to use for the secret token:"
secret_token = raw_input('> ')
if secret_token:
print 'Using secret token: %s' % secret_token
# have to copy all files to the new directory
# have to delete the .svn directories
os.system('rm -rf... |
"""
4 4
1 2 1
2 3 2
3 4 3
4 1 4
"""
from prims import prims
def test_prims_should_find_cost_of_6(GF1, simple_que):
v = GF1.any_vertice()
mst = prims(GF1, simple_que, v)
assert mst.cost == 6
def test_prims_should_find_vertices_1_2_3(GF1, simple_que):
v = GF1.any_vertice()
mst = prims(GF1, simple_qu... |
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from .views import ArticleDetailView, ArticleCreateView, ArticleList
urlpatterns = [
url(r'^create/(?P<pk>\d+)/$', ArticleCreateView, name='article-create'),
url(r'^$', ArticleList.as_view(), name='article-list'),
... |
#!/usr/bin/env python
# Copyright (c) 2018, Vanessa Sochat
# 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 ... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import json
import os
import time
import warnings
from collections import defaultdict
import h5py
import keras
import keras.backend as K
import keras.optimizers as opt
import numpy as np
from keras.callbacks import ModelCheckpoint
from keras.engi... |
import os
import requests
USERNAME = os.getenv("USERNAME")
IP = os.getenv("IP")
URL = f"http://{IP}/api/{USERNAME}/lights/1/state"
body = {
"bri": 254,
"on": True,
"sat": 0
}
requests.put(URL, json=body)
|
from .block import Block
from .nginx import Nginx
from .upstream import Upstream
from .map import Map, MapKeyParis, MapDefinition
from .server import Server
from .location import Location, LocationRewrite, LocationProxy
from .exception import NginxError, LocationError, ServerError
|
"""
Testing the Elasticsearch server deployment
"""
import logging
import time
from elasticsearch import Elasticsearch, exceptions as esexp
from ocs_ci.ocs import defaults
from ocs_ci.helpers.helpers import get_full_test_logs_path
from ocs_ci.helpers.performance_lib import run_command
from ocs_ci.ocs.ocp import OCP
... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 15 13:18:54 2021
@author: Eliza
"""
# Import the required libraries.
import random
# Create a "colour" variable and assign it a list of colours representing different bat species.
colour = ["white","red", "green", "blue"]
# Create "NewBat" class to make the bats fly, mo... |
# Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
#
# 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 ... |
import collections
import os
import datasets
from param import args
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data.dataloader import DataLoader
from fts_tsv.summ_data import HMTorchDataset
# from entryU import ModelU
# from entryO im... |
import os
import shutil
caminho_origem = r"E:\Danilo Gomes\Documents\GitHub\Cursos_de_Python\Curso_de_Python_3_do_Basico_Ao_Avancado_Udemy\aula130\Origem"
caminho_destino = r"E:\Danilo Gomes\Documents\GitHub\Cursos_de_Python\Curso_de_Python_3_do_Basico_Ao_Avancado_Udemy\aula130\Destino"
try:
os.mkdir(caminho_dest... |
from flask import Flask, jsonify, request
import ldap
from getpass import getpass
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity
)
app = Flask(__name__)
# Setup the Flask-JWT-Extended extension
app.config['JWT_SECRET_KEY'] = 'dhsnu3r2788hsnjGDhbjfdio190243ifnc... |
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
n = len(nums)
if n == 0 : return []
arr = []
a = nums[0]
for i in range(len(nums)):
if (i == n-1) or (nums[i] + 1 != nums[i+1]):
if nums[i... |
# Copyright 2011 OpenStack LLC.
# 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 b... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from .. import _utilities, _tables
from ... |
from .model import FNet # noqa
__version__ = "0.0.1"
|
import os
import pytest
import requests_mock
from audiomate import corpus
from audiomate import issuers
from audiomate.corpus import io
from audiomate.corpus.io import mailabs
from tests import resources
from . import reader_test as rt
@pytest.fixture()
def tar_data():
with open(resources.get_resource_path(['s... |
from src.app.db import db
class ClienteModel(db.Model):
__tablename__ = 'clientes'
nome = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(250), primary_key = True)
def __init__(self, nome, email):
self.nome = nome
self.email = email
def __repr__(self):
... |
from mock import MagicMock, patch, call
from pypodio2.transport import _retry, TransportException
from tests.utils import get_client_and_http
@patch('time.sleep')
def retry_helper(tries, delay, backoff, cap, mock_sleep):
"""
Helper function that calls a function with the retry decorator. This
helper retu... |
import jug.jug
import jug.subcommands.execute
from .task_reset import task_reset_at_exit, task_reset
from jug.tests.utils import simple_execute, find_test_jugfile
from jug.options import default_options
from functools import reduce
@task_reset
def test_barrier():
jugfile = find_test_jugfile('wbarrier.py')
sto... |
import re
import ast
import pickle
import sys
import getopt
import astor
import os
import astwalker
from glob import iglob
def normalise(path):
split = os.path.split(path)
base = split[0]
dirname = split[1]
normalised_target_path = os.path.join(base, dirname + "_normalised")
processed_file_path ... |
# -*- coding: cp1253 -*-
from tkinter import *
from time import sleep
var = 0
def create(w, x1, y1):
w.place(x=x1, y=y1)
def erase(w):
w.destroy()
def reset(w):
w.destroy()
start()
def exit(w):
w.destroy()
def callback(event):
print("clicked at", event.x, event.y)
def clicked(event)... |
# Copyright 2017 Become Corp. 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... |
from rockstar import RockStar
ocaml_code = 'print_string "Hello world!\n";;'
rock_it_bro = RockStar(days=400, file_name='hello.ml', code=ocaml_code)
rock_it_bro.make_me_a_rockstar()
|
# coding=utf-8
from flask import request, current_app
from flask_restful import Resource, reqparse
from sqlalchemy.exc import IntegrityError
from werkzeug.exceptions import HTTPException
from application.models import *
from application.utils import db
class ForumListApi(Resource):
def __init__(self):
s... |
# Copyright 2020 AUI, Inc. Washington DC, USA
#
# 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 la... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from mpi4py import MPI
from concurrent.futures import ThreadPoolExecutor
from utils import print_rank
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
""" Here we have classes and functions that allow one to send and process... |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('transmittals', '0004_auto_20151102_1437'),
]
operations = [
migrations.AlterModelOptions(
name='outgoingtransmittal',
options={'ordering': ('document_key',), 'verbos... |
class OPC(object):
"""recieve from app and return plus 1 msg"""
msg = "recieve: %d"
mapping = {
"+": lambda x: x + 1,
"-": lambda x: x - 1,
"%": lambda x: x / 2
}
def __init__(self, op):
self.op = op
def foo(self, x):
return self.mapping[self.op](x)
... |
from nltk.stem import PorterStemmer
porter = PorterStemmer()
|
from __future__ import absolute_import
import logging
from fuzzywuzzy import fuzz
from clims.legacy import utils
import copy
from genologics.entities import Artifact
class RoutingService(object):
def __init__(self, session, commit=True):
self.logger = logging.getLogger(__name__)
self.session = se... |
# source: https://code.oursky.com/tensorflow-svm-image-classifications-engine/
import pickle
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.svm import SVC
from utils.data import process_images, augment_data, flatten_da... |
import numpy as np
import scipy
from scipy.optimize import least_squares
import time
'''
n - nummber of images
X - n*d array -> for all n images d dimensional feature vector
O - Ordered attributes array
S - Similiarity attributes array
A - [O;S] p*n matrix -> p is number of preference pairs (+1,-1 sparse matrix)
C_O -... |
import argparse
import mr.config
import mr.shell as shell
import mr.util.hostconf
class Mercenary:
def __init__(self):
self.args = self.parse_args()
self.config = mr.config.Config('merc').read()
def parse_args(self):
parser = argparse.ArgumentParser()
parser.add_argument('pre... |
import csv
import numpy as np
import matplotlib.pyplot as plt
radar_nis_array = []
laser_nis_array = []
with open('./nis.csv') as csvfile:
reader = csv.reader(csvfile)
for line in reader:
if line[0] is not '':
radar_nis_array.append(line[0])
if line[1] is not '':
laser... |
from __future__ import unicode_literals
__version__ = '2019.09.12.1'
|
from .command import Command # noqa
from .command_register import CommandRegister # noqa
from .exceptions import CommandException # noqa
|
import requests, json
url = 'http://educacao.dadosabertosbr.com/api/cidades/ce'
cidades = requests.get(url).content
cidades = cidades.decode('utf-8')
cidades = json.loads(cidades)
for cidade in cidades:
codigo, nome = cidade.split(':')
print(nome)
|
import torch
import torch.nn.functional as F
from self_supervised.network.mode_latent_model import ModeLatentNetworkWithEncoder
import rlkit.torch.pytorch_util as ptu
def reconstruction_based_rewards(
mode_latent_model: ModeLatentNetworkWithEncoder,
obs_seq: torch.Tensor,
action_seq: torch.Te... |
import cv2 as cv
import numpy as np
from scipy import signal
from math import floor
def HoughCircles(image, minRadius, maxRadius):
circles = cv.HoughCircles(
image,
cv.HOUGH_GRADIENT,
1, 50,
param1=50,
param2=30,
minRadius=minRadius,
maxRadius=maxRadius
)
if (circles is None):
return []
return circ... |
import csv
import os
def read_conll_file(address):
ret = []
line_number = 0
print('Opening file ', address)
with open(address, encoding='UTF-8') as f:
line = f.readline()
while line:
l = line.strip()
if len(l) == 0:
ret.append([]) #... |
#!/usr/bin/env python
"""
Converts an Isophonics dataset into a collection of jams:
http://isophonics.net/datasets
Note that the structure of an Isophonics dataset (Carole King, The Beatles,
etc) is something like the following:
/* Annotations
/attribute
/Artist
/Album # -- may not exist --
... |
"""Script used to train neural parts."""
import argparse
import json
import random
import os
import string
import subprocess
import sys
import numpy as np
import torch
from torch.utils.data import DataLoader
from arguments import add_dataset_parameters
from utils import load_config
from neural_parts.datasets import... |
import uuid
def short_uuid():
return str(uuid.uuid4())[:8]
|
import json
import os
# import uuid
from SMELT.Store import Store, Connection
from datetime import datetime, date
def deserializeJSON(obj):
if "$DATETIME" in obj:
return datetime.fromisoformat(obj["$DATETIME"])
elif "$DATE" in obj:
return date.fromisoformat(obj["$DATE"])
return obj
def s... |
import utils
import numpy as np
import torch
from torch import nn
class ContrastiveSWM(nn.Module):
"""Main module for a Contrastively-trained Structured World Model (C-SWM).
Args:
embedding_dim: Dimensionality of abstract state space.
input_dims: Shape of input observation.
hidden_di... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82806311
# IDEA : TWO POINTERS
class Solution(object):
def numRescueBoats(self, people, limit):
"""
:type people: List[int]
:type limit: int
:rtype: int
"""
people.sort()
res = 0
hi, lo... |
from setuptools import setup, find_packages
setup(
name='cinemaPy',
version='0.1.0',
description='Watch streaming movies',
license='MIT',
install_requires=['requests','BeautifulSoup', 'lxml', 'html.parser' ],
packages=find_packages(),
scripts='moviepy.py'
) |
# -*- coding: utf-8 -*-
exclude_patterns = ['/tests'] |
# -*- coding: UTF-8 -*-
##############################################################################
# #
# Copyright (c) 2007-2010 Bernd Kreuss <prof7bit@gmail.com> #
# ... |
from textattack.constraints.grammaticality.language_models import (
LearningToWriteLanguageModel,
)
from textattack.constraints.overlap import MaxWordsPerturbed
from textattack.constraints.pre_transformation import (
RepeatModification,
StopwordModification,
)
from textattack.constraints.semantics import Wo... |
import numpy as np
from world import World, Route, Hybrid
from .utils import *
class Agent(object):
FOV = (-np.pi/2, np.pi/2)
__latest_agent_id__ = 0
def __init__(self, init_pos=np.zeros(3), init_rot=np.zeros(3), condition=Hybrid(),
live_sky=True, fov=None, rgb=False, visualiser=None, na... |
# pylint: disable=abstract-method
"""
A "safe" Shillelagh dialect.
When this dialect is used only adapters marked as safe and explicitly
listed are loaded.
"""
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy.engine.url import URL
from shillelagh.backends.apsw.dialects.base import APSWDialect
cl... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Author: lea.cgh
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from sklearn.metrics import roc_auc_score
from sklearn.metrics import log_loss
import tensorflow as tf
import n... |
# -*- coding: utf-8 -*-
import json
from django.test import TestCase
from django.test.client import Client
from django.core import management
from django.utils.encoding import smart_text
from tests.models import Simple
class RESTTestCase(TestCase):
def setUp(self):
management.call_command('loaddata',
... |
"""Python SQLite Porter main definitions
"""
import json
import re
class PySqlitePorter:
_DEFAULT_BATCH_INSERT_SIZE = 250
_separator = ';\n'
_statement_regex = re.compile('(?!\s|;|$)(?:[^;"\']*(?:"(?:\\.|[^\\"])*"|\'(?:\\.|[^\\\'])*\')?)*')
def _sql_escape(self, value):
if re.match('[_-]... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseStamped
from styx_msgs.msg import Lane, Waypoint
from scipy.spatial import KDTree
import numpy as np
import math
'''
This node will publish waypoints from the car's current position to some `x` distance ahead.
As ment... |
from django.db import models
# Create your models here.
from author.models import Author
typeChoices = (("P", "Post"), ("F", "Follow"), ("L", "Like"))
class InboxItem(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
type = models.CharField(
max_length=1, choices=typeCho... |
"""Initial revision
Revision ID: 25165517c582
Revises:
Create Date: 2020-01-01 20:14:45.905855
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "25165517c582"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto ge... |
import os
import numpy as np
import pandas as pd
import itertools
import logging
class StartPicker:
def __init__(self, N, n):
self.N = N
self.n = n
self.length = N - n + 1
def get_prob(self, i):
if i < self.n:
return np.sqrt(self.n / (i + 1))
elif i > self... |
import time
import _thread
import logging
from . import api_spotify
from . import bpm_render
prev_title = ""
prev_subtitle = ""
prev_image = ""
epd_lock = _thread.allocate_lock()
thread_counter = 0
def cycle(epd=None):
while True:
current_playback = api_spotify.get_currently_playing()
if curren... |
from ..auth import cookie_authentication
from ..auth import user_db
from ..settings import Settings
from ..db.database import SessionLocal
from fastapi import WebSocket
settings = Settings()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
async def websocket_auth(web... |
from marshmallow import Schema, fields
class GameSchema(Schema):
title = fields.Str(required=True)
description = fields.Str(required=True)
photo = fields.Nested('PhotoSizeSchema', many=True, required=True)
text = fields.Str()
text_entities = fields.Nested('MessageEntitySchema', many=True)
anim... |
import abc
from concurrent.futures import as_completed, Future
from contextlib import contextmanager
from datetime import datetime
from itertools import chain
from typing import (
Optional, Tuple, Callable, Iterable, Type, Dict, Any, List, Mapping,
Iterator, Union, Set
)
import agate
import pytz
from dbt.exce... |
from math import ceil
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.cache import cache_page
from django.utils.timezone import localtime
from database.models import Proxy, PROXY_STATE, PROXY_PROTOCOL, PROXY_CHECK_STATE
proxy_state = dict(PROXY_STATE)
proxy_protoco... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.