content stringlengths 4 20k |
|---|
#!/usr/bin/env python3
# This example shows how to implement a simple, but highly configurable window
# switcher (like a much improved "alt-tab") with iterative dmenu calls. This
# script works well for most use cases with no arguments.
#
# https://faq.i3wm.org/question/228/how-do-i-find-an-app-buried-in-some-workspac... |
import urllib
import json
import requests
class Client():
"""A Client for the OpenJUB-API.
:param token: Token to use for authentication.
:param app_id: App Id to be used only when using authentication.
:param server: The Address of the OpenJUB server to use. Must include protocol, port and ending slash.
""... |
import optimize_webui
import os
import shutil
import tempfile
import unittest
_HERE_DIR = os.path.dirname(__file__)
class OptimizeWebUiTest(unittest.TestCase):
def setUp(self):
self._out_folder = None
self._tmp_dirs = []
self._tmp_src_dir = None
def tearDown(self):
for tmp_dir in self._tmp_dirs... |
# -*- coding: utf-8 -*-
"""This package provides some built-in flash storage backends used to persist
the *flash* contents across requests.
"""
from django.conf import settings
# Alias for use in settings file --> name of module in "storage" directory.
# Any storage that is not in this dictionary is treated as a Py... |
#!/usr/bin/env kross
# -*- coding: utf-8 -*-
# import some python modules.
import os, sys, traceback, tempfile, zipfile
# import the kross module.
import Kross
KOfficeAppName="KWord"
KOfficeAppExt="odt"
try:
# try to import the KOffice application. If this fails we are not running embedded.
KOfficeAppModule... |
# -*- coding: utf-8 -*-
""" Efficient representation of tokens
We want to have a token_list and start_position for everything the
tokenizer returns. Therefore we need a memory efficient class. We
found that a flat object with slots is the best.
"""
from jedi._compatibility import utf8, unicode
class Token(object):
... |
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
... |
from spack import *
class PerlCompressRawZlib(PerlPackage):
"A low-Level Interface to zlib compression library"
homepage = "http://search.cpan.org/~pmqs/Compress-Raw-Zlib-2.081/lib/Compress/Raw/Zlib.pm"
url = "https://cpan.metacpan.org/authors/id/P/PM/PMQS/Compress-Raw-Zlib-2.081.tar.gz"
versio... |
"""File system utilities with event reporting."""
import errno
import os
from rose.reporter import Event
import shutil
import sys
class FileSystemEvent(Event):
"""An event raised on a file system operation."""
CHDIR = "chdir"
COPY = "copy"
CREATE = "create"
DELETE = "delete"
INSTALL = "inst... |
import unittest
import IECore
import Gaffer
import GafferTest
import GafferImage
import os
class RemoveChannelsTest( unittest.TestCase ) :
checkerFile = os.path.expandvars( "$GAFFER_ROOT/python/GafferTest/images/checker.exr" )
def testDirtyPropagation( self ) :
r = GafferImage.ImageReader()
r["fileName"].setV... |
'''
Red9 Studio Pack: Maya Pipeline Solutions
Author: Mark Jackson
email: <EMAIL>
Red9 blog : http://red9-consultancy.blogspot.co.uk/
MarkJ blog: http://markj3d.blogspot.co.uk
Core is the library of Python modules that make the backbone of the Red9 Pack
:Note that the registerMClassInheritanceMapping() call is... |
__author__ = 'Georgios Rizos (<EMAIL>)'
import datetime
import time
from oauth2client.tools import argparser
from googleapiclient.errors import HttpError
from youtube_discussion_collector.auth_new import get_authenticated_service
from youtube_discussion_collector.collect import get_video_metadata, get_all_comment_th... |
"""
EasyBuild support for DB, implemented as an easyblock
@author: Kenneth Hoste (Ghent University)
"""
import os
import shutil
from easybuild.easyblocks.generic.configuremake import ConfigureMake
from easybuild.tools.build_log import EasyBuildError
class EB_DB(ConfigureMake):
"""Support for building and instal... |
log_patterns = {
"resource": (
( # detail 0
"lrmd.*%% (?:start|stop|promote|demote|migrate)",
"lrmd.*RA output: .%%:.*:stderr",
"lrmd.*WARN: Managed %%:.*exited",
"lrmd.*WARN: .* %% .*timed out$",
"crmd.*LRM operation %%_(?:start|stop|promote|demo... |
from tests import unittest
from twisted.internet import defer
from mock import Mock, call
from collections import OrderedDict
from synapse.server import HomeServer
from synapse.storage._base import SQLBaseStore
from synapse.storage.engines import create_engine
class SQLBaseStoreTestCase(unittest.TestCase):
""... |
"""Classes to help gather user submissions."""
import logging
from typing import Dict, Any, Callable, Hashable, List, Optional # noqa pylint: disable=unused-import
import uuid
import voluptuous as vol
from .core import callback, HomeAssistant
from .exceptions import HomeAssistantError
_LOGGER = logging.getLogger(__na... |
"""Parses flags passed on the command line.
If you're looking for the entry points, they're in commands.py, this only
deals with user options.
"""
import sys
from functools import wraps
from .constants import VERSION
def flags(*args):
"""Returns a boolean of if any of the flags are selected.
-single char... |
# pylint: disable=missing-docstring,broad-except
"""
Reload forum (comment client) users from existing users.
"""
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
import openedx.core.djangoapps.django_comment_common.comment_client as cc
class Command(BaseCommand):
... |
import json
import pycurl
import re
import sys
if sys.version_info >= (3,):
from StringIO import BytesIO
else:
from StringIO import StringIO
import occi
# for curl helper callback function
header = []
def get_header2(buff):
global header
header.append(buff)
def get_header3(buff):
global heade... |
import sys
from mosek.fusion import *
# Customer locations
customerloc = DenseMatrix([ [12.0, 2.0],
[15.0, 13.0],
[10.0, 8.0],
[ 0.0, 10.0],
[ 6.0, 13.0],
[ 5.0, 8.0],
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 27 14:30:51 2017
Perform Lomb-Scargle algorithm on PTF optical data.
Dependencies: PTF_fulltable_phot{1/2}.txt
@author: stephaniekwan
"""
# License: BSD
# The figure produced by this code is published in the textbook
# "Statistics, Data Mining, and Machine Learning... |
import math
class Graph:
def __init__(self):
self.edge_weight_types = { "EUC_2D": self.euclidean_distance_2d }
self.name = None
self.comment = ""
self.dimension = -1
self.edge_weight_type = None
self.nodes = {}
self.distances = {}
def valid(self):
return (self.dimension == len(sel... |
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt
from ts2 import utils
class PositionGraphicsItem(QtGui.QGraphicsPolygonItem):
"""This class is a graphics representation of a position to be put on a
scene.
"""
def __init__(self, simulation, position=None, parent=None):
"""Constructor... |
# source: http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget
import sys, os, re
import traceback, platform
from PyQt4 import QtCore
from PyQt4 import QtGui
from electrum_doge import util
if platform.system() == 'Windows':
MONOSPACE_FONT = 'Lucida Console'
elif platform.... |
"""Tests for ceilometer.alarm.service.SingletonAlarmService.
"""
import mock
from oslo.config import cfg
from stevedore import extension
from ceilometer.alarm import service
from ceilometer import messaging
from ceilometer.openstack.common import test
class TestSingletonAlarmService(test.BaseTestCase):
def set... |
"""Unit tests for the ValueProvider class."""
from __future__ import absolute_import
import logging
import unittest
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.value_provider import RuntimeValueProvider
from apache_beam.options.value_provider import StaticValueProvider
... |
from __future__ import unicode_literals
from django.apps import apps
from django.db import models
from django.db.utils import OperationalError, ProgrammingError
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_text, force_text
from django.utils.encoding import python_2_un... |
# -*- coding: utf-8 -*-
"""
unit test for loop functions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2007 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
SIMPLE = '''{% for item in seq %}{{ item }}{% endfor %}'''
ELSE = '''{% for item in seq %}XXX{% else %}...{% endfor %}'''
EMPTYBLOC... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
tpi.py
---------------------
Date : October 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*********************... |
from io import StringIO
import pytest
import numpy as np
from astropy.io import ascii
from astropy.table import Table, QTable
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.io.misc.pandas import connect
# Check dependencies
pandas = pytest.importorskip("pandas")
connect.import_... |
from intelmq.lib.bot import Bot, sys
from intelmq.lib.message import Event
from intelmq.bots import utils
from azure.storage import BlobService
import gzip
import StringIO
import datetime
from urlparse import urlparse
class DCUCollectorBot(Bot):
"""
This IntelMQ collector is for getting a blob
fro... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
MacroEcoDialog
A QGIS plugin
Macro Ecology tools for presence absence matrices
-------------------
begin : 2011-02-21
co... |
""" This module contains the PCState state.
"""
from __future__ import absolute_import
from __future__ import print_function
import logging
from functools import partial
from core.tools import open_dialog
from core.components.game_event import GAME_EVENT, INPUT_EVENT
from core.components.locale import translator
from... |
# -*- encoding:utf-8 -*-
from __future__ import unicode_literals
MESSAGES = {
"%d min remaining to read": "%d perc van hátra olvasni",
"(active)": "(aktív)",
"Also available in:": "Olvasható még:",
"Archive": "Archív",
"Authors": "Szerzők",
"Categories": "Kategóriák",
"Comments": "Hozzászól... |
from a10sdk.common.A10BaseClass import A10BaseClass
class PortCfg(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param acct_port: {"description": "Specify the RADIUS server's accounting port (default 1813)", "minimum": 1, "type": "number", "maximum": 65535, "format": "... |
#!/usr/bin/env python
# This file should be compatible with both Python 2 and 3.
# If it is not, please file a bug report.
"""
This is a PermissionAccepter object used to get user approval of permissions via the command line.
"""
#external imports
from collections import OrderedDict
#internal imports
from subuserlib.... |
from django.shortcuts import get_object_or_404
class MultipleFieldLookupMixin(object):
"""
Apply this mixin to any view or viewset to get multiple field filtering
based on a `lookup_fields` attribute, instead of the default single field filtering.
Source: Django REST Framework Documentation
"""
... |
import numpy
import chainer
from chainer import _backend
from chainer.backends import _cpu
from chainer.backends import cuda
from chainer.backends import intel64
import chainerx
class ChainerxDevice(_backend.Device):
"""Device for ChainerX backend"""
def __init__(self, device):
# type: (chainerx.De... |
import inspect
import os
import random
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_messaging import server as rpc_server
from oslo_service import loopingcall
from oslo_service import service as common_service
from oslo_utils import excutils
from o... |
basestring = (str, bytes)
numeric_types = (int, float)
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v # pragma: no cover
elif isinstance(v, bool):
if v:
p... |
from gofer.rmi.container import Container
class Agent(Container):
"""
A remote agent.
"""
def __init__(self, url, address, **options):
"""
:param url: The agent URL.
:type url: str
:param address: The AMQP address to the agent.
:type address: str
"""
... |
# -*- coding: utf-8 -*-
'''
The module of a post manager object.
'''
import os
from cray.craylib import utility
from cray.craylib.page import Page
_LOGGER = utility.get_logger('cray.PageManager')
class PageManager(object):
"""Manager of pages"""
_init_template = ""
def __init__(self, page_dir):
... |
import errno
import os
from pylatex import Document, NoEscape, Package
from cirq import circuits
from cirq.contrib.qcircuit.qcircuit_diagram import circuit_to_latex_using_qcircuit
def circuit_to_pdf_using_qcircuit_via_tex(
circuit: circuits.Circuit,
filepath: str,
pdf_kwargs=None,
qcircuit_kwargs=No... |
from amino import *
from math import pi
sg = SceneGraph().load(".libs/libamino_baxter.so", "baxter")
sg.init()
win = SceneWin(scenegraph=sg,start=False)
win.set_config( {'right_s0': .05*pi,
'right_s1': -.25*pi,
'right_e1': .25*pi,
'right_w1': .25*pi } )
win.start(a... |
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.blocktools import create_block, create_coinbase
EXPEDITED_VERSION = 80002
# class InvResp(Flags):
REQ_TX = 1
REQ_THINBLOCK = 2
REQ_XTHINBLOCK = 4
REQ_BLOCK = 8
c... |
from pygments.lexer import RegexLexer, bygroups, using, default, include
from pygments.lexers.data import JsonLexer
from pygments.token import *
class StoryLexer(RegexLexer):
"""Lexer for the Rasa Core story file format.
Used for syntax highlighting of story snippets in the docs."""
name = "Story"
a... |
# -*- encoding=UTF-8 -*-
import os
from askMathPlus.settings import generate_color, COLORS_ALL
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext as _
class Video(models.Model):
lesson = models.ForeignKey('Lesson', verbose_name=_(u"Lesson"),
... |
#!/usr/bin/env python
from Cheetah.Template import Template
import os
import argparse
import re
import tempfile
import nibabel as nib
# This script will compile an FSL Feat Design File for the first level
class GenerateFSF(object):
"""
Generates the FSF file for FSL's Feat analysis.
"""
def __init__(self, te... |
"""
Unit Tests for nova.consoleauth.rpcapi
"""
from nova.consoleauth import rpcapi as consoleauth_rpcapi
from nova import context
from nova.openstack.common import cfg
from nova.openstack.common import rpc
from nova import test
CONF = cfg.CONF
class ConsoleAuthRpcAPITestCase(test.TestCase):
def _test_consoleaut... |
from core.moduleguess import ModuleGuess
from core.moduleexception import ProbeException, ProbeSucceed
WARN_DOWNLOAD_OK = 'Downloaded succeed'
class Webdownload(ModuleGuess):
'''Download web URL to remote filesystem'''
def _set_vectors(self):
self.vectors.add_vector(name='putcontent', interp... |
import cgi
from paste.urlparser import PkgResourcesParser
from pylons.middleware import error_document_template
from webhelpers.html.builder import literal
from prickle.lib.base import BaseController
class ErrorController(BaseController):
"""Generates error documents as and when they are required.
The Error... |
import logging
import zlib
import io
from ._collections import HTTPHeaderDict
from .exceptions import DecodeError
from .packages.six import string_types as basestring, binary_type
from .util import is_fp_closed
log = logging.getLogger(__name__)
class DeflateDecoder(object):
def __init__(self):
... |
"""
Routines for reading PDML produced from TShark.
Copyright (c) 2003, 2013 by Gilbert Ramirez <<EMAIL>>
SPDX-License-Identifier: GPL-2.0-or-later
"""
import sys
import xml.sax
from xml.sax.saxutils import quoteattr
import cStringIO as StringIO
class CaptureFile:
pass
class FoundItException(Exception):
""... |
#!/usr/bin/env python
import roslib; roslib.load_manifest('rfh_follow_me')
import rospy
import tf
import math
from rfh_follow_me.msg import Distance
import numpy as np
if __name__ == '__main__':
rospy.init_node('rfh_person_tracker')
listener = tf.TransformListener()
rate = rospy.Rate(10.0)
while not rospy.is_shu... |
import warnings
from qubell import deprecated
from qubell.api.private.environment import EnvironmentList
from qubell.api.private.revision import Revision
from qubell.api.private.service import ServiceMixin
import re
__author__ = "Vasyl Khomenko"
__copyright__ = "Copyright 2013, Qubell.com"
__license__ = "Apache"
__ema... |
import os
import logging
from .backends.elf.metaelf import MetaELF
from .errors import CLEFileNotFoundError
l = logging.getLogger('cle.gdb')
def convert_info_sharedlibrary(fname):
"""
Convert a dump from gdb's ``info sharedlibrary`` command to a set of options that can be passed to CLE to replicate
the a... |
from __future__ import absolute_import
import zulip
from six.moves import range
from typing import Any, Optional, Text
from mercurial import ui, repo
VERSION = "0.9"
def format_summary_line(web_url, user, base, tip, branch, node):
# type: (str, str, int, int, str, Text) -> Text
"""
Format the first line ... |
import sys,os
import re,glob
import numpy as np
import scipy.sparse
from sklearn.naive_bayes import MultinomialNB
import cPickle as pickle
import pkg_resources
from . import content_sources
#remove punctuation and prepositions from a string
def find_keywords(text):
keywords=re.sub('[{}:?!@#$%^&*\(\)_.\\/,\'\"]','... |
import csv
from operator import attrgetter
import bleach
from html import unescape
from django.conf import settings
from django.urls import reverse
from agir.lib.export import dicts_to_csv_lines
__all__ = ["groups_to_csv", "groups_to_csv_lines"]
COMMON_FIELDS = [
"name",
"published",
"contact_email",
... |
"""
Beating the Benchmark
Truly Native?
__author__ : David Shinn, modified by firefly2442
"""
from __future__ import print_function
import glob, multiprocessing, os, re, sys, time, pickle, random, string
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from nltk.corpus import stopwords
#make sur... |
from settings import ACCESS_TOKEN, SECRET_KEY
from coinone.account import Account
import random
import time
import logging
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(format=log_format, level=logging.DEBUG)
logger = logging.getLogger(__name__)
"""
Monkey is a dumb bot.
Ev... |
# coding: utf-8
from traitlets import default
from .baseapp import NbGrader, nbgrader_aliases, nbgrader_flags
from ..exchange import Exchange, ExchangeReleaseFeedback, ExchangeError
aliases = {}
aliases.update(nbgrader_aliases)
aliases.update({
"timezone": "Exchange.timezone",
"course": "CourseDirectory.cou... |
from django.db import IntegrityError
from django.test import TestCase
from base.models import learning_achievement
from base.tests.factories.academic_year import create_current_academic_year
from base.tests.factories.business.learning_units import GenerateContainer
from base.tests.factories.learning_achievement import... |
import datetime, time
import json
class Earthquake:
items = []
def __init__(self, service=''):
if len(service) <= 0:
self.__manager = Manager()
else:
self.__manager = Manager(service=service)
def __call__(*args, **kwargs):
totArgs = len(args) + len(kwargs.key... |
from tempest.api.identity import base
from tempest.common.utils import data_utils
from tempest import test
class PoliciesTestJSON(base.BaseIdentityV3AdminTest):
_interface = 'json'
def _delete_policy(self, policy_id):
self.policy_client.delete_policy(policy_id)
@test.attr(type='smoke')
def t... |
# File: producer.py
# Description: This is the AMQP SSL producer publishes outgoing AMQP
# communication to clients consuming messages from a broker server.
# This example applies routing-key pattern out of 5 patterns.
# It needs to acquire the public CA certificate to verify certificate of robomq.io.
#
# ... |
#!/usr/bin/env python
import json
import logging
import os
import requests
import sys
import tempfile
import tkMessageBox
from Crypto import Random
from Crypto.Cipher import AES
from datetime import datetime
from getpass import getpass
from hashlib import md5
from random import randint
from re import search, match
fro... |
from __future__ import division
def run(args):
if (len(args) == 0): args = ["--help"]
from libtbx.option_parser import option_parser
import libtbx.load_env
command_line = (option_parser(
usage="%s [options] fortran_file ..." % libtbx.env.dispatcher_name)
.option(None, "--top_procedure",
action="ap... |
"""This code example deactivates all active Labels.
To determine which labels exist, run get_all_labels.py. This feature is only
available to DFP premium solution networks."""
__author__ = ('Nicholas Chen',
'Joseph DiLallo')
# Import appropriate modules from the client library.
from googleads import df... |
"""
Django settings for tango_with_tango_project project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
... |
# Python's datetime strftime doesn't handle dates before 1900.
# These classes override date and datetime to support the formatting of a date
# through its full "proleptic Gregorian" date range.
#
# Based on code submitted to comp.lang.python by Andrew Dalke
#
# >>> datetime_safe.date(1850, 8, 2).strftime("%Y/%m/%d was... |
"""
This module defines a method genrdf, which takes a metadata dictionary
as parameter and returns a rdflib Graph instance.
"""
from hcsvlab_robochef.rdf.map import *
from hcsvlab_robochef.rdf.namespaces import *
# corpus identifier
ACE = "ACE"
ACENS = corpus_property_namespace(ACE)
ACE_GENRES = {'A': Literal('Press... |
import astropy.units as uu
import astropy.cosmology as co
aa = co.Planck13
#aah = co.FlatLambdaCDM(H0=100.0 *uu.km / (uu.Mpc *uu.s), Om0=0.307, Tcmb0=2.725 *uu.K, Neff=3.05, m_nu=[ 0. , 0. , 0.06]*uu.eV, Ob0=0.0483)
#rhom = aa.critical_density0.to(uu.solMass*uu.Mpc**-3).value
#aa.critical_density0.to(uu.solMass*uu.... |
from logging import getLogger
from pathlib import Path
from typing import Tuple
from panflute import convert_text
from panflute.tools import pandoc_version
from pytest import mark, xfail
# use the function exactly used by the cli
from pantable.table_to_codeblock import table_to_codeblock
logger = getLogger('pantable... |
#!/usr/bin/env python
""" A simple RPC server that shows how to serve generators
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2012-2014. Brian Granger, Min Ragan-Kelley, Alexander Glyzov
# Axel Voitier
#
# Distributed under the terms of the BSD License. The fu... |
from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, time
from collections import namedtuple
from django import forms
from django.utils.dateparse import parse_datetime
from django.utils.encoding import force_str
from django.utils.translation import ugettext_la... |
#!/usr/bin/env python
# svcrash.py - SIPvicious crash breaks svwar and svcrack
__GPL__ = """
Sipvicious crash exploits a bug in svwar/svcrack.py to stop unauthorized
scans from flooding the network.
Copyright (C) 2012 Sandro Gauci <<EMAIL>>
This program is free software: you can redistribute it and/or m... |
import os
import uuid
from oslo_config import cfg
import six
from sahara import conductor as c
from sahara import context
from sahara import exceptions as e
from sahara.i18n import _
from sahara.service.edp import base_engine
from sahara.service.edp.binary_retrievers import dispatch
from sahara.service.edp import hdf... |
"""File translation command"""
import logging
import warnings
import click
from cligj import format_opt
import numpy as np
from .helpers import resolve_inout
from . import options
import rasterio
from rasterio.coords import disjoint_bounds
warnings.simplefilter('default')
# Clip command
@click.command(short_help... |
"""Res data.
"""
import sys
import os
import csv
import glob
NUM_ARGS = 2
from ctes import *
from kdat import KDat
from clda import ClDat
from kscrap import KScrap
import unicodedata as un
class Res(object):
_LO = 0
_VI = 1
_SCO = 2
_GO = 3
_END = 4
_STATES = [ _LO, _VI, _S... |
# coding: utf-8
import copy
from google.appengine.ext import ndb
from webargs import fields as wf
from webargs.flaskparser import parser
import flask
import flask_login
import flask_wtf
import wtforms
import auth
import cache
import config
import model
import task
import util
from main import app
################... |
import os
from .time import str_to_datetime
from functools import wraps
import random
import string
import glob
import datetime
import shelve
import shutil
from operator import itemgetter
from .exif import dt_get
DEFAULT_EXTENSIONS = ["jpeg", "jpg", "tif", "tiff", "cr2", "raw", "nef", "png", "json"]
def needs_db(f):... |
"""
Import sample data for classification engine
"""
import predictionio
import argparse
import csv
import math
def import_events(client, file):
f = open(file, 'r')
count = 0
print "Importing data..."
dataset = csv.DictReader(f)
for row in dataset:
if row['Sex']=='male':
sex = 0
else:
... |
from aiorchestra.tests import base as aiorchestra
from openstack_plugin.tests.integration import base
from openstack_plugin.tests.integration import config
class TestAuth(base.BaseAIOrchestraOpenStackTestCase):
def setUp(self):
super(TestAuth, self).setUp()
def tearDown(self):
super(TestAut... |
import os
import unittest
from PIL import Image
from diffbrowsers.diffbrowsers import compare_image
class TestImgDiff(unittest.TestCase):
def setUp(self):
data_dir = os.path.join(os.path.dirname(__file__), 'data')
self.img_before_path = os.path.join(data_dir, 'img_before.jpg')
self.img_af... |
__author__ = 'Christopher Nelson'
class Quota:
def __init__(self, name, maximum_concurrent):
"""
Creates a new rule enforces a maximum number of globally concurrent jobs in the same
named queue.
:param name: The tag name to evaluate.
:param maximum_concurrent: The maximum ... |
import time
from director import segmentationroutines
from director import segmentation
from director.timercallback import TimerCallback
from director.visualization import *
class TrackDrillOnTable(object):
def __init__(self):
self.tableCentroid = None
def updateFit(self):
# get and display: ... |
import logging
from sn_agent import ontology
from sn_agent.job.job_descriptor import JobDescriptor
from sn_agent.job.job_descriptor import init_test_jobs
from sn_agent.log import setup_logging
from sn_agent.ontology.service_descriptor import ServiceDescriptor
import tests
log = logging.getLogger(__name__)
# Tests
... |
# makecontexts
#
# A script that extracts three words on either side of a word related to money.
import modelingcounter
import os, sys
import SonicScrewdriver as utils
import csv
rows, columns, table = utils.readtsv('/Volumes/TARDIS/work/metadata/MergedMonographs.tsv')
verbose = True
targetwords = {'crown', 'crowns... |
from unittest.case import TestCase
class Noh:
def __init__(self):
self.valor = None
self.proximo_noh = None
class ListaLigadaSimples:
def __init__(self):
self.inicio = None # aponta para o Noh inicial
def adicionar(lista, valor):
noh = Noh()
noh.valor = valor
if lista.... |
#!/usr/bin/env python
import os
import logging
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import pickle
def setLogger(fname,loglevel):
""" Function to handle error logging """
logging.basicConfig(filename=fname, filemode='w', level=loglevel, format='%(asctime)s - %(levelname)s - ... |
from atmPy.aerosols.size_distribution import sizedistribution
from atmPy.aerosols.size_distribution import diameter_binning
import pandas as pd
from atmPy.data_archives.arm._netCDF import ArmDataset
from atmPy.data_archives.arm._netCDF import Data_Quality
import numpy as np
class ArmDatasetSub(ArmDataset):
def __i... |
'''<b>Correct Illumination - Apply</b> applies an illumination function, usually created by
<b>CorrectIlluminationCalculate</b>, to an image in order to correct for uneven
illumination (uneven shading).
<hr>
This module applies a previously created illumination correction function,
either loaded by <b>LoadSingleImage<... |
"""Customized QWebInspector for QtWebEngine."""
import os
from PyQt5.QtCore import QUrl
# pylint: disable=no-name-in-module,import-error,useless-suppression
from PyQt5.QtWebEngineWidgets import QWebEngineView
# pylint: enable=no-name-in-module,import-error,useless-suppression
from qutebrowser.browser import inspecto... |
"""Use another Mapchete process as input."""
from mapchete import Mapchete
from mapchete.config import MapcheteConfig
from mapchete.formats import base
from mapchete.io.vector import reproject_geometry
METADATA = {
"driver_name": "Mapchete",
"data_type": None,
"mode": "r",
"file_extensions": ["mapche... |
import math
import numpy as np
from bs4 import BeautifulSoup
class Motor(object):
def __init__(self, _index=-1, _id=-1, _name=""):
self.index = _index
self.id = _id
self.name = _name
self.min_angle = -5.0 / 6.0 * math.pi
self.max_angle = 5.0 / 6.0 * math.pi
def swap(s... |
import cv2
import numpy as np
element_big = cv2.getStructuringElement(cv2.MORPH_RECT,( 10,10 ),( 0, 0))
element_small = cv2.getStructuringElement(cv2.MORPH_RECT,( 5,5 ),( 0, 0))
def otsuMulti(im):
N = float(im.shape[0]*im.shape[1])
histogram = np.histogram(im,bins=range(0,256),range=(0,255),density=False)
... |
__author__ = 'Neil Butcher'
'''
Created on 8 Oct 2012
@author: neil
'''
import unittest
from Rota_System.Worker import Worker
from Rota_System import Roles
class WorkerTest(unittest.TestCase):
def setUp(self):
self.bob = Worker()
self.bob.name = 'Bob'
Roles.GlobalRoleList.add_role(Roles.... |
#!/usr/bin/python
import meraki
import json
import csv
#
# Python Script Using Meraki API to pull public IP addresses for each field site
# Writes the data to CSV
#
# Enter User's API Key
apikey = 'XXXXXXXXX'
# Enter Organization ID Here
organizationid = 'XXXXXXX'
#Network lookup
networks = meraki.getnetworklist(a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##=====================================================================================##
## Autor: Daniel López Coto ##
## Programa: Conversor de tablas a formato LaTeX ##
##======================================================================... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.