<commit_before>#!/usr/bin/env python

"""Checks pilots mentioned in the EVE chatlogs against a KOS list."""

from eveapi import eveapi
import sys, string, os, tempfile, time, json, urllib2, zlib, cPickle, urllib

KOS_CHECKER_URL = 'http://kos.cva-eve.org/api/?c=json&type=unit&%s'
NPC = 'npc'

class SimpleCache(object):
  """Implements a memory and disk-based cache of previous API calls."""

  def __init__(self, debug=False):
    self.debug = debug
    self.count = 0
    self.cache = {}
    self.tempdir = os.path.join(tempfile.gettempdir(), 'eveapi')
    if not os.path.exists(self.tempdir):
      os.makedirs(self.tempdir)

  def log(self, what):
    """Outputs debug information if the debug flag is set."""
    if self.debug:
      print '[%d] %s' % (self.count, what)

  def retrieve(self, host, path, params):
    """Retrieves a cached value, or returns None if not cached."""
    # eveapi asks if we have this request cached
    key = hash((host, path, frozenset(params.items())))

    self.count += 1  # for logging

    # see if we have the requested page cached...
    cached = self.cache.get(key, None)
    if cached:
      cache_file = None
      #print "'%s': retrieving from memory" % path
    else:
      # it wasn't cached in memory, but it might be on disk.
      cache_file = os.path.join(self.tempdir, str(key) + '.cache')
      if os.path.exists(cache_file):
        self.log('%s: retrieving from disk at %s' % (path, cache_file))
        handle = open(cache_file, 'rb')
        cached = self.cache[key] = cPickle.loads(
            zlib.decompress(handle.read()))
        handle.close()

    if cached:
      # check if the cached doc is fresh enough
      if time.time() < cached[0]:
        self.log('%s: returning cached document' % path)
        return cached[1]  # return the cached XML doc

      # it's stale. purge it.
      self.log('%s: cache expired, purging!' % path)
      del self.cache[key]
      if cache_file:
        os.remove(cache_file)

    self.log('%s: not cached, fetching from server...' % path)
    # we didn't get a cache hit so return None to indicate that the data
    # should be requested from the server.
    return None

  def store(self, host, path, params, doc, obj):
    """Saves a cached value to the backing stores."""
    # eveapi is asking us to cache an item
    key = hash((host, path, frozenset(params.items())))

    cached_for = obj.cachedUntil - obj.currentTime
    if cached_for:
      self.log('%s: cached (%d seconds)' % (path, cached_for))

      cached_until = time.time() + cached_for

      # store in memory
      cached = self.cache[key] = (cached_until, doc)

      # store in cache folder
      cache_file = os.path.join(self.tempdir, str(key) + '.cache')
      handle = open(cache_file, 'wb')
      handle.write(zlib.compress(cPickle.dumps(cached, -1)))
      handle.close()

class CacheObject:
  """Allows caching objects that do not come from the EVE api."""
  def __init__(self, valid_duration_seconds):
    self.cachedUntil = valid_duration_seconds
    self.currentTime = 0

def tail_file(filename):
  """Repeatedly reads the end of a chat log and filters for names."""
  handle = open(filename, 'rb')
  while True:
    where = handle.tell()
    line = handle.readline()
    if not line:
      time.sleep(1)
      handle.seek(where)
    else:
      sanitized = ''.join([x for x in line if x in string.printable and
                                              x not in ['\n', '\r']])
      if not '> xxx ' in sanitized:
        continue
      yield sanitized.split('> xxx ')[1].split('  ')

class KosChecker:
  """Maintains API state and performs KOS checks."""

  def __init__(self):
    self.cache = SimpleCache()
    self.eveapi = eveapi.EVEAPIConnection(cacheHandler=self.cache)

  def koscheck(self, player):
    """Checks a given player against the KOS list, including esoteric rules."""
    kos = self.koscheck_internal(player)
    if kos == None or kos == NPC:
      # We were unable to find the player. Use employment history to
      # get their current corp and look that up. If it's an NPC corp,
      # we'll get bounced again.
      history = self.employment_history(player)

      if kos == None:
        kos = self.koscheck_internal(history[0])

      idx = 1
      while kos == NPC and idx < len(history):
        kos = self.koscheck_internal(history[idx])
        idx = idx + 1

    if kos == None or kos == NPC:
      kos = False

    return kos

  def koscheck_internal(self, entity):
    """Looks up KOS entries by directly calling the CVA KOS API."""
    result = self.cache.retrieve(KOS_CHECKER_URL, KOS_CHECKER_URL,
                                 {'entity': entity})
    if not result:
      result = json.load(urllib2.urlopen(
          KOS_CHECKER_URL % urllib.urlencode({'q' : entity})))
      obj = CacheObject(60*60)
      self.cache.store(KOS_CHECKER_URL, KOS_CHECKER_URL,
                       {'entity': entity}, result, obj)

    kos = None
    for value in result['results']:
      # Require exact match
      if value['label'] != entity:
        continue
      kos = False
      while True:
        kos |= value['kos']
        if 'npc' in value and value['npc'] and not kos:
          # Signal that further lookup is needed of player's last corp
          return NPC
        if 'corp' in value:
          value = value['corp']
        elif 'alliance' in value:
          value = value['alliance']
        else:
          return kos
      break
    return kos

  def employment_history(self, character):
    """Retrieves a player's most recent corporations via EVE api."""
    cid = self.eveapi.eve.CharacterID(
        names=character).characters[0].characterID
    cdata = self.eveapi.eve.CharacterInfo(characterID=cid)
    corps = [row.corporationID for row in cdata.employmentHistory]
    unique_corps = []
    for value in corps:
      if value not in unique_corps:
        unique_corps.append(value)
    return [row.name for row in
                self.eveapi.eve.CharacterName(
                    ids=','.join(str(x) for x in unique_corps)).characters]

  def loop(self, filename):
    """Performs KOS processing on each line read from the log file."""
    for entry in tail_file(filename):
      kos = []
      notkos = []
      error = []
      for person in entry:
        if person.isspace() or len(person) == 0:
          continue
        person = person.strip(' .')
        try:
          if self.koscheck(person):
            kos.append(person)
          else:
            notkos.append(person)
        except:
          error.append(person)

      fmt = '%s%6s (%3d) %s\033[0m'
      print fmt % ('\033[31m', 'KOS', len(kos), len(kos) * '*')
      print fmt % ('\033[34m', 'NotKOS', len(notkos), len(notkos) * '*')
      if len(error) > 0:
        print fmt % ('\033[33m', 'Error', len(error), len(error) * '*')
      print
      for person in kos:
        print '\033[31m%s\033[0m' % person
      print
      for person in notkos:
        print '\033[34m%s\033[0m' % person
      print
      for person in error:
        print '\033[33m%s\033[0m' % person
      print '-----'

if __name__ == '__main__':
  if len(sys.argv) > 1:
    KosChecker().loop(sys.argv[1])
  else:
    print ('Usage: %s ~/EVE/logs/ChatLogs/Fleet_YYYYMMDD_HHMMSS.txt' %
           sys.argv[0])

<commit_msg>sometimes kos checker reports NPC when player is now in new player corp. always double-check with eve api<commit_after>#!/usr/bin/env python

"""Checks pilots mentioned in the EVE chatlogs against a KOS list."""

from eveapi import eveapi
import sys, string, os, tempfile, time, json, urllib2, zlib, cPickle, urllib

KOS_CHECKER_URL = 'http://kos.cva-eve.org/api/?c=json&type=unit&%s'
NPC = 'npc'

class SimpleCache(object):
  """Implements a memory and disk-based cache of previous API calls."""

  def __init__(self, debug=False):
    self.debug = debug
    self.count = 0
    self.cache = {}
    self.tempdir = os.path.join(tempfile.gettempdir(), 'eveapi')
    if not os.path.exists(self.tempdir):
      os.makedirs(self.tempdir)

  def log(self, what):
    """Outputs debug information if the debug flag is set."""
    if self.debug:
      print '[%d] %s' % (self.count, what)

  def retrieve(self, host, path, params):
    """Retrieves a cached value, or returns None if not cached."""
    # eveapi asks if we have this request cached
    key = hash((host, path, frozenset(params.items())))

    self.count += 1  # for logging

    # see if we have the requested page cached...
    cached = self.cache.get(key, None)
    if cached:
      cache_file = None
      #print "'%s': retrieving from memory" % path
    else:
      # it wasn't cached in memory, but it might be on disk.
      cache_file = os.path.join(self.tempdir, str(key) + '.cache')
      if os.path.exists(cache_file):
        self.log('%s: retrieving from disk at %s' % (path, cache_file))
        handle = open(cache_file, 'rb')
        cached = self.cache[key] = cPickle.loads(
            zlib.decompress(handle.read()))
        handle.close()

    if cached:
      # check if the cached doc is fresh enough
      if time.time() < cached[0]:
        self.log('%s: returning cached document' % path)
        return cached[1]  # return the cached XML doc

      # it's stale. purge it.
      self.log('%s: cache expired, purging!' % path)
      del self.cache[key]
      if cache_file:
        os.remove(cache_file)

    self.log('%s: not cached, fetching from server...' % path)
    # we didn't get a cache hit so return None to indicate that the data
    # should be requested from the server.
    return None

  def store(self, host, path, params, doc, obj):
    """Saves a cached value to the backing stores."""
    # eveapi is asking us to cache an item
    key = hash((host, path, frozenset(params.items())))

    cached_for = obj.cachedUntil - obj.currentTime
    if cached_for:
      self.log('%s: cached (%d seconds)' % (path, cached_for))

      cached_until = time.time() + cached_for

      # store in memory
      cached = self.cache[key] = (cached_until, doc)

      # store in cache folder
      cache_file = os.path.join(self.tempdir, str(key) + '.cache')
      handle = open(cache_file, 'wb')
      handle.write(zlib.compress(cPickle.dumps(cached, -1)))
      handle.close()

class CacheObject:
  """Allows caching objects that do not come from the EVE api."""
  def __init__(self, valid_duration_seconds):
    self.cachedUntil = valid_duration_seconds
    self.currentTime = 0

def tail_file(filename):
  """Repeatedly reads the end of a chat log and filters for names."""
  handle = open(filename, 'rb')
  while True:
    where = handle.tell()
    line = handle.readline()
    if not line:
      time.sleep(1)
      handle.seek(where)
    else:
      sanitized = ''.join([x for x in line if x in string.printable and
                                              x not in ['\n', '\r']])
      if not '> xxx ' in sanitized:
        continue
      yield sanitized.split('> xxx ')[1].split('  ')

