content string |
|---|
#!/usr/bin/env python2.6
import os
import sys
import plistlib
import commands
import time
from string import Template
app = "build/Release/CoStats.app"
plist = plistlib.readPlist("%s/Contents/Info.plist" % app)
version = plist["CFBundleVersion"]
version_string = plist["CFBundleShortVersionString"]
dmgfile = "CoStats-... |
"""
QuadTree data structure
"""
def normalize_rect(rect):
x1, y1, x2, y2 = rect
if x1 > x2:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
return (x1, y1, x2, y2)
class QuadNode:
def __init__(self, item, rect):
self.item = item
self.rect = rect
class QuadTree... |
from uuid import uuid4
from Firefly import logging, scheduler
from Firefly.components.virtual_devices import AUTHOR
from Firefly.const import (COMMAND_UPDATE, DEVICE_TYPE_THERMOSTAT, LEVEL)
from Firefly.helpers.action import Command
from Firefly.helpers.device.device import Device
from Firefly.helpers.metadata.metadat... |
"""Utility functions."""
import warnings
import numpy as np
import xarray as xr
def replace_coord(arr, old_dim, new_dim, new_coord):
"""Replace a coordinate with new one; new and old must have same shape."""
new_arr = arr.rename({old_dim: new_dim})
ds = new_arr.to_dataset(name='new_arr')
ds[new_dim] ... |
#!/usr/bin/python
# This is python 2.7 on macOS 10.12.
from __future__ import print_function
from sharedstate import get_socket, wait
import api_pb2
import session
import _socket as socket
import logging
class AbstractTab(object):
def __repr__(self):
raise NotImplementedError("unimplemented")
def get_tab_id... |
'''
zendesk config
'''
ZENDESK_SUBDOMAIN = 'your_zendesk_domain'
ZENDESK_EMAIL = '<EMAIL>'
ZENDESK_TOKEN = ''
URL_LIST_CATEGORIES = None
'''
gengo config
'''
GENGO_PUBLIC_KEY = ''
GENGO_PRIVATE_KEY = ''
GENGO_API_URL = 'http://api.gengo.com/v2/translate/'
TRANSLATION_RESPONSE_DIR = "gen/gengo_translations/"
... |
from collections import deque
import numpy as np
from scipy.spatial.distance import cdist
def precision_recall(swc1, swc2, dist1=4, dist2=4):
'''
Calculate the precision, recall and F1 score between swc1 and swc2 (ground truth)
It generates a new swc file with node types indicating the agreement between tw... |
"""
Classes and functions for the output of reference policy modules.
This module takes a refpolicy.Module object and formats it for
output using the ModuleWriter object. By separating the output
in this way the other parts of Madison can focus solely on
generating policy. This keeps the semantic / syntactic issues
cl... |
import os
from .base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(SITE_ROOT, 'dev.db'),
}
}
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
}
BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis:/... |
'''
Objects for parsing a list of HTTPFlows into data suitable for writing to a
HAR file.
'''
import logging
from datetime import datetime
from pcaputil import ms_from_timedelta, ms_from_dpkt_time
import json
class Page:
'''
Represents a page entry in the HAR. Requests refer to one by its url.
Members:
title... |
from protocol import States, Lists, PrivacyModes
from time import time
class Group:
"""A group in the friend list"""
def __init__(self, id, name, friends = None):
self.id = id
self.name = name
if friends == None:
friends = {}
self.friends = friends
d... |
import os.path
from os import remove
import datetime
import h5py
import gc
import nose.tools as nt
import numpy as np
from hyperspy.io import load
from hyperspy.signal import Signal
from hyperspy.roi import Point2DROI
from hyperspy.datasets.example_signals import EDS_TEM_Spectrum
my_path = os.path.dirname(__file__)
... |
#!/usr/bin/env python
"""User dashboard tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from future.builtins import range
from grr_response_core.lib import rdfvalue
from grr_response_server.gui import gui_test_lib
from grr.t... |
from trac.core import *
from trac.perm import IPermissionPolicy, IPermissionRequestor
revision = "$Rev: 6669 $"
url = "$URL: https://svn.edgewall.org/repos/trac/trunk/sample-plugins/permissions/vulnerability_tickets.py $"
class SecurityTicketsPolicy(Component):
"""Prevent public access to security sensitive ticke... |
import os
import os.path
import fnmatch
import logging
import ycm_core
BASE_FLAGS = [
'-Wall',
'-Wextra',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-ferror-limit=10000',
'-DNDEBUG',
'-std=c99',
'-I/usr/lib/',
'-I/usr/include/',
'-I.',
'-Wno-und... |
from codecs import open as codecs_open
from setuptools import setup, find_packages
# Get the long description from the relevant file
try:
with codecs_open('README.rst', encoding='utf-8') as f:
long_description = f.read()
except:
# @todo for now, fall back to this - pex fails to resolve the README
... |
# c: 19.05.2008, r: 19.05.2008
filename_mesh = 'database/phono/mesh_circ21.mesh'
is3d = False
if is3d:
dim, geom = 3, '3_4'
else:
dim, geom = 2, '2_3'
field_1 = {
'name' : 'scalar_field',
'dim' : (1,1),
'domain' : 'Omega',
'bases' : {'Omega' : '%s_P1' % geom}
}
field_2 = {
'name' : 'vect... |
def load_microbial_data( GALAXY_DATA_INDEX_DIR, sep='\t' ):
# FIXME: this function is duplicated in the DynamicOptions class. It is used here only to
# set data.name in exec_after_process().
microbe_info= {}
orgs = {}
filename = "%s/microbial_data.loc" % GALAXY_DATA_INDEX_DIR
for i... |
import pygame
import random
from game_defines import *
class LevelMap(object):
def __init__(self, map_object, actors, level_assets):
self.map_object = map_object
self.actors = actors
self.map_surface = None
self.assets = level_assets
self.tile_image = { 'x': self.assets['... |
"""
Jonathan Reem
January 2014
Functional programming utility functions.
"""
# pylint: disable=C0103, W0142, W0622
from infix import Infix
from collections import namedtuple
Unit = namedtuple("Unit", "")
def curry(func, args):
"Curries a function."
return lambda *a: func(args + a)
def const(first, _):
... |
# -*- coding: utf-8 -*-
"""
@author: smorante
"""
import numpy as np
from sklearn import preprocessing
from scipy import stats
import matplotlib.pyplot as plt
def sumAll(demo1, demo2, method):
# print "Shapes demo1,demo2: ", np.array(demo1).shape, " , ", np.array(demo2).shape
if np.array(demo1).shape[0] > 1... |
+#Задача №12, Вариант 30
+#Разработайте игру "Крестики-нолики". (см. М.Доусон Программируем на Python гл. 6)
+
+#Шеменев Андрей.
+#25.04.2016
+def display_instruct():
+ print('''
+ Добро пожаловать на ринг грандиознейших интеллектуальных состязаний всех времён.
+ Твой мозг и мой процессор сойдутся в схватке з... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import netsvc
class ineco_start_workorder(osv.osv_memory):
_name = 'ineco.start.workorder'
_description = 'Wizard Start Workorder'
_columns = {
}
def update_data(self, cr, uid, ids, context=None):
... |
"""
HTML component editor in studio
"""
from six.moves import zip
from common.test.acceptance.pages.common.utils import click_css
from common.test.acceptance.pages.studio.utils import get_codemirror_value, type_in_codemirror
from common.test.acceptance.pages.studio.xblock_editor import XBlockEditorView
class HtmlX... |
# Demo Python Class for HTTP Event Collector of Splunk Enterprise 6.4.x
# Version 0.9.01
# Support JSON, RAW data inputs and Indexer acknowledgment
# Reference: http://docs.splunk.com/Documentation/Splunk/6.4.2/Data/UsetheHTTPEventCollector
# Disclaimer: This is not a official Splunk solution and with no liability. Use... |
from sqlalchemy import func
from sqlalchemy import Text
from sqlalchemy import Column
from sqlalchemy import String
from sqlalchemy import Integer
from sqlalchemy import DateTime
from sqlalchemy import Foreig... |
#!/usr/local/bin/python3
import os
import re
import subprocess
import os.path
import sys
def iterate_audio(path="."):
for root, dirs, files in os.walk(path, topdown=False):
for name in files:
print(name)
if re.search(".mp3",name):
print(name+"found")
... |
import sys
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
import setuptools
from pip import req
from setuptools.command import test
REQ = set([dep.name
for dep in req.parse_requirements('requirements/base.txt')])
TREQ = set([dep.name ... |
"""Tests for the Meteo-France config flow."""
from unittest.mock import patch
from meteofrance_api.model import Place
import pytest
from homeassistant import data_entry_flow
from homeassistant.components.meteo_france.const import (
CONF_CITY,
DOMAIN,
FORECAST_MODE_DAILY,
FORECAST_MODE_HOURLY,
)
from h... |
from __future__ import unicode_literals
from moto.core.exceptions import JsonRESTError
class SecretsManagerClientError(JsonRESTError):
code = 400
class ResourceNotFoundException(SecretsManagerClientError):
def __init__(self):
self.code = 404
super(ResourceNotFoundException, self).__init__(
... |
#
#
# Provides a convenient class for displaying patterns on the PiGlow:
# - includes a smooth transition between patterns
# - a more intuitive structure for the pattern, which is mapped onto
# the led values
from piglow import PiGlow
import time
class GlowShow(object):
piglow = PiGlow(1)
led_val =... |
"""
The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104
(3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has
exactly three permutations of its digits which are also cube.
Find the smallest cube for which exactly five permutations of its digits are
cube.
"""
if __n... |
from f5.bigip import ManagementRoot
from heat.common.i18n import _
from heat.engine import properties
from heat.engine import resource
from requests import HTTPError
class BigIPConnectionFailed(HTTPError):
pass
class F5BigIPDevice(resource.Resource):
'''Holds BigIP server, username, and password.'''
PR... |
from __future__ import unicode_literals
from datetime import datetime
import importlib
import jwt
def jwt_payload_handler(user):
from jwt_auth import settings
try:
username = user.get_username()
except AttributeError:
username = user.username
return {
'user_id': user.pk,
... |
from dependencies.dependency import ClassSecurityInfo
from lims import bikaMessageFactory as _
from lims.utils import t
from lims.browser.widgets.datetimewidget import DateTimeWidget
from lims.config import PRICELIST_TYPES, PROJECTNAME
from lims.content.bikaschema import BikaFolderSchema
from lims.interfaces import IPr... |
# -*- coding: utf-8 -*-
import json
import datetime
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from misc.decorators import staff_required, common_ajax_response, verify_permission
from common import cache, debug, page
from message.in... |
import os
import glob
import re
printVID = False
def read_line(filename):
"""help function to read a single line from a file. returns none"""
line = "Unknown"
try:
with open(filename) as f:
line = f.readline().strip()
finally:
return line
def re_group(regexp, text):
""... |
"""
Asset compilation and collection.
"""
from __future__ import print_function
import argparse
from paver.easy import sh, path, task, cmdopts, needs, consume_args, call_task, no_help
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
import glob
import traceback
import os
f... |
from __future__ import absolute_import, division, print_function, unicode_literals
import textwrap
import unittest
from pants.option.config import Config
from pants.util.contextutil import temporary_file
class ConfigTest(unittest.TestCase):
def setUp(self):
self.ini1_content = textwrap.dedent(
"""
... |
import os
import datetime
import json
import rados
import rbd
def main():
module = AnsibleModule(
argument_spec=dict(
state=dict(choices=['present', 'absent'], default='present'),
name=dict(required=True),
pool=dict(),
id=dict(),
options=dict(),
... |
"""WebSubmit Admin Regression Test Suite."""
__revision__ = "$Id$"
from invenio.testutils import InvenioTestCase
from invenio.config import CFG_SITE_URL
from invenio.testutils import make_test_suite, run_test_suite, \
test_web_page_content, merge_error_messages
from invenio.websubmitadm... |
'''
@author Sergey Chikuyonok (<EMAIL>)
@link http://chikuyonok.ru
'''
import re
re_word = re.compile(r'^[\w\-:\$]+')
re_attr_string = re.compile(r'^(["\'])((?:(?!\1)[^\\]|\\.)*)\1')
re_valid_name = re.compile(r'^[\w\d\-_\$\:@!]+\+?$', re.IGNORECASE)
def char_at(text, pos):
"""
Returns character at specified index ... |
import functools
import glob
import importlib
import importlib.util as import_util
import os.path
from squabble import logger, UnknownRuleException
def _load_plugin(directory):
"""
Given an arbitrary directory, try to load all Python files in order
to register the custom rule definitions.
Nothing is... |
import os
import unittest
from pygridspot import *
class TestInstanceList(unittest.TestCase):
def test_updates(self):
instances1 = {
"instances": [{
"instance_id": "inst_CP2WrQi2WIS4iheyAVkQYw",
"vm_num_logical_cores": 8,
"vm_num_physical_cores":... |
# -*- coding: utf-8 -*-
import os
import serial
import socket
import re
import time
import logging
import json
import hashlib
import sys
import cPickle as pickle
from user import User
APP_NAME = "WyboClient"
# User settings
DATA_FILE_LOCATION = "data/"
DATA_FILE_NAME = "user.json"
# Client serial port settings
CLIEN... |
"""Unit tests for the :class:`iris.coord_systems.TransverseMercator` class."""
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests
from iris.coord_systems import TransverseMercator
class Test_init_defaults(tests.IrisTest):
# NOTE: most of... |
try:
import httplib as hl
except ImportError:
import http.client as hl
import json
import logging
from random import randint
import time
import datetime
import requests
from .access_token import AccessToken
from .authentication_client import AuthenticationClient
from .rest_client_utils import RestClientUtils
... |
import random
import json
import requests
names_file = 'data/names.txt'
domains_file = 'data/domains.txt'
HOSTNAME = 'http://dry-beach-2224-staging.herokuapp.com'
#HOSTNAME = 'http://127.0.0.1:3000'
class User(object):
PASSWORD = 'qwerty1234'
def __init__(self, name, domain):
self.name = name.rstri... |
from pycp2k.inputsection import InputSection
class _each214(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Just_energy = None
self.Powell_opt = None
self.Qs_scf = None
self.Xas_scf = None
self.Md = None
self.Pint = None
self.Meta... |
from mrjob.job import MRJob
from mrjob.step import MRStep
from math import *
import sys
import pickle
from datetime import datetime, timedelta, time
import csv
from planar import Polygon
NODE_WEEKEND_D = "weekenddropoff.csv"
NODE_WEEKEND_P = "weekendpickup.csv"
NODE_WEEKDAY_D = "weekdaydropoff.csv"
NODE_WEEKDAY_P = "... |
import pickle
import numpy as np
import json
sentence = "I feel a little bit tired today , but I am really happy !"
sentence_neg = "Although the rain stopped , I hate this thick cloud in the sky ."
x_text = [line.split('\t')[2] for line in open('../data/s17/tst', "r").readlines()][:20]
x_text.append(sentence)
x_text.... |
import os, pytest
import do_grader
submission_dirs = []
for wd, directory, files in os.walk('.'):
for file in files:
if file == 'submission.sub':
submission_dirs.append(wd.split('/')[-1])
del wd, directory, files
print(submission_dirs)
@pytest.mark.parametrize("submission_dir", submission_... |
from functools import partial
from dateutil import rrule
from corehq.apps.locations.dbaccessors import get_one_user_at_location
from corehq.apps.locations.models import SQLLocation, Location
from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn
from corehq.apps.users.models import CommCareUser
f... |
"""
SPDX-License-Identifier: MIT
Install augur package with pip.
"""
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, "README.md"), encoding="utf-8") as f:
long_description = f.rea... |
import web
from libweasyl.configuration import configure_libweasyl
from weasyl.media import format_media_link
import weasyl.define as d
import weasyl.macro as m
import weasyl.middleware as mw
import weasyl.controllers.urls
web.config.debug = False
app = web.application(weasyl.controllers.urls.controllers, globals())
... |
from flask import url_for
from grano.core import app
from grano.model import Project
from grano.interface import Startup
from grano.es.view import blueprint
from grano.es.indexer import Indexer
script_indexer = Indexer()
class Configure(Startup):
def configure(self, manager):
#manager.add_command("ass... |
import email.utils
import traceback
import hashlib
import logging
import json
import requests
from datapackage import DataPackage
from tableschema_sql import Storage
from os_api_cache import get_os_cache
from .callbacks import *
from .model_registry import ModelRegistry
from .config import get_engine
from .fdp_utils ... |
"""
stage4 target, builds upon previous stage3/stage4 tarball
"""
# NOTE: That^^ docstring has influence catalyst-spec(5) man page generation.
from catalyst.base.stagebase import StageBase
class stage4(StageBase):
"""
Builder class for stage4.
"""
def __init__(self,spec,addlargs):
self.required_values=["stage... |
# encoding: utf-8
import os
from pypi_server.cache import Cache, DAY
from tornado.gen import coroutine, Return
from tornado_xmlrpc.handler import XMLRPCHandler
from pypi_server.handlers import route, add_slash
from pypi_server.handlers.base import BaseHandler, threaded
from pypi_server.handlers.pypi.proxy.client import... |
import sys
import json
# Map start block to current allocation info.
current_heap = {}
allocation_history = []
root = {}
def change_root(trace, size):
level = root
for frame in reversed(trace):
file_location = frame[1]
if file_location not in level:
level[file_location] = {"blocks"... |
#!/usr/bin/env python
import logging
import os
import shutil
import unittest
from ansibullbot.wrappers.ghapiwrapper import GithubWrapper
from ansibullbot.wrappers.issuewrapper import IssueWrapper
class GithubMock(object):
def get_repo(self, full_name):
gr = GithubRepoMock(full_name)
return gr
c... |
import os
import re
import shlex
def conf(filename='.env', force=False):
with open(filename) as f:
content = f.read()
envvars = parse(content)
updateenv(os.environ, envvars, force)
def parse(content):
"""
Parse the content of a .env file (a line-delimited KEY=value format) into a
dic... |
import collections
import numpy as np
import pytest
from pandas import Series
import pandas._testing as tm
class TestSeriesToDict:
@pytest.mark.parametrize(
"mapping", (dict, collections.defaultdict(list), collections.OrderedDict)
)
def test_to_dict(self, mapping, datetime_series):
# GH#... |
"""ShutIt module. See http://shutit.tk
"""
from shutit_module import ShutItModule
class cabal(ShutItModule):
def is_installed(self, shutit):
return shutit.file_exists('/root/shutit_build/module_record/' + self.module_id + '/built')
def build(self, shutit):
shutit.send('apt-get install -y ghc haddock')
shu... |
# -*- coding: utf-8 -*-
"""
Long term target tracking.
---
type:
python_module
validation_level:
v00_minimum
protection:
k00_public
copyright:
"Copyright 2016 High Integrity Artificial Intelligence Systems"
license:
"Licensed under the Apache License, Version 2.0 (the License);
you may not ... |
import datetime
from nose.tools import eq_, ok_
import mock
from django.contrib.auth.models import User, Group
from django.conf import settings
from django.utils import timezone
from django.core.urlresolvers import reverse
from airmozilla.base.tests.testbase import Response, DjangoTestCase
from airmozilla.manage.twe... |
# Time: O(1)
# Space: O(1)
# A binary watch has 4 LEDs on the top which represent the hours (0-11),
# and the 6 LEDs on the bottom represent the minutes (0-59).
#
# Each LED represents a zero or one, with the least significant bit
# on the right.
#
# For example, the above binary watch reads "3:25".
#
# Given a non-n... |
"""Test utils"""
import os
from pathlib import Path
from subprocess import check_call
from niworkflows.utils.misc import _copy_any, clean_directory
def test_copy_gzip(tmpdir):
filepath = tmpdir / "name1.txt"
filepath2 = tmpdir / "name2.txt"
assert not filepath2.exists()
open(str(filepath), "w").close(... |
import datetime
import string
import random
from django.utils import timezone
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django import forms
# Create your models here.
class Venue(models.Model):
venue_n... |
from unittest import TestCase
from machine import Rule, Halt, Machine
class Test_Machine(TestCase):
def test_create_rule(self):
r = Rule(current_state='A', read_symbol=0, write_symbol=1,
shift_right=True, next_state="B")
r2 = Rule("A", 0, 1, True, "B")
self.assertEqual(r, r2... |
#!/usr/bin/env python3
# requirement: a unique train for each given bitmap day and UID
import sys
from datetime import datetime, date, timedelta, time, MINYEAR
import json
from iso8601datetime.duration import duration_p, fromisoday_p, ISO8601_DATE, duration_f
from iso8601datetime.interval import interval_f, interval_... |
#from django.contrib.auth import authenticate, login, get_user
#from backends import authenticate, get_user
import logging
from backends import WEBIDAuthBackend
from django.contrib.auth import login
from django.contrib.auth import get_user
from django.contrib.auth.models import AnonymousUser
from django.conf import se... |
from odoo.addons.mrp.tests.common import TestMrpCommon
from odoo.exceptions import UserError
class TestProcurement(TestMrpCommon):
def test_procurement(self):
"""This test case when create production order check procurement is create"""
# Update BOM
self.bom_3.bom_line_ids.filtered(lambda ... |
#!/usr/bin/env python
import sys
import os.path
import ColumnMap
import Mapping
import Execution
from collections import defaultdict
import pprint, json, csv
def writeOutput(AllExecutions):
if "--json" in sys.argv:
writeJSON(AllExecutions)
elif "--summary" in sys.argv:
writeCSVList(AllExecutions)
else:
write... |
""" A page functions for Availability Zone
"""
from functools import partial
from navmazing import NavigateToSibling, NavigateToAttribute
from cfme import BaseLoggedInPage
import cfme.fixtures.pytest_selenium as sel
from cfme.web_ui import PagedTable, CheckboxTable, toolbar as tb, match_location
from utils.appliance ... |
#########################################################################################
#################### HOW TO USE ##########################
#########################################################################################
# This takes input from the terminal so run (in th... |
import logging
import os
from typing import List
from git import Repo as GitRepo
from polyaxon import settings
from polyaxon.client import RunClient
from polyaxon.env_vars.keys import (
POLYAXON_KEYS_GIT_CREDENTIALS,
POLYAXON_KEYS_SSH_PATH,
POLYAXON_KEYS_SSH_PRIVATE_KEY,
)
from polyaxon.exceptions import... |
from __future__ import unicode_literals
"""
Scheduler will call the following events from the module
`startup.schedule_handler` and Control Panel (for server scripts)
execute_always
execute_daily
execute_monthly
execute_weekly
The scheduler should be called from a cron job every x minutes (5?) depending
on the need.
... |
# -*- coding: utf-8 -*-
""" Incident Reporting System - Controllers
@author: Sahana Taiwan Team
"""
module = request.controller
if module not in deployment_settings.modules:
session.error = T("Module disabled!")
redirect(URL(r=request, c="default", f="index"))
# Options Menu (available in all Function... |
import requests
import xml.etree.ElementTree as ETree
import io
from collections import namedtuple
MESSAGE_TYPE_NORMAL = 0
MESSAGE_TYPE_FLASH = 1
MESSAGE_TYPE_WAP_PUSH = 2
MESSAGE_TYPE_VOICE = 3
class MessageRequest(namedtuple('MessageRequest', 'recipient sender text message_type user_sms_id wap_url')):
def as_x... |
#!/usr/bin/python
import subprocess
from info import Info
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
class Display:
lcd = Adafruit_CharLCDPlate()
info = None
screen = []
screenIdx = 0
systemHalt = False
def __init__(self):
self.lcd.clear()
self.lcd.backlight(sel... |
import os
import time
import numpy as np
import paddle
import paddle.fluid as fluid
import logging
import shutil
logger = logging.getLogger(__name__)
def test_without_pyreader(test_exe,
test_reader,
test_feeder,
test_fetch_list,
... |
from wxPython.grid import *
from wxPython.wx import *
import six
class wxCasaTable(wxPyGridTableBase):
"""
This is all it takes to make a custom data table to plug into a
wxGrid. There are many more methods that can be overridden, but
the ones shown below are the required ones. This table simply
... |
# -*- coding: utf-8 -*-
''' Used for processing FPCA requests'''
#
# Copyright © 2008 Ricky Zhou
# Copyright © 2008-2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2... |
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractBaseUser, User
import settings.prod as settings
import uuid
class Semester(models.Model):
# fields
start_date = models.DateField()
end_date = models.DateField()
""" term_code = 1x... |
from __future__ import absolute_import, unicode_literals
from tower_cli import models, resources, get_resource
from tower_cli.cli import types
from tower_cli.utils.parser import string_to_dict
from tower_cli.exceptions import BadRequest
from tower_cli.conf import settings
from tower_cli.resources.node import NODE_STAN... |
import json
from hashlib import md5
def digest_leafs(line):
rec_uri, work_ta_key, leafs = process_record(json.loads(line))
return rec_uri, work_ta_key, list(filter(None,
(digest_leaf(*args) for args in leafs)))
def process_record(data):
graph = data['@graph']
entities = graph[1:]
return ... |
"""
Starter fabfile for deploying the projectname project.
Change all the things marked CHANGEME. Other things can be left at their
defaults if you are happy with the default layout.
"""
import posixpath
from fabric.api import run, local, env, settings, cd, task
from fabric.contrib.files import exists
from fabric.op... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-bitcoinrpc"))
from decimal import Decimal, ROUND_DOWN
import json
import random
import shutil
import subprocess
import time
import re
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from util impo... |
'''
FABRIC UTILITY FUNCTIONS
'''
import collections
import os
import shutil
import subprocess
import boto
import fabric.api
import fabric.contrib.files
import fabric.operations
from fabric.api import (env, task, sudo, run, cd, local, lcd, execute, get,
put, settings)
from fabric.contrib.files... |
from django.conf import settings
from django.db import models
from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField
from django_iban.fields import IBANField, SWIFTBICField
from django.utils.translation import ugettext as _
class MonthlyDonor(models.Model):
"""
Information ab... |
# -*- coding: utf-8 -*-
"""
Math Render Plugin for Pelican
==============================
This plugin allows your site to render Math. It uses
the MathJax JavaScript engine.
For markdown, the plugin works by creating a Markdown
extension which is used during the markdown compilation
stage. Math therefore gets treated... |
#!/usr/bin/env python
# Foundations of Python Network Programming - Chapter 12 - mime_gen_alt.py
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import utils, encoders
def alternative(data, contenttype):
maintype, subtype = conten... |
from abc import ABCMeta, abstractmethod
from copy import deepcopy
from os.path import join, relpath
from PyQt5.QtWidgets import QStackedWidget, QFileDialog, QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSignal
from . import cur_folder
from .io import node_factory
from .ui_templates import (wizard_f... |
import time
import urllib
import cookielib
## TODO : Get rise of web package.
from web import web
# TODO : Use those line when python 2.6 will be out, for now, there is no
# reasons to not be compatible with python 2.4 just to please PEP 238 !
# (lines will be mandatory only with python 2.7)
# from .feed... |
import itertools
from collections import defaultdict
from autonetkit.design.utils import filters
from autonetkit.load.model import StructuredTopology
from autonetkit.network_model.network_model import NetworkModel
from autonetkit.network_model.types import PortType, NodeId, LinkId, PortId, DeviceType
def process_str... |
from pygaze import settings
# on Windows, PyGame's webcam support is a bit shaky, so we provide a vidcap
# back-end; project homepage: http://videocapture.sourceforge.net/
vidimp = False
if sys.platform == 'win32':
# we needn't use vidcap specifically, so we try to import it
try:
import vidcap
vidimp = True
# i... |
import colorsys
from gi.repository import Gtk as gtk
from lib import graphics
from lib.pytweener import Easing
from math import floor
class TailParticle(graphics.Sprite):
def __init__(self, x, y, color, follow = None):
graphics.Sprite.__init__(self, x = x, y = y)
self.follow = follow
self... |
import os
import json
import logging
import ckan.plugins as p
log = logging.getLogger('ckanext_apihelper')
def get_doc(action):
return p.toolkit.get_action(action).__doc__
def check_function(action):
check_list = [
private_check,
rest_check,
internal_function_check,
]
for fn... |
#!/usr/bin/env python
"""
This module contains a component that measures the tactile flow in a tactile image.
"""
#-*- encoding: utf-8 -*-
import rospy
import std_msgs.msg
import tactile_msgs.msg
import slip_detection.flow_calculator as flow_calculator
class TactileFlowExtractor(object):
"""
Measures the ta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.