content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from sys import *
import csv
def locase(s): return s[:1].lower() + s[1:]
reader = csv.DictReader(stdin, delimiter=',')
for item in reader:
itemstr = item.get('item')
itemid = itemstr[itemstr.rfind('/')+1:]
lang = item.get('itemLabel_lang')
str1 = locase(item.get('str1'))
str2 = locase(item.get('st... | python |
expected_results = {
"K64F": {
"desc": "error when bootloader not found",
"exception_msg": "not found"
}
}
| python |
import random
import json
import torch
from model import NeuralNetwork
from nltk_utils import tokenize,extract_stop_words,stem,bag_of_words
import os
import time
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with open('intents.json',encoding='UTF-8') as f:
intents = json.load(f)
DATA_FILE... | python |
import time, pytest, inspect
from utils import *
from PIL import Image
def test_mixer_from_config(run_brave, create_config_file):
subtest_start_brave_with_mixers(run_brave, create_config_file)
subtest_assert_two_mixers(mixer_0_props={'width': 160, 'height': 90, 'pattern': 6})
subtest_change_mixer_pattern(... | python |
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = raw_input('TELL ME a word in ENGRIXH:').lower()
| python |
from behave import given, when, then
import time
import os
@when("you navigate to CSW homepage")
def step(context):
url = os.environ["CSW_URL"]
context.browser.get(url)
@when('you navigate to CSW page "{path}"')
def step(context, path):
url = os.environ["CSW_URL"] + path
print(url)
context.brows... | python |
from django.contrib import admin
from models import Participant, Exchange
class ParticipantAdmin(admin.ModelAdmin):
pass
class ExchangeAdmin(admin.ModelAdmin):
pass
admin.site.register(Participant)
admin.site.register(Exchange) | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
class CrowdCounter(nn.Module):
def __init__(self, model_name):
super(CrowdCounter, self).__init__()
if model_name == 'AlexNet'.lower():
from .counters.AlexNet import AlexNet as net
elif model_nam... | python |
"""
The file defines the training process.
@Author: Yang Lu
@Github: https://github.com/luyanger1799
@Project: https://github.com/luyanger1799/amazing-semantic-segmentation
"""
from utils.data_generator import ImageDataGenerator
from utils.helpers import get_dataset_info, check_related_path
from utils.callbacks impor... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: gxs
@license: (C) Copyright 2016-2019, Light2Cloud (Beijing) Web Service Co., LTD
@contact: dingjianfeng@light2cloud.com
@software: AWS-DJF
@file: delete_s3_upload_data.py
@ide: PyCharm
@time: 2020/4/16 11:18
@desc:
"""
import base64
import csv
import fnmatch
... | python |
"""
Author: Fritz Alder
Copyright:
Secure Systems Group, Aalto University
https://ssg.aalto.fi/
This code is released under Apache 2.0 license
http://www.apache.org/licenses/LICENSE-2.0
"""
import cppimport
#This will pause for a moment to compile the module
cppimport.set_quiet(False)
m = cppimport.imp("minionn")
#... | python |
import csv
def savetoCSV(data, filename):
# specifying the fields for csv file
fields = ['Term', 'Poem', 'Part of Speech', 'Definition', 'Tags']
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv dict writer object
writer = csv.DictWriter(cs... | python |
"""plugins.py contains the main type and base class used by the analyzis plugins.
It also contains the work functions used to load the plugins both from disc and
from the resources."""
from act.scio import plugins
import addict
from importlib import import_module
from importlib.machinery import ModuleSpec
from import... | python |
from pathlib import Path
import pytest
from pytest_mock.plugin import MockerFixture
from dotmodules.renderer import ColorAdapter, Colors
@pytest.fixture
def colors() -> Colors:
return Colors()
@pytest.fixture
def color_adapter() -> ColorAdapter:
return ColorAdapter()
class TestColorTagRecognitionCases:
... | python |
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Driver for Parade PS8742 USB mux.."""
import hw_driver
import i2c_reg
class Ps8742Error(hw_driver.HwDriverError):
"""Error occurred accessing ps874... | python |
import jwt
import datetime
import tornado.testing
import tornado.httpserver
import tornado.httpclient
import tornado.gen
import tornado.websocket
from app import Application
APP = Application()
JWT_TOKEN_EXPIRE = datetime.timedelta(seconds=5)
class ChatAuthHandler(tornado.testing.AsyncTestCase):
def setUp(self)... | python |
# -*- coding: utf-8 -*-
"""
(베타) PyTorch를 사용한 Channels Last 메모리 형식
*******************************************************
**Author**: `Vitaly Fedyunin <https://github.com/VitalyFedyunin>`_
**번역**: `Choi Yoonjeong <https://github.com/potatochips178>`_
Channels last가 무엇인가요
----------------------------
Channels last 메모... | python |
# -*- coding: utf-8 -*-
import sys
import codecs
import os.path
from youtubeAPICrawler.database import *
#sys.stdout = codecs.getwriter('utf8')(sys.stdout)
db = YTDatabase()
data_dir = '../../../data/'
studio71 = 'network_channel_id_studio71.json'
maker = 'network_channel_id_maker.json'
broadtv = 'network_channel... | python |
import glob, os
from random import shuffle
import numpy as np
from PIL import Image
import pycuda.driver as cuda
import tensorrt as trt
import labels
import calibrator
MEAN = (71.60167789, 82.09696889, 72.30508881)
MODEL_DIR = 'data/fcn8s/'
CITYSCAPES_DIR = '/data/shared/Cityscapes/'
TEST_IMAGE = CITYSCAPES_DIR + 'l... | python |
import numpy as np
import os, errno
from PyQt4 import QtGui,QtCore
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg
from saltgui import MplCanvas
class FpParallWidget (QtGui.QWidget):
def __init__(self,parent=None):
super(FpParallWidget,self).__init__(... | python |
from logging import NullHandler
from ast import literal_eval
import io
class RequestCountHandler(NullHandler):
def __init__(self,queue):
NullHandler.__init__(self)
self.queue = queue
def handle(self, record):
if False and "request" in record.msg:
print("adding")
... | python |
from .network import launch_in_thread
from . import ui
import argparse
from ..logs import logger
def main(capture_file=None):
ui.init(launch_in_thread, capture_file)
ui.async_start()
if __name__ == "__main__":
logger.debug("Starting sniffer as __main__")
parser = argparse.ArgumentParser(
d... | python |
import os
import sqlite3
try:
from psycopg2cffi import compat
compat.register()
except ImportError:
pass
from sqlalchemy import Column, Integer, String, ForeignKey, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
import pytest
@pytest.fixtur... | python |
import time
from django.contrib.auth.models import User
from django.urls import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import Se... | python |
#!/usr/bin/env python3
import datetime
import logging
import os.path
import rescale.client
# Remember to set RESCALE_API_KEY env variable to your Rescale API key
# on platform.rescale.com (in Settings->API)
SHORT_TEST_ARCHIVE = 'inputs/all_short_tests.tar.gz'
LONG_TEST_FORMAT = 'inputs/long_test_{i}.tar.gz'
LONG_TES... | python |
#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import InfraredSensor
from pybricks.parameters import Port, Button
from pybricks.tools import wait
from pybricks.media.ev3dev import SoundFile, Font
# Create the brick connection.
ev3 = EV3Brick()
# Set Font.
print_font = ... | python |
# Copyright (c) 2013 Riccardo Lucchese, riccardo.lucchese at gmail.com
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any p... | python |
# -*- coding: utf-8 -*-
"""Wrapper for running Oncotator
"""
from snakemake.shell import shell
__author__ = "Manuel Holtgrewe"
__email__ = "manuel.holtgrewe@bihealth.de"
shell(
r"""
# -----------------------------------------------------------------------------
# Redirect stderr to log file by default and enable... | python |
#!/usr/bin/env python
# Copyright (c) 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module to resolve the current platform and bitness that works across
infrastructure systems.
"""
import itertools
import platf... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module: plot_model
-------------------
Contains the main driver function and some helper functions.
F. G. Ramon-Fox 2021
Last revision: May 2021
"""
import numpy as np
import iofunctions as io
import visualization as vis
from units import Units
from galrotcurve ... | python |
def sieve_of_atkin(limit: int) -> None:
"""
2 and 3 are known to be prime
"""
if limit > 2:
print(2, end=" ")
if limit > 3:
print(3, end=" ")
# Initialise the sieve array with False values
sieve: list[bool] = [False] * (limit + 1)
for i in range(0, limit + 1):
si... | python |
import cv2 as cv
import numpy as np
import glob
from tqdm import tqdm
import matplotlib.pyplot as plt
from math import degrees as dg
def cv_show(img,name='Figure'):
cv.namedWindow(name,cv.WINDOW_AUTOSIZE)
cv.imshow(name,img)
cv.waitKey(0)
cv.destroyAllWindows()
Path1 = 'F:\PyCharm\Camera_calibratio... | python |
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
# * File:
# * engine.py
# *
# * Library:
# * ebpf_ic/
# *
# * Author:
# * Lucas Duarte (lucas.f.duarte@ufv.br)
# *
# * Description:
# * Conversion and translation methods
# *
from Instruction import *
from data import *
from ... | python |
import os
import shutil
import hashlib
from django.contrib.auth.models import User
from django.core import mail
from django.urls import reverse
from django.test import TestCase
from django.conf import settings
from tagging.utils import edit_string_for_tags
from djangopeople.djangopeople.models import DjangoPerson, C... | python |
import unittest
from smart_energy_api import solaredge_api as s
class SolaredgeApiSideEffects(unittest.TestCase):
def test_solaredgemeters_meterdata(self):
d = s.solaredgemeters.meterdata()
print(d)
self.assertIsInstance(d, dict)
def test_siteenergy_energydata(self):
d = s.si... | python |
from django.utils.translation import ugettext_lazy as _
from fluent_pages.integration.fluent_contents.models import FluentContentsPage
from parler.models import TranslatableModel
from parler.utils.context import switch_language
from fluent_blogs.models import get_entry_model
class BlogPage(FluentContentsPage):
... | python |
from math import prod
from typing import List
from digits import champernowne_digit
def p40(positions: List[int]) -> int:
return prod(champernowne_digit(n) for n in positions)
if __name__ == '__main__':
print(p40([1, 10, 100, 1000, 10000, 100000, 1000000]))
| python |
#!/usr/bin/env python
import logging
from typing import Union
from expiringdict import ExpiringDict
from .cognito import CognitoUserPassAuth, CognitoBase, CognitoTokenAuth
from .entities import User, JWTToken, JWTPublicKeyRing
from . import __appname__
__author__ = "Giuseppe Chiesa"
__copyright__ = "Copyright 2017, ... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 12 16:11:08 2019
Analyze performance of multi sensor localization algorithms
@author: anantgupta
"""
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing as mp
import pickle
# from IPython import get_ipython
from functools import... | python |
a = "hello"
print(a[1])
# this gets the character at the 1st position
| python |
# Generated by Django 2.2.17 on 2021-04-15 15:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('autoemails', '0015_auto_20210405_1920'),
('consents', '0003_term_help_text'),
]
operations = [
migrations.AddField(
mod... | python |
# coding: utf-8
import numpy as np
import cPickle
import utils
import h5py
import os
def convert_files(file_paths, vocabulary, punctuations, output_path):
inputs = []
outputs = []
punctuation = " "
for file_path in file_paths:
with open(file_path, 'r') as corpus:
for line in c... | python |
from __future__ import division
from ev3.lego import ColorSensor
from time import time, sleep
tick = 0.05
color = ColorSensor()
def median(lst):
lst = sorted(lst)
if len(lst) < 1:
return None
if len(lst) %2 == 1:
return lst[((len(lst)+1)//2)-1]
if len(lst) %2 == 0:
... | python |
# SPDX-FileCopyrightText: 2009 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
#
# Project:
# glideinWMS
#
# File Version:
#
# Description:
# This module implements the basic functions needed
# to interface to rrdtool
#
# Author:
# Igor Sfiligoi
#
import shlex
import string
import subproces... | python |
# Write a program that outputs whether today is a weekday or a weekend.
import datetime
x = datetime.datetime.now()
y = x.weekday()
z = str(input('Ask me a tricky question, like "Weekday or weekend?"'))
question = ("Weekday or weekend?")
while z == question:
if y <= 3: ... | python |
#! /usr/bin/env python3
"""
unittest for hello solution
"""
__author__ = "Ram Basnet"
__copyright__ = "Copyright 2020"
__license__ = "MIT"
import unittest
from hello import answer
class TestHello(unittest.TestCase):
def test1_answer(self):
self.assertEqual(answer(), 'Hello World!', "Test failed...")
i... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Collection of tests for :mod:`orion.core.worker.consumer`."""
import logging
import os
import signal
import subprocess
import tempfile
import time
import pytest
import orion.core.io.experiment_builder as experiment_builder
import orion.core.io.resolve_config as resolve... | python |
# Copyright (c) 2021 PaddlePaddle 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 appli... | python |
import time
from os import environ
import grpc
import lnd_grpc.protos.rpc_pb2 as ln
import lnd_grpc.protos.rpc_pb2_grpc as lnrpc
from lnd_grpc.base_client import BaseClient
from lnd_grpc.config import defaultNetwork, defaultRPCHost, defaultRPCPort
# tell gRPC which cypher suite to use
environ["GRPC_SSL_CIPHER_SUITES... | python |
# Generated by Django 2.1.7 on 2019-05-15 13:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("ecommerce", "0010_remove_ecommerce_course_run_enrollment"),
("courses", "0007_add_enrollment_models"),
]
op... | python |
from django.test import TestCase
from django.urls import reverse
from books.models import Book, Genre
class GenresListViewTest(TestCase):
def test_uses_genres_list_template(self):
response = self.client.get(reverse('books:genres-list'))
self.assertTemplateUsed(response, "books/genres_list.html")... | python |
# coding : utf-8
class Route:
def __init__(self, bp, prefix):
self.bp = bp
self.prefix = prefix
| python |
import threading
from concurrent.futures.thread import ThreadPoolExecutor
from altfe.interface.root import interRoot
from app.lib.core.dl.model.dler_aria2 import Aria2Dler
from app.lib.core.dl.model.dler_dl import DlDler
from app.lib.core.dl.model.dler_dl_single import DlSingleDler
@interRoot.bind("dl", "LIB_CORE")
... | python |
from yowsup.layers.protocol_ib.protocolentities.ib import IbProtocolEntity
from yowsup.structs import ProtocolTreeNode
from yowsup.structs.protocolentity import ProtocolEntityTest
import unittest
class IbProtocolEntityTest(ProtocolEntityTest, unittest.TestCase):
def setUp(self):
self.ProtocolEntity = IbPro... | python |
from .general import *
from .run import *
from .project import *
| python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 03:47:45 2020
@author: Maryam
"""
import numpy as np
import argparse
import pickle
import time
from scipy.sparse.linalg import svds
from utils.read_preprocss_data import read_preprocss_data
parser = argparse.ArgumentParser()
# Set Path
parse... | python |
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
import smcat.common
def serializeDateTime(dt):
return smcat.common.datetimeToJsonStr(dt)
class DocumentItem(scrapy.Item):
"""
Attributes:
id: A unique id... | python |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | python |
# -*- coding: utf-8 -*-
#! \file ~/doit_doc_template/templates/base/library/type_page.py
#! \author Jiří Kučera, <sanczes AT gmail.com>
#! \stamp 2019-07-04 09:41:22 +0200
#! \project DoIt! Doc: Sphinx Extension for DoIt! Documentation
#! \license MIT
#! \ve... | python |
import sys
from .commands import main
sys.exit(main())
| python |
import logging
from hearthstone.battlebots.priority_storage_bot import priority_st_ad_tr_bot
from hearthstone.battlebots.random_bot import RandomBot
from hearthstone.host import RoundRobinHost
def main():
logging.basicConfig(level=logging.DEBUG)
host = RoundRobinHost({"random_action_bot":RandomBot(2),
... | python |
BUMP_LIMIT = 20
THREAD_LIMIT = 5
SQL_CONST_OP = 0
MAX_FILE_SIZE = 1 << 21 # 2 MB
MAX_OP_IMG_WH = 250
MAX_IMG_WH = 150
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'tiff', 'bmp'])
MAX_POST_LEN = 5000
class FlaskRestConf(object):
RESTFUL_JSON = {'default': str}
| python |
#!/usr/bin/env python
import glob
import os
import shlex
import sys
import platform
script_dir = os.path.dirname(__file__)
jc3_handling_editor_root = os.path.normpath(os.path.join(script_dir, os.pardir))
sys.path.insert(0, os.path.abspath(os.path.join(jc3_handling_editor_root, 'tools')))
sys.path.insert(0, os.path.j... | python |
from DownloadData import DownloadData, UnzipData
DownloadData()
UnzipData()
| python |
import argparse
from getpass import getpass
from classes.Application import Application
if __name__ == "__main__":
CONFIG_PATH = "./config/config.yaml"
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='function')
# Create accounts parser
parser_create_accounts = subpar... | python |
from django.db import models
from django.contrib.auth.models import User
import uuid
# Question user
class Quser(models.Model):
id= models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
email = models.EmailField(unique=... | python |
## @file
## @brief metacircular implementation in metaL/py
## @defgroup circ Metacircular
## @brief `implementation in metaL/py`
## @{
from metaL import *
## `<module:metaL>` reimplements itself using host VM metainfo
MODULE = vm['MODULE']
## `~/metaL/$MODULE` target directory for code generation
diroot = Dir(MODUL... | python |
# coding=utf-8
"""Provides utilities for serialization/deserialization of
Tempo data types.
"""
from six import string_types
from rest_framework import serializers
from tempo.recurrenteventset import RecurrentEventSet
# pylint: disable=no-init,no-self-use,no-member
class RecurrentEventSetField(serializers.Field):
... | python |
# -*- encoding: utf-8 -*-
#
# Copyright © 2018–2021 Mergify SAS
#
# 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 appl... | python |
import GPyOpt
import chaospy
import matplotlib
import math
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
np.set_printoptions(linewidth=200, precision=4)
def equation(x, selection_index):
target_region = {'x': (0, 1), 'y': (0, 1)}
def function(selection_index, h=1): #1 is just a dummy... | python |
"""Used to plan actions by comparing what is live and what is defined locally.
.. note:: Currently only supported for `AWS CDK`_, `CloudFormation`_,
`Terraform`_, and `Troposphere`_.
When run, the environment is determined from the current git branch
unless ``ignore_git_branch: true`` is specified in the
:r... | python |
import logging
import subprocess
import mlflow
import mlflow.deployments.cli
import pandas as pd
import requests
from mlflow.models.signature import infer_signature
from sklearn.metrics import accuracy_score, precision_score, recall_score, roc_auc_score
from sklearn.pipeline import Pipeline
from dataset import Datase... | python |
'''LC1460: Make Two Arrays Equal by Reversing Sub-arrays
https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/
Given two integer arrays of equal length target and arr.
In one step, you can select any non-empty sub-array
of arr and reverse it. You are allowed to make any
number of steps.
Return T... | python |
import os
import ctypes
import numpy as np
import copy
from envs import make_env
from envs.utils import goal_distance
from policy.replay_buffer import goal_concat
def c_double(value):
return ctypes.c_double(value)
def c_int(value):
return ctypes.c_int(value)
def gcc_complie(c_path, so_path=None):
assert c_path... | python |
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import password_validation
from django.utils.translation import ugettext_lazy as _
from django import forms
from .models import Profile, User
class LoginForm(AuthenticationForm):
username = forms.CharField(label="Username", max_len... | python |
import difflib
import os.path
import subprocess
import sys
from testconfig import config
from functools import partial
from six import print_, iteritems
tests_dir = partial(os.path.join, config['dirs']['tests'])
forth_dir = partial(os.path.join, config['dirs']['forth'])
logs_dir = partial(os.path.join, config['dirs'... | python |
import os
import urllib.parse
basedir = os.path.abspath(os.path.dirname(__file__))
class BaseConfig:
"""Base configuration"""
APP_NAME = 'Sunway Innovators'
DEBUG = False
TESTING = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.environ.get('SECRET_KEY')
UPLOAD_FOLDER = 'uplo... | python |
"""Tests for soft actor critic."""
from absl.testing import absltest
import acme
from acme import specs
from acme.testing import fakes
from acme.utils import loggers
from magi.agents import sac
class SACTest(absltest.TestCase):
def test_sac(self):
# Create a fake environment to test with.
environ... | python |
from abc import ABCMeta, abstractclassmethod
import numpy as np
from keras.layers import Input, Lambda
from keras.models import Model
from model.Autoencoder import Autoencoder
from model.loss.kullbackLeiberLoss import kullbackLeiberLossConstructor
from model.loss.variationalAutoencoderLoss import variationalAutoencod... | python |
import os
from utils import *
DATADIVR_PATH = os.path.realpath(os.path.join(os.path.dirname(os.getcwd()), "DataDiVR"))
LAYOUTS_DIR = os.path.join(DATADIVR_PATH, "viveNet/Content/data/layouts")
LINKS_DIR = os.path.join(DATADIVR_PATH, "viveNet/Content/data/links")
LABELS_DIR = os.path.join(DATADIVR_PATH, "viveNet/Conten... | python |
from app import app
from flask import render_template, request
from forms import GetLucky
from random import randint
@app.route('/')
def lucky_static():
lucky_num = randint(1, 10)
return render_template('simple.html', lucky_num=lucky_num)
@app.route('/<max>/')
def lucky_max(max):
lucky_num = randint(1, int(max))... | python |
import unittest
from stock_prices import fetchStockData
import io
import sys
class TestFileName(unittest.TestCase):
def test_function1(self):
symbol = 'AAPL'
self.assertTrue(fetchStockData(symbol), None)
if __name__ == '__main__':
unittest.main()
| python |
import re
from rdp.symbols import Regexp, flatten
letters = Regexp(r'[a-zA-Z]+')
digits = Regexp(r'[0-9]+')
hexdigits = Regexp(r'[0-9a-fA-F]+')
octdigits = Regexp(r'[0-7]+')
whitespace = Regexp(r'\s+')
word = Regexp(r'[a-zA-Z0-9_]+')
hyphen_word = Regexp(r'[a-zA-Z0-9_-]+')
identifier = Regexp(r'[a-zA-Z_][a-zA-Z0-9_]... | python |
__author__ = 'admin'
import pretender_defaults
import pretend_helpers
class Request:
def __init__(self):
self.url = pretender_defaults.url
self.headers = {}
self.body = pretender_defaults.request_body
self.method = pretender_defaults.method
def set_request_entities(self,request_json):
self.u... | python |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... | python |
# Kubos SDK
# Copyright (C) 2016 Kubos 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 ... | python |
import pygame
import attore
# Classe specifica per i pesci che eredita dalla classe Attore
class Pesce(attore.Attore):
pass
| python |
# -*- coding: utf-8 -*-
"""Various utilities for interacting with the API."""
import os
import re
import pyodbc
from django.conf import settings
from djimix.constants import TERM_LIST
from djimix.core.database import get_connection
from djimix.core.database import xsql
from djpsilobus.core.data import DEPARTMENTS
fr... | python |
#!/usr/bin/env python
import sys
from pyxl.codec.transform import pyxl_invert_string, pyxl_transform_string
if __name__ == '__main__':
invert = invertible = False
if sys.argv[1] == '-i':
invertible = True
fname = sys.argv[2]
elif sys.argv[1] == '-r':
invert = True
fname = ... | python |
"""Support for the PrezziBenzina.it service."""
import datetime as dt
from datetime import timedelta
import logging
from prezzibenzina import PrezziBenzinaPy
import voluptuous as vol
from homeassistant.const import ATTR_ATTRIBUTION, ATTR_TIME, CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeas... | python |
import numpy as np
import skfuzzy as fuzz
class cluster():
def __init__(self,x,y,U,n_clusters):
data = np.reshape(U,(1,-1))
cntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans(data,n_clusters,2,error=0.0001, maxiter=10000, init=None)
self.labels = np.reshape(np.argmax(u,axis=0),U.shape)
self.lab... | python |
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QDialog
from src.ui_elements.bonusingredient import Ui_addingredient
from src.config_manager import shared
from src.logger_handler import LoggerHandler
from src.display_controller import DP_CONTROLLER
from src.database_commander imp... | python |
#!/usr/bin/env python3
# coding: UTF-8
#---------------------------------------------------------------
# author:"Haxhimitsu"
# date :"2021/01/06"
# cite :
#Usage
# python3 src/tf_sample_ver2.0.py --dataset_path "{your input directory}" --log_dir "{your output directry}
#---------------------------------------------... | python |
#!/usr/bin/python3
"""
Defines a class Review.
"""
from models.review import Review
import unittest
import models
import os
class TestReview(unittest.TestCase):
"""Represent a Review."""
def setUp(self):
"""SetUp method"""
self.review = Review()
def TearDown(self):
"""Tea... | python |
import numpy as np
import pandas as pd
import pickle
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
... | python |
#!/usr/bin/env python3.6
# -*- coding:utf-8 -*-
__author__ = 'Lu ShaoAn'
__version__ = '1.0'
__date__ = '2021.05.13'
__copyright__ = 'Copyright 2021, PI'
import torch
res = torch.nn.functional.softmax(torch.tensor([13,9,9], dtype=torch.float32))
print(res) | python |
from drf_yasg.utils import swagger_auto_schema
from product.models import Category, Ingredient, Pizza
from product.serializers import (CategorySerializer, IngredientSerializer,
PizzaSerializer)
from product.utils import resource_checker
from rest_framework import status
from rest_framew... | python |
import streamlit as st
import pandas as pd
import os
import math
st.set_page_config(
page_title="ID4D", layout="wide"
)
#st.write(os.listdir('.'))
open('test.tmp','w').write('test')
st.sidebar.write('The following app will help to select standards should be utilized as part of a foundational identity syst... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# jacobian column s0 s1 e0 e1 w0 w1 w2
# -----------------------------------------
# Imports
# -----------------------------------------
import pdb
import os # used to clear the screen
import math
from numpy import *
from numpy.linalg... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('myapp', '0005_imagedetails'),
]
operations = [
migrations.CreateModel(
name='GoodsList',
fields=[
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.