content
string
# Python 2.6's urllib2 does not allow you to select the TLS dialect, # and by default uses a SSLv23 compatibility negotiation implementation. # Besides being vulnerable to POODLE, the OSX implementation doesn't # work correctly, failing to connect to servers that respond only to # TLS1.0+. These classes help set up TL...
# -*- coding: utf-8 -*- """ /*************************************************************************** Multi-Hazard Child Vulnerability Analysis and Mapping Plugin A QGIS plugin that performs Multi-Hazard Child Vulnerability Analysis and Mapping begin : 2017-01-03 copyright ...
from .. import protocols from .lexer import KatcpLexer from prompt_toolkit.lexers import PygmentsLexer class KatcpProtocol(protocols.Protocol): ARGS = { 'unescape': protocols.Argument(bool) } def __init__(self, name, arglist): self.unescape = False super().__init__(name, arglist)...
import sys, os, re import logging from types import StringTypes from lib.data.BackendResult import BackendResult from lib.ProgrammingBackend import EX_OK # local imports from backends.haskell.Haskell import Haskell from backends.haskell.Haskell import inputSchema from backends.haskell.Haskell import tests from backe...
from flask import Flask, render_template, redirect, request, session, \ flash, url_for import os import time import datetime import pymongo import requests from functools import wraps from jinja2 import Template app = Flask(__name__) app.secret_key = os.environ['SECRET_KEY'] db = py...
from django.conf import settings from django.core.management.base import BaseCommand, CommandError import logging import os import subprocess class Command(BaseCommand): help = 'Reads the contents of the upload_data_cache directory and uploads observations to DAFWA' def handle(self, *args, **options): ...
import numpy.testing as npt from pyewa.bases import Constant, Linear from pyewa.utils import create_support class TestConstant(object): def test_constant_init(self): c = Constant() assert c.M == 10 # Test multidimensionnal support support = create_support(base_dimension=3) ...
# -*- coding: utf-8 -*- # https://bitbucket.org/exirel/epub """Library to open and read files in the epub version 2.""" from __future__ import unicode_literals __author__ = 'Florian Strzelecki <<EMAIL>>' __version__ = '0.5.3' __all__ = ['opf', 'ncx', 'utils'] import os import shutil import tempfile import uuid impo...
""" perf is a tool included in the linux kernel tree that supports functionality similar to oprofile and more. @see: http://lwn.net/Articles/310260/ """ import time, os, stat, subprocess, signal import logging from autotest_lib.client.bin import profiler, os_dep, utils class perf(profiler.profiler): version = 1...
from django.contrib.syndication.feeds import Feed from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext as _ from django.shortcuts import get_object_or_404 from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.auth.models import U...
import urllib import re from assembla.error import AssemblaError from assembla.utils import convert_to_utf8_str re_path_template = re.compile('{\w+}') def bind_api(**config): class APIMethod(object): path = config['path'] payload_type = config.get('payload_type', None) payload_list = c...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'App' db.create_table('api_app', ( (u'id', self.gf('django.db.models.fields.AutoF...
def select_dict(coll, key, value): """ Given an iterable of dictionaries, return the dictionaries where the values at a given key match the given value. If the value is an iterable of objects, the function will consider any to be a match. This is especially useful when calling REST APIs which ...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Opportunity.fullfilled' db.delete_column(u'volunteers_opportunity', 'fullfilled') ...
from django import forms from forum.models import ForumUser class LoginForm(forms.Form): username = forms.CharField(min_length=4) password = forms.CharField(widget=forms.PasswordInput, min_length=6, max_length=28) class RegisterForm(forms.Form): username = forms.CharField...
import vigra import opengm import numpy import matplotlib.pyplot as plt img = vigra.readImage('/home/tbeier/datasets/BSR/BSDS500/data/images/train/56028.jpg') img = vigra.readImage('/home/tbeier/datasets/BSR/BSDS500/data/images/train/118035.jpg') img = img[::1, ::1,:] grad = vigra.filters.gaussianGradientMagnitude(vigr...
# -*- coding: utf-8; indent-tabs-mode: t; python-indent: 4; tab-width: 4 -*- """ This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase...
import argparse, os, time import urlparse, random from selenium import webdriver from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup #from pyvirtualdisplay import Display def SleepThread(interval = 0, add = 20.0): print 'START SLEEP ' + str(interval) if(interval > 0): time...
import logging import matplotlib.pyplot as plt import yaml import library """Q: How many patchsets to merge? Plot over time. Factor in LOC? """ logging.basicConfig() logger = logging.getLogger("patchsets") logger.setLevel(logging.DEBUG) def get_revisions(change_ids, repo): revisions = [] for details in ...
# -*- coding: utf-8 -*- """ Copyright 2015 Randal S. Olson This file is part of the Twitter Bot library. The Twitter Bot library 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, ...
#!/usr/bin/python3 import sys import optparse import buildconf class bcolors: HEADER = '\033[95m' USO = '\033[94m' OK = '\033[92m' WARNING = '\033[93m' KO = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def main(build1,build2): b1 = buildconf.BuildConf(build...
from setuptools import setup, find_packages try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') except ImportError: print("warning: pypandoc module not found, could not convert Markdown to RST") read_md = lambda f: open(f, 'r').read() tests_require = [ # 'mock', 'nose', ...
import logging from . import Analysis l = logging.getLogger(name=__name__) class SootClassHierarchyError(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class NoConcreteDispatch(SootClassHierarchyError): def __init__(self, msg): self.msg ...
# -*- coding: utf-8 -*- from gettext import gettext as _ NAME = _('Paraguay') STATES = [ (_('Alto Paraguay'), 254, 267, 128, 0), (_('Boquerón'), 253, 146, 294, 0), (_('Presidente Hayes'), 252, 367, 460, 0), (_('Concepción'), 251, 509, 390, -45), (_('Amambay'), 250, 605, 394, -70), (_('San Ped...
from tincan.serializable_base import SerializableBase """ .. module:: languagemap :synopsis: A simple wrapper for a map containing language mappings """ class LanguageMap(dict, SerializableBase): def __init__(self, *args, **kwargs): """Initializes a LanguageMap with the given mapping This co...
#!/usr/bin/python import ctypes import os from time import time from errno import errorcode class MessageQueueError(Exception): """Base error class for problems from the underlying library.""" class Timeout(MessageQueueError): """Exception for tiemouts on send, recv operations.""" class MessageQueueAttribut...
import math, geopy from rest_framework import viewsets, generics from geopy.distance import distance from geopy.geocoders import GoogleV3 from .models import Truck from .serializers import TruckSerializer class TruckViewSet(viewsets.ModelViewSet): """DRF default viewset provides basic read/write access to Truck ...
from ConfigParser import NoSectionError, NoOptionError import time from urllib import urlencode from urlparse import urljoin from twisted.internet import defer from twisted.web.client import getPage try: import simplejson as json except ImportError: import json from cattivo.log.loggable import Loggable from ...
from oslo_log import log as logging from neutron.agent.linux import utils as agent_utils LOG = logging.getLogger(__name__) # NOTE: Runtime checks are strongly discouraged in favor of sanity checks # which would be run at system setup time. Please consider writing a # sanity check instead. def dhcp_rel...
def Setup(Settings, DefaultModel): # set5-osm-model-variable-widths-depths/set5_w32_depth2_d1.py Settings["experiment_name"] = "set5_w32_depth2_d1" Settings["graph_histories"] = [] # ['all','together',[],[1,0],[0,0,0],[]] n = 0 #d1 5556x_markable_640x640 SegmentsData_marked_R100_4...
import logging from flask import current_app as app from superdesk import get_resource_service from superdesk.celery_app import celery from superdesk.notification import push_notification from celery.exceptions import SoftTimeLimitExceeded from liveblog.blogs.tasks import publish_blog_embeds_on_s3 from liveblog.blogs....
""" C++ source code generator for the vehicle interface firmware. """ import os import operator import logging from openxc.utils import find_file LOG = logging.getLogger(__name__) class CodeGenerator(object): """This class is used to build an implementation of the signals.h functions from one or more CAN me...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Channel.main_image' ...
#! /usr/bin/python # Title: samsungremote.py # Info: To send remote control commands to the Samsung tv over LAN # TODO: import socket import base64 import time, datetime from time import sleep #IP Address of TV tvip = "192.168.0.119" #IP Address of TV myip = str(socket.gethostbyname(socket.gethostname()))...
import sys import bonediagd_DHT # Parse command line parameters. sensor_args = { '11': bonediagd_DHT.DHT11, '22': bonediagd_DHT.DHT22, '2302': bonediagd_DHT.AM2302 } if len(sys.argv) == 3 and sys.argv[1] in sensor_args: sensor = sensor_args[sys.argv[1]] pin = sys.argv[2] else: p...
from numpy import * from itertools import combinations, chain from numpy.linalg import det, pinv, slogdet # core function def dPCA(Y,ncomp,tolerance = 10e-3,maxloop=100): ''' Y - data as np.array, one dimension per parameter ncomp - # of components to compute tolerance - breaking conditi...
from msrest.serialization import Model class EffectiveNetworkSecurityGroupListResult(Model): """Response for list effective network security groups API service call. Variables are only populated by the server, and will be ignored when sending a request. :param value: A list of effective network secu...
import json import logging import re from api.api_samples.python_client.api_client import CloudBoltAPIClient from api.api_samples.python_client.samples.api_helpers import wait_for_order_completion from common.methods import set_progress from servicecatalog.models import ServiceBlueprint from utilities.exceptions impor...
import argparse from seed.workflow.creation import create_seed from seed.workflow.listing import list_templates def main(): parse_arguments() def parse_arguments(): parser = argparse.ArgumentParser(description='seed bootstraps new slingring universe seeds.') subparsers = parser.add_subparsers(help='the...
# -*- coding: utf-8 -*- from PyQt4 import QtCore,QtGui import pyqtgraph as pg import zmq from .tools import RecvPosThread, MultiChannelParamsSetter from .guiutil import * from .multichannelparam import MultiChannelParam import time from matplotlib.cm import get_cmap from matplotlib.colors import ColorConverter #~ i...
import pytest from cachspeak import settings def test_unloaded_configurator(): """Assert CachspeakConfigParser raises when used without having loaded a file.""" config_parser = settings.CachspeakConfigParser() with pytest.raises(RuntimeError): config_parser.get('dummy_section', 'dummy_value') @...
#!/usr/bin/python # Quick and dirty backup of your git files. from pygithub3 import Github import git import os import subprocess os.chdir('/home/git/repositories') gh = Github(login='git') for user in ['JoeDumoulin','soycamo','suspect-devices','feurig'] : for repo in gh.repos.list(user).all(): try: os...
import socket import yaml import pymongo class Kwargs(object): def __init__(self, **kwargs): for key, val in kwargs.items(): self.__setattr__(key, val) class Config(object): def __init__(self, filename): self.conf = yaml.load(open(filename)) self.mongo = Kwargs() ...
from ctypes import * # PLC TYPES Unknow=0 PLC=1 SLC500=2 LGX=3 # EIP DATA TYPES PLC_BIT=1 PLC_BIT_STRING=2 PLC_BYTE_STRING=3 PLC_INTEGER=4 PLC_TIMER=5 PLC_COUNTER=6 PLC_CONTROL=7 PLC_FLOATING=8 PLC_ARRAY=9 PLC_ADRESS=15 PLC_BCD=16 # LOGIX DATA TYPES LGX_BOOL=0xC1 LGX_BITARRAY=0xD3 LGX_SINT=0xC2 LGX_INT=0xC3 LGX_DINT...
from Tkinter import * import wizard as w import anydbm import time root = Tk() root.title("AutoBill for Bharat Security") root.minsize(width=753, height=404) root.config(background="#ffffff") #Menu Bar class topMenu(Menu): def __init__(self, root, **kwargs): Menu.__init__(self, root, **kwargs) ...
#!/usr/bin/env python3 import sys import re import textwrap import argparse import MySQLdb.cursors db = MySQLdb.connect(db='uniprot', host='wrpxdb.bioch.virginia.edu', user='web_user', passwd='fasta_www', cursorclass=MySQLdb.cursors.DictCursor) cur1 = db.cursor() cur2 = db.cursor() get_iso_acc='...
import json import time from pushmanager.core.util import get_servlet_urlspec from pushmanager.servlets.api import APIServlet from pushmanager.testing.testdb import FakeDataMixin from pushmanager.testing.testservlet import ServletTestMixin import pushmanager.testing as T class APITests(T.TestCase, ServletTestMixin, F...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/MedicinalProductManufactured) on 2019-05-07. # 2019, SMART Health IT. from . import domainresource class MedicinalProductManufactured(domainresource.DomainResource): """ The manufactu...
# -*- coding: ascii -*- r""" :Copyright: Copyright 2014 - 2016 Andr\xe9 Malo or his licensors, as applicable :License: 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....
#!/usr/bin/env python import sys import string ############################################################### ## # ## Edyta Malolepsza # ## David Wales' group, University of Cambridge # ## in case of p...
# Functions for python logging import tempfile import os import platform __LOG_FILE_NAME__ = None __IS_LOGGING__ = False def _calc_log_file_name(): return tempfile.mkdtemp()+"/rest.log" def _get_log_file_name(): return __LOG_FILE_NAME__ if __LOG_FILE_NAME__ != None else _calc_log_file_name() def _is_logging(): ret...
import base64 import collections import inspect # Some arguments to __init__ is mungled in order to avoid name conflicts # with builtin names. # The standard mangling is to append '_' in order to avoid name clashes # with reserved keywords. # # PEP8: # Function and method arguments # If a function argument's name c...
import re, urllib2 import simplejson as json import xbmc class API: DOMAIN = "http://iptv.kartina.tv/" REST_URL_PATTERN = "http://iptv.kartina.tv/api/json/%s" class Exception(Exception): def __init__(self, code, error): self.code = code self.error = error ...
bl_info = { "name": "Mesh Cache Tools", "author": "Oscurart", "version": (1, 0), "blender": (2, 70, 0), "location": "Tools > Mesh Cache Tools", "description": "Tools for Management Mesh Cache Process", "warning": "", "wiki_url": "", "tracker_url": "", "category": "Impor...
from __future__ import print_function, division, absolute_import from .download import fetch_file, fetch_and_transform, fetch_csv_dataframe from .database_helpers import ( db_from_dataframe, db_from_dataframes, db_from_dataframes_with_absolute_path, fetch_csv_db, connect_if_correct_version ) from ....
"""Provider code for BJ-Share.""" from __future__ import unicode_literals import re from requests.compat import urljoin from requests.utils import add_dict_to_cookiejar, dict_from_cookiejar from sickbeard import logger, tvcache from sickbeard.bs4_parser import BS4Parser from sickchill.helper.common import convert_s...
# encoding: UTF-8 import shelve from collections import OrderedDict from pymongo import MongoClient from pymongo.errors import ConnectionFailure from eventEngine import * from vtGateway import * from vtFunction import loadMongoSetting,loadMysqlSetting from ctaAlgo.ctaEngine import CtaEngine from dataRecorder.drEngi...
import sys import nltk from nltk import FreqDist import os import re import csv import string class Analyzer: """ Analyzes word counts across a given CSV file's columns. A word will count only once per cell of a column. Counds reflect the prevalence of that word across all cells in that column. The results ...
""" GUI progressbar decorator for iterators. Includes a default (x)range iterator printing to stderr. Usage: >>> from tqdm_gui import tgrange[, tqdm_gui] >>> for i in tgrange(10): #same as: for i in tqdm_gui(xrange(10)) ... ... """ # future division is important to divide integers and get as # a result preci...
#!/usr/bin/env python3 """ Generate calendars with garbage collection times in iCal format. # name: retrive.py # license: MIT # List all unique values of SUMMARY with following command # grep -rh SUMMARY ics|sort|uniq """ from datetime import datetime from os import getpid, listdir, makedirs, path, rename, sep from ...
import pytest from tests.utils import asyncio_patch @pytest.fixture(scope="function") async def vm(compute_api, compute_project, on_gns3vm): with asyncio_patch("gns3server.compute.builtin.nodes.cloud.Cloud._start_ubridge"): response = await compute_api.post("/projects/{project_id}/cloud/nodes".format(pr...
from functools import partial import pytest from stp_core.loop.eventually import eventually from plenum.common.messages.node_messages import PrePrepare from stp_core.common.util import adict from plenum.server.suspicion_codes import Suspicions from plenum.test.helper import getNodeSuspicions from plenum.test.instance...
# house price predicting import numpy as np import pandas as pd import matplotlib.pyplot as plt houseData = pd.read_csv("input/kc_house_data.csv").dropna(how="any") orgPrice = houseData.price orgBedrooms = houseData.bedrooms orgBathRooms = houseData.bathrooms orgSqftLiving = houseData.sqft_living orgSqftLot = houseDat...
""" Created on Jun 01, 2012 @author: Bilel Msekni @contact: <EMAIL> @author: Houssem Medhioub @contact: <EMAIL> @organization: Institut Mines-Telecom - Telecom SudParis @license: Apache License - Version 2.0 """ from pyocni.dispachers.single_entityDispatcher import SingleEntityDispatcher from pyocni.dispachers.multi_e...
import os import datetime import flask_testing import unittest from app import app, db from blapi.authorization.models import User from blapi.authorization.tests.factories import UserFactory from blapi.bucketlists.models import Bucketlist, BucketlistItems from blapi.bucketlists.tests.factories import \ BucketlistF...
import numpy as np import pytest import astropy.units as u from astropy.time import Time from astropy.utils.exceptions import AstropyWarning from astropy.coordinates import EarthLocation, AltAz, GCRS, SkyCoord, CIRS from astropy.coordinates.erfa_astrom import ( erfa_astrom, ErfaAstrom, ErfaAstromInterpolator ) ...
''' Strip parts of speech we don't want preps corpus for topic modelling, other processing mlw ''' import os import csv from bs4 import BeautifulSoup BASE_DIR = '/Users/widner/Projects/DLCL/Alduy/Rhetoric_of_LePen/' INPUT_DIR = BASE_DIR + 'results/treetagger/year/' OUTPUT_DIR = BASE_DIR + 'results/stripped/year/' i...
import turtle def main(): #Initialize screen and turtle window = turtle.Screen() window.setup(1365,720) window.bgcolor('black') T = turtle.Turtle() T.ht() T.speed(0) T.tracer(0,0) #Initialize rainbow rainbow = ['green','blue','indigo','violet','red','orange','yellow'] #Actual function for deg in range(1,362...
from sqlalchemy import Column, Integer, String, ForeignKey, Boolean from sqlalchemy.orm import relation, object_mapper from quantum.db import model_base from quantum.db import models_v2 as models from quantum.openstack.common import uuidutils class L2NetworkBase(object): """Base class for L2Network Models.""" ...
import tensorflow as tf def conv_layer(bottom, params, training): """Build a convolutional layer using entry from layer_params)""" batch_norm = params[4] # Boolean if batch_norm: activation = None else: activation = tf.nn.relu kernel_initializer = tf.contrib.layers.variance_sca...
""" Checks for files missing a checksum """ from dv_apps.datasets.models import Dataset#, DatasetVersion from dv_apps.datafiles.models import Datafile#, FileMetadata from django.db.models import Q from dv_apps.quality_checks.named_stat import NamedStat class NoChecksumStats(object): """Checks for files with no che...
# -*- coding: utf-8 -*- ''' Copyright 2015 by Tobias Houska This file is part of Statistical Parameter Estimation Tool (SPOTPY). :author: Tobias Houska This class holds example code how to use the FAST algorithm ''' import spotpy #from spotpy.examples.spot_setup_hymod_python import spot_setup from spotpy.examples.sp...
#!/usr/bin/env python # -*- coding: utf-8 -*- from CTFd.models import Users from tests.helpers import ( create_ctfd, destroy_ctfd, gen_award, login_as_user, register_user, ) def test_accessing_hidden_users(): """Hidden users should not give any data from /users or /api/v1/users""" app = c...
import pytest try: from unittest.mock import patch except ImportError: from mock import patch from alpenhorn import acquisition, extensions, generic @pytest.fixture def fixtures(): from alpenhorn import db db._connect() db.database_proxy.create_tables( [ acquisition.AcqTyp...
def prefs_manager_get_undo_actions_limit(): return 2000 def prefs_manager_get_bracket_matching(): return True def prefs_manager_get_enable_search_highlighting(): return True def prefs_manager_get_source_style_scheme(): return "classic" def prefs_manager_get_side_panel_size(): return 100 def prefs_manager_get_...
from __future__ import absolute_import, print_function from edenscm.mercurial import util from hghave import require def printifpresent(d, xs, name="d"): for x in xs: present = x in d print("'%s' in %s: %s" % (x, name, present)) if present: print("%s['%s']: %s" % (name, x, d[x...
"""BLEU metric implementation. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import re import subprocess import tempfile import numpy as np from six.moves import urllib import tensorflow as tf def m...
# Week 4 - Python Echo Client import socket from sys import argv, exit finished = False num_of_bytes = 1024 # No. of bytes to accept quit_message = "n" # Quit message to end program # Create a TCP socket print("Starting client...") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def main(): try: ...
# -*- coding: utf-8 -*- # Widget for HTML view in Turpial # import os from gi.repository import Gtk from gi.repository import GLib from gi.repository import WebKit from gi.repository import GObject class HtmlView(Gtk.VBox): __gsignals__ = { "action-request": (GObject.SignalFlags.RUN_FIRST, GObject.TYPE_...
#!/usr/bin/python """ CoovaChilli Python Library Copyright (C) 2009 David Bird <<EMAIL>> 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 2 of the License, or (at your option) an...
#this is the base class for tester objects import sys import subprocess import logging import os from time import clock from result import Result studentLogger = logging.getLogger('errorLogger.progressLogger.studentLogger') studentLogger.setLevel(logging.INFO) h = logging.StreamHandler() h.setLevel(logging.INFO) stude...
import os ''' import sys sys.path.insert(1, os.path.join(os.path.abspath('.'),'lib') ) ''' from flask import Flask,request,Response from datetime import datetime import pytz import random import MySQLdb from flask import render_template import json app = Flask(__name__,static_url_path='/static') def connectSQL(): ...
""" pghoard: clean up unused WAL from archive Copyright (c) 2017 Ohmu Ltd See LICENSE for details """ import argparse import logging import os import sys from pghoard import common, config, logutil, version from pghoard.rohmu import get_transfer from pghoard.rohmu.errors import (FileNotFoundFromStorageError, InvalidC...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.energy_management_system import EnergyManagementSystemTrendVariable log = logging.getLogger(__name__) class TestEnergyManagementSystemTrendVariable(unittest.TestCase): def ...
#!/usr/bin/env python import sys, os import unittest try: sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) except: sys.path.insert(0, os.path.dirname(os.path.abspath("."))) from intervaltree import Interval from intervaltree import IntervalTree from intervalforest import IntervalForest from uti...
#!/usr/bin/python import math,sys,re from operator import itemgetter import MySQLdb as mdb def read_db(query): #fl = open('/home/khaled/Documents/CS6220/query_tesla1.csv',"r") #data = fl.readlines() A = [] #for line in data: # B = line.rstrip('\n') # B = B.split(':') # A.append(...
""" A PyQT4 dialog to select specific series/volume from list """ """ Copyright 2012-2014 Anthony Beville 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...
import os import sys from types import ModuleType from importlib import import_module from importlib.abc import MetaPathFinder, Loader from importlib.machinery import ModuleSpec from importlib.util import module_from_spec class Bunch(dict): """A dict with from_name-access""" def __getattr__(self, key): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket from app import context as ctx, config as cfg from app.net import net, irc from app.utils import timeutil from app import thread def get_local_ip(): s = None try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((cfg.T...
""" :mod:`tier_1_mn_core_getstatus` =============================== :Created: 2011-04-22 :Author: DataONE (Dahl) :Dependencies: - python 2.6 """ import context import test_client import d1_test_case class Test015GetStatus(d1_test_case.D1TestCase): def test_010_getstatus(self): """GetStatus() does not...
from hint.hint_class_helpers.find_matches import find_matches class Prob9_Part1: """ Author: Jigar Patel Date: 10/11/2016 """ def check_attempt(self, params): #unpack params self.attempt = params['attempt'] #student's attempt self.answer = params['answer'] #solution self.att_tree = params['att_tree'] #at...
""" model.py ~~~~~~~~~~~~~~~ Handles data sets used to implement kNN. Each Model instance keeps track of a set of tuples that relate an instance type to a feature vector. New instances can be added from raw data files. Additionally, old models can be loaded into new ones. Models can also be saved. The main program ca...
"""Finds devices that can be controlled by telemetry.""" from telemetry.internal.platform import android_device from telemetry.internal.platform import cros_device from telemetry.internal.platform import desktop_device DEVICES = [ android_device, cros_device, desktop_device, ] def _GetAllAvailableDevice...
# import import numpy as np from nueralnet_classes import nodeNet # define animal class class Animal(object): def __init__(self, cords = [0, 0], life=10, visRange=1, visDim=1, symbols=20): self.cords = np.array(cords) # (y, x).. but we are symmetric under 90deg rotation self.life = np.float32(life)...
# coding=utf-8 ''' Created on Feb 2, 2012 @author: tmetsch ''' # disabling 'Too many public methods' pylint check (unittest's fault) # disabling 'Invalid name' pylint check (We need longer names here) # pylint: disable=R0904,C0103 from occi.core_model import Action, Kind, Mixin, Resource, Link from occi.protocol.jso...
#!/usr/bin/python import time import sys import socket import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 import cwiid import json tdelay = 0.2 DEBUG = 0 ACC_DEBUG = 0 BUT_DEBUG = 0 FLX_DEBUG = 0 PRC_DEBUG = 0 PNG_DEBUG = 0 NET_DEBUG = 1 ACT_DEBUG = 0 NETWORK = 1 PINGTIMEOUT = 1 HOMENET = 0 ACTIONS = [] ALLOWED_K...
from tensorflow.examples.tutorials.mnist import input_data import numpy as np # from yadlt.models.rbm_models.rbm import RBM from my_rbm import Rbm if __name__ == '__main__': mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) train_images = mnist.train.images test_images = mnist.test.images ...
import datetime from gdata.analytics import client as ga_client from gdata.client import RequestError from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from django.contrib.sites.models import Site from django.conf import settings class AnalyticsSource(object): ...
"""Tests for mtg_ssm.scryfall.fetcher.""" # pylint: disable=protected-access import gzip import pickle import re from typing import List import pytest from responses import RequestsMock from mtg_ssm.containers.bundles import ScryfallDataSet from mtg_ssm.scryfall import fetcher from mtg_ssm.scryfall.models import Scr...
import json import struct import re import os import base64 import httplib import sys import hashlib import datetime import time settings = {} def uint32(x): return x & 0xffffffffL def bytereverse(x): return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) de...