content stringlengths 4 20k |
|---|
"""Import core names of TensorFlow.
Programs that want to build TensorFlow Ops and Graphs without having to import
the constructors and utilities individually can import this file:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
""... |
from unittest.mock import patch
import pytest
from pontoon.terminology.models import Term
from pontoon.test.factories import EntityFactory, TermFactory, TermTranslationFactory
@pytest.fixture
@patch("pontoon.terminology.models.update_terminology_project_stats")
def available_terms(_):
"""This fixture provides:
... |
# -*- coding: utf-8 -*-
import scrapy
import json
import re
from locations.items import GeojsonPointItem
REPLACES={
'Store hours:':'',
'</div><div>':';',
'<div>':';',
'</div>':';',
'PM':'pm',
'AM':'am',
'M':'Mo',
'W':'We',
'F':'Fr',
'SAT':'Sa',
'SUN':'Su',
'T':'Tu',
... |
import sys
import portage
portage._internal_caller = True
from portage import os
from portage.util._argparse import ArgumentParser
def command_recompose(args):
usage = "usage: recompose <binpkg_path> <metadata_dir>\n"
if len(args) != 2:
sys.stderr.write(usage)
sys.stderr.write("2 arguments are required, got %s... |
#=============================================================================
#
# Color Management
#
#=============================================================================
"""
Color Management
================
This system intends to equally support many different color representation
schemes. There are many... |
"""SCons.Tool.ar
Tool-specific initialization for ar (library archive).
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is hereby granted, fr... |
import codecs
import os
from setuptools import setup, find_packages
# Prevent spurious errors during `python setup.py test`, a la
# http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html:
try:
import multiprocessing
except ImportError:
pass
def read(fname):
fpath = os.path.join(os.path.dirname(__f... |
"""
Django settings for testapp project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... |
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from django.conf import settings
from django.core.exceptions import FieldError
from nopassword.models import LoginCode
from nopassword.utils import get_user_model
class NoPasswordBackend(object):
def authenticate(self, code=None, **credentials):
... |
from app.bot import BaseProcessor, BotProcessorFactory
from splitwise import Splitwise
from splitwise.expense import Expense
from splitwise.user import ExpenseUser
from splitwise.group import Group
from splitwise.debt import Debt
from datetime import datetime, timedelta
from botsplitwise import BotSplitwise
from botexc... |
"""
Network Analyst tools converted to Python
"""
import arcpy
import os
def closest_facility(network, rdv_name, facilities, incidents, table,
oneway_restriction=False):
"""
Execute the Closest Facility tool - Produce Closest Facility Layer
* facilities = destiny points
* inc... |
""" This module allows the user to place text in 3D at a location on the
scene.
Unlike the 'Text' module, this module positions text in 3D in the scene,
and in 2D on the screen. As a result the text resizes with the figure,
and can be masked by objects in the foreground.
"""
# Copyright (c) 2009, Enthought, Inc.
# Lic... |
# -*- coding: utf-8 -*-
#
# Validators Unit Tests
#
# To run this script use:
# python web2py.py -S eden -M -R applications/eden/tests/unit_tests/modules/s3/s3validators.py
#
import unittest
from gluon import current
from gluon.dal import Query
from s3.s3fields import *
# ==============================================... |
"""A hack to allow safe clearing of the cache in django.contrib.sites.
Since django.contrib.sites may not be thread-safe when there are
multiple instances of the application server, we're patching it with
a thread-safe structure and methods that use it underneath.
"""
import threading
from django.contrib.sites.models... |
"""ZConfig datatypes for <mailman> and <mailman-build> configuration keys."""
import os
import random
from string import (
ascii_letters,
digits,
)
__all__ = [
'configure_prefix',
'configure_siteowner',
]
EMPTY_STRING = ''
def configure_prefix(value):
"""Specify Mailman's configure's... |
import nose
import angr
import logging
l = logging.getLogger("angr.tests")
import os
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))
target_addrs = {
'i386': [ 0x080485C9 ],
'x86_64': [ 0x4006ed ],
'ppc': [ 0x1000060C ],
'armel': [ 0x85F0 ],
... |
"""
Python package for automating GUI manipulation on Windows
"""
from __future__ import absolute_import
__revision__ = "$Revision$"
__version__ = "0.5.0"
from . import findwindows
WindowAmbiguousError = findwindows.WindowAmbiguousError
WindowNotFoundError = findwindows.WindowNotFoundError
from . impor... |
from __future__ import unicode_literals
from django import http
from django.apps import apps
from django.conf import settings
from django.contrib.redirects.models import Redirect
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ImproperlyConfigured
class Redire... |
__all__= ['SnapshotCheckin','SnapshotAppendCheckin']
from file_checkin import *
from pyasm.search import Search
from checkin import CheckinException
class SnapshotCheckin(FileCheckin):
'''simple class to checkin a snapshot without files'''
def __init__(my, sobject, snapshot_xml, \
context="publish... |
"""Reference implementation of AugMix's data augmentation method in numpy."""
import augmentations
import numpy as np
from PIL import Image
# CIFAR-10 constants
MEAN = [0.4914, 0.4822, 0.4465]
STD = [0.2023, 0.1994, 0.2010]
def normalize(image):
"""Normalize input image channel-wise to zero mean and unit variance.... |
from typing import List
class Solution:
def minimumCost(self, N: int, conections: List[List[int]]) -> int:
father = [i for i in range(N + 1)]
size = [1 for i in range(N + 1)]
def find(i: int) -> int:
while father[i] != i:
i = father[i]
return i
... |
import copy
# Part of Cosmos by OpenGenus Foundation
boardsize = 6
_kmoves = ((2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1))
def chess2index(chess, boardsize=boardsize):
"Convert Algebraic chess notation to internal index format"
chess = chess.strip().lower()
x = ord(chess[0]) - ... |
"""Fichier contenant l'action verrouiller_porte."""
from primaires.scripting.action import Action
from primaires.scripting.instruction import ErreurExecution
class ClasseAction(Action):
"""Verrouille une porte."""
@classmethod
def init_types(cls):
cls.ajouter_types(cls.verrouiller_porte, "Salle"... |
import gevent
import socket
import fixtures
import subprocess
from util import retry
from mockredis import mockredis
from mockzoo import mockzoo
from mockifmap import mockifmap
import redis
import time
import urllib2
import copy
import os
import json
from operator import itemgetter
import sys, os
pyver = "%s.%s" % (sys... |
from gettext import gettext as _
from gettext import ngettext
import logging
import os
import time
#+---------------------------------------------------------------------------+
#| Related third party imports
#+---------------------------------------------------------------------------+
from gi.repository import Gtk, ... |
class Solution(object):
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
if len(prices) <= 1:
return 0
sold = [0] * len(prices)
hold = [0] * len(prices)
hold[0] = -prices[0]
for i ... |
from south.db import db
from django.db import models
from mypage.pages.models import *
import datetime
class Migration:
def forwards(self, orm):
# Changing field 'UserPage.site_copy'
db.alter_column('pages_userpage', 'site_copy_id', models.ForeignKey(orm['sites.Site'], default= lambda... |
import unittest
from eve.utils import config
from tests import BaseTest, SimpleDoc, ComplexDoc
class TestHttpDelete(BaseTest, unittest.TestCase):
def setUp(self):
response = self.client.post('/simpledoc/',
data='[{"a": "jimmy", "b": 23}, {"a": "steve", "b": 77}]',
content_type='a... |
import mock
from openstack.tests.unit import base
from openstack.network.v2 import agent
IDENTIFIER = 'IDENTIFIER'
EXAMPLE = {
'admin_state_up': True,
'agent_type': 'Test Agent',
'alive': True,
'availability_zone': 'az1',
'binary': 'test-binary',
'configurations': {'attr1': 'value1', 'attr2': ... |
import logging
from sqlagg.base import TableNotFoundException, ColumnNotFoundException
from corehq.apps.reports.sqlreport import SqlData, DictDataFormat, DataFormatter
logger = logging.getLogger(__name__)
class IndicatorSetException(Exception):
pass
class SqlIndicatorSet(SqlData):
no_value = 0
name = '... |
from cStringIO import StringIO
from socket import error as socketerror
protocol_name = 'BitTorrent protocol'
# header, reserved, download id, my id, [length, message]
class NatCheck(object):
def __init__(self, resultfunc, downloadid, peerid, ip, port, rawserver):
self.resultfunc = resultfunc
se... |
import corepy.spre.spe as spe
# ------------------------------
# Registers
# ------------------------------
class mods:
abs = 'abs'
bias = 'bias'
bx2 = 'bx2'
invert = 'invert'
sign = 'sign'
x2 = 'x2'
class divcomp:
x = 'x'
y = 'y'
z = 'z'
w = 'w'
class Address(object):
def __init__(self, base... |
"""empty message
Revision ID: 2fd5d2ceb21e
Revises: 309990f409a8
Create Date: 2016-05-12 23:09:59.027205
"""
# revision identifiers, used by Alembic.
revision = '2fd5d2ceb21e'
down_revision = '309990f409a8'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
"""
Event object for Gramps.
"""
#-------------------------------------------------------------------------
#
# standard python modules
#
#-------------------------------------------------------------------------
import logging
#-------------------------------------------------------------------------
#
# Gprime modu... |
# Initialize App Engine and import the default settings (DB backend, etc.).
# If you want to use a different backend you have to remove all occurences
# of "djangoappengine" from this file.
from djangoappengine.settings_base import *
import os
# Activate django-dbindexer for the default database
DATABASES['native'] =... |
import sys
if sys.version_info >= (3,):
from io import BytesIO
else:
try:
from cStringIO import StringIO as BytesIO
except:
from StringIO import StringIO as BytesIO
try:
from xml.etree import cElementTree as ETree
except ImportError:
from xml.etree import ElementTree as ETree
from... |
import re
import json
from Products.CMFCore.utils import getToolByName
from genweb.core.indicators import Calculator, CalculatorException
from genweb.serveistic.utilities import serveistic_config
from genweb.serveistic.data_access.servei import ServeiDataReporter
from genweb.serveistic.data_access.webanalytics import... |
from datetime import date
from django.db import models
from django.db.models import Q
from wagtail.wagtailsearch import index
from wagtail.wagtailadmin.edit_handlers import FieldPanel,MultiFieldPanel
from portal.base.models import PageBase,DetailPageBase
class Event(DetailPageBase):
parent_page_types = ['Calend... |
#!/usr/bin/env python
# encoding=utf8
import os
import sys
import getopt
import subprocess
from shutil import rmtree, copy
homeDir = os.getenv("HOME") + "/"
bkpDir = homeDir + ".bashrc_bkp/"
bashDir = homeDir + ".bashrc_include/"
tmpDir = homeDir + ".bashrc_tmp/"
repoUrl = "https://github.com/svilborg/dotfiles"
fil... |
# -*- coding: utf-8 -*-
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5 import QtGui
from submodules.gui_frame_tabs import gui_frame_tabs
from submodules.cmd_functions import keyCommends
class run_program(QtWidgets.QMainWindow):
Program = "Book Maker"
Version = "0.0.1"
Edit_fi... |
"""Loads and instantiates Celery, registers our tasks, and performs any other
necessary Celery-related setup. Also provides Celery-related utility methods,
in particular exposing a shortcut to the @task decorator.
Please note that this module should not import model-related code because
Django may not be properly set-... |
import sys
import os
from Components.ActionMap import ActionMap
from Components.Pixmap import Pixmap
from Components.ConfigList import ConfigListScreen
from Components.Label import Label
from datetime import datetime
from time import strftime
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
f... |
__all__ = ['Locus','StrandPos']
class StrandPos(object):
def __init__(self, sense, lower, higher):
"""
sense: True or False
always, lower < higher
for sense, lower,higher = start,end
for antisense, lower,higher = end,start
chr -------------------------------... |
"""Tests for policy_lisses."""
from seed_rl.agents.policy_gradient.modules import policy_losses
from seed_rl.agents.policy_gradient.modules import test_utils
import tensorflow as tf
class AdvantagePreprocessorTest(test_utils.TestCase):
def test_normalization(self):
adv = tf.constant([1.5, 4., 123., -3.])
a... |
# encoding: utf-8
"""
A[0, s] = 0; A[0, v] = +inf for all v != s
# Порядок обхода важен
# Correct if no neg cycles
n # count vetrex
m # #edges
# FIXME: а что с параллельными ребрами?
i # budget
for i = 1, 2... n-1:
for each v in V:
A[i, v] = min (
A[i-1, v] # 1)
# in/out... |
"""Base geometry class and utilities
"""
import sys
import warnings
from shapely.coords import CoordinateSequence
from shapely.ftools import wraps
from shapely.geos import lgeos
from shapely.impl import DefaultImplementation, delegated
from shapely import wkb, wkt
GEOMETRY_TYPES = [
'Point',
'LineString',
'Lin... |
# coding: utf-8
from google.appengine.ext import ndb
import config
import modelq
import modelx
import util
class Base(ndb.Model, modelq.Base):
created = ndb.DateTimeProperty(auto_now_add=True)
modified = ndb.DateTimeProperty(auto_now=True)
version = ndb.IntegerProperty(default=config.CURRENT_VERSION_TIMESTAMP... |
class ipc(object):
pass
class shutdown(ipc):
pass
class shutdownMicroprocess(shutdown):
def __new__(cls):
if cls != shutdownNow and shutdownNow not in cls.__bases__:
print "*** tsk tsk, creating a shutdownMicroprocess!!"
return shutdown.__new__(shutdownNow)
class shutdownNow... |
# Webhooks for external integrations.
import re
from typing import Any, Dict, List
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.co... |
# -*- coding: utf-8 -*-
""" RESTful Record Merger
@see: U{B{I{S3XRC}} <http://eden.sahanafoundation.org/wiki/BluePrintRecordMerger>}
@status: work in progress
@author: Dominic König <dominic[at]aidiq.com>
@copyright: 2009-2011 (c) Sahana Software Foundation
@license: MIT
Permission is hereb... |
from version import VERSION
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
long_description = '''
Create a swagger API from a set of classes.
Main features:
- Request validation and casting types according to the specification.
- ORM with sqlalchemy ba... |
import collections
import pilasengine
class Colisiones(object):
"Administra todas las _colisiones entre actores."
def __init__(self, pilas, escena):
self.pilas = pilas
self.escena = escena
# Esta lista contiene elementos de la forma:
#
# (grupo_o_actor_A, grupo_o_ac... |
import fcntl
import sys
HOST_FORMAT = 'Host format is [user@]host[:port] [user]'
def read_host_files(paths, default_user=None, default_port=None):
"""Reads the given host files.
Returns a list of (host, port, user) triples.
"""
hosts = []
if paths:
for path in paths:
hosts.ex... |
__author__ = 'Jagger Kyne'
import copy
import pickle
#1: Copied Cards
class Car:
pass
def copy_car():
car_1 = Car()
car_1.wheels = 4
car_2 = car_1
car_2.wheels = 3
print(car_1.wheels) # print out 3 instead of 4 because car_2 and car_1 are pointed to the same object
car_3 = copy.copy(car_... |
""" Copyright 2015 Will Boyce """
from __future__ import print_function, unicode_literals
from telegrambot.api.base import APIObject
class Audio(APIObject):
"""
This object represents an audio file to be treated as music by the Telegram clients.
file_id str Unique identifier for this fi... |
import os
import numpy as np
from keras import backend as K
from keras.legacy.interfaces import generate_legacy_interface, recurrent_args_preprocessor
from keras.models import model_from_json
legacy_prednet_support = generate_legacy_interface(
allowed_positional_args=['stack_sizes', 'R_stack_sizes',
... |
"""
Trove Command line tool
"""
import os
import sys
from troveclient.compat import common
# If ../trove/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]... |
import re
import sys
import eventlet
eventlet.monkey_patch()
from oslo.config import cfg
from oslo import messaging
from neutron.agent.common import config
from neutron.agent.linux import ip_lib
from neutron.agent.linux import utils
from neutron.common import config as common_cfg
from neutron.common import rpc
from... |
# -*- coding: utf-8 -*-
'''
Service support for RHEL-based systems, including support for both upstart and sysvinit
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not avail... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from functools import partial
from django.core.exceptions import PermissionDenied
from django.conf import settings
from django.views.decorators.http import require_http_methods
from dj... |
#!/usr/bin/python3
'''
Created on 4th July 2017
@author: Jeremy Gooch
Python AMQP 0-9-1 message receiver.
Execute script with -h parameter for usage
'''
# --- CONSTANTS --------------------------------------------------------------
CACERTFILE = "/mnt/ssl/ca/cacert.pem"
CERTFILE = "/mnt/ssl/client/cert.pe... |
import csv
import datetime
from io import StringIO
from unittest.mock import mock_open, patch
import pytz
from django.contrib.auth import get_user_model
from django.core.management import CommandError, call_command
from django.utils import timezone
from intranet.utils.date import get_senior_graduation_year
from ...... |
# Задача 8. Вариант 23
# Доработайте игру "Анаграммы" (см. М.Доусон Программируем на Python. Гл.4)
# так, чтобы к каждому слову полагалась подсказка. Игрок должен получать право
# на подсказку в том случае, если у него нет никаких предположений.
# Разработайте систему начисления очков, по которой бы игроки, отгадавшие
... |
from app import Handler
from entities.post import Post
from handlers.auth import Auth
from handlers.decorators import restricted
class EditPostHandler(Handler):
@restricted
def get(self, post_id):
current_user = self.current_user
post = Post.by_id(int(post_id))
# verify if post exis... |
from typing import List, Set
class F1Evaluator(object):
""" F1 evaluator for BIO tagging, e.g. NP chunking.
The entities are annotated as beginning of the entity (B), continuation of
the entity (I), the rest is outside the entity (O).
"""
def __init__(self, name: str = "F1 measure") -> None:
... |
""" TCP Server for mobile streaming
"""
try:
import SocketServer as socketserver
except ImportError:
import socketserver
from dss.tools import thread
from dss.tools.show import Show
from dss.config import config
from dss.storage import db
from .handler import MediaHandler
show = Show('Mobile')
# If some s... |
from odoo import fields, models, api, _
from odoo.exceptions import ValidationError
class AccountJournal(models.Model):
_inherit = "account.journal"
l10n_latam_use_documents = fields.Boolean(
'Use Documents?', help="If active: will be using for legal invoicing (invoices, debit/credit notes)."
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from calendar import monthrange
from datetime import date
from django.db import models
from django import forms
from django.utils.translation import ugettext as _
from paypal.pro.creditcard import verify_credit_card
class CreditCardField(forms.CharField):
"""Form fi... |
"""Tests for slater_determinants.py."""
import unittest
import numpy
from openfermion.config import EQ_TOLERANCE
from openfermion.transforms import get_sparse_operator
from openfermion.utils import (jw_configuration_state,
get_ground_state)
from openfermion.utils._sparse_tools import (... |
import sys
# [START storage_list_hmac_keys]
from google.cloud import storage
def list_keys(project_id):
"""
List all HMAC keys associated with the project.
"""
# project_id = "Your Google Cloud project ID"
storage_client = storage.Client(project=project_id)
hmac_keys = storage_client.list_hm... |
import logging
import json
import sys
from dlab.fab import *
from dlab.meta_lib import *
from dlab.actions_lib import *
import os
import uuid
if __name__ == "__main__":
local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'],
... |
"""Data used by the tornado.locale module."""
from __future__ import absolute_import, division, print_function, with_statement
# NOTE: This file is supposed to contain unicode strings, which is
# exactly what you'd get with e.g. u"Español" in most python versions.
# However, Python 3.2 doesn't support the u"" syntax,... |
from test.test_support import verbose, TestSkipped, run_unittest
from _locale import (setlocale, LC_NUMERIC, RADIXCHAR, THOUSEP, nl_langinfo,
localeconv, Error)
import unittest
from platform import uname
if uname()[0] == "Darwin":
maj, min, mic = [int(part) for part in uname()[2].split("... |
from django.db import models
from shop.models import Product
class Order(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=250)
postal_code = models.CharField(max_length=20)
... |
import os
from bokeh.layouts import gridplot
from bokeh.plotting import figure, show, save, output_file
from bokeh.models import ColumnDataSource, HoverTool, LinearColorMapper, BasicTicker, PrintfTickFormatter, ColorBar, Range1d
from bokeh.transform import transform
from bokeh.palettes import RdBu, Spectral, RdYlBu, Rd... |
"""
Editorial
Problem Statement
Calvin is driving his favorite vehicle on the 101 freeway. He notices that the check engine
light of his vehicle is on, and he wants to service it immediately to avoid any risks. Luckily,
a service lane runs parallel to the highway. The length of the highway and the service lane is
N... |
"""
==========================================
Seasonal decomposition of your time-series
==========================================
This example demonstrates how we can use the ``decompose`` function to extract
the trend, seasonal, and random components of the time series and then
plot them all using the ``decompose... |
"""
Bunch of api utilities for finding records by their names.
Katello API uses integer ids for record identification in most
cases. These util functions help with translating names to ids.
All of them throw ApiDataError if any of the records is not found.
"""
from katello.client.api.organization import OrganizationA... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import codecs
import pymongo
import hashlib
import jieba
import argparse
import re
import json
from pcnile.resource import format_bt, atom_magnet
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--target", type=str... |
from base import *
DEBUG = True
DATABASES['default']['NAME'] = ''
DATABASES['default']['USER'] = ''
DATABASES['default']['PASSWORD'] = ''
DATABASES['default']['HOST'] = '127.0.0.1'
DATABASES['default']['PORT'] = '5432'
# CACHING
# ------------------------------------------------------------------------------
CACHES... |
"""
STK500v2 protocol implementation for programming AVR chips.
The STK500v2 protocol is used by the ArduinoMega2560 and a few other Arduino platforms to load firmware.
This is a python 3 conversion of the code created by David Braam for the Cura project.
"""
import os
import struct
import sys
import time
from serial ... |
# coding: utf-8
import time
from bussiness.models.seller import Seller
from customer.models.customer import Customer
from admin.models.admin import Admin
from password_tools import check_password
from takeout.conn import redisClient
USER_MODEL_MAP = {
"admin": Admin,
"customer": Customer,
"bussiness": Sel... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import TestCase, run_module_suite, assert_equal, \
assert_array_equal
from scipy.stats import rankdata, tiecorrect
class TestTieCorrect(TestCase):
def test_empty(self):
"""An empty array requi... |
# -*- encoding: utf-8 -*-
import os
from datetime import datetime, date, time
from decimal import Decimal
import pytest
from waterboy import KVStore, RedisConfig
import waterboy.testing
MONGO_TEST_DATABASE = waterboy.testing.MONGO_TEST_DATABASE
REDIS_PORT = os.environ.get('REDIS_PORT', 6379)
MONGO_PORT = os.environ... |
from datetime import datetime, timedelta
from urllib.parse import urlparse
import requests
from requests.exceptions import ConnectTimeout, ReadTimeout
import simplejson
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import logout
from django.core.urlresolvers import reve... |
import numpy as np
import pytest
from pandas import DataFrame, NaT, date_range
import pandas.util.testing as tm
@pytest.fixture
def float_frame_with_na():
"""
Fixture for DataFrame of floats with index of unique strings
Columns are ['A', 'B', 'C', 'D']; some entries are missing
A... |
from osv import osv, fields
class stock_move(osv.osv):
_inherit = "stock.move"
_columns = {
'analytics_id': fields.many2one('account.analytic.plan.instance','Analytics Distribution',states={'done': [('readonly', True)]}),
}
def _create_account_move_line(self, cr, uid, move, src_acc... |
import re
def make_header(title):
header = '<!DOCTYPE HTML PUBLIC>\n'
header += '<html>\n'
header += '<head>\n'
header += '<title>' + unicode(title) + '</title>\n'
header += '<script src="../sorttable.js"></script>\n'
header += '<link rel="stylesheet" type="text/css" href="../style.css">\n'
... |
# coding=utf-8
"""
This module, problem_001.py, solves the fifteenth project euler problem.
"""
from project_euler_problems.problem import Problem
'''
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 ... |
import pynet,netext,percolator
import random
import numpy as np
def mst(net,maximum=False):
"""Find a minimum/maximum spanning tree
"""
return mst_kruskal(net,True,maximum)
def mst_kruskal(net,randomize=True,maximum=False):
"""Find a minimum/maximum spanning tree using Kruskal's algorithm
If ran... |
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-duat',
version='1.0',
packages=['duat'],
inclu... |
# Lint as: python3
"""Utilities to serialize and deserialize dictionaries of numpy arrays.
This module defines generic reader and writer for serialized data as well as
specialized methods to export collections of numpy arrays to files.
The latter is based on `TFRecords` format. The main difference is
that instead of d... |
# -*- coding: utf-8 -*-
# -*- mode: python -*-
import re
from PyQt4.QtGui import QApplication
from PyQt4.QtWebKit import QWebPage
from BeautifulSoup import BeautifulSoup
import exceptions as exc
class Evaluator(object):
_replacechars = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЪЭЮЯабвгдеёжзийклмнопрстуфхцчшщьъэюя'
def... |
from helpers import (number_to_16_bit, number_to_32_bit,
number_to_32_bit_unsigned, number_to_64_bit, pad_to_32bits)
from harparser import (parse_har, build_packets)
class Option:
def __init__(self, code, value):
"""
The given code(integer)
Note that the given `value` ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import time
import numpy as np
from sklearn.externals import joblib
def generate_X_y(pairs_file):
X, y, pairs = [], [], []
with open(pairs_file, 'r') as fin:
i = 0
while True... |
import re
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.util import re_escape
from quodlibet.plugins.events import EventPlugin
class RadioAdMute(EventPlugin):
PLUGIN_ID = "radio_ad_mute"
PLUGIN_NAME = _("Mute Radio Ads")
PLUGIN_DESC = _("Mutes output wh... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import assert_
from scipy.lib.six.moves import xrange
from scipy.sparse.linalg import lsqr
from time import time
# Set up a test problem
n = 35
G = np.eye(n)
normal = np.random.normal
norm = np.linalg.norm
for jj ... |
from google.appengine.api import users
from google.appengine.ext import db
import forms
import models
import decorators
from crud_handler import CRUDHandler
class CurrentUser(CRUDHandler):
model = models.UserProfile
form = forms.UserProfileForm
@decorators.json
def get(self):
user = users.get... |
from kivy.properties import ListProperty, StringProperty, \
NumericProperty, BooleanProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.accordion import AccordionItem
class RepoItem(BoxLayout):
"""
RepoItem; on repository list,
each element is using this class to display.
"""
... |
#!/usr/bin/env python
# encoding: utf-8
"""
GluinoAnalysisWorker.py
Created by Morten Dam Jørgensen on 2010-04-30.
Copyright (c) 2010 Niels Bohr Institute. All rights reserved.
"""
from GluinoAnalysis import GluinoAnalysis
import ROOT
from jobhandler import JobHandler
class GluinoAnalysisWorker(GluinoAnalysis):
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.