class KosChecker:
  """Maintains API state and performs KOS checks."""

  def __init__(self):
    self.cache = SimpleCache()
    self.eveapi = eveapi.EVEAPIConnection(cacheHandler=self.cache)

  def koscheck(self, player):
    """Checks a given player against the KOS list, including esoteric rules."""
    kos = self.koscheck_internal(player)
    if kos == None or kos == NPC:
      # We were unable to find the player. Use employment history to
      # get their current corp and look that up. If it's an NPC corp,
      # we'll get bounced again.
      history = self.employment_history(player)

      kos = self.koscheck_internal(history[0])

      idx = 1
      while kos == NPC and idx < len(history):
        kos = self.koscheck_internal(history[idx])
        idx = idx + 1

    if kos == None or kos == NPC:
      kos = False

    return kos

  def koscheck_internal(self, entity):
    """Looks up KOS entries by directly calling the CVA KOS API."""
    result = self.cache.retrieve(KOS_CHECKER_URL, KOS_CHECKER_URL,
                                 {'entity': entity})
    if not result:
      result = json.load(urllib2.urlopen(
          KOS_CHECKER_URL % urllib.urlencode({'q' : entity})))
      obj = CacheObject(60*60)
      self.cache.store(KOS_CHECKER_URL, KOS_CHECKER_URL,
                       {'entity': entity}, result, obj)

    kos = None
    for value in result['results']:
      # Require exact match
      if value['label'] != entity:
        continue
      kos = False
      while True:
        kos |= value['kos']
        if 'npc' in value and value['npc'] and not kos:
          # Signal that further lookup is needed of player's last corp
          return NPC
        if 'corp' in value:
          value = value['corp']
        elif 'alliance' in value:
          value = value['alliance']
        else:
          return kos
      break
    return kos

  def employment_history(self, character):
    """Retrieves a player's most recent corporations via EVE api."""
    cid = self.eveapi.eve.CharacterID(
        names=character).characters[0].characterID
    cdata = self.eveapi.eve.CharacterInfo(characterID=cid)
    corps = [row.corporationID for row in cdata.employmentHistory]
    unique_corps = []
    for value in corps:
      if value not in unique_corps:
        unique_corps.append(value)
    return [row.name for row in
                self.eveapi.eve.CharacterName(
                    ids=','.join(str(x) for x in unique_corps)).characters]

  def loop(self, filename):
    """Performs KOS processing on each line read from the log file."""
    for entry in tail_file(filename):
      kos = []
      notkos = []
      error = []
      for person in entry:
        if person.isspace() or len(person) == 0:
          continue
        person = person.strip(' .')
        try:
          if self.koscheck(person):
            kos.append(person)
          else:
            notkos.append(person)
        except:
          error.append(person)

      fmt = '%s%6s (%3d) %s\033[0m'
      print fmt % ('\033[31m', 'KOS', len(kos), len(kos) * '*')
      print fmt % ('\033[34m', 'NotKOS', len(notkos), len(notkos) * '*')
      if len(error) > 0:
        print fmt % ('\033[33m', 'Error', len(error), len(error) * '*')
      print
      for person in kos:
        print '\033[31m%s\033[0m' % person
      print
      for person in notkos:
        print '\033[34m%s\033[0m' % person
      print
      for person in error:
        print '\033[33m%s\033[0m' % person
      print '-----'

if __name__ == '__main__':
  if len(sys.argv) > 1:
    KosChecker().loop(sys.argv[1])
  else:
    print ('Usage: %s ~/EVE/logs/ChatLogs/Fleet_YYYYMMDD_HHMMSS.txt' %
           sys.argv[0])

<|endoftext|>


<commit_before>import cStringIO
import hashlib
import json
import requests
import tarfile
import urlparse
import uuid

from django.conf import settings

def publish_release(source, config, target):
    """
    Publish a new release as a Docker image

    Given a source image and dictionary of last-mile configuration,
    create a target Docker image on the registry.

    For example publish_release('registry.local:5000/gabrtv/myapp',
                                {'ENVVAR': 'values'},
                                'registry.local:5000/gabrtv/myapp',)
    results in a new Docker image at 'registry.local:5000/gabrtv/myapp:v23' which
    contains the new configuration as ENV entries.
    """
    try:
        src_image = source.rsplit(':', 1)[0]
        src_tag = source.rsplit(':', 1)[1]
        target_image = target.rsplit(':', 1)[0]
        target_tag = target.rsplit(':', 1)[1]
        image_id = _get_tag(src_image, src_tag)
    except RuntimeError:
        if src_tag == 'latest':
            # no image exists yet, so let's build one!
            _put_first_image(src_image)
            image_id = _get_tag(src_image, src_tag)
        else:
            raise
    image = _get_image(image_id)
    # construct the new image
    image['parent'] = image['id']
    image['id'] = _new_id()
    image['config']['Env'] = _construct_env(image['config']['Env'], config)
    # update and tag the new image
    _commit(target_image, image, _empty_tar_archive(), target_tag)

# registry access

def _commit(repository_path, image, layer, tag):
    _put_image(image)
    cookies = _put_layer(image['id'], layer)
    _put_checksum(image, cookies)
    _put_tag(image['id'], repository_path, tag)
    # point latest to the new tag
    _put_tag(image['id'], repository_path, 'latest')

def _put_first_image(repository_path):
    image = {
        'id': _new_id(),
        'parent': '',
        'config': {
            'Env': []
        }
    }
    # tag as v0 in the registry
    _commit(repository_path, image, _empty_tar_archive(), 'v0')

def _api_call(endpoint, data=None, headers={}, cookies=None, request_type='GET'):
    # FIXME: update API calls for docker 0.10.0+
    base_headers = {'user-agent': 'docker/0.9.0'}
    r = None
    if len(headers) > 0:
        for header, value in headers.iteritems():
            base_headers[header] = value
    if request_type == 'GET':
        r = requests.get(endpoint, headers=base_headers)
    elif request_type == 'PUT':
        r = requests.put(endpoint, data=data, headers=base_headers, cookies=cookies)
    else:
        raise AttributeError("request type not supported: {}".format(request_type))
    return r

def _get_tag(repository, tag):
    path = "/v1/repositories/{repository}/tags/{tag}".format(**locals())
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    r = _api_call(url)
    if not r.status_code == 200:
        raise RuntimeError("GET Image Error ({}: {})".format(r.status_code, r.text))
    return r.json()

def _get_image(image_id):
    path = "/v1/images/{image_id}/json".format(**locals())
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    r = _api_call(url)
    if not r.status_code == 200:
        raise RuntimeError("GET Image Error ({}: {})".format(r.status_code, r.text))
    return r.json()

def _put_image(image):
    path = "/v1/images/{id}/json".format(**image)
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    r = _api_call(url, data=json.dumps(image), request_type='PUT')
    if not r.status_code == 200:
        raise RuntimeError("PUT Image Error ({}: {})".format(r.status_code, r.text))
    return r.json()

def _put_layer(image_id, layer_fileobj):
    path = "/v1/images/{image_id}/layer".format(**locals())
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    r = _api_call(url, data=layer_fileobj.read(), request_type='PUT')
    if not r.status_code == 200:
        raise RuntimeError("PUT Layer Error ({}: {})".format(r.status_code, r.text))
    return r.cookies

def _put_checksum(image, cookies):
    path = "/v1/images/{id}/checksum".format(**image)
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    tarsum = TarSum(json.dumps(image)).compute()
    headers = {'X-Docker-Checksum': tarsum}
    r = _api_call(url, headers=headers, cookies=cookies, request_type='PUT')
    if not r.status_code == 200:
        raise RuntimeError("PUT Checksum Error ({}: {})".format(r.status_code, r.text))
    print r.json()

def _put_tag(image_id, repository_path, tag):
    path = "/v1/repositories/{repository_path}/tags/{tag}".format(**locals())
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    r = _api_call(url, data=json.dumps(image_id), request_type='PUT')
    if not r.status_code == 200:
        raise RuntimeError("PUT Tag Error ({}: {})".format(r.status_code, r.text))
    print r.json()

# utility functions

def _construct_env(env, config):
    "Update current environment with latest config"
    new_env = []
    # see if we need to update existing ENV vars
    for e in env:
        k, v = e.split('=', 1)
        if k in config:
            # update values defined by config
            v = config.pop(k)
        new_env.append("{}={}".format(k, v))
    # add other config ENV items
    for k, v in config.items():
        new_env.append("{}={}".format(k, v))
    return new_env

def _new_id():
    "Return 64-char UUID for use as Image ID"
    return ''.join(uuid.uuid4().hex * 2)

def _empty_tar_archive():
    "Return an empty tar archive (in memory)"
    data = cStringIO.StringIO()
    tar = tarfile.open(mode="w", fileobj=data)
    tar.close()
    data.seek(0)
    return data

#
# Below adapted from https://github.com/dotcloud/docker-registry/blob/master/lib/checksums.py
#

def sha256_file(fp, data=None):
    h = hashlib.sha256(data or '')
    if not fp:
        return h.hexdigest()
    while True:
        buf = fp.read(4096)
        if not buf:
            break
        h.update(buf)
    return h.hexdigest()

def sha256_string(s):
    return hashlib.sha256(s).hexdigest()

class TarSum(object):

    def __init__(self, json_data):
        self.json_data = json_data
        self.hashes = []
        self.header_fields = ('name', 'mode', 'uid', 'gid', 'size', 'mtime',
                              'type', 'linkname', 'uname', 'gname', 'devmajor',
                              'devminor')

    def append(self, member, tarobj):
        header = ''
        for field in self.header_fields:
            value = getattr(member, field)
            if field == 'type':
                field = 'typeflag'
            elif field == 'name':
                if member.isdir() and not value.endswith('/'):
                    value += '/'
            header += '{0}{1}'.format(field, value)
        h = None
        try:
            if member.size > 0:
                f = tarobj.extractfile(member)
                h = sha256_file(f, header)
            else:
                h = sha256_string(header)
        except KeyError:
            h = sha256_string(header)
        self.hashes.append(h)

    def compute(self):
        self.hashes.sort()
        data = self.json_data + ''.join(self.hashes)
        tarsum = 'tarsum+sha256:{0}'.format(sha256_string(data))
        return tarsum
<commit_msg>fix(controller): correct image name parsing<commit_after>import cStringIO
import hashlib
import json
import requests
import tarfile
import urlparse
import uuid

from django.conf import settings

def publish_release(source, config, target):
    """
    Publish a new release as a Docker image

    Given a source image and dictionary of last-mile configuration,
    create a target Docker image on the registry.

    For example publish_release('registry.local:5000/gabrtv/myapp:v22',
                                {'ENVVAR': 'values'},
                                'registry.local:5000/gabrtv/myapp:v23',)
    results in a new Docker image at 'registry.local:5000/gabrtv/myapp:v23' which
    contains the new configuration as ENV entries.
    """
    try:
        if source.count(':') == 2:
            src_image = source.rsplit(':', 1)[0].split('/', 1)[1]
            src_tag = source.split(':')[2]
        else:
            src_image = source
            src_tag = 'latest'
        target_image = target.rsplit(':', 1)[0]
        target_tag = target.rsplit(':', 1)[1]
        image_id = _get_tag(src_image, src_tag)
    except RuntimeError:
        if src_tag == 'latest':
            # no image exists yet, so let's build one!
            _put_first_image(src_image)
            image_id = _get_tag(src_image, src_tag)
        else:
            raise
    image = _get_image(image_id)
    # construct the new image
    image['parent'] = image['id']
    image['id'] = _new_id()
    image['config']['Env'] = _construct_env(image['config']['Env'], config)
    # update and tag the new image
    _commit(target_image, image, _empty_tar_archive(), target_tag)

# registry access

def _commit(repository_path, image, layer, tag):
    _put_image(image)
    cookies = _put_layer(image['id'], layer)
    _put_checksum(image, cookies)
    _put_tag(image['id'], repository_path, tag)
    # point latest to the new tag
    _put_tag(image['id'], repository_path, 'latest')

def _put_first_image(repository_path):
    image = {
        'id': _new_id(),
        'parent': '',
        'config': {
            'Env': []
        }
    }
    # tag as v0 in the registry
    _commit(repository_path, image, _empty_tar_archive(), 'v0')

