content stringlengths 4 20k |
|---|
{
'name': 'Belgium - Accounting',
'version': '1.1',
'category': 'Localization/Account Charts',
'description': """
This is the base module to manage the accounting chart for Belgium in OpenERP.
==============================================================================
After installing this module... |
import gevent.monkey
gevent.monkey.patch_all()
import cgi
import time
import json
import urllib
import weakref
import urlparse
from gevent.pywsgi import WSGIServer
from sse import Client, EventSource
CLIENTS = weakref.WeakSet()
CHANNELS = {'default': EventSource()}
INDEX_FILE = open('chat.html', 'rb')
INDEX = INDE... |
'''
JSON related utilities.
This module provides a few things:
1) A handy function for getting an object down to something that can be
JSON serialized. See to_primitive().
2) Wrappers around loads() and dumps(). The dumps() wrapper will
automatically use to_primitive() for you if needed.
3) Th... |
from __future__ import absolute_import
from .duration import Duration
from .enums import PredecessorType
from ..types import *
from ..util import serialize
from ..util import deserialize
class Predecessor(object):
"""Smartsheet Predecessor data model."""
def __init__(self, props=None, base_obj=None):
... |
"""
====================
Plain Value Mapper
====================
The mapper provided by the `PlainMapper` class maps value according to
configured mapping sections.
"""
__author__ = "André Malo"
__docformat__ = "restructuredtext en"
__all__ = ['Error', 'ConfigMappingSectionNotFoundError', 'PlainMapper']
# g... |
import time
from ..util import get_dependency
from ..errors import ConfigurationError
from .base import Storage
class RedisInteractor(object):
SCRIPT_MOVING_WINDOW = """
local items = redis.call('lrange', KEYS[1], 0, tonumber(ARGV[2]))
local expiry = tonumber(ARGV[1])
local a = 0
... |
import _ast
import ast
from ninja_ide.tools.completion import analyzer
from ninja_ide.tools.logger import NinjaLogger
logger_imports = NinjaLogger(
'ninja_ide.tools.introspection.obtaining_imports')
logger_symbols = NinjaLogger(
'ninja_ide.tools.introspection.obtainint_symbols')
_map_type = {
_ast.Tuple... |
from util import utils
import sys,os
import tables
import numpy as np
import matplotlib.pyplot as plt
from util.ObsFile import ObsFile
from util import MKIDStd
from util.rebin import rebin
from matplotlib import rcParams
import matplotlib
from scipy import interpolate
from scipy import integrate
from scipy.optimize.min... |
from mock import patch
import bokeh.core.validation as v
from bokeh.core.validation.errors import codes as ec
from bokeh.core.validation.warnings import codes as wc
from bokeh.model import Model
from bokeh.core.properties import Int
def test_error_decorator_code():
for code in ec:
@v.error(code)
... |
#!/usr/bin/env python
import optparse, re, sys
def error (msg, abortAfter=False):
sys.stderr.write(msg + "\n")
if abortAfter:
sys.exit(1)
def main ():
optparser = optparse.OptionParser()
options, args = optparser.parse_args()
file = open('./modules', 'r')
lines = file.readlines()
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
import os
import sys
import datetime
import time
from queue import Empty
from pytigon_lib.schtasks.publish import publish
import asyncio
from pytigon_lib.schtasks.remote_screen import RemoteScreen
def init_schedule(s... |
import ftpUpload
import ftplib
import ssl
import upload
__author__ = "Ned Batchelder"
__copyright__ = "Copyright 2016 Open Source Geospatial Foundation - all rights reserved"
__license__ = "GPL"
"""
FtpsUpload
Upload files via FTPS based on their content changing.
Based on original code by
Ned Batchelder
http... |
"""Commands: "!tenta [emote]", "!penta [emote]"."""
from bot.commands.command import Command
from bot.utilities.permission import Permission
class TentaReply(Command):
"""Reply with squid emotes or penta emotes."""
perm = Permission.User
def match(self, bot, user, msg, tag_info):
"""Match if the... |
# -*- coding: utf-8 -*-
import os
import mock
import lxml
import pytest
import responses
from nose.tools import * # noqa
from datacite import schema40
from framework.auth import Auth
from website import settings
from website.app import init_addons
from website.identifiers.clients import DataCiteClient
from website.... |
"""
WSGI config for semillas_backend project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLI... |
import string
from django.db import models
from django.core import validators
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser
from django.contrib.auth.signals import user_logged_in
from django.contrib.sessions.models import Session
from d... |
import sys
import caching
import urllib
import urllib2
import re
from pyquery import PyQuery as p
try: cache = caching.get_cache('itis')
except: cache = {}
def itis_lookup(name, TIMEOUT=10, CACHE=True):
'''
Look up "name" on itis.gov. If a standard name can be identified, returns
that name. Returns Fals... |
"""ShutIt module. See http://shutit.tk
"""
from shutit_module import ShutItModule
class erlang(ShutItModule):
def is_installed(self, shutit):
return shutit.file_exists('/root/shutit_build/module_record/' + self.module_id + '/built')
def build(self, shutit):
shutit.send('mkdir -p /tmp/build/erlang')
shutit... |
"""LInked List sparse matrix class
"""
from __future__ import division, print_function, absolute_import
__docformat__ = "restructuredtext en"
__all__ = ['lil_matrix','isspmatrix_lil']
import numpy as np
from scipy._lib.six import xrange
from .base import spmatrix, isspmatrix
from .sputils import (getdtype, isshape... |
from __future__ import absolute_import
from django.core.management.base import BaseCommand
from optparse import make_option
from ...vcs import VCS
from .ci import Command
class Command(Command):
help = (
'Usage: ./manage.py pup [--yes] [app_name]'
)
option_list = BaseCommand.option_list + (
... |
import matplotlib.pyplot
import utility
from matplotlib.backends.backend_pdf import PdfPages
import datetime
from crm_solver.atomic_db import RenateDB
class BeamletProfiles:
def __init__(self, param_path='output/beamlet/beamlet_test.xml', key=['profiles']):
self.param_path = param_path
self.param ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import json
from time import sleep
try:
from docker.errors import APIError
except ImportE... |
from rest_framework import renderers
from clldutils.dsv import UnicodeWriter
# TODO: add in 'How to cite' here
CSV_PREAMBLE = """
Research that uses data from D-PLACE should cite both the original source(s) of
the data and the paper by Kirby et al. in which D-PLACE was first presented
(e.g., research using cultural ... |
import hashlib
import locale
import math
import os
import re
import shlex
import socket
import subprocess
import time
import jinja2
from oslo.config import cfg
import requests
import stevedore.driver
import urllib3
from six.moves import zip_longest
from fuel_agent import errors
from fuel_agent.openstack.common impor... |
config = {
"name": "Flatworld", # plugin name
"type": "generator", #plugin type
"description": ["generates a flat world"] #description
}
import pygame
from pgu import gui
from omnitool.database import tiles, multitiles, walls, names, version
class Generator(): # required class to be called by plugin... |
class GetFeatures:
def __init__(self):
self.pos = {
"ADJ": 1,
"ADP": 2,
"ADV": 3,
"AUX": 4,
"CCONJ": 5,
"DET": 6,
"INTJ": 7,
"NOUN": 8,
"NUM": 9,
"PART": 10,
"PRON": 11,
... |
from collections import OrderedDict
import numpy as np
from os.path import isfile
from fastdtw import fastdtw
from pandas import read_csv
from csv import QUOTE_ALL
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF
from matplotlib import pyplot as plt
from ... |
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.expected_conditions import visibility_of_element_located, \
invisibility_of_element_located, presence_of_element_located
from selenium.webdriver.support.wait import WebDriverWait
from common.page_object import PageObject
from p... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# kate: space-indent on; indent-width 4; mixedindent off; indent-mode python;
from arsoft.utils import runcmdAndGetData, which
import sys, os
class TracAdmin(object):
def __init__(self, tracenv, trac_admin_bin=None, verbose=False):
self._tracenv = tracenv
... |
#!/usr/bin/env python
# UserString is a wrapper around the native builtin string type.
# UserString instances should behave similar to builtin string objects.
import string
from test import test_support, string_tests
from UserString import UserString, MutableString
import warnings
class UserStringTest(
... |
from django.test import TestCase
from api.helpers import user_service
from api.factories import UserFactory, PostFactory
class UserServiceTest(TestCase):
POSTS_PER_USER = 10
def setUp(self):
self.main_user = UserFactory()
self.follower = UserFactory()
self.test_user = UserFactory()
... |
"""
Claim objects for use with resource tracking.
"""
from oslo_log import log as logging
from oslo_serialization import jsonutils
from nova import context
from nova import exception
from nova.i18n import _
from nova.i18n import _LI
from nova import objects
from nova.objects import base as obj_base
from nova.virt imp... |
#Scenes
import sys, math, random, string #falta time?
from math import *
from pygame import *
from dynamics import *
from screen_setup import *
from cinematic import *
from axis import x_axis, y_axis
def scene_5 ( ):
puntos = width*height
chispa=range(0,puntos)
chispa_new=range(0,puntos)
color_up=255... |
"""
Django settings for web_sheets_django project.
Generated by 'django-admin startproject' using Django 1.11.
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/
"""
i... |
#! /usr/bin/env python
# encoding: utf-8
# DC 2008
# Thomas Nagy 2010 (ita)
"""
fortran support
"""
import re
from waflib import Utils, Task, TaskGen, Logs
from waflib.Tools import ccroot, fc_config, fc_scan
from waflib.TaskGen import feature, before_method, after_method, extension
from waflib.Configure import conf
... |
import numpy as np
import scipy as sp
from scipy import linalg
import pdb
## This is the main Kalman Filtering function.
## This calls everything and returns the final answer.
def kalman(y,dim_state,T,iter_max):
num_samples,dim_obsrv = y.shape
x_hat_initial = np.random.rand(dim_state)
P_hat_initial = np.... |
# -*- coding: utf-8 -*-
"""
End-to-end tests for the LMS.
"""
import pytest
from common.test.acceptance.fixtures.course import CourseFixture, XBlockFixtureDesc
from common.test.acceptance.pages.common.auto_auth import AutoAuthPage
from common.test.acceptance.pages.lms.courseware import CoursewarePage
from common.tes... |
# -*- coding: utf-8 -*-
"""
sleekxmpp.clientxmpp
~~~~~~~~~~~~~~~~~~~~
This module provides XMPP functionality that
is specific to external server component connections.
Part of SleekXMPP: The Sleek XMPP Library
:copyright: (c) 2011 Nathanael C. Fritz
:license: MIT, see LICENSE for more de... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from contextlib import contextmanager
import mock
from pex.package import EggPackage, Package, SourcePackage
from pex.resolver import Unsatisfiable, resolve... |
import functools
import operator
import sys
from setuptools import setup
if sys.version_info < (3, 5):
sys.exit('Python < 3.5 is not supported')
extras = {
'benchmark': ['pandas'],
'bot': ['ruamel.yaml', 'pygithub'],
'docker': ['ruamel.yaml', 'python-dotenv'],
'release': ['jinja2', 'jira', 'semver... |
import pytest
from pylaas_core.abstract.abstract_test_case import AbstractTestCase
from pylaas_core.pylaas_core import PylaasCore
from tests.fixtures.data_sets.service.dummy.dummy_configurable import DummyConfigurable
from tests.fixtures.data_sets.service.dummy_adapter.dummy_adapter_adapter import DummyAdapterAdapter
... |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
import json, os
def homepage(request):
return render(request, template_name='index.html', context={'page': 'home'})
def coc(request):
r... |
import threading
import shared
import time
import sys
import os
import pickle
import tr#anslate
from helper_sql import *
from helper_threading import *
from debug import logger
"""
The singleCleaner class is a timer-driven thread that cleans data structures
to free memory, resends messages when a remote node doesn't... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
"""
Example of a 2 dimensional root finidng problem (Rosenbrock).
Parameters taken from GNU GSL Manual
"""
from symneqsys import SimpleNEQSys, Problem
from symneqsys.gsl import GSL_Solver
class RosenbrockSys(SimpleNEQSys)... |
"""
A trivial container manager.
"""
from commissaire.bus import ContainerManagerError
from commissaire.containermgr import ContainerManagerBase
class TrivialContainerManager(ContainerManagerBase): # pragma: no cover
"""
Trivial, memory-only container manager to facilitate end-to-end testing.
"""
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import connection
from scrapy import signals
from scrapy.exceptions import DontCloseSpider
from scrapy.spider import Spider
class RedisMixin(object):
"""Mixin class to implement reading urls from a redis queue."""
redis_key = None # use default '<spider>:start_... |
"Misc. utility functions/classes for admin documentation generator."
import re
from email.errors import HeaderParseError
from email.parser import HeaderParser
from django.urls import reverse
from django.utils.safestring import mark_safe
try:
import docutils.core
import docutils.nodes
import docutils.pars... |
import mock
import dash_core_components as dcc
import dash_html_components as html # noqa: F401
import dash
from dash.development.base_component import ComponentRegistry
_monkey_patched_js_dist = [
{
"external_url": "https://external_javascript.js",
"relative_package_path": "external_javascript.js... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Unit test module."""
import unittest
__author__ = "Loic Jaquemet"
__copyright__ = "Copyright (C) 2012 Loic Jaquemet"
__email__ = "<EMAIL>"
__license__ = "GPL"
__maintainer__ = "Loic Jaquemet"
__status__ = "Production"
class SrcTests(unittest.TestCase):
def tear... |
# import argparse
import glob
import os
import shutil
import json
from subprocess import check_output
from subprocess import PIPE
from datetime import datetime
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.dirname(THIS_DIR)
def report_vcs(path):
"""
Returns `git` or `hg` depen... |
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'LatestNodetypesPlugin.metatype'
db.delete_column('cmsplugin_latestnodetypesplugin', 'metatype_id')
# Deleting field 'Lat... |
'''
@author Ewan Higgs (Universiteit Gent)
'''
import unittest
import pytest
import hod.commands.command as hcc
class HodCommandsCommandTestCase(unittest.TestCase):
'''Test Command functions'''
@pytest.mark.xfail
def test_command_breathing(self):
'''test command can actually be created.'''
... |
# -*- coding: utf-8 -*-
"""
Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
This file is part of fiware-pep-steelskin
fiware-pep-steelskin is free software: you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, eithe... |
import logging
from globus_sdk.authorizers.base import GlobusAuthorizer
from globus_sdk.utils.string_hashing import sha256_string
logger = logging.getLogger(__name__)
class AccessTokenAuthorizer(GlobusAuthorizer):
"""
Implements Authorization using a single Access Token with no Refresh
Tokens. This is s... |
import pytest
from flex.exceptions import ValidationError
from flex.error_messages import MESSAGES
from flex.constants import EMPTY
from tests.utils import (
generate_validator_from_schema,
assert_error_message_equal,
)
#
# minLength validation tests
#
@pytest.mark.parametrize(
'when',
(
'20... |
import pytest
import pytz
from datetime import datetime
from osf_tests.factories import PreprintFactory, UserFactory, ProjectFactory, TagFactory
from osf.models import Tag
from scripts.normalize_user_tags import normalize_source_tags, add_claimed_tags, add_osf_provider_tags, add_prereg_campaign_tags, PROVIDER_SOURCE_T... |
import os
import sys
import time
import exceptions
import copy
import logging
from threading import Thread, Lock
import uuid
try:
import cPickle as pickle
except:
import pickle
'''
@author: msune,lbergesio,omoya,cbermudo,CarolinaFernandez
@organization: i2CAT, OFELIA FP7
PolicyEngine RuleTable class
... |
import warnings
from pykickstart.version import FC3, FC6, F18
from pykickstart.base import KickstartCommand
from pykickstart.errors import KickstartParseError, KickstartDeprecationWarning
from pykickstart.options import KSOptionParser, commaSplit
from pykickstart.i18n import _
class FC3_Timezone(KickstartCommand):
... |
"""
==================================================
Plot different SVM classifiers in the iris dataset
==================================================
Comparison of different linear SVM classifiers on a 2D projection of the iris
dataset. We only consider the first 2 features of this dataset:
- Sepal length
- Se... |
import math
from PyQt5 import Qt
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets
class SpinningWaitClock(QtWidgets.QWidget):
# Spinning wait clock, inspired by
# https://wiki.python.org/moin/PyQt/A%20full%20widget%20waiting%20indicator
def __init__(self):
super().__... |
import os
import re
import cookielib
import urllib2
import urllib
import httplib, StringIO
from twitter_rec.debug import VerboseHTTPHandler
from twitter_rec.util import logger
from twitter_rec.util import unique_order
from bs4 import BeautifulSoup as BS
import simplejson as json
URL = "https://twitter.com"
class Se... |
from pyspark import since
from pyspark.rdd import ignore_unicode_prefix
from pyspark.sql.column import Column, _to_seq, _to_java_column, _create_column_from_literal
from pyspark.sql.dataframe import DataFrame
from pyspark.sql.types import *
__all__ = ["GroupedData"]
def dfapi(f):
def _api(self):
name = f... |
import pytest
import pandas as pd
@pytest.fixture(params=['Home',
'Away'])
def computed_actual_team_stats(request, game):
matchups = game.Matchups
boxscores = [matchup.Boxscore for matchup in matchups]
if request.param == 'Home':
homeSplitBox = [b.HomeTeamStats for b in box... |
################################################################################
# GangaND280 Project.
# Dima Vavilov
# Created 27/01/2016
################################################################################
"""@package ND280Control
Ganga module to execute RunAtmPitSim.exe from the atmPitSim package.
"""
f... |
""" Import required built in python modules,
method subclasses for different ciphering methods and
subclass for asking and checking user input """
import os
import datetime
from user_input import UserInput
from file_edit import FileEdit
from search_record import Search
from edit import RecordChange
# clear screen f... |
# 3rd party
import yaml
# local
import model
# order matters, copied from the end of the binary fancy.exe (v2.9)
FANCY_PIECES = [
'15', '16', '24', '25', '35', '37', 'al', 'am', 'an', 'ao', 'ar',
'b', 'bh', 'bk', 'bl', 'bp', 'br', 'bs', 'bt', 'bu', 'c', 'ca', 'cg',
'ch', 'cr', 'ct', 'cy', 'da', ... |
from tierror import TiError
class ParseError(TiError):
pass
def raise_parse_error(msg):
raise ParseError(msg)
# lex #####################################################
from simpletable import enum
# ignore spaces and comma
t_ignore = ' \t\r'
LPAREN = 'LPAREN'
RPAREN = 'RPAREN'
LBRACK = 'LBRACK'
RBRACK... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import re
import textwrap
import types
from units.compat import unittest
from units.compat.mock import MagicMock
from ansible.plugins.callback import CallbackBase
class TestCallback(unittest.TestCase):
# FIXME: ... |
#!/usr/bin/env python2.6
# coding: utf-8
import sys
import operator
import re
import types
from simpleparse import generator
from mx.TextTools import TextTools
from pprint import pprint
def checkerattr( *args ):
def setcheckerattr( func ):
setattr( func, 'type', ... |
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import numpy as np
import os.path as op
import util
import yt
import MPI_taskpull2
import logging
logging.getLogger('yt').setLevel(logging.ERROR)
# Scan for files
dirs = ['/home/ychen/data/0only_0529_h1/',\
'/hom... |
# -*- encoding: utf-8 -*-
# autor: Filip Varga
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim, vmodl
from time import sleep, time
from atexit import register
import ssl
def get_content(username, password, host):
s = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
s.verify_mode = ssl.CERT_NONE
... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Tier.newsletter'
db.delete_column('mirocommunity_saas_tier', 'newsletter')
def backw... |
from __future__ import absolute_import
from st2common.util import driver_loader
__all__ = ["BACKENDS_NAMESPACE", "get_available_backends", "get_backend_driver"]
BACKENDS_NAMESPACE = "st2common.runners.runner"
def get_available_backends():
return driver_loader.get_available_backends(namespace=BACKENDS_NAMESPACE... |
#!/usr/bin/env python3
import sys
from collections import OrderedDict
def emit(s):
sys.stdout.write(s)
def get_line(f):
line = f.readline()
return line
def get_file():
try:
fn = sys.argv[1]
f = open(fn, "r")
except:
exit("aborting, can't open {}".format(fn))
return f
def cancel_... |
# -*- coding: utf-8 -*-
from datetime import datetime
from elan.journal import _
from elan.journal.adapters import IJournalEntryContainer
from elan.journal.adapters import JournalEntry
from elan.journal.browser.base import BaseView
from plone import api
from plone.protect.interfaces import IDisableCSRFProtection
from P... |
from unittest import TestCase
from os import popen
from random import shuffle
from seecr.zulutime import ZuluTime, TimeError, UTC, Local
from seecr.zulutime._zulutime import _ZULU_FRACTION_REMOVAL_RE, _CEST, _TIMEDELTA_RE
# TODO:
# - Use python-aniso8601 for _parseZulutimeFormat (maybe formats too);
# since it... |
#!/usr/bin/env python
# Shine.Configuration.Configuration test suite
# Written by A. Degremont 2010-11-21
"""Unit test for Configuration"""
import unittest
from Utils import setup_tempdirs, clean_tempdirs, makeTempFile
from Shine.Configuration.Configuration import Configuration
from Shine.Configuration.Exceptions i... |
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", path_list=[
[TestAction.create_mini_vm, 'vm1', ],
[TestAction.reboot_vm, 'vm1'],
[TestAction.create_vm_backup, 'vm1', 'vm1-backup1'],
[TestAction.create_mini_vm... |
import datetime
from datetime import timedelta
from django.core.management.base import BaseCommand, CommandError
from django.db import models
from django.contrib.sites.models import Site
from django.conf import settings
from django.contrib.auth.models import User
from django.db.models import Q
from timeslot.models imp... |
# -*- coding: utf-8 -*-
from gettext import gettext as _
NAME = _('Saint Vincent and the Grenadines')
STATES = [
(_('Saint David'), 254, 176, 173, 60),
(_('Carlotte'), 253, 293, 271, 80),
(_('Saint Andrew'), 252, 112, 409, 30),
(_('Saint Patrick'), 251, 106, 317, 20),
(_('Saint George'), 250, 197... |
"""
Utilities for writing and reading files compatible with Fortran
"""
import re
def f2s(f):
"""
Format a string containing a float
"""
s = ""
if f >= 0.0:
s += " "
return s + "%1.9E" % f
class ChunkOutput:
"""
This outputs values in lines, inserting
newlines when need... |
import logging
import os
from translate.misc.lru import LRUCachingDict
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.functional import cached_property
fro... |
from tests import test
from cloudferrylib.os.storage import cinder_db
class CinderVolumeTestCase(test.TestCase):
def test_has_uuid_attribute(self):
v = cinder_db.CinderVolume()
self.assertTrue(hasattr(v, "id"))
def test_has_display_name_attribute(self):
v = cinder_db.CinderVolume()
... |
import os
import time
import logging
from ..logger import Logger
class FileLogger(Logger):
"""
Bucket class to save crash information to disk.
"""
BUCKET_ID = 'quokka_{}'.format(time.strftime('%a_%b_%d_%H-%M-%S_%Y'))
def __init__(self, **kwargs):
super(FileLogger, self).__init__()
... |
try:
from config import icon_path, bin_path, license_path, locale_path
except ImportError:
icon_path, bin_path, license_path, locale_path = None, None, None, None
import os, sys
def find_root(path=None):
p = path or os.getcwd()
while not os.path.isdir(os.path.join(p, ".hg")):
oldp = p
... |
"""
Utility collections or "bricks".
:module: watchdog.utils.bricks
:author: <EMAIL> (Yesudeep Mangalapilly)
:author: <EMAIL> (Lukáš Lalinský)
:author: <EMAIL> (Raymond Hettinger)
Classes
=======
.. autoclass:: OrderedSetQueue
:members:
:show-inheritance:
:inherited-members:
.. autoclass:: OrderedSet
"""
... |
import os
import time
from threading import Thread
from yowsup.stacks import YowStackBuilder
from yowsup.layers.auth import AuthError
from yowsup.layers import YowLayerEvent
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.network import YowNetworkLayer
from yowsup.common import YowCon... |
import os
import sh
from molecule import logger
from molecule import util
from molecule.verifier.lint import base
LOG = logger.get_logger(__name__)
class Flake8(base.Base):
"""
`Flake8`_ is the default verifier linter.
`Flake8`_ is a linter for python files.
Additional options can be passed to `f... |
import sys
from copy import deepcopy
from json import loads
from datetime import datetime, timedelta, tzinfo
from subprocess import Popen
from subprocess import PIPE
from signal import SIGTSTP, SIGSTOP, SIGUSR1, SIG_IGN, signal
from tempfile import NamedTemporaryFile
from threading import Thread
from time import time
... |
"""Stochastic gradient estimators.
These functions are meant to be used in conjuction with `StochasticTensor`
(`loss_fn` parameter) and `surrogate_loss`.
See Gradient Estimation Using Stochastic Computation Graphs
(http://arxiv.org/abs/1506.05254) by Schulman et al., eq. 1 and section 4, for
mathematical details.
##... |
#!/usr/bin/env python3
from sys import exit
from test.http_test import HTTPTest
from misc.wget_file import WgetFile
"""
This test ensures that Wget stores the cookie even in the event of a
401 Unauthorized Response
"""
############# File Definitions ###############################################
File1 = """Al... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 10 14:44:23 2017
@author: paras
"""
import csv
import numpy as np
spamReader = csv.reader(open('../out/results_n_1000_k_[5].csv', newline=''), delimiter=',')
next(spamReader,None)
#row1 = next(spamReader)
#print (row1[0])
n=1000#int(float(row1[0]))
#===================... |
from keystoneclient import exceptions
class ServiceCatalog(object):
"""Helper methods for dealing with a Keystone Service Catalog."""
@classmethod
def factory(cls, resource_dict, token=None, region_name=None):
"""Create ServiceCatalog object given a auth token."""
if ServiceCatalogV3.is_v... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from FloodFill import StripLineEnd, ReadField, PrintField
from FloodFill import emptyMarker, filledMarker, specialMarker, EscapeMarker
import numpy as np
import os
import copy
NumTrys = 0
InstanceCount = 0
#Debug = False
def inField( Field, rowNumber, columnNumber ):
LeftBo... |
from __future__ import unicode_literals, division, absolute_import, print_function
from compatibility_utils import unquoteurl
from unipath import pathof
import sys, os
SPECIAL_HANDLING_TAGS = {
'?xml' : ('xmlheader', -1),
'!--' : ('comment', -3),
'!DOCTYPE' : ('doctype', -1),
}
SPECIAL_HANDLING... |
import threading
import time
from rgbmatrix import graphics
from rgbmatrix import RGBMatrix
class Display(threading.Thread):
def __init__(self, weather, dimmer):
threading.Thread.__init__(self)
self.setDaemon(True)
self._weather = weather
self._dimmer = dimmer
# Configure... |
from __future__ import division
import os
import os.path
from Bio import SeqIO
import micca.seq
def merge(input_fns, output_fn, sep='.', fmt="fastq"):
with open(output_fn,'wb') as output_handle:
for input_fn in input_fns:
micca.seq.append(input_fn, output_handle, fmt=fmt, sep=sep) |
"""
The ResFi Configuration File
Copyright (C) 2016 Sven Zehl, Anatolij Zubow, Michael Doering, Adam Wolisz
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 th... |
#!/usr/bin/env python
# coding=utf-8
# -*- coding: utf-8 -*-
# 各种排序算法
# author zcl
# date:2016/1/11
#选择排序
def select_sort(sort_array,asc=True):
for i, elem in enumerate(sort_array):
for j, elem in enumerate(sort_array[i:len(sort_array)]):
if asc:
if sort_array[i] > sort_array[j +... |
from __future__ import unicode_literals, division
import time
from curtsies import FullscreenWindow, Input, FSArray
from curtsies.fmtfuncs import red, bold, green, on_blue, yellow, on_red
import curtsies.events
class Frame(curtsies.events.ScheduledEvent):
pass
class World(object):
def __init__(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.