src stringlengths 721 1.04M |
|---|
from ppp_cas.evaluator import evaluate
from unittest import TestCase
from sympy import latex
class TestEvaluation(TestCase):
def procedure(self, testCases):
for (expr, res) in testCases:
string, latex = evaluate(expr)
self.assertEqual(latex, res)
def testNumeric(self):
... |
import types
import logging
import inspect
import pprint
import operator
import re
from operator import isCallable
from resp import *
import swaf.error
import swaf.misc
from swaf.misc import isListOfFuncs
DEBUG=1
def wrapFilter(f, filter_name, filters):
newf = chainWrap(f)
newf.__name__ = f.__name__
newf.__modul... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 applicable law or... |
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License a... |
# -*- coding: utf-8 -*-
"""
vcs.backends
~~~~~~~~~~~~
Main package for scm backends
:created_on: Apr 8, 2010
:copyright: (c) 2010-2011 by Marcin Kuzminski, Lukasz Balcerzak.
"""
import os
from pprint import pformat
from vcs.conf import settings
from vcs.exceptions import VCSError
from vcs.utils.he... |
# -*- coding: utf-8 -*-
import pytest
import formation.parameter
from formation.parameter import Parameter
@pytest.mark.parametrize("parameter,expected_output", [
(
Parameter("A"),
"Parameter(title='A', param_type='String', **{})"
),
(
Parameter("A", "Number"),
"Parameter... |
import unittest
from splinter import Browser
from .fake_webapp import EXAMPLE_APP
from .base import WebDriverTests
class PhantomJSBrowserTest(WebDriverTests, unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.browser = Browser("phantomjs")
@classmethod
def tearDownClass(cls):
... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
#!/usr/bin/env python
#
# Copyright 2017 Anil Thomas
#
# 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 appl... |
import gevent
from gevent import monkey, pool
monkey.patch_all()
class Flooder():
def __init__(self, site, publisher, image_cache_handler):
self.site = site
self.publisher = publisher
self.image_cache_handler = image_cache_handler
self.cache_handlers = []
def _push_to(self,... |
#!/usr/bin/python
import datetime
import fcntl
import github3
import gzip
import json
import os
import re
import select
import socket
import subprocess
import sys
import time
import mysql.connector
TARGET_VM = 'devosa'
TARGET_IP_BLOCK = '192.168.53.0/24'
with open(os.path.expanduser('~/.github_automation'), 'r') ... |
# Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""
Unit tests for the :func:`iris.util.equalise_attributes` function.
"""
# import iris tests first so that some things can ... |
#
# Copyright (c) 2015, Arista Networks, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of condit... |
import os
import io
import flask
import flask_restful
from flask_cors import CORS, cross_origin
import flask_cache
import blobstorecore
import tools
import json
app = flask.Flask(__name__)
app.config["CACHE_DEFAULT_TIMEOUT"] = int(os.environ.get("CACHE_DEFAULT_TIMEOUT", 50))
app.config["CACHE_THRESHOLD"] = int(os.envi... |
#!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a livecoind or Li... |
from cement.core.controller import CementBaseController, expose
from cement.core import handler, hook
from ee.core.logging import Log
from ee.core.variables import EEVariables
from ee.core.aptget import EEAptGet
from ee.core.apt_repo import EERepo
from ee.core.services import EEService
from ee.core.fileutils import EEF... |
from opentrons.calibration.check.session import CheckCalibrationSession
from opentrons.calibration.check import models as calibration_models
from opentrons.calibration.session import CalibrationException
from robot_server.service.session import models
from robot_server.service.session.command_execution import \
Co... |
#!/usr/bin/env python3
"""Test the general module."""
import getpass
import unittest
import random
import os
import sys
import string
import tempfile
import yaml
import shutil
# Try to create a working PYTHONPATH
TEST_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
SWITCHMAP_DIRECTORY = os.path.abspath(os.pat... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC
#
# 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
... |
# MODULE: leon2-components
# CLASS: leon2-simple
from sim_core import *
from components import *
def _make_leon_cfg(dsu, sdram, wpts, mac, nwin, icsz, ilsz, dcsz, dlsz, div,
mul, wdog, mst, fpu, pci, wp):
leoncfg = 0
leoncfg = leoncfg | dsu << 30 # Debug Support Unit
leoncfg = leoncf... |
# -*- coding: utf-8 -*-
import sys
import os
import argparse
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
from utils.argparsers.simulationargparser import SimulationArgumentParser
class MultileaveArgumentParser(SimulationArgumentParser):
def __init__(self, description=None, set_arguments={}... |
from fractions import Fraction
import sys
# rational paramterization / approximation of bernoulli's lemniscate
# in a 3 dimensional 'dumbbell' arrangement.
# (note - this uses terms from Norman Wildberger's rational
# trigonometry/chromogeometry. briefly for a vector from 0,0 to x,y:
#
# blue quadrance (x,y) = x^2 +... |
# -*- 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 'Category.site'
db.add_column(u'cms_category', 'site',
... |
import argparse
import base64
import json
import numpy as np
import socketio
import eventlet
import eventlet.wsgi
import time
from PIL import Image
from PIL import ImageOps
from flask import Flask, render_template
from io import BytesIO
from keras.models import model_from_json
from keras.preprocessing.image import Im... |
"""
A pretty command line tool to calculate the number
of Pomodori available between two points in time.
"""
__author__ = 'Matt Deacalion Stevens'
__version__ = '1.0.2'
import datetime
from itertools import cycle
class PomodoroCalculator:
"""
Calculates the number of Pomodori available in an amount of time.
... |
from setuptools import setup, find_packages
try:
import pypandoc
long_description = pypandoc.convert('README.md', to='rst', format='md')
long_description += "\n\n" + pypandoc.convert('AUTHORS.md', to='rst', format='md')
except (IOError, ImportError):
long_description = ''
setup(
name='wad',
ve... |
try:
set
except NameError:
print("SKIP")
raise SystemExit
import micropython
# Tests both code paths for built-in exception raising.
# mp_obj_new_exception_msg_varg (exception requires decompression at raise-time to format)
# mp_obj_new_exception_msg (decompression can be deferred)
# NameError uses mp_ob... |
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distributed... |
# coding: utf-8
import unittest
import time
import redis
from nose.tools import eq_
from mock import Mock
from mock import patch
from retools.limiter import Limiter
from retools import global_connection
class TestLimiterWithMockRedis(unittest.TestCase):
def test_can_create_limiter_without_prefix_and_without_co... |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import *
from crispy_forms.bootstrap import *
from crispy_forms.layout import Layout, Submit, Reset, Div
from django import forms
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from activitydb.models import Feedback, TolaUser
fr... |
"""This module contains the functions and classes needed for mapping points between layers"""
import logging
import mathutils
import random
import numpy
from .mesh import *
from .constants import *
logger = logging.getLogger(__package__)
def computePoint(v1, v2, v3, v4, x1, x2):
"""Interpolates point on a quad
... |
# You created a game that is more popular than Angry Birds.
# Each round, players receive a score between 0 and 100, which you use to rank them from highest to lowest. So far you're using an algorithm that sorts in O(n\lg{n})O(nlgn) time, but players are complaining that their rankings aren't updated fast enough. You n... |
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2016 Andrew T. T. McRae
#
# This file is part of UFL (https://www.fenicsproject.org)
#
# SPDX-License-Identifier: LGPL-3.0-or-later
#
# Modified by Massimiliano Leoni, 2016
from ufl.finiteelement.finiteelementbase import FiniteElementBase
from ufl.sobolevspace import HDi... |
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2019, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.utils.transla... |
"""
Automated fitting script.
"""
import os
import sys
import fnmatch
import argparse
import logging
import multiprocessing
from paramselect import fit, load_datasets
from distributed import Client, LocalCluster
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--dask-scheduler",
met... |
import unittest
from vint.compat.unittest import mock
from vint.linting.cli import CLI
from vint.bootstrap import import_all_policies
class TestCLI(unittest.TestCase):
@classmethod
def setUpClass(cls):
# For test_start_with_invalid_file_path.
# The test case want to load saveral policies.
... |
"""Load precinct-level election results from the OpenElections Project
(http://www.openelections.net), the first free, comprehensive, standardized,
linked set of election data for the United States, including federal and
statewide offices.
"""
import csv
import os
import re
import sys
from datetime import date
from t... |
from astropy.io.fits import getdata, writeto
import numpy as np
from glob import glob
import os, time, sys
from multiprocessing import Pool
time_now = time.time()
# To identify unique ids
# IDs_dir='/data/avestruz/StrongCNN/Challenge/FinalData/GroundBased/'
# IDs_glob=['*[12]*', '*[34]*', '*[56]', '*[7... |
from django.contrib.contenttypes.fields import GenericRelation
from django.core.cache import cache
from django.db import models, IntegrityError, transaction
from .utils import detect_type
from .models import Option
class OptionsMixin(models.Model):
options = GenericRelation(Option)
class Meta:
abst... |
import sys
import os
import shutil
import io
import datetime
import time
import importlib
import threading
class HijackedStdOut(io.TextIOWrapper):
def write(self, s):
if s == '\n':
super().write(s)
return
s = '{:%Y.%m.%d %H:%M:%S} => {}'.format(datetime.datetime.now(), s)... |
from sqlalchemy import orm
from unittest import skip
from specifyweb.specify.api_tests import ApiTests
from .queryfieldspec import QueryFieldSpec
from . import models
@skip("These tests are out of date.")
class StoredQueriesTests(ApiTests):
# def setUp(self):
# super(StoredQueriesTests, self).setUp()
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-07-04 09:18
from __future__ import unicode_literals
from __future__ import unicode_literals
from django.db import migrations
from django.db import models
app_label = 'publications_bootstrap'
def forwards(apps, schema_editor):
Catalog = apps.get_model(... |
from django.conf.urls import url
from rest_framework import routers, viewsets
from rest_framework_nested import routers as nested_routers
class HybridRoutingMixin(object):
"""
Extends functionality of DefaultRouter adding possibility to register
simple API views, not just Viewsets.
Based on:
htt... |
# postgresql/psycopg2.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
.. dialect:: postgresql+psycopg2
:name: psycopg2
:dbapi: psycopg2... |
#!/usr/bin/env python
# Copyright 2021 Google Inc. All Rights Reserved.
#
# 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 require... |
import flickr_api
import pickle
import os
# returns the urls of all photos in an album
def get_photos_url(photos):
lista_url = []
for photo in photos:
lista_url.append(photo.getPhotoFile('Medium'))
return lista_url
def give_me_photos():
if not os.path.exists('album.pickle'):
return ([], [])
fp1 = file('albu... |
import numpy as np
import operator
from sklearn import naive_bayes
from sklearn import svm, tree
from kernels import GaussianKernel
class AbstractModel(object):
"""Abstract model of a learning algorithm. When implementing a subclass,
you have to implement method ``train``. Method ``predict`` is implemented
... |
"""
Sqlite data access.
"""
import datetime
import logging
import sqlite3
from snippy.utils.loggingtools import get_logger
# TODO: probably better to use built-in conversions
PYTHON_TO_SQLITE_TYPE = {
datetime.datetime: 'DATETIME',
str: 'TEXT',
}
SQLITE_TO_PYTHON_TYPE = {value: key for key, ... |
# coding: utf-8
# # Antibody Response Pulse
# https://github.com/blab/antibody-response-pulse
#
# ### B-cells evolution --- cross-reactive antibody response after influenza virus infection or vaccination
# ### Adaptive immune response for repeated infection
# In[3]:
'''
author: Alvason Zhenhua Li
date: 04/09/201... |
import os
import pygame as pg
SCREEN_SIZE = (1024, 640)
ORIGINAL_CAPTION = "Game"
# init pygame and create the window
pg.init()
pg.font.init()
os.environ['SDL_VIDEO_CENTERED'] = "TRUE"
pg.display.set_caption(ORIGINAL_CAPTION)
SCREEN = pg.display.set_mode(SCREEN_SIZE)
SCREEN_RECT = SCREEN.get_rect()
# load all the a... |
#!/usr/bin/env python3
"""
Use byzanz to create a GIF screencast of a specific window.
Required tools:
sudo apt-get install byzanz x11-utils xdotool
A tip: use an extra-long duration (-d 100), record your shot, and use
gimp to shorten the duration of the last frame. You need to rename the layer
from "Frame 123 (10000... |
import textwrap
classes = []
class SettingMeta(type):
def __new__(cls, name, bases, attrs):
base_constructor = super(SettingMeta, cls).__new__
parents = [
base for base in bases
if isinstance(base, SettingMeta)
]
if not parents:
return base_c... |
#!/usr/bin/env python
'''
Compute mutual information between individual features
and labels
'''
import argparse
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from common import *
def opts():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('feat... |
from indivo.lib import iso8601
from indivo.models import Device
XML = 'xml'
DOM = 'dom'
class IDP_Device:
def post_data(self, name=None,
name_type=None,
name_value=None,
name_abbrev=None,
identity=None,
id... |
# Copyright (c) 2018 Arista Networks, Inc.
# Use of this source code is governed by the Apache License 2.0
# that can be found in the LICENSE file.
import unittest
import base64
import os
import shutil
import tempfile
import zipfile
from switools import verifyswi
from switools.verifyswi import VERIFY_SWI_RESULT
from... |
from dyplot.c3 import C3 as Core
import numpy as np
class Hist(Core):
"""
Compute the histogram of a set of data.
"""
def __init__(self, a, bins=10, r=None, weights=None, density=None, xlabel = "", **kwargs):
"""
:param a: input data. The histogram is computed over the flat... |
import requests
import os
import logging
from enum import Enum
import json
logger = logging.getLogger(__file__)
logging.basicConfig(level=logging.DEBUG)
class PcfTaskStates(Enum):
SUCCEEDED = "SUCCEEDED" # Used for runs when all tasks were successful
RUNNING = "RUNNING" # Used for runs when one or more tas... |
import numpy as np
class ExperimentViewProperties(object):
""" An instance of this class is returned for each experiment
and contains plotting information.
"""
title = 'experiment'
info = ''
dataset = ''
x_axis_name = 'x-axis'
y_axis_name = 'y-axis'
xscale = 'linear'
fea... |
'''
Created on Feb 15, 2014
@author: EHWAAL
Copyright (C) 2014 Evert van de Waal
This program is released under the conditions of the GNU General Public License.
'''
# FIXME: Font names containing spaces are not handled properly.
# TODO: Allow style export & import. Use that to initialise the database
i... |
# coding: utf-8
from pprint import pprint
import unidecode
from djangoapp.apps.caronasbrasil.model.caronasbrasil.carona_post import CaronaPost
from djangoapp.apps.caronasbrasil.model.fb_groups.fb_groups_controller import FBGroupsController
from djangoapp.apps.caronasbrasil.persistence_controller import PersistenceContr... |
import os
from conans.client.cache.remote_registry import Remote
from conans.errors import ConanException, PackageNotFoundException, RecipeNotFoundException
from conans.errors import NotFoundException
from conans.model.ref import ConanFileReference, PackageReference, check_valid_ref
from conans.paths import SYSTEM_REQ... |
# Copyright (c) 2011-2013, ImageCat Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is... |
# -*- coding: utf-8 -*-
#LICENCE
#
# This File is part of the Webbouqueteditor plugin
# and licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported
# License if not stated otherwise in a files head. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc-sa/3.0... |
from hyperopt import fmin, tpe, hp
import lb_loader
import pandas as pd
import simtk.openmm.app as app
import numpy as np
import simtk.openmm as mm
from simtk import unit as u
from openmmtools import hmc_integrators, testsystems
pd.set_option('display.width', 1000)
n_steps = 300
platform_name = "CUDA"
precision = "mix... |
import sys
import tensorflow as tf
from tensorflow.python.ops import math_ops
sys.path.append("slim/")
slim = tf.contrib.slim
TRAIN_DIR = "/tmp/tf"
class Trainer(object):
def __init__(self, nb_classes, optimizer, learning_rate):
self.nb_classes = nb_classes
# learning rate can be a placeholder tensor
... |
from bs4 import BeautifulSoup
import time
from spiders_packege.unit.ResourcesDowmloader import ResourcesDownloader
from spiders_packege.unit.ResourcesProcessor import ResourcesProcessor
class PageProcessor:
def __init__(self):
pass
def dealAllImg(basePath,list,webDriver):
baseDetailUrl='http... |
from __future__ import print_function
from numpy import array, unique, hstack, zeros
class OBJ(object):
def __init__(self):
pass
def read_obj(self, obj_filename):
"""
v -0.0817245 0.000635 0.00421862
v -0.0817245 0.000580371 0.00421862
v -0.0817245 -0.000635 0.00421862
... |
# coding=utf-8
# 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 applicable law or agreed to in writing,... |
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
import os
def XmlToString(content, encoding='utf-8', pretty=False):
""" Writes the XML content to disk, touching the file only if it has changed.
... |
from Square import Square
import random
class Game(object):
"""docstring for Game"""
def __init__(self, x_dim, y_dim, num_mines):
super(Game, self).__init__()
self.x = x_dim
self.y = y_dim
self.mines = num_mines
# TODO: Validation
self.populate()
def populate(self):... |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
# SpeakerTest.py
# Group 7 ECE 4900
# Edward Reehorst w/ help from
# http://minhdo.ece.illinois.edu/teaching/speaker_recognition/
# Text independent speaker recognition system based on mel frequency coeffiecient
# features and vector quantization
import numpy as np
import scipy.fftpack as fft
import scipy.io.wavfile ... |
import serial
import math
import time
import csv
import thread
import numpy
from multiprocessing import Process
#globale variablen
#serial connection to mini Maestro
ser = serial.Serial('/dev/ttyACM1')
#leg length in cm
lega=3
legb=8
legc=10
def leg1(WinkelA,WinkelB,WinkelC,ser):
WinkelA=180-WinkelA
WinkelC=170... |
from __future__ import print_function
### READING FILES
file_name = 'data.txt'
# Reading in and parsing file contents
data_list = []
with open(file_name) as f:
# SKip the header (the first line)
next(f)
for line in f:
# Remove newline char
line = line.replace('\n', ... |
class Scale (object):
def __init__(self):
pass
class Tuning (object):
def __init__(self):
pass
class EqualTemper (Tuning):
def __init__(self, a4=440.0):
Tuning.__init__(self)
self.base_frequencies = [261.63, 277.18, 293.66, 311.13, 329.63,
... |
from loguru import logger
from PyQt5.QtWidgets import (
QGridLayout,
QLabel,
QPushButton,
QLineEdit,
QCheckBox,
QFileDialog,
)
from PyQt5 import QtGui, QtWidgets
import os.path as op
class SelectOutputPathWidget(QtWidgets.QWidget):
def __init__(
self,
path=None,
wid... |
##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... |
"""
Copyright (C) 2016 Warren Spencer warrenspencer27@gmail.com
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 vers... |
#!/usr/bin/env python3
# Copyright (c) 2020-2021 Project CHIP Authors
#
# 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 app... |
# Copyright (c) 2014-present PlatformIO <contact@platformio.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/LICENSE-2.0
#
# Unless required by appli... |
# -*- coding: UTF-8 -*-
import paypalrestsdk,urlparse,urllib2
from xml.etree import ElementTree as ETree
from hooks import paypal_api,pagseguro_api
from django.core.mail import send_mail
from django.conf import settings
from django.http import Http404,HttpResponse
from django.http import HttpResponse as response
from ... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2012 the MansOS team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice,
# ... |
import random
import json
from models import CITY
class Duplicates:
def __init__(self):
self.storage = dict()
pass
class Feature:
def __init__(self, *args, **kwargs):
self.data = dict({"type": "Feature", "properties": dict(), "geometry": {"type": kwargs['type'], "coordinates": []}})
... |
from collections import Iterable
import numpy as np
import tensorflow as tf
from . import config
from . import utilities
from .model import Description, Model, ModelError, Region
class DistributionError(Exception):
pass
def _parse_bounds(num_dimensions, lower, upper, bounds):
def _parse_bounds_1D(lower, u... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from collections import defaultdict
from future import standard_library
from nose.tools import raises
from pyload.core.database import DatabaseBackend, InvalidConfigSection
from pyload.core.manager import ConfigManager
from tests.helpe... |
#!/usr/bin/env python
"""
This program open a simple dialog that allows to issue a command to a remote server using SSH.
It needs a configuration file called remotecommander.ini with the following structure:
[GENERAL]
Host = 127.0.0.1
Port = 22
User = root
Password = xxxxx
Command = shutdown -h now
Comman... |
# Simple Aperture photometry. kind of a stupid class dependence.
# Ideally a photometer object should take an image and a region object
# as arguments, where the region object is an instance of a particualr aperture class and
# can return an in_region boolean (or perhaps a 'fraction') for
# any position(s). As it is ... |
#!/usr/bin/python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import json
import logging
import os
import random
import numpy as np
import torch
from torch.utils.data import DataLoader
from model import KGEModel
from dataloader impo... |
#!/usr/bin/env python
from peacock.Execute.JobRunner import JobRunner
from peacock.utils import Testing
class Tests(Testing.PeacockTester):
def setUp(self):
super(Tests, self).setUp()
self.runner = JobRunner()
self.runner.finished.connect(self.finishedCalled)
self.runner.outputAdded... |
# Copyright 2015 Dell Inc.
#
# 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 applicable law or agree... |
import os
import sys
import matplotlib as mpl
from matplotlib import cm
from colormaps import (
inferno, magma, plasma, viridis, inferno_r, magma_r, plasma_r, viridis_r
)
# Add the notebook dir to the path
if os.name == 'nt':
nbdir = 'D:/Dropbox/Notebooks'
else:
nbdir = '~/notebooks'
nbdir = os.path.expan... |
#!/usr/bin/python
import smtplib, imaplib, email, email.header
# Utility class to handle IMAP and SMTP
# IMAP is used to fetch emails while SMTP is used to send emails
class Gmail(object):
def __init__(self, email, password):
self.server = 'smtp.gmail.com'
self.port = 587
session = smtpli... |
import random
from collections import Counter
# >>> dict((x,l.count(x)) for x in set(l))
class OctaDie(object):
"""An eight-sided die (octahedron) instantiated for either attack or defence.
In attack, the faces of the die are, with their associated probability:
Hit (3 of 8, 37.5% probability)... |
'''
@author: Rahul Tanwani
@summary: Test cases to check compatibility between individual requests
and batch requests.
'''
import json
from django.test import TestCase
class TestCompatibility(TestCase):
'''
Tests compatibility.
'''
def assert_reponse_compatible(self, ind_resp, batch_... |
#
# This is a primitive script to parse the output of cdfIntegrate, and
# to generate a set of files (one for each track) that contains some of
# the integration results.
#
# It is intended as an example from which more useful scripts can be
# generated.
#
import sys
import re
import Point
from IntegrationLeg import In... |
#!/usr/bin/python3
'''
@file fractal_qt4_opengl_lib.py
@author Philip Wiese
@date 12 Okt 2016
@brief PyQt4 QGLWidget to displays Mandelbrot Set with OpenGl
'''
import sys, time
# PyQt4 imports
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtOpenGL import QGLWidget
# PyOpenGL imports
import OpenGL.GL ... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the rawtransaction RPCs.
Test the following RPCs:
- createrawtransaction
- signrawtransacti... |
from lemur.common.utils import parse_certificate
VALID_USER_HEADER_TOKEN = {
'Authorization': 'Basic ' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MjE2NTIwMjIsImV4cCI6MjM4NTY1MjAyMiwic3ViIjoxfQ.uK4PZjVAs0gt6_9h2EkYkKd64nFXdOq-rHsJZzeQicc',
'Content-Type': 'application/json'
}
VALID_ADMIN_HEADER_TOKEN... |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Spyder configuration options
Note: Leave this file free of Qt related imports, so that it can be used to
quickly load a user config file
"""
import... |
# Module to run tests on ararclines
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import numpy as np
import pytest
from astropy.table import Table
from pypeit import utils
from pypeit import artrace
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.