content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
"""
Simulate failure of the worker AI grading tasks.
When the workers fail to successfully complete AI grading,
the AI grading workflow in the database will never be marked complete.
To simulate the error condition, therefore, we create incomplete
AI grading workflows without scheduling a gradi... |
{
"name" : "Mexico - Accounting",
"version" : "2.0",
"author" : "Vauxoo",
"category" : "Localization/Account Charts",
"description": """
Minimal accounting configuration for Mexico.
============================================
This Chart of account is a minimal proposal to be able to use OoB the
a... |
"""Unicode email support (extends email from stdlib)"""
__docformat__ = "restructuredtext en"
import email
from encodings import search_function
import sys
if sys.version_info >= (2, 5):
from email.utils import parseaddr, parsedate
from email.header import decode_header
else:
from email.Utils import parse... |
import numpy as np
from numba import cuda, float32, float64, int32, void
from numba.cuda.testing import unittest, CUDATestCase
class TestCudaIDiv(CUDATestCase):
def test_inplace_div(self):
@cuda.jit(void(float32[:, :], int32, int32))
def div(grid, l_x, l_y):
for x in range(l_x):
... |
import asyncio
import logging
from operator import attrgetter
from urllib.parse import urlparse, parse_qsl
from http.cookies import SimpleCookie
from .util import cached_property
from .core import Context
from .core import ValueResolver, HierarchicalResolver
from .core import Scope, endpoint, resource
from .exceptions... |
"""
Solve the orthogonal Procrustes problem.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from .decomp_svd import svd
__all__ = ['orthogonal_procrustes']
def orthogonal_procrustes(A, B, check_finite=True):
"""
Compute the matrix solution of the orthogonal Procrus... |
import Tkinter
def properties(app, title, names, props):
t = Tkinter.Toplevel(app)
t.wm_transient(app)
t.wm_title(title)
t.wm_iconname(title)
t.wm_resizable(0,0)
for i, (k, n) in enumerate(names):
if k not in props: continue
l = Tkinter.Label(t, text = n)
l.grid(row=i, co... |
#! /usr/bin/env python
import os
import time
import sqlite3
import yaml
import re
import codecs
import logging
from flask import Flask, request, redirect, url_for, render_template, abort
from werkzeug import secure_filename
with open(u'%s/conf.yaml' % os.path.dirname(__file__), u'r') as f:
conf = yaml.safe_load(f... |
import sys, itertools, time, os, random
from ctypes import cdll, c_float, c_int, c_uint, c_void_p, Structure, addressof, create_string_buffer, cast, POINTER, pointer
from struct import pack, unpack, calcsize ... |
__author__ = 'tester'
class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, username, password):
wd = self.app.wd
wd.find_element_by_name("user").click()
wd.find_element_by_name("user").clear()
wd.find_element_by_name("user").send_keys("%s" % us... |
"""
Test Suite formatting:
>>> Suite.spades
<Suite.spades: 0>
>>> print(Suite.spades)
Suite.spades
>>> format(Suite.spades)
'spades'
>>> format(Suite.spades, 's')
'spades'
>>> format(Suite.spades, 'S')
'Spades'
>>> format(Suite.spades, 'p')
'♠'
>>> format(Suite.spade... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import base64
try:
import yaml
has_lib_yaml = True
except ImportError:
has_lib_yaml = False
############################################################################
######... |
"""distutils.archive_util
Utility functions for creating archive files (tarballs, zip files,
that sort of thing)."""
import os
from warnings import warn
import sys
try:
import zipfile
except ImportError:
zipfile = None
from distutils.errors import DistutilsExecError
from distutils.spawn import spawn
from d... |
from app import Roles
from app.repository import page_repository
from app.service import group_service, role_service
def set_read_page_permissions(page, new_groups):
current_groups = set(get_read_permission_groups_by_page(page))
new_groups = set(new_groups)
added_groups = new_groups - current_groups
... |
"""
Amd64 Support Module
"""
# Copyright (C) 2007 Invisigoth - See LICENSE file for details
import struct
import envi.archs.amd64 as e_amd64
import vtrace.archs.i386 as vt_i386
class Amd64Mixin(
e_amd64.Amd64Module,
e_amd64.Amd64RegisterContext,
vt_i386.i386WatchMixin):
"""
Do what we ... |
# -*- 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 'RegistrationCodeRedemption.course_enrollment'
db.add_column('shoppingcart_registrationcodere... |
#!/usr/bin/python
import sys
import time
import serial
from optparse import OptionParser, make_option
print "Loading twitter library"
execfile("twt.py")
from random import choice
sales = ['Sales are up 64% since last year!',
'With this rate, we\'re going to run out of stock soon!',
'All I do is - vend, vend, vend -... |
import os
import unittest
from telemetry.page import page_measurement_results
from telemetry.page import page_set
from telemetry.page import perf_tests_helper
def _MakePageSet():
return page_set.PageSet.FromDict({
"description": "hello",
"archive_path": "foo.wpr",
"pages": [
{"url": "http:... |
from SernaApi import *
import os
class TopicClickWatcher(SimpleWatcher):
def __init__(self, dp):
SimpleWatcher.__init__(self)
self.dp_ = dp
def notifyChanged(self):
se = self.dp_().sernaDoc().structEditor()
pos = se.getCheckedPos()
if not pos or pos.node().nodeName() !... |
"""Handler to make calls against the AdWords API."""
import time
from demo import VERSION
from googleads.adwords import AdWordsClient
from googleads.errors import GoogleAdsError
from googleads.oauth2 import GoogleRefreshTokenClient
class APIHandler(object):
"""Handler for the AdWords API using the Ads Python Cl... |
import logging
import os
from lintreview.tools import Tool
from lintreview.tools import run_command
from lintreview.utils import in_path
from lintreview.utils import npm_exists
log = logging.getLogger(__name__)
class Jshint(Tool):
name = 'jshint'
def check_dependencies(self):
"""
See if jsh... |
import click
import numpy as np
from tabulate import tabulate
from nupic.research.support import parse_config
STRIDE = 1
PADDING = 0
KERNEL_SIZE = 5
@click.command()
@click.option(
"-c",
"--config",
metavar="FILE",
type=open,
default="gsc/experiments.cfg",
show_default=True,
help="your e... |
from rdkit import Geometry
from rdkit import Chem
from rdkit.Chem import ChemicalFeatures
class FeatMapPoint(ChemicalFeatures.FreeChemicalFeature):
weight=0.0
featDirs = None
def __init__(self,*args,**kwargs):
ChemicalFeatures.FreeChemicalFeature.__init__(self,*args,**kwargs)
self.featDirs=[]
def init... |
"""Creates symlinks to native libraries for an APK.
The native libraries should have previously been pushed to the device (in
options.target_dir). This script then creates links in an apk's lib/ folder to
those native libraries.
"""
import optparse
import os
import sys
from util import build_device
from util import ... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify the behavior of passing our own function to Progress().
"""
import TestSCons
test = TestSCons.TestSCons()
test.write('SConstruct', """\
import sys
env = Environment()
env['BUILDERS']['C'] = Builder(action=Copy('$TARGET', '$SOURCE'))
def my_pro... |
import mock
from oslo_concurrency import processutils
from nova import test
from nova import utils
from nova.virt.libvirt.volume import remotefs
class RemoteFSTestCase(test.NoDBTestCase):
"""Remote filesystem operations test case."""
@mock.patch.object(utils, 'execute')
def _test_mount_share(self, mock_... |
"""
Based on "TinyMCE Compressor PHP" from MoxieCode.
http://tinymce.moxiecode.com/
Copyright (c) 2008 Jason Davies
Licensed under the terms of the MIT License (see LICENSE.txt)
"""
from datetime import datetime
import os
import re
from django.conf import settings
from django.core.cache import cache
... |
import os
import click
import boto3
import botocore
import dpath.util
import botocore.vendored.requests.packages.urllib3 as urllib3
urllib3.disable_warnings(urllib3.exceptions.SecurityWarning)
from base64 import b64decode
from .base import BaseHelper
# TODO: Better permissions checking
class AWSHelper(BaseHelper):... |
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings'
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "List language codes."
def add_arguments(self, parser):
parser.add_argument(
'--project',
action='append',
des... |
{
'name': 'Account Journal Always Check Date',
'version': '0.1',
'category': 'Accounting & Finance',
'license': 'AGPL-3',
'summary': 'Option Check Date in Period always active on journals',
'description': """
Check Date in Period always active on Account Journals
================================... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 07 11:08:41 2016
@author: Radu
"""
import numpy
import simrun
import time
from ballandstick_clarke_new import ClarkeRelay
#from neuron import h,gui
from neuron import h
h.load_file('stdgui.hoc')
#h.load_file("stdrun.hoc")
from math import sin, cos, pi
from matplotlib im... |
import datetime
import requests
from flask_socketio import emit
from home.core.models import get_device
from home.web.utils import ws_login_required
from home.web.web import socketio
NEXTBUS_URL = 'http://webservices.nextbus.com/service/publicJSONFeed?a=cyride&command=predictions&stopId={}'
class NextBus:
def _... |
from __future__ import absolute_import, unicode_literals
import datetime
import time
import warnings
from email.header import Header
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from django.conf import settings
from django.core import signals
from django.core import... |
###import the simple module from the paraview
from paraview.simple import *
#### disable automatic camera reset on 'Show'
paraview.simple._DisableFirstRenderCameraReset()
total_proc=2
#Render={}
#Disp={}
#get active source.
#ActiveReader= GetActiveSource()
# get active view
#renderView1 = GetActiveViewOrCreate('Rende... |
"""convert Gettext PO localization files to plain text (.txt) files
see: http://translate.sourceforge.net/wiki/toolkit/po2txt for examples and
usage instructions
"""
try:
import textwrap
except ImportError:
textwrap = None
from translate.storage import factory
class po2txt:
"""po2txt can take a po file... |
#coding=utf-8
from cart import Cart
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import *
from voodoo.admin_center.models import Product
from voodoo.admin_center.models import Order, OrderStatus
from django.utils.simplejson import dumps
def add_to_cart(r... |
#!/usr/bin/python3
#-*-coding:utf-8-*-
#$File: trainer.py
#$Date: Sat May 7 11:00:10 2016
#$Author: Like Ma <milkpku[at]gmail[dot]com>
from config import Config
from dataset import load_data
from model import get_model
import tensorflow as tf
import argparse
import logging
def train(args):
device = args.devic... |
import argparse
import sys
from os.path import dirname, exists, isdir
from mycroft.configuration import ConfigurationManager
from mycroft.messagebus.client.ws import WebsocketClient
from mycroft.skills.core import create_skill_descriptor, load_skill
from mycroft.skills.intent_service import IntentService
from mycroft... |
import numpy as np
import cv2
from motioncapture.tracking import ObjectDetection
class Calibrator:
def __init__(self, gridDimensions, camera):
self.gridDimensions = gridDimensions
self.camera = camera
self.reset()
self.point = np.zeros((self.gridDimensions[0] * self.gridDimensions[1... |
"""Tests for Samba library functions."""
import sys, re, comfychair
from unicodenames import *
class snprintf_Test(comfychair.TestCase):
def runtest(self):
# Everything is built in to the test
out, err = self.runcmd('t_snprintf')
# Define the tests exported by this module
tests = [snprint... |
import account_analytic_analysis
import res_config
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""Test aiohttp request helper."""
from aiohttp import web
from homeassistant.components.cloud import utils
def test_serialize_text():
"""Test serializing a text response."""
response = web.Response(status=201, text="Hello")
assert utils.aiohttp_serialize_response(response) == {
"status": 201,
... |
# vim:tw=50
"""Exercise: For Loops (1)
For loops are pretty handy and compactly defined.
They fit the way that people think when they want
to "do something to everything in this list".
They're also good for making one list from another
one. We'll do that, here.
Sometimes you have a list, and you realy just want
to ... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ImportError:... |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import sys, hashlib, random
DEFAULT_BLOCK_SIZE = 128 # 128 bytes
BYTE_SIZE = 256 # One byte has 256 different values.
def cipher(request):
"""密码学"""
return render(r... |
"""Handles converting of pragmas."""
class PragmaHandler(object):
"""Class that handles the conversion of pragmas."""
def __init__(self, warning_method):
"""Create a pragma handler.
Args:
warning_method: A function to call to display a warning message.
"""
self._warning_method = warning_... |
import sys
sys.path.insert(0, '.')
sys.path.insert(0, '..')
from Hydranet.db import DB, User, Customer, Graph, Data, Sensor, Alert
import ConfigParser
from os.path import expanduser
def openDatabase():
config = ConfigParser.ConfigParser()
config.read(expanduser('~/hydranetrc'))
dbname = 'Database_test'
... |
import logging
import xml.dom.minidom
_log = logging.getLogger(__name__)
class UnitTestResults(object):
@classmethod
def results_from_string(self, string):
if not string:
return None
try:
dom = xml.dom.minidom.parseString(string)
failures = []
f... |
"""The server password extension."""
from nova.api.metadata import password
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova import compute
authorize = extensions.extension_authorizer('compute', 'server_password')
class ServerPasswordCont... |
"""
Czech-specific form helpers
"""
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Select, RegexField, Field
from django.utils.translation import ugettext_lazy as _
import re
birth_number = re.compile(r'^(?P<birth>\d{6})/?(?P<id>\d{3,4})$')
ic_... |
import xbmc
import xbmcgui
import os
import re
import urllib2
def getPath():
path = xbmc.translatePath('special://home/addons')
path = os.path.join(path, 'Navi-X')
return path
def installed():
return os.path.exists(getPath())
def getVersion():
path = getPath()
file = os.pa... |
from __future__ import absolute_import, division, print_function
import operator
import os
import platform
import sys
from pip._vendor.pyparsing import (
ParseException, ParseResults, stringStart, stringEnd,
)
from pip._vendor.pyparsing import ZeroOrMore, Group, Forward, QuotedString
from pip._vendor.pyparsing im... |
from couchpotato.core.helpers.encoding import tryUrlencode
from couchpotato.core.helpers.rss import RSS
from couchpotato.core.helpers.variable import cleanHost, splitString, tryInt
from couchpotato.core.logger import CPLog
from couchpotato.core.providers.base import ResultList
from couchpotato.core.providers.nzb.base i... |
from optparse import make_option
from google.appengine._internal.django.conf import settings
from google.appengine._internal.django.core.management.base import AppCommand, CommandError
from google.appengine._internal.django.core.management.color import no_style
from google.appengine._internal.django.core.management.sq... |
from ambari_client.model import host
__docformat__ = "epytext"
def _add_hosts(root_resource, cluster_name , host_list):
"""
Adds a hosts to a cluster.
@param root_resource: The root Resource object.
@param cluster_name: Cluster name
@param host_list: list of hosts
@return: A StatusModel object
"""
ret... |
{
'name': 'Products & Pricelists',
'version': '1.1',
'author': 'OpenERP SA',
'category': 'Sales Management',
'depends': ['base', 'decimal_precision', 'mail'],
'demo': [
'product_demo.xml',
'product_image_demo.xml',
],
'description': """
This is the base module for managin... |
#!/usr/bin/python
"""
Threat Matrix Model
Original Author: Matthew Perry and Shaun Walbirdge
ArcGIS port: Shaun Walbridge
python $PROJECT_DIR/code/threats/threat_model_arcgis.py $PROJECT_DIR/data/matrices/generated/all_med_annual_sst.csv model_all_med_annual_sst
"""
# ArcGIS implementation
import arcpy
from... |
# Write a function 'kalman_filter' that implements a multi-
# dimensional Kalman Filter for the example given
from math import *
class matrix:
# implements basic operations of a matrix class
def __init__(self, value):
self.value = value
self.dimx = len(value)
self.dimy = len(value[0... |
#!/usr/bin/python
#============================ adjust path =====================================
import sys
import os
if __name__ == '__main__':
here = sys.path[0]
sys.path.insert(0, os.path.join(here, '..'))
#============================ imports =========================================
import... |
#!/usr/bin/python
import sys
from time import time
# Parametros:
# - k : indice del trabajo a asignar.
# - tiempos : vector con los tiempos de los m trabajos.
# - solucion_actual : vector con el tiempo de trabajo
# asignado a cada maquina.
# - max_tiempo : Maximo de solucion_actual
# - maquina... |
from distutils import errors
import os
_extra_files = []
def get_extra_files():
global _extra_files
return _extra_files
def set_extra_files(extra_files):
# Let's do a sanity check
for filename in extra_files:
if not os.path.exists(filename):
raise errors.DistutilsFileError(
... |
"""
Tests for kqueue wrapper.
"""
import socket
import errno
import time
import select
import sys
import unittest
from test import test_support
if not hasattr(select, "kqueue"):
raise unittest.SkipTest("test works only on BSD")
class TestKQueue(unittest.TestCase):
def test_create_queue(self):
kq = sel... |
import os
from resolwe.flow.models import Data, Secret
from resolwe.test import tag_process
from resolwe_bio.utils.test import BioProcessTestCase
class ImportProcessorTestCase(BioProcessTestCase):
@tag_process("import-sra", "import-sra-single", "import-sra-paired")
def external_test_sra(self):
# sin... |
"""Functional test for GradientDescent."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import backprop
from tensorflow.python.eager import context
from tensorflow.python.eager import function
from tensorflow.python.framework... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.usd
~~~~~~~~~~~~~~~~~~~
The module that parses Pixar's Universal Scene Description file format.
:copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroup... |
#!/usr/bin/env python
from .Rule import Rule
class CopyRule(Rule):
def __init__(self, hist, ruleHist, srcID, srcField, dstID, dstField, typ, ptype, content):
Rule.__init__(self, hist, ruleHist, srcID, srcField, dstID, dstField)
self.typ = typ
self.ptype = ptype
if 'Comp' in self.t... |
from __future__ import unicode_literals
import mimetypes
import os
import random
import sys
import time
from email import (
charset as Charset, encoders as Encoders, generator, message_from_string,
)
from email.header import Header
from email.message import Message
from email.mime.base import MIMEBase
from email.m... |
#/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import unicodedata
import re
import codecs
import os
# tag set
#tag-set:
#m: number
#e: non CJK char, e.g. English pinyin
#[unuse] t: time. 年号 干支等(此处识别出后,仅加入 oov ,不参与实际分词)
#c: CJK char.
#s: Symbol e.g. @
#w: Sentence seperator.
#x: unknown char.
... |
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
OSC = '\033]'
BEL = '\007'
def code_to_chars(code):
return CSI + str(code) + 'm'
class AnsiCodes(object):
def __init__(self, codes):
for name in dir(c... |
import mock
import pytest
from mock import Mock
from olympia import amo
from olympia.amo import models as amo_models
from olympia.amo.tests import TestCase
from olympia.amo import models as context
from olympia.addons.models import Addon
from olympia.users.models import UserProfile
pytestmark = pytest.mark.django_db... |
"""
NFCBeer
Usage:
nfcbeer.py client <id>
nfcbeer.py server
nfcbeer.py [-h | --help]
Options:
-h --help Shows help
"""
from docopt import docopt
import time
import RPi.GPIO as GPIO
import random
import MFRC522
import sys
import zmq
context = zmq.Context()
sock = context.socket(zmq.REQ)
sock... |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
"""Parse (absolute and relative) URLs.
See RFC 1808: "Relative Uniform Resource Locators", by R. Fielding,
UC Irvine, June 1995.
"""
__all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag",
"urlsplit", "urlunsplit"]
# A classification of scheme... |
"""
all-ipv6 protocl support class(es)
http://libvirt.org/formatnwfilter.html#nwfelemsRulesProtoMiscv6
"""
from virttest.libvirt_xml import accessors, xcepts
from virttest.libvirt_xml.nwfilter_protocols import base
class All_ipv6(base.TypedDeviceBase):
"""
Create new All_ipv6 xml instances
Properties:... |
import os
import sys
import mock
import testtools
from neutron.agent.linux import daemon
from neutron.tests import base
FAKE_FD = 8
class TestPidfile(base.BaseTestCase):
def setUp(self):
super(TestPidfile, self).setUp()
self.os_p = mock.patch.object(daemon, 'os')
self.os = self.os_p.sta... |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import sys
import os
import numpy as np
import numpy.testing as npt
import scipy.sparse
import scipy.io
from mdtraj import io
from msmbuilder import tpt
from msmbuilder.scripts import FindPaths
from msmbuilder... |
from south.db import db
from django.db import models
from pressroom.models import *
class Migration:
def forwards(self, orm):
# Adding field 'Article.enable_comments'
db.add_column('pressroom_article', 'enable_comments', models.BooleanField(default=True))
def ba... |
from __future__ import unicode_literals
"""
Syncs a database table to the `DocType` (metadata)
.. note:: This module is only used internally
"""
import os
import frappe
from frappe import _
from frappe.utils import cstr, cint
class InvalidColumnName(frappe.ValidationError): pass
type_map = {
'Currency': ('decimal... |
from __future__ import absolute_import
from timeside.core import implements, interfacedoc
from timeside.core.analyzer import Analyzer, IAnalyzer
from timeside.core.preprocessors import frames_adapter
from timeside.plugins.analyzer.utils import MACHINE_EPSILON
from timeside.core.tools.buffering import BufferTable
imp... |
#!/usr/bin/python
'''
Copyright 2012 Google Inc.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
'''
'''
Generates a visual diff of all pending changes in the local SVN (or git!)
checkout.
Launch with --help to see more information.
TODO(epoger): Now that this tool ... |
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.zone_hvac_controls_and_thermostats import ThermostatSetpointSingleHeating
log = logging.getLogger(__name__)
class TestThermostatSetpointSingleHeating(unittest.TestCase):
de... |
# -*- coding: utf-8 -*-
"""
On the Subject of Keypads
:Copyright: 2015 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from collections import Counter
from itertools import chain, zip_longest
from tkinter import ttk
from tkinter import E, N, S, W
COPYRIGHT_SIGN = ... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
viewshed.py
---------------------
Date : October 2019
Copyright : (C) 2019 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
****************... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
connect_nodes_bi,
sync_chain,
sync_blocks,
)
def unidirectional_node_sync_via_rpc(node_src, node_dest):
blocks_to_copy = []
blockhash = node_src.getbestblockhash()
while True:
... |
import logging
import re
import json
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.decorators import jsonify
from nodetraq.model.meta import Session
from nodetraq.lib.base import BaseController, render, user_level
from nodetraq.l... |
from opencog.cogserver import MindAgent
from opencog.atomspace import types
from pln.chainers import Chainer
from pln.rules import *
class InferenceAgent(MindAgent):
def __init__(self):
self.chainer = None
self.num_steps_per_cycle = 100
def create_chainer(self, atomspace):
# Note: usi... |
from __future__ import absolute_import
import datetime
import logging
import os
import socket
from socket import error as SocketError, timeout as SocketTimeout
import warnings
from .packages import six
from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection
from .packages.six.moves.http_client imp... |
###
# Imports
###
from __future__ import unicode_literals
from slackclient import SlackClient
import yaml
###
# Classes
###
class Command:
def __init__(self, name, function, num_args=0):
self.name = name
self.function = function
self.num_args = num_args
class Player:
def __init__(se... |
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(sys.argv) < 2:
sys.stderr.write('Please include username as an argument.\n')
sys.exit(0)
username = sys.argv[1]
#This uses os.urandom() underneath
cryptogen = SystemRandom()
#Create 16 byte hex salt
salt_seq... |
# -*- coding: utf-8 -*-
"""
flask.jsonimpl
~~~~~~~~~~~~~~
Implementation helpers for the JSON support in Flask.
:copyright: (c) 2012 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import io
import uuid
from datetime import datetime
from .globals import current_app, request
fro... |
""" Tests for tab functions (just primitive). """
from contentstore.views import tabs
from django.test import TestCase
from xmodule.modulestore.tests.factories import CourseFactory
from courseware.courses import get_course_by_id
class PrimitiveTabEdit(TestCase):
"""Tests for the primitive tab edit data manipulat... |
"""
Heaps and Priority Queues
"""
class Heap:
"""A (max-)heap efficiently supports the following operations:
Insert(e)
e = ExtractMax()
e = replace(new_e)
It maintains the heap invariant, which that the children of any
element are less that the element."""
def __init__... |
from __future__ import absolute_import
from werkzeug.wrappers import Request
from werkzeug.exceptions import NotFound
from .settings import get_settings
from .content_map import ContentMap
class Application(object):
"""
The main WSGI application, __init__ runs on app start so we do everything here that does... |
# -*- coding: utf-8 -*-
"""
werkzeug.contrib.limiter
~~~~~~~~~~~~~~~~~~~~~~~~
A middleware that limits incoming data. This works around problems with
Trac_ or Django_ because those directly stream into the memory.
.. _Trac: http://trac.edgewall.org/
.. _Django: http://www.djangoproject.com/
... |
"""Class representing audio/* type MIME documents."""
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
__all__ = ['MIMEAudio']
import sndhdr
from io import BytesIO
from future.backports.email import encoders
from future.backports.email.mime.non... |
"""Test Automation config panel."""
import json
from unittest.mock import patch
from homeassistant.bootstrap import async_setup_component
from homeassistant.components import config
from homeassistant.helpers import entity_registry as er
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa:... |
# This module exports classes for the various canvas item types
# NOTE: This module was an experiment and is now obsolete.
# It's best to use the Tkinter.Canvas class directly.
from warnings import warnpy3k
warnpy3k("the Canvas module has been removed in Python 3.0", stacklevel=2)
del warnpy3k
from Tkinter import Ca... |
"""
Reads from a file and generates PAL TV pictures in black and white
which can be displayed using ImageMagick or realtime using
gr-video-sdl (To capture the input file Use usrp_rx_file.py, or use
usrp_rx_cfile.py --output-shorts if you have a recent enough
usrp_rx_cfile.py)
Can also use usrp directly as capture sour... |
from ctypes import c_void_p, POINTER, sizeof, Structure, windll, WinError, WINFUNCTYPE, addressof, c_size_t, c_ulong
from ctypes.wintypes import BOOL, BYTE, DWORD, HANDLE, LARGE_INTEGER
LPVOID = c_void_p
LPDWORD = POINTER(DWORD)
SIZE_T = c_size_t
ULONG_PTR = POINTER(c_ulong)
# A ULONGLONG is a 64-bit unsigned integer... |
import time
import copy
import numpy as np
from .. import pick_channels
from ..utils import logger, verbose
from ..epochs import _BaseEpochs
from ..event import _find_events
from ..io.proj import setup_proj
class RtEpochs(_BaseEpochs):
"""Realtime Epochs
Can receive epochs in real time from an RtClient.
... |
"""
Timezone-related classes and functions.
This module uses pytz when it's available and fallbacks when it isn't.
"""
import sys
import time as _time
from datetime import datetime, timedelta, tzinfo
from threading import local
from django.conf import settings
from django.utils import lru_cache, six
from django.util... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.