content stringlengths 4 20k |
|---|
from test_framework.test_framework import PresidentielcoinTestFramework
from test_framework.util import *
class KeyPoolTest(PresidentielcoinTestFramework):
def run_test(self):
nodes = self.nodes
addr_before_encrypting = nodes[0].getnewaddress()
addr_before_encrypting_data = nodes[0].valida... |
from abc import ABC
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.db import transaction, Error
from django.utils.translation import ugettext as _
from base.business.education_groups.postponement import ConsistencyError
from base.models.academic_year import AcademicYear, co... |
import RPi.GPIO as GPIO
import pigpio
import time
import atexit
from time import sleep
from flask import Flask, render_template, request, send_from_directory
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
GPIO = pigpio.pi()
GPIO.set_servo_pulsewidth(23, 1500) #
GPIO.set_servo_pulse... |
import os
from setuptools import setup, find_packages
version=__import__('django_pyres').__version__
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-pyres',
version=version,
description='django pyres integration',
long_description=read('README.... |
from numpy import genfromtxt, zeros
from math import pi
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
map_from_file = genfromtxt('../data/map.dat')
N = 512
projection = 'moll' # 'cyl', 'moll', 'ortho'
save_as_png = False
save_as_svg = False
inside_map = zeros((int(N + 1), int(N / 2 + 1))... |
from bs4 import BeautifulSoup
from datetime import datetime, timezone
from collections import OrderedDict
import requests, time, json, csv, os, random
def new_payload(block, flat_type, contract):
return {
"Flat": flat_type,
"Block": block,
"Contract": contract,
"Town": "Toa Payoh",
... |
# -*- coding: utf-8 -*-
"""
This module contains functions for sending email and SMS messages
to Remote Care users.
:subtitle:`Function definitions:`
"""
import messagebird
from datetime import date
from core.encryption.hash import create_hmac
from apps.mollie.api import Mollie
from apps.mollie.exceptions import Molli... |
"""Model architecture for predictive model, including CDNA, DNA, and STP."""
"""use directly from flow data"""
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.layers.python import layers as tf_layers
from tensorflow.python.ops import init_ops
def resize_like(... |
"""
Script that trains Sklearn singletask models on GDB7 dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import os
import deepchem as dc
import numpy as np
import shutil
from sklearn.kernel_ridge import KernelRidge
np.random.seed(123)
base_di... |
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from shared.variational_autoencoder import *
from tensorflow.examples.tutorials.mnist import input_data
from scipy.misc import imsave
import hyperchamber as hc
hc.set("model", "255bits/vae-mnist")
mnist = input_data.read_data_sets("MNIST_da... |
#!/usr/bin/env python3
class Solution:
def permutation(self, nums):
if len(nums) == 0:
return []
if len(nums) == 1:
return [nums]
ret = []
for i in set(nums):
ix = nums.index(i)
ret += [[i] + m for m in self.permutation(nums[:ix]+nums[... |
from django.conf import settings
from django.utils import translation
from geotrek.tourism import models as tourism_models
from geotrek.tourism.views import TouristicContentViewSet, TouristicEventViewSet
from geotrek.trekking.management.commands.sync_rando import Command as BaseCommand
# Register mapentity models
fro... |
from django.views.generic import DetailView
from django.core.exceptions import PermissionDenied
from C4CApplication.models.member import Member
from C4CApplication.views.utils import create_user
class ProfileView(DetailView):
template_name = "C4CApplication/Profile.html"
context_object_name = "member_shown"
... |
#!/usr/bin/python
import urllib2, json, traceback # ConfigParser, argparse #, logging
from datetime import timedelta, datetime, date
from string import join
import xml.etree.ElementTree as ET
from os import sys
from .nat_lib import *
from .reset_lib import NoGameException, NoTeamException, DabException
intRollo... |
'''
Created on Dec 16, 2014
@author: paul
'''
import xml.etree.ElementTree as ET
# import splunklib.client as client
from spec.sharp.CONST import CONST
class KeywordSearchConfig(object):
'''
classdocs
'''
def __init__(self, host='', port='', user='', password='', \
s_name='', s_ke... |
import time
import urllib3
from .base import Connection
from ..exceptions import ConnectionError
from ..compat import urlencode
class Urllib3HttpConnection(Connection):
"""
Default connection class using the `urllib3` library and the http protocol.
:arg http_auth: optional http auth information as either... |
import glob
from pytest import raises
from migrator import _generate_migration_list
from migrator import _escape_migration
# Just to make the tests easier to read:
UP = False
DOWN = True
class TestMigrations(object):
def test_target_is_current_up(self):
for x in 0, 10:
assert _generate_mig... |
# Snafu: Snake Functions - Docker Executor
import requests
import os
import configparser
import time
import random
container = "jszhaw/snafu"
endpoints = {}
multi = 3
authorised = True
def launch(tenant, portnum):
authmount = ""
if authorised:
accdb = os.path.expanduser("~/.snafu-accounts")
accdir = os.path.e... |
##USAGE:
##"path_to_wsadmin\wsadmin.bat" -user ********** -password *********** -lang jython -f C:\WebSphereAppManageWAR.py nameOfApp start
##"path_to_wsadminn\wsadmin.bat" -user ********** -password *********** -lang jython -f C:\WebSphereAppManageWAR.py nameOfApp stop
##"path_to_wsadminn\wsadmin.bat" -user *******... |
from __future__ import print_function
import os
import re
import sys
import json
import signal
import codecs
import logging
import datetime
import argparse
import fileinput
from twarc.client import Twarc
from twarc.version import version
from twarc.json2csv import csv, get_headings, get_row
from dateutil.parser impor... |
__author__ = 'Allison MacLeay'
from sklearn.tree import DecisionTreeClassifier
import CS6140_A_MacLeay.Homeworks.HW4 as decTree
import CS6140_A_MacLeay.Homeworks.HW4 as hw4
import numpy as np
class BoostRound():
def __init__(self, adaboost, round_number):
self.learner = adaboost.learner
self.erro... |
import time
from zato.server.service import Service
from ulakbus.models.zato import ZatoServiceChannel, ZatoServiceFile
class ServiceManagement(Service):
"""
Eğer yerelde çalışıyorsanız zato ortamına http://localhost:8183/ adresini vererek
bağlanabirlisiniz.
Service Management Zato'ya y... |
# -*- coding: utf-8 -*-
"""Helper for project configuration."""
import configparser
class ProjectDefinition(object):
"""Project definition.
Attributes:
description_long (str): long description.
description_short (str): short description.
git_url (str): URL of the git repository.
homepage_url (st... |
import pinutils;
info = {
'name' : "Mini STM32 angled 7 inch LCD Board (VGT6)",
#'variables' : 2800,
'variables' : 5376, # (96-12)*1024/16-1
'serial_bootloader' : True,
'binary_name' : 'espruino_%v_mini_stm32_vg.bin',
'build' : {
'defines' : [
'USE_GRAPHICS',
'USE_LCD_FSMC',
'USE_FILESYSTEM',
... |
from google.cloud.exceptions import NotFound
from google.cloud._helpers import _rfc3339_nanos_to_datetime
from google.cloud.storage.constants import _DEFAULT_TIMEOUT
from google.cloud.storage.retry import DEFAULT_RETRY
from google.cloud.storage.retry import DEFAULT_RETRY_IF_ETAG_IN_JSON
class HMACKeyMetadata(object)... |
#!/usr/bin/python
from L3GD20 import L3GD20
import time
import sys, math, pygame
class Point3D:
def __init__(self, x = 0, y = 0, z = 0):
self.x, self.y, self.z = float(x), float(y), float(z)
def rotateX(self, angle):
""" Rotates the point around the X axis by the given angle in degrees. """
... |
# -*- coding: utf-8 -*-
from datetime import datetime
import unittest
from mock import Mock, sentinel, patch, ANY
from nose.tools import assert_equal, assert_true
import pytz
from six import advance_iterator
from twilio.rest.resources.imports import json
from twilio.rest.resources import Resource, NextGenListResource... |
"""
Actions - things like 'a model was removed' or 'a field was changed'.
Each one has a class, which can take the action description and insert code
blocks into the forwards() and backwards() methods, in the right place.
"""
import sys
import datetime
from django.db.models.fields.related import RECURSIVE_RELATIONSHI... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import sys
from ansible import constants as C
from ansible import context
from ansible.errors import AnsibleError
from ansible.module_utils.compat.paramiko import paramiko
from ansible.module_utils.six import iteritems
f... |
import pytest
from app.backend.env import hardware, env
from mock import Mock
def test_generate_mem_info():
info = hardware.get_mem_info()
assert info is not None
print info
assert info['free'] is not None
assert info['used'] is not None
assert info['total'] is not None
def test_generate_mem... |
<<<<<<< HEAD
<<<<<<< HEAD
"""Tests for the pdeps script in the Tools directory."""
import os
import sys
import unittest
import tempfile
from test import support
from test.test_tools import scriptsdir, skip_if_missing, import_tool
skip_if_missing()
class PdepsTests(unittest.TestCase):
@classmethod
def setU... |
import sys, platform, re, pytest
from numpy.core._multiarray_umath import __cpu_features__
def assert_features_equal(actual, desired, fname):
__tracebackhide__ = True # Hide traceback for py.test
actual, desired = str(actual), str(desired)
if actual == desired:
return
detected = str(__cpu_feat... |
"""
Infrastructure module URLs
"""
from django.conf.urls import patterns, url
from anaf.infrastructure import views
urlpatterns = patterns('anaf.infrastructure.views',
url(r'^(\.(?P<response_format>\w+))?$', views.index, name='infrastructure'),
url(r'^index(\.(?P<respons... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import copy
import json
from ansible import constants as C
from ansible.plugins.action.normal import ActionModule as _ActionModule
from ansible.module_utils.asa import asa_provider_spec
from ansible.module_utils.network... |
import urllib
from networkapiclient.ApiGenericClient import ApiGenericClient
from networkapiclient.utils import build_uri_with_ids
class ApiVipRequest(ApiGenericClient):
def __init__(self, networkapi_url, user, password, user_ldap=None, log_level='INFO'):
"""Class constructor receives parameters to conn... |
from __future__ import print_function, division, absolute_import
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNES... |
from test_framework.test_framework import BitsendTestFramework
from test_framework.util import (start_nodes, start_node, assert_equal, bitsendd_processes)
def read_dump(file_name, addrs, hd_master_addr_old):
"""
Read the given dump, count the addrs that match, count change and reserve.
Also check that the... |
"""
Rules needed to restrict access to the enterprise data api.
"""
import crum
import rules
from edx_rbac.utils import request_user_has_implicit_access_via_jwt, user_has_access_via_database
from edx_rest_framework_extensions.auth.jwt.authentication import get_decoded_jwt_from_auth
from edx_rest_framework_extensions.a... |
import subprocess
from sqlalchemy.orm.exc import NoResultFound
import logging
from database.model import Session
from database.definition_model import HardwareDefinition, SoftwareDefinition
from monitor.system.info import get_device_name, getserial
def shutdown():
command = ['sudo', 'shutdown', 'now'... |
"""
This submodule contains all the transformations passes offered in Pythran.
This file is just for convenience and turns the import from
import transformations.xxxxx.xxxxx
into
import transformations.xxxxx
"""
from .expand_builtins import ExpandBuiltins
from .expand_globals import ExpandGlobals
from .expand_imp... |
# Simple script that manages the creation of
# datastores in CKAN / HDX.
# Dependencies
import os
import csv
import json
import scraperwiki
import ckanapi
import urllib
import requests
import sys
import hashlib
# Collecting configuration variables
API_KEY = sys.argv[1]
FILE_PATH = sys.argv[2]
# configuring the remot... |
from .pages.article import ArticlePage
from weboob.tools.browser import BaseBrowser
class NewspaperLibeBrowser(BaseBrowser):
"NewspaperLibeBrowser class"
PAGES = {"http://.*liberation.fr/.*": ArticlePage}
def is_logged(self):
return False
def login(self):
pass
def fillobj(self, ... |
import numpy as np
from warnings import warn
from os import linesep
from . import Simu
from tick.simulation import features_normal_cov_toeplitz, \
features_normal_cov_uniform
# TODO: features simulation isn't launch each time we call simulate
# TODO: there's a problem if we give other coeffs with another size or
... |
from spack import *
class Rose(AutotoolsPackage):
"""A compiler infrastructure to build source-to-source program
transformation and analysis tools.
(Developed at Lawrence Livermore National Lab)"""
homepage = "http://rosecompiler.org/"
url = "https://github.com/rose-compiler/rose/archive/v0... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from argparse import ArgumentParser
from ast import literal_eval
try: from ConfigParser import RawConfigParser
except: from configparser import RawConfigParser
class ArgConfParser(ArgumentParser):
kCONFIG_EXTENSION = '.conf'
kCONFIG_SECTION = 'Setting... |
from tempest.api.identity import base
from tempest.common.utils import data_utils
from tempest import test
class EndPointsTestJSON(base.BaseIdentityV2AdminTest):
@classmethod
def resource_setup(cls):
super(EndPointsTestJSON, cls).resource_setup()
cls.service_ids = list()
s_name = data... |
import lldb
import binascii
import os
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
from gdbclientutils import *
@skipIfRemote
class TestProcessConnect(GDBRemoteTestBase):
NO_DEBUG_INFO_TESTCASE = True
@skipIfWindows
def test_gdb_remote_sync(self):
"""Test the gdb... |
# Uses followers.json to create dictionary disciples
# disciples is similar to users from getTweeters.py
# it maps followers from follower.json -> unique_integer
# Creates a directed graph of tweeters --> followers
import json
import os.path
import networkx as nx
from networkx import linalg
import matplotlib.pyplot as... |
#!/usr/bin/env python3
"""
This script uses the following input:
- Annotated GFF3 file
- Full go.obo file
- Pickled go slim
And produces count output in plain text like this:
cellular_component GO:0005575 cellular_component 650
cellular_component GO:0016020 membrane 135
cellular_component GO:0043226 organelle 51
ce... |
import logging
import os
from tempfile import gettempdir
import AppKit as ak
import Foundation as fn
import objc
from mocker import Mocker, expect, ANY, MATCH
from nose.tools import *
import editxt.constants as const
import editxt.project as mod
from editxt.application import Application, DocumentController
from edit... |
def vscale(r, vec):
return [r * x for x in vec]
def vadd(*args):
return [sum(tuple) for tuple in zip(*args)]
class Vector(object):
def __init__(self, *components):
self.components = components
def __getitem__(self, i):
return self.components[i]
def __setitem__(self, i, value):
... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
import json
import logging
from restapi import Controller, Mapper, Resource
from restapi.main import start_server
from restapi.middlewares import Middleware, register_middleware
from restapi.serializers import JSONSerializer
from restapi.util... |
import argparse
from Bio import SeqIO
import sys
import os
class Cluster(object):
def __init__(self, name):
self.name = name
self.out_name = self.name + ".fna"
self.contigs = {}
self.overwrite = True
def parse_cluster_faa(self, cluster_faa_f, min_len=100):
""" Parses... |
# -*- coding: utf-8 -*-
import datetime
from cronq.models.base import Base
from sqlalchemy import CHAR
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Interval
from sqlalchemy import Text
from sqlalchemy import Uniqu... |
import qi
import argparse
import sys
import time
import os
# The IP of the robot from the tablet is 198.18.0.1
webpageinit = "http://198.18.0.1/apps/spqrel/index.html"
imageinit = "http://198.18.0.1/apps/spqrel/spqrel_logo.jpg"
def do_init(session):
print "Init webpage to ",webpageinit
tablet_service = sess... |
# -*- coding: utf-8 -*-
"""
.. module: api
:platform: Unix, Windows
:synopsis: Wrap the TastyPie API providing basic get/add/update/delete methods.
.. moduleauthor:: Christian Boelsen <<EMAIL>>
"""
__all__ = ('TastyApi', )
import json
import requests
from .exceptions import (
ErrorResponse,
Canno... |
import math
import unittest
import numpy
import pytest
import cupy
from cupy import testing
import cupyx.scipy.stats # NOQA
from cupyx.scipy import stats
from cupyx.scipy.stats import distributions
try:
import scipy.stats # NOQA
except ImportError:
pass
@testing.gpu
class TestEntropyBasic(unittest.TestCa... |
import logging
logger = logging.getLogger(__name__)
from lxml import etree
from base64 import b64encode
try:
from urllib import unquote
except ImportError: # Python 3
from urllib.parse import unquote
# import email data format related stuff
try:
# python >= 2.5
from email.mime.multipart import MIMEMu... |
""" A set of scoring functions. """
import numpy as np
from .pyglmnet import _logL
def deviance(y, yhat, distr, theta):
"""Deviance metrics.
Parameters
----------
y : array
Target labels of shape (n_samples, )
yhat : array
Predicted labels of shape (n_samples, )
distr: str
... |
from __future__ import absolute_import, division
from desispec.io import read_frame
from desispec.io import read_fiberflat
from desispec.io import read_sky
from desispec.io import write_qa_frame
from desispec.io.fluxcalibration import read_stdstar_models
from desispec.io.fluxcalibration import write_flux_calibration
... |
import os
import re
from conans.model.ref import ConanFileReference, PackageReference
from conans.test.assets.genconanfile import GenConanfile
from conans.test.utils.tools import TestClient
def test_auto_package_no_components():
client = TestClient()
conan_file = str(GenConanfile().with_settings("build_type"... |
import os
import tempfile
from driver_pete_python_sandbox.download import S3
from driver_pete_python_sandbox.trajectory_reader import read_compressed_trajectory,\
write_compressed_trajectory
def test_trajectory_reader():
folder = tempfile.mkdtemp()
s3 = S3('driverpete-storage')
filename = s3.download(... |
import gtk
import gtk.glade
import logging
from deluge.ui.client import client
from deluge.plugins.pluginbase import GtkPluginBase
import deluge.component as component
import deluge.common
from common import get_resource
log = logging.getLogger(__name__)
class GtkUI(GtkPluginBase):
def enable(self):
lo... |
# functions to support bundled libraries
from Configure import conf
import sys, Logs
from samba_utils import *
def PRIVATE_NAME(bld, name, private_extension, private_library):
'''possibly rename a library to include a bundled extension'''
# we now use the same private name for libraries as the public name.
... |
from datetime import datetime, time
import unittest
from airflow import configuration
configuration.test_mode()
from airflow import jobs, models, DAG, executors, utils, operators
from airflow.www.app import app
from airflow import utils
NUM_EXAMPLE_DAGS = 5
DEV_NULL = '/dev/null'
LOCAL_EXECUTOR = executors.LocalExecut... |
"""Various constants (that probably should be config options later on)"""
# Name of the ordinary member type
DEFAULT_MEMBER_NAME = 'Medlem'
# Name of the support membership type
DEFAULT_SUPPORT_MEMBER_NAME = 'Støttemedlem'
# Name of the status newly signed up members should be set to
SIGNUP_STATUS_NAME = 'Innmeldt'
#... |
#!/usr/bin/python
"""
This module contains `main` method plus related subroutines.
`main` is executed as the command line ``vcgif`` program and takes care of
parsing options and commands
"""
import argparse
from vcgif.GifBootstrap import GifBootstrap
def main():
try:
parser = argparse.ArgumentParser(desc... |
import logging
import time
import tensorflow as tf
from tensorlog import simple
import expt
def runMain():
params = expt.setExptParams()
prog = params['prog']
tlog = simple.Compiler(db=prog.db, prog=prog, autoset_db_params=False)
train_data = tlog.annotate_big_dataset(params['trainData'])
test_data = tlog.a... |
from tabulate import tabulate
def num_versions_to_str(nv):
if nv is None or nv < 0:
return 'unknown'
if nv == 0:
return 'same version'
lbl = 'versions' if nv > 1 else 'version'
return '-{0} {1}'.format(nv, lbl)
def timedelta_to_str(td):
if td is None:
return 'unknown'
... |
#! /usr.bin/env python
# zzz
import os.path
from subprocess import Popen, PIPE
import logging
real_transcode = True
class Transcoder(object):
"""
call ffmpeg in system, transcode for HLS
"""
def __init__(self, ffmpeg_path=None):
if ffmpeg_path is None:
ffmpeg_path = 'ffmpeg'
... |
import sys
import unittest
from telemetry import decorators
from telemetry.page import page
from telemetry.testing import options_for_unittests
from telemetry.testing import page_test_test_case
from telemetry.util import wpr_modes
from telemetry.value import scalar
from measurements import smoothness
import mock
c... |
import json
from .db import Model
from .admin import disableable, admin_only
from .player import Player
from .location import Location
from .template import templater, inside_page
class Murder(Model):
_table='murder'
def __init__(self, id, game, murderer, victim, datetime, location, lat=None, lng=None):
self.id,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Basic) on 2019-05-07.
# 2019, SMART Health IT.
from . import domainresource
class Basic(domainresource.DomainResource):
""" Resource for non-supported content.
Basic is used ... |
# -*- coding: utf-8 -*-
"""Module designed to handle the simple case when one wants to use Sprout but does not use the
parallelizer. Uses IPAppliance that is pushed on top of the appliance stack"""
import pytest
from threading import Timer
from fixtures.parallelizer import dump_pool_info
from fixtures.terminalreporte... |
import arcpy
try:
#set features and cursors so that they are deletable in
#'finally' block should the script fail prior to their creation
feature, features = None, None
inTable = arcpy.GetParameterAsText(0)
inField = arcpy.GetParameterAsText(1)
inPercent = arcpy.GetParameterAsText(2)
numr... |
#!/usr/local/python3/bin/python3
import time
import socket
import re
import os
pattern_byte = re.compile(b'(?<=Host: ).*\w')
work_path = '/opt/store'
def search_host(file_name):
with open(file_name, 'rb') as fs:
byte_flow = fs.read(512)
match = pattern_byte.search(byte_flow)
if match:
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0015_auto_20150515_1523'),
]
operations = [
migrations.CreateModel(
name='Partner',
fields=[... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
Generating time series
----------------------
A few routines are provided to generate test data from simple equations.
Since there are powerfull packages (for example Dynamics by Helena Nusse
and Jim Yorke) that can generate chaotic data, we have only included a
mini... |
"""
Functionality to deal with GL Contexts in vispy. This module is defined
in gloo, because gloo (and the layers that depend on it) need to be
context aware. The vispy.app module "provides" a context, and therefore
depends on this module. Although the GLContext class is aimed for use
by vispy.app (for practical reason... |
import copy
import testtools
from sahara.conductor import manager
from sahara import context
from sahara import exceptions as ex
import sahara.tests.unit.conductor.base as test_base
SAMPLE_CLUSTER = {
"plugin_name": "test_plugin",
"hadoop_version": "test_version",
"tenant_id": "tenant_1",
"is_transi... |
#! /usr/bin/env python
class Markov:
def __init__(self, histsize, choice):
self.histsize = histsize
self.choice = choice
self.trans = {}
def add(self, state, next):
self.trans.setdefault(state, []).append(next)
def put(self, seq):
n = self.histsize
... |
from __future__ import print_function
import sys
import os
import os.path
if 'develop' in sys.argv[1]:
from setuptools import setup, Extension
else:
from distutils.core import setup, Extension
# include/library directories
# if None, setup will try to discover the correct value automatically
plot_h_dir = None... |
#-*- encoding: utf-8 -*-
"""
HatenaBookmark.py
"""
__author__="ymotongpoo <<EMAIL>>"
__date__ ="$2008/12/10 00:29:41$"
__version__="$Revision: 0.10"
__credits__="0x7d8 -- programming training"
import urllib
from HTMLParser import HTMLParser, HTMLParseError
import re # temporary for invalid HTML of hatena bookmark ... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... |
from __future__ import absolute_import, division, print_function
from .core import common_subexpression
from .expressions import Expr, Symbol
from .reductions import Reduction, Summary, summary
from ..dispatch import dispatch
from datashape import dshape, Record, Option, Unit, var
__all__ = ['by', 'By', 'count_values... |
# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
testinfo = "s, t 0.3, s, t 0.6, s, t 1, s, q"
tags = "skeleton, BitmapSkin, Animate"
import cPickle
import summa
from summa.director import director
from s... |
import math
import torch
from torch import nn
from torch.autograd import Variable
from time import time
#########################################################################################
## Encoder
#########################################################################################
class Sampler(nn.Module... |
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
from UIGraphicsItem import *
class TextItem(UIGraphicsItem):
"""
GraphicsItem displaying unscaled text (the text will always appear normal even inside a scaled ViewBox).
"""
def __init__(self, text='', color=(200,200,200), html=None, anchor... |
from tkinter import TclError
class ContextError(Exception):
"""This error representes all errors that come from the context.
It could be :
- Open a non existant file
- Open a file the no right to do so.
- go to a non existant tag
Those errors are mainly raised by commands ... |
from airflow.contrib.hooks.azure_cosmos_hook import AzureCosmosDBHook
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
class AzureCosmosDocumentSensor(BaseSensorOperator):
"""
Checks for the existence of a document which
matche... |
#!/usr/bin/env python3
import sys
import os
import re
from itertools import count
from logging import warning
NEWDOC_RE = re.compile(r'^###C: new article')
TIME_RE = re.compile(r'###C: timestamp = (\d+-\d+-\d+)T(\d+):(\d+):(\d+)')
URL_RE = re.compile(r'###C: url = https://yle.fi/.*/(\S+)(?:\?origin=rss|\.txt)')
d... |
#!coding=utf-8
from helper import tmux_cmd, tmux_send_keys
def start_list_selection(prefix_cmd, argv):
tmux_cmd("split-window -h -l 30", prefix_cmd % ("-s %s" % " ".join(argv)))
def jump_prev():
tmux_send_keys("C-g Up C-a C-Space C-e")
def jump_next():
tmux_send_keys("C-g Down C-a C-Space C-e")
def list... |
import importlib
import os
from .fairseq_lr_scheduler import FairseqLRScheduler
LR_SCHEDULER_REGISTRY = {}
def build_lr_scheduler(args, optimizer):
return LR_SCHEDULER_REGISTRY[args.lr_scheduler](args, optimizer)
def register_lr_scheduler(name):
"""Decorator to register a new LR scheduler."""
def re... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2017-06-16 Fri 18:57:39 Shaikh>
import numpy as np
import convolve_py
import pyximport
pyximport.install(setup_args={"include_dirs": np.get_include()},
reload_support=False, inplace=False)
import convolve_c
import convolve_c2
import convol... |
from weboob.deprecated.browser import Page,BrokenPageError
from weboob.capabilities.torrent import Torrent
from weboob.capabilities.base import NotAvailable, NotLoaded
from html2text import unescape
class TorrentsPage(Page):
def unit(self, n, u):
m = {'B': 1,
'KB': 1024,
'... |
from os import path
from plant.plant import Plant
from order.orderlist import OrderList
from schedulerperf import SchedulerLargeValuesPerf, SchedulerMachinesPerf, \
SchedulerOrdersPerf
from simulatorperf import SimulatorLargeValuesPerf, SimulatorMachinesPerf, \
SimulatorOrdersPerf
from optimizerperf import Optimize... |
# -*- coding: utf-8 -*-
from openerp import fields, models, api, _
from datetime import timedelta
class ResCompany(models.Model):
_inherit = "res.company"
#TODO check all the options/fields are in the views (settings + company form view)
fiscalyear_last_day = fields.Integer(default=31, required=True)
... |
from threading import RLock
import logging
from trytond.modules import load_modules, register_classes
from trytond.transaction import Transaction
import __builtin__
class Pool(object):
classes = {
'model': {},
'wizard': {},
'report': {},
}
_started = False
_lock = RLock()
... |
from __future__ import division
import logging
from OpenGL.GL import *
from contextlib import contextmanager
import numpy as np
from fretwork.task import Task
log = logging.getLogger(__name__)
class Layer(Task):
def __getattr__(self, name): #for new out-themed rendering
if name.startswith("img_"): #ra... |
# Define usable ranges as bulbs either ignore or behave unexpectedly
# when it is sent a value is outside of the range.
TEMPERATURE_PROFILES = dict((model, temp) for models, temp in (
# Lightify RGBW, 1900-6500K
(["LIGHTIFY A19 RGBW"], (151, 555)),
) for model in models)
COLOR_PROFILES = dict((model, gamut) fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.