def _api_call(endpoint, data=None, headers={}, cookies=None, request_type='GET'):
    # FIXME: update API calls for docker 0.10.0+
    base_headers = {'user-agent': 'docker/0.9.0'}
    r = None
    if len(headers) > 0:
        for header, value in headers.iteritems():
            base_headers[header] = value
    if request_type == 'GET':
        r = requests.get(endpoint, headers=base_headers)
    elif request_type == 'PUT':
        r = requests.put(endpoint, data=data, headers=base_headers, cookies=cookies)
    else:
        raise AttributeError("request type not supported: {}".format(request_type))
    return r

def _get_tag(repository, tag):
    path = "/v1/repositories/{repository}/tags/{tag}".format(**locals())
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    r = _api_call(url)
    if not r.status_code == 200:
        raise RuntimeError("GET Image Error ({}: {})".format(r.status_code, r.text))
    return r.json()

def _get_image(image_id):
    path = "/v1/images/{image_id}/json".format(**locals())
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    r = _api_call(url)
    if not r.status_code == 200:
        raise RuntimeError("GET Image Error ({}: {})".format(r.status_code, r.text))
    return r.json()

def _put_image(image):
    path = "/v1/images/{id}/json".format(**image)
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    r = _api_call(url, data=json.dumps(image), request_type='PUT')
    if not r.status_code == 200:
        raise RuntimeError("PUT Image Error ({}: {})".format(r.status_code, r.text))
    return r.json()

def _put_layer(image_id, layer_fileobj):
    path = "/v1/images/{image_id}/layer".format(**locals())
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    r = _api_call(url, data=layer_fileobj.read(), request_type='PUT')
    if not r.status_code == 200:
        raise RuntimeError("PUT Layer Error ({}: {})".format(r.status_code, r.text))
    return r.cookies

def _put_checksum(image, cookies):
    path = "/v1/images/{id}/checksum".format(**image)
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    tarsum = TarSum(json.dumps(image)).compute()
    headers = {'X-Docker-Checksum': tarsum}
    r = _api_call(url, headers=headers, cookies=cookies, request_type='PUT')
    if not r.status_code == 200:
        raise RuntimeError("PUT Checksum Error ({}: {})".format(r.status_code, r.text))
    print r.json()

def _put_tag(image_id, repository_path, tag):
    path = "/v1/repositories/{repository_path}/tags/{tag}".format(**locals())
    url = urlparse.urljoin(settings.REGISTRY_URL, path)
    r = _api_call(url, data=json.dumps(image_id), request_type='PUT')
    if not r.status_code == 200:
        raise RuntimeError("PUT Tag Error ({}: {})".format(r.status_code, r.text))
    print r.json()

# utility functions

def _construct_env(env, config):
    "Update current environment with latest config"
    new_env = []
    # see if we need to update existing ENV vars
    for e in env:
        k, v = e.split('=', 1)
        if k in config:
            # update values defined by config
            v = config.pop(k)
        new_env.append("{}={}".format(k, v))
    # add other config ENV items
    for k, v in config.items():
        new_env.append("{}={}".format(k, v))
    return new_env

def _new_id():
    "Return 64-char UUID for use as Image ID"
    return ''.join(uuid.uuid4().hex * 2)

def _empty_tar_archive():
    "Return an empty tar archive (in memory)"
    data = cStringIO.StringIO()
    tar = tarfile.open(mode="w", fileobj=data)
    tar.close()
    data.seek(0)
    return data

#
# Below adapted from https://github.com/dotcloud/docker-registry/blob/master/lib/checksums.py
#

def sha256_file(fp, data=None):
    h = hashlib.sha256(data or '')
    if not fp:
        return h.hexdigest()
    while True:
        buf = fp.read(4096)
        if not buf:
            break
        h.update(buf)
    return h.hexdigest()

def sha256_string(s):
    return hashlib.sha256(s).hexdigest()

class TarSum(object):

    def __init__(self, json_data):
        self.json_data = json_data
        self.hashes = []
        self.header_fields = ('name', 'mode', 'uid', 'gid', 'size', 'mtime',
                              'type', 'linkname', 'uname', 'gname', 'devmajor',
                              'devminor')

    def append(self, member, tarobj):
        header = ''
        for field in self.header_fields:
            value = getattr(member, field)
            if field == 'type':
                field = 'typeflag'
            elif field == 'name':
                if member.isdir() and not value.endswith('/'):
                    value += '/'
            header += '{0}{1}'.format(field, value)
        h = None
        try:
            if member.size > 0:
                f = tarobj.extractfile(member)
                h = sha256_file(f, header)
            else:
                h = sha256_string(header)
        except KeyError:
            h = sha256_string(header)
        self.hashes.append(h)

    def compute(self):
        self.hashes.sort()
        data = self.json_data + ''.join(self.hashes)
        tarsum = 'tarsum+sha256:{0}'.format(sha256_string(data))
        return tarsum
<|endoftext|>


<commit_before>#!/usr/bin/python

#
# Careful with naming to deliberately allow this:
# from actor import *
#

import Queue as _Queue
import sys
from threading import Thread as _Thread
import time

__all__ = ["Actor", "actor_method", "actor_function", "process_method",
           "late_bind", "UnboundActorMethod", "ActorException",
           "late_bind_safe", "pipe", "wait_for", "stop", "pipeline",
           "wait_KeyboardInterrupt", "start"]

class UnboundActorMethod(Exception):
    pass

class ActorException(Exception):
    def __init__(self, *argv, **argd):
        super(ActorException, self).__init__(*argv)
        self.__dict__.update(argd)

class ActorMetaclass(type):
    def __new__(cls, clsname, bases, dct):
        new_dct = {}
        for name, val in dct.items():
            new_dct[name] = val
            if val.__class__ == tuple and len(val) == 2:
                tag, fn = str(val[0]), val[1]
                if tag.startswith("ACTORMETHOD"):
                    def mkcallback(func):
                        def t(self, *args, **argd):
                            self.inbound.put_nowait((func, self, args, argd))
                        return t

                    new_dct[name] = mkcallback(fn)

                elif tag.startswith("ACTORFUNCTION"):
                    def mkcallback(func):
                        resultQueue = _Queue.Queue()

                        def t(self, *args, **argd):
                            op = (func, self, args, argd)
                            self.F_inbound.put_nowait((op, resultQueue))
                            e, result = resultQueue.get(True, None)
                            if e != 0:
                                raise e.__class__, e, e.sys_exc_info
                            return result
                        return t

                    new_dct[name] = mkcallback(fn)

                elif tag.startswith("PROCESSMETHOD"):
                    def mkcallback(func):
                        def s(self, *args, **argd):
                            x = func(self)
                            if x == False:
                                return
                            self.core.put_nowait((s, self, (), {}))
                        return s

                    new_dct[name] = mkcallback(fn)

                elif tag == "LATEBIND":
                    def mkcallback(func):
                        def s(self, *args, **argd):
                            raise UnboundActorMethod("Call to Unbound Latebind")
                        return s
                    new_dct[name] = mkcallback(fn)

                elif tag == "LATEBINDSAFE":
                    # print "latebindsafe", name, clsname
                    def mkcallback(func):
                        def t(self, *args, **argd):
                            self.inbound.put_nowait((func, self, args, argd))
                        return t

                    new_dct[name] = mkcallback(fn)

        return type.__new__(cls, clsname, bases, new_dct)

def actor_method_max_queue(length):
    def decorator(method):
        return ("ACTORMETHOD", length, method)
    return decorator

def actor_method_lossy_queue(length):
    def decorator(method):
        return ("ACTORMETHOD", length, method)
    return decorator

def actor_method(method):
    return ("ACTORMETHOD", method)

def actor_function(fn):
    return ("ACTORFUNCTION", fn)

def process_method(method):
    return ("PROCESSMETHOD", method)

def late_bind(method):
    return ("LATEBIND", method)

def late_bind_safe(method):
    return ("LATEBINDSAFE", method)

class Actor(_Thread):
    __metaclass__ = ActorMetaclass
    daemon = True

    def __init__(self):
        self.inbound = _Queue.Queue()
        self.F_inbound = _Queue.Queue()
        self.core = _Queue.Queue()
        self.killflag = False
        super(Actor, self).__init__()
        self._uThread = None
        self._g = None

    def run(self):
        self._uThread = self.main()

        while True:
            try:
                self._uThread.next()
            except StopIteration:
                break
            if self.killflag:
                self.onStop()
                dobreak = False
                try:
                    self._uThread.throw(StopIteration)
                except StopIteration:
                    dobreak = True
                try:
                    if self._g:
                        self._g.throw(StopIteration)
                except StopIteration:
                    dobreak = True
                if dobreak:
                    break

    def interpret(self, command):
        # print command
        callback, zelf, argv, argd = command
        if zelf:
            try:
                result = callback(zelf, *argv, **argd)
                return result
            except TypeError:
                import sys
                sys.stderr.write("FAILURE -- ")
                sys.stderr.write("command (callback, zelf, argv, argd): ")
                sys.stderr.write(", ".join([repr(x) for x in command]))
                sys.stderr.write("\n")
                sys.stderr.flush()
                # print "self", self
                raise
        else:
            result = callback(*argv, **argd)
            return result

    def process_start(self):
        pass

    def onStop(self):
        pass

    def main(self):
        self.process_start()
        self.process()
        try:
            g = self.gen_process()
        except:
            g = None
        self._g = g
        while True:
            if g != None:
                g.next()
            yield 1
            if (self.F_inbound.qsize() > 0 or
                self.inbound.qsize() > 0 or
                self.core.qsize() > 0):

                if self.inbound.qsize() > 0:
                    command = self.inbound.get_nowait()
                    try:
                        self.interpret(command)
                    except:
                        self.stop()

                if self.F_inbound.qsize() > 0:
                    command, result_queue = self.F_inbound.get_nowait()
                    result_fail = 0
                    try:
                        result = self.interpret(command)
                    except Exception as e:
                        result_fail = e
                        result_fail.sys_exc_info = sys.exc_info()[2]

                    result_queue.put_nowait((result_fail, result))

                if self.core.qsize() > 0:
                    command = self.core.get_nowait()
                    self.interpret(command)
            else:
                if g == None:
                    time.sleep(0.01)

    @process_method
    def process(self):
        return False

    def stop(self):
        self.killflag = True

    @actor_method
    def bind(self, source, dest, destmeth):
        setattr(self, source, getattr(dest, destmeth))

    def go(self):
        self.start()
        return self

    @late_bind_safe
    def output(self, *argv, **argd):
        pass

    @actor_method
    def input(self, *argv, **argd):
        pass

def pipe(source, source_box, sink, sinkbox):
    source.bind(source_box, sink, sinkbox)

def pipeline(*processes):
    x = list(processes)
    while len(x) > 1:
        pipe(x[0], "output", x[1], "input")
        del x[0]

def wait_for(*processes):
    for p in processes:
        p.join()

def stop(*processes):
    for p in processes:
        p.stop()

def start(*processes):
    for p in processes:
        p.start()

def wait_KeyboardInterrupt():
    while True:
        try:
            time.sleep(0.1)
        except KeyboardInterrupt:
            break
<commit_msg>Use functools.wrap to preserve method metadata<commit_after>#!/usr/bin/python

#
# Careful with naming to deliberately allow this:
# from actor import *
#

