code stringlengths 1 199k |
|---|
from __future__ import annotations
import pytest
import scitbx.matrix
from cctbx import crystal, sgtbx, uctbx
from cctbx.sgtbx import bravais_types
from dxtbx.model import Crystal
from dials.algorithms.indexing import symmetry
@pytest.mark.parametrize("space_group_symbol", bravais_types.acentric)
def test_SymmetryHandl... |
"""
Tests for the following offsets:
- BQuarterBegin
- BQuarterEnd
"""
from __future__ import annotations
from datetime import datetime
import pytest
from pandas._libs.tslibs.offsets import QuarterOffset
from pandas.tests.tseries.offsets.common import (
Base,
assert_is_on_offset,
assert_offset_equal,
)
from... |
"""Library for manipulating naclports packages in python.
This library can be used to build tools for working with naclports
packages. For example, it is used by 'update_mirror.py' to iterate
through all packages and mirror them on commondatastorage.
"""
import optparse
import os
import urlparse
import shlex
import sh... |
from precious import db
from datetime import datetime
class Build(db.Model):
__tablename__ = 'builds'
id = db.Column(db.Integer, primary_key=True, unique=True)
project_id = db.Column(db.Integer, db.ForeignKey('projects.id'))
date = db.Column(db.DateTime)
revision = db.Column(db.LargeBinary)
stdo... |
""" Needed Tests
clip_to_rect() tests
--------------------
DONE *. clip_to_rect is inclusive on lower end and exclusive on upper end.
DONE *. clip_to_rect behaves intelligently under scaled ctm.
DONE *. clip_to_rect intersects input rect with the existing clipping rect.
DONE *. c... |
"""Testing for overlap intervals
"""
import unittest
from genda.transcripts.exon_utils import calcOverlap, collideIntervals, \
collapseIntervals
class TestOverlapFunctions(unittest.TestCase):
def setUp(self):
# Simple Overlap
self.simple = [(1,10), (6,15)]
# One interval enclosed in ... |
"""//testing/scripts wrapper for the network traffic annotation auditor checks.
This script is used to run traffic_annotation_auditor_tests.py on an FYI bot to
check that traffic_annotation_auditor has the same results when heuristics that
help it run fast and spam free on trybots are disabled."""
import json
import os... |
"""Fichier définissant la classe BaseNoeud détaillée plus bas."""
class BaseNoeud:
"""Classe représentant la base d'un noeud.
Cette classe est héritée par tous les autres types de noeuds.
"""
importeur = None
def __init__(self):
"""Constructeur du noeud de base"""
self.nom = ""
... |
from math import isclose
import numpy as np
from pytest import fixture
from hoomd.box import Box
@fixture
def box_dict():
return dict(Lx=1, Ly=2, Lz=3, xy=1, xz=2, yz=3)
def test_base_constructor(box_dict):
box = Box(**box_dict)
for key in box_dict:
assert getattr(box, key) == box_dict[key]
@fixture... |
"""
This module provides the Koalix CRM core functionality
""" |
from jenkinsflow.flow import serial
from .framework import api_select
prefixed_jobs = """
serial flow: [
job: 'top_quick1'
serial flow: [
job: 'top_x_quick2-1'
]
serial flow: [
job: 'top_x_quick2-2'
]
serial flow: [
job: 'top_x_quick2-3'
]
job: 'top_quick3'
parallel flow: (
... |
from django import template
from django_users.forms import CreateUserForm
register = template.Library()
@register.inclusion_tag('users/templatetags/registration.html', takes_context = True)
def registration_form(context, form=None, *args, **kwargs):
if not form:
form = CreateUserForm
return {
... |
from hiveplotter import HivePlot
from networkx import nx
import random
from unittest import TestCase
SEED = 1
NTYPES = ['A', 'B', 'C']
class SimpleCase(TestCase):
def make_graph(self):
G = nx.fast_gnp_random_graph(30, 0.2, seed=SEED)
for node, data in G.nodes_iter(data=True):
data['ntype... |
import argparse
import sys
import re
import settings
import psycopg2
import imp
class UpdSource():
def __init__(self,in_source,last_update):
self.upd_dict=dict()
self.source=in_source
self.src_handler=None
self.last_update=last_update
if self.source=='file':
self._parse_file()
def _parse_file(self):
... |
from streamable_archive_tests import *
from delivery_collection_tests import * |
"""
This module contains dsolve() and different helper functions that it
uses.
dsolve() solves ordinary differential equations. See the docstring on
the various functions for their uses. Note that partial differential
equations support is in pde.py. Note that ode_hint() functions have
docstrings describing their vario... |
import roslib; roslib.load_manifest('vigir_behavior_simple_joint_control_test')
from flexbe_core import Behavior, Autonomy, OperatableStateMachine, Logger
from vigir_flexbe_states.check_current_control_mode_state import CheckCurrentControlModeState
from vigir_flexbe_states.change_control_mode_action_state import Change... |
import pytest
from httpie import ExitStatus
from httpie.output.formatters.colors import get_lexer
from utils import TestEnvironment, http, HTTP_OK, COLOR, CRLF
class TestVerboseFlag:
def test_verbose(self, httpbin):
r = http('--verbose',
'GET', httpbin.url + '/get', 'test-header:__test__')
... |
from django.views.generic import ListView, TemplateView
class IndexView(TemplateView):
template_name = 'index.html' |
import hou
import IECore
from _IECoreHoudini import *
from FnParameterisedHolder import FnParameterisedHolder
from FnOpHolder import FnOpHolder
from FnProceduralHolder import FnProceduralHolder
from TestCase import TestCase
from TestProgram import TestProgram
import ParmTemplates
import Utils
from ActiveTake import Act... |
import numpy as np
import warnings
from scipy._lib._util import check_random_state
def rvs_ratio_uniforms(pdf, umax, vmin, vmax, size=1, c=0, random_state=None):
"""
Generate random samples from a probability density function using the
ratio-of-uniforms method.
Parameters
----------
pdf : callab... |
from __future__ import unicode_literals
from django.db import migrations
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('home', '0004_auto_20160511_0845'),
]
operations = [
migrations.AlterField(
model_name='teammember',
name='bio'... |
"""
Contains base level parents that aren't to be used directly.
"""
from twisted.internet.defer import inlineCallbacks, returnValue
from fuzzywuzzy.process import QRatio
from fuzzywuzzy import utils as fuzz_utils
from src.daemons.server.ansi import ANSI_HILITE, ANSI_NORMAL
from src.daemons.server.objects.exceptions im... |
import os
import twitter
import urllib, urllib2
from django.conf import settings
from django.contrib.sites.models import Site
TWITTER_MAXLENGTH = getattr(settings, 'TWITTER_MAXLENGTH', 140)
def post_to_twitter(sender, instance, *args, **kwargs):
"""
Post new saved objects to Twitter.
Example:
from d... |
import sys
import os
import shlex
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'leonardo-api'
copyrigh... |
import wpan
from wpan import verify
test_name = __file__[:-3] if __file__.endswith('.py') else __file__
print('-' * 120)
print('Starting \'{}\''.format(test_name))
speedup = 4
wpan.Node.set_time_speedup_factor(speedup)
NUM_CHILDREN = 7
router = wpan.Node()
children = []
for i in range(NUM_CHILDREN):
children.append... |
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url('^$',
'actionkit_raplet.views.raplet',
name='raplet'),
) |
import datetime
import commonware.log
import django_tables as tables
import jinja2
from django.conf import settings
from django.template import Context, loader
from django.utils.datastructures import SortedDict
from jingo import register
from tower import ugettext as _, ugettext_lazy as _lazy, ungettext as ngettext
imp... |
'''
Created on May 9, 2014
@author: Jennifer Reiber Kyle
'''
from kaggle import Submitter, DataReader
from prediction import Preprocessor, Classifier
def runPrediction(sourceDirectory,submitDirectory):
reader = DataReader(dataDir)
p = Preprocessor(*reader.getData())
submitter = Submitter(submitDir)
trai... |
from setuptools import setup
setup(
name="Ente",
version="0.1",
description="place finder on commoncrawl dataset",
author="László Nagy",
author_email="rizsotto@gmail.com",
license='LICENSE',
url='https://github.com/rizsotto/Ente',
long_description=open('README.md').read(),
scripts=['... |
"""Functional tests using WebTest.
See: http://webtest.readthedocs.org/
"""
from flask import url_for
from power_grid_helper.user.models import User
from .factories import UserFactory
class TestLoggingIn:
"""Login."""
def test_can_log_in_returns_200(self, user, testapp):
"""Login successful."""
... |
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from nose.tools import assert_raises
from nose.tools import assert_dict_equal
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_eq... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import math
import random
import unittest
from measurement_stats import angle
from measurement_stats import value
from measurement_stats import value2D
HALF_SQRT_2 = 0.5 *... |
import nose
def test_nose_working():
"""
Test that the nose runner is working.
"""
assert True |
default_app_config = 'django_tenants.apps.DjangoTenantsConfig' |
import os
def numCPUs():
if not hasattr(os, "sysconf"):
raise RuntimeError("No sysconf detected.")
return os.sysconf("SC_NPROCESSORS_ONLN")
bind = "127.0.0.1:8000"
workers = numCPUs() * 2 + 1 |
import os
import libxml2
from sfatables.command import Command
from sfatables.globals import sfatables_config, target_dir, match_dir
class Add(Command):
def __init__(self):
self.options = [('-A','--add')]
self.help = 'Add a rule to a chain'
self.matches = True
self.targets = True
... |
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to de... |
from sensu_plugin import SensuPluginMetricJSON
import requests
import json
from sh import curl
from walrus import *
import math
import statsd
import warnings
from requests.packages.urllib3 import exceptions
db = Database(host='localhost', port=6379, db=0)
c = statsd.StatsClient('grafana', 8125)
class FooBarBazMetricJSO... |
"""ACE -- Automated Coordinate Extraction.
"""
__all__ = ["config", "database", "datatable", "exporter", "set_logging_level", "scrape", "sources", "tableparser", "tests", "__version__"]
import logging
import sys
import os
from version import __version__
def set_logging_level(level=None):
"""Set package-wide logging... |
import sys
import getopt
import re as re_
import base64
import datetime as datetime_
etree_ = None
Verbose_import_ = False
(
XMLParser_import_none, XMLParser_import_lxml,
XMLParser_import_elementtree
) = range(3)
XMLParser_import_library = None
try:
# lxml
from lxml import etree as etree_
XMLParser_... |
import json
from prismriver import util, main
class SongJsonEncoder(json.JSONEncoder):
def default(self, o):
return o.__dict__
def format_output(songs, output_format, txt_template=None):
if output_format == 'txt':
formatted_songs = []
for song in songs:
lyrics_txt = ''
... |
import cStringIO
import os
import tarfile
import zipfile
def test_download(data_builder, file_form, as_admin, api_db):
project = data_builder.create_project(label='project1')
session = data_builder.create_session(label='session1')
session2 = data_builder.create_session(label='session1')
session3 = data_... |
from __future__ import unicode_literals, division, absolute_import
import os
from flexget import plugin
from flexget.event import event
from flexget.utils import json
def load_uoccin_data(path):
udata = {}
ufile = os.path.join(path, 'uoccin.json')
if os.path.exists(ufile):
try:
with open... |
from django.test import TestCase
from django.contrib.auth import get_user_model
from model_mommy import mommy
from rolepermissions.roles import RolesManager, AbstractUserRole
class RolRole1(AbstractUserRole):
available_permissions = {
'permission1': True,
'permission2': True,
}
class RolRole2(Ab... |
import argparse
import sys
def gen_primes():
""" Generate an infinite sequence of prime numbers.
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number bein... |
from __future__ import unicode_literals
from arpeggio import ParserPython, Optional, EOF
def g(): return [Optional('first'), Optional('second'), Optional('third')], EOF
def test_optional_in_choice():
parser = ParserPython(g)
input_str = "second"
parse_tree = parser.parse(input_str)
assert parse_tree ... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from reviews_manager.models import ClinicalAnnotationStep
from rois_manager.models import Slice, Core, FocusRegion
class SliceAnnotation(models.Model):
author = models.ForeignKey(User, on_delete=models.PROTECT... |
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_lost_aqualish_soldier_female_01.iff"
result.attribute_template_id = 9
result.stfName("npc_name","aqualish_base_female")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import operator
from textwrap import dedent
from twisted.trial import unittest
from ometa.grammar import OMeta, TermOMeta, TreeTransformerGrammar
from ometa.compat import OMeta1
from ometa.runtime import (ParseError, OMetaBase, OMetaGrammarBase, EOFError,
expected, TreeTransformerBase)
from o... |
__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.2 $"
__date__ = "$Date: 2016/05/31$"
__revision__ = "$Date: 2016/06/11 $"
__copyright__ = "Copyright 2016 Luxembourg Institute of Science and Technology"
__license__ = ""
import logging
import datetime
from werkzeug import generate_password_hash
from flask impo... |
from image_mat_util import *
from mat import Mat
from vec import Vec
import matutil
from solver import solve
def move2board(v):
'''
Input:
- v: a vector with domain {'y1','y2','y3'}, the coordinate representation of a point q.
Output:
- A {'y1','y2','y3'}-vector z, the coordinate representat... |
import unittest
from common.BinaryTree import BinaryTree
from .. import BinaryTreeMaximumPathSum
class test_BinaryTreeMaximumPathSum(unittest.TestCase):
solution = BinaryTreeMaximumPathSum.Solution()
def test_maxPathSum(self):
self.assertEqual(self.solution.maxPathSum(BinaryTree.create_tree([1, 2, 3])[0... |
"""DNS Wire Data Helper"""
import dns.exception
from ._compat import binary_type, string_types, PY2
class _SliceUnspecifiedBound(binary_type):
def __getitem__(self, key):
return key.stop
if PY2:
def __getslice__(self, i, j): # pylint: disable=getslice-method
return self.__getitem__(... |
"""
WSGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "firstapp.settings")
from django.core.wsgi ... |
from cupy import elementwise
_id = 'out0 = in0'
_clip = elementwise.create_ufunc(
'cupy_clip',
('???->?', 'bbb->b', 'BBB->B', 'hhh->h', 'HHH->H', 'iii->i', 'III->I',
'lll->l', 'LLL->L', 'qqq->q', 'QQQ->Q', 'eee->e', 'fff->f', 'ddd->d'),
'out0 = min(in2, max(in1, in0))')
def clip(a, a_min, a_max, out=No... |
from common2 import *
class rsm:
def __init__(self,n,m,c=0,**kw):
"""Random Sample Memory
n -- number of neurons
m -- max connections per neuron (memory)
"""
self.mem = {j:set() for j in range(n)}
self.win = {j:0 for j in range(n)}
self.tow = {j:-42000 for j in range(n)} # time of win
self.t = 0
se... |
from setuptools import setup, find_packages
version = "6.3.0"
with open("requirements.txt", "r") as f:
install_requires = f.readlines()
setup(
name='frappe',
version=version,
description='Metadata driven, full-stack web framework',
author='Frappe Technologies',
author_email='info@frappe.io',
pa... |
import fibo
def test():
"""Test cases."""
print('Example 1:')
fibo.fib(1000)
print('Example 2:')
print(fibo.fib1(1000))
print('Example 3:')
print(fibo.__name__)
# Assigning function a local name
fib = fibo.fib
print('Example 4:')
fib(1000)
if __name__ == '__main__':
test(... |
import cv2
import os
import scipy.misc as misc
path = os.getcwd()
for x in xrange(15):
rgb = cv2.imread(path + '/output/rgb_img_' + str(x) + '.jpg')
depth = cv2.imread(path + '/output/depth_img_' + str(x) + '.jpg')
depth_inquiry = depth.copy()
# depth_inquiry[depth_inquiry > 180] = 0
# Depth thresho... |
"""distutils.fancy_getopt
Wrapper around the standard getopt module that provides the following
additional features:
* short and long options are tied together
* options have help strings, so fancy_getopt could potentially
create a complete usage summary
* options set attributes of a passed-in object
"""
__re... |
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/creature/npc/droid/shared_wed_treadwell_base.iff"
result.attribute_template_id = 3
result.stfName("droid_name","wed_treadwell_base")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
from decouple import Csv, config
from dj_database_url import parse as db_url
from .base import * # noqa
DEBUG = False
SECRET_KEY = config('SECRET_KEY')
DATABASES = {
'default': config('DATABASE_URL', cast=db_url),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
... |
from setuptools import setup, find_packages
DESCRIPTION = """
Send emails based on a Django template
See:
https://github.com/prestontimmons/django-email-template
"""
setup(
name="django-email-template",
version="1.0.2",
description="Send emails based on a Django template",
long_description=DESCRIPTION,
... |
import django_filters
from dal import autocomplete
from .models import SkosConcept, SkosConceptScheme
django_filters.filters.LOOKUP_TYPES = [
('', '---------'),
('exact', 'Is equal to'),
('iexact', 'Is equal to (case insensitive)'),
('not_exact', 'Is not equal to'),
('lt', 'Lesser than/before'),
... |
from django.test import override_settings, SimpleTestCase
from arcutils.settings import NO_DEFAULT, PrefixedSettings, get_setting
@override_settings(ARC={
'a': 'a',
'b': [0, 1],
'c': [{'c': 'c'}],
'd': 'd',
})
class TestGetSettings(SimpleTestCase):
def get_setting(self, key, default=NO_DEFAULT):
... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "battleground.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from swgpy.object import *
def create(kernel):
result = Mission()
result.template = "object/mission/base/shared_base_mission.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import os
from collections import namedtuple
from eg import color
from eg import config
from mock import patch
_YELLOW = '\x1b[33m'
_MAGENTA = '\x1b[35m'
_BLACK = '\x1b[30m'
_GREEN = '\x1b[32m'
SubFlags = namedtuple(
'SubFlags',
[
'pound',
'pound_reset',
'heading',
'heading_reset... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/attachment/weapon/shared_blacksun_heavy_weapon2_s02.iff"
result.attribute_template_id = 8
result.stfName("item_n","ship_attachment")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
"""Test kytos.core.buffers module."""
import asyncio
from unittest import TestCase
from unittest.mock import MagicMock, patch
from kytos.core.buffers import KytosBuffers, KytosEventBuffer
class TestKytosEventBuffer(TestCase):
"""KytosEventBuffer tests."""
def setUp(self):
"""Instantiate a KytosEventBuff... |
import sys
import codecs
from textblob import Blobber
from textblob.wordnet import Synset
from textblob.en.np_extractors import ConllExtractor
from collections import Counter
import re
from nltk.corpus import wordnet as wn
from nltk.corpus.reader import NOUN
import os
import string
import itertools
from nltk.corpus imp... |
from decimal import Decimal
from electrum.util import (format_satoshis, format_fee_satoshis, parse_URI,
is_hash256_str, chunks)
from . import SequentialTestCase
class TestUtil(SequentialTestCase):
def test_format_satoshis(self):
self.assertEqual("0.00001234", format_satoshis(1234)... |
__all__ = [ 'SystemInfoWdg', 'LinkLoadTestWdg' ,'ClearSideBarCache']
import os, platform, sys
from pyasm.common import Environment, Config, Common
from pyasm.security import Login
from tactic.ui.common import BaseRefreshWdg
from pyasm.web import DivWdg, Table, WebContainer, Widget, SpanWdg
from pyasm.search import Sear... |
from TestCase import TestCase
import NetworkEventHandler as NEH
import Log
class case901 (TestCase):
def config(self):
self.name = "Case 901"
self.description = "Presence of RFC3261 branch ID in Via"
self.isClient = False
self.transport = "UDP"
self.interactRequired = True
def run(self):
self.neh = NEH.Ne... |
hostname_patterns = [
'SMI::enterprises.2349.2.2.2.5 = "(.*)"'
]
import time
import sys
import re
site_name = "TESTSITE"
deamon_path = "/omd/sites/%s/tmp/run/mkeventd/events" % site_name
data = []
match_host = False
for line in sys.stdin:
line = line.strip()
if hostname_patterns:
for pattern in hostn... |
from cities_light.models import Country, City
from django.test import TestCase
from django.contrib.auth.models import User
from blog.models import Tag, ResourceType, News, Resource
from community.models import Community
from users.models import SystersUser
class TagModelTestCase(TestCase):
def test_str(self):
... |
import mistune
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import html
from flask import current_app, render_template
from application.models.system import site
from application.services.system import has
base_env = {
'site': site,
'has': has,
'tags'... |
"""
Created on Thu Nov 6 15:32:36 2014
@author: commun
Converts filtered data sets to tx2 format used in Aarhusinv.
CHANGELOG:
"""
import numpy as np
path_filt = '../shiprock_filt/v4/l8_1_mg_4b.dat'
path_tx2 = '../'
electrode_spacing = 2
pulselength=2
ngates=20
frags = path_filt.split('/')
lid = frags[-1][:-4]
ngates ... |
from sqlobject.dbconnection import registerConnection
def builder():
import mysqlconnection
return mysqlconnection.MySQLConnection
def isSupported():
try:
import MySQLdb
except ImportError:
return False
return True
registerConnection(['mysql'], builder, isSupported) |
from time import sleep
vtysh_cr = "\r\n"
route_max_wait_time = 300
class SwitchVtyshUtils():
@staticmethod
def vtysh_cfg_cmd(switch, cfg_array, show_running_cfg=False,
show_results=False):
switch("configure terminal")
for cmd in cfg_array:
result = switch(cmd)
... |
import networkx as nx
import re
def get_graph_info(file_path):
def extract_first_two(collection):
return [int(collection[0]), int(collection[1])]
with open(file_path) as ifs:
lines = map(lambda ele: ele.strip(), ifs.readlines())
lines = filter(lambda ele: not ele.startswith('#') and re.m... |
"""
***************************************************************************
SumLines.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*******************************************************... |
import wx
class Choice(wx.Choice):
def GetValue(self):
return self.GetSelection() |
__author__ = 'Tom Schaul, tom@idsia.ch'
from pybrain.utilities import blockCombine
from scipy import mat, dot, outer
from scipy.linalg import inv, cholesky
def calcFisherInformation(sigma, invSigma=None, factorSigma=None):
""" Compute the exact Fisher Information Matrix of a Gaussian distribution,
given its cov... |
class MastermindError(Exception):
@property
def code(self):
return MASTERMIND_ERROR_CODES[type(self)]
@staticmethod
def make_error(code, msg):
if code not in MASTERMIND_ERROR_CLS:
raise ValueError('Unknown error code {}'.format(code))
return MASTERMIND_ERROR_CLS[code]... |
__author__ = "Dulip Withanage"
__email__ = "dulip.withanage@gmail.com"
import re
import string
import sys
import operator
import globals as gv
import os
import subprocess
import shutil
class FrontMatterParser:
def __init__(self, gv):
self.gv = gv
def parse_authors(self, filestring):
# this works for perception-m... |
import os
import grp
import tempfile
from django.conf import settings
from utilities import encoding
import shutil
import zipfile
gid = None
if (settings.USEPRAKTOMATTESTER):
gid = grp.getgrnam('praktomat').gr_gid
def makedirs(path):
if os.path.exists(path):
return
else:
(head, tail) = os.pa... |
from __future__ import print_function, unicode_literals
from datetime import datetime, timedelta
import time
import unittest
from DenyHosts.counter import Counter, CounterRecord
class CounterRecordTest(unittest.TestCase):
def test_init(self):
c = CounterRecord()
self.assertEqual(c.get_count(), 0)
... |
import sys
import getopt
import os
import libvirt
import select
import errno
import time
import threading
use_pure_python_event_loop = True
do_debug = False
def debug(msg):
global do_debug
if do_debug:
print(msg)
class virEventLoopPure:
# This class contains the data we need to track for a
# sin... |
__all__ = [
'ui',
'lib',
'daemon',
'modules',
] |
import inc_const as const
PJSUA = ["--null-audio --max-calls=1 --id sip:pjsua@localhost --add-buddy $SIPP_URI"]
PJSUA_EXPECTS = [[0, "", "s"],
[0, "Subscribe presence of:", "1"],
[0, "Presence subscription .* is TERMINATED", ""],
[0, "Resubscribing .* in 5000 ms", ""]
] |
from llvmlite import ir
from ctypes import CFUNCTYPE, c_float
import llvmlite.binding as llvm
from ply import yacc
from lex_ula import tokens
import os
import sys
start = "Start"
def p_start(p):
"""Start : Program"""
p[0] = p[1]
def p_program_statements(p):
"""Program : Statements"""
p[0] = ["Program", ... |
"""
Option class representing a list of places.
"""
from . import Option
class PlaceListOption(Option):
"""
This class describes a widget that allows multiple places from the
database to be selected.
"""
def __init__(self, label):
"""
:param label: A label to be applied to this optio... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from django import VERSION
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'SignalDeferredDispatch'
db.create_table(u'dbmail_signalde... |
"""
The OpenMP package does contain all code templates required for the openMP
code generation in ANNarchy.
BaseTemplates:
defines the basic defintions common to all sparse matrix formates, e. g. projection header
[FORMAT]_SingleThread:
defines the format specific defintions for the currently available formats:... |
import urllib.request
import time
preço = 99.99 #algum valor maior
while preço >= 4.74:
pagina = urllib.request.urlopen(
'http://beans.itcarlow.ie/prices-loyalty.html')
texto = pagina.read().decode('utf8')
onde = texto.find('>$')
início = onde + 2
fim = início + 4
preço = float(texto[início:... |
import pcapy
import socket
import time
from random import randint
from mitmflib.impacket import structure, ImpactDecoder
class BootpPacket(structure.Structure):
commonHdr = (
('op','b'),
('htype','b=1'), # 1 = Ether
('hlen','b=len(chaddr)'),
('hops','b=0'),
... |
from parso.python import tree
from parso.python.token import PythonTokenTypes
from parso.parser import BaseParser
NAME = PythonTokenTypes.NAME
INDENT = PythonTokenTypes.INDENT
DEDENT = PythonTokenTypes.DEDENT
class Parser(BaseParser):
"""
This class is used to parse a Python file, it then divides them into a
... |
from utils import get_class
class AbstractRankingFunction:
"""Abstract base class for ranking functions."""
def __init__(self,
ranker_arg_str,
ties,
feature_count,
init=None,
sample=None):
self.feature_count = feature_c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.