content stringlengths 4 20k |
|---|
# coding: utf-8
from __future__ import absolute_import, division, print_function
import pytest
from astrodynamics.compat.contextlib import suppress
class TestSuppress:
def test_instance_docs(self):
# Issue 19330: ensure context manager instances have good docstrings
cm_docstring = suppress.__doc... |
from django.http import HttpResponse
from django_xhtml2pdf.utils import generate_pdf
from io import BytesIO
from .doc import generate_doc
def render_pdf(request, template, context, pk=None, company_name=None):
filename = 'export.pdf'
if company_name and pk:
filename = '%s_%s_%s.pdf' % (company_name, ... |
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.loadbalancer.base import Member, Algorithm
from libcloud.loadbalancer.drivers.elb import ElasticLBDriver
from libcloud.loadbalancer.types import State
from libcloud.test import MockHttpTestCase
from libcloud.test.secrets import LB_ELB_PAR... |
from __future__ import division, absolute_import, print_function
import sys
import platform
import pytest
import numpy as np
import numpy.core.umath as ncu
from numpy.testing import (
assert_raises, assert_equal, assert_array_equal, assert_almost_equal
)
# TODO: branch cuts (use Pauli code)
# TODO: conj 'sym... |
from django.shortcuts import render
from .forms import DateFilterForm
from core.models import *
from messaging.models import *
from prescriptions.models import *
from testResults.models import *
from transfer.models import *
from django.contrib.auth.decorators import login_required, user_passes_test
from core.views i... |
##
# .port.signal1_msw
##
"""
Support for PG signals on Windows platforms.
This implementation supports all known versions of PostgreSQL. (2010)
CallNamedPipe:
http://msdn.microsoft.com/en-us/library/aa365144%28VS.85%29.aspx
"""
import errno
from ctypes import windll, wintypes, pointer
# CallNamedPipe from kernel32... |
import base64
from urllib.error import URLError
from py.error import ENOENT
import cfme.utils.browser
from cfme.fixtures.artifactor_plugin import fire_art_test_hook
from cfme.utils import safe_string
from cfme.utils.appliance import find_appliance
from cfme.utils.browser import take_screenshot
from cfme.utils.datafil... |
"""Migrate resources from old data.gouv.fr to static HTTP server."""
import argparse
import hashlib
import io
import json
import logging
import os
import re
import socket
import sys
import urllib
import urllib2
import urlparse
from biryani1 import baseconv, custom_conv, states, strings
from ckan import model, plugin... |
"""
Django settings for addressbook project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...... |
from mupif import FunctionID
import mmp_mie_api as mie
# Function IDs until implemented at mupif ###
FunctionID.FuncID_ScatteringCrossSections = 55
FunctionID.FuncID_ScatteringInvCumulDist = 56
###############################################
if __name__ == '__main__':
mieApp = mie.MMPMie('/dev/null')
mieApp.... |
"""add_backend_info_table
Revision ID: 4a482571410f
Revises: 27cb96d991fa
Create Date: 2017-05-18 14:47:38.201658
"""
# revision identifiers, used by Alembic.
revision = '4a482571410f'
down_revision = '27cb96d991fa'
from alembic import op
from oslo_log import log
import sqlalchemy as sql
LOG = log.getLogger(__name... |
# Unit tests for c11.py
# IMPORTS
from c11 import Employee
from c11 import Manager
import unittest
# main
class EmployeeTests(unittest.TestCase):
def setUp(self):
self.e = Employee()
def test_get_name(self):
self.assertEqual("", self.e.get_name())
def test_get_salary(self):
sel... |
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'fabsreq7_detached_award_financial_assistance'
def test_column_headers(database):
expected_subset = {'row_number', 'assistance_type', ... |
"""Base class for a QtWebKit/QtWebEngine web inspector."""
import base64
import binascii
from PyQt5.QtWidgets import QWidget
from qutebrowser.config import configfiles
from qutebrowser.utils import log, usertypes
from qutebrowser.misc import miscwidgets, objects
def create(parent=None):
"""Get a WebKitInspecto... |
"""
HTML Logger allows to log all remarks into HTML
"""
__author__ = 'maxim.shcherbakov'
class htmlLogger():
"""
Attributes
----------
file_name : String
Name of the file for logging
file_pointer : pointer
Pointer to open file
"""
file_name = ''
file_pointer = Non... |
from datetime import datetime, timedelta
from math import radians, degrees, sin, cos, asin, acos, sqrt, fabs, atan2
from numpy import dot
from numpy.linalg import norm
from peregrine.gps_time import datetime_to_tow
import numpy as np
import os, os.path, subprocess
import peregrine.gps_constants as gps
import urllib
de... |
"""Clean up resources from gcp projects. """
import argparse
import collections
import datetime
import json
import subprocess
import sys
# A resource that need to be cleared.
Resource = collections.namedtuple('Resource', 'name condition managed')
DEMOLISH_ORDER = [
# Beware of insertion order
Resource('insta... |
__author__ = 'arobres'
import requests
from nose.tools import assert_equals, assert_true
import ujson
#make a POST request
response = requests.post('http://localhost:8081/v1.0/users')
#Assert response
assert_true(response.ok, 'BAD REQUEST!!!!!, Response obtained is: {} {}'.format(response.status_code, response.co... |
from datetime import datetime
import importlib
from optparse import make_option
from dateutil import parser
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
import pytz
class Command(BaseCommand):
args = '<start_date end_date>'
... |
import glob
import os.path
import re
import tempfile
import zipfile
from typing import *
import click
import pros.common.ui as ui
import pros.conductor as c
from pros.common.utils import logger
from pros.conductor.templates import ExternalTemplate
from .common import default_options, template_query
from .conductor im... |
"""Test class for module_streams UI
:Requirement: module_streams
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: ContentManagement
:Assignee: ltran
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import pytest
from fauxfactory import gen_string
from nailgun import entities
from ... |
import logging
from typing import Dict
from typing import Iterable
from typing import List
from typing import Tuple
from typing import Type
from service_configuration_lib import read_service_configuration
from paasta_tools import utils
from paasta_tools.utils import deep_merge_dictionaries
from paasta_tools.utils imp... |
# -*- coding: utf-8 -*-
"""
FFmpeg Wrapper
Released under the MIT license
Copyright (c) 2014, Ian Bird
@category misc
@version $Id: 1.7.0, 2016-08-22 14:53:29 ACST $;
@author Ian Bird
@license http://opensource.org/licenses/MIT
"""
import os
import re
import subprocess
import database
import logger
cl... |
"""
SoftLayer.config
~~~~~~~~~~~~~~~~
Handles different methods for loading configuration for the API bindings
:license: MIT, see LICENSE for more details.
"""
import os
import os.path
from SoftLayer import utils
def get_client_settings_args(**kwargs):
"""Retrieve client settings from user-suppl... |
"""Ctags execution and output parsing functionality
"""
import os
import sys
import tempfile
from contextlib import contextmanager
from enki.core.core import core
import enki.lib.get_console_output as gco
class FailedException(UserWarning):
"""Tags generation failed.
Module API exception
"""
pass
... |
from tempest.lib.services.network import base
class SubnetpoolsClient(base.BaseNetworkClient):
def list_subnetpools(self, **filters):
uri = '/subnetpools'
return self.list_resources(uri, **filters)
def create_subnetpool(self, **kwargs):
uri = '/subnetpools'
post_data = {'subn... |
from enigma import eServiceReference, getBestPlayableServiceReference
from ServiceReference import ServiceReference
from info import getInfo
from urllib import unquote, quote
import os
import re
from Components.config import config
from twisted.web.resource import Resource
class GetSession(Resource):
def GetSID(self,... |
"""Filename matching with shell patterns.
fnmatch(FILENAME, PATTERN) matches according to the local convention.
fnmatchcase(FILENAME, PATTERN) always takes case in account.
The functions operate by translating the pattern into a regular
expression. They cache the compiled regular expressions for speed.
The function... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... |
#!/usr/bin/python3
#author = 'zeek'
import urllib.request
import urllib.parse
import mylog
import json
import time
ZHANQI_URL = 'http://www.zhanqi.tv'
CAPTCHA_URL = '/api/auth/user.captcha'
LOGIN_URL = '/api/auth/user.login'
opener = urllib.request.build_opener()
opener.addheaders = [('appVersion', '2.5.9'),
... |
# -*- coding: utf-8 -*-
from classytags.arguments import Argument, MultiValueArgument
from classytags.core import Options, Tag
from classytags.helpers import InclusionTag
from classytags.parser import Parser
from cms.models import Page, Placeholder as PlaceholderModel
from cms.plugin_rendering import render_plugins, re... |
from mock import MagicMock, patch
from pretend import stub
import helga_versionone
from .util import V1TestCase
class TestCommands(V1TestCase):
def test_no_patching(self):
# settings are patched
from helga_versionone import settings
assert settings.VERSIONONE_URL == 'https://www.example.... |
"""
Death Streams Addon
Copyright (C) 2017 Mr.Blamo
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 the License, or
(at your option) any later version.
... |
import os
import tvm
import numpy as np
from tvm import relay
from tvm.relay.scope_builder import ScopeBuilder
from tvm.relay.testing.config import ctx_list
from tvm.relay.prelude import Prelude
import pytest
def check_result(args, expected_result, mod=None):
"""
Check that evaluating `expr` applied to the ar... |
"""Config validation helper for the automation integration."""
import asyncio
import importlib
import voluptuous as vol
from homeassistant.components.device_automation.exceptions import (
InvalidDeviceAutomationConfig,
)
from homeassistant.config import async_log_exception, config_without_domain
from homeassistan... |
import os
import shutil
import unittest
import scrape_wiki as sc
class TestScraper(unittest.TestCase):
def test_get_query_params(self):
file = open("dummy_file.txt", 'w')
test_res = sc.Scraper(
"dummy_file.txt",
"https://hi.wikipedia.org/w/api.php").get_query_params(
... |
"""The **splunklib.data** module reads the responses from splunkd in Atom Feed
format, which is the format used by most of the REST API.
"""
from __future__ import absolute_import
import sys
from xml.etree.ElementTree import XML
from splunklib import six
__all__ = ["load"]
# LNAME refers to element names without na... |
""" Data Commons Python API Query Module.
Implements functions for sending graph queries to the Data Commons Graph.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datacommons.utils import _API_ROOT, _API_ENDPOINTS, _ENV_VAR_API_KEY
import json
i... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
lasmergePro.py
---------------------
Date : October 2014
Copyright : (C) 2014 by Martin Isenburg
Email : martin near rapidlasso point com
***************... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
from binascii import crc32 as CRC32
from core import dbmysql
from core.err_code import USER_ALREADY_EXIST, UNACCP_PARAS, USER_NOT_EXIST
from models.Account import *
from models.Common import DEFAULT_ACCOUNT
from utils.commonUtil import b64_decode
AUTHKEY_TIMEOU... |
import os
from twisted.python import log
from buildslave import runprocess
from buildslave.commands.base import SourceBaseCommand
class BK(SourceBaseCommand):
"""BitKeeper-specific VC operation. In addition to the arguments
handled by SourceBaseCommand, this command reads the following keys:
['bkurl']... |
# -*- coding: utf-8 -*-
"""File data provider."""
import re
from typing import Any, Optional
from mimesis.data import EXTENSIONS, MIME_TYPES
from mimesis.enums import FileType, MimeType
from mimesis.locales import Locale
from mimesis.providers.base import BaseProvider
from mimesis.providers.text import Text
__all__... |
# -*- coding: utf-8 -*-
"""
Dummy implementation for switching interface.
Qudi 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 the License, or
(at your option) any later version.
Qudi is dist... |
from nova.tests.integrated.v3 import api_sample_base
class AggregatesSampleJsonTest(api_sample_base.ApiSampleTestBaseV3):
extension_name = "os-aggregates"
def test_aggregate_create(self):
subs = {
"aggregate_id": '(?P<id>\d+)'
}
response = self._do_post('os-aggregates', 'a... |
from __future__ import absolute_import, division
import cgi
import contextlib
import csv
import json
import os
import os.path
import urllib
from twisted.python import log
from twisted.web import http
from twisted.web import resource
from shinysdr.types import EnumT, to_value_type
_NO_DEFAULT = object()
_json_colum... |
"""Views for the ``multilingual_news`` app."""
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.utils.decorators impo... |
import os
import time
import argparse
import random
import txaio
txaio.use_twisted()
import netifaces
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from twisted.internet.error import ReactorNotRunning
from twisted.internet.task import LoopingCall
from autobahn.twisted.wamp ... |
import re
"""Module that handles the like features"""
from math import ceil
from re import findall
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from .time_util import sleep
import random
LIKE_TAG_CLASS = 'coreSpriteHeartOpen'
def get_like_on_feed(bro... |
"""
Preparing model:
- Install bazel ( check tensorflow's github for more info )
Ubuntu 14.04:
- Requirements:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
- Download bazel, ( https://github.com/baze... |
#!/usr/bin/env python3
from mock_decorators import setup, teardown
from flask import Flask, request
from threading import Thread
import socket
import select
import sys
import os
@setup('WiFi release ClientContext')
def setup_tcpsrv(e):
global thread
app = Flask(__name__)
def run():
global runn... |
"""The tests for the litejet component."""
import logging
import unittest
from unittest import mock
from homeassistant import bootstrap
from homeassistant.components import litejet
from tests.common import get_test_home_assistant
import homeassistant.components.scene as scene
_LOGGER = logging.getLogger(__name__)
EN... |
# -*- coding: utf-8 -*-
import re
from time import strptime, mktime, gmtime
from urlparse import urljoin
from module.network.RequestFactory import getURL
from module.plugins.internal.SimpleHoster import SimpleHoster, parseFileInfo
def getInfo(urls):
for url in urls:
html = getURL("http://www.fshare.vn/... |
#!/usr/bin/env python3
import sqlite3
import re
def main():
conn = sqlite3.connect('latin-db.sqlite3')
cur = conn.cursor()
cur.execute("SELECT id FROM words;")
word_ids = cur.fetchall()
count_map = {}
for id in word_ids:
count_map[id[0]] = 0
f = open('aeneid_counts.txt', 'r')
... |
"""Hyperbolic DQN agent."""
import collections
import math
from dopamine.agents.dqn import dqn_agent
import gin
import tensorflow.compat.v1 as tf
from hyperbolic_discount import agent_utils
from hyperbolic_discount.replay_memory import circular_replay_buffer
from tensorflow.contrib import slim
@gin.configurable
cl... |
# -*- coding: utf-8 -*-
import os
import logging
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import jinja2
import webapp2
from authomatic import Authomatic
from authomatic.adapters import Webapp2Adapter
if 'development' in os.environ['SERVER_SOFTWARE'].lower():
import config
logging.info('imported... |
from wtforms import fields
from peewee import (DateTimeField, DateField, TimeField,
PrimaryKeyField, ForeignKeyField, BaseModel)
from wtfpeewee.orm import ModelConverter, model_form
from flask.ext.admin import form
from flask.ext.admin._compat import iteritems, itervalues
from flask.ext.admin.mod... |
import scrapy
import re
from research.items import ResearchItem
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class CaltechSpider(scrapy.Spider):
name = "PSU"
allowed_domains = ["eecs.psu.edu"]
start_urls = [
"http://www.eecs.psu.edu/research/Facilities/EECS-Research-Labs-Communications-Networking.aspx",... |
# C:\home\eric\wrk\scipy\weave\examples>python functional.py
# desired: [2, 3, 4]
# actual: [2, 3, 4]
# actual2: [2, 3, 4]
# python speed: 0.039999961853
# SCXX speed: 0.0599999427795
# speed up: 0.666666666667
# c speed: 0.0200001001358
# speed up: 1.99998807913
fr... |
"""Routines common to Linux and OSX."""
from __future__ import division
import os
import subprocess
__all__ = ['executable_is_in_path', 'list2cmdline', 'execute_cmdline',
'get_executable_path', 'execute_piped_cmdlines', 'execute_cmdline2']
#################################################################... |
import random
from collections import defaultdict
from heapq import nlargest
from luigi import six
import luigi
import luigi.contrib.hadoop
import luigi.hdfs
import luigi.postgres
class ExternalStreams(luigi.ExternalTask):
"""
Example of a possible external data dump
To depend on external targets (typi... |
class Color:
"""Describes a color."""
COLOR_SPACE_NAME_SRGB="sRGB"
COLOR_SPACE_NAME_CALIBRATED="Calibrated"
def __init__(self, r=0, g=0, b=0, a=255, color_space="sRGB"):
"""Create a color.
r: Red, in 0-255
g: Green, in 0-255
b: Blue, in 0-255
a: Alpha, ... |
# -*- coding: utf-8 -*-
"""Functional tests using WebTest.
See: http://webtest.readthedocs.org/
"""
import pytest
from flask import url_for
from dhmn_demo.user.models import User
from .factories import UserFactory
class TestLoggingIn:
def test_can_log_in_returns_200(self, user, testapp):
# Goes to hom... |
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import fnmatch
import numpy
import pytest
from lasio import read
from lasio import exceptions
test_dir = os.path.dirname(__file__)
egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn)
stegfn = lambda vers, fn: os.pa... |
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
import os
import sys
class Command(BaseCommand):
option_list = BaseCommand.option_list + ()
help = "Starts a Tornado Web."
args = '[optional port number, or ipaddr:port]'
def handle(self, addrp... |
"""
Support for LaMetric time.
This is the base platform to support LaMetric components:
Notify, Light, Mediaplayer
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/lametric/
"""
import logging
import voluptuous as vol
import homeassistant.helpers.conf... |
#!/usr/bin/env python3
"""Remote execution for preprocess_corpus.py."""
from __future__ import absolute_import, division, print_function
try:
from itertools import izip_longest as zip_longest
from itertools import izip as zip
except:
from itertools import zip_longest
from io import StringIO
import os
im... |
from typing import TYPE_CHECKING
from twisted.web.resource import Resource
from twisted.web.server import Request
from unpaddedbase64 import encode_base64
from sydent.db.invite_tokens import JoinTokenStore
from sydent.http.servlets import get_args, jsonwrap
from sydent.types import JsonDict
if TYPE_CHECKING:
fro... |
from PyQt5.Qt import QHBoxLayout, QWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView
def default_size_hint(ans):
ans.setWidth(400), ans.setHeight(600)
return ans
class DevTools(QWebEngineView):
def __init__(self, parent=None):
QWebEngineView.__init__(self, parent)
def set_inspecte... |
import math
import numpy
from safe.impact_functions.earthquake.itb_earthquake_fatality_model import (
ITBFatalityFunction)
from safe.common.utilities import ugettext as tr
from safe.common.utilities import get_defaults
class PAGFatalityFunction(ITBFatalityFunction):
"""
Population Vulnerability Model Pa... |
import time
import logging
from coaplrucache import CoapLRUCache
from coapthon import utils
from coapthon.messages.request import *
__author__ = 'Emilio Vallati'
logger = logging.getLogger(__name__)
class Cache(object):
def __init__(self, mode, max_dim):
"""
:param max_dim:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import platform
fid = open('README.md','w')
fid.write('''# DataMining
Some scripts about Data Mining and Machine Learning.
In this repository:
1. There are some diplomas which were got from Coursera MOOC platform.
2. Also, I have finished a scraper b... |
from osv import osv, fields
class res_company(osv.osv):
_name = "res.company"
_inherit = 'res.company'
_columns = {
'currency2_id' : fields.many2one('res.currency', string="Secondary Currency"),
} |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './Debugger/StartCoverageDialog.ui'
#
# by: PyQt5 UI code generator 5.3.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_StartCoverageDialog(object):
def setupUi(self, S... |
import asyncio
import websockets
class BroadcastHandler(object):
clients = []
@asyncio.coroutine
def listener(self, websocket, path):
self.clients.append(websocket)
print("{} clients are connected".format(len(self.clients)))
while True:
message = yield from websocket.r... |
#######################################
# Title: Get and Delete group members
# Description: Gets a list of member IDs and deletes them from the group.
# Update community base URL, username, and password.
# Python Version: 2.7
# Jive Rest API: v3
# GitHub Repository: https://github.com/thales007/Jive-Community-Ma... |
__title__ = "_CommandElementFluid1D"
__author__ = "Ofentse Kgoa"
__url__ = "http://www.freecadweb.org"
## @package CommandFemElementFluid1D
# \ingroup FEM
import FreeCAD
from FemCommands import FemCommands
import FreeCADGui
from PySide import QtCore
class _CommandFemElementFluid1D(FemCommands):
"The FEM_Elemen... |
from __future__ import division, print_function, absolute_import
import numpy
from . import _ni_support
from . import _nd_image
__all__ = ['fourier_gaussian', 'fourier_uniform', 'fourier_ellipsoid',
'fourier_shift']
def _get_output_fourier(output, input):
if output is None:
if input.dtype.typ... |
from __future__ import absolute_import, division, print_function
import muninn
from .utils import create_parser, parse_args_and_run
def prepare(args):
with muninn.open(args.archive) as archive:
if args.dry_run:
print("The following SQL statements would be executed:")
for sql in a... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas
import logging
import time
import argparse
import sys
import unicodedata
# CVE_ENT: clave de la entidad
# CVE_MUN: clave del municipio
# CVE_LOC: clave de localidad
# NOM_LOC: nombre de la localidad
# CVE_ENT: clave de la entidad
# NOM_ENT: nombre de la entidad... |
import sys
import os
import syslog
from rozofs.core.agent import AgentServer
from rozofs.core.storaged import StoragedAgent
from rozofs.core.exportd import ExportdAgent, ExportdPacemakerAgent
from rozofs.core.constants import STORAGED_MANAGER, EXPORTD_MANAGER, \
ROZOFSMOUNT_MANAGER
from rozofs.core.rozofsmount imp... |
"""rc3e_manager URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author: Thiago Lopes Trugillo da Silveira
Date: July 7, 2015
Description:
I. The EDF class was implemented for reading EDF files in Python. It was successfully tested with recordings from [1].
This class is an extension of the implementation available in https://gi... |
"""Provides IO for the emcee sampler.
"""
from .base_sampler import BaseSamplerFile
from .posterior import PosteriorFile
class CPNestFile(BaseSamplerFile):
"""Class to handle file IO for the ``cpnest`` sampler."""
name = 'cpnest_file'
def write_resume_point(self):
pass
def write_niterations... |
"""
Algorithmic Thinking 1
wk 4
Aplication #2
Questions
"""
# imports
import urllib2
import random
import time
import math
import UPATrial
import numpy
from collections import deque
import matplotlib.pyplot as plt
############################################
def copy_graph(graph):
"""
Make... |
from flask import Blueprint
from flask import session, escape, redirect, url_for, render_template, request
from hashlib import sha256
from datetime import datetime
from model import mongo
page = Blueprint('admin_page', __name__,
template_folder='templates')
def is_login():
return 'username' in session
... |
"""Get a file, chunk by chunk. Minion side."""
import sys
import sha
import func_module
try:
# py 2.4
from base64 import b64encode
except ImportError:
# py 2.3
from base64 import encodestring as b64encode
class GetFile(func_module.FuncModule):
"""Get a file, chunk by chunk"""
def chunkslen(self, filen... |
from sqlalchemy import util, exceptions
import types
from sqlalchemy.orm import mapper, Query
def _monkeypatch_query_method(name, ctx, class_):
def do(self, *args, **kwargs):
query = Query(class_, session=ctx.current)
util.warn_deprecated('Query methods on the class are deprecated; use %s.query.%s ... |
#!/usr/bin/env python
import device
import apptest
import launch
import log
import argparse
import os
import config
import base64
import logging
import crawl
import replay
import traceback
#bugname = "oix1"
#bugname = "oi451"
#bugname = "oi403"
#bugname = "kpd130"
#bugname = "kpd61"
#bugname = "kpdx2"
#bugname = "cb1... |
from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm.exc import NoResultFound
def create_database(uri: str, base):
engine = create_engine(uri)
... |
"""
Utility for creating **accounts.yaml** file for concurrent test runs.
Creates one primary user, one alt user, one swift admin, one stack owner
and one admin (optionally) for each concurrent thread. The utility creates
user for each tenant. The **accounts.yaml** file will be valid and contain
credentials for created... |
"""
"""
import csv
import scipy as SP
import scipy.linalg as LA
import pdb
import lmm_lasso_pg_a as lmm_lasso
import os
# load genotypes
X = SP.array(list(csv.reader(open('geno.csv','rb'),
delimiter=','))).astype(float)
[n_f,n_s] = X.shape
for i in xrange(n_f):
m=X[i].mean()
std=X... |
import datetime
import isodate
import unittest
from pulp.common import dateutils
# test timezones and timezone conversions
_zero = datetime.timedelta(0)
_one_hour = datetime.timedelta(hours=1)
class _StdZone(datetime.tzinfo):
def __init__(self, utc_offset=0):
self.utc_offset = utc_offset
def dst(... |
import calendar
import commands
from config import bindIp as interfaceIp
from config import myIpAddress as hostName
from config import YAMLConfig as ConfigModel
import data.blocks
import data.clients
import data.players
import datetime
import json
import os
import plugins
from plugins import commands as pluginCommand... |
#!/usr/bin/env python
import json
import logging
import time
from minecraft_query import MinecraftQuery
class reportGenerator():
def __init__(self, sfilename):
sfile = open(sfilename)
self.serverlist = json.load(sfile)
sfile.close()
def _query(self, hosts):
logging.debug("Begin... |
import logging
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker, mapper, SessionExtension, scoped_session
from sqlalchemy.pool import SingletonThreadPool, QueuePool
import karesansui
from karesansui.db.model import reload_mappers
#: SQLAlchemy#Engine
__engine = None
class Kares... |
"""
Data structures for manipulating Chip's Challenge (CC) data
Created for the class Programming for Game Designers
"""
BYTE_ORDER = "little"
class CCField:
"""The base field class
Member vars:
type_val (int): the type identifier of this class (set to 3)
byte_val (bytes): the byte data of the... |
print "Welcome to RecoDev-Evaluator4!"
base_path = sys.argv[1]
project_name = sys.argv[2]
#new_issue_text = sys.argv[3]
print "#4. Evaluation of the *hybrid* recommendation engine using single-label (i.e., normal) classification ***PLUS web and social networks data***..."
print "The similarity measure of the collabor... |
import csv
import logging
import re
import collections
import ast
ValidationResult = collections.namedtuple('ValidationResult', ['success', 'keys'])
class IllegalPropertyName(Exception):
pass
def validate_metadata_from_csv(path):
"""
Check if metadata is ok
:param path:
:return: true / false
... |
"""Script analise_tipos -- faz uma análise dos tipos de proposições votadas em 2011"""
import proposicoes
proposicoes = proposicoes.parse_html()
pl = plp = pdc = mpv = pec = 0
for prop in proposicoes:
if (prop['tipo'] == 'PL'):
pl += 1
elif (prop['tipo'] == 'PLP'):
plp += 1
elif (prop['tipo'] == 'PDC')... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
import django.core.validators
import django.contrib.auth.models
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.