content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from django.shortcuts import redirect
from django.views.generic import UpdateView
from ...models.survey import Survey, Question, Choice
from ...models.answer import SurveyAnswer
from ...forms.surveys import AnswerSurveyQuestionsForm
from ..helper import get_ip, get_next_question
from ..error import permission_user_u... | python |
import unittest
from pathlib import Path
import colab_transfer
class TestTransferMethods(unittest.TestCase):
def get_dummy_data_root(self):
data_root_folder_name = 'dummy_data_for_unit_test/'
return data_root_folder_name
def create_dummy_data(self):
input_data_folder_name = self.ge... | python |
"""Differential Evolution Optimization
:Author: Robert Kern
Copyright 2005 by Robert Kern.
"""
import numpy as np
# Licence:
# Copyright (c) 2001, 2002 Enthought, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the fo... | python |
from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QGroupBox, \
QVBoxLayout, QRadioButton, QLabel, QSlider, QPushButton, QMessageBox
from Windows.Templates.SimplePerfOptionsTemplate import Ui_Dialog
from Windows.GeneralPerf import GeneralPerf
import re
import numpy as np
from util_tools.PopUp... | python |
# Autogenerated from KST: please remove this line if doing any edits by hand!
import unittest
from type_ternary import _schema
class TestTypeTernary(unittest.TestCase):
def test_type_ternary(self):
r = _schema.parse_file('src/term_strz.bin')
self.assertEqual(r.dif.value, 101)
| python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from builtins import range
import sys
import os
import ntpath # equivalent to os.path when running on windows
def run(id, gtotool, config, debug):
try:
gtomain = gtotool.gtomain
# read config
module_name = ... | python |
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
import abc
class TargetNotFoundError(Exception):
@abc.abstractproperty
def _target_type(self):
return None
def __init__(self, *args, **kwargs):
self._target ... | python |
# 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 applica... | python |
from django.db import models
import uuid
from django.contrib.auth.models import User
# Create your models here.
TIPOS_USUARIOS = (
('admin', 'Admin'),
('estudiante', 'Estudiante'),
('docente', 'Docente'),
('administrativo', 'Personal administrativo')
)
TIPOS_UNIVERSIDADES = (
('unfv', 'Universida... | python |
# -*- coding: utf-8 -*-
import abjad
class ScoreTemplate(object):
def __call__(self):
# Violin
violin_staff = abjad.Staff(
[abjad.Voice(name='Violin Voice')],
name='Violin Staff',
lilypond_type='ViolinStaff',
)
violin_tag = abjad.LilyPondLi... | python |
def setup():
size(500,500)
smooth()
background(50)
strokeWeight(2)
stroke(250)
counter= 0
mcolor=0
cx = 250
cy = 250
R = 200
def draw():
global cx,cy, R, counter, mcolor
y1 = cos(counter)*R + cy
x1 = sin(counter)*R + cx
mcolor=mcolor+1
stroke(mcolor)
... | python |
#!/usr/bin/env python
"""
synopsis:
Paranoid Pirate queue
Original author: Daniel Lundin <dln(at)eintr(dot)org>
Modified for async/ioloop: Dave Kuhlman <dkuhlman(at)davekuhlman(dot)org>
usage:
python ppqueue.py
notes:
To test this, use the lazy pirate client. To run this, start any number of
p... | python |
""" Core abstract rendering abstractions. This includes the main drivers of
execution and the base clases for shared data representations.
"""
from __future__ import print_function, division, absolute_import
from six.moves import range
import numpy as np
import abstract_rendering.geometry as geometry
import abstract_r... | python |
from .core.protocol import Range
from .core.protocol import Request
from .core.registry import get_position
from .core.registry import LspTextCommand
from .core.sessions import method_to_capability
from .core.typing import Any, Dict, Optional, List, Tuple
from .core.views import range_to_region
from .core.views import ... | python |
from haystack.preprocessor.cleaning import clean_wiki_text
from haystack.preprocessor.utils import convert_files_to_dicts, fetch_archive_from_http
from haystack.reader.farm import FARMReader
from haystack.reader.transformers import TransformersReader
from haystack.utils import print_answers
from haystack.document_store... | python |
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, related_name = 'auth_user')
wms_id = models.IntegerField(default = 0)
is_grp = models.BooleanField(defaul... | python |
from setuptools import setup, find_packages
from os import path
import io
import versioneer
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='knitty',
version=versioneer.get_version(),
cmdclass=vers... | python |
#!/usr/bin/env python3
# Copyright (c) 2020-2021 Dimitrios-Georgios Akestoridis
#
# 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 righ... | python |
"""Define setup for installing the repository as a pip package."""
from setuptools import find_packages, setup
setup(
name="ikshana",
packages=find_packages(),
version="0.1.1",
description="Python package for computer vision",
author="ikshana.ai",
license="MIT",
url="https://github.com/iksh... | python |
from django.http import HttpResponseBadRequest
from django.http import HttpResponseBadRequest
from django.core.exceptions import ValidationError
from django.core.exceptions import SuspiciousOperation
import json
import logging
logger = logging.getLogger(__name__)
class validation:
def __init__(self, data):
... | python |
import asyncio
import pydash
import math
from rocon_client_sdk_py.virtual_core.path_planner import PathPlanner
class Actuator(): #metaclass=SingletonMetaClass):
def __init__(self, context):
pass
async def change_position(self, context, destination_point, destination_map=None):
worker = context... | python |
import logging
from django.core.management.base import BaseCommand
from parliament.models import PoliticalParty
from openkamer.parliament import create_parties
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
parties = create_parties(update_votes=Fal... | python |
import cython
import threading
class PWM:
_port: object
_pin: object
_duty_cycle: cython.longdouble
cycle_time: cython.longdouble
_pwm_thread: object
def __init__(self, gpio_port: object, pwm_pin: object, duty_cycle: cython.longdouble = 0, cycle_time: cython.longdouble = 0.02):
se... | python |
from autolens.pipeline.phase.imaging.analysis import Analysis
from autolens.pipeline.phase.imaging.result import Result
from .phase import PhaseImaging
| python |
from piccolo.apps.migrations.auto import MigrationManager
from piccolo.columns.column_types import Date
from piccolo.columns.column_types import Varchar
from piccolo.columns.defaults.date import DateNow
from piccolo.columns.indexes import IndexMethod
ID = "2021-09-26T17:01:33:631238"
VERSION = "0.50.0"
DESCRIPTION = ... | python |
from .SRW_RWF_ISRW import SRW_RWF_ISRW
from .Snowball import Snowball, Queue
from .ForestFire import ForestFire
from .MHRW import MHRW
from .TIES import TIES
| python |
# Copyright (C) NVIDIA CORPORATION. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | python |
from yahoo_finance import Currency
file= open("Currency_update.txt", 'r')
x=file.readlines()
for y in x:
L=map(str, y.split())
res=''
for z in L[:-1]:
res+=z+' '
print '%30s %s'%(res,L[-1])
first_currency=raw_input("enter first currency: ")
second_currency=raw_input("enter second curren... | python |
#!/usr/bin/env python3
#encoding=utf-8
#-----------------------------------------------------
# Usage: python3 timer3.py
# Description: timer function with keywordonly argument
#-----------------------------------------------------
'''
Same usage as timer2.py, but uses 3.X keyword-only default arguments
instead of... | python |
"""
Generate a autoencoder neural network visualization
"""
# Changing these adjusts the size and layout of the visualization
FIGURE_WIDTH = 16
FIGURE_HEIGHT = 9
RIGHT_BORDER = 0.7
LEFT_BORDER = 0.7
TOP_BORDER = 0.8
BOTTOM_BORDER = 0.6
N_IMAGE_PIXEL_COLS = 64
N_IMAGE_PIXEL_ROWS = 48
N_NODES_BY_LAYER = [10, 7, 5, 8]
... | python |
from kafka import KafkaConsumer
from kafka.errors import KafkaError
import logging
import sys
BOOTSTRAP_SERVERS = ['3.209.55.41:9092']
KAFKA_TOPIC = 'fledge-testing'
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
forma... | python |
import os
from shutil import copy2
from datetime import datetime
from PIL import Image
from sys import argv
username = argv[1]
dest = argv[2]
source = "C:/Users/" + username + "/AppData/Local/Packages/Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy/LocalState/Assets"
currentImgs = []
for filename in os.listdir(... | python |
class HabitatError(Exception):
_msg = 'Unhandled Error'
def __init__(self, *args, **kwargs):
return super().__init__(self._msg%args, **kwargs)
class InvalidBiomeError(HabitatError):
_msg = '%s is not a valid biome!'
class AmbiguousProvidesError(HabitatError):
_msg = '%s and %s both provide %s... | python |
import random
# Easy to read representation for each cardinal direction.
N, S, W, E = ('n', 's', 'w', 'e')
class Cell(object):
"""
Class for each individual cell. Knows only its position and which walls are
still standing.
"""
def __init__(self, x, y, walls):
self.x = x
self.y = y
... | python |
import numpy as np
import pandas as pd
from sklearn.linear_model import lasso_path
from lassoloaddata import get_folds
# define the grid of lambda values to explore
alphas = np.logspace(-4, -0.5, 30)
def get_lasso_path(X_train, y_train, alphas=alphas):
"""
compute the lasso path for the given data
Args:
... | python |
""""
Settings:
pos_id
second_key
client_id
client_secret
"""
import hashlib
import json
import logging
from collections import OrderedDict
from decimal import Decimal
from typing import Optional, Union
from urllib.parse import urljoin
from django import http
from django.conf import settings
from django... | python |
from redbot.core import commands
class Tutorial_Cog(commands.Cog):
"""Minimal tutorial bot"""
def __init__(self, bot):
self.bot = bot
@commands.group()
async def simple_cog(self, ctx):
pass
@simple_cog.command()
async def hello(self, ctx, *, message):
"""Says something... | python |
from IPython.display import HTML
import IPython
import htmlmin
def _format_disqus_code(page_url: str, page_identifier: str, site_shortname: str) -> str:
"""This function formats the necessary html and javascript codes needed to be
inserted into the jupyter notebook
Args:
page_url (str): your page'... | python |
DEBUG = True
# Make these unique, and don't share it with anybody.
SECRET_KEY = "c69c2ab2-9c58-4013-94a6-004052f2583d40029806-a510-4c48-a874-20e9245f55f70394cbad-48b5-4945-9499-96c303d771e6"
NEVERCACHE_KEY = "9fb86bbb-51a2-494d-b6ca-1065c0f1f58ee6d757ec-85b0-4f66-9003-ff57c8a3d9d8b37a8b11-19a9-4c03-8596-ba129af542ed"... | python |
from setuptools import setup, find_packages
setup(
name="componentsdb",
version="0.1",
packages=find_packages(exclude=['tests']),
package_data={
'componentsdb': [
'ui/templates/*.html',
'ui/static/*',
],
},
install_requires=[
'enum34',
'fl... | python |
#!/usr/bin/env python3
# https://leetcode.com/problems/ugly-number/
import unittest
class Solution:
def isUgly(self, num: int) -> bool:
if num <= 0:
return False
if num == 1:
return True
original = num
while num % 2 == 0:
num //= 2
while... | python |
import unittest
from unittest import mock
from easybill_rest import Client
from easybill_rest.resources.resource_attachments import ResourceAttachments
from easybill_rest.tests.test_case_abstract import EasybillRestTestCaseAbstract
class TestResourceAttachments(unittest.TestCase, EasybillRestTestCaseAbstract):
... | python |
#########
#IMPORTS#
#########
from tensorflow.keras.losses import binary_crossentropy
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import *
class Unet2D:
def __init__(self):
c1 = Conv2D(32, (3, 3), activation='relu', padding='s... | python |
async def get_value():
return "not-none"
<caret>if await get_value():
print("Not none")
else:
print("None") | python |
import sys
from bson.objectid import ObjectId, InvalidId
from girder import logger
from girder.constants import AccessType
from girder.models.model_base import AccessControlledModel
from girder.models.model_base import ValidationException
from girder.models.user import User as UserModel
from girder.utility.model_import... | python |
from .model import DeepUNet
| python |
from flask import Blueprint, redirect, url_for, render_template, request, abort, Flask
from flask import current_app
from website import db
from website.main.forms import SearchForm
from website.main.utils import db_reset, build_destination, make_parks, miles_to_meters, seconds_to_minutes
from website.models import Res... | python |
import pytest
import os
import time
import projects.sample.sample as sample
from tests.backgroundTestServers import BackgroundTestServers
from rtCommon.clientInterface import ClientInterface
from tests.common import rtCloudPath
test_sampleProjectPath = os.path.join(rtCloudPath, 'projects', 'sample')
test_sampleProject... | python |
from . import meta_selector # noqa
from .pg import PatternGenerator
from .selector import Selector
PatternGenerator('')
Selector('')
| python |
def binc(n,m):
bc = [[0 for i in range(1000)] for j in range(1000)];
for x in range(m+1):
bc[0][x] = 1;
bc[1][0] = 1;
for i in range(1,n):
for j in range(i+1):
print("I", i, "J", j);
bc[i][j] = bc[i-1][j-1] + bc[i-1][j];
... | python |
# coding: utf-8
# Python libs
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import shutil
import tempfile
import time
# Salt libs
import salt.utils.files
from salt.beacons import watchdog
from salt.ext.six.moves import range
# Salt test... | python |
# PART 1
def draw_stars(x):
for count in range(0, len(x)):
print '*' * x[count]
x = [1, 2, 4, 8, 16, 32]
draw_stars(x)
# PART 2
def draw_star(x):
for count in range(0, len(x)):
if(isinstance(x[count], str)):
print x[count].lower()[:1] * len(x[count])
else:
print '*' * x[count] | python |
from influence_module.interface import IInfluencer
from music_module.interface import IMusic
from graphics_module.interface import IVisuals
from parse_module.interface import parse_config
from timeit import default_timer as timer
import numpy as np
configs = None
i_visuals = None
i_influencer = None
i_music = None
de... | python |
"""
This file stores a subclass of DistanceSolver, UPGMA. The inference procedure is
a hierarchical clustering algorithm proposed by Sokal and Michener (1958) that
iteratively joins together samples with the minimum dissimilarity.
"""
from typing import Callable, Dict, List, Optional, Tuple, Union
import abc
from col... | python |
from pathlib import Path
from unittest import mock
from credsweeper.file_handler.patch_provider import PatchProvider
class TestPatchProvider:
def test_load_patch_data_p(self) -> None:
"""Evaluate base load diff file"""
dir_path = Path(__file__).resolve().parent.parent
file_path = dir_pat... | python |
import md5
i = 0
while 1:
key = 'ckczppom' + str(i)
md = md5.new(key).hexdigest()
if md[:5] == '00000':
break
i+=1
print i | python |
from django.contrib import admin
# Register your models here.
from .models import Item
class ItemAdmin(admin.ModelAdmin):
list_display = ['item_id', 'price', 'type', 'seller',
'customer_id', 'quantity_per_item', 'total_price' ]
admin.site.register(Item, ItemAdmin) | python |
import sys
from base64 import b64encode
from nacl import encoding, public
"""
This script is used to encrypt the github secrets for the
Debricked login, since the bindings for golang suck.
"""
def encrypt(public_key: str, secret_value: str) -> str:
"""Encrypt a Unicode string using the public key."""
public_k... | python |
from qgis.core import *
import psycopg2
QgsApplication.setPrefixPath("/usr", True)
qgs = QgsApplication([], False)
qgs.initQgis()
uri = QgsDataSourceURI()
uri.setConnection("192.168.50.8", "5432", "pub", "ddluser", "ddluser")
try:
conn = psycopg2.connect("dbname='soconfig' user='ddluser' host='192.168.50.8' pas... | python |
from django.conf.urls import include, url
from olympia.reviews.feeds import ReviewsRss
from . import views
# These all start with /addon/:id/reviews/:review_id/.
review_detail_patterns = [
url('^$', views.review_list, name='addons.reviews.detail'),
url('^reply$', views.reply, name='addons.reviews.reply'),
... | python |
#!/usr/bin/env python3
import json
import urllib.request
import mirrorz
import config
def fetch_json(url):
print(f"fetching {url}")
response = urllib.request.urlopen(url)
data = response.read()
return json.loads(data)
def main():
for name, cfg in config.sites.items():
values=[]
for... | python |
from pprint import pprint # noqa
from datetime import datetime
from normality import stringify
REMOVE = [
"Shape.STArea()",
"Shape.STLength()",
"Shape.len",
"SHAPE.len",
"SHAPE.fid" "FullShapeGeometryWKT",
"Shape__Length",
]
RENAME = {
"SDELiberiaProd.DBO.MLMELicenses_20160119.Area": "Ar... | python |
from jsonrpc11base.errors import APIError
from src import exceptions
class UnknownTypeError(APIError):
code = 1000
message = 'Unknown type'
def __init__(self, message):
self.error = {
'message': message
}
class AuthorizationError(APIError):
code = 2000
message = 'Aut... | python |
from django.contrib import admin
from .models import Tag, Category, Article, About
# Register your models here.
admin.site.register(Tag)
admin.site.register(Category)
admin.site.register(About)
@admin.register(Article)
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
| python |
# import the necessary package
from functools import wraps
from flask import request
from PIL import Image
from io import BytesIO
from app.main import config
import numpy as np
import base64
import cv2
import os
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
data, status = Auth.get_l... | python |
import time
from typing import Union
import pyglet
from kge.core import events
from kge.core.constants import DEFAULT_FPS
from kge.core.system import System
class Updater(System):
def __init__(self, engine=None, time_step=1 / (DEFAULT_FPS), **kwargs):
super().__init__(engine, **kwargs)
... | python |
NUMBERS = [
".",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
]
OPERATIONS = [
"+",
"-",
"=",
"×",
"÷",
]
FUNCTIONS = [
"%",
"(",
")",
"⁺⁄₋",
"¹⁄ₓ",
"10ˣ",
"2ⁿᵈ",
"²√x",
"³√x",
"AC",
"cos",
"cosh",
... | python |
import json
from collections import OrderedDict
from raven_preprocess.np_json_encoder import NumpyJSONEncoder
from ravens_metadata_apps.utils.basic_response import \
(ok_resp, err_resp)
def json_dump(data_dict, indent=None):
"""Dump JSON to a string w/o indents"""
if indent is not None and \
not is... | python |
__author__ = 'Govind Patidar'
class Locator(object):
# open page locator All ID
logo = "//img[@alt='Mercury Tours']"
btn_skip = "com.flipkart.android:id/btn_skip"
banner_text = "com.flipkart.android:id/banner_text"
mobile_no = "com.flipkart.android:id/mobileNo"
btn_msignup = "com.flipkart.andr... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime, date, timedelta
from functools import reduce
from django.db.models import Count
from rest_framework import serializers
from common.consts import CFEI_TYPES, PARTNER_TYPES
from common.mixins.views import PartnerIdsMixin
fro... | python |
import base64
import mimetypes
from io import BytesIO
from time import time
from typing import Any, Dict, List, TypedDict
from PyPDF2 import PdfFileReader
from PyPDF2.utils import PdfReadError
from ....models.models import Mediafile
from ....permissions.permissions import Permissions
from ....shared.exceptions import... | python |
# Copyright 2022 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | python |
import io
import os
from unittest.mock import MagicMock, patch
from uuid import uuid4
from django.core.files.uploadedfile import SimpleUploadedFile
from django.template.exceptions import \
TemplateSyntaxError as DjangoTemplateSyntaxError
from django.test import TestCase
from jinja2 import TemplateSyntaxError
from ... | python |
#python3 Steven 12/05/20,Auckland,NZ
#pytorch backbone models
import torch
from commonTorch import ClassifierCNN_NetBB
from summaryModel import summaryNet
from backbones import*
def main():
nClass = 10
net = ClassifierCNN_NetBB(nClass, backbone=alexnet)
summaryNet(net, (3,512,512))
#net = Class... | python |
from fastapi import FastAPI
app = FastAPI()
@app.get("/keyword-weights/", response_model=dict[str, float])
async def read_keyword_weights():
return {"foo": 2.3, "bar": 3.4}
| python |
"""Submodule providing embedding lookup layer."""
from typing import Tuple, Dict
import tensorflow as tf
from tensorflow.keras.layers import Flatten, Layer # pylint: disable=import-error,no-name-in-module
class EmbeddingLookup(Layer):
"""Layer implementing simple embedding lookup layer."""
def __init__(
... | python |
import sys
import os
import numpy as np
from numpy import array
import datetime
import calendar
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import FuncFormatter
from swaty.swaty_read_model_configuration_file import swat_read_model_configuration_file
from swaty.classes... | python |
class Solution:
cache = {0: 0, 1: 1}
def fib(self, N: int) -> int:
if N in self.cache:
return self.cache[N]
self.cache[N] = self.fib(N - 1) + self.fib(N - 2)
return self.cache[N]
# Contributed by LeetCode user mereck.
class Solution2:
def fib(self, N: int) -> in... | python |
import unittest
from src.command.shutter_command import ShutterCommand, ShutterCommandType
class TestShutterCommand(unittest.TestCase):
def test_parse(self):
self.assertEqual(ShutterCommand.parse(" Up "), ShutterCommand(ShutterCommandType.POSITION, 0))
self.assertEqual(ShutterCommand.parse(" ... | python |
#
# Photo Fusion
#
# Peter Turney, February 8, 2021
#
# Read a fusion pickle file (fusion_storage.bin) and
# make photos of the fusion events.
#
import golly as g
import model_classes as mclass
import model_functions as mfunc
import model_parameters as mparam
import numpy as np
import time
import pickle
... | python |
from subprocess import call
import re
import json
# cache for `dependencies`
dependencies = dict()
# parses and represents a carthage dependency
class Dependency(object):
def __init__(self, line, origin):
self.line = line
self.origin = origin
match = re.match(r"^(?P<identifier>(github|git|... | python |
#!/usr/bin/env python3
import argparse
import gzip
import logging
import hashlib
from glob import glob
from json import load
from inscriptis import get_text
from inscriptis.model.config import ParserConfig
from collections import defaultdict
from harvest import posts
from harvest.extract import extract_posts
from url... | python |
#!/usr/bin/python
import timeit
from graphtheory.structures.edges import Edge
from graphtheory.structures.graphs import Graph
from graphtheory.structures.factory import GraphFactory
from graphtheory.traversing.bfs import BFSWithQueue
from graphtheory.traversing.bfs import SimpleBFS
V = 10
#V = 1000000 # OK
graph_fa... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import colorsimple as cs
entry_dict = {
"A (Rhodopsin)" : { "shape" : 7, "ps" : 1.5, "clr" : "#FFB8B8" },
"B1 (Secretin)" : { "shape" : 7, "ps" : 1.5, "clr" : "#00A600" },
"C (Glutamate)" : { "shape" : 7, "ps" : 1.5, "clr" ... | python |
from typing import Dict, Optional, Tuple
from datadog import initialize, statsd
from .base import BaseClient
class DogstatsdClient(BaseClient):
def __init__(self, agent_host: str, port: int) -> None:
initialize(statsd_host=agent_host, statsd_port=port)
def increment_counter(
self, name: str... | python |
symbols = ["DOLLAR SIGN", "BANANA", "CHERRY", "DIAMOND", "SEVEN", "BAR"]
import random
reel_1 = random.choice(symbols)
reel_2 = random.choice(symbols)
reel_3 = random.choice(symbols)
if reel_1 == reel_2 and reel_2 == reel_3:
print("%s! %s! %s! LUCKY STRIKE! YOU WIN £10"% (reel_1, reel_2, reel_3))
elif reel_1... | python |
from tkinter import Canvas
class GraphicItem:
itemType: str
coords: list
config: dict
def __init__(self, cnv: Canvas):
self.cnv = cnv
self.uid = None
def update(self):
if self.uid is None:
self.uid = self.cnv._create(
itemType=self.itemType,
... | python |
class cel:
def __init__(self):
self.temp = 1234567890
| python |
import datetime
import dateutil.parser
import pytz
import pytz.exceptions
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseNotFound
from django.shortcuts import redirect, render
from django.utils import timezone, translation
from django.utils.... | python |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | python |
from collections import OrderedDict
class Decision:
def __init__(self, id, name):
self.id = id
self.name = name
self.decisionTables = []
class DecisionTable:
def __init__(self, id, name):
self.id = id
self.name = name
self.inputs = []
self.outputs = [... | python |
#!/usr/bin/env python
from __future__ import absolute_import, print_function
import numpy as np
import math
import random
import time
import rospy
import tf
from geometry_msgs.msg import Point, Pose, Twist
from utils import generatePoint2D, bcolors, close2Home
WHEEL_OFFSET = 0
class Wanderer():
"""
Super class... | python |
"""Quantum Inspire library
Copyright 2019 QuTech Delft
qilib is available under the [MIT open-source license](https://opensource.org/licenses/MIT):
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 Softwar... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from contextlib import contextmanager
from datetime import datetime
import os
import tensorflow as tf
def batch_size_from_env(default=1):
"""Get batch size from environment variable SALUS_BATCH_SIZE"""
... | python |
import logging
import redis
import time
import iloghub
iloghub = iloghub.LogHub()
iloghub.config()
# create logger
logger = logging.getLogger('simple_example')
#formater = logging.Formatter(style=" %(message)s")
fmt = "%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s"
datefmt = "%H:%M:%S"
formatte... | python |
from os.path import exists
import speech_recognition as sr
import mss
import numpy as np
import os
from PIL import Image
path, dirs, files = next(os.walk("D:/Document/3INFO/BDD/Demon/"))
monitor =2
i = len(files)
import glob
def record_volume(path,i):
fichier=open(path[0:-3]+".txt","a")
r = sr.Recognizer()
... | python |
# -*- coding: utf-8 -*-
"""SymptomSuggestion.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1TCme3BRC34OqIgLUca6GkivYK-1HFs-j
"""
# !git clone https://github.com/rahul15197/Disease-Detection-based-on-Symptoms
# cd Disease-Detection-b... | python |
#!/usr/bin/python3
"""
TXFMTrackService
(C) 2015
David Rieger
"""
import bottle
from bottle import route, run, response
from storagemanager import StorageManager
sm = StorageManager()
@route('/api/get/all')
def get_all_songs():
response.headers['Access-Control-Allow-Origin'] = '*'
return sm.get_songs()
@r... | python |
from domain.Contest.database.contest_repository import ContestRepository
from domain.Contest.usecase.contest_interactor import ContestInteractor
from infrastructure.database.postgres.sqlhandler import SqlHandler
class ContestController:
def __init__(self, sqlhandler: SqlHandler):
self.interactor = Contest... | python |
# dht11_serial.py - print humidity and temperature using DHT11 sensor
# (c) BotBook.com - Karvinen, Karvinen, Valtokari
import time
import serial # <1>
def main():
port = serial.Serial("/dev/ttyACM0", baudrate=115200, timeout=None) # <2>
while True:
line = port.readline() # <3>
arr = line.split() # <4>
if len... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.