content string |
|---|
from __future__ import unicode_literals
from django.db import models
from django.test import TestCase
from rest_framework import serializers
from .models import OneToOneTarget
class OneToOneSource(models.Model):
name = models.CharField(max_length=100)
target = models.OneToOneField(OneToOneTarget, related_nam... |
import unittest
from unittest import mock
from unittest.mock import patch
import pytest
import requests
from airflow.exceptions import AirflowException, AirflowSensorTimeout
from airflow.models import TaskInstance
from airflow.models.dag import DAG
from airflow.providers.http.operators.http import SimpleHttpOperator
... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j F Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = 'j F Y H:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'Y-m-d... |
import os
from oslo_log import log as logging
from trove.common.i18n import _
from trove.common import instance as rd_instance
from trove.common.notification import EndNotification
from trove.guestagent import backup
from trove.guestagent.datastore.experimental.couchbase import service
from trove.guestagent.datastore... |
import os
import sys
import json
import fnmatch
TEST_DIR = "/webvtt/"
CATEGORIES_FILE = "../categories.json"
class Test:
def __init__(self, file, name, status, message):
self.file = file
self.name = name
self.status = status
self.message = message
self.passed = status == 'P... |
import sys
from osgeo import gdal
from osgeo import ogr
from osgeo import osr
def Usage():
print("""
gdal_polygonize [-8] [-nomask] [-mask filename] raster_file [-b band|mask]
[-q] [-f ogr_format] out_file [layer] [fieldname]
""")
sys.exit(1)
# ===============================================... |
'''
GCE external inventory script
=================================
Generates inventory that Ansible can understand by making API requests
Google Compute Engine via the libcloud library. Full install/configuration
instructions for the gce* modules can be found in the comments of
ansible/test/gce_tests.py.
When run a... |
"""
Interface monitor.
Watching packet received on this interface and parse VRRP packet.
VRRPManager creates/deletes instances of interface monitor dynamically.
"""
from ryu.base import app_manager
from ryu.controller import handler
from ryu.lib.packet import packet
from ryu.lib.packet import vlan
from ryu.lib.packet... |
import pkg_resources
# legacy imports
from MaKaC.services.implementation.base import ServiceBase
from MaKaC.plugins.base import PluginsHolder
# indico imports
from indico.web.handlers import RHHtdocs
from indico.ext.importer.helpers import ImporterHelper
import indico.ext.importer
class RHImporterHtdocs(RHHtdocs):
... |
import unittest2
class TestLabelValueType(unittest2.TestCase):
def _getTargetClass(self):
from gcloud.monitoring.label import LabelValueType
return LabelValueType
def test_one(self):
self.assertTrue(hasattr(self._getTargetClass(), 'STRING'))
def test_names(self):
for nam... |
import math
import mock
from neutron.common import constants as const
from neutron import context
from neutron.extensions import securitygroup as ext_sg
from neutron import manager
from neutron.tests import tools
from neutron.tests.unit.agent import test_securitygroups_rpc as test_sg_rpc
from neutron.tests.unit.api.v2... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2010 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# stdlib
import logging
# Zato
from zato.admin.web.forms import ChangePasswordFo... |
from openquake.hazardlib.gsim.chiou_youngs_2014 import (
ChiouYoungs2014, ChiouYoungs2014PEER, ChiouYoungs2014NearFaultEffect)
from openquake.hazardlib.tests.gsim.utils import BaseGSIMTestCase
from openquake.hazardlib.calc import ground_motion_fields
from openquake.hazardlib import const
from openquake.hazardlib.i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_homepage(apps, schema_editor):
# Get models
ContentType = apps.get_model('contenttypes.ContentType')
Page = apps.get_model('wagtailcore.Page')
Site = apps.get_model('wagtailcore.Site')
Home... |
from __future__ import absolute_import, print_function
from pyximport import pyximport; pyximport.install(reload_support=True)
import os, sys
import time, shutil
import tempfile
def make_tempdir():
tempdir = os.path.join(tempfile.gettempdir(), "pyrex_temp")
if os.path.exists(tempdir):
remove_tempdir... |
"""Unit tests for contextlib.py, and other context managers."""
import sys
import tempfile
import unittest
from contextlib import * # Tests __all__
from test import test_support
try:
import threading
except ImportError:
threading = None
class ContextManagerTestCase(unittest.TestCase):
def test_contextm... |
"""Implementation of SQLAlchemy backend."""
import uuid
from sqlalchemy.sql.expression import asc
from sqlalchemy.sql.expression import literal_column
import nova.context
from nova.db.sqlalchemy import api as sqlalchemy_api
from nova import exception
from nova.openstack.common.db import exception as db_exc
from nova... |
"""
====================
Breadth-first search
====================
Basic algorithms for breadth-first searching.
"""
__author__ = """\n""".join(['Aric Hagberg <<EMAIL>>'])
__all__ = ['bfs_edges', 'bfs_tree',
'bfs_predecessors', 'bfs_successors']
import networkx as nx
from collections import defaultdict
... |
#A set of model vector visualization tools.
#Each visualizer should be a subclass of VisVector, which is an abstract class.
#If a visualizer is added, it should be added to the if statement in
#VisVectorFactory. Each new class should follow the nameing convention
#XVisVector, where X is the string that gets passed to ... |
from Muon.GUI.Common.home_tab.home_tab_presenter import HomeTabSubWidget
class HomeRunInfoWidgetPresenter(HomeTabSubWidget):
def __init__(self, view, model):
self._view = view
self._model = model
def show(self):
self._view.show()
def update_view_from_model(self):
self._v... |
"""Support for Minut Point."""
import asyncio
import logging
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_TOKEN, CONF_WEBHOOK_ID
from homeassistant.helpers import config_validation as cv
from homeassistant.h... |
import cgi
import datetime
import os
import shutil
import tempfile
try:
import json
except ImportError:
import simplejson as json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
import ansible.module_utils.six as six
from ansible.module_utils._tex... |
from __future__ import unicode_literals
from django import http
from django.apps import apps
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.requests import RequestSite
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext as _
def sh... |
import logging
import unittest2 as unittest
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.test.finder import Finder
class FinderTest(unittest.TestCase):
def setUp(self):
files = {
'/foo/bar/baz.py':... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
import time
class crm_phonecall2phonecall(osv.osv_memory):
_name = 'crm.phonecall2phonecall'
_description = 'Phonecall To Phonecall'
_columns = {
'name' : fields.char('Call summary', required=True, select=1),
'user_... |
#!/usr/bin/env python2
import sys
# check input parameters, generate INDATA list
# code placed here to avoid unneccesary vtk loading
if len(sys.argv) == 1 :
sys.stderr.write('Using standard data set, to use other data:\n'.format(sys.argv[0]))
sys.stderr.write('Usage: {0} <pdb file> <connection file> |<protna... |
"""Support for interface with a Sony Bravia TV."""
import ipaddress
import logging
from getmac import get_mac_address
import voluptuous as vol
from homeassistant.components.media_player import MediaPlayerDevice, PLATFORM_SCHEMA
from homeassistant.components.media_player.const import (
SUPPORT_NEXT_TRACK,
SUPP... |
import dbus
from dbus.mainloop.glib import DBusGMainLoop as DBusMainLoop
from json import dumps, loads
from calendar import timegm
from hamster.lib import datetime as dt
from hamster.lib.fact import Fact
"""D-Bus communication utilities."""
# file layout: functions sorted in alphabetical order,
# not taking into ac... |
# -*- coding: utf-8 -*-
import os # noqa
from dateutil.parser import parse as dateparse
from flask import request
from website import models
from website.project.decorators import must_be_valid_project
from website.project.decorators import must_not_be_registration
from website.project.decorators import must_have_a... |
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from config import config # 导入配置
from flask_login import LoginManager
from flask_pagedown import PageDown
# 初始化flask-login
login_manager = LoginManager()
#... |
"""
node for 2 conv's paired together, which allows more flexible combinations of
filter size and padding - specifically even filter sizes can have "same"
padding
"""
import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
import canopy
fX = theano.config.floatX
@treeano... |
"""Tests for binary operators on subtypes of built-in types."""
import unittest
from test import test_support
def gcd(a, b):
"""Greatest common divisor using Euclid's algorithm."""
while a:
a, b = b%a, a
return b
def isint(x):
"""Test whether an object is an instance of int or long."""
re... |
import numpy as np
class WordClusters(object):
def __init__(self, vocab, clusters):
self.vocab = vocab
self.clusters = clusters
def ix(self, word):
"""
Returns the index on self.vocab and self.clusters for 'word'
"""
temp = np.where(self.vocab == word)[0]
... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.0'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ce import get_config, load_config, ce_argument_spec, run_commands
class SnmpTraps(object):
""" ... |
"""
media-storage : compression
===========================
Offers efficient handlers for compressing and decompressing data, using
file-like objects (often tempfiles).
This module is shared by every Python facet of the media-storage project and
changes to one instance should be reflected in all.
Usage
-----
(De)co... |
#!/usr/bin/python
import gearman
def check_request_status(job_request):
if job_request.complete:
print "Job %s finished! Result: %s - %s" % (job_request.job.unique, job_request.state, job_request.result)
elif job_request.timed_out:
print "Job %s timed out!" % job_request.unique
elif job_r... |
from __future__ import absolute_import
import logging
import warnings
from pip.basecommand import Command
from pip.exceptions import CommandError
from pip.index import PackageFinder
from pip.utils import (
get_installed_distributions, dist_is_editable)
from pip.utils.deprecation import RemovedInPip10Warning
from ... |
#!/usr/bin/env python3
# -*- mode: python; indent-tabs-mode: nil; tab-width: 2 -*-
"""
mct_to_mfcdump.py - Converts a dump from MIFARE Classic Tool to mfoc/mfcuk .mfc
format (raw data)
Copyright 2015-2018 Michael Farrell <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms... |
import numpy as np
from ..core import GP
from ..models import GPLVM
from ..mappings import *
class BCGPLVM(GPLVM):
"""
Back constrained Gaussian Process Latent Variable Model
:param Y: observed data
:type Y: np.ndarray
:param input_dim: latent dimensionality
:type input_dim: int
:param in... |
import mock
import unittest
import a10_openstack_lib.resources.a10_certificate as a10_certificate
import a10_openstack_lib.resources.a10_device_instance as a10_device_instance
import a10_openstack_lib.resources.a10_scaling_group as a10_scaling_group
import a10_openstack_lib.resources.template as template
class TestR... |
"""Tests to ensure that the html5lib tree builder generates good trees."""
import warnings
try:
from bs4.builder import HTML5TreeBuilder
HTML5LIB_PRESENT = True
except ImportError, e:
HTML5LIB_PRESENT = False
from bs4.element import SoupStrainer
from bs4.testing import (
HTML5TreeBuilderSmokeTest,
... |
from openerp.osv import fields,osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
# Overloaded stock_picking to manage carriers :
class stock_picking(osv.osv):
_inherit = 'stock.picking'
def _cal_weight(self, cr, uid, ids, name, args, context=None):
res = {}
... |
#!/usr/bin/python
# TODO: issues with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python
from participantCollection import ParticipantCollection
import string
import re
import datetime
import pyperclip
# Edit Me!
# Remember, this is during signup, so current month is not March, it'... |
"""Presubmit script for Chromium JS resources.
See chrome/browser/resources/PRESUBMIT.py
"""
class JSChecker(object):
def __init__(self, input_api, output_api, file_filter=None):
self.input_api = input_api
self.output_api = output_api
self.file_filter = file_filter
def RegexCheck(self, line_number, l... |
from __future__ import (absolute_import, division, print_function)
import json
from copy import deepcopy
import pytest
from ansible.module_utils._text import to_bytes
from ansible.module_utils import basic
from ansible.module_utils.ec2 import HAS_BOTO3
if not HAS_BOTO3:
pytestmark = pytest.mark.skip("test_elb_a... |
""" Routines for manipulating RFC2047 encoded words.
This is currently a package-private API, but will be considered for promotion
to a public API if there is demand.
"""
# An ecoded word looks like this:
#
# =?charset[*lang]?cte?encoded_string?=
#
# for more information about charset see the charset module. ... |
"""
Load pp, plot and save
"""
import os, sys
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from matplotlib import rc
from matplotlib.font_manager import FontProperties
from matplotlib import rcParams
from mpl_toolkits.basemap import Basemap
rc('font', family = '... |
""" Cisco_IOS_XE_environment_oper
This module contains a collection of YANG definitions for
monitoring Environment of a Network Element.Copyright (c) 2016\-2017 by Cisco Systems, Inc.All rights reserved.
"""
import re
import collections
from enum import Enum
from ydk.types import Empty, YList, YLeafList, DELETE,... |
from __future__ import print_function
import time
import re
from six.moves.urllib.parse import quote
import requests
import logging
from tweepy.error import TweepError, RateLimitError, is_rate_limit_error_message
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.co... |
"""
Utils for video bumper
"""
import copy
import json
import pytz
import logging
from collections import OrderedDict
from datetime import datetime, timedelta
from django.conf import settings
from .video_utils import set_query_parameter
try:
import edxval.api as edxval_api
except ImportError:
edxval_api = No... |
from model.group import Group
from timeit import timeit
from model.group_address import Address_data
from test.test_string_value import merge_emails
from test.test_string_value import merge_phones_like_on_homepage
#def test_group_list(app, db):
# print(timeit(lambda: app.group.get_group_list(), number=1))
# def ... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2017 SML
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.hdl
~~~~~~~~~~~~~~~~~~~
Lexers for hardware descriptor languages.
:copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, bygroups, include, using, t... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import nipype.pipeline.engine as pe
import nipype.interfaces.fsl as fsl
import nipype.interfaces.freesurfer as fs
import nipype.interfaces.meshfix as mf
import nipype.interfaces.io as nio
import nipype.in... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
smuggle_url,
update_url_query,
)
class FoxSportsIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?foxsports\.com/(?:[^/]+/)*(?P<id>[^/]+)'
_TEST = {
'url': 'http://www.foxsports.com/tennessee/v... |
_debug = 0
eDetecting = 0
eFoundIt = 1
eNotMe = 2
eStart = 0
eError = 1
eItsMe = 2
SHORTCUT_THRESHOLD = 0.95 |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_str,
)
from ..utils import (
int_or_none,
ExtractorError,
)
class VubeIE(InfoExtractor):
IE_NAME = 'vube'
IE_DESC = 'Vube.com'
_VALID_URL = r'https?://vube\.com/(?:[^/]+/)+(?P<id... |
{
'name': 'Bill Time on Tasks',
'version': '1.0',
'category': 'Project Management',
'description': """
Synchronization of project task work entries with timesheet entries.
====================================================================
This module lets you transfer the entries under tasks defined ... |
from taiga.base.api.permissions import (TaigaResourcePermission, HasProjectPerm,
IsProjectOwner, PermissionComponent,
AllowAny, IsAuthenticated, IsSuperUser)
class IssuePermission(TaigaResourcePermission):
enought_perms = IsProjectOwn... |
"""Tests for the SeedStream class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.distributions.python.ops import seed_stream
from tensorflow.python.platform import test
class SeedStreamTest(test.TestCase):
def assertAllUniq... |
"""
Storing files according to a custom storage system
``FileField`` and its variations can take a ``storage`` argument to specify how
and where files should be stored.
"""
import random
import tempfile
from django.core.files.storage import FileSystemStorage
from django.db import models
class CustomValidNameStorag... |
"""Sparse Dtype"""
import re
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type
import warnings
import numpy as np
from pandas._typing import Dtype, DtypeObj
from pandas.errors import PerformanceWarning
from pandas.core.dtypes.base import ExtensionDtype, register_extension_dtype
from pandas.core.dty... |
from __future__ import unicode_literals
import threading
import time
from multiple_database.routers import TestRouter
from django.db import DatabaseError, connection, router, transaction
from django.test import (
TransactionTestCase, override_settings, skipIfDBFeature,
skipUnlessDBFeature,
)
from .models im... |
import random
lane_num = 2
lane = [[], []]
max_car_num = 10000
road_len = 1000
h = 6
p_b = 0.94
p_0 = 0.5
p_d = 0.1
v_max = [6, 10]
gap = 7
p_car = 1
p_crash = 0
time_period = 200
class Car:
car_cnt = 0
def __init__(self, v = 1, lane = 1):
self.size = 1
if random.random() < 0.1:
... |
#!/usr/bin/env python
""" Python Character Mapping Codec for ROT13.
See http://ucsub.colorado.edu/~kominek/rot13/ for details.
Written by Marc-Andre Lemburg (<EMAIL>).
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return ... |
"""Test module for the noddy examples
Noddy 1:
>>> import noddy
>>> n1 = noddy.Noddy()
>>> n2 = noddy.Noddy()
>>> del n1
>>> del n2
Noddy 2
>>> import noddy2
>>> n1 = noddy2.Noddy('jim', 'fulton', 42)
>>> n1.first
'jim'
>>> n1.last
'fulton'
>>> n1.number
42
>>> n1.name()
'jim fulton'
>>> n1.first = 'will'
>>> n1.n... |
import os
import menu_main
import fr_functions
import cfg
# =================================
# SERVICES MENU
# =================================
def view_services():
os.system('clear')
print("\n\nService".ljust(40) + " Price")
print("="*60)
for n in cfg.SERVICES:
print("| " + str(n).... |
#! /usr/bin/python
# -*- encoding: utf-8 -*-
import sys
import os
import commands
import datetime
def post_dingtalk(msg):
print('sending dingtalk message.....')
os.system("curl %s -H 'Content-Type: application/json' \
-d '{\"msgtype\": \"text\",\"text\": {\"content\": \" %s \"}}'"%(dingtalk_url, msg))... |
"""defines Service as abstract interface"""
# -*- python -*-
import random, socket
class Service:
""" the service base class that all the
other services inherit from. """
def __init__(self, serviceDesc, workDirs):
self.serviceDesc = serviceDesc
self.workDirs = workDirs
def getName(self):
return ... |
# -*- coding: utf-8 -*-
import copy
import datetime
import mock
import pytest
import elastalert.alerts
import elastalert.ruletypes
from elastalert.config import get_file_paths
from elastalert.config import load_configuration
from elastalert.config import load_options
from elastalert.config import load_rules
from elas... |
#!/usr/bin/env python3
"""
Copyright 2017 Andris Zbitkovskis
Licensed 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by a... |
from openerp.osv import osv
class account_unreconcile(osv.osv_memory):
_name = "account.unreconcile"
_description = "Account Unreconcile"
def trans_unrec(self, cr, uid, ids, context=None):
obj_move_line = self.pool.get('account.move.line')
if context is None:
context = {}
... |
from django.views.generic import TemplateView, DetailView
from django.utils.translation import ugettext as _
from common.permissions import PermissionsMixin, IsValidUser
from .models import Ticket
from . import mixins
class TicketListView(PermissionsMixin, TemplateView):
template_name = 'tickets/ticket_list.html... |
from __future__ import unicode_literals
import os
from optparse import make_option
from django.core.management.base import LabelCommand
from django.utils.encoding import smart_text
from django.contrib.staticfiles import finders
class Command(LabelCommand):
help = "Finds the absolute paths for the given static fi... |
import logging
import sys
import time
class BuildFormatter(logging.Formatter):
def __init__(self):
self._fmt = "[%(asctime)s] %(message)s"
self.datefmt = None
self.starttime = time.time()
def converter(self, recordtime):
"""
This returns a timestamp relatively to the time when we started
the build.
... |
import res_config
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""Unittests for log_console.py"""
import unittest
import wx
import launcher
class LogConsoleTest(unittest.TestCase):
def ConfirmedShow(self, doshow):
"""Dropped into the Console so we can insure Show(False) has been called."""
if doshow == False:
self.did_hide = True
def ConfirmedDestroy(self):
... |
__author__ = 'Michael Isik'
from pybrain.supervised.evolino.gpopulation import Population, SimplePopulation
from pybrain.supervised.evolino.gfilter import Randomization
from pybrain.supervised.evolino.individual import EvolinoIndividual, EvolinoSubIndividual
from pybrain.tools.kwargsprocessor import KWArgsProcessor
... |
import cPickle as pickle
import numpy as np
import os
from scipy.misc import imread
def load_CIFAR_batch(filename):
""" load single batch of cifar """
with open(filename, 'rb') as f:
datadict = pickle.load(f)
X = datadict['data']
Y = datadict['labels']
X = X.reshape(10000, 3, 3... |
from __future__ import unicode_literals
import frappe
import json
import copy
from frappe import throw, _
from frappe.utils import flt, cint
from frappe.model.document import Document
class MultiplePricingRuleConflict(frappe.ValidationError): pass
class PricingRule(Document):
def validate(self):
self.validate_mand... |
"""
aminator.plugins.provisioner.apt
================================
basic apt provisioner
"""
import logging
import os
from aminator.exceptions import ProvisionException
from aminator.plugins.provisioner.base import BaseProvisionerPlugin
from aminator.util import retry
from aminator.util.linux import monitor_command... |
class Solution:
# @param words, a list of strings
# @param L, an integer
# @return a list of strings
def fullJustify(self, words, L):
result = []
length = len(words)
i = 0
c = 0
sublength =0
sub = []
while i < length:
lc = len(words[i... |
"""
Django Views for service status app
"""
import json
import time
from django.http import HttpResponse
from dogapi import dog_stats_api
from service_status import tasks
from djcelery import celery
from celery.exceptions import TimeoutError
def index(_):
"""
An empty view
"""
return HttpResponse(... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_pagefile
version_added: "2.4"
short_description: Query or change pagefile configuration
description:
- Query current pagefile configuration... |
"""Extended file operations available in POSIX.
f = posixfile.open(filename, [mode, [bufsize]])
will create a new posixfile object
f = posixfile.fileopen(fileobject)
will create a posixfile object from a builtin file object
f.file()
will return the original builtin file object
f.dup()
... |
"""Unit test utilities for Google C++ Testing Framework."""
__author__ = '<EMAIL> (Zhanyong Wan)'
import atexit
import os
import shutil
import sys
import tempfile
import unittest
_test_module = unittest
# Suppresses the 'Import not at the top of the file' lint complaint.
# pylint: disable-msg=C6204
try:
import sub... |
"""Downloads items from the Chromium continuous archive."""
import os
import platform
import urllib
import util
CHROME_27_REVISION = '190466'
CHROME_28_REVISION = '198276'
_SITE = 'http://commondatastorage.googleapis.com'
class Site(object):
CONTINUOUS = _SITE + '/chromium-browser-continuous'
SNAPSHOT = _SITE... |
import types
import functools
from pip._vendor.requests.adapters import HTTPAdapter
from .controller import CacheController
from .cache import DictCache
from .filewrapper import CallbackFileWrapper
class CacheControlAdapter(HTTPAdapter):
invalidating_methods = set(['PUT', 'DELETE'])
def __init__(self, cach... |
Experiment(description='Trying to recreate old results using latest code',
data_dir='../data/radio/',
max_depth=4,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=2,
jitter_sd=0.1,
... |
"""
ACE parser
From wotsit.org and the SDK header (bitflags)
Partial study of a new block type (5) I've called "new_recovery", as its
syntax is very close to the former one (of type 2).
Status: can only read totally file and header blocks.
Author: Christophe Gisquet <<EMAIL>>
Creation date: 19 january 2006
"""
from... |
"""Base Command class, and related routines"""
import os
import socket
import sys
import tempfile
import traceback
import time
import optparse
from pip.log import logger
from pip.download import urlopen
from pip.exceptions import (BadCommand, InstallationError, UninstallationError,
Command... |
# -*- coding: utf-8 -*-
# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /
"""
Requests HTTP library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> ... |
from __future__ import unicode_literals
import unittest
import frappe
import frappe.defaults
from frappe.utils import flt, add_days, nowdate
from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt, make_purchase_invoice
class TestPurchaseOrder(unittest.TestCase):
def test_make_purchase_... |
"""
Classes implementing logic related to the analytical computation of the KL
divergence between :math:`q_\\phi(\\mathbf{z} \\mid \\mathbf{x})` and
:math:`p_\\theta(\\mathbf{z})` in the VAE framework
"""
__authors__ = "Vincent Dumoulin"
__copyright__ = "Copyright 2014, Universite de Montreal"
__credits__ = ["Vincent D... |
{
'name': 'Per Project Configurable Categorie on Issues',
'summary': 'Projects Issues can have an allowed category list',
'version': '8.0.0.1.0',
"category": "Project Management",
'description': """\
Adds to Issues the ability to limit selectable Categories to a Proeject's
specific list.
""",
'a... |
"""
=====================
SGD: Weighted samples
=====================
Plot decision function of a weighted dataset, where the size of points
is proportional to its weight.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
# we create 20 points
np.random.seed(0)
X ... |
import mock
from oslo_utils import uuidutils
from neutron.agent.l3 import legacy_router
from neutron.agent.linux import ip_lib
from neutron.common import constants as l3_constants
from neutron.tests import base
_uuid = uuidutils.generate_uuid
class BasicRouterTestCaseFramework(base.BaseTestCase):
def _create_ro... |
"""Cython.Distutils.build_ext
Implements a version of the Distutils 'build_ext' command, for
building Cython extension modules."""
# This module should be kept compatible with Python 2.3.
__revision__ = "$Id:$"
import sys
import os
import re
from distutils.core import Command
from distutils.errors import DistutilsP... |
#!/usr/bin/env python
from __future__ import print_function
import redis
import time
import signal
import argparse
import sys
import os
# if PAPARAZZI_SRC not set, then assume the tree containing this
# file is a reasonable substitute
PPRZ_SRC = os.getenv("PAPARAZZI_SRC", os.path.normpath(os.path.join(os.path.dirnam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.