from functools import wraps as _wraps
import Queue as _Queue
import sys
from threading import Thread as _Thread
import time

__all__ = ["Actor", "actor_method", "actor_function", "process_method",
           "late_bind", "UnboundActorMethod", "ActorException",
           "late_bind_safe", "pipe", "wait_for", "stop", "pipeline",
           "wait_KeyboardInterrupt", "start"]

class UnboundActorMethod(Exception):
    pass

class ActorException(Exception):
    def __init__(self, *argv, **argd):
        super(ActorException, self).__init__(*argv)
        self.__dict__.update(argd)

class ActorMetaclass(type):
    def __new__(cls, clsname, bases, dct):
        new_dct = {}
        for name, val in dct.items():
            new_dct[name] = val
            if val.__class__ == tuple and len(val) == 2:
                tag, fn = str(val[0]), val[1]
                if tag.startswith("ACTORMETHOD"):
                    def mkcallback(func):
                        @_wraps(func)
                        def t(self, *args, **argd):
                            self.inbound.put_nowait((func, self, args, argd))
                        return t

                    new_dct[name] = mkcallback(fn)

                elif tag.startswith("ACTORFUNCTION"):
                    def mkcallback(func):
                        resultQueue = _Queue.Queue()

                        @_wraps(func)
                        def t(self, *args, **argd):
                            op = (func, self, args, argd)
                            self.F_inbound.put_nowait((op, resultQueue))
                            e, result = resultQueue.get(True, None)
                            if e != 0:
                                raise e.__class__, e, e.sys_exc_info
                            return result
                        return t

                    new_dct[name] = mkcallback(fn)

                elif tag.startswith("PROCESSMETHOD"):
                    def mkcallback(func):
                        @_wraps(func)
                        def s(self, *args, **argd):
                            x = func(self)
                            if x == False:
                                return
                            self.core.put_nowait((s, self, (), {}))
                        return s

                    new_dct[name] = mkcallback(fn)

                elif tag == "LATEBIND":
                    def mkcallback(func):
                        @_wraps(func)
                        def s(self, *args, **argd):
                            raise UnboundActorMethod("Call to Unbound Latebind")
                        return s
                    new_dct[name] = mkcallback(fn)

                elif tag == "LATEBINDSAFE":
                    # print "latebindsafe", name, clsname
                    def mkcallback(func):
                        @_wraps(func)
                        def t(self, *args, **argd):
                            self.inbound.put_nowait((func, self, args, argd))
                        return t

                    new_dct[name] = mkcallback(fn)

        return type.__new__(cls, clsname, bases, new_dct)

def actor_method_max_queue(length):
    def decorator(method):
        return ("ACTORMETHOD", length, method)
    return decorator

def actor_method_lossy_queue(length):
    def decorator(method):
        return ("ACTORMETHOD", length, method)
    return decorator

def actor_method(method):
    return ("ACTORMETHOD", method)

def actor_function(fn):
    return ("ACTORFUNCTION", fn)

def process_method(method):
    return ("PROCESSMETHOD", method)

def late_bind(method):
    return ("LATEBIND", method)

def late_bind_safe(method):
    return ("LATEBINDSAFE", method)

class Actor(_Thread):
    __metaclass__ = ActorMetaclass
    daemon = True

    def __init__(self):
        self.inbound = _Queue.Queue()
        self.F_inbound = _Queue.Queue()
        self.core = _Queue.Queue()
        self.killflag = False
        super(Actor, self).__init__()
        self._uThread = None
        self._g = None

    def run(self):
        self._uThread = self.main()

        while True:
            try:
                self._uThread.next()
            except StopIteration:
                break
            if self.killflag:
                self.onStop()
                dobreak = False
                try:
                    self._uThread.throw(StopIteration)
                except StopIteration:
                    dobreak = True
                try:
                    if self._g:
                        self._g.throw(StopIteration)
                except StopIteration:
                    dobreak = True
                if dobreak:
                    break

    def interpret(self, command):
        # print command
        callback, zelf, argv, argd = command
        if zelf:
            try:
                result = callback(zelf, *argv, **argd)
                return result
            except TypeError:
                import sys
                sys.stderr.write("FAILURE -- ")
                sys.stderr.write("command (callback, zelf, argv, argd): ")
                sys.stderr.write(", ".join([repr(x) for x in command]))
                sys.stderr.write("\n")
                sys.stderr.flush()
                # print "self", self
                raise
        else:
            result = callback(*argv, **argd)
            return result

    def process_start(self):
        pass

    def onStop(self):
        pass

    def main(self):
        self.process_start()
        self.process()
        try:
            g = self.gen_process()
        except:
            g = None
        self._g = g
        while True:
            if g != None:
                g.next()
            yield 1
            if (self.F_inbound.qsize() > 0 or
                self.inbound.qsize() > 0 or
                self.core.qsize() > 0):

                if self.inbound.qsize() > 0:
                    command = self.inbound.get_nowait()
                    try:
                        self.interpret(command)
                    except:
                        self.stop()

                if self.F_inbound.qsize() > 0:
                    command, result_queue = self.F_inbound.get_nowait()
                    result_fail = 0
                    try:
                        result = self.interpret(command)
                    except Exception as e:
                        result_fail = e
                        result_fail.sys_exc_info = sys.exc_info()[2]

                    result_queue.put_nowait((result_fail, result))

                if self.core.qsize() > 0:
                    command = self.core.get_nowait()
                    self.interpret(command)
            else:
                if g == None:
                    time.sleep(0.01)

    @process_method
    def process(self):
        return False

    def stop(self):
        self.killflag = True

    @actor_method
    def bind(self, source, dest, destmeth):
        setattr(self, source, getattr(dest, destmeth))

    def go(self):
        self.start()
        return self

    @late_bind_safe
    def output(self, *argv, **argd):
        pass

    @actor_method
    def input(self, *argv, **argd):
        pass

def pipe(source, source_box, sink, sinkbox):
    source.bind(source_box, sink, sinkbox)

def pipeline(*processes):
    x = list(processes)
    while len(x) > 1:
        pipe(x[0], "output", x[1], "input")
        del x[0]

def wait_for(*processes):
    for p in processes:
        p.join()

def stop(*processes):
    for p in processes:
        p.stop()

def start(*processes):
    for p in processes:
        p.start()

def wait_KeyboardInterrupt():
    while True:
        try:
            time.sleep(0.1)
        except KeyboardInterrupt:
            break
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)

"""Spyder terminal configuration page."""

# Standard library imports
from distutils.version import LooseVersion
import os
import platform
import sys

# Third party imports
from qtpy.QtWidgets import (QVBoxLayout, QGroupBox, QGridLayout, QButtonGroup,
                            QRadioButton, QWidget)
from spyder.api.preferences import PluginConfigPage
from spyder.config.base import get_translation
from spyder.utils.programs import find_program

# Constants
WINDOWS = os.name == 'nt'
UNIX_SHELLS = ['bash', 'sh', 'ksh', 'zsh', 'csh', 'pwsh', 'rbash', 'dash',
               'screen', 'tmux', 'tcsh', 'fish']
WINDOWS_SHELLS = ['cmd', 'powershell']

# For translations
_ = get_translation('spyder_terminal')

class TerminalConfigPage(PluginConfigPage):
    def setup_page(self):
        """Create configuration page."""
        options_layout = QGridLayout()
        # Custom shell options
        shell_group = QGroupBox(_("Terminal shell"))
        shell_layout = QVBoxLayout()
        if WINDOWS:
            self.shells = WINDOWS_SHELLS
        else:
            self.shells = UNIX_SHELLS

        valid_shells = []
        for shell in self.shells:
            if find_program(shell) is not None:
                valid_shells.append(shell)
        valid_shells = zip(valid_shells, valid_shells)
        if WINDOWS:
            default_option = 'cmd'
        elif sys.platform.startswith('linux'):
            default_option = 'bash'
        else:
            mac_ver = LooseVersion(platform.mac_ver()[0])
            if mac_ver >= LooseVersion('10.15.0'):
                # Catalina changed the default shell to zsh
                default_option = 'zsh'
            else:
                default_option = 'bash'
        shell_combo = self.create_combobox(_("Select the shell interpreter:"),
                                           valid_shells, 'shell', restart=True,
                                           default=default_option)
        shell_combo.combobox.setMinimumContentsLength(15)
        shell_layout.addWidget(shell_combo)
        shell_group.setLayout(shell_layout)
        shell_layout.addStretch(1)
        options_layout.addWidget(shell_group)

        # Style preferences
        terminal_group = QGroupBox(_("Terminal style preferences"))
        # Custom bar option
        cursor_choices = [(_("Block"), 0), (_("Underline"), 1), (_("Bar"), 2)]
        self.cursor_combo = self.create_combobox(_("Type of cursor:"),
                                                 cursor_choices,
                                                 'cursor_type')
        self.cursor_combo.combobox.setMinimumContentsLength(15)
        options_layout.addWidget(self.cursor_combo)

        # Custom buffer limit
        self.buffer_sb = self.create_spinbox(_("Buffer limit: "), "",
                                             'buffer_lim', min_=100,
                                             default=1000,
                                             max_=1000000, step=1)
        options_layout.addWidget(self.buffer_sb)

        # Custom sound option
        self.sound_cb = self.create_checkbox(
            _("Enable bell sound"), 'sound',
            tip=_("Enable bell sound on terminal"))
        options_layout.addWidget(self.sound_cb)

        terminal_group.setLayout(options_layout)

        layout = QVBoxLayout()
        layout.addWidget(shell_group)
        layout.addWidget(terminal_group)
        layout.addStretch(1)

        self.setLayout(layout)
<commit_msg>Create new section in the confpage<commit_after># -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)

"""Spyder terminal configuration page."""

# Standard library imports
from distutils.version import LooseVersion
import os
import platform
import sys

# Third party imports
from qtpy.QtWidgets import (QVBoxLayout, QGroupBox, QGridLayout, QButtonGroup,
                            QRadioButton, QWidget)
from spyder.api.preferences import PluginConfigPage
from spyder.config.base import get_translation
from spyder.utils.programs import find_program

# Constants
WINDOWS = os.name == 'nt'
UNIX_SHELLS = ['bash', 'sh', 'ksh', 'zsh', 'csh', 'pwsh', 'rbash', 'dash',
               'screen', 'tmux', 'tcsh', 'fish']
WINDOWS_SHELLS = ['cmd', 'powershell']

# For translations
_ = get_translation('spyder_terminal')

