content stringlengths 4 20k |
|---|
# All transforms used to answer the four questions of exercise 1, broken up by question.
# These are repeated for clarity in the question answers.
# Python import to ensure HiveContext is ready
try:
sc.stop()
except NameError:
pass
from pyspark import SparkContext
sc = SparkContext()
from pyspark.sql i... |
from spack import *
class GnuProlog(Package):
"""A free Prolog compiler with constraint solving over finite domains."""
homepage = "http://www.gprolog.org/"
url = "http://www.gprolog.org/gprolog-1.4.4.tar.gz"
version('1.4.4', '37009da471e5217ff637ad1c516448c8')
parallel = False
def ins... |
# if elif else
age = 15
if(age>=18):
print("成年人!")
else:
print("小屁孩!")
#---------------------------------------
if age<18:
print("小屁孩!")
else:
print("大人!")
#---------------------------------------
if age >= 18:
print('adult')
elif age >= 6: # <==> else if
print('teenager')
else:
... |
# -*- coding: UTF-8 -*-
#Proyecto Python:
#Bajo la galeria de entorno grafico "Tkynter"
# @author Jose Maria Romero
""" Galería de metedos útiles y de uso recurrente """
def getRuta():
#Obtiene la ruta donde se aloja el proyecto. Es necesario para cargar las imagenes
import inspect, os
return o... |
from __future__ import division, absolute_import, print_function
__all__ = ['logspace', 'linspace']
from . import numeric as _nx
from .numeric import array
def linspace(start, stop, num=50, endpoint=True, retstep=False):
"""
Return evenly spaced numbers over a specified interval.
Returns `num` evenly sp... |
from unittest import TestCase
import datetime
import multiprocessing
from rpihome.home import home_user1
class TestHomeUser1(TestCase):
def setUp(self):
self.testQueue = multiprocessing.Queue(-1)
self.user = home_user1.HomeUser1(self.testQueue)
self.ip = "10.5.30.99"
self.... |
"""
This schema represents all known key/value pairs for the builder config file.
"""
from strictyaml import (
load,
Map,
MapPattern,
Str,
Int,
Float,
S... |
import math
import operator
import netaddr
from neutron_lib import constants
from neutron_lib import exceptions as lib_exc
from oslo_db import exception as db_exc
from oslo_utils import uuidutils
from neutron._i18n import _
from neutron.common import exceptions as n_exc
from neutron.db import models_v2
from neutron.i... |
import judicious
judicious.register("http://127.0.0.1:5000")
text = """
During the 1990s, a nine year old girl in Ruston Louisiana won a trophy, 5000 dollars, and a trip to the United States Capital Bl;dg.
Thomas Shriver Junior an employee of the Roess Company in Fairbanks Alaska has a Ph.D. in economics and will be... |
import numpy as np
import torch
class ConcreteDropout(torch.nn.Module):
"""Applies Dropout to the input, even at prediction time and learns dropout probability
from the data.
In convolutional neural networks, we can use dropout to drop entire channels using
the 'channel_wise' argument.
... |
from . import settings
from .models import Referrer
class ReferrerMiddleware():
def process_request(self, request):
if settings.GET_PARAMETER in request.GET:
referrer = None
referrer_name = request.GET.get(settings.GET_PARAMETER, '').strip()
if not referrer_name:
... |
# This are here only because it's always better safe than sorry.
# The issue is that from-time-to-time CPython's termios.tcgetattr
# returns list of mostly-strings of length one, but with few ints
# inside, so we make sure it works
import sys
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.rtyper.too... |
import re
import string
import glob
from gensim.parsing.porter import PorterStemmer
# improved list from Stone, Denis, Kwantes (2010)
STOPWORDS = """
a about above across after afterwards again against all almost alone along already also although always am among amongst amoungst amount an and another any anyhow anyo... |
"""Module tests."""
from __future__ import absolute_import, print_function
import hashlib
from elasticsearch_dsl import Q, Search
from flask import request
from invenio_search.api import DefaultFilter, RecordsSearch
def test_empty_query(app):
"""Test building an empty query."""
q = RecordsSearch()
ass... |
#!/usr/bin/env python3
"""Write stdin to specified sqlite file."""
# pylama:ignore=E501,D213
import argparse
import os
import csv
import sqlite3
from common import log
def edit_distance(s1, s2):
"""Edit distance for two strings.
This is the Levenshtein distance, adapted from the code at
https://en.wi... |
# -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
class AbstractSubscription(models.Model):
""" An abstract model that can be used to define a Subscription-like model. """
... |
# -*- coding: utf-8 -*-
"""
unit test for the undefined types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2008 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
test_default_undefined = '''
>>> from jinja2 import Environment, Undefined
>>> env = Environment(undefined=Undefined)
>>... |
#!/usr/bin/env python
"""
"""
import rospy, sys
import re
from actionlib import SimpleActionClient
from move_base_msgs.msg import *
from actionlib_msgs.msg import *
from geometry_msgs.msg import *
from std_msgs.msg import String
from sound_play.libsoundplay import SoundClient
import sys
from phoenix_robot.interact... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from marshmallow import validate, ValidationError
from marshmallow_jsonapi import Schema, fields
from marshmallow_jsonapi.exceptions import IncorrectTypeError
class AuthorSchema(Schema):
id = fields.Int()
first_name = fields.Str(required=True)
la... |
#! /usr/bin/env python
#! -*- encoding: utf-8 -*-
def echo(value=None):
print "Execution starts when 'next()' is called for the time."
try:
while True:
try:
print type(value)
value = (yield value)
print type(value)
except Exceptio... |
from __future__ import absolute_import
import jinja2
from flask import request, session, current_app
from wtforms.ext.csrf.session import SessionSecureForm
from wtforms.fields import HiddenField
class Form(SessionSecureForm):
"Implements a SessionSecureForm using app.SECRET_KEY and flask.session obj"
def __i... |
import unittest
from textwrap import dedent
from mail_reply_cleaner import clean_mail
class TestMailCleaner(unittest.TestCase):
def test_should_raise_ValueError_if_string_is_not_unicode(self):
with self.assertRaises(ValueError):
clean_mail('this is a test')
def test_normal_mail_should_r... |
from django.test import TestCase
from ..models import Sponsor
from companies.models import Company
class SponsorModelTests(TestCase):
def setUp(self):
self.company1 = Company.objects.create(name='Python')
self.Sponsor1 = Sponsor.objects.create(
company=self.company1,
is_p... |
import BoostBuild
###############################################################################
#
# test_alias_rule()
# -----------------
#
###############################################################################
def test_alias_rule(t):
"""Basic alias rule test."""
t.write("jamroot.jam... |
from bf import bytecode
# ------------------------------------------------------------------------------
# -- Parser --------------------------------------------------------------------
def parse(program):
bc, codemap, loopmap, pc = [], [], [], 0
## Loop state
# Used for constant folding
cinc, cfold1... |
"""Python-level wrapper client"""
import _pylibmc
from .consts import (hashers, distributions, all_behaviors,
hashers_rvs, distributions_rvs,
all_callbacks, BehaviorDict)
_all_behaviors_set = set(all_behaviors)
_all_behaviors_set.update(set(all_callbacks))
server_type_map = ... |
from pycp2k.inputsection import InputSection
class _each236(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... |
"""
Django settings for imagersite project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build p... |
from . import exceptions
import matrix_client.errors
from string import ascii_lowercase, digits
import uuid
def gen_txn_id():
"""Returns a new, unique txn id."""
return str(uuid.uuid1())
def is_full_mxid(user_string):
"""Returns True if a string is a valid mxid."""
if not user_string[0] == "@":
... |
IP_V6_REGEX = r'(([0-9a-fA-F]{1,4}:)' \
r'{7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:)' \
r'{1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]' \
r'{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4})' \
r'{1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}' \
... |
# -*- coding: utf-8 -*-
import six
import warnings
from ws4redis import settings
"""
A type instance to handle the special case, when a request shall refer to itself, or as a user,
or as a group.
"""
SELF = type('SELF_TYPE', (object,), {})()
def _wrap_users(users, request):
"""
Returns a list with the given... |
"""
Implements the logging facility for conary.
Similar to the C printf function, the functions in this module take a
format string that specifies how the subsequent variables should be
converted in the log output.
For example::
log.error("%s not found", foo)
"""
import logging
import os
import sys
import time
f... |
from telemetry.internal.platform import gpu_device
class GPUInfo(object):
"""Provides information about the GPUs on the system."""
def __init__(self, device_array, aux_attributes,
feature_status, driver_bug_workarounds):
if device_array == None:
raise Exception('Missing required "devices... |
from flask import request, session
from dataactcore.utils.jsonResponse import JsonResponse
from dataactcore.utils.statusCode import StatusCode
from dataactbroker.handlers.accountHandler import AccountHandler
from dataactbroker.handlers.aws.session import LoginSession
from dataactbroker.routeUtils import RouteUtils
def... |
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.functional import total_ordering
from django_extensions.db.fields import ModificationDateTimeField
from django_extensions.db.fields.json import JSONField
from bedrock.base.urlresolvers import reverse
from product_details.... |
"""Provides support functions to enalyze modules"""
import sys
from gentoolkit.dbapi import PORTDB, VARDB
from gentoolkit import errors
from gentoolkit.keyword import reduce_keywords
from gentoolkit.flag import (reduce_flags, get_flags, get_all_cpv_use,
filter_flags, get_installed_use, get_iuse)
#from gentoolkit.pac... |
from pymongo import MongoClient, ASCENDING as pymASCEND, DESCENDING as pymDESCENDING
from bson.objectid import ObjectId
import atp_classes
class AppDB:
client = None
db = None
ASCENDING = pymASCEND
DESCENDING = pymDESCENDING
def __init__(self):
config = atp_classes.Config()
host =... |
# coding=utf-8
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
... |
#pylint: disable=no-init,invalid-name
from __future__ import (absolute_import, division, print_function)
from mantid.simpleapi import *
from mantid.api import *
from mantid.kernel import *
import numpy
import sys
class FilterLogByTime(PythonAlgorithm):
def category(self):
return "Events\\EventFiltering"
... |
#!/usr/bin/env python
import requests
import yaml
from bs4 import BeautifulSoup
url = raw_input('Please enter a Jenkins job URL: ')
if !url.endswith('/'):
url += '/'
print 'Retrieving build URLs...'
resp = requests.get(url + 'api/json?tree=allBuilds[url]')
builds = yaml.safe_load(resp.text)
# Only include succes... |
from GenericInstaller import GenericInstaller
from gram.am.gram import config
class Glance(GenericInstaller):
glance_directory = "/etc/glance"
glance_registry_conf_filename = 'glance-registry.conf'
glance_api_conf_filename = 'glance-api.conf'
service_tenant_name = "service"
saved_glance_registry_c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: WFJ
Version: 0.1.0
FileName: test_api.py
CreateTime: 2017-03-19 12:15
"""
import json
import unittest
from app import create_app
from base64 import b64encode
import flask_testing
# 测试json格式返回的API
# @app.route("/ajax/")
# def some_json(... |
from __future__ import print_function
import os
import sys
import time
from pprint import pformat
from contextlib import contextmanager
from soap.context import context as _global_context
class levels():
name = {}
levels = levels()
for i, l in enumerate(['debug', 'info', 'warning', 'error', 'off']):
levels... |
import subprocess
import os
import time
import shutil
"""Configure the pieces for hostname generator"""
#### Modifiable fields ###########
DS_repo_path = 'Full path to DS Repo'
############### Paths ###############
Biplist_url = 'https://bitbucket.org/wooster/biplist'
Repo_file = DS_repo_path + '/Files/'
Temp_folde... |
"""
Support for the Environment Canada radar imagery.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.environment_canada/
"""
import datetime
import logging
import voluptuous as vol
from homeassistant.components.camera import (
PLATFORM_SCHEM... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Speech.speaker'
db.add_column('speeches_speech', 'speaker',
self.gf('d... |
import pytest
from cfme.configure.access_control import simple_user
from cfme.login import login
from cfme.web_ui import menu
from utils.conf import credentials
from utils.testgen import auth_groups, generate
from utils import version
from utils.providers import setup_a_provider
pytest_generate_tests = generate(auth_... |
"""Test the webhistory flows."""
import os
from grr.client import client_utils_linux
from grr.client import client_utils_osx
from grr.client.client_actions import standard
from grr.lib import aff4
from grr.lib import rdfvalue
from grr.lib import test_lib
from grr.lib import utils
class TestWebHistory(test_lib.FlowT... |
"""Fire up the GUI for XLSForm conversion
Under the hood, ``convert`` does the dirty work. The code here presents the
knobs and whistles for setting options and choosing files.
Created: 11 May 2016
Last edited: 10 November 2016
E-mail: <EMAIL>
"""
import sys
import traceback
import StringIO
from Tkinter import Frame,... |
import os
import sys
from shutil import which
from subprocess import Popen, PIPE, call
def shell(args, msg=None):
# Fix Windows error if passed a string
proc = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate(input=msg)
exitcode = proc.returncode
if exitcode!=0:
... |
import eventlet
eventlet.monkey_patch()
import contextlib
import sys
from oslo.config import cfg
from openstack.common import log as logging
from openstack.common import rpc
from openstack.common.rpc import impl_zmq
CONF = cfg.CONF
CONF.register_opts(rpc.rpc_opts)
CONF.register_opts(impl_zmq.zmq_opts)
def main():... |
import numpy as np
from scipy.optimize import curve_fit
from astLib.astStats import bootstrap
from astLib import astCalc as aca
import h5py as hdf
# aardvark simulation cosmology
aca.H0 = 72
aca.OMEGA_M0 = 0.23
aca.OMEGA_L0 = 0.77
def mass(s1d, clusz, a1d=1082, a=1/3.):
''' This is the general form of the VD-mas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# python import
import random, string, struct, StringIO
def random_str(length):
"""Simple method to generate unique and random string value.
"""
return ''.join(random.choice(string.letters) for i in xrange(length))
def get_image_info(data):
"""Tricky me... |
"""Defines the Main URLS."""
import os
from django.conf import settings
from django.conf.urls.defaults import url, patterns, include
from django.contrib import admin
from django.views.generic.simple import direct_to_template
from apps.admin.admin import sys_admin_site, challenge_designer_site, \
challenge_manager_... |
"""
This is an internal PyTango module.
"""
__all__ = ('init',)
__docformat__ = "restructuredtext"
from .attribute_proxy import attribute_proxy_init
from .base_types import base_types_init
from .exception import exception_init
from .callback import callback_init
from .api_util import api_util_init
from .encoded_attr... |
"""
ESSArch is an open source archiving and digital preservation system
ESSArch
Copyright (C) 2005-2019 ES Solutions AB
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either... |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class QualityInspection(Document):
def get_item_specification_details(self):
self.set('readings', [])
variant_of = frappe.db.get_value("Item", self.item_code, "variant_of")
if variant_of:
specification = frappe... |
import os
import re
import socket
import time
# py2 vs py3; replace with six via ansiballz
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
try:
import paramiko
from paramiko.ssh_exception import AuthenticationException
HAS_PARAMIKO = True
except ImportError:
HAS_... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'UserProfile.location'
db.delete_column('UserProfile', 'location')
def backwards(self,... |
# -*- coding:Utf-8 -*-
from mongoengine import fields
from timeline.models.invoicing_entries.invoicing_timeline_entry import InvoicingTimelineEntry
__all__ = (
'QuotationAddedAttachment',
'PurchaseOrderAddedAttachment',
'InvoiceAddedAttachment',
'DownPaymentInvoiceAddedAttachment',
'CreditNoteAd... |
from django import forms
from django.core.exceptions import ValidationError
from prosodyauth import fields, authenticate
from helpers.forms import PlaceholderForm
class PasswordChangeForm(PlaceholderForm):
old_password = fields.PassField(min_length=8, label='current password')
new_password = fields.PassFi... |
#===============================================================================
#--- SETUP Config
#===============================================================================
from config.config import *
import unittest
#===============================================================================
#--- SETUP Log... |
# -*- encoding: utf-8 -*-
import imp
import os
from importlib import import_module
from types import ModuleType
from knecht.engine import Engine
from knecht import log
def load_config(env_var):
c = Metadata({
'_raw' : ModuleType,
'repos' : str,
'blogconf' : str,
'engine' : Engin... |
"""
File: plcscan.py
Desc: PLC scanner
Version: 0.1
Copyright (c) 2012 Dmitry Efanov (Positive Research)
"""
__author__ = 'defanov'
import modbus
import s7
import sys
from optparse import OptionParser
import socket
import struct
def status(msg):
sys.stderr.write(msg[:-1][:39].ljust(39,' ')+msg... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
from login_widget import LoginDialog
from chat_widget import ChatWidget
from rank_widget import RankList
from gamelist_widget import GameListWidget
from game_window_widget import GameWindow
import logging
# sy... |
from PyQt4 import QtGui
from PyQt4.QtCore import Qt, QRectF, QPointF
from lgsip.frontend.gates.gate import DeleteGateButton, _LgsipGateButton
from uuid import uuid4
import imp
class Wire(QtGui.QGraphicsObject):
def __init__(self, propagating=False, parent=None):
super(Wire, self).__init__(parent)
... |
from base64 import b64decode
import os
from unittest import TestCase
from unittest.mock import patch
import responses
from ..index import lambda_handler
@patch('index.REGION', 'us-east-1')
class TestS3Select(TestCase):
"""Tests S3 Select"""
def setUp(self):
self.requests_mock = responses.RequestsMoc... |
"""VGG Models from torchvision.
For more information on the models please refer to
Very Deep Convolutional Networks for Large-Scale Image Recognition
International Conference on Learning Representations, 2015
and the PyTorch documentation: https://pytorch.org/hub/pytorch_vision_vgg/
Note that the model will be ... |
from socket import *
import sys
import time
class Log:
def push(self, t, msg):
if t == 'WARNING':
print '[!] %s' %(msg)
elif t == 'REQUEST':
print '[<] %s' %(msg)
elif t == 'RESPONSE':
print '[>] %s' %(msg)
else:
print '[i] %s' %(... |
"""
nesMemory: represents the emulated NES memory space.
"""
#import struct
class Memory(object):
"""Manages the emulated representation of NES memory."""
def __init__(self):
# 7FF - 4000 and 6000+ isnt even used
self.memory = 0x8000 * [0]
def ClearMemory(self):
self.memory = 0x80... |
import warnings
def deprecated(func):
'''This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.'''
def new_func(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
... |
# -*- coding: utf-8 -*-
from django.forms import MultiWidget, Select, TextInput
from ..settings import CURRENCY_CHOICES
__all__ = ('MoneyWidget',)
class MoneyWidget(MultiWidget):
def __init__(self, choices=CURRENCY_CHOICES, amount_widget=TextInput, currency_widget=None, default_currency=None,
... |
# -*- coding: utf-8 -*-
"""
Tests for the determine_package utility.
"""
# Future
from __future__ import absolute_import, division, print_function, \
unicode_literals, with_statement
# Standard Library
import string
# Third Party
import nose
from nose.tools.trivial import eq_
# First Party
from metaopt.concurren... |
"""Utilities for synapse handling."""
import enum
import functools as ft
from typing import Callable, List, Sequence, Text, Union, Optional
import dataclasses as dc
import jax.numpy as jp
import numpy as np
import tensorflow.compat.v1 as tf
from blur import blur_env
TensorShape = tf.TensorShape
Tensor = Union[tf.Te... |
"""
draw_climatology_map_MISR_AOD.py
Use OCW to download an MISR dataset, subset the data, calculate the 16 and 5 year
mean and draw a countour map of the means and the current values.
In this example:
1. Download a dataset from https://dx.doi.org/10.6084/m9.figshare.3753321.v1.
*** Note ***... |
from miasm2.core.utils import pck32, pck64
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE
try:
import unicorn
except ImportError:
unicorn = None
from sibyl.engine.engine import Engine
from sibyl.commons import END_ADDR, init_logger
class UnexpectedStopException(Exception):
"""Exception to be called... |
from __future__ import unicode_literals
import webnotes
from webnotes import _, msgprint
from webnotes.utils import flt, _round
from buying.utils import get_item_details
from setup.utils import get_company_currency
from webnotes.model.doc import addchild
from controllers.stock_controller import StockController
class... |
"""
The MIT License (MIT)
Copyright (c) 2016 John Board
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, ... |
import os
import numpy as np
import numpy.testing
from dipy.data import get_data, get_sphere
from dipy.core.gradients import gradient_table
from dipy.reconst.gqi import GeneralizedQSamplingModel
from dipy.reconst.dti import TensorModel, quantize_evecs
from dipy.tracking import utils
from dipy.tracking.eudx import EuDX... |
from __future__ import print_function
import base64
import json
import os
import shutil
import subprocess
import zlib
import boto3
from botocore.exceptions import ClientError
import sys
#Read in the configuration
# bucket to store save games
BUCKET = os.environ['BUCKET']
# Access key for IAM user to access S3 bucket
... |
from api.util import settings
import contextlib
import sqlite3
import json
class RedisStatsProvider(object):
"""A Sqlite based persistance to store and fetch stats
"""
def __init__(self):
stats = settings.get_sqlite_stats_store()
self.location = stats.get('path', 'db/redislive.sqlite')
... |
# stdlib
# stdlib
import dataclasses
from uuid import UUID
# third party
import sympc
from sympc.config import Config
from sympc.tensor import ShareTensor
# syft absolute
import syft
# syft relative
from ...generate_wrapper import GenerateWrapper
from ...lib.torch.tensor_util import protobuf_tensor_deserializer
fro... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para nosvideo
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------
import re
from core import logger
from core import scrap... |
"""
.. module:: reversi.tema
.. moduleauthor:: Luka Lodrant <<EMAIL>>, Lenart Treven <<EMAIL>>
Kivy barvna tema aplikacije
"""
from kivy.utils import get_color_from_hex as from_hex
from kivy.properties import ListProperty
from kivy.uix.widget import Widget
class Tema(Widget):
"""
Kivy barvna tema aplikacij... |
#!/usr/bin/python
'''
Extract _("...") strings for translation and convert to Qt4 stringdefs so that
they can be picked up by Qt linguist.
'''
from subprocess import Popen, PIPE
import glob
OUT_CPP="src/qt/mudcoinstrings.cpp"
EMPTY=['""']
def parse_po(text):
"""
Parse 'po' format produced by xgettext.
Ret... |
"""Test bitcoin-cli"""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_process_error, get_auth_cookie
class TestBitcoinCli(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
... |
import inspect
import os
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import importutils
import testtools
from nova.api.metadata import password
# Import extensions to pull in osapi_compute_extension CONF option used below.
from nova.console ... |
"""Unit-tests for blackjack/score.py module."""
import unittest
import blackjack.card
import blackjack.score
class TestValuesFromCard(unittest.TestCase):
def test_numbered_card(self):
card = blackjack.card.Card('Spade', '2')
values = blackjack.score.values_from_card(card)
self.assertEqu... |
from os.path import join
from logilab.common.testlib import TestCase, unittest_main
from logilab.common.pytest import *
class ModuleFunctionTC(TestCase):
def test_this_is_testdir(self):
self.assertTrue(this_is_a_testdir("test"))
self.assertTrue(this_is_a_testdir("tests"))
self.assertTrue(th... |
from django.contrib import admin
from model_utils.managers import QueryManager
from .models import CostoParametro, ArchivosAdjuntosPeriodo, Costo, CostoTipo, AvanceObra
from .forms import CostoEditPorCCForm, CostoEditPorEquipoForm
@admin.register(CostoParametro)
class CostoParametroAdmin(admin.ModelAdmin):
list... |
import json
import logging
import urllib2
from glob import glob
from datetime import datetime
from elasticsearch import Elasticsearch, helpers
def index_tweets():
es = Elasticsearch(["http://mixednode1:9200"], use_ssl=False)
inputs = glob("filtered/*/*.json")
logging.info(inputs)
for filename in inputs:
... |
from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
str = type('')
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
import compoundpi as _setup
# -- General configuration ------------------------------------------------
ext... |
from collections import namedtuple
from math import sqrt
import random
from PIL import Image
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', dest='filename', help='input file')
parser.add_argument('-c', '--colors', dest='colors', type=int, default=3, help='number of colors')
ar... |
import os.path
import shutil
import fixtures
from oslotest import moxstubout
import osprofiler.web
from glance.api.middleware import context
from glance.common import config
from glance.tests import utils as test_utils
class TestPasteApp(test_utils.BaseTestCase):
def setUp(self):
super(TestPasteApp, se... |
# -*- coding: utf-8 -*-
from .env import *
from .utils import *
from amoco.arch.core import Formatter
whitespace = ' '
def regs(i):
return ['%{0}'.format(r) for r in i.operands]
def address(a):
if not a._is_eqn:
return '%'+str(a)
l = reg_or_imm(a.l)
op = a.op.symbol
r = reg_or_imm(a.r)
... |
from .functions import Singleton
import pickle
import os
import time
import uuid, json,logging
import keyring
@Singleton
class ConfigManager:
device_id = ''
data_path = ''
rdiff_path = ''
proxies = None
proxies_loaded = False
def __init__(self, configs_path, data_path):
self.configs_... |
import sys
sys.path.append("../")
from midiutil.TrackGen import LoopingArray
from midiutil.MidiGenerator import MidiGenerator
midiGenerator = MidiGenerator(tempo=90)
scale = reduce(lambda x,y:x+y,[[y+(12*x)+36 for y in [0,3,5,7,8,10]] for x in range (5)])
pos = 0
for base in [10,9,8,7,6,5,4,3,2,1]:
... |
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import *
import tweepy
import re
import io
from facepy import GraphAPI
from facepy.exceptions import *
from scheduler.models import *
from datetime import datetime, timedelta
from django.utils import timezone
import requests
from bs... |
# -*- coding: utf-8 -*-
from chatterbot import ChatBot
import logging
"""
This example shows how to create a chat bot that
will learn responses based on an additional feedback
element from the user.
"""
# Uncomment the following line to enable verbose logging
# logging.basicConfig(level=logging.INFO)
# Create a new ... |
# -*- coding: utf-8 -*-
"""High level integration / functional tests of the work engine actions."""
import logging
logger = logging.getLogger(__name__)
import json
import fysom
import transaction
import pyramid_basemodel as bm
from pyramid import config as pyramid_config
from pyramid_torque_engine import constant... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.