text stringlengths 2 999k |
|---|
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2018-present MagicStack Inc. and the EdgeDB 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... |
# coding: utf-8
import copy
from timeit import default_timer as timer
import numpy as np
# Main function
##########
class Pair:
def __init__(self, lhs, rhs, parent):
self.lhs = lhs
self.rhs = rhs
self.parent = parent
def __str__(self):
return "["+str(self.lhs)+","+str(self.r... |
import os
import sys
import json
import yaml
import mkdocs
import logging
from mkdocs.plugins import BasePlugin
from mkdocs.utils import warning_filter
from jinja2 import Template
from pathlib import Path
from itertools import chain
log = logging.getLogger(__name__)
log.addFilter(warning_filter)
CONFIG_KEYS = ["site... |
from flask import Flask
from flask_graphql import GraphQLView
from models import db_session
from schema import schema, Department
app = Flask(__name__)
app.debug = True
@app.route('/')
def index():
return '<p> Hello World!</p>'
app.add_url_rule(
'/graphql',
view_func=GraphQLView.as_view(
'graph... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###########################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# Copyright (c) 2005-2010 Thierry Benita - atReal <contact@atreal.net>
# All Rights Reserved.
#
# This software is subject to the prov... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
from analyze_perf import group_perf_by_events, filter_events_after_timestamp, \
classify_events_by_stages, get_percentage
from profiling_stages import draw_profiling_plot
x_labels = ['OPQ16,IVF262144\nnprobe=1', \
'OPQ16,IVF26214... |
def concat_multiples(num, multiples):
return int("".join([str(num*multiple) for multiple in range(1,multiples+1)]))
def is_pandigital(num):
return sorted([int(digit) for digit in str(num)]) == list(range(1,10))
def solve_p038():
# retrieve only 9 digit concatinations of multiples where n = (1,2,..n)
... |
import models
import json
import re
import constants.userConstants as UserConstants
from enums import UserEnums
from databaseService.bookDatabaseService import BookDatabaseService
def validate_and_convert_new_user_request_object(aa: dict, bb: models.User):
for field in UserConstants.USER_MANDATORY_FIELDS:
... |
# -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j F Y'
TIME_FORMAT = 'G:i'
DATETI... |
from car_ctrl import servo
import time
#max angle turns right
#0 turns left
def test_servo_rotation():
s = servo()
print(vars(s))
print("max_angle: " +str(s.max_angle))
print("slope: " +str(s.slope))
for i in range(0,3):
s.steer(s.max_angle)
print("turning left")
time.sleep(0... |
import os
class Config:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = True
SECRET_KEY = os.environ.get('SECRET_KEY')
UPLOADED_PHOTOS_DEST = 'app/static/photos'
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 450
MAIL_USE_TLS = False
MAIL_USE_SSL = ... |
# Dependencies
from splinter import Browser
from bs4 import BeautifulSoup
from webdriver_manager.chrome import ChromeDriverManager
import time
import pandas as pd
from pprint import pprint
from urllib.parse import urlsplit
import pymongo
# Initialize PyMongo to work with MongoDBs
conn = 'mongodb://localhost:27017'
c... |
from pydriller import RepositoryMining
import iocsv
import csv
repos = iocsv.read_csv_repos_fil("data_filtered.csv")
out = open('project_bot.csv', 'w')
w_out = csv.writer(out)
for commit in RepositoryMining(path_to_repo=repos, only_modifications_with_file_types= ['.yml']).traverse_commits():
files = []
for m... |
from fastapi import APIRouter
from gladia_api_utils.submodules import TaskRouter
router = APIRouter()
inputs = [
{
"type": "text",
"name": "text",
"default": "Лорем ипсум долор сит амет",
"tooltip": "Insert the text to transliterate here",
},
{
"type": "text",
... |
"""
flask_flatpages_pandoc
~~~~~~~~~~~~~~~~~~~~~~
Flask-FlatPages-Pandoc is an HTML renderer for Flask-FlatPages that uses
pandoc as backend.
:copyright: (c) 2014 Fabian Hirschmann <fabian@hirschmann.email>
:license: MIT, see LICENSE.txt for more details.
With some changes by @apas:
- Invoke pandoc via pypandoc i... |
import os
from WMCore.Configuration import Configuration
from CRABClient.UserUtilities import config, getUsernameFromCRIC
config = Configuration()
config.section_("General")
config.General.requestName = '2018_ST_tW'
config.General.transferOutputs = True
config.General.transferLogs = True
config.section_("JobType")
co... |
from .GogsClient import GogsClient
from js9 import j
JSConfigBaseFactory = j.tools.configmanager.base_class_configs
class GogsFactory(JSConfigBaseFactory):
def __init__(self):
self.__jslocation__ = "j.clients.gogs"
self.__imports__ = "requests,psycopg2"
JSConfigBaseFactory.__init__(self,... |
import os
import time
from multiprocessing.dummy import Pool
import pytest
from helpers.cluster import ClickHouseCluster
from helpers.test_tools import assert_eq_with_retry
cluster = ClickHouseCluster(__file__)
node1 = cluster.add_instance("node1", main_configs=["configs/wide_parts_only.xml"])
@pytest.fixture(scop... |
from common.methods import set_progress
from resourcehandlers.aws.models import AWSHandler
def run(job, resource, **kwargs):
set_progress("Connecting to AWS s3 cloud")
aws = AWSHandler.objects.get(id=resource.aws_rh_id)
wrapper = aws.get_api_wrapper()
set_progress("This resource belongs to {}".format... |
#File: tank.py
#Author: Mariana Avalos
#Date: 22/02/2019
#Description: Python code that makes a 3D tank
import maya.cmds as c
import math as math
# 8 tires
tireTranslation = [3, -3]
tireRadius = 1.25
for j in range(len(tireTranslation)):
for i in range(4):
name = 'c' + str(i + (j * 4) + 1)
... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: ... |
import sys
import utils
import torch
from datasets import VisualDialogDataset
import torchvision.transforms as transforms
def build_dataset(mode, args, shared_dictionary=None, with_options=True):
normalize = transforms.Normalize(mean=[0.4711, 0.4475, 0.4080], std=[0.1223, 0.1221, 0.1450]) #visdial
transf... |
import os
import json
import string
import inspect
import sublime
from .miscellaneous_utils import command_kind_type
kind_mapping = {
"window": command_kind_type("window"),
"text": command_kind_type("text"),
"application": command_kind_type("application"),
"find": command_kind_type("find")
}
def co... |
# ⋆ ˚。⋆୨୧˚ v a p o r w a v e b o t ˚୨୧⋆。˚ ⋆
# Simple Telegram bot that converts standard unicode chars to full-width ones
# Unicode full width characters, means that all characters has the size of a chinese character.
# Full width characters goes from 0xFF1 to 0xFFE5
# Japanese hirigana char... |
import torch
from torch.autograd import Variable
from torchvision import models
import cv2
import sys
import numpy as np
import os
import math
import torch.nn.functional as F
idx_to_class = {0 : 'aeroplane', 1 : 'bicycle', 2 : 'bird', 3 : 'boat', 4 : 'bottle', 5 : 'bus', 6 : 'car', 7 : 'cat',
8 : 'chai... |
import pytest
from wecs.core import Entity, System, Component, World
from wecs.core import and_filter
# Absolute basics
@pytest.fixture
def world():
return World()
@pytest.fixture
def entity(world):
return world.create_entity()
# Null stuff
@Component()
class NullComponent:
pass
@pytest.fixture
d... |
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""Parent ship class for Blast."""
def __init__(self, blast_settings, screen):
"""Init ship and starting position."""
super(Ship, self).__init__()
self.screen = screen
self.blast_settings = blast_setting... |
n1 = int(input('qual sua idade ? '))
n2 = int(input('qual sua idade ? '))
n3 = int(input('qual sua idade ? '))
n4 = int(input('qual sua idade ? '))
n5 = int(input('qual sua idade ? '))
n6 = int(input('qual sua idade ? '))
n7 = int(input('qual sua idade ? '))
if n1 > n2,n3,n4,n5,n6,n7
#tia tbm não entendi |
__version__ = '3.0-dev'
from .facets import Facet, GlobalTermsFacet, RangeFilter, TermsFacet, YearHistogram
from .mapping import (
DEFAULT_ANALYZER, Indexable, ModelIndex, RawMultiString, RawString, build_mapping, deep_field_factory,
document_field, document_from_model)
from .registry import app_documents, doc... |
import json
from Qt import QtGui
from Qt import QtWidgets
def set_palette_from_dict(dct):
"""Set palette to current QApplication based on given dictionary"""
groups = ["Disabled", "Active", "Inactive", "Normal"]
roles = [
"AlternateBase",
"Background",
"Base",
"Button",
... |
#
# 2020 ExpertSystem
#
'''Script for generating predictions for the coinform250 dataset
using the acred predictor
See https://github.com/co-inform/Datasets
See also scripts/fetch-data.sh, which should download the input json file
and place it in the `data/evaluation/` folder.
'''
import argparse
import time
import ... |
#!/usr/bin/env python
import argparse
from LhcVaspTools.BasicUtils import readDataFromJson
from LhcVaspTools.OamExts import EnergyBandsWithOam
def parseArgv() -> argparse.Namespace:
parser: argparse.ArgumentParser = argparse.ArgumentParser(
description="This script is used to plot bands")
parser.add_... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from typing import Any, Callable, Dict, Iterable, List, Mapping, Tuple, TypeVar
from mock import patch, MagicMock
from django.http import HttpResponse
from django.test import TestCase, override_settings
from zerver.l... |
from .sentence_dataloader import * |
import time
from inky_fork import InkyPHAT, InkyWHAT
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from datetime import datetime
from time import gmtime, strftime
inky_display = InkyWHAT("black_fast")
font = ImageFont.truetype("Nunito-ExtraLight.ttf", 130)
i = 10
while True:
image = I... |
while True:
n = int(input("Quer ver a tabuada de qual valor? "))
if n < 0:
print('-=' * 19)
print('PROGRAMA TABUADA ENCERRADO, VOLTE SEMPRE')
break
print('-=' * 19)
for c in range(1, 11):
print(f'{n} x {c:2} = {n*c:2}') |
#!/usr/bin/python
#
# Copyright 2016 Red Hat | Ansible
# 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
DOCUMENTATION = '''
module: docker_network
short_description: Manage Docker network... |
#!/uwsr/bin/env python3
import asyncio
async def main():
print('hello')
await asyncio.sleep(1)
print('world')
if __name__=="__main__":
asyncio.run(main())
|
"""Translation constants."""
import pathlib
PROJECT_ID = "130246255a974bd3b5e8a1.51616605"
DOCKER_IMAGE = "b8329d20280263cad04f65b843e54b9e8e6909a348a678eac959550b5ef5c75f"
INTEGRATIONS_DIR = pathlib.Path("homeassistant/components")
|
import os
from flask import Flask, send_from_directory
app = Flask(__name__, static_folder='client/build')
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
if(path == ""):
return send_from_directory('client/build', 'index.html')
else:
if(os.path.exists("client... |
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pyteaser import SummarizeUrl
from scipy import spatial
import re, math
from collections import Counter
#http://stackoverflow.com/questions/15173225/how-to-calculate-cosine-similarity-given-2-sentence-strings-python
WORD = re.compile(r'\w+')
def get_cosine(vec1, vec2)... |
# Copyright 2013 Red Hat, 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... |
# Copyright (C) 2020 THL A29 Limited, a Tencent company.
# All rights reserved.
# Licensed under the BSD 3-Clause 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/BSD-3-Clause
# Unless required by appl... |
#!/usr/bin/env python
# Copyright (c) 2014, Palo Alto Networks
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" A... |
import random
import string
from django.conf import settings
SHORTCODE_MIN = getattr(settings, "SHORTCODE_MIN", 5)
def code_generator(size=SHORTCODE_MIN, chars=string.ascii_lowercase + string.digits + string.ascii_uppercase):
return ''.join(random.choice(chars) for _ in range(size))
def create_shortcode(instance,... |
preprocess_output = r"D:\Codes\Wos_IE\result\content_dic.json"
abbreviate_dictionary_output = r"D:\Codes\Wos_IE\result\abbreviate_words.json" |
# coding: utf-8
from itertools import combinations
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.cross_validation import KFold
data = load_iris()
for k, v in data.items():
print k
print v, '\n'
featureNames = data['feature_names']
features = data['data']
targetNames = ... |
"""
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 in wri... |
"""empty message
Revision ID: ee248674f637
Revises: ebf728dc4d0d
Create Date: 2017-05-31 15:07:32.715000
"""
# revision identifiers, used by Alembic.
revision = 'ee248674f637'
down_revision = 'ebf728dc4d0d'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic ... |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2020, empress development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
# Copyright 2017 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 numpy as np
from tqdm import tqdm, trange
from script.data_handler.Base.BaseDataset import BaseDataset
from script.model.sklearn_like_model.BaseModel import BaseModel
from script.model.sklearn_like_model.Mixin import UnsupervisedMetricCallback
from script.model.sklearn_like_model.NetModule.BaseNetModule imp... |
"""
# Train a new model starting from pre-trained weights
python3 training.py --dataset=/path/to/dataset --weight=/path/to/pretrained/weight.h5
# Resume training a model
python3 training.py --dataset=/path/to/dataset --continue_train=/path/to/latest/weights.h5
"""
import logging
import warnings
import ... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import time
from collections import defaultdict
import requests
from six import iteritems, itervalues
from six.moves.urllib.parse import urljoin, urlparse
from datadog_checks.base import AgentCheck, is_affirma... |
" Userman: UI modules. "
import tornado.web
from . import constants
class Icon(tornado.web.UIModule):
"HTML for an icon, optionally labelled with a title."
template = """<img src="{url}" class="icon" alt="{alt}" title="{title}">"""
def render(self, name, title=None, label=False):
if not isinst... |
NLOT = CouplingOrder(name = 'NLOT', # ggS triangle nlo couplings
expansion_order = 1,
hierarchy = 2)
NLOTHL = CouplingOrder(name = 'NLOTHL', # ggS triangle nlo couplings for HL
expansion_order = 1,
hierarchy = 2)
NLOTHH = CouplingOrder(n... |
# 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... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libxevie(AutotoolsPackage, XorgPackage):
"""Xevie - X Event Interception Extension (XEvIE)... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Ingredient
from recipe.serializers import IngredientSerializer
INGREDIENTS_URL = reverse('recipe:ingred... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#=============================================================================
# FileName: lickeeper.py
# Desc:
# Author: Jeyrce.Lu
# Email: jianxin.lu@woqutech.com
# HomePage: www.woqutech.com
# Version: 0.0.1
# LastChange: 2021/1/13 上午11:18
# History:
#==============... |
from twisted.internet.protocol import Protocol
from gandyloo import parse
class MinesweeperClient(Protocol):
'''Represents a connection to a server using twisted's Protocol framework.
Created with an event sink, where parsed events (subclasses of
gandyloo.message.Response) are fired. Sink should have a met... |
import pytest
from datagears.core.network import Network
@pytest.fixture
def myfeature() -> Network:
"""Testing fixture for a feature."""
from datagears.core.network import Network
from datagears.features.dummy import my_out
network = Network("my-network", outputs=[my_out])
return network
@pyt... |
from generators.neural_rendering import NeuralRenderer
import math
def next_upsample_step(curriculum, current_step):
# Return the epoch when it will next upsample
current_metadata = extract_metadata(curriculum, current_step)
current_size = current_metadata['img_size']
for curriculum_step in sorted([cs ... |
from datetime import datetime, timedelta
import trading_calendars
ANNUAL_DAYS = 240
# Get public holidays data from Shanghai Stock Exchange
cn_calendar = trading_calendars.get_calendar('XSHG')
holidays = [x.to_pydatetime() for x in cn_calendar.precomputed_holidays]
# Filter future public holidays
start = datetime.t... |
#!/usr/bin/env python3
import redis
import argparse
import hashlib
from getpass import getpass
r = redis.StrictRedis(host="localhost", port=6379)
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--add', action='store_true', help='Adds a service')
group... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
import numpy as np
import sys
import os
import time
from cntk import Trainer, Axis,... |
from django.views.generic import TemplateView
class HomeRequestView(TemplateView):
http_method_names = ['get', ]
template_name = "home.html"
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Atenção: usado no notebook da aula.
Não precisa ser usado diretamente
"""
print("Este script não deve ser executado diretamente")
from ipywidgets import widgets, interact, interactive, FloatSlider, IntSlider
import numpy as np
import cv2
def make_widgets_mat... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 11:12:44 2020
Files for this layout:
ftp://ftpe.rrc.texas.gov/sholed
ftp://ftpe.rrc.texas.gov/sholed/olf001l.ebc.gz
ftp://ftpe.rrc.texas.gov/sholed/olf003l.ebc.gz
ftp://ftpe.rrc.texas.gov/sholed/olf004l.ebc.gz
ftp://ftpe.rrc.texas.go... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import glob
import pickle
# read in all the images in the calibration folder
calib_images = glob.glob(".\camera_cal\*.jpg")
#define chess board parameters:
nx = 9
ny = 6
# Arrays to store image point and opbject points
imgpoints = []
objpoints = []
def g... |
# coding: utf-8
"""
.. module: scieloopds
:synopsis: WSGI Application to provide SciELO Books in OPDS protocol.
.. moduleauthor:: Allison Vollmann <allisonvoll@gmail.com>
Example configuration (aditional parameters):
.. note::
[app:main]
...
mongo_uri = mongodb://localhost:27017/scieloopds
scielo_uri =... |
# -*- coding: utf-8 -*-
import pandas as pd
from futu.common import RspHandlerBase
from futu.quote.quote_query import *
class StockQuoteHandlerBase(RspHandlerBase):
"""
异步处理推送的订阅股票的报价。
.. code:: python
class StockQuoteTest(StockQuoteHandlerBase):
def on_recv_rsp(self, rsp_str):
... |
from datetime import datetime
from io import StringIO
from unittest.mock import patch
from django.conf import settings
from django.core import mail
from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone
from main import models
from main.management.commands i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Partially based on AboutMessagePassing in the Ruby Koans
#
from runner.koan import *
class AboutAttributeAccess(Koan):
class TypicalObject:
pass
def test_calling_undefined_functions_normally_results_in_errors(self):
typical = self.TypicalOb... |
"""Here we import the different task submodules/ collections"""
from invoke import Collection, task
from tasks import docker, package, sphinx, test # pylint: disable=import-self
# pylint: disable=invalid-name
# as invoke only recognizes lower case
namespace = Collection()
namespace.add_collection(test)
namespace.add... |
from pygame import Rect
# noinspection PyPackageRequirements
from OpenGL import GL
from albow.openGL.GLViewport import GLViewport
class GLOrtho(GLViewport):
"""
GLOrtho provides an OpenGL drawing area with an orthographic projection.
Using a GLOrtho widget is the same as using a GLViewport, except tha... |
import pytest
from mock import MagicMock, patch, PropertyMock
from pontoon.tags.models import Tag
from pontoon.tags.utils import (
TagsLatestTranslationsTool, TagsResourcesTool,
TagsStatsTool, TagsTool, TagTool)
from pontoon.tags.utils.base import Clonable
def test_util_tags_tool():
# test tags tool in... |
# Generated by Django 3.2.6 on 2021-08-26 16:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
from __future__ import annotations
import os
import itertools
from typing import Any, Optional, TypeVar
import pygame
from gupb.controller import keyboard
from gupb.model import characters
from gupb.model import effects
from gupb.model import games
from gupb.model import tiles
from gupb.model import weapons
pygame.i... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2019 all rights reserved
#
# externals
import collections
# superclass
from .AbstractMetaclass import AbstractMetaclass
# class declaration
class AttributeClassifier(AbstractMetaclass):
"""
A base metaclass that enables attribute categ... |
#!/usr/bin/env python
import sys
import string
from sklearn.feature_extraction import text
stops = set(text.ENGLISH_STOP_WORDS)
# get all lines from stdin
for line in sys.stdin:
# remove leading and trailing whitespace, lower case letters, remove punctuation
line = line.strip().lower().translate(None, string.p... |
from ..base import MultiGridEnv
from .empty import EmptyMultiGrid, EmptyColorMultiGrid
from .doorkey import DoorKeyEnv
from .cluttered import ClutteredMultiGrid
from .goalcycle import ClutteredGoalCycleEnv
from .viz_test import VisibilityTestEnv
from .hallways import HallWaysMultiGrid
from .comm_game import Communicat... |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Tests the framework events.
:author: Thomas Calmant
"""
# Standard library
try:
import unittest2 as unittest
except ImportError:
import unittest
# Pelix
from pelix.framework import FrameworkFactory, Bundle, BundleException, \
BundleContext, Bundle... |
"""Core tests."""
from typing import Any
import pytest
from borsh_construct import (
F32,
F64,
I8,
I16,
I32,
I64,
I128,
U8,
U16,
U32,
U64,
U128,
Bool,
Vec,
CStruct,
TupleStruct,
Enum,
String,
Option,
HashMap,
HashSet,
Bytes,
)
from... |
import sys
sys.path.append("../..")
from api.control.PID import PID
from api.control.sensor import sensor
from api.control.robot import robot
import posix_ipc as ipc
import time
import threading
import math
import numpy as np
graphq = ipc.MessageQueue('/graphQueue', ipc.O_CREAT)
mq = ipc.MessageQueue('/keyQueue', ipc... |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pickle
import math
from dynsimf.models.Model import Model
from dynsimf.models.Model import ModelConfiguration
from dynsimf.models.components.Memory import MemoryConfiguration
from dynsimf.models.components.Memory import MemoryConfiguration... |
from functools import partial
from pyais.exceptions import UnknownMessageException
import typing
import bitarray
from pyais.constants import (
NavigationStatus,
ManeuverIndicator,
TransmitMode,
EpfdType,
ShipType,
StationType,
StationIntervals,
NavAid
)
from pyais.util import get_int, ... |
""" Module for controlling Thorlabs motorized pollarization paddles """
import ctypes
from ctypes import Structure
import time
from pylabnet.utils.logging.logger import LogHandler
#from comtypes.typeinfo import SAFEARRAYABOUND
#enum FT_Status
FT_OK = ctypes.c_short(0x00)
FT_InvalidHandle = ctypes.c_short(0x0)
FT_Dev... |
from abc import ABCMeta, abstractmethod
from ..utils.activations import *
class NetworkBase(metaclass=ABCMeta):
def __init__(self, sizes, activation, last_layer, **kwargs):
self.sizes = sizes
self.num_layers = len(sizes)
if activation.lower() == "sigmoid":
self.activation = Sigm... |
"""prawtools setup.py."""
import re
from codecs import open
from os import path
from setuptools import setup
PACKAGE_NAME = "prawtools"
HERE = path.abspath(path.dirname(__file__))
with open(path.join(HERE, "README.md"), encoding="utf-8") as fp:
README = fp.read()
with open(path.join(HERE, PACKAGE_NAME, "__init__... |
#-*- coding: utf-8 -*-
"""
Created on Mon Dec 10 12:48:22 2018
@author: Aite Zhao
"""
from __future__ import print_function
#import random
import tensorflow as tf
#from tensorflow.python.ops import rnn, rnn_cell
import numpy as np
#import plot_confusion_matrix
import rnn_cell_GRU as rnn_cell
import rnn
from sklearn i... |
import datetime
import shutil
import services.inventory
import workflow
import pandas as pd
import os
import file_system
import file_system.images as images
import json
from file_system.file_system_object import FileSystemObject
from services import inventory, library
from tabulate import tabulate
import cv2
TEMP_FOL... |
from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import thread_slice
expected_verilog = """
module test;
reg CLK;
reg RST;
wire [8-1:0] LED;
blinkled
uut
(
.CLK(CLK),
.RST(RST),
.LED(LED)
);
initial begin
$dumpfile("uut.vcd");
$dumpv... |
import keras
import tensorflow as tf
import keras.backend.tensorflow_backend as K
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
# config.gpu_options.per_process_gpu_memory_fraction = 0.9
sess = tf.Session(config=config)
K.set_session(sess)
import os
import sys
sys.path.insert(0, '../')
from models.... |
import sys
try:
from django.conf import settings
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="normal_admin.urls",
INSTALLED_APPS=[
... |
from social_core.backends.azuread_tenant import AzureADTenantOAuth2
from social_core.backends.azuread_b2c import AzureADB2COAuth2
from tethys_services.backends.multi_tenant_mixin import MultiTenantMixin
class AzureADTenantOAuth2MultiTenant(MultiTenantMixin, AzureADTenantOAuth2):
pass
class AzureADB2COAuth2Mult... |
import unittest
import sys
sys.path.append('bin')
from umdinst import wrap
class TestIsSourceFile(unittest.TestCase):
def testHasExtension(self):
self.failUnless(wrap.hasextension('foo.c'))
self.failIf(wrap.hasextension('bar'))
def testIsSourceFile(self):
self.failUnless(wrap... |
import numpy as np
import matplotlib.pyplot as plt
"""
As in evAccum.py, the direct simulation for a single agent. Here the code is modified to stop when the agent hits a
boundary and also tracks where the LLR paths are. This allows us to output an array of exit times and compute the
survival probability.
"""
# Parame... |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# Copyright (c) 2008-2021 pyglet contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the follo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.