content stringlengths 4 20k |
|---|
import re
from bs4 import BeautifulSoup
from . import bagofrequests as bag
from . import handlers
from . import result as res
HEX_MASSAGE = [(re.compile('&#x([^;]+);'), lambda m: '&#%d;' % int(m.group(1), 16))]
class ContentRepo(object):
def __init__(self, url, **kwargs):
self.url = url
self.kwa... |
from webkitpy.tool.commands.queuestest import QueuesTest
class SheriffBotTest(QueuesTest):
pass # No unittests as the moment. |
from datetime import datetime, timedelta
import time
class DHLShipment:
"""
A class for creating separate shipments.
"""
DROP_OFF_REGULAR_PICKUP = 'REGULAR_PICKUP'
DROP_OFF_REQUEST_COURIER = 'REQUEST_COURIER'
SERVICE_TYPE_EU = 'U'
SERVICE_TYPE_WORLD = 'P'
SERVICE_TYPE_WORLD_DOCUMENTS... |
from django import forms
from reservations.models import *
class ReservationForm(forms.ModelForm):
class Meta:
model = Reservation
# To limit the set of displayed fields use:
# exclude = ['start_time', 'end_time']
# (or list the needed ones with "fields = ")
## To hide certain fields, we use widgets:
## h... |
teamAbv = {
"L.A": "LOS ANGELES KINGS",
"ANA": "ANAHEIM DUCKS",
"CAR": "CAROLINA HURRICANES",
"MTL": "MONTREAL CANADIENS",
"DET": "DETROIT RED WINGS",
"COL": "COLORADO AVALANCHE",
"NSH": "NASHVILLE PREDATORS",
"BOS": "BOSTON BRUINS",
"DAL": "DALLAS STARS",
"PHI": "PHILA... |
"""Shared functionality useful for multiple package managers.
"""
import yaml
from fabric.api import *
from fabric.contrib.files import *
def _yaml_to_packages(yaml_file, to_install, subs_yaml_file = None):
"""Read a list of packages from a nested YAML configuration file.
"""
env.logger.info("Reading %s" %... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def Eq(field, value):
return {'_field': field, '_value': value}
def Gt(field, value):
return {'_gt': {field: value}}
def Gte(field, value):
return {'_gte': {field: value}}
def Lt(field, value):
return {'_lt': {field: value}}
def Lte(field, value):
... |
import matplotlib
from kid_readout.measurement.legacy import sweeps
from kid_readout.roach import baseband
matplotlib.use('agg')
import numpy as np
import time
import sys
from kid_readout.utils import data_file
from kid_readout.analysis.resonator.legacy_resonator import fit_best_resonator
from kid_readout.equipment i... |
"""
Copyright (c) 2012-2014, Austin Benson and David Gleich
All rights reserved.
This file is part of MRTSQR and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
"""
"""
Direct TSQR algorithm (part 3).
... |
from importlib import import_module
from .parameter import Parameter
from .. import __version__
from ..errors import ParameterError
import logging
log = logging.getLogger(__name__)
class ParametricObject(object):
"""
Parametric objects may be defined like so:
.. doctest::
>>> from cqparts.par... |
"""
Autopsy Forensic Browser
Copyright 2016-2018 Basis Technology Corp.
Contact: carrier <at> sleuthkit <dot> org
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... |
"""
Since we rely on an underlying blog engine we are primarily
testing the integration points of the chosen blog engine. E.g.
* Are the URLs from the blog engine hooked up correctly?
* Are we including the blog data into the sitemap?
* Are we exposing a blog feed?
"""
from django.core.urlresolvers import reverse
fr... |
from __future__ import division
import random
from vector import Vector
from utils import translatemap, clamp, EventHook
from dna import DNA
from stuff import Food
import time
margin = 25
width = displayHeight
energyFood = 80
depth = displayHeight
states = {
'detect': 'detect',
'decide': 'decide',
... |
from __future__ import print_function, division, absolute_import
import json
import time
import requests
from . import settings
from .utils import three_digit, create_paired_list, geocode
class Search(object):
""" The search class """
def __init__(self):
self.api_url = settings.API_URL
def sea... |
from enum import Enum
from bearlibterminal import terminal
def key_to_action(key):
if key in (terminal.TK_UP, terminal.TK_KP_8):
return GamePad.up
elif key in (terminal.TK_DOWN, terminal.TK_KP_2):
return GamePad.down
elif key in (terminal.TK_LEFT, terminal.TK_KP_4):
return GamePad.... |
import datetime
from tabulate import tabulate
import pytz
from moneywagon.crypto_data import crypto_data
from moneywagon.core import CurrencyNotSupported, make_standard_halfing_eras
from moneywagon.blocktime_adjustments import adjustments
class SupplyEstimator(object):
"""
Returns a function that can be used ... |
# -*- coding: utf-8 -*-
# flake8: noqa
from __future__ import unicode_literals
from django.db import models, migrations
import webplatformcompat.validators
import webplatformcompat.fields
class Migration(migrations.Migration):
dependencies = [
('webplatformcompat', '0001_initial'),
]
operations... |
import numpy as np
import pytest
from sklearn.datasets.samples_generator import make_blobs
from sklearn.cluster.optics_ import (OPTICS,
_extend_region,
_extract_xi_labels)
from sklearn.metrics.cluster import contingency_matrix
from sklearn.metri... |
from os.path import exists, join as pjoin
from ..utils import btl
from internal import btlBase
from .. import benchconfig as cfg
availableTests = (
'FFTW_1D_Forward_Measure', 'FFTW_1D_Forward_Estimate',
'FFTW_1D_Backward_Measure', 'FFTW_1D_Backward_Estimate',
'FFTW_2D_Forward_Measure', 'FFTW_2D_Forward_Es... |
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always all... |
# encoding: UTF-8
'''
本文件中实现了行情数据记录引擎,用于汇总TICK数据,并生成K线插入数据库。
使用DR_setting.json来配置需要收集的合约,以及主力合约代码。
'''
import json
import os
import copy
from collections import OrderedDict
from datetime import datetime, timedelta
from Queue import Queue
from threading import Thread
from eventEngine import *
from vtGateway import V... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime, argparse, socket
def parse_args():
usage = """usage: %prog [options] [hostname]:port ...
This is the Get Poetry Now! client, blocking edition.
Run it like this:
python3 get_poetry.py port1 port2 port3 ...
"""
parser = argparse.ArgumentParse... |
from oslo_log import log
from manila.scheduler.filters import base_host
from manila.scheduler import utils
LOG = log.getLogger(__name__)
class CapabilitiesFilter(base_host.BaseHostFilter):
"""HostFilter to work with resource (instance & volume) type records."""
def _satisfies_extra_specs(self, capabilities... |
"""Tests for inception_resnet_v2.py.
This test mainly focuses on comparing slim inception resnet v2 and Keras
inception resnet v2 for object detection. To verify the consistency of the two
models, we compare:
1. Output shape of each layer given different inputs
2. Number of global variables
We also visualize the ... |
import os
import numpy as np
class combustion_target():
###Class definition and acquisition of input parameters.
def __init__(self,data,index):
self.data = data
parameters = self.data.split(',')
self.calculated = 0
self.case_index = "case-"+str(index)
self.input_file = self.target = self.simulation = self.... |
import json
import netifaces
import socket
import subprocess
from tendrl.commons import objects
from tendrl.commons.utils import log_utils as logger
from tendrl.commons.utils.service import Service
NODE_PLUGINS = {
'collectd',
'cpu',
'mount_point',
'memory',
'swap',
'network',
'latency',... |
from __future__ import absolute_import
import errno
import os
from vdsm.constants import EXT_TC
from vdsm.utils import execCmd
_TC_ERR_PREFIX = 'RTNETLINK answers: '
_errno_trans = dict(((os.strerror(code), code) for code in errno.errorcode))
def process_request(command):
command.insert(0, EXT_TC)
retcode, ... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import json
import os
import re
import subprocess
from twitter.common.collections import maybe_list
from pants.base.build_environment import get_buildroot
from pants... |
from wx import glcanvas
import wx
import os
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.arrays import vbo
import struct, math
import numpy as np
import pprint
BUTTONDIM = (48,48)
def vec(*args):
return (GLfloat * len(args))(*args)
class StlCanvas(glcanvas.GLCanvas):
def __init__(self, parent, ... |
# -*- coding: utf-8 -*-
import io
import os
import csv
import gzip
import logging
from website.app import setup_django
setup_django()
from admin.base import utils
from django.utils import timezone
from admin.pre_reg import serializers
from website import mails
from website import settings
from framework.celery_task... |
#!/usr/bin/env python
import download
import os
import shutil
import sys
if os.environ.get('BITS') == '32':
host_bits = 'i686'
extra_bits = 'x86_64'
else:
host_bits = 'x86_64'
extra_bits = 'i686'
# Figure out our target triple
if sys.platform == 'linux' or sys.platform == 'linux2':
host = host_b... |
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User as DjangoUser
from anaf.core.models import User, Group, Perspective, ModuleSetting
from models import KnowledgeFolder, KnowledgeItem, KnowledgeCategory
class ... |
"""
This module is for the miscellaneous routines which do not fit somewhere else.
"""
import glob
import os
import pprint
import py_compile
import sys
from PyInstaller import log as logging
from PyInstaller.compat import BYTECODE_MAGIC, text_read_mode
logger = logging.getLogger(__name__)
def dlls_in_subdirs(direc... |
__all__ = [ 'EVENTMAP' ]
from ... import core as freevo
#
# Default key-event map
#
MENU_EVENTS = {
'LEFT' : freevo.MENU_LEFT,
'RIGHT' : freevo.MENU_RIGHT,
'UP' : freevo.MENU_UP,
'DOWN' : freevo.MENU_DOWN,
'CH+' : freevo.MENU_PAGEUP,
'CH-' : freevo.MENU_PAGEDO... |
#!/usr/bin/env python
"""
Spice Migration test
Somewhat stressfull test of continuous migration with spice in VGA mode or QXL mode,
depends on supplying an image in IMAGE variable (if no image is supplied then
VGA mode since it will just be SeaBIOS).
Dependencies:
either qmp in python path or running with spice and q... |
from django.conf import settings
from django.db import models,transaction
from django.template.defaultfilters import slugify
from django.urls import reverse
from django.utils import timezone
from django.utils.safestring import mark_safe
from .markdown import MarkdownText
class MarkdownField(models.TextField):
d... |
import sickbeard
from sickbeard import logger
from sickbeard.classes import NZBSearchResult
from sickrage.helper.common import try_int
from sickrage.providers.GenericProvider import GenericProvider
class NZBProvider(GenericProvider):
def __init__(self, name):
GenericProvider.__init__(self, name)
... |
#!/usr/bin/env python3
educators = [
'ambitious cruel shy envious slothful charitable',
'lustful patient slothful deceitful gluttonous cynical',
'zealous humble charitable deceitful',
'arbitrary patient content brave gregarious',
'ambitious proud gregarious paranoid craven',
'diligent gluttono... |
#!/usr/bin/env python
import sys, os.path
from PyQt4.QtCore import QString, SIGNAL, Qt, QSize
from PyKDE4.kdecore import ki18n, KAboutData, KCmdLineArgs, i18n
from PyKDE4.kdeui import KApplication, KXmlGuiWindow, KTextEdit, KAction
from PyKDE4.kdeui import KStandardAction, KIcon
class MainWindow (KXmlGuiWindow):
... |
from google.appengine.ext import db
from google.appengine.api import memcache
class Stats(db.Model):
reviewTimeUnit = db.IntegerProperty(required=True) #milliseconds
reviewTimeUnitWeight = db.IntegerProperty(default=1)
def setDefaultStats():
stats = getStats()
stats.reviewTimeUnit = 30 * 24... |
from typing import Dict, Optional, Tuple, TYPE_CHECKING
import copy
import json
from ..config import Config
from ..utils import dump_json
from .irresource import IRResource
from .irtlscontext import IRTLSContext
if TYPE_CHECKING:
from .ir import IR # pragma: no cover
class IRListener (IRResource):
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
import logging
from werkzeug.utils import import_string
from flask import request, session
from flask.ext.admin import Admin
from ..models import (Link, Config, SubContentPurpose, ChannelType,
ContentTemplateType, Channel)
from .models import ModelAd... |
#!/usr/bin/env python3
import argparse
import configparser
import os
import sys
from map import Map
from population import Population
from graphics import save_svg
from contexttimer import Timer
from collections import deque
from ast import literal_eval
class CircularBuffer(deque):
def __init__(self, size=0):
... |
from .column import Column
class Table:
def __init__(self, name='', columns=None, equivalences=None):
self._name = name
if not columns:
columns = []
self.columns = columns
if not equivalences:
equivalences = []
self.equivalences = equivalences
... |
# coding: utf-8
from Bio import Entrez
import argparse
import time
import urllib
import ssl
import sys
parser = argparse.ArgumentParser(description='UniProt codes')
parser.add_argument('uniprotAcc')
parser.add_argument('email')
args=parser.parse_args()
Entrez.email = args.email
attempts = 0
ids=args.uniprotAcc
contx=s... |
# -*- coding: utf-8 -*-
import sys
import pytest
from fpylll import GSO, IntegerMatrix, LLL
from fpylll.config import float_types, int_types
from copy import copy
import tools
if sys.maxsize >= 2**62:
dimensions = ((0, 0), (2, 2), (3, 3), (10, 10), (30, 30), (50, 50), (60, 60))
else:
dimensions = ((0, 0), ... |
__author__="Daniel Berenguer"
__date__ ="$Aug 20, 2011 10:36:00 AM$"
#########################################################################
import time
from SerialPort import SerialPort
from CcPacket import CcPacket
from swap.SwapException import SwapException
class SerialModem:
"""
Class representing a s... |
#!/usr/bin/env python
"""
Usage:
import this stuff, most likely with import serialwrite
serialwrite().send_signal(brand, signal, spamAmount)
Containts a stub for modules, however no implementation for it yet.
It has been set to 123 for now.
"""
import serial
import sys
import os
import json
import saschapath
class ... |
import sys
sys.path.insert(1, "../../../")
import h2o
def fiftycatRF(ip,port):
# Training set has only 45 categories cat1 through cat45
#Log.info("Importing 50_cattest_train.csv data...\n")
train = h2o.import_file(path=h2o.locate("smalldata/gbm_test/50_cattest_train.csv"))
train["y"] = train... |
'''
Created on Jan 12, 2013
@author: Paulson McIntyre (GpMidi) <<EMAIL>>
'''
from users import *
from index import *
from instances import * |
"""
This page is in the table of contents.
Gcode_small is an export plugin to remove the comments and the redundant z and feed rate parameters from a gcode file.
An export plugin is a script in the export_plugins folder which has the getOutput function, the globalIsReplaceable variable and if it's output is not replac... |
"""
Module for checking permissions with the comment_client backend
"""
import logging
from types import NoneType
from request_cache.middleware import RequestCache
from lms.lib.comment_client import Thread
from opaque_keys.edx.keys import CourseKey
from django_comment_common.models import all_permissions_for_user_in... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Post.slug'
db.add_column(u'blogengine_post', 'slug',
... |
import sys
from common.system.file import File
class TextFile(File):
def __init__(self, path, file_id):
# example output:
# 'ASCII text'
self._path = path
self._file_id = file_id
if not self.magic_match(self._get_raw_type()):
raise ValueError("Not a text file... |
import os
from setuptools import setup, find_packages
def readlocal(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
DISTNAME = 'larray_eurostat'
VERSION = '0.33-dev'
AUTHOR = 'Alix Damman, Gaetan de Menten, Geert Bryon, Johan Duyck'
AUTHOR_EMAIL = '<EMAIL>'
DESCRIPTION = "Additional p... |
"""
Utilities related to Pip or Python's standard package/modules.
"""
import os
import pathlib2 as pathlib
import six
import sys
try:
reload
except NameError:
try:
from importlib import reload
except ImportError:
from imp import reload
def get_site_packages(prefix):
"""
Returns the path to the `s... |
class node:
def __init__(self, value):
self.data = value
self.next = None
class Stacks:
def __init__(self):
self.TOS = None
def Push(self, value):
new_node = node(value)
new_node.next = self.TOS
self.TOS = new_node
def Pop(self):
if self.TOS == ... |
from datetime import datetime
import glob
import operator
import os
import string
import subprocess
import sys
import urllib
def load_src(name, fpath):
import os, imp
return imp.load_source(name, os.path.join(os.path.dirname(__file__), fpath))
load_src("utils_malletinterpret", os.path.join("..", "utils", "uti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# email : gmail, pmav99
"""
Calculate crane Loads according to Eurocode 1991-2
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import os
import sys
imp... |
import re
import sys
from setuptools import setup
def get_version(filename):
# This regex isn't very robust, but it should work for most files.
regex = re.compile(r'''__version__.*=.*['"](\d+\.\d+(?:\.\d+)?)['"]''')
with open(filename) as f:
for line in f:
match = regex.search(line)
... |
import sys
import cv2
import cv2.cv as cv
import time
import numpy as np
from matplotlib import pyplot as plt
from scipy import ndimage
sys.path.append('../sdk')
from buggy import Buggy
# ********************** VARIABLES **********************
#
# Modify these to tailor to your environment.
#
DETECT_FL... |
#!/usr/bin/env python
#
# Utilities used by the LendingClubInvestor
#
"""
The MIT License (MIT)
Copyright (c) 2013 Jeremy Gillick
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 restric... |
from __future__ import absolute_import
import os.path
import re
import multiprocessing
import sys
import numpy
import uproot3.source.chunked
class HTTPSource(uproot3.source.chunked.ChunkedSource):
# makes __doc__ attribute mutable before Python 3.3
__metaclass__ = type.__new__(type, "type", (uproot3.source.... |
"""This module supports executing CartoDB queries."""
import copy
import urllib
import logging
from appengine_config import runtime_config
from google.appengine.api import urlfetch
# CartoDB endpoint:
if runtime_config.get('cdb_endpoint'):
ENDPOINT = runtime_config.get('cdb_endpoint')
else:
ENDPOINT = 'http:... |
#!/usr/bin/env python3
""" Printers """
__author__ = 'Andrea Dainese <<EMAIL>>'
__copyright__ = 'Andrea Dainese <<EMAIL>>'
__license__ = 'https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode'
__revision__ = '20170430'
from netdoc.catalog.models import *
def printableNetwork(network):
return {
'id'... |
import os
import pyfastaq
import pysam
import primer3tools
class Error (Exception): pass
class PrimerUniqueness:
def __init__(self, genomes_file, primer3_outdir, outprefix, min_product_length=50, max_product_length=1000):
self.genomes_file = os.path.abspath(genomes_file)
self.primer3_outdir = os... |
"""
Internal helpers for basic commandline tools
"""
from __future__ import absolute_import, print_function
import os
import sys
from macholib.util import is_platform_file
def check_file(fp, path, callback):
if not os.path.exists(path):
print(
"%s: %s: No such file or directory" % (sys.argv[... |
import geopandas as gpd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import os
import folium
from folium.raster_layers import ImageOverlay
from folium.plugins import MarkerCluster
print(folium.__version__)
def get_aval_data(shp_file):
dt = os.path.split(shp_file)[1].split('.')[0].split... |
#!/usr/bin/python
from k5test import *
# These tests will become much less important after the y2038 boundary
# has elapsed, and may start exhibiting problems around the year 2075.
if runenv.sizeof_time_t <= 4:
skip_rest('y2038 timestamp tests', 'platform has 32-bit time_t')
# Start a KDC running roughly 21 year... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.php
~~~~~~~~~~~~~~~~~~~
Lexers for PHP and related languages.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, bygroups, default, us... |
import os, sys
import numpy as np
from netCDF4 import Dataset
# Index calculation functions definition
def getAreaRange(srcVar, lat, lon, WEIGHTS, rng, win):
""" Calculate the Mean Surface Temperature. """
nt = srcVar.shape[0]
index = np.empty((nt,))
ilat = (lat >= win[1]) & (lat <= win[3])
ilon = ... |
"""
Django settings for lecture10 project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import ... |
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from django.db.models import signals as dbsignals
from django.dispatch import receiver
from django.core.urlresolvers import reverse
from elasticutils import S
from elasticutils.models import SearchMixin
from tower i... |
from Csmake.CsmakeModuleAllPhase import CsmakeModuleAllPhase
from CsmakeProviders.SwiftProvider import SwiftProvider
class SwiftWrapper(CsmakeModuleAllPhase):
"""Library: csmake-providers
Purpose: Creates and provides information for a container that holds
an entire release set
Option... |
from openerp import SUPERUSER_ID
from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp.addons.website_event.controllers.main import website_event
from openerp.addons.website_sale.controllers.main import get_pricelist
from openerp.tools.translate import _
class website_event(webs... |
"""
twitter.common.python support for interpreter environments.
"""
from __future__ import absolute_import
try:
from numbers import Integral
except ImportError:
Integral = (int, long)
from collections import defaultdict
import os
import re
import subprocess
import sys
from .base import maybe_requirement, maybe_r... |
""" turtle-example-suite:
tdemo_wikipedia3.py
This example is
inspired by the Wikipedia article on turtle
graphics. (See example wikipedia1 for URLs)
First we create (ne-1) (i.e. 35 in this
example) copies of our first turtle p.
Then we let them perform their steps in
parallel.
Followed ... |
"""
Django settings for refugee_matchmaking project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
... |
import pandas as pd
import argparse
import re
import skbio
from copy import deepcopy
import skbio
from skbio.alignment import local_pairwise_align_ssw, make_identity_substitution_matrix
from skbio.sequence import Protein
ident = make_identity_substitution_matrix(match_score=1, mismatch_score=0, alphabet=skbio.sequence.... |
from datetime import datetime
import hashlib
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from markdown import markdown
import bleach
from flask import current_app, request, url_for
from flask.ext.login import UserMixin,... |
"""Box packing algorithm
This is a fairly dumb algorithm.
The gist of it is as follows:
1. Shuffle the list of all boxes
2. Take the summed area of all boxes and create a huge container
3. For every box, insert it into the huge container
5. If we're satisfied with the result, return it
5. Switch list position of two... |
#!/usr/bin/env python
import sys
import os
import numpy
import StringIO
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from scipy.stats import norm
from scipy.stats import normaltest
def plot_string(title, content, years_limit, distance_limit):
matrix = np.... |
from types import SimpleNamespace
from typing import KeysView
from elasticsearch import Elasticsearch, AsyncElasticsearch
from collections import UserDict
class HCResult(UserDict):
pass # Health Check Result
class DBHealth():
def __init__(self, client):
self.client = client
def check(self, **kw... |
#!/usr/bin/env python
from nose.tools import *
import networkx as nx
from networkx import NetworkXNotImplemented
class TestAttractingComponents(object):
def setUp(self):
self.G1 = nx.DiGraph()
self.G1.add_edges_from([(5, 11), (11, 2), (11, 9), (11, 10),
(7, 11), (7,... |
"""Tankerkoenig sensor integration."""
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CURRENCY_EURO,
)
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdat... |
import itertools
import math
import unittest
data = """Alice would gain 54 happiness units by sitting next to Bob.
Alice would lose 81 happiness units by sitting next to Carol.
Alice would lose 42 happiness units by sitting next to David.
Alice would gain 89 happiness units by sitting next to Eric.
Alice would lose 89... |
"""
ExplainToMe
===========
"""
import logging
import os
from dateutil.parser import parser
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_cors import CORS
from flask_heroku import Heroku
from flask_wtf import CsrfProtect
from mashapeanalytics.middleware import FlaskMiddleware as MashapeAnaly... |
import os
import time
# Constants
safe = "safe"
unsafe = "unsafe"
needQuote = "needQuote"
quote = "quote"
integer = "int"
class Manifest:
def __init__(self, date, flaw="Not define"):
self.date=date
path = "../PHPTestSuite_"+self.date+"/" + flaw
if not os.path.exists(path):
o... |
from __future__ import with_statement
import time
import hashlib
try:
import json; json
except ImportError:
json = None
try:
import requests; requests
except ImportError:
requests = None
from mapproxy.client.log import log_request
from mapproxy.cache.tile import TileCreator, Tile
from mapproxy.source... |
#!/usr/bin/env python
"""These flows are system-specific GRR cron flows."""
import bisect
import time
import logging
from grr.endtoend_tests import base
from grr.lib import access_control
from grr.lib import aff4
from grr.lib import config_lib
from grr.lib import data_store
from grr.lib import export_utils
from grr... |
import codecs
from functools import partial
import json
import os
from typing import Any, List, Match, Tuple, Union # pylint: disable=unused-import
from urllib.parse import urljoin, urlencode, quote as urlquote
from jinja2 import Environment, PackageLoader, select_autoescape, Markup, escape
import thor
from redbot ... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Announcement'
db.create_table(u'core_announcement', (
... |
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APITestCase
class OpenBudgetsUITestCase(TestCase):
def listview(self):
"""Simple test to verify the UI list view returns what we'd minimally expect"""
l... |
import os
import re
from setuptools import setup
root_dir = os.path.abspath(os.path.dirname(__file__))
def get_version(package_name):
version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$")
package_components = package_name.split('.')
path_components = package_components + ['__init__.py']
w... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append("web2py")
import argparse
import logging
import os
import shutil
from apps.CreateApp import CreateApp
from apps.SplitSentences import SplitSentences
from db.Corpus_DB import Corpus_DB
from db.BOW_DB import BOW_DB
from db.BOW_ComputeStats import... |
# -*- coding: utf-8 -*-
"""sda.shortcuts
.. codeauthor:: John Lane <<EMAIL>>
"""
from __future__ import unicode_literals
from selenium.webdriver.remote.webdriver import WebDriver
from sda.locators import Locators
__all__ = ['generate_elements']
def generate_elements(_class, locator):
"""Iterate through all el... |
#!/usr/bin/python
# -*- coding: utf-8
# * Creative Commons (cc), 2015, Yuri Terahata
# * Adaptado de 101 Computing (http://www.101computing.net/pixel-art-in-python/)
# *
# * *** Pixel Art com Python ***
# * Gera a imagem de uma Pixel Art no formato PNG conforme valores embutidos
# * em uma matriz.
# carrega as bibli... |
"""Functions for loading well data into data structures"""
from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.python.framework import dtypes
import numpy
################################################################################
def dense_to_one_hot(labels_dense, num_classes):
""... |
from sparkle.QtWrapper import QtGui
from sparkle.resources.icons import arrowdown, arrowup
class WidgetHider(QtGui.QWidget):
"""Takes a widget and places it into a collapsable container widget
:param content: widget to form the hidable contents of this container
:type content: :qtdoc:`QWidget`
"""... |
import pandas as pd
from lib.exp.featx import Featx
from lib.exp.pairing import PairFeats
from lib.exp.xframes import xFrames
from lib.exp.evaluator.xframes import XframeEval
from storage import _Storage as Stg
class Mary(object):
root = "univ_07"
names = ["coates", "chaves", "rozenblit"]
def __init__(se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.