content stringlengths 5 1.05M |
|---|
name=input("enter your name : ")
print("Name inserted =" , name)
age=int(input("Enter your age"))
print("Age : ",age)
print(type(name))
print(type(age))
|
def password_valid(password):
is_valid = True
counter = 0
if not 6 <= len(password) <= 10:
is_valid = False
print("Password must be between 6 and 10 characters")
for i in password:
if i.isdigit():
counter += 1
if not i.isalpha() and not i.isdi... |
# Copyright 2017 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.
from recipe_engine import recipe_api
class InfraCheckoutApi(recipe_api.RecipeApi):
"""Stateless API for using public infra gclient checkout."""
# Named... |
import tensorflow as tf
import tensorlayer as tl
from rlzoo.common import math_utils
from rlzoo.common.value_networks import *
from rlzoo.common.policy_networks import *
from rlzoo.common.utils import set_seed
'''
full list of algorithm parameters (alg_params)
-----------------------------------------------
net_list... |
import discord
import os
import asyncio
import time
import logging
from discord.ext import commands
from __main__ import settings
from cogs.utils.dataIO import dataIO
reminders_path = "data/remindme/reminders.json"
mod_log_path = 'data/mod/mod.log'
class RemindMe:
"""Pour ne plus rien oublier."""
# _ignore_li... |
from __future__ import print_function
import FWCore.ParameterSet.Config as cms
bmtfStage2Raw = cms.EDProducer(
"L1TDigiToRaw",
Setup = cms.string("stage2::BMTFSetup"),
InputLabel = cms.InputTag("simBmtfDigis","BMTF"),
InputLabel2 = cms.InputTag("simTwinMuxDigis"),
FedId = cms.int32(1376),
FWId... |
# -*- coding: utf-8 -*-
# @Time : 2018/6/16 下午4:43
# @Author : yidxue
from gensim.corpora.Dictionary import load_from_text, doc2bow
from gensim.corpora import MmCorpus
from gensim.models.ldamodel import LdaModel
document = "This is some document..."
# load id->word mapping (the dictionary)
id2word = load_from_text... |
import sys
n = int(input().strip())
sockColors = [int(color) for color in input().strip().split(' ')]
d = dict()
for color in sockColors:
if color not in d:
d[color] = 0
d[color] += 1
count = 0
for key, colorCount in d.items():
count += colorCount // 2
print(count) |
# $Id: programs.py,v 1.1 2011-09-28 19:38:22 wirawan Exp $
#
# pyqmc.nwchem.programs module
#
# Wirawan Purwanto
# Created: 20101028
#
"""
This module contains a general encapsulation of nwchem program.
"""
import sys
import os
import os.path
import time
import wpylib.shell_tools as sh
from wpylib.params import fla... |
from tracker.index_aliases import tracker_index_alias
from tracker.indexers import AttachmentFileIndexer
class TrackerTestCaseMixin(object):
def setUp(self):
tracker_index_alias.write_index.delete(ignore=404)
tracker_index_alias.read_index.create(ignore=400)
def refresh_index(self):
w... |
from __future__ import print_function
import cv2 as cv
import argparse
## [Load image]
parser = argparse.ArgumentParser(description='Code for Histogram Equalization tutorial.')
parser.add_argument('--input', help='Path to input image.', default='../data/lena.jpg')
args = parser.parse_args()
src = cv.imread(args.input... |
"""Entry point for the analysis runner."""
import os
import hailtop.batch as hb
from analysis_runner import dataproc
service_backend = hb.ServiceBackend(
billing_project=os.getenv('HAIL_BILLING_PROJECT'), bucket=os.getenv('HAIL_BUCKET')
)
batch = hb.Batch(name='new-variants-plot-pca', backend=service_backend)
d... |
from setuptools import setup
setup(
name='elementflow',
version='0.5',
author='Ivan Sagalaev',
author_email='maniac@softwaremaniacs.org',
url='https://github.com/isagalaev/elementflow',
license='BSD',
description='Python library for generating XML as a stream without building a tree in memo... |
# This file is part of beets.
# Copyright 2014, Stig Inge Lea Bjornsen.
#
# 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... |
# coding: utf-8
import ee
import time
import ee.mapclient as mc
import matplotlib.pyplot as plt
import sys
from osgeo import ogr
import os
import glob
class WaterProductivityCalc(object):
def __init__(self):
pass
class L1WaterProductivity(WaterProductivityCalc):
def __init__(self):
ee.Initia... |
"""
Command handler
This module contains the infrastructure for accepting commands on the
command line. The process is as follows:
1) The calling object (caller) inputs a string and triggers the command parsing system.
2) The system checks the state of the caller - loggedin or not
3) If no command string was supplied... |
from django import forms
from allauth.account.forms import SignupForm
from django.utils.translation import gettext_lazy as _
class CustomSignupForm(SignupForm):
email = forms.EmailField(label=_("E-mail"),
required=True,
widget=forms.TextInput(
... |
# Author : Ali Snedden
# Date : 5/15/19
# License: MIT
# Purpose:
#
# Notes :
#
# Questions:
#
# References :
#
import time
import sys
import os
import glob
import numpy as np
import subprocess
import shutil
import bisect
from error import exit_with_error
from functions import parse_run_time
from functions import ... |
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn import functional as F
class relative_depth_crit(nn.Module):
def __loss_func_arr(self, z_A, z_B, ground_truth):
mask = torch.abs(ground_truth)
z_A = z_A[0]
a_B = z_B[0]
return mask * torch.log(1 + ... |
import carla
import cv2
import gym
import random
import time
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from agents.navigation.behavior_agent import BehaviorAgent, BasicAgent
from carla import ColorConverter as cc
from collections import deque
from copy import deepcop... |
import pytest
from pkg_resources import resource_filename
import numpy as np
pyhessio = pytest.importorskip("pyhessio")
testfile = 'tests/resources/gamma_test_large_truncated.simtel.gz'
def test_adc_samples():
from eventio import EventIOFile
from eventio.simtel import (
ArrayEvent, TelescopeEvent, AD... |
import unittest
import rubik
import random
class TestRubik(unittest.TestCase):
def setUp(self):
self.turned = {
"left": rubik.cube.Cube("HCDNFVIJELMTPASKUQXZ",
"20010200100102010200"),
"right": rubik.cube.Cube("ACSEMHIDKLUNFQZTPVXJ",
... |
# Notices:
# Copyright 2017, United States Government as represented by the Administrator
# of the National Aeronautics and Space Administration. All Rights Reserved.
# Disclaimers
# No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY
# OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTO... |
from django.db import models
from django.db.models.signals import post_save
from authentication.models import User
# 父类是 django.db.models.base.Model 类
class Profile(models.Model):
"""用户个人简介映射类
"""
user = models.OneToOneField(User, on_delete=models.CASCADE)
url = models.CharField(max_length=50, null=... |
"""Implements the :py:class:`RolesClient` class."""
from datetime import datetime, timezone
from typing import Callable, Optional, List, Dict, Any
from flask import current_app, has_app_context
import pymongo
from .exceptions import InvalidEntity
__all__ = ['RolesClient']
class RolesClient:
"""This class impl... |
#!/usr/bin/env python3
"""
lastcheckpoint is a simple kludge to identify and print out the name
of the last checkpoint TimeSeries produced by a previous run of
ksfdsolver2.py. Typical usage is
export LASTCHECK=`python lastcheckpoint.py checks/checks115/options115e`
The argument (checks/checks115/options115e in t... |
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if -0<n<=2:
return True
s = 1
while s < n:
s = s*2
if s ==n:
return True
return False |
import math
def pages_numbering_with_ink(current, num_of_digits):
while num_of_digits >= 0:
num_of_digits -= int(math.ceil(math.log(current+1, 10)))
current += 1
return current - 2
if __name__ == '__main__':
current = 1
num_of_digits = 5
print(pages_numbering_with_ink(current, nu... |
n = int(input())
d = {}
for i in range(0, n * 2, 2):
name = input()
party = input()
d[name] = [party, 0]
m = int(input())
for i in range(m):
b = input()
for key, val in d.items():
if b == key:
val[1] += 1
lst = sorted([val[1] for key, val in d.items()], reverse=True)
p = []
for key, val in d.item... |
from proteus.default_p import *
from proteus.mprans import RANS2P
import numpy as np
from math import cos
from proteus import Context
ct = Context.get()
domain = ct.domain
nd = domain.nd
mesh = domain.MeshOptions
LevelModelType = RANS2P.LevelModel
if ct.useOnlyVF:
LS_model = None
else:
LS_model = 2
if ct.useR... |
#!/usr/bin/env python
import rospy
from tug_python_utils import YamlHelper as Config
class NominalValue():
"""
Base class for nominal value.
"""
def __init__(self):
pass
def check_hypothesis(self, value):
"""
Should contain the verification of the value based on the define... |
from app import db
from app.models import Rank
SQL_CMD = 'CREATE DATABASE kifutalk CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci'
# initialize database
db.create_all()
# populate ranks table
for i in range(18):
r = Rank(rank_en='%dk'%(18-i), rank_cn='%d级'%(18-i))
db.session.add(r)
for i in range(9):
r = Ran... |
#!/usr/bin/env python
from itertools import groupby
import math
import nltk
import sys
def do_check(filename):
body_grammar = nltk.data.load("file:%s" % filename, 'cfg')
uses = {}
print "Nonterminals with no productions:"
for label,prods in groupby(body_grammar.productions(),
... |
#!/usr/bin/env python
#
# setup.py
#
"""Aberdeen Setup Script"""
from setuptools import setup, find_packages
from importlib.machinery import SourceFileLoader
desc = "Conversion from markdown files to database entries to use as the backend of a blog"
NAME = "aberdeen"
CONSOLE_SCRIPTS = [
'aberdeen-init = aberde... |
from itertools import groupby
S = input()
for key, gr in groupby(S):
print(tuple([len(list(gr)), int(key)]), end=' ') |
from simple_hilbert import *
from advection_block_analytical import *
import space_filling_decomp_new as sfc
import numpy as np # Numpy
import scipy.sparse.linalg as spl
import scipy.linalg as sl
import scipy.sparse as sp
from util import *
def loadsimulation(data_dir, simulaion_steps, simulaion_num, reshape = False... |
#code of the program
#fibonacci series
n=int(input("No. of terms :-" ))
#1st two terms are predefined
a1=0
a2=1
i=0
#applying conditions for correct results
if n<=0:
print("Enter the terms > 0 ")
elif n==1:
print(a1)
else:
#using loops
print("FIBONACCI SERIES :-") #generating the series
while ... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2019 all rights reserved
#
class Value:
"""
Mix-in class to encapsulate nodes that can hold a value.
"""
# value management
def getValue(self, **kwds):
"""
Return my value
"""
# easy enough
... |
import pygame, math, time
from Pendulum import Pendulum, dist, onPath, collide
if __name__ == "__main__":
# Define pygame variables
(width, height) = (640, 480)
background_colour = (255,255,255)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pendulum")
run... |
from abc import ABCMeta, abstractmethod
from six import with_metaclass, integer_types
from functools import partial
from PySide2 import QtWidgets
from . import afnbase
from ..xml import xmlutils
from ..userinterface import qmainmenu, qloggingmenu
import logging
logging.basicConfig()
log = logging.getLogger(__name__)
... |
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
import spconv
from pointnet2.pointnet2_modules import PointnetSAModuleMSG
from pointnet2.pointnet2_utils import furthest_point_sample
from pvrcnn.config import PvrcnnConfig
from pvrcnn.data_classes import Boxes3D
from pvrcnn.roi... |
#!/usr/bin/env python3
# Copyright (c) 2018-2020 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Tests around dash governance objects."""
import json
import time
from test_framework.messages import uin... |
"""
Entradas
salario-->int-->s
categoria-->int-->c
Salidas
aumento-->int-->a
salario nuevo-->int-->sn
"""
s=int(input("Digite el salario:") )
c=int(input("Digite una categoria del 1 al 5: "))
if (c==1):
a=s*.10
if (c==2):
a=s*.15
if (c==3):
a=s*.20
if (c==4):
a=s*.40
if (c==5):
a=s*.60
sn=s+a
prin... |
from magma import *
from mantle.lattice.mantle40.logic import OrN
__all__ = ['DefineEncoder', 'Encoder']
#
# Given an n-bit input array with only a single bit set,
# return the position of the set bit.
#
# NB. The current implementation only works for n<=8
#
def DefineEncoder(n):
assert n <= 8
logn = log2(n)
... |
# Copyright 2017 F5 Networks Inc.
#
# 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 writi... |
#!/usr/bin/env python3
import time, argparse
from learn import main
def get(help, choices=None, default=None):
while True:
i = input(help)
if i:
if choices and i not in choices:
pass
else:
if default == []:
i = i.split()
... |
# coding: utf-8
import json
import uuid
from datetime import datetime
import io
import unicodecsv as ucsv
from django.contrib.auth.models import User
from onadata.apps.logger.models import Instance
from onadata.libs.utils.logger_tools import dict2xml, safe_create_instance
def get_submission_meta_dict(xform, instanc... |
import cv2
import caffe
import tools
import sys
import os
import numpy as np
from functools import partial
import config
def gen_scales(w, h, min_imgsize, net_imgsize):
scales = []
scale = float(net_imgsize) / min_imgsize;
minhw = min(w, h) * scale;
while minhw > net_imgsize:
scales.append(sc... |
# ===========================================================================
# Different topic strategy
# ===========================================================================
from __future__ import print_function, division, absolute_import
topic2T = {
'dsname': ['est', 'fin', 'sam'],
'feats': ['mfcc'],... |
from dataset.jester import Jester
from config import Config
def get_training_set(spatial_transform, temporal_transform,
target_transform):
return Jester(
Config.dataset_path,
Config.annotation_path,
'training',
spatial_transform=spatial_transform,
tempor... |
"""Copyright 2011 The University of Michigan
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 writi... |
#!/usr/bin/env python3
from aws_cdk import core as cdk
from stacks.base_stack import BaseStack
from stacks.databases_stack import DatabasesStack
from stacks.lakeformation_stack import LakeFormationStack
from stacks.opensearch_stack import OpenSearchStack
app = cdk.App()
base = BaseStack(app, "aws-data-wrangler-base")... |
__version__ = '0.9.4d1'
|
from Queue import Queue
import comms
import cPickle
import nav
import threading
import time
GRAPH_FILE = 'graph.txt'
G = cPickle.load(open(GRAPH_FILE))
BASE_VALUE = 0
READY_VALUE = 1
ERROR_VALUE = 2
task_queue = Queue()
car_queue = Queue()
car_task_locations = {}
class Car(threading.Thread):
""" Object that mainta... |
import json
from os.path import join, isfile
from .targets import DirectoryTarget, NamedVolumeTarget, TargetOptions
root_path = "/bb8/etc/"
source_config_path = join(root_path, "source-config.json")
config_path = join(root_path, "config.json")
ssh_key_path = join(root_path, "secrets/ssh_key")
host_key_path = join(roo... |
from textwrap import dedent
import pytest
from pylox.lox import Lox
# Base cases from https://github.com/munificent/craftinginterpreters/blob/master/test/constructor/arguments.lox
TEST_SRC = dedent(
"""\
class Foo {
init(a, b) {
print "init"; // expect: init
this.a = a;
this.b =... |
import sys
import unittest
import numpy as np
import os
from shutil import rmtree
try:
from concurrent import futures
except ImportError:
futures = False
try:
import z5py
except ImportError:
sys.path.append('..')
import z5py
class TestUtil(unittest.TestCase):
tmp_dir = './tmp_dir'
shape ... |
import cv2
import numpy as np
resim = cv2.imread("ati.JPG")
cv2.imshow("resim",resim)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
num_list = [int(x) for x in input().split()]
sum = int(input("Enter the sum: "))
low = 0
hi = len(num_list)-1
found = False
while low<hi:
s = num_list[low]+num_list[hi]
if s==sum:
found = True
break
elif s<sum:
if num_list[low]<num_list[hi]:
low +=1
else:
hi -=1
else:
if num_list[low]>num_list[hi]:
... |
# -*- coding:utf8 -*-
# Performance optimization model(Maybe Only Linux)
if __name__ == "__main__":
from main import app
from werkzeug.contrib.profiler import ProfilerMiddleware
from config import GLOBAL
Host = GLOBAL.get('Host')
Port = GLOBAL.get('Port')
app.config['PROFILE'] = True
app.ws... |
from django.conf.urls import patterns, url
urlpatterns = patterns('betty.image_browser.views',
url(r'^search.html$', 'search'), # noqa
url(r'^upload\.html$', 'upload'),
url(r'^crop\.html$', 'crop'),
)
|
import datetime
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from aimsbackend.models import Students, Courses, Subjects, CustomUser, Attendance, At... |
import ccobra
from Modal_Logic.ccobra_adapter import ccobra_to_assertion
from Modal_Logic.solver import does_a_follow_from_b
class MentalModel(ccobra.CCobraModel):
def __init__(self, name='Modal Logic System S4'):
super(MentalModel, self).__init__(
name, ['modal'], ['verify'])
def predict... |
# Read from file, announce on the web, irc, xml-rpc
from twisted.application import internet, service, strports
from twisted.internet import protocol, reactor, defer, endpoints
from twisted.words.protocols import irc
from twisted.protocols import basic
from twisted.web import resource, server, static, xmlrpc
import cgi... |
from django.shortcuts import redirect
from django.http import JsonResponse
from django.core import serializers
from django.contrib import messages
class ReviewAjaxFormMixin(object):
def form_invalid(self, form):
response = super(ReviewAjaxFormMixin, self).form_invalid(form)
if self.request.is_ajax... |
import cv2
import numpy as np
from tensorflow.keras.models import load_model
from image_utils import preprocess
model = load_model('./model.h5')
print(model.summary())
img = cv2.imread('/home/sajith/Documents/Acedamic/self-driving-car/data/data/IMG/center_2021_01_12_13_20_30_027.jpg')
cv2.imshow('tem', img)
img = p... |
###############################################################################
# WaterTAP Copyright (c) 2021, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory, Oak Ridge National
# Laboratory, National Renewable Energy Laboratory, and National Energy
# Technology Laboratory ... |
#######################################
# 文字列の操作
#######################################
def f1(a, b):
# 文字列aとbを連結してxに代入せよ
# (次の行を書き換える)
x = ""
return x
def f2(s):
# 文字列sの、左から数えて3文字目を取り出してxに代入せよ
# 例: "abcdefg" => "c"
# (次の行を書き換える)
x = ""
return x
def f3(s):
# 文字列sの、左から数えて3文... |
"""
Jinsung Yoon (9/13/2018)
PATE-GAN: Synthetic Data Generation
"""
import numpy as np
from PATE_GAN import PATE_GAN
import argparse
import os
import time
import pandas as pd
import initpath_alg
initpath_alg.init_sys_path()
import utilmlab
# gpu_frac = 0.5
# config = tf.ConfigProto()
# config.gpu_options.per_proces... |
import datetime
import unittest
from unittest import mock
from aprsd import messaging
class TestMessageTrack(unittest.TestCase):
def setUp(self) -> None:
config = {}
messaging.MsgTrack(config=config)
def _clean_track(self):
track = messaging.MsgTrack()
track.data = {}
... |
#!/usr/bin/env ipython
import sys, unittest
import numpy as np
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class DotTestCase(unittest.TestCase):
"""A test fixture for numpy's dot products"""
def setUp(self):
"""Establish our fixture"""
n = 4
self.x... |
"""
Time:2019-2-26
Author:pengfei
Motivation:for training on a csv dataset
"""
"""csv Dataset Classes
Original author: Francisco Massa
https://github.com/fmassa/vision/blob/voc_dataset/torchvision/datasets/voc.py
Updated by: Ellis Brown, Max deGroot
"""
from .config import HOME
import os.path as osp
import sys
import... |
# for more information on how to install requests
# http://docs.python-requests.org/en/master/user/install/#install
import requests
import json
# TODO: replace with your own app_id and app_key
app_id = '-'
app_key = '-'
def get_meaning(word):
language = 'en'
word_id = str(word)
url = 'https://od-api.oxfo... |
#/usr/bin/python
# senderclient.py - this file is part of dailyimage
# Log in and send emails to clients
import sys # argv, exit
import smtplib # for email ...
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.mime.image import MIMEImage
from... |
import numpy as np
import pandas as pd
import matplotlib.image as mpimg
from typing import Tuple
from .config import _dir
_data_dir = '%s/input' % _dir
cell_types = ['HEPG2', 'HUVEC', 'RPE', 'U2OS']
positive_control = 1108
negative_control = 1138
nsirna = 1108 # excluding 30 positive_control + 1 negative_control
pl... |
"""
Unified interfaces to minimization algorithms.
Functions
---------
- minimize : minimization of a function of several variables.
"""
__all__ = ['minimize', 'show_minimize_options']
from warnings import warn
# unconstrained minimization
from optimize import _minimize_neldermead, _minimize_powell, \
_mi... |
#!/usr/bin/env python
import numpy as np
import unittest
import pyphil
class tick_tack_toe_board:
"""
Does things pertaining to current board position. X moves first, O moves second in all cases.
X and O are represented by the type variable
"""
def __init__(self,rows=3,cols=3):
# for printing the board
self.... |
import logging
import torch
from torch import nn
from .base_mapping import MappingBase
logger = logging.getLogger(__name__)
class ProjectionMapping(MappingBase):
"""
A class for simple contextualization of word-level embeddings.
Runs an untrained BiLSTM on top of the loaded-from-disk embeddings.
""... |
import time
import xnmt.loss
from xnmt.vocab import Vocab
from xnmt.events import register_xnmt_handler, handle_xnmt_event
from xnmt import logger, yaml_logger
class LossTracker(object):
"""
A template class to track training process and generate report.
"""
REPORT_TEMPLATE = 'Epoch {epoch:.4f}: {d... |
import os
import glob
import subprocess
import random
import unittest
import time
import numpy as np
import readingdb as rdb
# make sure we're testing the version of readingdb in this dir.
assert os.path.dirname(os.path.abspath(rdb.__file__)) == \
os.path.dirname(os.path.abspath(__file__))
datadir = '_testdata'
... |
"""This module is useful to clean the firestore tables during the tests.
Thousands of entries could be generated and it won't be possible to remove them
from the Firestore UI
"""
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compl... |
import boto3
import os
import json
region = 'us-east-2'
instances = list(json.loads((os.environ['EC2_INSTANCES'])).values())
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances)) |
from sensors.interfaces import GPIOs
from sensors.tachometer import Tachometer
GPIO_ADDRESS_A = 15
gpios = GPIOs([GPIO_ADDRESS_A, ])
interfaces = {
'gpios': gpios,
}
encoder = Tachometer(interfaces)
print(encoder.get_value())
|
class Solution(object):
def XXX(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.search(root) != -1
def search(self, root):
if not root:
return 0
l_left = self.search(root.left)
if l_left == -1:
return -1
... |
#!/usr/bin/env python
import os
import sys
from flask_script import Manager
from {{cookiecutter.module_name}} import create_app
from {{cookiecutter.module_name}}.database import MyDatabase
sys.path.insert(0, os.getcwd())
manager = Manager(create_app)
@manager.command
def initdb():
try:
# FIXME replac... |
from .stickers import *
__red_end_user_data_statement__ = "No personal data is stored."
def setup(bot):
bot.add_cog(Stickers(bot))
|
from django.test import TestCase
from smartfields.dependencies import FileDependency
class MiscTestCase(TestCase):
def test_file_dependency(self):
self.assertEqual(
FileDependency(storage='foo', upload_to='somewhere', keep_orphans=True),
FileDependency(storage='foo', upload_to='so... |
import IceRayPy
def Translate(
P_dll
,P_child : IceRayPy.core.object.Wrapper
,P_move
):
pretender = core.geometry.Pretender( P_dll, P_child.cast2Geometry(), P_child )
translator = core.geometry.transform.Translate( P_dll, pretender )
translator.move( P_move )
result = IceRa... |
class Messages:
def __init__(self, database):
self.database = database
@property
def required_tables(self) -> dict:
return {
'message': {
'columns': [
'id BIGINT NOT NULL',
'channel_id BIGINT NOT NULL',
... |
import pytest
def test_qtdatavisualization():
"""Test the qtpy.QtDataVisualization namespace"""
# Using import skip here since with Python 3 you need to install another package
# besides the base `PyQt5` or `PySide2`.
# For example in the case of `PyQt5` you need `PyQtDataVisualization`
# QtDataV... |
from laserpony import app
from flask.ext.bcrypt import Bcrypt
from flask_login import LoginManager
from flask.ext.markdown import Markdown
from flask_mongoengine import MongoEngine
from itsdangerous import URLSafeTimedSerializer
#Bcrypt
bcrypt = Bcrypt(app)
#Login Manager
login_manager = LoginManager(app)
login_manag... |
import scrapy
from datetime import datetime
from spoon.items import SinaTopSummaryItem
class SinatopsummarySpider(scrapy.Spider):
name = 'sinaTopSummary'
allowed_domains = ['weibo.com']
start_urls = ['https://s.weibo.com/top/summary/']
def parse(self, response):
print(response.url)
l... |
import logging
import os
import re
import sys
import xml.etree.ElementTree as ET
import czech_stemmer
from RDRPOSTagger_python_3.pSCRDRtagger.RDRPOSTagger import RDRPOSTagger
from RDRPOSTagger_python_3.Utility.Utils import readDictionary
os.chdir('../..') # because above modules do chdir ... :/
from rouge_2_0.rouge_... |
"""A program for simulating personal finances."""
from argparse import ArgumentParser
from .simulation import Simulation
def main():
"""Simulates personal finances."""
parser = ArgumentParser(description="Simulate personal finances.")
parser.add_argument(
"--start",
metavar="YEAR",
... |
# This module enables a test to provide a handler for "hooked://..." urls
# passed into serial.serial_for_url. To do so, set the value of
# serial_class_for_url from your test to a function with the same API as
# ExampleSerialClassForUrl. Or assign your class to Serial.
from . import NoOpSerial
def ExampleSerialClas... |
import os
import threading
import socket
import select
import time
import queue
import cwipc
class _Sink_Passthrough(threading.Thread):
FOURCC="cwiU"
SELECT_TIMEOUT=0.1
QUEUE_FULL_TIMEOUT=0.001
def __init__(self, sink, verbose=False, nodrop=False):
threading.Thread.__init__(self)... |
import logging
from .articleparser import ArticleParser
from crawler.webpage import WebPage
from pony.orm import db_session
from bs4 import BeautifulSoup
from data import Article, Author
from text_processing import TextProcessor
import re
import dateutil.parser
import urllib.parse
class ArxivParser(ArticleParser):
... |
#!/usr/bin/env python2.7
import json
import os
import sys
import auth
import common
def jsonrpc_change_password():
"""Accept a JSONRPC-style change password, with parameters like so:
{"jsonrpc":"2.0","method":"use.setpassword","params":["username","password", "oldpassword"],"id":1}
On successful login, ... |
WARNING = 'Warning'
print('DunderImported:', __name__) |
#!/usr/bin/env python3
import collections
import glob
import os
import subprocess
import sys
import numpy as np
import pandas as pd
batch_size = int(sys.argv[1])
n_iterations = 3
if __name__ == '__main__':
for root, dirs, files in os.walk('./'):
data_sets = dirs
for data_set in data_sets:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.