class TerminalConfigPage(PluginConfigPage):
    def setup_page(self):
        """Create configuration page."""
        options_layout = QGridLayout()
        # Custom shell options
        shell_group = QGroupBox(_("Terminal shell"))
        shell_layout = QVBoxLayout()
        if WINDOWS:
            self.shells = WINDOWS_SHELLS
        else:
            self.shells = UNIX_SHELLS

        valid_shells = []
        for shell in self.shells:
            if find_program(shell) is not None:
                valid_shells.append(shell)
        valid_shells = zip(valid_shells, valid_shells)
        if WINDOWS:
            default_option = 'cmd'
        elif sys.platform.startswith('linux'):
            default_option = 'bash'
        else:
            mac_ver = LooseVersion(platform.mac_ver()[0])
            if mac_ver >= LooseVersion('10.15.0'):
                # Catalina changed the default shell to zsh
                default_option = 'zsh'
            else:
                default_option = 'bash'
        shell_combo = self.create_combobox(_("Select the shell interpreter:"),
                                           valid_shells, 'shell', restart=True,
                                           default=default_option)
        shell_combo.combobox.setMinimumContentsLength(15)
        shell_layout.addWidget(shell_combo)
        shell_group.setLayout(shell_layout)
        shell_layout.addStretch(1)
        options_layout.addWidget(shell_group)

        # Display preferences
        display_group = QGroupBox(_("Terminal display preferences"))
        display_layout = QVBoxLayout()
        # Custom buffer limit
        self.buffer_sb = self.create_spinbox(_("Buffer limit: "), "",
                                             'buffer_lim', min_=100,
                                             default=1000,
                                             max_=1000000, step=1)
        display_layout.addWidget(self.buffer_sb)
        display_group.setLayout(display_layout)
        display_layout.addStretch(1)
        options_layout.addWidget(display_group)

        # Style preferences
        terminal_group = QGroupBox(_("Terminal style preferences"))
        # Custom bar option
        cursor_choices = [(_("Block"), 0), (_("Underline"), 1), (_("Bar"), 2)]
        self.cursor_combo = self.create_combobox(_("Type of cursor:"),
                                                 cursor_choices,
                                                 'cursor_type')
        self.cursor_combo.combobox.setMinimumContentsLength(15)
        options_layout.addWidget(self.cursor_combo)

        # Custom sound option
        self.sound_cb = self.create_checkbox(
            _("Enable bell sound"), 'sound',
            tip=_("Enable bell sound on terminal"))
        options_layout.addWidget(self.sound_cb)

        terminal_group.setLayout(options_layout)

        layout = QVBoxLayout()
        layout.addWidget(shell_group)
        layout.addWidget(display_group)
        layout.addWidget(terminal_group)
        layout.addStretch(1)

        self.setLayout(layout)
<|endoftext|>


<commit_before>import visa
import time
import datetime
import os

import textwrap

#import instruments

class powersupply(object):
    PSU=False
    rm=False
    setvolt=3.7
    def __init__(self,resourcemanager,gpib):
        try:
            self.rm=resourcemanager
            self.PSU = self.rm.get_instrument("GPIB0::"+gpib+"::INSTR")
            self.PSU.write('INST P6V')
            self.PSU.write('CURR 1e0;:VOLT '+"3.7"+';')
#            self.PSU.write('VOLT:PROT:STATE ON;:VOLT:PROT 5.6;')
        except:
            pass

    def SetVoltage(self,volt):
        try:
            self.PSU.write('VOLT '+volt)
            self.setvolt=volt
            return True
        except:
            pass

    def SetCurrent(self,current):
        try:
            self.PSU.write('CURR '+current)
#            self.setvolt=volt
            return True
        except:
            pass

    def disconnect(self,visalib):
        try:
            visa.VisaLibrary.gpib_control_ren(visalib, self.PSU.session,6)
            visa.VisaLibrary.close(visalib, self.PSU.session)
        except:
            pass

    def output(self,on=False):
        if on:
            self.PSU.write('OUTPut 1')
#            self.PSU.write('OUTPut ON')
        else:
            self.PSU.write('OUTPut 0')
#            self.PSU.write('OUTPut OFF')
#        pass

    def read(self):
        return self.setvolt

class sourcemeter(object):
    SMU=False
    rm=False
    setvolt=3.7
    setcurrent=0.0
    def __init__(self,resourcemanager,gpib):
        self.rm=resourcemanager
        self.SMU = self.rm.get_instrument("GPIB0::"+gpib+"::INSTR")
#        print self.SMU
        self.reset()

    def disconnect(self,visalib):
        try:
            visa.VisaLibrary.gpib_control_ren(visalib, self.SMU.session,6)
            visa.VisaLibrary.close(visalib, self.SMU.session)
        except:
            pass

    # Resets Equipment
    def reset (self):
        self.SMU.write('*RST')

    # Controls Beeper
#    def beep (self, beeper = 'ON'):
#        self.SMU.write(':SYST:BEEP:STAT %s' % beeper)

    # Enable Outputs
    def output_enable (self, channel = 1):
        if (channel == 1):
            self.SMU.write(':OUTP:STAT 1;:INIT')
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))
    # Disable outputs
    def output_disable (self, channel = 1):
        self.SMU.write(':OUTP:STAT 0')
        if (channel != 1):
            raise Exception("Invalid channel selection CH{0}" .format(channel))
    def output(self,on=False):
        if on:
            self.output_enable(1)
        else:
            self.output_disable(1)

    def sense_4W_enable (self):
        self.SMU.write(':SYST:RSEN ON')

    def sense_4W_disable (self):
        self.SMU.write(':SYST:RSEN OFF')
    def sense_4W(self,on=False):
        if on:
            self.sense_4W_enable()
        else:
            self.sense_4W_disable()

    # Set Out V
    def set_v (self, voltage, channel = 1):
        if (channel == 1):
            self.SMU.write(":SOUR:FUNC VOLT")
            self.SMU.write(":SOUR:VOLT:MODE FIX")
            self.SMU.write(":SOUR:VOLT %f"%(voltage))
#            :SOUR:FUNC VOLT
#            :SOUR:VOLT:MODE FIX
#            :SOUR:VOLT %f
#            '''%(voltage) ))
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Set Out I
    def set_i (self, current, channel = 1):
        if (channel == 1):
            self.SMU.write(":SOUR:FUNC CURR")
            self.SMU.write(":SOUR:CURR:MODE FIX")
            self.SMU.write(":SOUR:CURR %f"%(current))
#            self.SMU.write(textwrap.dedent ('''
#            :SOUR:FUNC CURR
#            :SOUR:CURR:MODE FIX
#            :SOUR:CURR %f
#            '''%(current) ))
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Set Out V Limit
    def set_v_limit (self, voltage, channel = 1):
        if (channel == 1):
            self.SMU.write(":SOUR:FUNC CURR")
            self.SMU.write(":SOUR:CURR:MODE FIX")
            self.SMU.write(":SENS:VOLT:DC:PROT:LEV %f"%(voltage))
#            self.SMU.write(textwrap.dedent ('''
#            :SOUR:FUNC CURR
#            :SOUR:CURR:MODE FIX
#            :SENS:VOLT:DC:PROT:LEV %f
#            '''%(voltage) ))
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Set Out I Limit
    def set_i_limit (self, current, channel = 1):
        if (channel == 1):
            self.SMU.write(textwrap.dedent ('''
            :SOUR:FUNC VOLT
            :SOUR:VOLT:MODE FIX
            :SENS:CURR:DC:PROT:LEV %f
            '''%(current) ))
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Set V Range
    def set_v_range (self, voltage, channel = 1, mode = 'source'):
        if (channel == 1):
            if (mode == 'sense'):
                if (voltage != 'auto'):
                    self.SMU.write(':SENS:VOLT:RANG %f' % voltage)
                else:
                    self.SMU.write(':SENS:VOLT:DC:RANGE:AUTO 1')

            elif (mode == 'source'):
                if (voltage != 'auto'):
                    self.SMU.write(textwrap.dedent ('''
                    :SOUR:FUNC VOLT
                    :SOUR:VOLT:MODE FIX
                    :SOUR:VOLT:RANG %f
                    '''%(voltage) ))
                else:
                    self.SMU.write(':SOUR:VOLT:DC:RANGE:AUTO 1')

            else:
                raise Exception('Invalid Mode Selection ("source" or "sense")')

        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Set I Range
    def set_i_range (self, current, channel = 1, mode = 'source'):
        if (channel == 1):
            if (mode == 'sense'):
                if (current != 'auto'):
                    self.SMU.write(':SENS:CURR:RANG %f' % current)
                else:
                    self.SMU.write(':SENS:CURR:DC:RANGE:AUTO 1')

            elif (mode == 'source'):
                if (current != 'auto'):
                    self.SMU.write(textwrap.dedent ('''
                    :SOUR:FUNC CURR
                    :SOUR:CURR:MODE FIX
                    :SOUR:CURR:RANG %f
                    '''%(current) ))
                else:
                    self.SMU.write(':SOUR:CURR:DC:RANGE:AUTO 1')

            else:
                raise Exception('Invalid Mode Selection ("source" or "sense")')

        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Read V
    def read_v (self, samples = 1, channel = 1, avg_mode = 'MOV', filt = 'ON', nplc = 1):
        if (channel == 1):
            self.SMU.write(textwrap.dedent ('''
                *CLS
                :ABOR
                :ARM:COUN 1;SOUR TIM
                :FUNC 'VOLT:DC';:VOLT:NPLC %f;:AVER:TCON %s;COUN %d;STAT %s
                :FORM:ELEM:SENS VOLT
                :INIT
                ''' %(nplc, avg_mode, samples, filt)))

            self.SMU.ask('*OPC?')

            return float(self.SMU.ask(':SENSE:DATA:LAT?'))
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Read I
    def read_i (self, samples = 1, channel = 1, avg_mode = 'MOV', filt = 'ON', nplc = 1):
        if (channel == 1):
            self.SMU.write(textwrap.dedent ('''
            *CLS
            :ABOR
            :ARM:COUN 1;SOUR TIM
            :FUNC 'CURR:DC';:CURR:NPLC %f;:AVER:TCON %s;COUN %d;STAT %s
            :FORMAT:ELEMENTS:SENSE CURR
            :INIT
            ''' %(nplc, avg_mode, samples, filt)))

            self.SMU.ask('*OPC?')

            return float(self.SMU.ask(':SENSE:DATA:LAT?'))

        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Read W
#    def read_w (self, samples=1, channel=1):
#        if (channel == 1):
#            self.SMU.write(textwrap.dedent ('''
#            :CALC:MATH:NAME "POWER"
#            :CALC:STAT ON
#            :INIT
#            ''' ))
#
#            return float(self.SMU.ask(":CALC:DATA?"))
#
#        else:
#            raise Exception("Invalid channel selection CH{0}" .format(channel))

    #Set I range for the display
    def set_range_display (self, digits = 7, channel = 1):
        if (channel == 1):
            self.SMU.write(':DISP:DIG %d' % int(digits) )

            return

        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    def error_query(self):
        ''' the error queue hold error and status messages
        '''
        print self.SMU.ask('SYST:ERR?')

class multimeter(object):
    VOLTMETER=""
    rm=""
    def __init__(self,resourcemanager,gpib,isUSB=False):
        self.rm=resourcemanager
        if isUSB==False:
            self.VOLTMETER = self.rm.get_instrument("GPIB0::"+gpib+"::INSTR")
        else:
            self.VOLTMETER = self.rm.get_instrument("USB0::0x0957::0x1A07::"+gpib+"::INSTR")#USB0::0x0957::0x1A07::SN????????::INSTR

            self.VOLTMETER.write("INP:IMP:AUTO ON")

#        self.VOLTMETER = self.rm.get_instrument("SENS:VOLT:IMP:AUTO ON")
#        self.VOLTMETER = self.rm.get_instrument(gpib)#debug code

    def sample(self):
        read=self.VOLTMETER.ask('READ?')
#        read=self.VOLTMETER.read()
        #print( ">>>" +read+'\n')
        return read

    def disconnect(self,visalib):
        visa.VisaLibrary.gpib_control_ren(visalib, self.VOLTMETER.session,6)
        visa.VisaLibrary.close(visalib, self.VOLTMETER.session)
        return True

