code
stringlengths
1
199k
""" This module contains tasks for asynchronous execution of grade updates. """ from logging import getLogger import six from celery import task from celery_utils.logged_task import LoggedTask from celery_utils.persist_on_failure import PersistOnFailureTask from django.conf import settings from django.contrib.auth.mode...
import sys,os,json import course,rectangle,details import caldata import csvverifier import year import datetime year = year.Year([datetime.date(2011,10,4),datetime.date(2012,1,17),datetime.date(2012,4,24)]) def update_calendar(det_str,cal): c = course.Course(det_str['id'],det_str['name']) cal.refresh_course(c)...
"""Module for handling miscellaneous web pages of the website."""
import numpy as np from math import * from essentia_test import * class TestFalseStereoDetector(TestCase): def testZero(self): size = 512 zeros = array([(0., 0.)] * size) self.assertEqual(FalseStereoDetector()(zeros), (0, 0.)) def testOneChannelBias(self): ...
from PIL import Image import glob, os for infile in glob.glob("*.jpg"): file, ext = os.path.splitext(infile) im = Image.open(infile) width, height = im.size sizem = 1024,height if int(width) > 1024: imm.thumbnail(sizem, Image.ANTIALIAS) imm.save(file + "_display_1024","JPEG") els...
from odoo import fields, models class ResCompany(models.Model): _inherit = "res.company" cons_invoice_text = fields.Html() due_from_account_id = fields.Many2one("account.account", "Due From") due_to_account_id = fields.Many2one("account.account", "Due To") due_fromto_payment_journal_id = fields.Many...
""" Tests for course_overviews app. """ from cStringIO import StringIO import datetime import ddt import itertools import math import mock import pytz from django.conf import settings from django.test.utils import override_settings from django.utils import timezone from PIL import Image from lms.djangoapps.certificates...
from decimal import Decimal from weboob.capabilities.bank import Investment from weboob.tools.browser2.page import RawPage, HTMLPage, method, ListElement, ItemElement from weboob.tools.browser2.filters import CleanDecimal, CleanText, Date from weboob.tools.capabilities.bank.transactions import FrenchTransaction __all__...
""" Provides XML I{element} classes. """ from logging import getLogger from suds import * from suds.sax import * from suds.sax.attribute import Attribute import sys if sys.version_info < (2, 4, 0): from sets import Set as set del sys log = getLogger(__name__) class Element: """ An XML element object. ...
from odoo import api, fields, models, _ from odoo.exceptions import UserError class HelpDeskPhoneCallConfirm(models.TransientModel): _name = 'helpdesk.phonecall.confirm' _description = 'Wizard to confirm phonecall' @api.multi def action_confirm_finish_phonecall(self): context = dict(self._contex...
import numpy as np from numpy.linalg import inv from numpy.core.umath_tests import inner1d def initialize_gpu(): from cudamat import cudamat as cm global cm # this class wraps matrix operations so that you can switch between numpy and cuda operations cm.cuda_set_device(0) cm.init() def random(size,t...
import inspect import functools import logging import uuid import sys from datetime import datetime, timedelta, MINYEAR from cPickle import loads, dumps, UnpicklingError from openerp import SUPERUSER_ID from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT from openerp.tools.translate import _ from ..exception impor...
from __future__ import (unicode_literals, print_function, absolute_import, division) from pyramid.i18n import TranslationStringFactory from netprofile.common.hooks import register_hook _ = TranslationStringFactory('netprofile_domains') @register_hook('core.dpanetabs.domains.Domain') def _dpane_d...
from intelmq.lib.bot import Bot, sys from intelmq.lib.message import Event from intelmq.lib import utils class DragonResearchGroupSSHParserBot(Bot): def process(self): report = self.receive_message() if not report.contains("raw"): self.acknowledge_message() raw_report = utils.bas...
from . import models from . import wizard from . import tests
"""Provide kiskadee Database operations.""" from sqlalchemy import create_engine, orm import kiskadee from kiskadee.model import Base from kiskadee.model import Package, Fetcher, Version, Report, Analysis class Database: """kiskadee Database class.""" def __init__(self, db='db_development'): """Return a...
""" This module provides utility functions for django_comment_client """ from pymongo.errors import PyMongoError from pymongo import MongoClient from django.conf import settings from django.contrib.auth.models import User MONGO_PARAMS = settings.FORUM_MONGO_PARAMS def get_mongo_connection_string(): """ Creates ...
""" @file TP.py Temporal pooler implementation. This is the Python implementation and is used as the base class for the C++ implementation. """ import copy import cPickle as pickle import itertools import numpy from nupic.bindings.math import Random from nupic.bindings.algorithms import getSegmentActivityLevel, isSegme...
from flask import Blueprint, render_template ag4_40323109 = Blueprint('ag4_40323109', __name__, url_prefix='/ag4_40323109', template_folder='templates') @ag4_40323109.route('/A') def task1(): outstring = ''' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>網際 2D 繪圖</title> <!-- IE 9: disp...
from odoo import api, models, fields class GlobalTag(models.Model): _inherit = 'clv.global_tag' family_aux_ids = fields.Many2many( comodel_name='clv.family_aux', relation='clv_family_aux_global_tag_rel', column1='global_tag_id', column2='family_aux_id', string='Families (...
""" Extension of the datetime module to suit HRSelf project needs. """ import datetime from datetime import timedelta import types import xmlrpclib DAY = DAYS = timedelta(days=1) DATE_FORMAT = '%Y-%m-%d' DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' XML_RPC_DATETIME_FORMAT = '%Y%m%dT%H:%M:%S' def to_date(obj, date_format=None)...
from __future__ import unicode_literals import urllib from copy import deepcopy from mock import MagicMock, mock_open from nose_parameterized import parameterized from django.test import TestCase from django.core.exceptions import ObjectDoesNotExist from django.test.utils import override_settings from wstore.asset_mana...
"""Views, navigation and actions for BranchMergeProposals.""" __metaclass__ = type __all__ = [ 'BranchMergeCandidateView', 'BranchMergeProposalActionNavigationMenu', 'BranchMergeProposalAddVoteView', 'BranchMergeProposalChangeStatusView', 'BranchMergeProposalCommitMessageEditView', 'BranchMergeP...
from io import BytesIO import json import os import re from hashlib import md5 from itertools import chain import unicodedata import mimetypes from django.conf import settings from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.core.exceptions import Va...
""" Unit tests for video-related REST APIs. """ import csv import json import re from datetime import datetime from functools import wraps from StringIO import StringIO from contextlib import contextmanager import dateutil.parser import ddt import pytz from django.conf import settings from django.test.utils import over...
""" Mappers ======= Mappers are the ConnectorUnit classes responsible to transform external records into Odoo records and conversely. """ import logging from collections import namedtuple from contextlib import contextmanager from odoo import models from ..connector import ConnectorUnit, MetaConnectorUnit, ConnectorEnv...
from . import mrp_product_caliber
import json import nose import sys from nose.tools import assert_equal, raises import pylons from pylons import config import sqlalchemy.orm as orm import paste.fixture import ckan.plugins as p import ckan.lib.create_test_data as ctd import ckan.model as model import ckan.tests.legacy as tests import ckan.config.middle...
from django.contrib.auth.models import User from django.urls import reverse from wger.core.tests.base_testcase import WgerTestCase from wger.utils.helpers import make_token class WorkoutPdfLogExportTestCase(WgerTestCase): """ Tests exporting a workout as a pdf """ def export_pdf_token(self): """...
{ '!langcode!': 'id', '!langname!': 'Indonesian', '%d days ago': '%d hari yang lalu', '%d hours ago': '%d jam yang lalu', '%d minutes ago': '%d menit yang lalu', '%d months ago': '%d bulan yang lalu', '%d seconds ago': '%d detik yang lalu', '%d seconds from now': '%d detik dari sekarang', '%d weeks ago': '%d minggu yan...
from numpy import median from numpy import where import numpy as np from pitchfilter.pitchfilter import PitchFilter from morty.pitchdistribution import PitchDistribution from morty.converter import Converter import matplotlib.pyplot as plt import matplotlib.ticker from copy import deepcopy __author__ = 'hsercanatli' cl...
""" Serializers for use in the support app. """ from rest_framework import serializers from student.models import ManualEnrollmentAudit class ManualEnrollmentSerializer(serializers.ModelSerializer): """Serializes a manual enrollment audit object.""" enrolled_by = serializers.SlugRelatedField(slug_field='email',...
__metaclass__ = type from doctest import DocTestSuite import time import unittest from zope.interface import ( directlyProvidedBy, directlyProvides, ) from lp.registry.interfaces.person import PersonVisibility from lp.services.mail.helpers import ( ensure_not_weakly_authenticated, ensure_sane_signat...
import json import requests import rdflib from pylons import config import ckan.plugins as p from ckanext.dcat.interfaces import IDCATRDFHarvester from ckanext.sweden.dcat import template_helpers VALIDATION_SERVICE = 'https://validator.dcat-editor.com/service' rdflib.plugin.register( 'application/octet-stream', rdf...
from . import test_analytic_attribution
from AccessControl import getSecurityManager from Products.CMFCore.permissions import ModifyPortalContent from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t from bika.lims.browser.bika_listing import BikaListingView from bika.lims.utils import getUsers from bika.lims.permissions import * from b...
import copy from shinken_test import * class TestConfig(ShinkenTest): #setUp is in shinken_test def get_hst(self): return self.sched.hosts.find_by_name("test_host_0") #Look if get_*_name return the good result def test_get_name(self): hst = self.get_hst() print hst.get_dbg_name()...
import nose from flask_testing import TestCase if __name__ == '__main__' and __package__ is None: from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from call_server.app import create_app, db from call_server.config import TestingConfig from call_server.extensions impor...
import pytest from edisgo.network.topology import Topology from edisgo.io import ding0_import from edisgo.network.components import Generator, Load, Switch from edisgo.network.grids import LVGrid class TestGrids: @classmethod def setup_class(self): self.topology = Topology() ding0_import.import_...
from __future__ import unicode_literals from collections import OrderedDict import json from random import randint from django.utils import timezone from dash.categories.models import Category from dash.orgs.models import Org from dash.stories.models import Story from datetime import datetime from django.contrib.auth.m...
import sys import os import shlex from sphinx import version_info major, minor, patch, label, label_number = version_info sys.path.insert(0, os.path.abspath('../src')) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx' ] if major >= 1 and minor >= 3: # Included in Sphinx 1.3 extensions.append...
'''Infrastructure helpers for the library.''' __all__ = ('get_class_name', 'combination', 'RejectError', 'Taker', 'Args') import types def get_class_name(obj): return obj.__class__.__name__ class RejectError(Exception): pass class Taker(object): '''Base class for taker objects. The Taker base class give...
""" Tests for pkgdb messages """ import unittest from fedmsg.tests.test_meta import Base from .common import add_doc class TestPkgdbACLUpdate(Base): """ The Fedora `Package DB <https://admin.fedoraproject.org/pkgdb>`_ publishes these messages when an ACL changes on a package. """ expected_title = "pkgdb...
""" This module implements a fancy logger on top of python logging It adds: - custom specifiers for mpi logging (the mpirank) with autodetection of mpi - custom specifier for always showing the calling function's name - rotating file handler - a default formatter. - logging to an UDP server (vsc.logging.logdaemon....
from unittest import TestCase from mock import patch, Mock from gofer.common import ThreadSingleton from gofer.messaging.model import Document, VERSION from gofer.messaging.adapter.url import URL from gofer.messaging.adapter.model import Model, _Domain, Node from gofer.messaging.adapter.model import BaseExchange, Excha...
"""Test of cell and row reading in Writer tables.""" from macaroon.playback import * import utils sequence = MacroSequence() sequence.append(PauseAction(5000)) sequence.append(KeyComboAction("<Control>Home")) sequence.append(KeyComboAction("Down")) sequence.append(KeyComboAction("Down")) sequence.append(KeyComboAction(...
from setuptools import setup from subprocess import Popen, PIPE import os import re def read_file(path): with open(os.path.join(os.path.dirname(__file__), path)) as fp: return fp.read() def _get_version_match(content): # Search for lines of the form: # __version__ = 'ver' regex = r"^__version__ = ['...
import soaplib from soaplib.core.service import soap from soaplib.core.service import DefinitionBase from soaplib.core.model.primitive import String, Integer from soaplib.core.server import wsgi from soaplib.core.model.clazz import Array ''' This is a simple HelloWorld example to show the basics of writing a webservice...
from api import ProteusClient
from threading import Thread, get_ident, Barrier from functools import update_wrapper from gi.repository import Gtk, GLib class GuiThread(Thread): thread_id = None instance = None def __init__(self): super().__init__(daemon=True) self.start() GuiThread.instace = self def run(self...
""" Created on Sat Oct 3 13:06:06 2015 An Article object that holds information about a scientific article obtained from the Internet. @author: Alek @version: 1.0.0 @since: Sat Oct 3 13:06:06 2015 CHANGELOG: Sat Oct 3 13:06:06 2015 - 1.0.0 - Alek - Issued the first version based on a class previously defined elsewhe...
from pycp2k.inputsection import InputSection class _each284(InputSection): def __init__(self): InputSection.__init__(self) self.Just_energy = None self.Powell_opt = None self.Qs_scf = None self.Xas_scf = None self.Md = None self.Pint = None self.Metady...
from django.conf.urls import url, include PK = r'(?P<pk>\d+)' SLUG = r'(?P<slug>[-a-zA-Z0-9_]+)' def pattern(*args): return r'^{}/?$'.format('/'.join(args)) def mini_url(view, *args): name = '_'.join([i for i in args if '?P' not in i]) return url(pattern(*args), view.as_view(), name=name) def list_url(view,...
"""Connectors""" __copyright__ = "Copyright (C) 2014 Ivan D Vasin" __docformat__ = "restructuredtext" from base64 import b64decode as _b64decode from ... import plain as _plain from ... import http as _http from ... import _exc from ... import _info from .. import _std_http class TornadoHttpBasicClerk(_std_http.Tornado...
import numpy as np from yt.mods import * from yt.utilities.physical_constants import cm_per_kpc, cm_per_mpc import logging logging.getLogger().setLevel(logging.WARNING) data = dict(ZVelocity = freeprocessing.stream) pf = load_uniform_grid(data, data["ZVelocity"].shape, cm_per_mpc, nprocs=1) print...
from __future__ import print_function, absolute_import, division import os import sys BASEPATH = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../')) if BASEPATH not in sys.path: sys.path.append(BASEPATH) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "flutype_webapp.settings") impo...
import operator import sys COMMONHEADER = """ /* DO NOT EDIT! This is an autogenerated file. See scripts/layoutrom.py. */ OUTPUT_FORMAT("elf32-i386") OUTPUT_ARCH("i386") SECTIONS { """ COMMONTRAILER = """ /* Discard regular data sections to force a link error if * code attempts to access data not mar...
import numpy as np from pykdtree.kdtree import KDTree data_pts_real = np.array([[ 790535.062, -369324.656, 6310963.5 ], [ 790024.312, -365155.688, 6311270. ], [ 789515.75 , -361009.469, 6311572. ], [ 789011. , -356886.562, 6311869.5 ], [ 788508.438, -352785.969, 631216...
""" This demo program illustrates how to solve Poisson's equation - div grad u(x, y) = f(x, y) on the unit square with pure Neumann boundary conditions: du/dn(x, y) = -sin(5*x) and source f given by f(x, y) = 10*exp(-((x - 0.5)^2 + (y - 0.5)^2) / 0.02) Since only Neumann conditions are applied, u is only de...
import os from cork.backends import SQLiteBackend def populate_backend(): b = SQLiteBackend(os.environ['DBNAME'], initialize=True) b.connection.executescript(""" INSERT INTO users (username, email_addr, desc, role, hash, creation_date) VALUES ( 'admin', 'admin@ccl.io', ...
from __future__ import division from __future__ import print_function def input(in_msg): import inspect in_msg.input_file = inspect.getfile(inspect.currentframe()) print("*** read input from ", in_msg.input_file) # 8=MSG1, 9=MSG2, 10=MSG3 in_msg.sat = "Meteosat" #in_msg.sat = "meteosat" #in_...
__all__ = ['protocols', 'transport', 'endpoint']
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'wj9rt420!n0(np*gi6#rpb7)y*b2qzp#@3l8p66na#q(4svs!e' DEBUG = True ALLOWED_HOSTS = ['localhost', 'django'] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django...
def layout(req): """This function is included in TEMPLATE_CONTEXT_PROCESSORS as default by RapidSMS, to inject hacks and settings into the template, without exposing the entire HttpRequest. That would be... bad.""" # a magic GET parameter can be provided to remove various # parts of the webui....
import sys import os RULES = """ANALYSIS_STOPS|(disabled by default) ARRAY_OUT_OF_BOUNDS_L1|(disabled by default) ARRAY_OUT_OF_BOUNDS_L2|(disabled by default) ARRAY_OUT_OF_BOUNDS_L3|(disabled by default) Abduction_case_not_implemented|(enabled by default) Array_of_pointsto|(enabled by default) Assert_failure|(enabled b...
N=int(input("cuantos numeros promediaremos? ")) if N > 0: contador = 0 suma = 0 while contador < N: numero = int(input("entregame el numero "+str(contador+1)+": ")) suma = suma + numero contador = contador + 1 promedio = suma/N print("el promedio es "+str(promedio)) if N <= 0...
class Date( object ): __name = [ "Invalid", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] __days = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] def __init__( self, month=0, day=0, year=0 ): """ Cons...
__description__ = \ """ Still a hacked script. Uses a nexus file to figure out the names of each sequence in a set of trees generated by a mrbayes run, then puts those names into the tree file. """ import sys, re from string import letters from random import choice f = open(sys.argv[1],'r') lines = f.readlines() f.clo...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( compat_urllib_parse, compat_urllib_request, ExtractorError, find_xpath_attr, fix_xml_ampersands, HEADRequest, unescapeHTML, url_basename, RegexNotFoundError, ) def _media_xml_tag...
''' Created on 04.05.2015 @author: vvladych ''' from gi.repository import Gtk from masterdata_abstract_window import MasterdataAbstractWindow from publisher_add_mask import PublisherAddMask from publisher_list_mask import PublisherListMask class PublisherWindow(MasterdataAbstractWindow): def __init__(self, main_win...
from setuptools import find_packages from setuptools import setup REQUIRED_PACKAGES = [ 'tensorflow>=1.12.1', ] setup( name='trainer', version='0.1', install_requires=REQUIRED_PACKAGES, packages=find_packages(), include_package_data=True, requires=[] )
from os import environ from base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': environ.get('DATABASE_NAME'), 'USER': environ.get('DATABASE_USER'), 'PASSWORD': environ.get('DATABASE_PASSWORD'), 'HOST': environ.get('DATABASE_HOS...
"""Code to run lending experiments.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import attr import core import params import rewards import run_util from agents import classifier_agents from agents import oracle_lending_agent from agents import thresho...
from __future__ import absolute_import from __future__ import print_function from enable.component_editor import ComponentEditor from traits.api import HasTraits, Any from traitsui.api import View, Item class ExtractionLineCanvas(HasTraits): """ """ canvas2D = Any manager = Any def toggle_item_ident...
from libs.traits import IntegerTrait from libs.individuals import Individual from libs.biosphere import Biosphere TARGET = raw_input("String to evolve: "); traits = {} class GuesserTrait(IntegerTrait): int_min = 0 int_max = 255 delta = 5 class StringGuesser(Individual): traits = traits mutation_chan...
""" File: urls.py Author: William J. Bosl Children's Hospital Boston 300 Longwood Avenue Boston, MA 02115 Email: william.bosl@childrens.harvard.edu Web: http://chip.org Copyright (C) 2011 William Bosl, Children's Hospital Boston Informatics Program (CHIP) http://chip.org. Purpose...
import sys import os from xml.sax import make_parser, handler import xml from util_binary import * from struct import * execfile(os.path.join(os.path.dirname(__file__), "weights.py")) class LoadOsm(handler.ContentHandler): """Parse an OSM file looking for routing information, and do routing with it""" def __init__(...
"""Utils for upright 3d box.""" import tensorflow as tf from waymo_open_dataset import label_pb2 from waymo_open_dataset.utils import transform_utils __all__ = [ 'is_within_box_3d', 'compute_num_points_in_box_3d', 'is_within_box_2d', 'get_upright_3d_box_corners', 'transform_point', 'transform_box', 'box_to_...
import abc import fractions from oslo_config import cfg from oslo_log import log as logging import six from stevedore import driver from voluptuous import All from voluptuous import Any from voluptuous import Coerce from voluptuous import Error as VoluptuousError from voluptuous import In from voluptuous import Invalid...
"""service_profile """ revision = '9744740aa75c' down_revision = 'fd98aa15958d' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'service_profiles', sa.Column('id', sa.String(36), nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True), ...
from django.shortcuts import render from nuit.views import SearchableListView from .models import Publisher from .forms import PublisherForm from django.contrib import messages from django.contrib.auth.decorators import permission_required class MyListView(SearchableListView): model = Publisher template_name = ...
''' You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 ''' ''' The main idea is quite simple, but need to...
import ray ray.init(num_cpus=2) def compute(i): return i * 2 pipeline = ray.data.range(10).repeat(100) pipeline = pipeline.map(compute).map(compute).map(compute).map(compute) pipeline.repartition(1).write_json("/tmp/output")
import os import pytest import subprocess import glob import pdb def test_runGATK_UG(hive_dir, bgzip_folder, gatk_folder, datadir, clean_tmp): bam_file = "{0}/exampleBAM.bam".format(datadir) reference = "{0}/exampleFASTA.fasta".format(datadir) work_dir = "{0}/outdir".format(datadir) command="perl {0}/sc...
import os, sys, traceback, math, decimal import arcpy from arcpy import env from arcpy import sa def zfactor(dataset): desc = arcpy.Describe(dataset) # if it's not geographic return 1.0 if desc.spatialReference.type != "Geographic": return 1.0 extent = desc.Extent extent_split = [extent.XMin...
import re import collections from enum import Enum from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST, ...
import os from traits.api import Dict from pychron.core.helpers.strtools import to_csv_str from pychron.loggable import Loggable from pychron.paths import paths def write_txt_file(p, out): with open(p, 'w') as wfile: for line in out: wfile.write('{}\n'.format(to_csv_str(line))) class AutomatedRu...
from google.cloud import dialogflowcx_v3beta1 async def sample_create_transition_route_group(): # Create a client client = dialogflowcx_v3beta1.TransitionRouteGroupsAsyncClient() # Initialize request argument(s) transition_route_group = dialogflowcx_v3beta1.TransitionRouteGroup() transition_route_gr...
''' Copyright 2018 University of Michigan 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 a...
import os import sys try: from setuptools import find_packages from setuptools import setup packages = find_packages() except ImportError: from distutils.core import setup packages = ['cooperative'] if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() def read(f...
import pandas as pd import os KNOWLEDGE_BASE_PATH = os.path.dirname(__file__) KNOWLEDGE_BASE_FILE = os.path.join(KNOWLEDGE_BASE_PATH, "periodic-table-extract.csv") def get_kb_value(element, column_name): kb = pd.read_csv(KNOWLEDGE_BASE_FILE, dtype=object) return str(kb[kb["Element"].str.lower() == element.lower...
"""Tests for tensorflow.python.framework.ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.python.platform from tensorflow.python.framework import device as pydev from tensorflow.python.framework import ops from tensorflow.python.frame...
tequila_list = ["Jose Cuervo", "JLP", "Herradura", "El Jimador", "Arette", "Casa Noble","Don Julio Blanco", "Don Julio", "Don Julio 1942", "KAH", "Patron",\ "Porfidio", "1800", "1800 Anejo", "Fortaleza", "T1", "Gran Centenario", "Jose Cuervo Reserva"] weights = { "jose cuervo":0.9, #guess "jlp":...
import json import logging import os, csv from utils import Util from subprocess import check_output, CalledProcessError class Reputation(object): BATCH_SIZE = 1 REP_KEY = 'rep' CAT_KEY = 'cat' AFLAG_KEY = 'aflag' DEFAULT_REP = 16 QUERY_PLACEHOLDER = "###QUERY###" def __init__(self,conf,logg...
from __future__ import absolute_import from __future__ import division from __future__ import print_function class Preprocessor(object): """Defines an abstract observation preprocessor function.""" def __init__(self, options): self.options = options self._init() def _init(self): pass...
import hashlib import plistlib from datetime import datetime from django.utils import timezone from urllib import quote import unicodecsv as csv from django.conf import settings from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.http import (HttpResponse, ...
import RPi.GPIO as GPIO import time import os import gpio_utilities power_pin = 43 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(power_pin, GPIO.IN) try: while True: if gpio_utilities.getGPIOInput(power_pin1, 20) == GPIO.LOW: # print GPIO.input(power_pin) os.system("halt"...
import threading class LocalizationData: def __init__(self, localization_pb=None): self.localization_pb = localization_pb def update(self, localization_pb): self.localization_pb = localization_pb
"""Tests for ceilometer/storage/impl_mongodb.py .. note:: In order to run the tests against another MongoDB server set the environment variable CEILOMETER_TEST_MONGODB_URL to point to a MongoDB server before running the tests. """ from ceilometer.storage import base from ceilometer.storage import impl_mongodb fro...
from gyun.iaas import constants as const from gyun.misc.utils import filter_out_none class S2Action(object): def __init__(self, conn): self.conn = conn def create_s2_server(self, vxnet, service_type, s2_server_name=None, ...