content stringlengths 5 1.05M |
|---|
from typing import List, Tuple
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
# Auxiliary LDA Functions
def print_topics(model, vectorizer, top_n: int=10)-> List:
"""Print the top n words found by each topic model.
Args:
mo... |
"""MIT License
Copyright (c) 2021 Jacopo Schiavon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish... |
#
# 02_led_wiringpi_softpwm.py
#
import wiringpi
LED_PORT = 18
PWM_RANGE = 100
# Software PWM
wiringpi.wiringPiSetupGpio()
wiringpi.pinMode(LED_PORT, wiringpi.GPIO.PWM_OUTPUT)
wiringpi.softPwmCreate(LED_PORT, 0, PWM_RANGE)
# LEDを2秒間点灯する
for duty in (5, 20, 50, 80, 100):
print(duty)
wiringpi.softPwmWrite(LED... |
#!/usr/bin/ipython
import os, pdb
import argparse
from data_loader import get_loader
from torch.backends import cudnn
import config as cfg
def main(config):
# For fast training
cudnn.benchmark = True
# Create directories if not exist
if not os.path.exists(config.log_path):
os.makedirs(config.... |
# Lint as: python3
"""Generate the RSS feeds."""
import sys
import json
import logging
import datetime
import os
from feedgen.feed import FeedGenerator
from compile import augment_post, render_post
logging.basicConfig(level=logging.DEBUG)
ROOT = os.path.dirname(os.path.realpath(__file__))
RSS_FILENAME = "rss.xml"
BL... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'read_excel_main_code.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import xlrd
import xlwt
import xlsxwriter
from xlutils.c... |
import os
import sys
import time
import imp
import runpy
import traceback
import argparse
import logging
from multiprocessing import Process
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
def run_module(module, function=None):
if function is not None: # run it as a mo... |
# Generated by Django 2.2.1 on 2019-05-19 11:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0006_projectmember'),
]
operations = [
migrations.AlterField(
model_name='projectmember',
name='role',
... |
import ssl
import socket
import asyncio
import logging
import collections
from asyncio import sslproto
from email._header_value_parser import get_addr_spec, get_angle_addr
from email.errors import HeaderParseError
from public import public
from warnings import warn
__version__ = '1.1'
__ident__ = 'Python SMTP {}'.fo... |
"""This module manage the default settings for eo_utils module"""
import os
import sys
# Package location
EO_PACKAGE_BASE = os.path.abspath(os.path.join(__file__, '..', '..', '..', '..', '..'))
DEFAULT_CALIB_FILE = os.path.join(EO_PACKAGE_BASE, 'templates', 'calib_flavor.yaml')
# SITE DEPENDENT STUFF
SITE = os.en... |
import os
import cPickle
import random
import numpy as np
import scipy.sparse as sp
from w2v import load_word2vec
import theano
import theano.tensor as T
import lasagne
class CNN_model(object):
def __init__(self, args):
# Model Hyperparameters
self.sequence_length = args.sequence_length
se... |
import os
import shutil
from cStringIO import StringIO
import boto.s3.connection
import boto.s3.key
import config
class Storage(object):
""" Storage is organized as follow:
$ROOT/images/<image_id>/json
$ROOT/images/<image_id>/layer
$ROOT/repositories/<namespace>/<repository_name>/<tag_name>
""... |
import abc
from six import with_metaclass
class Container(with_metaclass(abc.ABCMeta, object)):
@classmethod
def type_hierarchy(cls):
return cls.__mro__
class Data(Container):
@abc.abstractproperty
def data(self):
'''
The data that is held by this Container
'''
... |
import torch
import torch.nn as nn
from src.config import WrapperConfig
class PromptEncoder(nn.Module):
def __init__(self,
config: WrapperConfig,
prompt_length: int,
embeddings: nn.Embedding):
super(PromptEncoder, self).__init__()
self.config = c... |
"""df[{}] = df[{}].astype({})"""
def run(dfs: dict, settings: dict) -> dict:
"""df[{}] = df[{}].astype({})"""
if 'columns' not in settings:
raise Exception('Missing columns param')
dfs[settings['df']] = dfs[settings['df']].astype(settings['columns'])
return dfs
|
import unittest
from abpytools import ChainCollection
from abpytools.features.composition import *
class SequenceCompositionTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.chain = ChainCollection.load_from_file(path='./tests/Data/chain_collection_1_light.json')
cls.chain.load()... |
from django.contrib import admin
from rules.models import TypeRule, Rule
admin.site.register(TypeRule)
admin.site.register(Rule)
|
import sys
input = sys.stdin.readline
x, y, z = map(int, input().split())
for i in range(1, x):
if y * i + z * (i + 1) > x:
print(i - 1)
exit()
|
from mighty.applications.shop.models.items.discount import Discount
from mighty.applications.shop.models.items.service import Service
from mighty.applications.shop.models.items.item import Item
__all__ = (
Discount,
Service,
Item,
) |
# -*- coding: utf-8 -*-
"""
Cryptide NSFW Cog
~~~~~~~~~~~~~~~~~
This Allows NSFW Commands That Need/Use Cog Functions To Be Used As An Extension.
:copyright: (c) 2021 Trenton "Kawasaki" G
:terms: No Public Use
:visibilty: Private Cog
"""
#Discord
import discord
from discord.ext import commands
#... |
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
Callable,
Iterable,
List,
Optional,
Union,
)
from warnings import warn
from sanic.constants import HTTP_METHODS
from sanic.exceptions import InvalidUsage
if TYPE_CHECKING:
from sanic import Sanic
from san... |
from benchmark import *
import oneflow_benchmark
from flowvision.models.poolformer import poolformer_s12
from flowvision.models.poolformer import poolformer_s24
from flowvision.models.poolformer import poolformer_s36
from flowvision.models.poolformer import poolformer_m36
from flowvision.models.poolformer import poolfo... |
# -*- coding: utf-8 -*-
"""
Data models for the Drycc Manager API.
"""
import logging
import uuid
from django.db import models
logger = logging.getLogger(__name__)
class AuditedModel(models.Model):
"""Add created and updated fields to a model."""
created = models.DateTimeField(auto_now_add=True)
updat... |
from typing import NamedTuple
class Material(NamedTuple):
temp_coeff: float
rho_0: float
@property
def conductivity_0(self) -> float:
"""The conductivity of the material.
Returns:
float: The conductivity of the material.
"""
return 1 / self.rho_0
ALUMINI... |
# This file contains all the global variables that can be shared with different functions written in different files
current_tab = 0
progressbar_maximum = 0
progressbar_value = 0
progress_value = 0
progressbarlabel_text = None
progress_text = ''
trainingDataNumInstances = None
trainingDataNumClasses = None
trainingDat... |
# -*- coding: utf-8 -*-
# Part of BrowseInfo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
# classes under cofigration menu of laboratry
class medical_test_type(models.Model):
_name = 'medical.test_type'
name = fields.Char('Name', required = True)
... |
"""
Main server file. Contains the HTTP request handlers to
access and create shortened URLs.
"""
# Library imports.
from datetime import datetime
from flask import abort, Flask, jsonify, make_response, redirect, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import exc
from werkzeug.exceptions import... |
# References:
# - Original model: https://google.github.io/mediapipe/solutions/face_detection.html
# - Pumpkin image: https://pixabay.com/photos/pumpkin-fruit-orange-fall-2805140/
import cv2
import mediapipe as mp
import numpy as np
from utils.pumpkin_face_utils import read_pumpkin_image, draw_pumpkins
show_webcam ... |
#coding:utf-8
#
# id: bugs.core_6266
# title: Deleting records from MON$ATTACHMENTS using ORDER BY clause doesn't close the corresponding attachments
# decription:
# Old title: Don't close attach while deleting record from MON$ATTACHMENTS using ORDER BY clause.
# ... |
from graphql import GraphQLSchema, GraphQLResolveInfo
import frappe
def bind(schema: GraphQLSchema):
schema.mutation_type.fields["deleteDoc"].resolve = delete_doc_resolver
def delete_doc_resolver(obj, info: GraphQLResolveInfo, **kwargs):
doctype = kwargs.get("doctype")
name = kwargs.get("name")
doc... |
from bson.objectid import ObjectId
from marshmallow import Schema, fields, post_load
import database
from datetime import datetime
class Hardware():
def __init__(self, name = "", capacity = 0, unitPrice = 0.0, unitsUsed = 0):
self.name = name
self.capacity = capacity
self.unitPrice = unitP... |
# coding: utf-8
from collections import defaultdict
import factors as fs
class NthNumbersDistribution(object):
"""
TODO: memoize, persist
"""
def __init__(self, n):
"""
..note:: does not include the number n
"""
self.ffs = [fs.factor(x) for x in xrange(n)]
def max_... |
import fastai.optimizer as opt
from functools import partial
def get_optimizer(run_params):
# Scheduling
# FixMatch is highly influenced by the Optimizer and its parameters
# TODO: Study which parameters are best for this use-case
if run_params["SSL"] == run_params["SSL_FIX_MATCH"]:
# sched = ... |
import math as m
import measure as ms
Ui = [ [5.864, 5.409, 4.958, 4.528, 4.078, 3.620, 3.206, 2.802, 2.424, 2.081, 1.760, 1.432, 1.172, 0.911, 0.690, 0.488, 0.332, 0.200, 0.095, 0.028],
[6.060, 5.630, 5.183, 4.731, 4.273, 3.831, 3.389, 2.974, 2.575, 2.200, 1.869, 1.546, 1.234, 0.976, 0.735, 0.513, 0.329, 0.186... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
class DBConnect:
'''
A class for managing dbconnection
'''
def __init__(self, **data):
data.setdefault('dbhost', '')
data.setdefault('dbport', '')
data.setdefault('dbuser', '')
data.setdefault('dbpass', '')
data.se... |
from loguru import logger
import functools
def __msg_formatter(error_msg, arg_tuple, arg_name):
if (len(arg_tuple) > 0):
error_msg += "\n" + arg_name + ":{}".format(arg_tuple)
return error_msg
def log_wrapper(log_start: bool = True, log_end: bool = True, log_exception: bool = True, throw_exception: ... |
import pathlib
import torch
import numpy as np
project_root = pathlib.Path(__file__).resolve().parents[2]
__all__ = ['project_root'] |
# -*- coding: utf-8 -*-
"""
Created on May 20 2021
@author: Prosenjit
A linear slider to graphically enter data
TODO: Popup dialog
"""
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, pyqtSignal
from typing import Union
from math import sqrt
from .display_config import ICDisplayConfig
from .b... |
import asyncio
import itertools
import sys
def countdown(n=1) -> str:
print(n)
pass
async def spin(msg):
write, flush = sys.stdout.write, sys.stdout.flush
for char in itertools.cycle('|/-\\'):
status = char + ' ' + msg
write(status)
flush()
write('\x08' * len(status))... |
# Copyright (c) Facebook, Inc. and its affiliates.
import colorsys
import numpy as np
from enum import Enum, unique
import cv2
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as mplc
import matplotlib.figure as mplfigure
import pycocotools.mask as mask_util
from matplotlib.backends.bac... |
import sys
from time import sleep
import random
class colors:
OKBLUE = '\033[94m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
CBLACK = '\33[30m'
CRED = '\33[31m'
CGREEN = '\33[32m'
CYELLOW = '\33[33m'
CBLUE = '\33[34m'
... |
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2020 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... |
from .category import CategoryViewSet
from .supplier import SupplierViewSet
from .product import ProductViewSet
from .cart_item import CartItemViewSet |
from sympy import (
Abs,
And,
Derivative,
Dummy,
Eq,
Float,
Function,
Gt,
I,
Integral,
LambertW,
Lt,
Matrix,
Or,
Poly,
Q,
Rational,
S,
Symbol,
Ne,
Wild,
acos,
asin,
atan,
atanh,
cos,
cosh,
diff,
erf,
... |
import datetime
import sqlalchemy
from .db_session import SqlAlchemyBase
from sqlalchemy_serializer import SerializerMixin
class Group(SqlAlchemyBase, SerializerMixin):
__tablename__ = 'groups'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
name = sqlalchemy.Column(sqlalchemy.String)
sc... |
import pandas as pd
from pathlib import Path
from datetime import datetime as dt
from datetime import date as date
from collections import defaultdict
from utils import patient_default_dict
import json
import os
PATH_PATIENTS = Path("data")
# Patient Class is more like a interface between a dataframe storing the pati... |
# -*- coding: utf-8 -*-
"""Class representing a string entry in a bibtex file."""
from bibpy.entry.base import BaseEntry
class String(BaseEntry):
"""Represents a string entry in a bibtex file."""
def __init__(self, variable, value):
"""Create an entry with a variable name and a value."""
se... |
import unittest
import numpy as np
import tensorflow as tf
import GPflow
import convgp.svsumgp as sumgp
GPflow.settings.numerics.float_type = tf.float64
class TestEquivalence(unittest.TestCase):
def test_mf_full_equivalence(self):
# Setup dataset
X = np.random.rand(100, 1) * 6
Y = 0.6 *... |
# Use setuptools if we can
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_exceptional_middleware'
VERSION = '1.2.1'
package_data = {
'exceptional_middleware': [ 'templates/http_responses/*.html' ],
}
setup(
name=PACKAGE, version=VERSI... |
try:
import unittest2 as unittest
except:
import unittest
import numpy as np
from hyperopt import rand, tpe
from hpsklearn.estimator import hyperopt_estimator
from hpsklearn import components
class TestRegression(unittest.TestCase):
def setUp(self):
np.random.seed(123)
self.X_train = np.... |
from PPlay.sprite import *
def barra_de_vida_vi(vida_inimigo, inimigo):
barras = []
Vi3= Sprite("images/vi_verde.png")
Vi2= Sprite("images/vi_amarelo.png")
Vi1= Sprite("images/vi_vermelho.png")
if vida_inimigo == 9:
barras = [Vi3, Vi3, Vi3]
if vida_inimigo == 8:
barras = [Vi3, ... |
usuario1=input('digite seu usuario')
usuario2='123456'
qtd=len(usuario1)
if (qtd)!=6 or usuario1!=usuario2:
print('senha incorreta')
else:
print('senha correta')
|
# Random Testing
# --------------
# Write a random tester for the Queue class.
# The random tester should repeatedly call
# the Queue methods on random input in a
# semi-random fashion. For instance, if
# you wanted to randomly decide between
# calling enqueue and dequeue, you would
# write something like this:
#
... |
class CacheHelper:
def LoadCache(path="./cache"):
pass;
def GenerateCache(path="./cache"):
pass;
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
get_ipython().system(' pip install folium')
# In[2]:
# basic imports
import matplotlib.pyplot as plt
import numpy as np
import math as mt
import csv
import pandas as pd
from pandas.tools import plotting
import folium
import warnings # supprssion des warnings pandas
i... |
def dist(source, target):
"""trying to match word source to target word"""
dp = [[0 for i in range(len(source)+1)] for i in range(2)]
for i in range(len(source)+1): dp[0][i] = i
for i in range(len(target)+1):
for j in range(len(source)+1):
if j==0: dp[i%2][j] = i
elif s... |
from setuptools import setup
setup(
name='benchmike',
version='1.0',
description='Module for measuring time complexity of functions',
license='MIT',
url='www.github.com/mikegpl',
author='Michał Grabowski',
author_email='mkg.grabowski@gmail.com',
packages=['benchmike'],
install_requi... |
x, y = input().split(' ')
x = float(x)
y = float(y)
if x == 0:
if y == 0:
print('Origem')
if y != 0:
print('Eixo Y')
if y == 0:
if x != 0:
print('Eixo X')
if x > 0:
if y > 0:
print('Q1')
if y < 0:
print('Q4')
if x < 0:
if y > 0:
print('Q2')
if ... |
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def swap(array, i, j):
temp = array[i]
array[i] = array[j]
array[j] = temp
def partition(array, left, right):
pivotelement = array[right]
partitionidx = left... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 12:02:08 2021
@author: Mahmu
"""
import numpy
import random
import pylab
import imp
"""
Generate random coin flips and return a result list
"""
def generateCoinFlipData(numberOfCoins, numberOfFlips):
flippedCoinResults = []
for i in range(numberOfCoins):
... |
Program:
# Castle drawing using turtle
import turtle
def polygon(a_turtle, num_side, side_length):
'''
The function draws a regular ploygon with the given number of sides, each
side of the given length.
a_turtle (turtle) - The turtle that is drawing.
num_side (int) - Number of sides of the polygon... |
from django.contrib import admin
from .models import UserInfo, MyUser
# Register your models here.
admin.site.register(UserInfo)
admin.site.register(MyUser) |
months = ['January', # 'JAN'
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
# 1. Lambda function calculating kinetic energy Ke = (m*v**2)/2
kine... |
from .core import parse, match, run
from .utils import compatible_with
__all__ = ('parse', 'run', 'match')
# The following variables will be used in PyPI index.
__name__ = 'classarg'
__author__ = 'Ian Chen'
__license__ = 'MIT'
__version__ = '0.0.2'
__email__ = 'patrickchen1994@gmail.com'
# Prototype, Developmen... |
# -*- coding: utf-8 -*-
import functools
import six
from .constants import MESSAGES
from .logger import logger
from .common import StateError
def inherit_docstrings(cls):
'''
Take a base class and apply it's docstrings to functions
that do NOT have docstrings.
'''
bases = cls.__bases__
for bas... |
from flask import current_app, request
from flask_restful import Resource
from flask_discoverer import advertise
from flask import Response
from SIMBAD import get_simbad_data
from SIMBAD import simbad_position_query
#from SIMBAD import parse_position_string
from NED import get_ned_data
from NED import get_NED_refcodes
... |
"""Config flow for Toshiba AC integration."""
from __future__ import annotations
import logging
import random
from typing import Any
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
from homeassistant.ex... |
from ._discrete_distribution import DiscreteDistribution
from numpy import random
class IIDStdGaussian(DiscreteDistribution):
"""
A wrapper around NumPy's IID Standard Gaussian generator `numpy.random.randn`.
>>> dd = IIDStdGaussian(dimension=2,seed=7)
>>> dd
IIDStdGaussian (DiscreteDistribution... |
from rich.console import Console
from dataclasses import dataclass
from random import choice
from sqlite3 import Error, connect
from prompt_toolkit import PromptSession
import os
cons = Console()
# Todo
@dataclass
class Todo:
tag: str
content: str
done: bool
# Main
class Main:
def __init__(self) -> N... |
import pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
@pytest.fixture
def driver(request):
driver = webdriver.Ie()
request.addfinalizer(driver.quit)
... |
from __future__ import unicode_literals
class PrimeRestoreException(Exception):
pass
class PrimeRestoreUserException(PrimeRestoreException):
pass
class RestorePermissionDenied(Exception):
""" Raised when the user is not permitted to restore """
|
from typing import Iterable
def _is_collection(collection, desired_obj_types):
if isinstance(collection, str):
return False
if isinstance(collection, desired_obj_types):
return False
return isinstance(collection, Iterable) |
from sciencebeam_parser.models.model_impl_factory import (
EngineNames,
get_engine_name_for_config
)
class TestGetEngineNameForConfig:
def test_should_return_wapiti_if_engine_prop_is_wapiti(self):
assert get_engine_name_for_config({
'engine': EngineNames.WAPITI
}) == EngineName... |
# BEFEHLE: kara.
# move() turnRight() turnLeft()
# putLeaf() removeLeaf()
#
# SENSOREN: kara.
# treeFront() treeLeft() treeRight()
# mushroomFront() onLeaf()
# Variablen
max_leaf_sum = 3
# Methoden
def check_leaf(mls):
if kara.onLeaf():
kara.removeLeaf()
mls -= 1
return mls
else:
return mls
... |
from .scraper import Scraper
def main():
s = Scraper()
products = s.get_all_products_from_category("smartklokker", no_pages=1)
sellers_and_prices = s.get_sellers_and_prices_of_product_list(
products["Product number"]
)
print(sellers_and_prices.head())
|
# Generated by Django 2.0 on 2019-04-02 15:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('publications', '0025_publication_is_from_systematic_search'),
]
operations = [
migrations.AlterField(
model_name='experimentpopula... |
"""
@author: Nihal & Adi
"""
from sequence import simpleSequence
from Qlearn import Qlearn
from minimaxQ import miniMAX
import random
import time
def M_M(player, player2):
M1 = miniMAX(player)
M2 = miniMAX(player2)
s = simpleSequence()
s.printTitle("Minimax Q vs Minimax Q")
s.print_board()
s.... |
def leiaInt(mgn):
print('-' * 30)
while True:
n = str(input(mgn))
if n.isnumeric():
return n
break
else:
print('\033[31mErro! Digite um número inteiro válido.\033[m')
n = leiaInt('Digite um número: ')
print(f'Você acabou de digitar o número {n}') |
"""
Track Map to process XY positions of cones to a map
Author: Mahmoud Kamaleldin
"""
# Pip packages
import math
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pickle
from scipy.interpolate import splprep, splev
# Local packages
from fastslam import *
def distance(x1... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def insert_career(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Career = apps.get_model("... |
import os
from collections import namedtuple
import pytest
from leapp.exceptions import StopActorExecutionError
from leapp.libraries.actor import addupgradebootentry
from leapp.libraries.common.config.architecture import ARCH_X86_64, ARCH_S390X
from leapp.libraries.common.testutils import CurrentActorMocked
from leap... |
#! /usr/bin/env python
import json
import sys
# Dependencies can be installed by running:
# pip install keras tensorflow h5py pillow
# Run script as:
# ./extract-features.py images/*.jpg
from keras.applications.vgg16 import VGG16
from keras.models import Model
from keras.preprocessing import image
from keras.appl... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 04 12:29:27 2016
@author: kodai
"""
from sklearn.datasets import load_digits
import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
digits = load_digits(2)
img_data, img_label = (digits.data, digits.target) # データとラベルに分ける
alpha = 0.5 ... |
"""Object-oriented interface to an experiment's data."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import os
import re
from itertools import chain
from collections import OrderedDict
import ... |
from .cluster import CharacterCluster
from .html_creator import HTMLCreator
from .argument_parser import parse_arguments
import ntpath
import timeit
class Main:
"""Entrypoint to the clustering program
"""
def __init__(self):
self.parsed_arguments = parse_arguments()
def execute(self):
... |
import Queue
from timeit import default_timer as timer
import almath
import vision_definitions as vd
from naoqi import ALProxy, motion
import Image
from constants import *
class NAO:
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.motion = ALProxy("ALMotion", ip, port)... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import random
import signal
import sys
import time
import unittest
from common_utils import (TestCase, run_tests, IS_WINDOWS, NO_MULTIPROCESSING_SPAWN)
import torch.multiprocessing as mp
def test_success_func(i):
pass
... |
from tkinter import *
window = Tk()
def km_miles():
miles = float(e1_val.get()) * 1.6
t1.delete("1.0", END)
t1.insert(END, miles)
print('Successfully converted')
l1 = Label(window, text='Enter kilometers: ')
l1.grid(row = 0, column = 0)
e1_val = StringVar()
e1 = Entry(window, textvariable = e1_v... |
class Game():
def __init__(self):
self.agent_list = []
self.index = 0
def add_agent(self, agent):
self.agent_list.append(agent)
def index_of_agent(self, agent):
for index, a in enumerate(self.agent_list):
if a == agent:
... |
from file_1 import A
class B(A):
def target_func(self, p):
p.another_func()
class C(object):
def func1(self, a):
a.target_func(A())
def func2(self):
a = A()
b = B()
a.target_func(b)
def bar1(a):
a.target_func(a)
def bar2(a, b):
atf, btf = a.target_fun... |
# Generated by Django 2.1.5 on 2019-02-20 18:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('articles', '0006_article... |
OBJECT( 'PARSE_TOKEN_QUOTE',
methods = [
MTID_IS( 'TYPE' ),
MS( ARG( CW( 'consume' ), CG( 'LIST', 'phrase' ) ), """
JUMP__consume_LIST( $CA(FRAME__PARSE_TOKEN_QUOTE_0_new( CONTEXT )),
$CA(PATTERN_new( $LISTNEW( CHARACTER_new( 0x5B ), SHAPE_new( $CA(WORD_new( "content" )), nom_parse_phrase_clau... |
#!/usr/bin/env python3
"""
Copyright (c) 2019 CIIRC, CTU in Prague
All rights reserved.
This source code is licensed under the BSD-3-Clause license found in the
LICENSE file in the root directory of this source tree.
@author: Zdenek Kasner
"""
from nlp_crow.database.Database import Database, State
from nlp_crow.dat... |
from keras.models import Sequential
from matplotlib import pyplot # To be deleted
from sklearn.model_selection import train_test_split # To be deleted
from scipy import signal
import pandas as pd
import tensorflow as tf
from keras.layers.merge import concatenate
from keras.layers import Input, Dense, Conv1D, MaxPooli... |
import argparse
import json
import logging
import os
import pathlib
import random
import sys
from typing import Any, Dict, Optional
import yaml
import neighborly
from neighborly.exporter import NeighborlyJsonExporter
from neighborly.loaders import UnsupportedFileType
from neighborly.simulation import NeighborlyConfig... |
import json
import re
import websocket
import servitor_utils
try:
import thread
except ImportError:
import _thread as thread
import time
def check_message(ws, message):
try:
parsed_message = json.loads(message)
print json.dumps(parsed_message['message'], ensure_ascii=False)
except:
... |
# coding: utf-8
"""
OOXML Automation
This API helps users convert Excel and Powerpoint documents into rich, live dashboards and stories. # noqa: E501
The version of the OpenAPI document: 0.1.0-no-tags
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
name = "Fastest-0-Baseline"
# Testing 20 times the same thing just to see if n=300 is enough to get reliable min values
# the 20 tests should not have a huge variance
execution_strategy = {
"ignore_first_n_results": 0,
"sample_size": 2,
"type": "step_explorer",
"knobs": {
"irrelevant": ([1, 40]... |
import numpy as np
from holoviews.core.data import Dataset
from .base import HomogeneousColumnTests, InterfaceTests
class ArrayDatasetTest(HomogeneousColumnTests, InterfaceTests):
"""
Test of the ArrayDataset interface.
"""
datatype = 'array'
data_type = np.ndarray
def test_dataset_empty_l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.