class multimeter2(object):
    VOLTMETER2=""
    channels="(@101)"
    rm=""
    isUse=False
    def __init__(self,resourcemanager,gpib=10,isuse=False):
        self.isUse=isuse
        self.rm=resourcemanager
        if self.isUse == True:
            self.VOLTMETER2 = self.rm.get_instrument("GPIB0::"+gpib+"::INSTR")
            read=self.VOLTMETER2.ask('*IDN?')
#            read=self.VOLTMETER2.read()
            #print( ">>>" +self.VOLTMETER2.read()+'\n')
            self.VOLTMETER2.write('*RST')
            #print(self.channels)

    def sample(self):
        if self.isUse == True:
            self.VOLTMETER2.write('SENS:FUNC "VOLT:DC", '+self.channels    )
            self.VOLTMETER2.write('INP:IMP:AUTO ON,'+self.channels    )#

            self.VOLTMETER2.write('SENS:VOLT:DC:NPLC 2, '+self.channels    )
            self.VOLTMETER2.write('SENS:VOLT:DC:RANG:AUTO ON, '+self.channels    )
            self.VOLTMETER2.write('TRIG:SOUR IMM')
#            self.VOLTMETER2.write('TRIG:TIM MIN')
            self.VOLTMETER2.write('TRIG:COUNT 1.0e0')
            self.VOLTMETER2.write('INIT')
#            self.VOLTMETER2.write('*OPC?')
            read=self.VOLTMETER2.ask("*OPC?")
            #print( ">>>" + self.VOLTMETER2.read()+'\n')
            read=self.VOLTMETER2.ask('READ?')#
#            read=self.VOLTMETER2.read()
            #print( ">>>" + read+'\n')
            return read
        return 0

    def setChannel(self,chanlist):
        if self.isUse == True:
            self.channels = chanlist
#            self.VOLTMETER2.write('SYST:PRES')
            self.VOLTMETER2.write('CONF:VOLT:DC 10,1.0e-5,'+chanlist)
            self.VOLTMETER2.write('ROUT:SCAN '+chanlist)
            self.VOLTMETER2.write('ROUT:CHAN:DEL:AUTO OFF, '+chanlist    )
            self.VOLTMETER2.write('ROUT:CHAN:DEL 2e-1, '+chanlist    )
            self.VOLTMETER2.write('FORM:READ:TIME:TYPE ABS')
#            self.VOLTMETER2.write('FORM:READ:ALAR OFF')
            self.VOLTMETER2.write('FORM:READ:CHAN ON')
#            self.VOLTMETER2.write('FORM:READ:TIME OFF')
#            self.VOLTMETER2.write('FORM:READ:UNIT OFF')
            self.VOLTMETER2.write('SENS:FUNC "VOLT:DC", '+self.channels    )
            self.VOLTMETER2.write('INP:IMP:AUTO ON,'+self.channels    )#

#            self.VOLTMETER2.write('SENS:VOLT:DC:NPLC 2, '+self.channels    )
#            self.VOLTMETER2.write('SENS:VOLT:DC:RANG:AUTO ON, '+self.channels    )
#            self.VOLTMETER2.write('TRIG:SOUR IMM')
#            self.VOLTMETER2.write('TRIG:TIM MIN')
#            self.VOLTMETER2.write('TRIG:COUNT 1.0e0')

        return True

    def disconnect(self,visalib):
        if self.isUse == True:
            visa.VisaLibrary.gpib_control_ren(visalib, self.VOLTMETER2.session,6)
            visa.VisaLibrary.close(visalib, self.VOLTMETER2.session)
        return True

class chamber(object):
    isCtrl=False
    CHAMBER=""
    def __init__(self,resourcemanager,gpib=16,isctrl=False):
        isCtrl=isctrl
        self.rm=resourcemanager
        self.CHAMBER = self.rm.get_instrument("GPIB0::"+gpib+"::INSTR")
        self.CHAMBER.ask('ROM?')
        #print( ">>>" + self.CHAMBER.read()+'\n')
#        self.CHAMBER.read()
        self.CHAMBER.ask("MODE, STANDBY")
#        self.CHAMBER.read()
        #print( ">>>" + self.CHAMBER.read()+'\n')
        if isCtrl == True:
            self.CHAMBER.ask("MODE, CONSTANT")
#            self.CHAMBER.read()
            #print(">>>"+self.CHAMBER.read()+'\n')

    def getTemp(self):
#        self.CHAMBER.write("TEMP?")
        read=self.CHAMBER.ask("TEMP?")
        #print( ">>>" + read+'\n')
        return read.split(',')

    def setTemp(self,temp):
        read=self.CHAMBER.ask("TEMP,s"+temp)
#        self.CHAMBER.read()
        #print( ">>>" + self.CHAMBER.read()+'\n')
        return read

    def close(self):
        self.CHAMBER.ask("MODE, STANDBY")
#        self.CHAMBER.read()
        #print( ">>>" + self.CHAMBER.read()+'\n')
        return True

    def disconnect(self,visalib):
        self.close()
        visa.VisaLibrary.gpib_control_ren(visalib, self.CHAMBER.session,6)
        visa.VisaLibrary.close(visalib, self.CHAMBER.session)
        return True

class dummy(object):
    def __init__(self):
        pass

    def SetVoltage(self,volt):
        pass

    def SetCurrent(self,current):
        pass

    def output(self,on=False):
        pass

    def disconnect(self,visalib):
        pass

    def read(self):
        return -3640

    def sample(self):
        return -34401

    def setChannel(self,chanlist):
        pass

    def getTemp(self):
        return ['-241','-241','limit+','limit-']

    def setTemp(self,temp):
        return "dummy"

    def reset (self):
        pass

    def sense_4W(self,on=False):
        pass

    def set_v_limit (self, voltage, channel = 1):
        pass

    def set_i_limit (self, current, channel = 1):
        pass

    def set_v_range (self, voltage, channel = 1, mode = 'source'):
        pass

    def set_i_range (self, current, channel = 1, mode = 'source'):
        pass

    def read_v (self, samples = 1, channel = 1, avg_mode = 'MOV', filt = 'ON', nplc = 1):
        return "dummy"

    def read_i (self, samples = 1, channel = 1, avg_mode = 'MOV', filt = 'ON', nplc = 1):
        return "dummy"

    def set_v (self, voltage, channel = 1):
        pass

    def set_i (self, current, channel = 1):
        pass

<commit_msg>removed comments<commit_after>import visa
import time
import datetime
import os

import textwrap

class powersupply(object):
    PSU=False
    rm=False
    setvolt=3.7
    def __init__(self,resourcemanager,gpib):
        try:
            self.rm=resourcemanager
            self.PSU = self.rm.get_instrument("GPIB0::"+gpib+"::INSTR")
            self.PSU.write('INST P6V')
            self.PSU.write('CURR 1e0;:VOLT '+"3.7"+';')
        except:
            pass

    def SetVoltage(self,volt):
        try:
            self.PSU.write('VOLT '+volt)
            self.setvolt=volt
            return True
        except:
            pass

    def SetCurrent(self,current):
        try:
            self.PSU.write('CURR '+current)
            return True
        except:
            pass

    def disconnect(self,visalib):
        try:
            visa.VisaLibrary.gpib_control_ren(visalib, self.PSU.session,6)
            visa.VisaLibrary.close(visalib, self.PSU.session)
        except:
            pass

    def output(self,on=False):
        if on:
            self.PSU.write('OUTPut 1')
        else:
            self.PSU.write('OUTPut 0')

    def read(self):
        return self.setvolt

class sourcemeter(object):
    SMU=False
    rm=False
    setvolt=3.7
    setcurrent=0.0
    def __init__(self,resourcemanager,gpib):
        self.rm=resourcemanager
        self.SMU = self.rm.get_instrument("GPIB0::"+gpib+"::INSTR")
        self.reset()

    def disconnect(self,visalib):
        try:
            visa.VisaLibrary.gpib_control_ren(visalib, self.SMU.session,6)
            visa.VisaLibrary.close(visalib, self.SMU.session)
        except:
            pass

    def reset (self):
        self.SMU.write('*RST')

    def output_enable (self, channel = 1):
        if (channel == 1):
            self.SMU.write(':OUTP:STAT 1;:INIT')
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    def output_disable (self, channel = 1):
        self.SMU.write(':OUTP:STAT 0')
        if (channel != 1):
            raise Exception("Invalid channel selection CH{0}" .format(channel))
    def output(self,on=False):
        if on:
            self.output_enable(1)
        else:
            self.output_disable(1)

    def sense_4W_enable (self):
        self.SMU.write(':SYST:RSEN ON')

    def sense_4W_disable (self):
        self.SMU.write(':SYST:RSEN OFF')
    def sense_4W(self,on=False):
        if on:
            self.sense_4W_enable()
        else:
            self.sense_4W_disable()

    # Set Out V
    def set_v (self, voltage, channel = 1):
        if (channel == 1):
            self.SMU.write(":SOUR:FUNC VOLT")
            self.SMU.write(":SOUR:VOLT:MODE FIX")
            self.SMU.write(":SOUR:VOLT %f"%(voltage))
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Set Out I
    def set_i (self, current, channel = 1):
        if (channel == 1):
            self.SMU.write(":SOUR:FUNC CURR")
            self.SMU.write(":SOUR:CURR:MODE FIX")
            self.SMU.write(":SOUR:CURR %f"%(current))
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Set Out V Limit
    def set_v_limit (self, voltage, channel = 1):
        if (channel == 1):
            self.SMU.write(":SOUR:FUNC CURR")
            self.SMU.write(":SOUR:CURR:MODE FIX")
            self.SMU.write(":SENS:VOLT:DC:PROT:LEV %f"%(voltage))
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Set Out I Limit
    def set_i_limit (self, current, channel = 1):
        if (channel == 1):
            self.SMU.write(textwrap.dedent ('''
            :SOUR:FUNC VOLT
            :SOUR:VOLT:MODE FIX
            :SENS:CURR:DC:PROT:LEV %f
            '''%(current) ))
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Set V Range
    def set_v_range (self, voltage, channel = 1, mode = 'source'):
        if (channel == 1):
            if (mode == 'sense'):
                if (voltage != 'auto'):
                    self.SMU.write(':SENS:VOLT:RANG %f' % voltage)
                else:
                    self.SMU.write(':SENS:VOLT:DC:RANGE:AUTO 1')

            elif (mode == 'source'):
                if (voltage != 'auto'):
                    self.SMU.write(textwrap.dedent ('''
                    :SOUR:FUNC VOLT
                    :SOUR:VOLT:MODE FIX
                    :SOUR:VOLT:RANG %f
                    '''%(voltage) ))
                else:
                    self.SMU.write(':SOUR:VOLT:DC:RANGE:AUTO 1')

            else:
                raise Exception('Invalid Mode Selection ("source" or "sense")')

        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Set I Range
    def set_i_range (self, current, channel = 1, mode = 'source'):
        if (channel == 1):
            if (mode == 'sense'):
                if (current != 'auto'):
                    self.SMU.write(':SENS:CURR:RANG %f' % current)
                else:
                    self.SMU.write(':SENS:CURR:DC:RANGE:AUTO 1')

            elif (mode == 'source'):
                if (current != 'auto'):
                    self.SMU.write(textwrap.dedent ('''
                    :SOUR:FUNC CURR
                    :SOUR:CURR:MODE FIX
                    :SOUR:CURR:RANG %f
                    '''%(current) ))
                else:
                    self.SMU.write(':SOUR:CURR:DC:RANGE:AUTO 1')

            else:
                raise Exception('Invalid Mode Selection ("source" or "sense")')

        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Read V
    def read_v (self, samples = 1, channel = 1, avg_mode = 'MOV', filt = 'ON', nplc = 1):
        if (channel == 1):
            self.SMU.write(textwrap.dedent ('''
                *CLS
                :ABOR
                :ARM:COUN 1;SOUR TIM
                :FUNC 'VOLT:DC';:VOLT:NPLC %f;:AVER:TCON %s;COUN %d;STAT %s
                :FORM:ELEM:SENS VOLT
                :INIT
                ''' %(nplc, avg_mode, samples, filt)))

            self.SMU.ask('*OPC?')

            return float(self.SMU.ask(':SENSE:DATA:LAT?'))
        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    # Read I
    def read_i (self, samples = 1, channel = 1, avg_mode = 'MOV', filt = 'ON', nplc = 1):
        if (channel == 1):
            self.SMU.write(textwrap.dedent ('''
            *CLS
            :ABOR
            :ARM:COUN 1;SOUR TIM
            :FUNC 'CURR:DC';:CURR:NPLC %f;:AVER:TCON %s;COUN %d;STAT %s
            :FORMAT:ELEMENTS:SENSE CURR
            :INIT
            ''' %(nplc, avg_mode, samples, filt)))

            self.SMU.ask('*OPC?')

            return float(self.SMU.ask(':SENSE:DATA:LAT?'))

        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    #Set I range for the display
    def set_range_display (self, digits = 7, channel = 1):
        if (channel == 1):
            self.SMU.write(':DISP:DIG %d' % int(digits) )

            return

        else:
            raise Exception("Invalid channel selection CH{0}" .format(channel))

    def error_query(self):
        ''' the error queue hold error and status messages
        '''
        print self.SMU.ask('SYST:ERR?')

