content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('account', '0001_initial'),
]
ope... |
import cv2
import numpy as np
#Start of Maze Solving
#Initiates webcam
cap = cv2.VideoCapture(0)
#Sets camera_capture to image attained from webcam and saves it as Maze1.png
def get_image():
retval, im = cap.read()
return im
camera_capture = get_image()
cap.release()
cv2.imwrite("Maze1.png", camera_ca... |
import numpy
from . import cxrayutilities, exception, utilities
from .gridder import Gridder, axis, delta, ones
class Gridder3D(Gridder):
def __init__(self, nx, ny, nz):
Gridder.__init__(self)
# check input
if nx <= 0 or ny <= 0 or nz <= 0:
raise exception.InputError('None o... |
import re
import sys
import time
#
# This script splits mapped sam files by chromosome
#
print("opening sam file")
sam_file = sys.argv[1]
sam_file_contents = open(sam_file).read().rstrip("\n").split("\n")
num_files = int(sys.argv[2])
outfile_prefix = sys.argv[3]
if sam_file.endswith("sam"):
bam_flag = "SA... |
#!/usr/bin/env python
import urllib.request
from bs4 import BeautifulSoup
from colorama import Fore
from subprocess import call
userInput = input(Fore.BLUE + "PIRATE SEARCH : " + Fore.RESET)
#userInput="castle s01e02"
userInput.replace(" ", "%20")
page = 'https://thepiratebay.se/search/' + userInput + '/0/7/0ls'
pag... |
import pytest
from pytest import yield_fixture
@yield_fixture(scope='module')
def decimal_table(cur):
table_name = 'tmp_decimal_table'
ddl = """CREATE TABLE {0} (
f1 decimal(10, 2),
f2 decimal(7, 5),
f3 decimal(38, 17))""".format(table_name)
cur.execute(d... |
__author__ = 'tanel'
import logging
import logging.config
import time
import thread
import argparse
from subprocess import Popen, PIPE
from gi.repository import GObject
import yaml
import json
import sys
import locale
import codecs
import zlib
import base64
import time
from ws4py.client.threadedclient import WebSock... |
class Concept(object):
"""
A formal concept, contains intent and extent
Examples
========
Create a concept with extent=['Earth', 'Mars', 'Mercury', 'Venus']
and intent=['Small size', 'Near to the sun'].
# >>> extent = ['Earth', 'Mars', 'Mercury', 'Venus']
# >>> intent = ['Small size', 'N... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import unittest
class TreeNode(object):
def __init__(self):
self.Children = []
def Add(self, node):
self.Children.append(node)
class BookTree(object):
Root = None
Nodes = {}
def _GetNode(self, nodeId, listOfNodes):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function, unicode_literals)
"""many helpers and variables for the package"""
import os
import codecs
import inspect
from collections import OrderedDict
from datetime import datetime
from HTMLParser import HTMLParse... |
"""The :xfile:`models.py` module for :mod:`lino_voga.lib.invoicing`.
"""
from __future__ import unicode_literals
from lino_xl.lib.invoicing.models import *
from lino.api import _
class Plan(Plan):
"""An extended invoicing plan.
.. attribute:: course
If this field is nonempty, select only enrolmen... |
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
import settings, os
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', direct_to_template, {'template': 'index.html'}),
... |
"""Functions for reading and writing graphs in the *sparse6* format.
The *sparse6* file format is a space-efficient format for large sparse
graphs. For small graphs or large dense graphs, use the *graph6* file
format.
For more information, see the `sparse6`_ homepage.
.. _sparse6: http://users.cecs.anu.edu.au/~bdm/d... |
from sixquiprend.sixquiprend import app
import os
# Load default config and override config from an environment variable
app.config.update(dict(
SQLALCHEMY_TRACK_MODIFICATIONS=False,
DATABASE_USER='sixquiprend',
DATABASE_PASSWORD='sixquiprend',
DATABASE_HOST='localhost',
DATABASE_NAME='sixquiprend'... |
"""Demo app for the Titan Channel API."""
import cgi
import hashlib
import os
import jinja2
import webapp2
from titan import channel
from titan import users
class MainHandler(webapp2.RequestHandler):
def get(self):
# This is the low-level App Engine Channel API client_id, and should
# be unique for each ... |
import dynker.filters.base
import faker
import os
import random
import six
import sure
import unittest
import yaml
from .. import mock
class TestFilter(unittest.TestCase):
def setUp(self):
self.faker = faker.Faker()
self.module = dynker.filters.base
def test_obj_prio(self):
obj = obj... |
import logging
from typing import Iterator
from noisicaa import node_db
from noisicaa.builtin_nodes import node_description_registry
from . import scanner
logger = logging.getLogger(__name__)
class Builtins(object):
RealmSinkDescription = node_db.NodeDescription(
uri='builtin://sink',
display_n... |
from pprint import pprint
from aioutils.celery import asyncio_task, delay_or_call
from celery.utils.log import get_task_logger
from django.db import transaction
from rentme.celery.celery_app import app
from rentme.raw.models.search import Property, Flatmate
from rentme.raw.models.listings import ListedItemDetail
from... |
import binascii
import os
import sqlalchemy
import selenium
from selenium.webdriver.common import keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from timpani import database
LOGIN_TITLE = "Login - Timpa... |
from django.conf import settings
from django.core.urlresolvers import reverse
from eats.tests.views.view_test_case import ViewTestCase
class DateChangeViewTestCase (ViewTestCase):
def setUp (self):
super(DateChangeViewTestCase, self).setUp()
self.date_period = self.create_date_period('lifespan')... |
"""
Implementation of VM state
"""
from stack import VMStack
from memory import VMMemory
MASTER_THREAD_ID = 0
class VMRuntime(object):
def __init__(self, program, mem_bytes, stack_size, n_threads=4):
# program = list of instructions
self.program = program
self.memory = VMMemory(mem_bytes... |
# _*_ coding: utf-8 _*_
import pymysql.cursors
from .schema import DBSchema, Table, Column, ForeignKey
class MySQLSchema(DBSchema):
"""Introspection class for MySQL Database"""
def _init_conn(self, db_dict, schemas=[]):
if self._meta.conn is not None:
try:
self._meta.conn.close()
except Exception:
... |
from .sub_resource import SubResource
class ApplicationGatewayPathRule(SubResource):
"""Path rule of URL path map of an application gateway.
:param id: Resource ID.
:type id: str
:param paths: Path rules of URL path map.
:type paths: list of str
:param backend_address_pool: Backend address po... |
import PyLucene
from PyLucene import Field
from spyse.core.platform.platform import Platform
import thread
import os
import time
from Queue import Queue
from ibas_global import IBASGlobal
COLUMN_NID = "nid"
COLUMN_NODE_STATUS = "cloneStatus"
COLUMN_OBJECT = "object"
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .element import Element
from .point import Point
class MultiElement(Element):
def __init__(self):
super(MultiElement, self).__init__()
self.points = []
self.valid_points = 2
def add(self, point):
self.points.append... |
# -*- coding: utf-8 -*-
"""This module operates the `Advanced search` box located on multiple pages."""
import re
from functools import partial
from cfme.fixtures import pytest_selenium as sel
from cfme.web_ui import expression_editor as exp_ed
from cfme.web_ui import Input, Region, Select, fill
from cfme.web_ui.form_... |
import os
import subprocess
import numpy as np
import pandas as pd
import fiona
from fiona import crs
import utm
class fiona_handler:
def __init__ (self, filename = None, mode = 'r'):
'''
constructor takes a prototype. The prototype provides a pre-prepared schema. If writing
the file, the p... |
import requests
import json
import time
import sys
import argparse
import os
my_env = os.environ
url = my_env["CS_NESSUS_URL"] if 'CS_NESSUS_URL' in my_env else "https://127.0.0.1:8834"
username = my_env["CS_NESSUS_USER"] if 'CS_NESSUS_USER' in my_env else "nessus"
password = my_env["CS_NESSUS_PASS"] if 'CS_NESSUS_PA... |
"""Test event model."""
from happening.tests import TestCase
from model_mommy import mommy
from datetime import datetime, timedelta
import pytz
from dateutil.relativedelta import relativedelta, MO, TU, WE, TH, FR, SA, SU
from happening.utils import custom_strftime
class TestEvent(TestCase):
"""Test event model.... |
import os
import json
import unittest
import requests
from superdesk.publish import SUBSCRIBER_TYPES
from superdesk.publish.transmitters.http_push import HTTPPushService
from unittest import mock
from unittest.mock import Mock
from superdesk.errors import PublishHTTPPushServerError, PublishHTTPPushClientError
def g... |
# -*- coding: UTF-8 -*-
"""
Lastship Add-on (C) 2019
Credits to Lastship, Placenta and Covenant; our thanks go to their creators
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, e... |
from oslo_config import cfg
network_group = cfg.OptGroup(name='network',
title='Options for the container network')
network_opts = [
cfg.StrOpt('driver',
default='kuryr',
help='Defines which driver to use for container network.'),
]
ALL_OPTS = (network_... |
from functools import wraps
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from pootle.i18n.gettext import ugettext as _
from pootle_app.models.permissions import (check_permission,
... |
import _lxc
import os
import subprocess
import time
default_config_path = _lxc.get_global_config_item("lxc.lxcpath")
get_global_config_item = _lxc.get_global_config_item
version = _lxc.get_version()
class ContainerNetwork(object):
props = {}
def __init__(self, container, index):
self.container = con... |
#!/usr/bin/env python
"""
This script is a trick to setup a fake Django environment, since this reusable
app will be developed and tested outside any specifiv Django project.
Via ``settings.configure`` you will be able to set all necessary settings
for your app and run the tests as if you were calling ``./manage.py te... |
# -*- encoding: utf-8 -*-
from osv import osv, fields
class sale_order(osv.osv):
_name = 'sale.order'
_inherit = 'sale.order'
_columns = {
'vehicle_id': fields.many2one('fleet.vehicle',
'Vehículo',
required="True",
... |
"""
Inner module for enumerations and base types.
"""
import logging
from onirim import util
LOGGER = logging.getLogger(__name__)
class Color(util.AutoNumberEnum):
"""
Enumerated colors of cards.
Attributes:
red
blue
green
yellow
"""
red = ()
blue = ()
... |
import os
import sys
import shutil
class NoDirectoriesError(Exception):
"Error thrown when no directories starting with an underscore are found"
class DirHelper:
def __init__(self, is_dir, list_dir, walk, rmtree):
self.is_dir = is_dir
self.list_dir = list_dir
self.walk = walk
... |
# apis_v1/documentation_source/save_analytics_action_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def save_analytics_action_doc_template_values(url_root):
"""
Show documentation about saveAnalyticsAction
"""
required_query_parameter_list = [
{
'name': ... |
import re
import ast
import operator
from itertools import chain
from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils.basic import AnsibleFallbackNotFound
try:
from jinja2 import Environment
from jinja2.exceptions import UndefinedError
HAS_JINJA2 = True
except ImportErro... |
from django import forms
from django.core import exceptions
from django.utils.translation import ugettext_lazy as _
from treebeard.forms import movenodeform_factory
from oscar.core.loading import get_class, get_model
from oscar.core.utils import slugify
from oscar.forms.widgets import ImageInput, DateTimePickerInput
... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
class Base:
def append_text_edit(self, text, text_edit, qt_color=QtCore.Qt.black):
cursor = text_edit.textCursor()
txt_format = cursor.charFormat()
txt_format.setForeground(qt_color)
cursor.setCharFormat(txt_for... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
from urllib import quote_plus
from os.path import join
from os.path import basename
from settings import WEB_ADDR
from settings import WEB_PORT
from sett... |
from util.common import getContainer
from interact import interact
import ZODB, transaction
from BTrees.OOBTree import OOBTree
class Recorder:
'''
A class for managing simple records.
The records stored in a flat fashion, that is, one key, one value
'''
def __init__(self, db_path):
self.db_... |
""" The module governing tables and objects that represent what are known as
Services (defined below) in Aquilon.
Many important tables and concepts are tied together in this module,
which makes it a bit larger than most. Additionally there are many layers
at work for things, especially for Host, Servi... |
import sys
class Stats:
def __init__(self, sequence):
# sequence of numbers we will process
# convert all items to floats for numerical processing
self.sequence = [float(item) for item in sequence]
def sum(self):
if len(self.sequence) < 1:
return N... |
from msrest.serialization import Model
class StorageAccountCheckNameAvailabilityParameters(Model):
"""StorageAccountCheckNameAvailabilityParameters
:param name:
:type name: str
:param type: Default value: "Microsoft.Storage/storageAccounts" .
:type type: str
"""
_validation = {
... |
# -*- coding: utf-8 -*-
from collections import defaultdict
import mock
from searx.engines import startpage
from searx.testing import SearxTestCase
class TestStartpageEngine(SearxTestCase):
def test_request(self):
query = 'test_query'
dicto = defaultdict(dict)
dicto['pageno'] = 1
... |
#!/usr/bin/env python
# for non-list/dict, CHANGE_TO -> variables replace previous values
# for 'list' , ADD_TO -> append to list
# EXCLUDE_FROM -> remove element from list
# for 'dict' , REPLACE_WITH -> replace matching keys
# as CHANGE_TO, ADD_T... |
import os
import re
from HTMLParser import HTMLParser
from urllib import urlopen
from urlparse import urljoin
class LinkParser(HTMLParser):
_BASE_URL = "https://simple.wikipedia.org/wiki/"
_BASE_URL_LEN = len(_BASE_URL)
_INVALID_NAME_PATTERN = re.compile(
"((Category|File|Help|Media|Special|Talk|T... |
"""Code for Bag-of-SFA Symbols in Vector Space."""
# License: BSD-3-Clause
import numpy as np
from math import ceil
from sklearn.utils.validation import check_array, check_X_y, check_is_fitted
from sklearn.utils.multiclass import check_classification_targets
from sklearn.base import BaseEstimator
from sklearn.metrics... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify PCH works if variant dir has spaces in its name
"""
import time
import TestSCons
test = TestSCons.TestSCons(match = TestSCons.match_re)
test.skip_if_not_msvc()
test.write('Main.cpp', """\
#include "Precompiled.h"
int main()
{
return tes... |
from Bio.SeqUtils import MeltingTemp as mt
import argparse, rnafold, math
def analyse(sequence,
GC=True,
Tm=62.0,
Na=50.,
K=0.,
Tris=0.,
Mg=2.0,
dNTPs=0.2,
oligo=500.,
min_length=10,
max_length=50):
"""Return a list of secondary structure temparatures for ... |
""" Search dialogs for returned sales """
import datetime
from stoqlib.domain.person import Branch
from stoqlib.domain.sale import Sale
from stoqlib.domain.views import (ReturnedSalesView, PendingReturnedSalesView,
ReturnedItemView)
from stoqlib.domain.returnedsale import ReturnedSal... |
"""Logging that uses pickles.
TODO: add log that logs to a file.
"""
# twisted imports
from twisted.spread import banana
from twisted.persisted import dirdbm
from twisted.internet import defer
from twisted.python.components import backwardsCompatImplements
from zope.interface import implements
# sibling imports
impo... |
"""
TASKS:
init:
maintain SSH tunnel to conductor
listen to Web API
open DB connection
runtime:
maintain DB of inventory histories?
generate HTML reports
serve reports on request
API for conductor:
receive_inventory_and_map
Dashboard:
web interface
w... |
import sys
class HawkeyeLog:
def __init__(self,modules,verbose):
self._verbose = verbose
for item in modules:
self._initialize_module(item)
def _initialize_module(self,mod):
name = mod.get('module')
if name is not None:
module = self._import_module(name,... |
#!/usr/bin/env python
import unittest
import doctest
from amount_words import pluralize, lithuanian_number, amount_words
import txinvoice
from subprocess import check_output
class TestFormatAmount(unittest.TestCase):
def test_pluralize(self):
forms = 'tūkstančių', 'tūkstantis', 'tūkstančiai'
self.... |
import os
from collections import OrderedDict
from pathlib import Path
from tempfile import TemporaryDirectory
import pytest
from libqtile import utils
def test_rgb_from_hex_number():
assert utils.rgb("ff00ff") == (1, 0, 1, 1)
def test_rgb_from_hex_string():
assert utils.rgb("#00ff00") == (0, 1, 0, 1)
d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import oioioi.base.utils.validators
import django.core.validators
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contests', '0002_auto_20141219_1346'),
... |
# -*- coding: utf-8 -*-
ABRT_URL = 'http://repos.fedorapeople.org/repos/abrt/abrt/fedora-18/x86_64/'
ABRT_FILES = ['abrt-2.1.3.11.g4d5cf.dirty-1.fc18.x86_64.rpm',
'abrt-addon-ccpp-2.1.3.11.g4d5cf.dirty-1.fc18.x86_64.rpm',
'abrt-addon-kerneloops-2.1.3.11.g4d5cf.dirty-1.fc18.x86_64.rpm',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Proxy models for OCD Filing related models..
"""
from __future__ import unicode_literals
from opencivicdata.campaign_finance.models import (
Committee,
CommitteeType,
CommitteeIdentifier,
CommitteeName,
CommitteeSource,
)
from calaccess_processed.pro... |
'''
commandregistry: Command Registry module
Processes incoming command strings from the System Analyst client. All commands and their
source code can be created and edited in commands.py.
Contact Charlie Friend [<EMAIL>] for help with this module.
Copyright 2015, UVic AERO
Licensed under MIT
'''
import sys, ins... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 14 11:50:29 2014
@author: Tobias Jachowski
"""
__author__ = "Tobias Jachowski"
__copyright__ = "Copyright 2016, The PyOTIC Project"
__credits__ = []
__license__ = "Apache-2.0"
__maintainer__ = "Tobias Jachowski"
__email__ = "<EMAIL>"
__status__ = "beta"
import os
direct... |
import re
import os
from django.core.management.base import NoArgsCommand
from django.conf import settings
from peps.converters import (
get_pep0_page, get_pep_page, add_pep_image, get_peps_rss
)
pep_number_re = re.compile(r'pep-(\d+)')
class Command(NoArgsCommand):
"""
Generate CMS Pages from flat fil... |
# -*- coding: utf8 -*-
# Soubor: main.py
# Datum: 22.02.2014 11:20
# Autor: Marek Nožka, marek <@t> tlapicka <d.t> cz
# Licence: GNU/GPL
# Úloha: web interface
############################################################################
from bottle import run, route, request, redirect, response, \
template... |
# -*- coding: utf-8 -*-
"""
enums.py
~~~~~~~~
<Add description of the module here>.
:copyright: (c) 2015-2020 by Jochen Gerhaeusser.
:license: BSD, see LICENSE for details.
"""
import enum
class Enumeration(enum.IntEnum):
""" The `Enumeration` class is a subclass from the :class:`~enum.IntEnum`
class provid... |
import itertools
import copy
from vitrage.common.constants import EdgeProperties
from vitrage.common.constants import VertexProperties as VProps
from vitrage.datasources import NOVA_HOST_DATASOURCE
from vitrage.graph import Direction
from vitrage.graph.driver.networkx_graph import NXGraph
from vitrage.graph import Ed... |
#!/usr/bin/env python
import os
import os.path
import sys
import six
import nose
import logging
import datetime
from pykwalify.core import Core
from pykwalify.errors import SchemaError
# add load path.
for path in ["lib"]:
sys.path.append(os.path.join(os.path.abspath(
os.path.dirname(__file__)), path))
f... |
import sys
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast
import networkx as nx
import numpy as np
from pyquil.quilatom import Parameter, unpack_qubit
from pyquil.quilbase import Gate
if sys.version_info < (3, 7):
from pyquil.external.dataclasses import dataclass
else:
from datacl... |
#!/usr/bin/env python
#coding:utf8
##
# @file python-tags.py
# @brief 考虑到存在多个python版本的问题,因为pyenv或者多版本安装,
# 在打开vim时,对于tags文件的导入可能发生混淆,所以利用
# 该脚本对python_bamboo.vim进行更改操作
# @author unlessbamboo
# @version 1.0
# @date 2016-03-03
import os
import sys
import subprocess
def error_msg(pstr):
"""err... |
#!/usr/bin/env python
import qi
import sys
import time
import math
import rospy
import actionlib
from std_msgs.msg import String
from optparse import OptionParser
from naoqi_bridge_msgs.msg import SpeechWithFeedbackAction, SpeechWithFeedbackGoal
class TalkControllerPepper:
def __init__(self, sim=False):
... |
'''
Created on May 7, 2014
@author: bwilkinson
'''
import unittest
import emtools.common.utils as utils
import test_common
import autooam.cluster.emvmgr as emvmgr
import emtools.common as common
import os
import shutil
import time
# callbacks to test various wget paths
def mysyscb1(cmd):
ret = '''<HTML><HEAD><TIT... |
"""
Test methods for the Transaction class.
"""
import mock
import pytest
from repoguard.core import process
from repoguard.core import transaction
class TestTransaction(object):
def setup_method(self, _):
self._transaction = transaction.Transaction("repoPath", "10")
self._... |
from django.db import models
from django_orm.postgresql.hstore import forms, util
from django.utils.translation import ugettext_lazy as _
class HStoreDictionary(dict):
"""
A dictionary subclass which implements hstore support.
"""
def __init__(self, value=None, field=None, instance=None, **params):
... |
# system configuration generated and used by the sysconfig module
build_time_vars = {'AC_APPLE_UNIVERSAL_BUILD': 0,
'AIX_GENUINE_CPLUSPLUS': 0,
'AR': 'ar',
'ARFLAGS': 'rc',
'ASDLGEN': './Parser/asdl_c.py',
'ASDLGEN_FILES': './Parser/asdl.py ./Parser/asdl_c.py',
'AST_ASDL': './Parser/Python.asdl',
'AST_C': 'Pytho... |
from pd import *
cseed(4)
info()
timer()
ffps = FFParamSet()
ffps.readLib("amber03aa.ff")
## test simple loading of PDB file
sim = PDB_In(ffps, "../../pdb/trpcage.pdb");
sim.loadAll();
# create workspace from the system sim
wspace = WorkSpace( sim )
# print loaded system - this can be compared later
wspace.printPDB... |
"""Functions that deal with geographic data that does not vary over time
This type of data varies based on geography, but does not differ across
different time periods (or at least not on a relevant scale). For instance,
a raster of euclidean distance to airports would be included in this category
"""
from s3_utils i... |
from django.conf import settings
from django.db.backends.creation import BaseDatabaseCreation
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated PostgreSQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolat... |
"""Test that forward declarations don't cause bogus conflicts in namespaced types"""
from __future__ import print_function
import unittest2
import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbutil as lldbutil
class NamespaceDefinitionsTestCase(TestBas... |
import datetime
import json
from unittest.mock import MagicMock
from django.http import QueryDict
from django.urls import reverse
from rest_framework import status
from api.test.base import APITestBase
from api.views import (
ReportsViewSet,
)
from workshops.models import (
Badge,
Award,
Person,
R... |
# coding: utf-8
from flask import Flask, render_template, request, abort
import time
from flask.ext.login import LoginManager, current_user
app = Flask(__name__)
app.config.from_object('config')
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
login_ma... |
from spectrum.arma import arma2psd
from spectrum.burg import *
from spectrum.datasets import marple_data, data_cosine
from spectrum.tools import cshift
from spectrum.criteria import *
from numpy.testing import assert_array_almost_equal, assert_almost_equal
import numpy
import pylab
def test_arburg2():
from spect... |
import copy
import time
from tempest.api.identity import base
from tempest.lib.common.utils import data_utils
from tempest.lib import exceptions
from tempest import manager
from tempest import test
class IdentityV3UsersTest(base.BaseIdentityV3Test):
@classmethod
def resource_setup(cls):
super(Identi... |
'''
@author Raj Singh
@file ion/processes/data/transforms/viz/google_dt.py
@description Convert CDM data to Google datatabbles
'''
from pyon.core.exception import BadRequest, Timeout
from pyon.public import log
from ion.core.function.transform_function import SimpleGranuleTransformFunction
from ion.services.dm.utili... |
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
gettext = lambda s: s
BASE_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), '..')
from datetime import timedelta
import djcelery
djcelery.setup_loader()
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
CEL... |
'''
Inserts data into the protective marking database.
'''
import sys
import os
import json
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(current_dir))
# Append the main ideaworks directory
is_directory = os.path.join(os.path.dirname(os.path.dirname(current_dir)),... |
from datetime import date, datetime
from corehq.apps.userreports.expressions.factory import ExpressionFactory
from corehq.apps.userreports.specs import FactoryContext
from corehq.util.test_utils import generate_cases
@generate_cases([
({'dob': '2015-01-20'}, 1, date(2015, 2, 20)),
({'dob': '2015-01-20'}, 3, d... |
settings = {
'population_size': 50, # number of organisms
'number_of_dimensions': 2, # I don't think we can do any dimensions greater than 2
'bounds': [ # this must have 1 pair per dimension
(-1,1.5),
(-1,2)
],
'num_iterations': 100,
'time_delay': 0.0,
##### Leave these betw... |
"""
Django settings for reviews project.
Generated by 'django-admin startproject' using Django 1.8.5.
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/
"""
# Build path... |
from msrest.serialization import Model
class OperationImpact(Model):
"""The impact of an operation, both in absolute and relative terms.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar name: The name of the impact dimension.
:vartype name: str
:i... |
import os
import os.path
from configparser import ConfigParser
from .projects import PROJECTS, ENCODING
# The name of the ini file within each project containing the metadata
INI_FILENAME = 'puppy-project.ini'
class ProjectManager:
"""Manage the list of existing projects."""
def __init__(self, root):
... |
#!/usr/bin/env python
from setuptools import setup
def get_version():
with open("tictyl.py", "r") as fp:
for line in fp:
if line.startswith("__version__"):
return eval(line.split("=")[-1])
def read(filename):
with open(filename, "r") as fp:
return fp.read()
setu... |
# This is the Twisted Get Poetry Now! client, version 1.0.
# NOTE: This should not be used as the basis for production code.
# It uses low-level Twisted APIs as a learning exercise.
import datetime, errno, optparse, socket
from twisted.internet import main
def parse_args():
usage = """usage: %prog [options] [h... |
import RPi.GPIO as GPIO # Import GPIO Library
import time,sys
# Output ports
out_1 = 16
out_2 = 20
out_3 = 21
# Delays
delay_bit = 0.01
delay_after_value = 0.01
##############################################################################
#
# clockSignal()
#
# This function is used to produce a qu... |
# -*- coding: utf-8 -*-
"""
Serverscope.io benchmark tool
"""
import os
import platform
import tempfile
import shutil
from .cli import get_parser
from .benchmarks import get_selected_benchmark_classes
from .utils import Color as c, get_geo_info, post_results
from .server import get_server_specs
from six import prin... |
from .base import FlotillaOutput
class Number(FlotillaOutput):
"""
Number
"""
module = "number"
brightness = 40
digits = [0, 0, 0, 0, ]
colon = False
apostrophe = False
number = None
hours = None
minutes = None
seconds = None
NUM_DOT = 1
NUM_MID = 2
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import os.path
import argparse
import flask
from . import app, compat
from .compat import PY_LEGACY
class ArgParse(argparse.ArgumentParser):
default_directory = os.path.abspath(compat.getcwd())
default_host = os.getenv('BROWSEPY_HOST', '127.... |
import os
import traceback
from hashlib import md5
from jinja2 import Environment
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(default=None, required=True),
use_sudo=dict(required=False, choices=BOOLEANS, default=False),
plugin=dict(default=None, r... |
'''
Created on 25 May 2019
@author: si
'''
from datetime import datetime
from multiprocessing import Process, Pipe
from multiprocessing.connection import wait
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from pi_fly.actional.abstract import CommsMessage
from pi_fly.model import Base, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.