content stringlengths 4 20k |
|---|
from envisage.ui.tasks.preferences_pane import PreferencesPane
from traits.api import Bool, Float, Enum
from traitsui.api import View, Item, VGroup, HGroup
# ============= standard library imports ========================
# ============= local library imports ==========================
from pychron.envisage.tasks.bas... |
import click
import json.decoder
import jsonpickle
import os.path
import proscli
import proscli.utils
# from typing import List
class ConfigNotFoundException(Exception):
def __init__(self, message, *args, **kwargs):
super(ConfigNotFoundException, self).__init__(args, kwargs)
self.messa... |
from flask import url_for
from monkeygod import models
def test_index(app):
with app.test_client() as client:
res = client.get(url_for('monkey_views.index'))
assert 'Meet the Monkeys' in str(res.data)
def test_search_basic(app, testdata_with_friends):
with app.test_client() as client:
re... |
from abc import abstractmethod
from traits.has_traits import HasTraits
from traits.trait_types import Date, List
class EventSelectionQuery(HasTraits):
period_start_date = Date
period_end_date = Date
list_of_source_classes = List
selected_list_of_source_classes = List
list_of_event_severity_leve... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import unittest
from pants.backend.jvm import argfile
class SafeArgTest(unittest.TestCase):
def test_safe_args_over_max_arg(self):
# len(args) > max_args, so it should a file should be yielded
args = ['1', '2', '3... |
from pyanaconda.flags import can_touch_runtime_system
from pyanaconda.ui.tui.spokes import EditTUISpoke, OneShotEditTUIDialog
from pyanaconda.ui.tui.spokes import EditTUISpokeEntry as Entry
from pyanaconda.ui.tui.simpleline import TextWidget, ColumnWidget
from pyanaconda.i18n import N_, _
from pyanaconda import network... |
import os.path
import ctypes
from commoncode import system
from commoncode import command
import typecode
"""
magic2 is minimal and specialized wrapper around a vendored libmagic file
identification library. This is NOT thread-safe. It is based on python-magic
by Adam Hup and adapted to the specific needs of ScanCod... |
"""The Laplace distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
from tensorflow.contrib.distributions.python.ops import distribution
from tensorflow.contrib.distributions.python.ops import special_math
... |
import operator
from sys import version_info
from unittest import TestCase
from xml.etree import ElementTree
from genologics.entities import StepActions, Researcher, Artifact, \
Step, StepPlacements, StepPools, Container, Stage, ReagentKit, ReagentLot, Sample, Project
from genologics.lims import Lims
if version_i... |
from unittest.mock import patch
from odoo.addons.base.models.ir_mail_server import IrMailServer
from odoo.addons.survey.tests import common
from odoo.tests import tagged
from odoo.tests.common import HttpCase
@tagged('-at_install', 'post_install', 'functional')
class TestCertificationFlow(common.TestSurveyCommon, Ht... |
import sys, os, argparse, logging, signal, threading, pickle, subprocess
import pwd, grp
from aadict import aadict
from . import framework
from .util import SvnpublishLogFormatter
from .i18n import _
log = logging.getLogger(__name__)
#------------------------------------------------------------------------------
cla... |
from __future__ import print_function
from ovirtsdk.api import API
import sys
class vm_balance():
"""moves a vm from a host with to many"""
# What are the values this module will accept, used to present
# the user with options
properties_validation = 'maximum_vm_count=[0-9]*'
def _get_connection... |
"""Automatically generated random variables."""
from edward2.trace import traceable
import scipy.stats
# Note a vanilla Edward2-like PPL in SciPy would introduce a RandomVariable
# abstraction: it wraps SciPy frozen distributions and calls `rvs` to associate
# the RandomVariable with a sampled value. SciPy distributi... |
import os
import sys
import inspect
import argparse
from datetime import date, datetime
ARGS = None
cmd_folder = os.path.abspath(os.path.join(os.path.split(inspect.getfile(
inspect.currentframe()))[0], ".."))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
from tsheets.api import TSheets
from t... |
"""
Core MozTrap models (Product).
"""
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from pkg_resources import parse_version
from preferences.models import Preferences
from ..environments.models import HasEnvironmentsModel
from ..mtmodel import MTModel, MTManager, TeamM... |
from hypothesis import given, assume
from hypothesis.strategies import just, tuples, lists, integers, floats
from hypothesis.extra.numpy import arrays
def get_ops():
return NumpyOps()
def get_model(W_values, b_values):
model = Affine(W_values.shape[0], W_values.shape[1], ops=NumpyOps())
model.initialize... |
# coding: utf-8
"""
Tests for querystring utilities.
"""
from tests import case
class TestUpdateQueryString(case.TestCase):
@property
def func(self):
from moztrap.view.utils.querystring import update_querystring
return update_querystring
def test_basic(self):
self.assertEqual(
... |
import curses
import numpy as np
import time
import threading
import traceback
COLUMNS = [
("call", 10),
("lat", 10),
("lon", 10),
("alt", 7),
("gs", 5),
("tas", 5),
("ias", 5),
("mach", 7),
("roc", 7),
("trk", 10),
("hdg", 10),
("live", 6),
]
UNCERTAINTY_COLUMNS = [
... |
"""
Code related to the handling of Proctored Exams in Studio
"""
import logging
import six
from django.conf import settings
from edx_proctoring.api import (
create_exam,
create_exam_review_policy,
get_all_exams_for_course,
get_exam_by_content_id,
remove_review_policy,
update_exam,
update... |
'''
lfm
---
lfm is the `AWS Lambda <http://aws.amazon.com/lambda/>`_ Function Manager.
Deploy your functions directly from a local directory or Git repo!
'''
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='lfm',
version='0.1.0',
url='https://github.com/willyg302... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
Relief.py
---------------------
Date : December 2016
Copyright : (C) 2016 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*****************... |
# -*- coding: utf-8 -*-
""" *==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3... |
#!/usr/bin/python
# run gcov coverage checker on all tests.
# filter uninteresting errors and known false positives
#
import re
from os import system, remove, environ, defpath, path, pathsep, X_OK, access, sep
from sys import exit, stdout
from subprocess import Popen, PIPE
re_file = re.compile("File '([^']+)'")
re_ex... |
# -*- coding: utf-8 -*-
"""
<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>
A Displayer
"""
#<DefineAugmentation>
import ShareYourSystem as SYS
BaseModuleStr="ShareYourSystem.Standards.Controllers.Controller"
DecorationModuleStr="ShareYourSystem.Standards.Classors.Cla... |
from pprint import pprint
from hpOneView.oneview_client import OneViewClient
from hpOneView.exceptions import HPOneViewException
from config_loader import try_load_from_file
config = {
"ip": "",
"credentials": {
"userName": "administrator",
"password": ""
}
}
# Try load config from a file ... |
"""
Test SBValue.GetObjectDescription() with the value from SBTarget.FindGlobalVariables().
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ObjectDescriptionAPITestCase(TestBase):
mydi... |
#coding=utf-8
import string
import re
import itertools
from string import Template
a = "Hello Word"
b = a[4]
c = a[:5]
d = a[6:]
e = a[3:8]
g = a + " This is a test"
x = "37"
y = "42"
z = x + y
z = int(x) + int(y)
s = "The value of x is " + str(x)
s = "The value of x is " + str(x)
a1 = "Your name is {0} and your age is... |
import weechat
import re
w = weechat
SCRIPT_NAME = "colorize_nicks"
SCRIPT_AUTHOR = "xt <<EMAIL>>"
SCRIPT_VERSION = "23"
SCRIPT_LICENSE = "GPL"
SCRIPT_DESC = "Use the weechat nick colors in the chat area"
VALID_NICK = r'([@~&!%+])?([-a-zA-Z0-9\[\]\\`_^\{|\}]+)'
valid_nick_re = re.compile(VALID_NICK)
ignore_cha... |
import argparse
import csv
import os
import numpy as np
from collections import Counter
import json
"""
Data pre-processing from:
https://github.com/guillaume-chevalier/LSTM-Human-Activity-Recognition
"""
def load_X(X_signals_paths):
"""
Load X (inputs)
:param X_signals_paths: (list of strings) path to inpu... |
# coding: utf-8
import flask
from main import app
###############################################################################
# Redirects
###############################################################################
@app.route('/guide/')
def guide():
return flask.redirect(flask.url_for('howto'))
#########... |
from .app import db
from flask.ext.login import UserMixin
class User(db.Model, UserMixin):
__tablename__ = "user"
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
admin = db.Column(db.Boolean, default=False)
active = db.Column(db.Boolean, default=True)
gender = db.Column(db.Enum("Male", "Female"... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from converters.caffe.caffe_graph import CaffeGraph
import common.IR.graph_pb2 as graph_pb2
from common.IR.graph_pb2 import NodeDef, GraphDef, DataType
from common.DataStructure.parser import Parser
... |
import errno
import os
import subprocess
from bp import abstract, generic
from bp.filepath import FilePath
from characteristic import Attribute, attributes
from zope.interface import implementer
def from_path(path):
git_dir = path.child(".git")
if git_dir.isdir():
return GitPath(git_dir=git_dir, path... |
import argparse
import glob
import gyp_crashpad
import os
import re
import subprocess
import sys
def main(args):
parser = argparse.ArgumentParser(
description='Set up an Android cross build',
epilog='Additional arguments will be passed to gyp_crashpad.py.')
parser.add_argument('--arch', requir... |
"""A persistent cache implementation using sqlite3.
See the persistent_cache module for a detailed description.
"""
import errno
import os
from googlecloudsdk.core.cache import exceptions
from googlecloudsdk.core.cache import metadata_table
from googlecloudsdk.core.cache import persistent_cache_base
import sqlite3
... |
import proto # type: ignore
__protobuf__ = proto.module(
package='google.ads.googleads.v6.enums',
marshal='google.ads.googleads.v6',
manifest={
'CustomAudienceStatusEnum',
},
)
class CustomAudienceStatusEnum(proto.Message):
r"""The status of custom audience. """
class CustomAudie... |
__author__ = "Individual contributors (see AUTHORS file)"
__date__ = "$DATE$"
__rev__ = "$REV$"
__license__ = "AGPL v.3"
__copyright__ = """
This file is part of ArgCache.
Copyright (c) 2015 by the individual contributors
(see AUTHORS file)
This program is free software: you can redistribute it and/o... |
from sqlalchemy import *
from migrate import *
from nova import log as logging
meta = MetaData()
LOG = logging.getLogger(__name__)
# Just for the ForeignKey and column creation to succeed, these are not the
# actual definitions of instances or services.
instances = Table('instances', meta,
Column('id', Int... |
"""
Test sending and receiving coins
"""
import copy
import time
from decimal import Decimal
from test_framework.blocktools import (
create_coinbase,
TIME_GENESIS_BLOCK,
)
from test_framework.messages import (
CBlock,
CBlockHeader,
BLOCK_HEADER_SIZE
)
from test_framework.mininode import (
P2P... |
"""
A library for implementing JSON-RPC based web services
This is lightweight, low on features, and not a whole lot of effort
has been paid to really complying with the JSON-RPC spec. Feel
free to improve it. ;)
It'd be nice to factor the JSON-RPC stuff out so that it could
be used with something besides just HTTP.... |
import os
import sys
from common import gajim
from common import exceptions
from common import i18n
_ = i18n._
try:
import dbus
version = getattr(dbus, 'version', (0, 20, 0))
supported = True
except ImportError:
version = (0, 0, 0)
supported = False
if not os.name == 'nt': # only say that to non Windows users
... |
# -*- coding:UTF-8 -*-
"""
====================================================================
K-Means 和 MiniBatchKMeans 聚类算法的比较
====================================================================
我们想要去比较一下MiniBatchKMeans 和 KMeans 算法的性能:
MiniBatchKMeans 更快, 但是结果会略有不同(请参阅 :ref:`mini_batch_kmeans` )
我们将对一组数据进行聚类,首先使用... |
class MissingHeaderCheckScriptError(RuntimeError):
"""
Error indicating problems with missing header in check script.
"""
def __init__(self, script=""):
if script:
message = "A header missing in the %s check script" % script
else:
message = "A header missing in a ... |
"""This example deactivates all active line items custom fields.
To determine which custom fields exist, run get_all_custom_fields.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the... |
"""This example gets all networks that you have access to with the current login
credentials.
A networkCode should be left out for this request."""
__author__ = ('Nicholas Chen',
'Joseph DiLallo')
# Import appropriate modules from the client library.
from googleads import dfp
def main(client):
# In... |
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
import accum_trainer
class AccumTrainerTest(tf.test.TestCase):
def testAccum(self):
with self.test_session():
var0 = tf.Variable([1.0, 2.0])
trainer = accum_trainer.AccumTrainer()
cost = tf.square(var0)
trai... |
__copyright__ = """ Copyright (c) 2010-2011 Torsten Schmits
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is di... |
from shinymud.models import Model, Column, model_list
from shinymud.models.shiny_types import *
from shinymud.models.room import Room
from shinymud.models.item import BuildItem
from shinymud.models.npc import Npc
from shinymud.models.script import Script
from shinymud.modes.text_edit_mode import TextEditMode
from shiny... |
#!/usr/bin/env python
# ('Dusty Oak Staff', {'Health': 9, 'Energy': 14, 'Strength': 15, 'Defense': 9, 'Type': 'Dusty', 'Worth': 4})
# ('Forsaken Chestplate', {'Health': 6524, 'Energy': 247872, 'Strength': 206, 'Defense': 29, 'Type': 'Forsaken', 'Worth': 32})
# ('Shiny Legs', {'Health': 497, 'Energy': 255, 'Strength': ... |
from django.core.management.base import BaseCommand
from xbrowse_server import xbrowse_controls
from xbrowse_server.base.models import Project
from xbrowse_server.mall import get_datastore
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('project_id')
parser.add_a... |
import logging, openravepy, prpy
from prpy.action import ActionMethod
from prpy.planning.base import PlanningError
from contextlib import contextmanager
from prpy.util import FindCatkinResource
import numpy, cPickle, time, os.path
logger = logging.getLogger('herbpy')
@ActionMethod
def Point(robot, focus, manip=None... |
"""
byceps.services.tourney.models.tourney_category
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import NewType
from uuid import UUID
from sqlalchemy.ext.orderinglist import ordering_list
from ....database... |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.core.validators import MaxLengthValidator
from django.db import models
from django.utils import six
from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
from fancy_cronfield.validators import CronValidator
f... |
from enable.component_editor import ComponentEditor
from traits.api import HasTraits, Instance, DelegatesTo, \
Button, String
from traitsui.api import View, UItem, HGroup, VGroup, Controller, Action, TabularEditor, EnumEditor
from traitsui.tabular_adapter import TabularAdapter
# ============= standard library impor... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from ..person import RegExpName
from ._memberbase import child_base
... |
from typing import Dict, List
from polyaxon.polyflow import V1ArtifactsMount
from polyaxon.schemas.types import V1ConnectionType
def override_stores(
stores: List[V1ConnectionType], store_refs_by_name: Dict[str, V1ArtifactsMount]
) -> List[V1ConnectionType]:
results = []
if not stores or not store_refs_b... |
"""
Implements chi_squared_dist_table() function.
"""
def chi_squared_dist_table(k=0, p=0):
"""
From `Wikipedia <https://en.wikipedia.org/wiki/Chi-squared_distribution>`_.
The p-value is the probability of observing a test statistic at least as
extreme in a chi-squared distribution. Accordingl... |
from django.contrib.auth.models import AnonymousUser, User
from django.test import TestCase, RequestFactory
from extuser.models import CustomUser
from extuser.views import profile_view, RegisterFormView, edit_profile
from auto.models import CarMark, CarModel, Car
from rent.models import Rent
from datetime import date
i... |
#!/usr/bin/env python
# coding: utf-8
"""
Converts a Python dictionary to a valid XML string
"""
from __future__ import unicode_literals
__version__ = '0.2.0'
version = __version__
from xml.dom import minidom
from xml.etree.ElementTree import Element, tostring
import logging
def dict2xml(dict, encoding="utf-8", p... |
from spack import *
class AtSpi2Atk(MesonPackage):
"""The At-Spi2 Atk package contains a library that bridges ATK to
At-Spi2 D-Bus service."""
homepage = "http://www.linuxfromscratch.org/blfs/view/cvs/x/at-spi2-atk.html"
url = "http://ftp.gnome.org/pub/gnome/sources/at-spi2-atk/2.26/at-spi2-a... |
"""A python port of the archive-commons org.archive.url HandyURL class
The original java version is here:
http://archive-access.svn.sourceforge.net/viewvc/archive-access/trunk/archive-access/projects/archive-commons/src/main/java/org/archive/url/
"""
from .handyurl import handyurl
from .surt import surt
__all__= [
... |
#!/usr/bin/env python
import types, sys, os, math, json
import transform_par, utilities
import math
import multiprocessing
from multiprocessing import Process, Queue
#
# global search counter
#
search_counter = 0
CPU_NO = 4
def run_delta(delta_change, delta_type, change_set, type_set, search_config,
original_con... |
"""
Serializer class to convert Python objects into a binary data stream for
sending them to Rserve.
"""
import struct
import os
import socket
import io
import types
###
import numpy
###
from . import rtypes
from .misc import PY3, FunctionMapper, byteEncode, padLen4, string2bytesPad4
from .taggedContainers import Tagge... |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from numpy import *
import sys
import datetime
#datafile="life_hpc_host_mpi.out"
datafile="std_ldebug.err"
if len(sys.argv) > 1:
datafile=sys.argv[1]
plotfile=datafile+".png"
data = loadtxt(datafile)
today = datetime.date.today()
fig = plt... |
import os
import errno
import threading
import datetime
import tempfile
import shutil
import json
import time
import socket
import re
from copy import deepcopy
from GangaCore.Utility.Config import getConfig
from GangaCore.Utility.logging import getLogger
from GangaCore.Core.exceptions import GangaException
from GangaCo... |
# -*- coding: utf-8 -*-
from openerp import api, fields, models
class hr_department(models.Model):
_inherit = 'hr.department'
@api.multi
def _compute_new_applicant_count(self):
applicant_data = self.env['hr.applicant'].read_group(
[('department_id', 'in', self.ids), ('stage_id.sequenc... |
#!/usr/bin/python3
'''
@file fractal_qt5_opengl_lib.py
@author Philip Wiese
@date 12 Okt 2016
@brief PyQt4 QGLWidget to displays Mandelbrot Set with OpenGl
'''
import sys, time
# PyQt4 imports
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtOpenGL import QGLWidget
# PyOpenGL imports
import OpenGL.GL ... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import datetime
import os
import sys
os.environ['TZ'] = 'UTC'
def crprint(s):
'''
Print using DOS line endings (to match Arduino code)
:param s:
:return:
'''
sys.stdout.write(s)
sys.stdout.write('\r\n')
parse... |
"""This module include a class that checks the command change_domain.py"""
from django.test import TestCase
from django.core.management import call_command
from edunext_openedx_extensions.ednx_microsites.models import Microsite
class ChangeDomainTestCase(TestCase):
""" This class checks the command change_domai... |
"""Test code for softmax"""
import os
import numpy as np
import tvm
from tvm import te
from tvm import topi
import tvm.testing
import tvm.topi.testing
import logging
from tvm.topi.utils import get_const_tuple
_softmax_schedule = {
"generic": topi.generic.schedule_softmax,
"cpu": topi.x86.schedule_softmax,
... |
from flask.ext.plugins import connect_event
from flaskbb.plugins import FlaskBBPlugin
from flaskbb.utils.populate import (create_settings_from_fixture,
delete_settings_from_fixture)
from flaskbb.forum.models import Forum
from .views import portal, inject_portal_link
__version__ = ... |
#!/home/jim/anaconda/bin/ipython
import os
from rebineo import *
import matplotlib.patches as patches
import matplotlib.transforms as transforms
import console_colors as ccl
def makefig(medVAR, avrVAR, stdVAR, nVAR, tnorm,
dTday, SUBTITLE, YLIMS, YLAB, fname_fig, varname):
fig = figure(1, figsize=(13,... |
def verbing(s):
# +++your code here+++
if s[-3:] == 'ing':
return s + 'ly'
elif len(s) >= 3:
return s + 'ing'
else:
return s
# E. not_bad
# Given a string, find the first appearance of the
# substring 'not' and 'bad'. If the 'bad' follows
# the 'not', replace the whole 'not'...'bad' substring
# wi... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from author.views import WelcomeView, LogoutView
from django.views.generic import TemplateView
from .views import login
urlpatterns = patterns('',
url(r'^surveys/', include("surv... |
from test import helpers
from test.helpers import ProviderTestBase
from cloudbridge.cloud.interfaces import VolumeState
from cloudbridge.cloud.interfaces.exceptions import WaitStateException
class CloudObjectLifeCycleTestCase(ProviderTestBase):
@helpers.skipIfNoService(['block_store.volumes'])
def test_obje... |
"""This example updates teams by adding an ad unit to a team.
To determine which teams exist, run get_all_teams.py. To determine which ad
units exist, run get_all_ad_units.py
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
... |
import rg
class Robot(object):
'''This version of bipolar bot runs away from other bullies,
even if they are on the same team. This doesn't seem to improve
his chances much more than the original version, but oh well.'''
DISPOSITIONS = {}
def act(self, game):
if self.hp < (rg.settings.ro... |
'''
File input/output for this project ONLY
'''
import copy
import os
import sys
import numpy as np
import pandas as pd
from scipy.stats.mstats import zscore
import joblib
from nilearn.signal import clean
def save_output(dataset, confound, best_clf, X, Y, path):
'''
save the scores and cognitve measures in ... |
# $language = "python"
# $interface = "1.0"
import sys
def main():
screen = crt.Screen
dlg = crt.Dialog
screen.Synchronous = True
passwd = dlg.Prompt('Please enter your password', isPassword = True)
userID = dlg.Prompt("Enter user's employee ID")
# Unlock User's account
screen.Send("sudo g... |
""" Package vvmovie (visvis-movie)
All submodules have been designed to be work independent of each-other
(except the image2avi module, which requires the images2ims module).
Provides the following functions:
* readGif & writeGif -> a movie stored as animated GIF
* readSwf & writeSwf -> a movie stored as shock... |
import logging
from twisted.internet import interfaces # noqa: F401
from twisted.internet.protocol import Factory
from twisted.protocols.tls import TLSMemoryBIOFactory
from twisted.web.client import readBody
from twisted.web.http import HTTPChannel
from sygnal.helper.proxy.proxyagent_twisted import ProxyAgent
from ... |
"""Test overloaded method resolution in VTK-Python
The wrappers should call overloaded C++ methods using similar
overload resolution rules as C++. Python itself does not have
method overloading.
Created on Feb 15, 2015 by David Gobbi
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
class T... |
import time
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from skynet.linear.k_nearest_neighbor import KNearestNeighbor
from skynet.linear.linear_classifier import Softmax, LinearSVM
from skynet.utils.data_utils ... |
from geopy.geocoders import GoogleV3
import csv
import pandas as pd
# with open('asians.csv', 'rU') as csvfile:
# reader = csv.reader(csvfile)
# # for row in reader:
# # print(row[0])
#
# col_1 = list(zip)
# geolocator = Nominatim()
# location = geolocator.geocode("Singapore")
# print(location.latitude,... |
"""Main entry point into the Identity service."""
from keystone.common import dependency
from keystone.common import logging
from keystone.common import manager
from keystone import config
from keystone import exception
CONF = config.CONF
LOG = logging.getLogger(__name__)
def filter_user(user_ref):
"""Filter ... |
#!/usr/bin/env python
import sys,sqlite3
from subprocess import call
if __name__ == "__main__":
if len(sys.argv) != 3:
print ("usage: load_database database_name division download")
print ("\t\tdatabase_name = any database name that will be referred to later")
print ("\t\tdivision = the division as recognized ... |
"""
Django settings for pystp project.
Generated by 'django-admin startproject' using Django 1.11.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
... |
#! /usr/bin/python
# Module:
from ..agent import GuardAgent
class ExecutionContext:
guard = None
DEBUG_LEVEL = 4
INFO_LEVEL = 3
WARNING_LEVEL = 2
ERROR_LEVEL = 1
def __init__(self, print_level = 1):
self.print_level = print_level
self.guard = GuardAgent(self)
def launch(self, agent):
rai... |
import os, platform
DEVELOPMENT_MODE = (platform.node() != "uhura.websushi.org")
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
DEFAULT_FROM_EMAIL = "<EMAIL>"
ADMINS = (
('Arne Brodowski', '<EMAIL>'),
('Jannis Leidel', '<EMAIL>'),
('Martin Mahner', '<EMAIL>'),
)
MANAGERS = ADMINS
if DEVELOPM... |
"""
FCMatch - command ``/bin/fc-match -sv 'sans:regular:roman' family fontformat``
==============================================================================
This command gets the fonts information in the current system.
Typical output of this command is::
Pattern has 2 elts (size 16)
family: "DejaVu... |
from datetime import datetime
import django
import traceback
import csv
import os
os.environ['DJANGO_SETTINGS_MODULE'] = "mwd_proj.settings"
django.setup()
from django.db.models import Max, Min
from mwd_proj.phase1.models import *
def normalize_tables():
"This method normalizes all timestamp and actor_movie_rank valu... |
"""Statistical accumulators. They accumulate the highs, lows, averages,
etc., of a sequence of records."""
import math
import weewx
from weewx.units import ListOfDicts
class OutOfSpan(ValueError):
"""Raised when attempting to add a record outside of the timespan held by an accumulator"""
#======================... |
from setuptools import setup, find_packages
VERSION = '0.2.1'
AUTHOR_NAME = 'Bryant E. McDonnell (EmNet LLC)'
AUTHOR_EMAIL = '<EMAIL>'
setup(name='SWMMOutputAPI',
version=VERSION,
description='Python Wrapper for SWMM5 Binary Output File',
author=AUTHOR_NAME,
url='https://github.com/bemcd... |
# -*- coding: utf-8 -*-
# Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
#
# Below is one possible representation of s1 = "great":
#
# great
# / \
# gr eat
# / \ / \
# g r e at
# / \
# a t
# To scramble... |
#!/usr/bin/python2
import argparse
import os.path
from itertools import izip_longest, product
from math import ceil
from struct import pack, unpack
from StringIO import StringIO
from wii_lz77 import WiiLZ77
from PIL import Image
from lz77 import compress
# Attributes from sprite.h of libnds
# Attribute 0 consists of 8... |
"""
cmap_value.py
"""
# Load the needed packages
import numpy as np
from ..core import QtWidgets, QtGui, QtCore
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends import pylab_setup
FigureCanvasQTAgg = pylab_setup()[0].FigureCanvasQTAgg
#from matplotlib.backends.backend_qt4a... |
from future.standard_library import install_aliases
install_aliases()
import json
import re
import requests
import datetime, time
from future.utils import iteritems
from urllib.parse import urljoin, quote_plus
class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES =... |
def _is_using_buggy_driver():
import bgl
# We need to be conservative here because in multi-GPU systems display card
# might be quite old, but others one might be just good.
#
# So We shouldn't disable possible good dedicated cards just because display
# card seems weak. And instead we only blac... |
from odoo import api, fields, models
from odoo.tools import float_compare
class MrpProduction(models.Model):
_inherit = 'mrp.production'
sale_name = fields.Char(compute='_compute_sale_name_sale_ref', string='Sale Name', help='Indicate the name of sales order.')
sale_ref = fields.Char(compute='_compute_sa... |
# -*- coding: utf-8 -*-
'''
Test suite for vdirsyncer.
'''
import random
import hypothesis.strategies as st
from vdirsyncer.vobject import Item
import urllib3
import urllib3.exceptions
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def blow_up(*a, **kw):
raise AssertionError('Did not exp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.