class multimeter(object):
    VOLTMETER=""
    rm=""
    def __init__(self,resourcemanager,gpib,isUSB=False):
        self.rm=resourcemanager
        if isUSB==False:
            self.VOLTMETER = self.rm.get_instrument("GPIB0::"+gpib+"::INSTR")
        else:
            self.VOLTMETER = self.rm.get_instrument("USB0::0x0957::0x1A07::"+gpib+"::INSTR")#USB0::0x0957::0x1A07::SN????????::INSTR

            self.VOLTMETER.write("INP:IMP:AUTO ON")

    def sample(self):
        read=self.VOLTMETER.ask('READ?')
        return read

    def disconnect(self,visalib):
        visa.VisaLibrary.gpib_control_ren(visalib, self.VOLTMETER.session,6)
        visa.VisaLibrary.close(visalib, self.VOLTMETER.session)
        return True

class multimeter2(object):
    VOLTMETER2=""
    channels="(@101)"
    rm=""
    isUse=False
    def __init__(self,resourcemanager,gpib=10,isuse=False):
        self.isUse=isuse
        self.rm=resourcemanager
        if self.isUse == True:
            self.VOLTMETER2 = self.rm.get_instrument("GPIB0::"+gpib+"::INSTR")
            read=self.VOLTMETER2.ask('*IDN?')
            self.VOLTMETER2.write('*RST')

    def sample(self):
        if self.isUse == True:
            self.VOLTMETER2.write('SENS:FUNC "VOLT:DC", '+self.channels    )
            self.VOLTMETER2.write('INP:IMP:AUTO ON,'+self.channels    )#

            self.VOLTMETER2.write('SENS:VOLT:DC:NPLC 2, '+self.channels    )
            self.VOLTMETER2.write('SENS:VOLT:DC:RANG:AUTO ON, '+self.channels    )
            self.VOLTMETER2.write('TRIG:SOUR IMM')
            self.VOLTMETER2.write('TRIG:COUNT 1.0e0')
            self.VOLTMETER2.write('INIT')
            read=self.VOLTMETER2.ask("*OPC?")
            read=self.VOLTMETER2.ask('READ?')#
            return read
        return 0

    def setChannel(self,chanlist):
        if self.isUse == True:
            self.channels = chanlist
            self.VOLTMETER2.write('CONF:VOLT:DC 10,1.0e-5,'+chanlist)
            self.VOLTMETER2.write('ROUT:SCAN '+chanlist)
            self.VOLTMETER2.write('ROUT:CHAN:DEL:AUTO OFF, '+chanlist    )
            self.VOLTMETER2.write('ROUT:CHAN:DEL 2e-1, '+chanlist    )
            self.VOLTMETER2.write('FORM:READ:TIME:TYPE ABS')
            self.VOLTMETER2.write('FORM:READ:CHAN ON')
            self.VOLTMETER2.write('SENS:FUNC "VOLT:DC", '+self.channels    )
            self.VOLTMETER2.write('INP:IMP:AUTO ON,'+self.channels    )#
        return True

    def disconnect(self,visalib):
        if self.isUse == True:
            visa.VisaLibrary.gpib_control_ren(visalib, self.VOLTMETER2.session,6)
            visa.VisaLibrary.close(visalib, self.VOLTMETER2.session)
        return True

class chamber(object):
    isCtrl=False
    CHAMBER=""
    def __init__(self,resourcemanager,gpib=16,isctrl=False):
        isCtrl=isctrl
        self.rm=resourcemanager
        self.CHAMBER = self.rm.get_instrument("GPIB0::"+gpib+"::INSTR")
        self.CHAMBER.ask('ROM?')
        self.CHAMBER.ask("MODE, STANDBY")
        if isCtrl == True:
            self.CHAMBER.ask("MODE, CONSTANT")

    def getTemp(self):
        read=self.CHAMBER.ask("TEMP?")
        return read.split(',')

    def setTemp(self,temp):
        read=self.CHAMBER.ask("TEMP,s"+temp)
        return read

    def close(self):
        self.CHAMBER.ask("MODE, STANDBY")
        return True

    def disconnect(self,visalib):
        self.close()
        visa.VisaLibrary.gpib_control_ren(visalib, self.CHAMBER.session,6)
        visa.VisaLibrary.close(visalib, self.CHAMBER.session)
        return True

class dummy(object):
    def __init__(self):
        pass

    def SetVoltage(self,volt):
        pass

    def SetCurrent(self,current):
        pass

    def output(self,on=False):
        pass

    def disconnect(self,visalib):
        pass

    def read(self):
        return -3640

    def sample(self):
        return -34401

    def setChannel(self,chanlist):
        pass

    def getTemp(self):
        return ['-241','-241','limit+','limit-']

    def setTemp(self,temp):
        return "dummy"

    def reset (self):
        pass

    def sense_4W(self,on=False):
        pass

    def set_v_limit (self, voltage, channel = 1):
        pass

    def set_i_limit (self, current, channel = 1):
        pass

    def set_v_range (self, voltage, channel = 1, mode = 'source'):
        pass

    def set_i_range (self, current, channel = 1, mode = 'source'):
        pass

    def read_v (self, samples = 1, channel = 1, avg_mode = 'MOV', filt = 'ON', nplc = 1):
        return "dummy"

    def read_i (self, samples = 1, channel = 1, avg_mode = 'MOV', filt = 'ON', nplc = 1):
        return "dummy"

    def set_v (self, voltage, channel = 1):
        pass

    def set_i (self, current, channel = 1):
        pass

<|endoftext|>


<commit_before>import random
choices = {'r':'rock', 'p': 'paper', 's':'scissors'}
rules = {'r': ['s'], 's': ['p'], 'p': ['r']}

def play():
    print "choices ", choices
    print "rules ", rules
    print "type exit to finish game"
    pc_wins = 0
    user_wins = 0
    ties = 0
    while True:
        user_play = raw_input("Play: ")
        pc_play = random.choice(choices.keys())
        if user_play in choices:
            if pc_play == user_play:
                ties +=1
                print "Tie"
            elif pc_play in rules[user_play]:
                user_wins +=1
                print "User Wins"
            elif user_play in rules[pc_play]:
                pc_wins +=1
                print "Pc Wins"
            else:
                print "wierd"
        elif user_play == "exit":
            break
        else:
            print "Not a Valid Option"
    total = user_wins+pc_wins+ties
    pc_w_r = (pc_wins * 100 / total)
    us_w_r = (user_wins * 100 / total)
    ties_w_r = (ties * 100 / total)
    print "Stats"
    print "Total games:", total
    print "Pc Win rate: ", pc_w_r, "%"
    print "User Win rate: ", us_w_r , "%"
    print "Ties Rate: ", ties_w_r, "%"
play()<commit_msg>forking scissors<commit_after>import random

choices = {'r': 'rock', 'p': 'paper', 's': 'scissors'}
rules = {'r': ['s'], 's': ['p'], 'p': ['r']}
deviation0 = 2
deviation1 = 5
deviation2 = 10
deviation3 = 15

def think(historical):

def play():
    print "choices ", choices
    print "rules ", rules
    print "type exit to finish game"
    pc_wins = 0
    user_wins = 0
    ties = 0
    historical = []
    while True:
        user_play = raw_input("Play: ")
        thinked_play = think(historical)
        pc_play = random.choice(choices.keys())
        if user_play in choices:
            historical.append(user_play)
            if pc_play == user_play:
                ties += 1
                print "Tie"
            elif pc_play in rules[user_play]:
                user_wins += 1
                print "User Wins"
            elif user_play in rules[pc_play]:
                pc_wins += 1
                print "Pc Wins"
            else:
                print "wierd"
        elif user_play == "exit":
            break
        else:
            print "Not a Valid Option"
    total = user_wins + pc_wins + ties
    pc_w_r = (pc_wins * 100 / total)
    us_w_r = (user_wins * 100 / total)
    ties_w_r = (ties * 100 / total)
    print "Stats"
    print "Total games:", total
    print "Pc Win rate: ", pc_w_r, "%"
    print "User Win rate: ", us_w_r, "%"
    print "Ties Rate: ", ties_w_r, "%"

play()<|endoftext|>


<commit_before>from flask import render_template, request, flash
from flask_login import login_required

from .. import main
from ... import data_api_client
from ..auth import role_required

@main.route('/buyers', methods=['GET'])
@login_required
@role_required('admin')
def find_buyer_by_brief_id():
    brief_id = request.args.get('brief_id')

    try:
        brief = data_api_client.get_brief(brief_id).get('briefs')

    except:
        flash('no_brief', 'error')
        return render_template(
            "view_buyers.html",
            users=list(),
            title=None,
            brief_id=brief_id
        ), 404

    users = brief.get('users')
    title = brief.get('title')
    return render_template(
        "view_buyers.html",
        users=users,
        title=title,
        brief_id=brief_id
    )
<commit_msg>Remove unnecessary variable from route<commit_after>from flask import render_template, request, flash
from flask_login import login_required

from .. import main
from ... import data_api_client
from ..auth import role_required

@main.route('/buyers', methods=['GET'])
@login_required
@role_required('admin')
def find_buyer_by_brief_id():
    brief_id = request.args.get('brief_id')

    try:
        brief = data_api_client.get_brief(brief_id).get('briefs')

    except:
        flash('no_brief', 'error')
        return render_template(
            "view_buyers.html",
            users=list(),
            brief_id=brief_id
        ), 404

    users = brief.get('users')
    title = brief.get('title')
    return render_template(
        "view_buyers.html",
        users=users,
        title=title,
        brief_id=brief_id
    )
