content string |
|---|
from dao import word
from samplevars import x
def parse(grammar_element, text):
x = Var()
code = grammar_element(x)+x
return eval([code, text])
def match(grammar_element, text):
x = Var()
code = grammar_element(x)
return eval([code, text])
print parse(word, 'hello')
print match(word, 'h... |
from __future__ import print_function
import os
import re
import sys
import subprocess
import tempfile
from error import EditorError
class Editor(object):
"""Manages the user's preferred text editor."""
_editor = None
globalConfig = None
@classmethod
def _GetEditor(cls):
if cls._editor is None:
... |
#!/usr/bin/env python
import sys
import os
import glob
import time
class archive:
# The archive class represent an archive media with its age related parameters
def __init__(self, path):
self.path = path
self.time = time.gmtime(os.path.getmtime(path))
self.year = time.strftime("%Y", sel... |
import board
import controllers
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from ansible.compat.tests.mock import patch, Mock, MagicMock, call
import sys
if sys.version_info[:2] != (2, 6):
import requests
from units.modules.utils import set_module_args
from .netscaler_module import TestModule, nitro_base_patcher
class TestNetscalerCSPolicyModule(TestModule):
@classmethod
def... |
import pytest
import ibis
@pytest.fixture
def pipe_table():
return ibis.table(
[
('key1', 'string'),
('key2', 'string'),
('key3', 'string'),
('value', 'double'),
],
'foo_table',
)
def test_pipe_positional_args(pipe_table):
def my_f... |
import re
import glob
import os
import bsettings
import command
class Toolchain:
"""A single toolchain
Public members:
gcc: Full path to C compiler
path: Directory path containing C compiler
cross: Cross compile string, e.g. 'arm-linux-'
arch: Architecture of toolchain as dete... |
# encoding: utf-8
"""
vpls.py
Created by Nikita Shirokov on 2014-06-16.
Copyright (c) 2014-2017 Nikita Shirokov. All rights reserved.
Copyright (c) 2014-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
from struct import unpack
from struct import pack
from exabgp.protocol.fa... |
import os
import re
import glob as g
import shutil
import tempfile
from oeqa.selftest.case import OESelftestTestCase
from oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars
class MetaOESourceMirroring(OESelftestTestCase):
# Can we download everything from the OpenEmbedded Sources Mirror over http ... |
"""
Utilities for django models.
"""
import re
import unicodedata
from django.conf import settings
from django.dispatch import Signal
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from django_countries.fields import Country
from eventtracking import tracker
# The setti... |
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.flatpages.forms import FlatpageForm
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.test import TestCase, modify_settings, override_settings
from django.utils impor... |
__author__ = 'Shyue Ping Ong'
__copyright__ = 'Copyright 2014, The Materials Virtual Lab'
__version__ = '0.1'
__maintainer__ = 'Shyue Ping Ong'
__email__ = '<EMAIL>'
__date__ = '1/24/14'
import unittest
import os
from monty.os.path import which, zpath
from monty.os import cd
test_dir = os.path.join(os.path.dirname(... |
from __future__ import unicode_literals
import re
from unittest import TestCase
from django import forms
from django.core import validators
from django.core.exceptions import ValidationError
class UserForm(forms.Form):
full_name = forms.CharField(
max_length=50,
validators=[
validato... |
#!/usr/bin/env python3
import urllib.parse
import requests
import queue
import os
import interface
class Download_Configer(object):
# Init download settings...
def __init__(self, url, saveto):
self.url = url
parse_result = urllib.parse.urlparse(self.url)
self.filename = self.url.split... |
import sys
import struct
import re
header_event_id = 0xffffffffffffffff
header_magic = 0xf2b177cb0aa429b4
header_version = 0
trace_fmt = '=QQQQQQQQ'
trace_len = struct.calcsize(trace_fmt)
event_re = re.compile(r'(disable\s+)?([a-zA-Z0-9_]+)\(([^)]*)\).*')
def err(msg):
sys.stderr.write(msg + '\n')
sys.e... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import io
from django.conf import settings
from django.core.cache import cache
from django.http import HttpResponse
from django.http.response import HttpResponseBase
from django.test import SimpleTestCase
UTF8 = 'utf-8'
ISO88591 = 'iso-8859-1'
class ... |
#!/usr/bin/env python
from numpy import *
from scipy.io import mmread
# Loading an example sparse matrix of dimension 479x479, real, unsymmetric
mtx=mmread('../../../data/logdet/west0479.mtx')
parameter_list=[[mtx,100,60,1]]
def mathematics_logdet (matrix=mtx,max_iter_eig=1000,max_iter_lin=1000,num_samples=1):
fr... |
class TriggerEfficiency:
"""
Class calculating the trigger efficiency from a given min. bias container and a given triggered container
"""
def __init__(self, triggername, minbiascontainer, triggeredcontainer):
"""
Constructor
"""
self.__triggername = triggername
... |
#!/usr/bin/env python
from saml2 import element_to_extension_element
from saml2 import extension_elements_to_elements
from saml2 import SamlBase
from saml2 import md
__author__ = 'rolandh'
"""
Functions used to import metadata from and export it to a pysaml2 format
"""
IMP_SKIP = ["_certs", "e_e_", "_extatt"]
EXP_SK... |
class ModifiedFile(object):
def __init__(self, filename):
super(ModifiedFile, self).__init__()
self.filename = filename
def __repr__(self):
return self.filename
def __eq__(self, other):
return isinstance(other, ModifiedFile) and other.filename == self.filename |
from __future__ import unicode_literals
import datetime
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
from django.db.models import signals
from django.db import model... |
#!/usr/bin/env python
'''This demonstrates controlling a screen oriented application (curses).
It starts two instances of gnuchess and then pits them against each other.
'''
import pexpect
import string
import ANSI
import sys, os, time
class Chess:
def __init__(self, engine = "/usr/local/bin/gnuchess -a -h ... |
from __future__ import absolute_import
from django.test import TestCase
from .models import Source, Item
class ReverseSingleRelatedTests(TestCase):
"""
Regression tests for an object that cannot access a single related
object due to a restrictive default manager.
"""
def test_reverse_single_rel... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
sanitized_Request,
str_to_int,
)
class ExtremeTubeIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?extremetube\.com/(?:[^/]+/)?video/(?P<id>[^/#?&]+)'
_TESTS = [{
'u... |
#!venv/bin/python
# -*- coding: utf-8 -*-
import tornado
import tornado.websocket
import tornado.wsgi
import logging
import time
import json
import random
from app import app, db
from app.models import User, Game, Fact, Deck, ROLE_USER, ROLE_ADMIN, get_object_or_404
a = {'あ':'a',
'い':'i',
'う':'u',
'え':'e',
'お':'o',
... |
import os
class WhatypeErr(Exception):
def __init__(self, when, error):
self.when = when
self.error = error
def __str__(self):
return repr("Whatype Error on " + self.when + " : " + self.error)
class MagicNode(object):
def __init__(self, byte):
self.byte = byte
... |
"""Functional tests for reduction ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tens... |
# -*- coding: utf-8 -*-
"""
PE-specific Form helpers.
"""
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField, CharField, Select
from django.utils.translation import ugettext_lazy as _
class PERegionSelect(Select):
"""
A Select wi... |
DATE_FORMAT = 'j. F Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = 'j. F Y H:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = 'd.m.Y'
SHORT_DATETIME_FORMAT = 'd.m.Y H:i'
FIRST_DAY_OF_WEEK = 1 # Monday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/... |
import sys
import unittest
from glob import glob
import numpy as np
class NotAvailable(SystemExit):
def __init__(self, msg, code=0):
SystemExit.__init__(self, (msg,code,))
self.msg = msg
self.code = code
# -------------------------------------------------------------------
# Custom test... |
"Misc. utility functions/classes for admin documentation generator."
import re
from email.Parser import HeaderParser
from email.Errors import HeaderParseError
try:
import docutils.core
import docutils.nodes
import docutils.parsers.rst.roles
except ImportError:
docutils_is_available = False
else:
do... |
'''
We base the NetLapRLS implementation on the one from PyDTI project, https://github.com/stephenliu0423/PyDTI, changes were made to the evaluation procedure
[1] Xia, Zheng, et al. "Semi-supervised drug-protein interaction prediction from heterogeneous biological spaces." BMC systems biology 4.Suppl 2 (2010): S6.
De... |
from operator import attrgetter
import pytest
from ..config import (
Config,
ConfigKey,
ConfigKeyTypes,
InvalidConfigValue,
MissingConfigKey,
)
class TestConfigKeyTypes:
def test_get_converter_unknown_type(self):
"""An error is raised if type is unknown."""
with pytest.raises... |
#!/usr/bin/env python
"""Run the py->rst conversion and run all examples.
This also creates the index.rst file appropriately, makes figures, etc.
"""
from __future__ import print_function, division, unicode_literals, absolute_import
from builtins import open
from past.builtins import execfile
# -----------------------... |
#!/usr/bin/env python
import lief
import sys
import os
# Parse PE file
pe = lief.parse(sys.argv[1])
sep = (":") if sys.version_info.minor > 7 else ()
# Get authenticode
print(pe.authentihash_md5.hex(*sep)) # 1c:a0:91:53:dc:9a:3a:5f:34:1d:7f:9b:b9:56:69:4d
print(pe.authentihash(lief.PE.ALGORITHMS.SHA_1).hex(*sep)) # ... |
import logging
import optparse
import os
import sys
import types
import unittest
from chromedriver_launcher import ChromeDriverLauncher
import py_unittest_util
import test_paths
# Add the PYTHON_BINDINGS first so that our 'test' module is found instead of
# Python's.
sys.path = [test_paths.PYTHON_BINDINGS] + sys.path... |
# -*- 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):
# Changing field 'Document.stored_validity_rate'
db.alter_column(u'crowdataapp_document', 'stored_validity_... |
import os
import re
import sys
import zipfile
def main():
ZIP_PATTERN = re.compile('dmprof......\.zip')
assert len(sys.argv) == 6
assert sys.argv[1] == 'cp'
assert sys.argv[2] == '-a'
assert sys.argv[3] == 'public-read'
assert ZIP_PATTERN.match(os.path.basename(sys.argv[4]))
assert sys.argv[5] == 'gs:/... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class JeuxVideoIE(InfoExtractor):
_VALID_URL = r'http://.*?\.jeuxvideo\.com/.*/(.*?)\.htm'
_TESTS = [{
'url': 'http://www.jeuxvideo.com/reportages-videos-jeux/0004/00046170/tearaway-playstation-vita... |
"""Provides the definition of an RPC serialization handler"""
import abc
class Serializer(object):
"""Generic (de-)serialization definition base class."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def serialize_entity(self, context, entity):
"""Serialize something to primitive form.
... |
"""A Dataflow job that counts the number of rows in a BQ table.
Can be configured to simulate slow reading for a given number of rows.
"""
from __future__ import absolute_import
import logging
import unittest
from hamcrest.core.core.allof import all_of
from nose.plugins.attrib import attr
from apache_beam.io.gc... |
import sys,string, os, traceback, types, completion, signal
import line_to_arguments
from cmd import *
#from api.vfs import *
#from api.taskmanager.taskmanager import TaskManager
from api.manager.manager import ApiManager
from ui.console.complete_raw_input import complete_raw_input
from ui.history import history
PR... |
import argparse
import os
from assignment import Assignment
from command import Command
class LabConvert(object):
def __init__(self):
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument(
'-v', '--verbose',
... |
import pyaudio
import wave
import sys
import time
import cv2
import numpy as np
import os
from Tkinter import *
from pydubtest import play, make_chunks
from pydub import AudioSegment
from threading import Thread
from vidAnalysis import vid2SoundFile
from eventBasedAnimationClass import EventBasedAnimationClass
import i... |
"""Helpers that help with state related things."""
import asyncio
import datetime as dt
import json
import logging
from collections import defaultdict
from types import ModuleType, TracebackType
from typing import Awaitable, Dict, Iterable, List, Optional, Tuple, Type, Union
from homeassistant.loader import bind_hass,... |
from datetime import datetime
from django.conf import settings
from django.contrib.auth.models import User
from django.test.utils import override_settings
from basket.base import BasketException
from celery.exceptions import Retry
from mock import patch
from nose.tools import eq_, ok_
from mozillians.common.tests im... |
from __future__ import unicode_literals
from itertools import chain
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from guardian.utils import get_identity
from guardian.utils import get_user_obj_perms_model
from guardian.uti... |
from __future__ import unicode_literals
from django.apps import apps
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.auth.tests.custom_user import CustomUser
from django.core.exceptions import ImproperlyConfigured
from django.dispatch import... |
from __future__ import absolute_import
import os
import nox
LOCAL_DEPS = (os.path.join("..", "api_core"), os.path.join("..", "core"))
@nox.session(python="3.7")
def lint(session):
"""Run linters.
Returns a failure if the linters find linting errors or sufficiently
serious code quality issues.
"""
... |
"""
FR-specific Form helpers
"""
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
import re
phone_digits_re = re.com... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import shlex
import os
import re
import sys
def get_version(pacman_output):
"""Take pacman -Qi or pacman -Si output and get the Version"""
lines = pacman_output.split('\n... |
#!/usr/bin/env python
"""
C.11.5 Index and Glossary (p211)
"""
import string, os
from plasTeX.Tokenizer import Token, EscapeSequence
from plasTeX import Command, Environment, IgnoreCommand, encoding
from plasTeX.Logging import getLogger
from Sectioning import SectionUtils
try:
from pyuca import Collator
col... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.eos import eos_banner
from units.modules.utils import set_module_args
from .eos_module import TestEosModule, load_fixture
class TestEosBannerModule(TestEosModule):
... |
import unittest
import sys
import os.path
from copy import copy
sys.path.append(os.path.dirname(__file__) + "/../../..")
from pox.lib.mock_socket import MockSocket
class MockSocketTest(unittest.TestCase):
def setUp(self):
pass
def test_simple_send(self):
(a, b) = MockSocket.pair()
a.send("Hallo")
... |
"""Reads and writes the configuration file of PyARTOS.
This module provides access to the configuration given in the file 'pyartos.ini',
which is searched for in the current working directory. To access the configuration
options, the 'config' object in this module's dictionary can be used, which is an
instance of... |
"""
This module houses the GoogleMap object, used for generating
the needed javascript to embed Google Maps in a Web page.
Google(R) is a registered trademark of Google, Inc. of Mountain View, California.
Example:
* In the view:
return render_to_response('template.html', {'google' : GoogleMap(key="... |
import django_filters
from .models import (
CommunityHealthUnit,
CommunityHealthWorker,
CommunityHealthWorkerContact,
Status,
CommunityHealthUnitContact,
Approver,
CommunityHealthUnitApproval,
CommunityHealthWorkerApproval,
ApprovalStatus
)
from common.filters.filter_shared import ... |
from boto.exception import InvalidLifecycleConfigError
# Relevant tags for the lifecycle configuration XML document.
LIFECYCLE_CONFIG = 'LifecycleConfiguration'
RULE = 'Rule'
ACTION = 'Action'
DELETE = 'Delete'
CONDITION = 'Condition'
AGE = 'Age'
CREATED_... |
from sqlalchemy import Column
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import Text
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
compute_nodes = Table('compute_nodes', meta, autoload=True)
shadow_compute_nodes = Table('shadow_compute_nod... |
import resource
import faces
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
__import__("pkg_resources").declare_namespace(__name__) |
"""setuptools.command.bdist_egg
Build .egg distributions"""
# This module should be kept compatible with Python 2.3
import sys, os, marshal
from setuptools import Command
from distutils.dir_util import remove_tree, mkpath
try:
# Python 2.7 or >=3.2
from sysconfig import get_path, get_python_version
def _g... |
"""The volumes snapshots api."""
from oslo_log import log as logging
from oslo_utils import strutils
from six.moves import http_client
import webob
from cinder.api import common
from cinder.api.openstack import wsgi
from cinder.api.schemas import snapshots as snapshot
from cinder.api import validation
from cinder.api... |
from django.contrib import admin
from .models import AbilityList, AbilityExamples, OccupationList, DriveList, DriveExamples, AssociatedOccuDrive, AssociatedOccuAbil, SpecialList
# Primary keys you care about
#primary_keys = [
# 'occupation',
# 'drive',
# 'ability'
# ]
# Inline projects to build the editin... |
from django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.dashboards.admin.metering import views
urlpatterns = patterns(
'openstack_dashboard.dashboards.admin.metering.views',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^samples$', views.SamplesView.as_... |
from eve import Eve
from endpoints import xml_collections_endpoint, geo_collections_endpoint
class XMLEve(Eve):
"""
This class aims to let Eve be able to import XML documents
It is meant to overload the view function `collections endpoint`.
It interprets the text/xml Content-Type and calls the `post`... |
import copy
from . import ElementTree
XINCLUDE = "{http://www.w3.org/2001/XInclude}"
XINCLUDE_INCLUDE = XINCLUDE + "include"
XINCLUDE_FALLBACK = XINCLUDE + "fallback"
##
# Fatal include error.
class FatalIncludeError(SyntaxError):
pass
##
# Default loader. This loader reads an included resource from disk.
#
#... |
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
t... |
"""
This module has the mock object definitions used to hold reference geometry
for the GEOS and GDAL tests.
"""
import gzip
import os
from django.contrib import gis
from django.utils import simplejson
# This global used to store reference geometry data.
GEOMETRIES = None
# Path where reference test data is located... |
import random, time, queue
from multiprocessing.managers import BaseManager
from multiprocessing import freeze_support
task_queue = queue.Queue()
result_queue = queue.Queue()
class QueueManager(BaseManager):
pass
def return_task_queue():
global task_queue
return task_queue
def return... |
# -*- 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):
# Removing index on 'Address', fields ['address']
if db.backend_name != 'sqlite3':
# South forg... |
#!/usr/bin/env python2
# $Date$
# $Revision$
# $Author$
# $HeadURL$
# $Id$
import sys, re, os
import xml.parsers.expat
from xml.dom import minidom
from Tools.pretty import *
from Tools.colours import Colours
tokens = [
['&' , '####amp####'],
['&' , '&'],
['<' , '<'],
['>' , '>'],
... |
"""Ops for fused Cudnn RNN models.
@@CudnnGRU
@@CudnnLSTM
@@CudnnRNNRelu
@@CudnnRNNTanh
@@RNNParamsSaveable
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops import CudnnGRU
from tensorflow.contr... |
import base64
import logging
import os
import unittest
import urllib
import urllib2
import urlparse
import wptserve
logging.basicConfig()
here = os.path.split(__file__)[0]
doc_root = os.path.join(here, "docroot")
class Request(urllib2.Request):
def __init__(self, *args, **kwargs):
urllib2.Request.__init... |
#!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = '<EMAIL> (Wesley Chun)'
from datetime import datetime
import endpoints
fr... |
#!/usr/bin/env python
"""
sarcorrelation.py : Calculates interferometric correlation
usage::
$ sarcorrelation.py int_file amp_input [options]
Parameters
----------
int_file : complex interferogram file
amp_input : amplitude file(s); one of:
-a bip_amp... |
#
# db model for psychometrics data
#
# this data is collected in real time
#
from django.db import models
from courseware.models import StudentModule
class PsychometricData(models.Model):
"""
This data is a table linking student, module, and module performance,
including number of attempts, grade, max g... |
import traceback
import sys
import os
def exception_string(e):
(ty,v,tb) = sys.exc_info()
return traceback.format_exception_only(ty,v)
def daemonize(prog, args, stdin_tmpfile=None):
"""Runs a program as a daemon with the list of arguments. Returns the PID
of the daemonized program, or returns... |
#!/usr/bin/env python
import time
import sys
import logging
import argparse
from socketIO_client import SocketIO
from messenger import Messenger
logger = logging.getLogger('get_status')
logging.basicConfig(level=logging.DEBUG)
APPKEY = '5697113d4407a3cd028abead'
#TOPIC = 'yunba_smart_plug'
#ALIAS = 'plc_0'
class St... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import os
import sys
from ansible.module_utils.basic import AnsibleModule
def _fail(modu... |
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from .display import Display, Header, Sorter, YN, Commas, TimeLong, TimeShort, Sortable, BodyFormat, PlainNum
from .display import NumKMG
__all__ = ["Display", "Header",... |
import ansible
from ansible import utils
from ansible.runner.return_data import ReturnData
class ActionModule(object):
''' Print statements during execution '''
NEEDS_TMPPATH = False
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp, module_name, module_args, inject, ... |
"""stack symbolizes native crash dumps."""
import re
import symbol
def PrintTraceLines(trace_lines):
"""Print back trace."""
maxlen = max(map(lambda tl: len(tl[1]), trace_lines))
print
print "Stack Trace:"
print " RELADDR " + "FUNCTION".ljust(maxlen) + " FILE:LINE"
for tl in trace_lines:
(addr, s... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class DisableWalletTest (BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 1
def setup_network(self, split=False):
self.... |
import sys
import os
import unittest
from io import StringIO
from types import ListType
from email.test.test_email import TestEmailBase
from test.support import TestSkipped, run_unittest
import email
from email import __file__ as testfile
from email.iterators import _structure
def openfile(filename):
from os.pat... |
from unittest import TestCase
from nose.tools import assert_equal, raises, assert_true, assert_false
from wlauto import Instrument
from wlauto.core import signal, instrumentation
from wlauto.instrumentation import instrument_is_installed, instrument_is_enabled, clear_instrumentation
class MockInstrument(Instrument)... |
from ctypes import POINTER, Structure, c_char_p, c_float, c_int, string_at
from django.contrib.gis.geoip.libgeoip import free, lgeoip
# #### GeoIP C Structure definitions ####
class GeoIPRecord(Structure):
_fields_ = [('country_code', c_char_p),
('country_code3', c_char_p),
('cou... |
import os
import unittest
from src.test.py.bazel import test_base
class DEFParserTest(test_base.TestBase):
def createAndBuildProjectFiles(self):
self.ScratchFile('WORKSPACE')
self.ScratchFile('BUILD', ['cc_library(name="hello", srcs=["x.cc"])'])
self.ScratchFile('x.cc', [
'#include <stdio.h>',
... |
import os
from datetime import datetime, timedelta
from boto.utils import parse_ts
import boto
class ResultProcessor(object):
LogFileName = 'log.csv'
def __init__(self, batch_name, sd, mimetype_files=None):
self.sd = sd
self.batch = batch_name
self.log_fp = None
self.num_files... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'Skill.applicant'
db.add_column(u'projects_skill', 'applic... |
"""Adds xref targets to the top of files."""
import sys
import os
testing = False
DONT_TOUCH = (
'./index.txt',
)
def target_name(fn):
if fn.endswith('.txt'):
fn = fn[:-4]
return '_' + fn.lstrip('./').replace('/', '-')
def process_file(fn, lines):
lines.insert(0, '\n')
lines... |
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse, reverse_lazy
from django.contrib.auth.decorators import login_required
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
from ..account.views im... |
from django import http
from django.contrib.messages import constants, get_level, set_level, utils
from django.contrib.messages.api import MessageFailure
from django.contrib.messages.constants import DEFAULT_LEVELS
from django.contrib.messages.storage import base, default_storage
from django.contrib.messages.storage.ba... |
'''
Created on Mar 5, 2017
@author: PJ
'''
from django.db.models.aggregates import Avg, Sum
from django.db.models.expressions import Case, When
def get_team_metrics(team, regional_code):
metrics = team.scoreresult_set.filter(competition__code=regional_code).aggregate(
... |
# http://g95.sourceforge.net/
from __future__ import division, absolute_import, print_function
from numpy.distutils.fcompiler import FCompiler
compilers = ['G95FCompiler']
class G95FCompiler(FCompiler):
compiler_type = 'g95'
description = 'G95 Fortran Compiler'
# version_pattern = r'G95 \((GCC (?P<gccver... |
import re
from bpython.test import unittest
from bpython.line import current_word, current_dict_key, current_dict, \
current_string, current_object, current_object_attribute, \
current_from_import_from, current_from_import_import, current_import, \
current_method_definition_name, current_single_word, \
... |
import re
import random
import sys
#new line
NL='\r\n'
_width = len(repr(sys.maxint-1))
_fmt = '%%0%dd' % _width
class MIMEMessage:
def __init__(self):
self._files = []
self._xmlMessage = ""
self._startCID = ""
self._boundary = ""
def makeBoundary(self):
#create the... |
#!/usr/bin/python
import os
import pickle
import random
import re
import sys
from irc import IRCBot, IRCConnection
class MarkovBot(IRCBot):
"""
Hacking on a markov chain bot - based on:
http://code.activestate.com/recipes/194364-the-markov-chain-algorithm/
http://github.com/ericflo/yourmomdotcom
... |
from itertools import count
def layer(x, y, z, n):
return 2*(x*y + y*z + x*z) + 4*(x + y + z + n - 2) * (n - 1)
print(layer(3, 2, 1, 1)) # 22
print(layer(3, 2, 1, 2)) # 46
print(layer(3, 2, 1, 3)) # 78
print(layer(3, 2, 1, 4)) # 118
print(layer(5, 1, 1, 1)) # 22
limit = 30000
memo = {}
for x in count(1):
... |
from __future__ import absolute_import, division, print_function
import inspect
import logging
from lmfit import Model
from .lineshapes import (elastic, compton, lorentzian2)
from .base.parameter_data import get_para
logger = logging.getLogger(__name__)
def set_default(model_name, func_name):
"""
Set values ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.