content stringlengths 4 20k |
|---|
"""
Contains a list of lists that will be used as the DDT arguments for the studio test.
"""
ddt_scenarios = [
[
'Poll Studio',
'answer',
4,
'label.poll-answer-text'
],
[
'Survey Studio',
'answer',
5,
'th.survey-answer'
],
[
'Su... |
import os
import hashlib
from dropbox.session import DropboxSession
from dropbox.client import DropboxClient
from dropbox.rest import ErrorResponse
from tests.utils import driver
from onitu.utils import u, b, get_random_string
from onitu_dropbox.dropbox_driver import (ONITU_APP_KEY,
... |
from itertools import chain
from datadog_checks.dev import get_docker_hostname, get_here
from datadog_checks.dev.utils import ON_MACOS, ON_WINDOWS
from datadog_checks.sqlserver import SQLServer
from datadog_checks.sqlserver.const import (
AO_METRICS,
AO_METRICS_PRIMARY,
AO_METRICS_SECONDARY,
DATABASE_F... |
import os
import configparser
import logging
import traits.api as t
import matplotlib.pyplot as plt
from pathlib import Path
from hyperspy.misc.config_dir import config_path, data_path
from hyperspy.misc.ipython_tools import turn_logging_on, turn_logging_off
from hyperspy.ui_registry import add_gui_method
defaults_... |
from libravatar import settings
# Default useful variables for the base page template.
# pylint: disable=unused-argument
def basepage(request):
context = {}
context['avatar_url'] = settings.AVATAR_URL
context['contact_us'] = settings.CONTACT_US
context['dev_email'] = settings.DEV_EMAIL
context['di... |
#
# camManager.py
# camManager - Raspberry Pi Video Manager
# Make live updates to the picamera object
#
# Created by Jeremy Noonan on 10/12/2014
import socket
import time
import ast
import picamera
from PIL import Image
class camManager(object):
isRunning = False
quadrants = [(0,0,0.5,0.5), (0.5,0,0.5,0.5), (... |
__author__ = 'tarciso'
import subprocess
class LinuxUtils():
@staticmethod
def runLinuxCommand(command):
print command
proc = subprocess.Popen(command,stdout=subprocess.PIPE,shell=True)
return (proc.communicate(),proc.returncode)
@staticmethod
def checkPathExists(path):
... |
from socketserver import ThreadingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler
import datetime
import ssl
import traceback
import threading
import json
import socket
from logger import getLogger
logger = getLogger(__name__)
class webHook(threading.Thread):
class ReqHandler(BaseHTTPRequestHandl... |
import datetime
import requests
from lxml import etree
from lxml.html import soupparser
import coursescalendar
import locations
class SisALoginError(Exception):
def __init__(self, reason):
Exception.__init__(self, reason)
self.reason = reason
def __str__(self):
return self.reason
... |
""" robotparser.py
Copyright (C) 2000 Bastian Kleineidam
You can choose between two licenses when using this package:
1) GNU GPLv2
2) PSF license for Python 2.2
The robots.txt Exclusion Protocol is implemented as specified in
http://www.robotstxt.org/norobots-rfc.txt
"""
import urlparse
imp... |
#!/usr/bin/env python3
"""
Expected directory structure:
<BASE_PATH>/courses/<SEMESTER>/<COURSES>/submissions/<HW>/<WHO>/<VERSION#>
This script will find all submissions that match the provided
pattern and add them to the grading queue.
USAGE:
regrade.py <one or more (absolute or relative) PATTERN PATH>
"""
im... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 15:17:26 2020
@author: rish-r
"""
from config import *
from initialize_arango import *
from ontology_mapper import *
from arango import ArangoClient, ArangoServerError, DocumentInsertError
import json
import requests
import time
import gzip
from pathlib import Path
... |
"""Testing the web package."""
import pytest
from leopard_lavatory import web
@pytest.fixture
def client():
"""Create testing client for other tests."""
app = web.create_app()
app.config['TESTING'] = True
app.secret_key = 'testing'
yield app.test_client()
def test_index_get(client):
"""Che... |
from collections import namedtuple
from copy import deepcopy
from redux.ast import FunctionDefinition, BitfieldDefinition, ReturnStmt, Assignment, VarRef
from redux.intrinsics import get_intrinsic_functions, IntrinsicFunction, GetAchronalField, SetAchronalField
from redux.types import is_numeric, common_arithmetic_type... |
#Authors Bhargav K,SriVennelaVaishnapu
#Email <EMAIL>
#Error Diffusion Algorithm
#error = actualColour - nearestColour
#PutPixelColour(x+1, y ) = Truncate(GetPixelColour(x+1, y ) + 0.5 * error)
#PutPixelColour(x , y+1) = Truncate(GetPixelColour(x , y+1) + 0.5 * error)
#Procedure Truncate(value)
# If value < 0 The... |
'''Basic classes and functions for Wikidata items.'''
import re
from typing import Text
import attr
from shapely.geometry.point import Point
# Regular expression to pull the latitude and longitude out of a Point that is
# represented as a string. Ignores situation where multiple points are provided,
# taking just th... |
"""Application-specific settings."""
import os
from django.conf import settings as _settings
from django.core.exceptions import ImproperlyConfigured
###############################################################################
# Single settings.
######################################################################... |
import os
import os.path
import re
from unittest import TestCase
# Require TestCase to have subTest().
if not hasattr(TestCase, "subTest"):
from unittest2 import TestCase
import responses
from clarify.jurisdiction import Jurisdiction
COUNTIES_AR = [
"Adair",
"Allen",
"Anderson",
"Ballard",
... |
from spacy.lang.vi import Vietnamese
from ...util import make_tempdir
def test_vi_tokenizer_serialize(vi_tokenizer):
tokenizer_bytes = vi_tokenizer.to_bytes()
nlp = Vietnamese()
nlp.tokenizer.from_bytes(tokenizer_bytes)
assert tokenizer_bytes == nlp.tokenizer.to_bytes()
assert nlp.tokenizer.use_py... |
# -*- encoding:utf-8 -*-
from __future__ import unicode_literals
MESSAGES = {
"%d min remaining to read": "",
"(active)": "",
"Also available in:": "Također dostupno i u:",
"Archive": "Arhiva",
"Categories": "Kategorije",
"Comments": "Komentari",
"LANGUAGE": "hrvatski",
"Languages:": "J... |
from nbodykit.source.mesh.catalog import CatalogMesh
from nbodykit import _global_options
import numpy
import logging
import warnings
# for converting from particle to mesh
from pmesh.pm import RealField
from nbodykit.utils import attrs_to_dict
class MultipleSpeciesCatalogMesh(CatalogMesh):
"""
A subclass of ... |
import re
from functions import *
#Initialization of variables
separators = [u"|"]
ending_words = []
decoded_ending_words = []
hyponyms = []
words_for_relations=[]
related_words=[]
count=0
count_diff=0
index=0
output=''
#...........................
# Preprocessing
words_for_relations.append([unichr(i) for i in [2344,... |
{
'name': 'Sale Order Line',
'version': '1.0',
'category': 'Sales',
'sequence': 19,
'summary': 'Sale Order Line',
'description': """
Standard OpenERP manages Sales by Orders.
In Sales Module after Sales Order Menu,
it was added Sales by Product Menu.
User will open a tree vi... |
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
# Global Definitions
u_0 = 4 * np.pi * 10**-7
# Integratttiionn
def norm( vect ):
return np.linalg.norm(vect)
def Biot_Savare(R, I, pos):
#inner = integrate.dblquad( lambda dlx, dly: np.linalg.norm(np.cross( [dlx, dly, 0], [pos[0... |
from json import dumps
from flask import Blueprint, redirect, request
from .doc import auto
frontend = Blueprint('frontend', __name__, url_prefix='/blog')
users = []
posts = []
class User(object):
def __init__(self, username):
self.username = username
users.append(self)
self.id = use... |
#!/usr/bin/env python
#
# Generated by generateDS.py.
#
import sys
import simpletypes_other2_sup as supermod
etree_ = None
Verbose_import_ = False
( XMLParser_import_none, XMLParser_import_lxml,
XMLParser_import_elementtree
) = range(3)
XMLParser_import_library = None
try:
# lxml
from lxml import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""iris query parser tests."""
from unittest import TestCase
from iris.query import parser as q
ME = q.FullFirstMatchException
class TokenTestCase(TestCase):
"""Like a regular TestCase, but with some extra asserts."""
def assertToken(self, token, type, name=None... |
# Посимвольный вывод символов
def VyvestiStrokuPosimvolno(stroka):
dlina = len(stroka)
i = 0
while i < dlina:
tekSimvol = stroka[i]
paste(tekSimvol)
i = i + 1
# Паузы
ShortBreak = 1
MiddleBreak = 3
BigBreak = 5
step = sys.argv[1]
# Открытие текстового редактора
if step == "1":
... |
from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.rst'), encoding='utf-8') as... |
"""
Multiplexed-Rhizi instance configuration generator:
- generate Apache instance configuration files
- generate Neo4j instance, instance configuration files
- generate Rhizi instance configuration files
This tool currently does not handle module confdir/rootdir creation, file mode/ownership creation,
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='carro',
fields=[
('id', models.AutoField(verbos... |
from datetime import datetime
import threading
from sqlalchemy import Column, String, DateTime
from bigorna.commons.config import Config
from bigorna.commons.event_bus import bus, Event
from bigorna.tasks import TaskDefinition, Status, task_status_changed_evt
from bigorna.tracker.persistence import get_sessionmaker
... |
from gattlib import GATTRequester, DiscoveryService
from time import sleep
#
# CONSTANTS
#
# BUTTONS
TOP = 0
ONE = 1
TWO = 2
THREE = 3
ANY = 99
# SOUNDS
BYEBYE = 'BO_V7_VARI'
COOL = 'COOL '
HAHA = 'HAPPYLAUGH'
HI = 'DASH_HI_VO'
LETSGO = 'LETS_GO'
TRUMPET = 'TRUMPET_01'
TAHD... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import tokenize
from pants.backend.python.tasks.checkstyle.common import CheckstylePlugin
# TODO(wickman) Update this to sanitize line continuation styling as we ha... |
import re
from urlparse import urljoin
from w3lib.html import remove_tags, replace_entities, replace_escape_chars
from scrapy.link import Link
from .sgml import SgmlLinkExtractor
linkre = re.compile(
"<a\s.*?href=(\"[.#]+?\"|\'[.#]+?\'|[^\s]+?)(>|\s.*?>)(.*?)<[/ ]?a>",
re.DOTALL | re.IGNORECASE)
def... |
#!/usr/local/bin/python
import sys
import pymongo
import argparse
from bson import ObjectId
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
import bottle
from bottle import Bottle, redirect, request, response, static_file, request
from bson.json_util import dumps
import author... |
class Actor(object):
''' Represent something which can act -- perhaps a character, perhaps a mob, perhaps...?'''
def __init__(self, name, hp=100, attack_weight=0, attack_damage=0, defense_weight=0, defense_damage=0):
self._items = []
self._name = name
self._attack_weight = attack_weight... |
from openerp.tools.translate import _
from openerp.osv import orm, fields
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
import time
import re
class L10nEsAeatReport(orm.Model):
_name = "l10n.es.aeat.report"
_description = "AEAT report base module"
def on_change_company_id(self, cr, uid, ids, c... |
import rospy
import roslib, roslib.message
import rosnode
from monarch_situational_awareness.msg import ReaderProperties
from monarch_situational_awareness.srv import CreateReader
from monarch_situational_awareness.srv import CreateReaderResponse
from monarch_situational_awareness.srv import GetSlotInfo
class SAMRead... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import io
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with io.open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()... |
import binascii
import base64
import umsgpack
from collections import namedtuple
from storjnode.util import node_id_to_address, address_to_node_id
from storjnode.common import PROTOCOL_VERSION
from storjnode.common import MAX_PACKAGE_DATA
MAX_MESSAGE_DATA = MAX_PACKAGE_DATA - 29 # max data - message call overhead
... |
#!/usr/bin/python
"""
print p4configs.depots
for d in p4config.depots:
print p4configs.depot[d]
print p4configs.depot[d]['p4port']
to use a generated module:
import myconfig
print myconfig.keys
for i in myconfig.keys:
print myconfig.data
"""
import sys
import re
import optparse
import cx... |
from __future__ import division
from vistrails.db.domain import DBPluginData
import unittest
import copy
import random
from vistrails.db.domain import IdScope
import vistrails.core
class PluginData(DBPluginData):
##########################################################################
# Constructors and c... |
from utils import *
def grid_values(grid):
"""Convert grid string into {<box>: <value>} dict with '.' value for empties.
Args:
grid: Sudoku grid in string form, 81 characters long
Returns:
Sudoku grid in dictionary form:
- keys: Box labels, e.g. 'A1'
- values: Value in corr... |
from unittest import TestCase
import validictory
class TestProperties(TestCase):
props = {
"prop01": {"type":"string"},
"prop02": {"type":"number", "optional":True},
"prop03": {"type":"integer"},
"prop04": {"type":"boolean"},
"prop05": {
"type":"object",
... |
"""
Copyright 2017 Oliver Smith
This file is part of pmbootstrap.
pmbootstrap 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.
pmbootstrap ... |
import os
import third_party.json_schema_compiler.model as model
import docs_server_utils as utils
class APIListDataSource(object):
""" This class creates a list of chrome.* APIs and chrome.experimental.* APIs
for extensions and apps that are used in the api_index.html and
experimental.html pages.
|api_path| ... |
import os
import sys
try:
sys.path.insert(0, os.getenv('PNP_HOME')+'/PNPnaoqi/py')
except:
print "Please set PNP_HOME environment variable to PetriNetPlans folder."
sys.exit(1)
import pnp_cmd_naoqi
from pnp_cmd_naoqi import *
p = PNPCmd()
p.begin()
p.exec_action("say", "What's_your_name?")
p.exec_acti... |
'''
Created on May 25, 2011
@author: bzcseife
This is a python ganglia plugin which monitors the status of an OSD service of the XtreemFS
filesystem. It is intend to run on the same host as the OSD and gathers information of the OSD per
SNMP. Therefore you have to configure your OSD to provide a SNMP Agent on this h... |
import operator
import sifter.grammar
import sifter.validators
__all__ = ('TestSize',)
# section 5.9
class TestSize(sifter.grammar.Test):
RULE_IDENTIFIER = 'SIZE'
COMPARISON_FNS = {
'OVER' : operator.gt,
'UNDER' : operator.lt,
}
def __init__(self, arguments=None, te... |
from __future__ import absolute_import
import mock
import db.exceptions
from webserver.testing import AcousticbrainzTestCase
from webserver.testing import DB_TEST_DATA_PATH
from flask import url_for
import os
class LegacyViewsTestCase(AcousticbrainzTestCase):
def test_submit_low_level(self):
mbid = '0d... |
#!/usr/bin/python2.6
# -*- coding: utf8 -*-
"""
name: config.py
Module holding param values that might be reloaded without restarting the dispatcher
The dispatcher handles a "reconfig" request wich ask the worker application to reload the source config file and recreate the conf object
Basic usage:
import singl... |
import json
import base64
import urllib
import urllib.request
import urllib.error
class Api:
def __init__(self, user, token):
self.user = user
self.token = token
def aqi_request(self, url, retry=True):
req = urllib.request.Request(url)
if self.token:
auth = base... |
from __future__ import print_function
from bcc import BPF
from time import sleep
from sys import argv
def usage():
print("USAGE: %s [time]" % argv[0])
exit()
interval = 99999999
if len(argv) > 1:
try:
interval = int(argv[1])
if interval == 0:
raise
except: # also catches -h... |
from __future__ import absolute_import
import six
from sentry.utils.http import absolute_uri
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.exceptions import ResourceDoesNotExist
from sentry.models import ... |
# -*- coding: utf-8 -*-
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time, unittest
def is_alert_present(wd):
try:
wd.switch_to_alert().text
return True
except:
return False
class text_megic(unittes... |
#!/usr/bin/env py27
from ecmwfapi import ECMWFDataServer
import numpy as np
import datetime as dt
import calendar
server = ECMWFDataServer()
dir = "/automount/agh/Projects/skiefer/"
year_first = 1957
year_last = 1957
years_vec = np.arange(year_first, (year_last + 1))
months_vec = np.arange(1, 13)
for i in range(... |
"""
This module is installed as the `shuup_admin` template function namespace.
"""
import itertools
from django.conf import settings
from django.core.urlresolvers import NoReverseMatch, reverse
from django.middleware.csrf import get_token
from django.utils.lru_cache import lru_cache
from django.utils.text import forc... |
from biicode.common.exception import (AuthenticationException, NotFoundException,
ServerInternalErrorException, BiiRequestRedirectionException,
BiiRequestErrorException, ForbiddenException,
BiiException, Pu... |
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
from django_webtest import WebTest
from guardian.shortcuts import assign_perm
from .base import GrootTestMixin
from .models import Author
class TestAccessGroupPermissions(GrootTestMixin, WebTest):
def s... |
#!/usr/bin/env python
import urllib2
import zipfile
import os
#from os.path import abspath, dirname, join, getsize
#from os.path import exists
#from os import mkdir
PREFIX = '/opt/mingw/test'
CACHE = os.path.join(PREFIX, 'cache')
# runable from any location, not only CWD
SCRIPT_PREFIX = os.path.dirname(os.path.abspa... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'NewItemDetails.ui'
#
# Created by: PyQt5 UI code generator 5.7.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_NewItemDetails(object):
def setupUi(self, NewItemDetails):
... |
"""Module for simulating data for ``mapmuts`` package.
This module contains function to simulate data that can be analyzed
by the ``mapmuts`` package. This simulated data can be useful for
testing the package's performance.
Use the `Seed` function if you want to ensure repeatable output.
Written by Jesse Bloom.
Li... |
# -*- coding: utf-8 -*-
import logging
import sys
import os
from datetime import datetime
from ebay_tweet_bot import Config, EbayParser, Tweeter
def main():
# get full file paths in case script is called from another dir
dir_path = os.path.dirname(sys.argv[0])
log_file_path = os.path.join(dir_path, 'ebay_... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from .. import Rule
#-----------------------------------------------... |
"""
Rule that checks for a family that is an ancestor of a specified family.
"""
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from .. import Rule
from ....const import GRAMPS_LOCALE as glocale
... |
import json
import os
import sys
import zipfile
from pathlib import Path
from shutil import copy
from textwrap import dedent
import asynctest
import distlib
import pytest
import run
from run import download_package
from run import extract
from run import main
from run import PackageResult
from run import read_plugins... |
import os
def fasta2dict(fasta_file, samtools, picard):
try:
print " - genome.dict"
os.system("java -jar " + picard + "/CreateSequenceDictionary.jar R=" + fasta_file + " O=" + fasta_file.replace(".fa", ".dict") + " &>/dev/null")
print " - genome.fa.fai"
os.system(samtools + " fai... |
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import re
import io
import email
import sys
import signal
import asyncio
import hashlib
import traceback
import logging
from http import client
from jinja2 import Environment, FileSystemLoader
from websockets.server import WebSocketServerProtocol
from websockets.exceptio... |
# Django
from django.core.exceptions import ObjectDoesNotExist
# local Django
from event.models import Event
from job.services import get_jobs_by_event_id, remove_empty_jobs_for_volunteer
from shift.models import Shift
from shift.services import get_volunteer_shifts_with_hours, get_unlogged_shifts_by_volunteer_id
de... |
#!/usr/bin/env python
from setuptools import setup, find_packages
DESCRIPTION = ("Python REST API for Humans.")
with open('README.rst') as f:
LONG_DESCRIPTION = f.read()
install_requires = [
'cerberus>=1.1',
'events>=0.3,<0.4',
'simplejson>=3.3.0,<4.0',
'werkzeug>=0.9.4,<=0.11.15',
'markupsafe... |
import csv
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
csvwrite = csv.writer(open('CHICAGO_DATA/CTARailLines.csv', 'wb'))
tree = ET.parse('CHICAGO_DATA/CTARailLines.kml')
root = tree.getroot()
start = root.find('Folder')
row=[]
count = 0
for segment in start... |
from formencode.validators import Invalid as InvalidForm
from tornado.web import authenticated
from tornado import escape as tornado_escape
from amonone.web.apps.core.baseview import BaseView
from amonone.sms.models import sms_model, sms_recepient_model
from amonone.web.apps.settings.forms import SMSForm, SMSRecepient... |
from dispatch.apps.frontend.helpers import templates
from dispatch.apps.frontend.models import TemplateVariable
class TemplateManager:
@staticmethod
def save_fields(article_id, template_slug, fields):
entries = [TemplateVariable(article_id=article_id, template_slug=template_slug, variable=field, value... |
"""
Copyright 2008-2011 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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 2
of the License, or (at your option) any l... |
# Longest Collatz sequence
# Problem 14
# The following iterative sequence is defined for the set of positive integers:
#
# n → n/2 (n is even)
# n → 3n + 1 (n is odd)
#
# Using the rule above and starting with 13, we generate the following sequence:
#
# 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
# It can be seen that ... |
#!/usr/bin/python
from sys import argv, stdout, stderr
import xml.dom.minidom
from libglibcodegen import NS_TP, get_docstring, \
get_descendant_text, get_by_path
class Generator(object):
def __init__(self, prefix, dom, output_base):
self.prefix = prefix + '_'
self.spec = get_by_path(dom, ... |
# Extracts information from a project that has a distutils setup.py file.
import os
import sys
import string
import logging
def parse_version(version):
vmap = {'a': 'alpha', 'b': 'beta', 'c': 'candidate'}
res = []
version = list(reversed(version))
v = ''
while version:
x = version.pop()
... |
# settings for POR
import utils as pymunk
import os
MAIN_WINDOW_WIDTH = 1024
MAIN_WINDOW_HEIGHT = 768
RESOURCE_PATH = map(os.path.abspath, ['data', 'data/images', 'data/sounds',
'data/music', 'data/other', '.', ''])
# master game FPS
MAIN_UPDATE_INTERVAL = 1.0/120.0
STARTING_LIVES = 5
ENTITY_DEFAU... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import numpy as np
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.eager import backprop
from tensorflow.python.eager import context
from tensorflow.python.eager import... |
from nailgun import consts
from nailgun import objects
from nailgun.test.base import BaseIntegrationTest
from nailgun.test.base import fake_tasks
class TestCluster(BaseIntegrationTest):
def check_no_primary_node(self, cluster, roles):
self.assertIsInstance(roles, (tuple, list))
for role in roles:... |
from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from djgeojson.views import GeoJSONLayerView
from wagtail.contrib.wagtailsitemaps.views import sitemap
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtaildocs import urls as wagtaildo... |
__author__ = 'shihhau' # Shih-Hau Tan
#
# Copyright 2016-2020 Cuemacro
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
import logging
from twisted.internet.defer import inlineCallbacks, returnValue, succeed
from juju.errors import ProviderError
from juju.providers.common.base import MachineProviderBase
from .cobbler import CobblerClient
from .files import FileStorage
from .launch import OrchestraLaunchMachine
from .machine import ma... |
import biokbase.narrative.clients as clients
from .specmanager import SpecManager
from biokbase.narrative.app_util import (
map_inputs_from_job,
map_outputs_from_state
)
import json
import uuid
from jinja2 import Template
"""
KBase job class
"""
__author__ = "Bill Riehl <<EMAIL>>"
class Job(object):
job_... |
"""
Uniform
Date: 10-Feb-16
Authors: Y.M. Dijkstra
"""
import numpy as np
import nifty as ny
from nifty.functionTemplates import FunctionBase
import copy
class UniformXF(FunctionBase):
# Variables
# Methods
def __init__(self, dimNames, data, m):
"""Initialise a uniform profile.
Args:
... |
from _objects import SchemaObject
from _pgsql import pgQuery
from wh import xlt
class View(SchemaObject):
typename=xlt("View")
shortname=xlt("View")
grantTypename='TABLE'
refreshOid="rel.oid"
allGrants='arwdDxt'
favtype='v'
relkind='v'
@staticmethod
def FindQuery(schemaName, schemaOid, patterns):
... |
import os
import logging
from framework._utils import FunctionHook
class CodeJamExtractCheat(FunctionHook):
''' This method will extract set of duplicated source codes. '''
@staticmethod
def find_plagiarism(contents):
''' returns all set of names which has same source code. '''
from coll... |
import logging
from synapse.api.errors import AuthError, SynapseError
from synapse.http.server import respond_with_html
from synapse.http.servlet import RestServlet
from ._base import client_patterns
logger = logging.getLogger(__name__)
class AccountValidityRenewServlet(RestServlet):
PATTERNS = client_patterns... |
import asyncio
import asyncpg
import os
import jinja2
import orjson
from logging import getLogger
from random import randint
from operator import itemgetter
from apidaora.asgi.app import asgi_app
from apidaora.asgi.responses import (
JSON_RESPONSE, HTML_RESPONSE, PLAINTEXT_RESPONSE
)
from apidaora.asgi.router impor... |
import errno
import os
import pytest
from wal_e.worker import prefetch
from wal_e import worker
@pytest.fixture
def pd(tmpdir):
d = prefetch.Dirs(str(tmpdir))
return d
@pytest.fixture
def seg():
return worker.WalSegment('0' * 8 * 3)
@pytest.fixture
def raise_eperm():
def raiser(*args, **kwargs):
... |
"""Automatically setup docs for a project
Call from command line:
bench setup-docs app path
"""
import os, json, frappe, shutil, re
from frappe.website.context import get_context
from frappe.utils import markdown
class setup_docs(object):
def __init__(self, app):
"""Generate source templates for models referen... |
#!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: Top Block
# Generated: Thu Jul 10 20:31:13 2014
##################################################
from PyQt4 import Qt
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import gr
fr... |
from a10sdk.common.A10BaseClass import A10BaseClass
class WebCategoryLicense(A10BaseClass):
""" :param action: {"optional": true, "enum": ["import"], "type": "string", "description": "'import': import; ", "format": "enum"}
:param file_handle: {"description": "Full path of the uploaded file", "format":... |
"""
The iHMPSession module allows users to easily establish a connection
to an Open Science Data Framwork (OSDF) instance operated for the
Integrative Human Microbiome Project (iHMP).
"""
import importlib
import logging
from osdf import OSDF
from cutlass.Util import *
class iHMPSession(object):
"""
The iHMP S... |
# Based on: http://www.djangosnippets.org/snippets/73/
#
# Modified by Sean Reifschneider to be smarter about surrounding page
# link context. For usage documentation see:
#
# http://www.tummy.com/Community/Articles/django-pagination/
from django import template
register = template.Library()
def paginatorUse... |
from collections import defaultdict
import argparse
import logging
from eval.ner.readers.ConllOutput import read_sequence_list_conll, ConllOutput
def iter_dataset(dataset):
for seq in dataset.sequence_list.seq_list:
for word, gold, predict in zip(seq.x, seq.y, seq.z):
yield (word, gold, predi... |
from xbmcswift2 import Plugin
import urllib
from BeautifulSoup import BeautifulSoup as BS
plugin = Plugin()
BASE_URL = 'http://www.gamekings.tv/videos/'
STREAM_URL = 'http://stream.gamekings.tv/large/'
def get_video_link(page):
src = urllib.urlopen(page)
html = BS(src)
video_url = html.find('meta',{"p... |
import logging
from xml.etree import ElementTree
from nova import vendor
from twisted.internet import defer
from nova import exception
from nova import flags
from nova import test
from nova import utils
from nova.compute import model
from nova.compute import node
FLAGS = flags.FLAGS
class InstanceXmlTestCase(test.... |
# -*- coding: utf-8 -*-
from string import Template
from textwrap import dedent
# This file contains templates used to generate HandleProcess file
'''
The following template is based on Part 4 (Section ParseHandleBuffer())
'''
handle_process_template = Template(dedent("""\
#include "Tpm.h"
#include "In... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.