<|endoftext|>


<commit_before>"""Generic plugin support so we can find XBlocks.

This code is in the Runtime layer.

"""

import functools
import itertools
import logging
import pkg_resources
from xblock.internal import class_lazy

log = logging.getLogger(__name__)

PLUGIN_CACHE = {}

class PluginMissingError(Exception):
    """Raised when trying to load a plugin from an entry_point that cannot be found."""
    pass

class AmbiguousPluginError(Exception):
    """Raised when a class name produces more than one entry_point."""
    def __init__(self, all_entry_points):
        classes = (entpt.load() for entpt in all_entry_points)
        desc = ", ".join("{0.__module__}.{0.__name__}".format(cls) for cls in classes)
        msg = "Ambiguous entry points for {}: {}".format(all_entry_points[0].name, desc)
        super(AmbiguousPluginError, self).__init__(msg)

def default_select(identifier, all_entry_points):
    """
    Raise an exception when we have ambiguous entry points.
    """

    if len(all_entry_points) == 0:
        raise PluginMissingError(identifier)

    elif len(all_entry_points) == 1:
        return all_entry_points[0]

    elif len(all_entry_points) > 1:
        raise AmbiguousPluginError(all_entry_points)

class Plugin(object):
    """Base class for a system that uses entry_points to load plugins.

    Implementing classes are expected to have the following attributes:

        `entry_point`: The name of the entry point to load plugins from.

    """
    entry_point = None  # Should be overwritten by children classes

    @class_lazy
    def extra_entry_points(cls):  # pylint: disable=no-self-argument
        """
        Temporary entry points, for register_temp_plugin.  A list of pairs,
        (identifier, entry_point):

        [('test1', test1_entrypoint), ('test2', test2_entrypoint), ...]
        """
        return []

    @classmethod
    def _load_class_entry_point(cls, entry_point):
        """
        Load `entry_point`, and set the `entry_point.name` as the
        attribute `plugin_name` on the loaded object
        """
        class_ = entry_point.load()
        setattr(class_, 'plugin_name', entry_point.name)
        return class_

    @classmethod
    def load_class(cls, identifier, default=None, select=None):
        """Load a single class specified by identifier.

        If `identifier` specifies more than a single class, and `select` is not None,
        then call `select` on the list of entry_points. Otherwise, choose
        the first one and log a warning.

        If `default` is provided, return it if no entry_point matching
        `identifier` is found. Otherwise, will raise a PluginMissingError

        If `select` is provided, it should be a callable of the form::

            def select(identifier, all_entry_points):
                # ...
                return an_entry_point

        The `all_entry_points` argument will be a list of all entry_points matching `identifier`
        that were found, and `select` should return one of those entry_points to be
        loaded. `select` should raise `PluginMissingError` if no plugin is found, or `AmbiguousPluginError`
        if too many plugins are found
        """
        identifier = identifier.lower()
        key = (cls.entry_point, identifier)
        if key not in PLUGIN_CACHE:

            if select is None:
                select = default_select

            all_entry_points = list(pkg_resources.iter_entry_points(cls.entry_point, name=identifier))
            for extra_identifier, extra_entry_point in cls.extra_entry_points:
                if identifier == extra_identifier:
                    all_entry_points.append(extra_entry_point)

            try:
                selected_entry_point = select(identifier, all_entry_points)
            except PluginMissingError:
                if default is not None:
                    return default
                raise

            PLUGIN_CACHE[key] = cls._load_class_entry_point(selected_entry_point)

        return PLUGIN_CACHE[key]

    @classmethod
    def load_classes(cls, fail_silently=True):
        """Load all the classes for a plugin.

        Produces a sequence containing the identifiers and their corresponding
        classes for all of the available instances of this plugin.

        fail_silently causes the code to simply log warnings if a
        plugin cannot import. The goal is to be able to use part of
        libraries from an XBlock (and thus have it installed), even if
        the overall XBlock cannot be used (e.g. depends on Django in a
        non-Django application). There is diagreement about whether
        this is a good idea, or whether we should see failures early
        (e.g. on startup or first page load), and in what
        contexts. Hence, the flag.
        """
        all_classes = itertools.chain(
            pkg_resources.iter_entry_points(cls.entry_point),
            (entry_point for identifier, entry_point in cls.extra_entry_points),
        )
        for class_ in all_classes:
            try:
                yield (class_.name, cls._load_class_entry_point(class_))
            except Exception:  # pylint: disable=broad-except
                if fail_silently:
                    log.warning('Unable to load %s %r', cls.__name__, class_.name, exc_info=True)
                else:
                    raise

    @classmethod
    def register_temp_plugin(cls, class_, identifier=None, dist='xblock'):
        """Decorate a function to run with a temporary plugin available.

        Use it like this in tests::

            @register_temp_plugin(MyXBlockClass):
            def test_the_thing():
                # Here I can load MyXBlockClass by name.

        """
        from mock import Mock

        if identifier is None:
            identifier = class_.__name__.lower()

        entry_point = Mock(
            dist=Mock(key=dist),
            load=Mock(return_value=class_),
        )
        entry_point.name = identifier

        def _decorator(func):                           # pylint: disable=C0111
            @functools.wraps(func)
            def _inner(*args, **kwargs):                # pylint: disable=C0111
                global PLUGIN_CACHE

                old = list(cls.extra_entry_points)
                old_cache = PLUGIN_CACHE

                cls.extra_entry_points.append((identifier, entry_point))
                PLUGIN_CACHE = {}

                try:
                    return func(*args, **kwargs)
                finally:
                    cls.extra_entry_points = old
                    PLUGIN_CACHE = old_cache
            return _inner
        return _decorator
<commit_msg>Fixed typo in comment<commit_after>"""Generic plugin support so we can find XBlocks.

This code is in the Runtime layer.

"""

import functools
import itertools
import logging
import pkg_resources
from xblock.internal import class_lazy

log = logging.getLogger(__name__)

PLUGIN_CACHE = {}

class PluginMissingError(Exception):
    """Raised when trying to load a plugin from an entry_point that cannot be found."""
    pass

class AmbiguousPluginError(Exception):
    """Raised when a class name produces more than one entry_point."""
    def __init__(self, all_entry_points):
        classes = (entpt.load() for entpt in all_entry_points)
        desc = ", ".join("{0.__module__}.{0.__name__}".format(cls) for cls in classes)
        msg = "Ambiguous entry points for {}: {}".format(all_entry_points[0].name, desc)
        super(AmbiguousPluginError, self).__init__(msg)

def default_select(identifier, all_entry_points):
    """
    Raise an exception when we have ambiguous entry points.
    """

    if len(all_entry_points) == 0:
        raise PluginMissingError(identifier)

    elif len(all_entry_points) == 1:
        return all_entry_points[0]

    elif len(all_entry_points) > 1:
        raise AmbiguousPluginError(all_entry_points)

class Plugin(object):
    """Base class for a system that uses entry_points to load plugins.

    Implementing classes are expected to have the following attributes:

        `entry_point`: The name of the entry point to load plugins from.

    """
    entry_point = None  # Should be overwritten by children classes

    @class_lazy
    def extra_entry_points(cls):  # pylint: disable=no-self-argument
        """
        Temporary entry points, for register_temp_plugin.  A list of pairs,
        (identifier, entry_point):

        [('test1', test1_entrypoint), ('test2', test2_entrypoint), ...]
        """
        return []

    @classmethod
    def _load_class_entry_point(cls, entry_point):
        """
        Load `entry_point`, and set the `entry_point.name` as the
        attribute `plugin_name` on the loaded object
        """
        class_ = entry_point.load()
        setattr(class_, 'plugin_name', entry_point.name)
        return class_

    @classmethod
    def load_class(cls, identifier, default=None, select=None):
        """Load a single class specified by identifier.

        If `identifier` specifies more than a single class, and `select` is not None,
        then call `select` on the list of entry_points. Otherwise, choose
        the first one and log a warning.

        If `default` is provided, return it if no entry_point matching
        `identifier` is found. Otherwise, will raise a PluginMissingError

        If `select` is provided, it should be a callable of the form::

            def select(identifier, all_entry_points):
                # ...
                return an_entry_point

        The `all_entry_points` argument will be a list of all entry_points matching `identifier`
        that were found, and `select` should return one of those entry_points to be
        loaded. `select` should raise `PluginMissingError` if no plugin is found, or `AmbiguousPluginError`
        if too many plugins are found
        """
        identifier = identifier.lower()
        key = (cls.entry_point, identifier)
        if key not in PLUGIN_CACHE:

            if select is None:
                select = default_select

            all_entry_points = list(pkg_resources.iter_entry_points(cls.entry_point, name=identifier))
            for extra_identifier, extra_entry_point in cls.extra_entry_points:
                if identifier == extra_identifier:
                    all_entry_points.append(extra_entry_point)

            try:
                selected_entry_point = select(identifier, all_entry_points)
            except PluginMissingError:
                if default is not None:
                    return default
                raise

            PLUGIN_CACHE[key] = cls._load_class_entry_point(selected_entry_point)

        return PLUGIN_CACHE[key]

    @classmethod
    def load_classes(cls, fail_silently=True):
        """Load all the classes for a plugin.

        Produces a sequence containing the identifiers and their corresponding
        classes for all of the available instances of this plugin.

        fail_silently causes the code to simply log warnings if a
        plugin cannot import. The goal is to be able to use part of
        libraries from an XBlock (and thus have it installed), even if
        the overall XBlock cannot be used (e.g. depends on Django in a
        non-Django application). There is disagreement about whether
        this is a good idea, or whether we should see failures early
        (e.g. on startup or first page load), and in what
        contexts. Hence, the flag.
        """
        all_classes = itertools.chain(
            pkg_resources.iter_entry_points(cls.entry_point),
            (entry_point for identifier, entry_point in cls.extra_entry_points),
        )
        for class_ in all_classes:
            try:
                yield (class_.name, cls._load_class_entry_point(class_))
            except Exception:  # pylint: disable=broad-except
                if fail_silently:
                    log.warning('Unable to load %s %r', cls.__name__, class_.name, exc_info=True)
                else:
                    raise

    @classmethod
    def register_temp_plugin(cls, class_, identifier=None, dist='xblock'):
        """Decorate a function to run with a temporary plugin available.

        Use it like this in tests::

            @register_temp_plugin(MyXBlockClass):
            def test_the_thing():
                # Here I can load MyXBlockClass by name.

        """
        from mock import Mock

        if identifier is None:
            identifier = class_.__name__.lower()

        entry_point = Mock(
            dist=Mock(key=dist),
            load=Mock(return_value=class_),
        )
        entry_point.name = identifier

        def _decorator(func):                           # pylint: disable=C0111
            @functools.wraps(func)
            def _inner(*args, **kwargs):                # pylint: disable=C0111
                global PLUGIN_CACHE

                old = list(cls.extra_entry_points)
                old_cache = PLUGIN_CACHE

                cls.extra_entry_points.append((identifier, entry_point))
                PLUGIN_CACHE = {}

                try:
                    return func(*args, **kwargs)
                finally:
                    cls.extra_entry_points = old
                    PLUGIN_CACHE = old_cache
            return _inner
        return _decorator
<|endoftext|>


<commit_before><commit_msg>Python Refactor: yake_keyword_extraction<commit_after><|endoftext|>