text:
<TITLE>Review for Mad Dog and Glory (1993)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Mad Dog and Glory (1993)

reviewed by
Eric Walker

                             MAD DOG AND GLORY
                       A film review by Eric Walker
                        Copyright 1993 Eric Walker

     What a refreshing movie this was!

     In these days of Hollywood "cop" movies, where the good guys are
macho dudes and the bad guys are slimy and totally evil, a movie like
MAD DOG AND GLORY shines because it cares about something far more than
brainless melodrama.

     This a comedy, but you won't be rolling in the aisles with
laughter.  It's leisurely and even slow-paced, and you won't be on the
edge of your seat (until the climax).  There's some very brief nudity
and one extended sex scene, but it's not very erotic and there's almost
no T-and-A.  It has lots of gangsters, but there are no chase scenes,
no big shoot-outs, and the only time we see people blown away is during
the first five minutes.  So if you go to this one expecting the likes
of MARKED FOR DEATH or LETHAL WEAPON, you're going to be sorely
disappointed.

     MAD DOG AND GLORY isn't interested in pandering to our love of sex
and violence.  The director, John McNaughton, is interested more in
character development than in chase scenes and shoot outs.  This is
what makes the movie such a delight:  We CARE about the characters.

     The film does everything possible to distance itself from the
standard Hollywood cop movie, even in its choice of leads.  Robert De
Niro and Bill Murray headline the film, and one would expect De Niro to
play the cool, suave gangster (in a replay of his role in THE
UNTOUCHABLES), but it's Murray who's the heavy here.  De Niro is a cop
named Wayne (his friends call him "Mad Dog"), and he carries a gun, but
he hasn't used it in fifteen years.  He's a photographer: he
photographs the corpses of crime victims for police records.  Unlike
your typical Hollywood cop, he's shy, nervous, and unsure of himself,
so that when he stumbles across a holdup in a grocery store, one night,
he's willing to let the robber have anything he wants.  He's far from
perfect, and he feels guilty about it: later on he even fantasizes
about blowing away the robber, the way he "should have" done (and the
way we see cops shoot down bad guys in one movie after another).

     Bill Murray, meanwhile, doesn't look like such a bad guy at
first.  He's a gangster, Frank, and he does nasty things, but he wants
to make people laugh; he even does stand-up comedy at one of his own
clubs.  (He's not a very good comedian, however; all of his best lines
are stolen from someone else.)  De Niro saves his life during that hold
up--but he's the "bad guy" and ol' Mad Dog is the "good guy." So what
does he do?  He picks him up, and they go out drinking.  Cops and
gangsters aren't supposed to fraternize like this, of course, but real
life isn't the black-and-white world of Hollywood cop movies.  Stuff
like this happens all the time, and there's a fine line that both sides
occasionally tread.

     Which is why Frank decides to reward Wayne: he sends a girl over
to "be his friend" for a week.  It seems that she owes Frank "a
favor"--everyone seems to owe things to Frank--and she's paying off
her debt in this fashion.

     But as the trailer for the movie shows, things get a little more
complicated than anyone expects.  Wayne falls in love with Glory, and
Frank doesn't like this.  So he gives Frank an ultimatum: give Glory
back--or else.

     It sounds like your typical Hollywood cop plot, doesn't it?  But
I'm not giving away anything here, because the plot is the least
important part of the entire film.  What makes it such a joy to watch
is De Niro's typically amazing performance, backed up by a wonderful
role from Uma Thurman, who plays Glory.  Bill Murray is also good; this
may be the best role I've ever seen him play.

     I love watching De Niro in his "quiet" moments.  He can entrance
an audience just by talking softly, so much so that the sound of his
breathing is as mesmerizing as his voice.  He becomes his characters,
and he makes them so three-dimensional and lifelike that by the time
the climax rolled around I was watching his actions (including an
important financial transaction) and thinking "Really?  I didn't think
Wayne wouldn't do that."  I was rooting for him during the final fight
scene, and he underplays his character superbly.

     Uma Thurman is equally impressive as the equally insecure and shy
Glory.  Here are two characters who are tailor-made for each other, but
they have to overcome their initial shyness and self-doubt before they
can trust each other.  They're a long way from the brainless "macho"
cop and the whorish "moll" who jumps into the sack with the hero just
because he blinks in her direction.

     There's a sex scene that deserves especial mention: it's funny at
first, as Wayne and Glory finally get to know each other better; but it
becomes sad and tender as they embrace each other.  They're not merely
banging away and getting the audience hot and bothered; they're really
holding onto each other for security, for comfort.  They CARE about
each other, and that's why we care about them.

     The laughs in this film don't come from out-and-out gags, except
for one hilarious fight scene between a cop and a thug.  Instead, it's
the characters, both good and bad, who hold our attention and keep us
interested.  This movie is a character piece, and its strengths lie in
the way it works better when we THINK about the characters.

     John McNaughton is making a career for himself as a Hollywood
outsider.  A couple of years ago, he was asked to make a horror film
that could be marketed to the splatter-film crowd--but what he
delivered was HENRY: PORTRAIT OF A SERIAL KILLER.  The studio didn't
know what to do with it (especially since it was threatened with the X
rating), so they dumped it to the "art-house" market and released it on
video.  Now he's taken the "macho cop vs. gangster" cliche and turned
it on its side, giving us a film with no breathless action, little
blood-and-guts, and no car chases or smashing plate glass windows.  So
Universal released the film in the "quiet" period between Christmas and
Memorial Day, hoping to cash in on De Niro's reputation (and Bill
Murray's sudden popularity from the success of GROUNDHOG DAY).  The
film is fading fast from theaters, too--it's not going to be
remembered by anyone except the movie critics by the time the Christmas
movie season rolls around.

     But box-office isn't everything.  MAD DOG AND GLORY is a
delightfully original film, and if you enjoy original performances and
character development over chase-and-crash scenes, you'll be won over
by this film.  Check it out.

     When John McNaughton's next film hits the theaters, I'll certainly
be there to see it.

--
Channel 1 (R)   Cambridge, MA

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews

redpajama_set_name: RedPajamaGithub


text:
import {
  isString, iterateObject, keys,
  collectFromObject, collectFromArray
} from '../utils';
import { Mixin } from '../Mixin';

const CSS_STYLES_SEPARATOR_REGEX = /\s*;\s*/;
const CSS_STYLE_SEPARATOR_REGEX = /\s*:\s*/;

class Style extends Mixin {
  css = {};

  afterUpdate(newValue, oldValue) {
    const {
      elem,
      args,
      css
    } = this;

    if (args) {
      newValue = collectFromObject(args, (css, prop) => {
        css[prop] = newValue;
      });
    }

    if (isString(newValue)) {
      newValue = collectFromArray(
        newValue
          .split(CSS_STYLES_SEPARATOR_REGEX)
          .filter(Boolean)
          .map(constructStyleFromString),
        addCSSProp
      );
    }

    iterateObject(css, (value, prop) => {
      if (!newValue[prop]) {
        elem.removeCSS(prop);
      }
    });
    elem.css(newValue);

    this.css = newValue;
  }

  beforeRemove(isElementRemoved) {
    if (!isElementRemoved) {
      const {
        elem,
        css
      } = this;

      elem.removeCSS.apply(elem, keys(css));
    }
  }
}

function addCSSProp(css, item) {
  const [prop, value] = item;

  css[prop] = value;
}

function constructStyleFromString(style) {
  const split = style.split(CSS_STYLE_SEPARATOR_REGEX);

  return [
    split[0].trim(),
    split[1].trim()
  ];
}

export { Style };


text:
package statsd

import (
	"bytes"
	"fmt"
	"math"
	"strconv"
	"strings"

	"github.com/circonus-labs/circonus-agent/internal/config"
	"github.com/circonus-labs/circonus-agent/internal/tags"
	cgm "github.com/circonus-labs/circonus-gometrics/v3"
	"github.com/maier/go-appstats"
	"github.com/spf13/viper"
)

// processPacket parses a packet for metrics.
func (s *Server) processPacket(pkt []byte) {
	if len(pkt) == 0 {
		return
	}

	s.logger.Debug().Str("packet", string(pkt)).Msg("received")
	metrics := bytes.Split(pkt, []byte("\n"))
	for _, metric := range metrics {
		if err := s.parseMetric(string(metric)); err != nil {
			_ = appstats.IncrementInt("statsd_metrics_bad")
			s.logger.Warn().Err(err).Str("metric", string(metric)).Msg("parsing")
		}
	}
}

// getMetricDestination determines "where" a metric should be sent (host or group)
// and cleans up the metric name if it matches a host|group prefix.
func (s *Server) getMetricDestination(metricName string) (string, string) {
	if s.hostPrefix == "" && s.groupPrefix == "" { // no host/group prefixes - send all metrics to host
		return destHost, metricName
	}

	if s.hostPrefix != "" && s.groupPrefix != "" { // explicit host and group, otherwise ignore
		if strings.HasPrefix(metricName, s.hostPrefix) {
			return destHost, strings.Replace(metricName, s.hostPrefix, "", 1)
		}
		if strings.HasPrefix(metricName, s.groupPrefix) {
			return destGroup, strings.Replace(metricName, s.groupPrefix, "", 1)
		}
		s.logger.Debug().Str("metric_name", metricName).Msg("does not match host|group prefix, ignoring")
		return destIgnore, metricName
	}

	if s.groupPrefix != "" && s.hostPrefix == "" { // default to host
		if strings.HasPrefix(metricName, s.groupPrefix) {
			return destGroup, strings.Replace(metricName, s.groupPrefix, "", 1)
		}
		return destHost, metricName
	}

	if s.groupPrefix == "" && s.hostPrefix != "" { // default to group
		if strings.HasPrefix(metricName, s.hostPrefix) {
			return destHost, strings.Replace(metricName, s.hostPrefix, "", 1)
		}
		return destGroup, metricName
	}

	s.logger.Debug().Str("metric_name", metricName).Msg("does not match host|group criteria, ignoring")
	return destIgnore, metricName
}

func (s *Server) parseMetric(metric string) error {
	// ignore 'blank' lines/empty strings
	if len(metric) == 0 {
		return nil
	}

	metricName := ""
	metricType := ""
	metricValue := ""
	metricRate := ""
	sampleRate := 1.0
	metricTagSpec := ""

	if !s.metricRegex.MatchString(metric) {
		return fmt.Errorf("invalid metric format '%s', ignoring", metric) //nolint:goerr113
	}

	for _, match := range s.metricRegex.FindAllStringSubmatch(metric, -1) {
		for gIdx, matchVal := range match {
			switch s.metricRegexGroupNames[gIdx] {
			case "name":
				metricName = s.nameSpaceReplaceRx.ReplaceAllString(matchVal, "_")
			case "type":
				metricType = matchVal
			case "value":
				metricValue = matchVal
			case "sample":
				metricRate = matchVal
			case "tags":
				metricTagSpec = matchVal
			default:
				// ignore any other groups
			}
		}
	}

	if metricName == "" || metricValue == "" {
		return fmt.Errorf("empty metric name (%s) or metric value (%s) - metricRegex failed, check", metricName, metricValue) //nolint:goerr113
	}

	if metricRate != "" {
		r, err := strconv.ParseFloat(metricRate, 32)
		if err != nil {
			return fmt.Errorf("invalid metric sampling rate: %w, ignoring", err)
		}
		sampleRate = r
		if sampleRate == 0.0 {
			return fmt.Errorf("invalid sample rate %f", sampleRate) //nolint:goerr113
		}
	}

	var (
		dest       *cgm.CirconusMetrics
		metricDest string
	)
	metricDest, metricName = s.getMetricDestination(metricName)

	if metricDest == destGroup {
		dest = s.groupMetrics
	} else if metricDest == destHost {
		dest = s.hostMetrics
		// metricName = s.hostCategory + config.MetricNameSeparator + metricName
	}

	if dest == nil {
		return fmt.Errorf("invalid metric destination (%s)->(%s)", metric, metricDest) //nolint:goerr113
	}

	// add stream tags to metric name
	metricTagList := []string{}
	if metricTagSpec != "" {
		metricTagList = strings.Split(metricTagSpec, tags.Separator)
	}
	tagList := make([]string, 0, len(s.baseTags)+len(metricTagList))
	tagList = append(tagList, s.baseTags...)
	tagList = append(tagList, metricTagList...)
	metricTags := tags.FromList(tagList)

	s.logger.Debug().
		Str("destination", metricDest).
		Str("metric", metric).
		Str("name", metricName).
		Str("type", metricType).
		Str("value", metricValue).
		Float64("rate", sampleRate).
		Strs("mtags", metricTagList).
		Msg("parsed")

	switch metricType {
	case "c": // counter
		v, err := strconv.ParseUint(metricValue, 10, 64)
		if err != nil {
			return fmt.Errorf("invalid counter value: %w", err)
		}
		val := int64(math.Round(float64(v) / sampleRate))
		metricTags = append(metricTags, cgm.Tag{Category: "statsd_type", Value: "count"})
		// counters always go in bin 0
		dest.RecordCountForValueWithTags(metricName, metricTags, 0, val)
		// s.logger.Debug().
		// 	Str("metric_name", metricName).
		// 	Float64("sample_rate", sampleRate).
		// 	Float64("bin", 0).
		// 	Int64("val", val).
		// 	Msg("RecordCountForValueWithTags - COUNTER")

	case "g": // gauge
		var val interface{}
		switch {
		case strings.Contains(metricValue, "."):
			v, err := strconv.ParseFloat(metricValue, 64)
			if err != nil {
				return fmt.Errorf("invalid gauge value: %w", err)
			}
			val = v
		case strings.Contains(metricValue, "-"):
			v, err := strconv.ParseInt(metricValue, 10, 64)
			if err != nil {
				return fmt.Errorf("invalid gauge value: %w", err)
			}
			val = v
		default:
			v, err := strconv.ParseUint(metricValue, 10, 64)
			if err != nil {
				return fmt.Errorf("invalid gauge value: %w", err)
			}
			val = v
		}
		if viper.GetBool(config.KeyClusterEnabled) && viper.GetBool(config.KeyClusterStatsdHistogramGauges) {
			dest.RemoveHistogramWithTags(metricName, metricTags)
			dest.SetHistogramValueWithTags(metricName, metricTags, val.(float64))
		} else {
			metricTags = append(metricTags, cgm.Tag{Category: "statsd_type", Value: "gauge"})
			dest.GaugeWithTags(metricName, metricTags, val)
		}
	case "h": // histogram (circonus)
		v, err := strconv.ParseFloat(metricValue, 64)
		if err != nil {
			return fmt.Errorf("invalid histogram value: %w", err)
		}
		val := int64(math.Round(1.0 / sampleRate))
		dest.RecordCountForValueWithTags(metricName, metricTags, v, val)
	case "ms": // timing measurement
		v, err := strconv.ParseFloat(metricValue, 64)
		if err != nil {
			return fmt.Errorf("invalid histogram value: %w", err)
		}
		metricTags = append(metricTags, cgm.Tag{Category: "statsd_type", Value: "timing"})
		val := int64(math.Round(1.0 / sampleRate))
		dest.RecordCountForValueWithTags(metricName, metricTags, v, val)
		// s.logger.Debug().
		// 	Str("metric_name", metricName).
		// 	Float64("sample_rate", sampleRate).
		// 	Float64("bin", v).
		// 	Int64("val", val).
		// 	Msg("RecordCountForValueWithTags - TIMING")
	case "s": // set
		// in the case of sets, the value is the unique "thing" to be tracked
		// counters are used to track individual "things"
		metricTags = append(metricTags, cgm.Tags{
			cgm.Tag{Category: "set_id", Value: metricValue},
			cgm.Tag{Category: "statsd_type", Value: "count"},
		}...)
		dest.RecordCountForValueWithTags(metricName, metricTags, 0, 1)
	case "t": // text (circonus)
		dest.SetTextWithTags(metricName, metricTags, metricValue)
	default:
		return fmt.Errorf("invalid metric type (%s)", metricType) //nolint:goerr113
	}

	return nil
}


text:
package com.lynden.gmapsfx.service.directions;

/**
 *
 * @author Andre
 */
public enum DirectionStatus {
    INVALID_REQUEST, OK, OVER_QUERY_LIMIT,
    REQUEST_DENIED, UNKNOWN_ERROR, NOT_FOUND,
    MAX_WAYPOINTS_EXCEEDED ;
}


text:
package odp

import (
	"fmt"
	"net"
	"syscall"

	"github.com/weaveworks/go-odp/odp"
)

// ODP admin functionality

func CreateDatapath(dpname string) (err error, supported bool) {
	dpif, err := odp.NewDpif()
	if err != nil {
		if odp.IsKernelLacksODPError(err) {
			return nil, false
		}

		return err, true
	}

	defer dpif.Close()

	dp, err := dpif.CreateDatapath(dpname)
	if err != nil && !odp.IsDatapathNameAlreadyExistsError(err) {
		return err, true
	}

	// Pick an ephemeral port number to use in probing for vxlan
	// support.
	udpconn, err := net.ListenUDP("udp4", nil)
	if err != nil {
		return err, true
	}

	// we leave the UDP socket open, so creating a vxlan vport on
	// the same port number should fail.  But that's fine: It's
	// still sufficient to probe for support.
	portno := uint16(udpconn.LocalAddr().(*net.UDPAddr).Port)
	vpid, err := dp.CreateVport(odp.NewVxlanVportSpec(
		fmt.Sprintf("vxlan-%d", portno), portno))
	if nlerr, ok := err.(odp.NetlinkError); ok {
		if syscall.Errno(nlerr) == syscall.EAFNOSUPPORT {
			dp.Delete()
			return fmt.Errorf("kernel does not have Open vSwitch VXLAN support"), false
		}
	}

	if err == nil {
		dp.DeleteVport(vpid)
	}

	udpconn.Close()
	return nil, true
}

func DeleteDatapath(dpname string) error {
	dpif, err := odp.NewDpif()
	if err != nil {
		return err
	}

	defer dpif.Close()

	dp, err := dpif.LookupDatapath(dpname)
	if err != nil {
		if odp.IsNoSuchDatapathError(err) {
			return nil
		}

		return err
	}

	return dp.Delete()
}

func AddDatapathInterface(dpname string, ifname string) error {
	dpif, err := odp.NewDpif()
	if err != nil {
		return err
	}

	defer dpif.Close()

	dp, err := dpif.LookupDatapath(dpname)
	if err != nil {
		return err
	}

	_, err = dp.CreateVport(odp.NewNetdevVportSpec(ifname))
	return err
}


text:
package ast;

import tagtable.Tag;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Branch implements Seedling {
    protected final Tag tag;
    private final ArrayList<Branch> children = new ArrayList<>();
    private Seedling parent;
    int level;

    public Branch(Tag tag) {
        this.tag = tag;
    }

    public void append(Branch subNode) {
        subNode.registerParent(this);
        children.add(subNode);
    }
    public void registerParent(Seedling seedling) {
        this.parent = seedling;
    }
    public Seedling getParent() {
        return parent;
    }
    public void lrTraverse(BranchProcessFunction func, int level) {
        func.processBranch(this, level);
        for (Branch aChildren : children) {
            aChildren.lrTraverse(func, level + 1);
        }
    }
    public void setLevel(int level) {
        this.level = level;
    }
    public int getLevel() {
        return level;
    }

    @Override
    public List<? extends Seedling> getChildren() {
        return children;
    }
    public Tag getTag() {
        return tag;
    }
    public String toString() {
        return tag.getValue();
    }

    public void flipChildren() {
        LinkedList<Branch> children = new LinkedList<>();
        for (Branch cr : this.children) {
            children.addFirst(cr);
        }
        this.children.clear();
        this.children.addAll(children);
    }
}


text:
var shell = require('shelljs'),
    spec = __dirname,
    path = require('path'),
    util = require('util'),
    fs = require('fs');

    var cordova_bin = path.join(spec, '../..', 'bin');
    var test_projectPath = path.join(spec, '../', 'cdv-test-project');
    var test_platformPath = path.join(test_projectPath, 'platforms', 'osx');

    var tmp = require('tmp').dirSync().name;

function initProject() {
    // remove existing folder
    var pPath = path.join(test_projectPath, 'platforms');
    shell.rm('-rf', pPath);
}

describe('platform add', function() {

    beforeEach(function() {
        initProject();

        shell.cd(test_projectPath);
        var command = 'cordova platform add ../../';
        console.log('executing "%s" in "%s"', command, shell.pwd());
        var return_code = shell.exec(command, { silent: false}).code;
        expect(return_code).toBe(0);
    });

    it('should have a config.xml', function() {
        var configXmlPath = path.join(test_platformPath, 'HelloCordova', 'config.xml');
        expect(fs.existsSync(configXmlPath)).toBe(true);
    });

    it('should have the correct icons', function() {

        var platformIcons = [
            {name: 'icon-16x16.png', width: 16, height: 16},
            {name: 'icon-32x32.png', width: 32, height: 32},
            {name: 'icon-64x64.png', width: 64, height: 64},
            {name: 'icon-128x128.png', width: 128, height: 128},
            {name: 'icon-256x256.png', width: 256, height: 256},
            {name: 'icon-512x512.png', width: 512, height: 512},
            {name: 'icon-1024x1024.png', width: 1024, height: 1024}
        ];

        var appIconsPath = path.join(test_platformPath, 'HelloCordova','Images.xcassets','AppIcon.appiconset');
        var srcIcon = path.join(test_projectPath, 'res', 'test-64x64.png');
        platformIcons.forEach(function(iconDef) {
            var iconPath = path.join(appIconsPath, iconDef.name);
            expect(fs.existsSync(iconPath)).toBe(true);

            // check if the icons are the same as the one specified in the config.xml
            var cmd = util.format('cmp "%s" "%s"', srcIcon, iconPath);
            var return_code = shell.exec(cmd, { silent: false}).code;
            expect(return_code).toBe(0);

        });
    });

});


text:
Author

            {{site.username}}

{{site.user_description}}

        {{site.email}}


text:
typedef NS_ENUM(NSUInteger, SliderAnimateDirection) {
    SliderAnimateDirectionL2R,
    SliderAnimateDirectionR2L,
    SliderAnimateDirectionT2B,
    SliderAnimateDirectionB2T
};

@interface SliderAnimate : NSObject<NSViewControllerPresentationAnimator>
@property (copy, nonatomic) void(^presentationWillBeginCompletion)(void);
@property (copy, nonatomic) void(^presentationDidEndCompletion)(void);
@property (copy, nonatomic) void(^dismissDidEndCompletion)(void);
@property (copy, nonatomic) void(^dismissWillBeginCompletion)(void);
@property (assign, nonatomic) SliderAnimateDirection direction;
@end


text:
"""Script for doing QA on Ganeti.

"""

# pylint: disable=C0103
# due to invalid name

import copy
import datetime
import optparse
import sys

import qa_cluster
import qa_config
import qa_daemon
import qa_env
import qa_error
import qa_group
import qa_instance
import qa_monitoring
import qa_network
import qa_node
import qa_os
import qa_performance
import qa_job
import qa_rapi
import qa_tags
import qa_utils

from ganeti import utils
from ganeti import rapi # pylint: disable=W0611
from ganeti import constants
from ganeti import pathutils

from ganeti.http.auth import ParsePasswordFile
import ganeti.rapi.client # pylint: disable=W0611
from ganeti.rapi.client import UsesRapiClient

def _FormatHeader(line, end=72):
  """Fill a line up to the end column.

  """
  line = "---- " + line + " "
  line += "-" * (end - len(line))
  line = line.rstrip()
  return line

def _DescriptionOf(fn):
  """Computes the description of an item.

  """
  if fn.__doc__:
    desc = fn.__doc__.splitlines()[0].strip()
  else:
    desc = "%r" % fn

  return desc.rstrip(".")

def RunTest(fn, *args, **kwargs):
  """Runs a test after printing a header.

  """

  tstart = datetime.datetime.now()

  desc = _DescriptionOf(fn)

  print
  print _FormatHeader("%s start %s" % (tstart, desc))

  try:
    retval = fn(*args, **kwargs)
    return retval
  finally:
    tstop = datetime.datetime.now()
    tdelta = tstop - tstart
    print _FormatHeader("%s time=%s %s" % (tstop, tdelta, desc))

def ReportTestSkip(desc, testnames):
  """Reports that tests have been skipped.

  @type desc: string
  @param desc: string
  @type testnames: string or list of string
  @param testnames: either a single test name in the configuration
      file, or a list of testnames (which will be AND-ed together)

  """
  tstart = datetime.datetime.now()
  # TODO: Formatting test names when non-string names are involved
  print _FormatHeader("%s skipping %s, test(s) %s disabled" %
                      (tstart, desc, testnames))

def RunTestIf(testnames, fn, *args, **kwargs):
  """Runs a test conditionally.

  @param testnames: either a single test name in the configuration
      file, or a list of testnames (which will be AND-ed together)

  """
  if qa_config.TestEnabled(testnames):
    RunTest(fn, *args, **kwargs)
  else:
    desc = _DescriptionOf(fn)
    ReportTestSkip(desc, testnames)

def RunEnvTests():
  """Run several environment tests.

  """
  RunTestIf("env", qa_env.TestSshConnection)
  RunTestIf("env", qa_env.TestIcmpPing)
  RunTestIf("env", qa_env.TestGanetiCommands)

def _LookupRapiSecret(rapi_user):
  """Find the RAPI secret for the given user.

  @param rapi_user: Login user
  @return: Login secret for the user

  """
  CTEXT = "{CLEARTEXT}"
  master = qa_config.GetMasterNode()
  cmd = ["cat", qa_utils.MakeNodePath(master, pathutils.RAPI_USERS_FILE)]
  file_content = qa_utils.GetCommandOutput(master.primary,
                                           utils.ShellQuoteArgs(cmd))
  users = ParsePasswordFile(file_content)
  entry = users.get(rapi_user)
  if not entry:
    raise qa_error.Error("User %s not found in RAPI users file" % rapi_user)
  secret = entry.password
  if secret.upper().startswith(CTEXT):
    secret = secret[len(CTEXT):]
  elif secret.startswith("{"):
    raise qa_error.Error("Unsupported password schema for RAPI user %s:"
                         " not a clear text password" % rapi_user)
  return secret

def SetupCluster(rapi_user):
  """Initializes the cluster.

  @param rapi_user: Login user for RAPI
  @return: Login secret for RAPI

  """
  rapi_secret = utils.GenerateSecret()
  RunTestIf("create-cluster", qa_cluster.TestClusterInit,
            rapi_user, rapi_secret)
  if not qa_config.TestEnabled("create-cluster"):
    # If the cluster is already in place, we assume that exclusive-storage is
    # already set according to the configuration
    qa_config.SetExclusiveStorage(qa_config.get("exclusive-storage", False))
    if qa_rapi.Enabled():
      # To support RAPI on an existing cluster we have to find out the secret
      rapi_secret = _LookupRapiSecret(rapi_user)

  # Test on empty cluster
  RunTestIf("node-list", qa_node.TestNodeList)
  RunTestIf("instance-list", qa_instance.TestInstanceList)
  RunTestIf("job-list", qa_job.TestJobList)

  RunTestIf("create-cluster", qa_node.TestNodeAddAll)
  if not qa_config.TestEnabled("create-cluster"):
    # consider the nodes are already there
    qa_node.MarkNodeAddedAll()

  RunTestIf("test-jobqueue", qa_cluster.TestJobqueue)
  RunTestIf("test-jobqueue", qa_job.TestJobCancellation)

  # enable the watcher (unconditionally)
  RunTest(qa_daemon.TestResumeWatcher)

  RunTestIf("node-list", qa_node.TestNodeList)

  # Test listing fields
  RunTestIf("node-list", qa_node.TestNodeListFields)
  RunTestIf("instance-list", qa_instance.TestInstanceListFields)
  RunTestIf("job-list", qa_job.TestJobListFields)
  RunTestIf("instance-export", qa_instance.TestBackupListFields)

  RunTestIf("node-info", qa_node.TestNodeInfo)

  return rapi_secret

def RunClusterTests():
  """Runs tests related to gnt-cluster.

  """
  for test, fn in [
    ("create-cluster", qa_cluster.TestClusterInitDisk),
    ("cluster-renew-crypto", qa_cluster.TestClusterRenewCrypto),
    ("cluster-verify", qa_cluster.TestClusterVerify),
    ("cluster-reserved-lvs", qa_cluster.TestClusterReservedLvs),
    # TODO: add more cluster modify tests
    ("cluster-modify", qa_cluster.TestClusterModifyEmpty),
    ("cluster-modify", qa_cluster.TestClusterModifyIPolicy),
    ("cluster-modify", qa_cluster.TestClusterModifyISpecs),
    ("cluster-modify", qa_cluster.TestClusterModifyBe),
    ("cluster-modify", qa_cluster.TestClusterModifyDisk),
    ("cluster-modify", qa_cluster.TestClusterModifyDiskTemplates),
    ("cluster-modify", qa_cluster.TestClusterModifyFileStorageDir),
    ("cluster-modify", qa_cluster.TestClusterModifySharedFileStorageDir),
    ("cluster-rename", qa_cluster.TestClusterRename),
    ("cluster-info", qa_cluster.TestClusterVersion),
    ("cluster-info", qa_cluster.TestClusterInfo),
    ("cluster-info", qa_cluster.TestClusterGetmaster),
    ("cluster-redist-conf", qa_cluster.TestClusterRedistConf),
    (["cluster-copyfile", qa_config.NoVirtualCluster],
     qa_cluster.TestClusterCopyfile),
    ("cluster-command", qa_cluster.TestClusterCommand),
    ("cluster-burnin", qa_cluster.TestClusterBurnin),
    ("cluster-master-failover", qa_cluster.TestClusterMasterFailover),
    ("cluster-master-failover",
     qa_cluster.TestClusterMasterFailoverWithDrainedQueue),
    (["cluster-oob", qa_config.NoVirtualCluster],
     qa_cluster.TestClusterOob),
    (qa_rapi.Enabled, qa_rapi.TestVersion),
    (qa_rapi.Enabled, qa_rapi.TestEmptyCluster),
    (qa_rapi.Enabled, qa_rapi.TestRapiQuery),
    ]:
    RunTestIf(test, fn)

def RunRepairDiskSizes():
  """Run the repair disk-sizes test.

  """
  RunTestIf("cluster-repair-disk-sizes", qa_cluster.TestClusterRepairDiskSizes)

def RunOsTests():
  """Runs all tests related to gnt-os.

  """
  os_enabled = ["os", qa_config.NoVirtualCluster]

  if qa_config.TestEnabled(qa_rapi.Enabled):
    rapi_getos = qa_rapi.GetOperatingSystems
  else:
    rapi_getos = None

  for fn in [
    qa_os.TestOsList,
    qa_os.TestOsDiagnose,
    ]:
    RunTestIf(os_enabled, fn)

  for fn in [
    qa_os.TestOsValid,
    qa_os.TestOsInvalid,
    qa_os.TestOsPartiallyValid,
    ]:
    RunTestIf(os_enabled, fn, rapi_getos)

  for fn in [
    qa_os.TestOsModifyValid,
    qa_os.TestOsModifyInvalid,
    qa_os.TestOsStatesNonExisting,
    ]:
    RunTestIf(os_enabled, fn)

def RunCommonInstanceTests(instance, inst_nodes):
  """Runs a few tests that are common to all disk types.

  """
  RunTestIf("instance-shutdown", qa_instance.TestInstanceShutdown, instance)
  RunTestIf(["instance-shutdown", "instance-console", qa_rapi.Enabled],
            qa_rapi.TestRapiStoppedInstanceConsole, instance)
  RunTestIf(["instance-shutdown", "instance-modify"],
            qa_instance.TestInstanceStoppedModify, instance)
  RunTestIf("instance-shutdown", qa_instance.TestInstanceStartup, instance)

  # Test shutdown/start via RAPI
  RunTestIf(["instance-shutdown", qa_rapi.Enabled],
            qa_rapi.TestRapiInstanceShutdown, instance)
  RunTestIf(["instance-shutdown", qa_rapi.Enabled],
            qa_rapi.TestRapiInstanceStartup, instance)

  RunTestIf("instance-list", qa_instance.TestInstanceList)

  RunTestIf("instance-info", qa_instance.TestInstanceInfo, instance)

  RunTestIf("instance-modify", qa_instance.TestInstanceModify, instance)
  RunTestIf(["instance-modify", qa_rapi.Enabled],
            qa_rapi.TestRapiInstanceModify, instance)

  RunTestIf("instance-console", qa_instance.TestInstanceConsole, instance)
  RunTestIf(["instance-console", qa_rapi.Enabled],
            qa_rapi.TestRapiInstanceConsole, instance)

  RunTestIf("instance-device-names", qa_instance.TestInstanceDeviceNames,
            instance)
  DOWN_TESTS = qa_config.Either([
    "instance-reinstall",
    "instance-rename",
    "instance-grow-disk",
    ])

  # shutdown instance for any 'down' tests
  RunTestIf(DOWN_TESTS, qa_instance.TestInstanceShutdown, instance)

  # now run the 'down' state tests
  RunTestIf("instance-reinstall", qa_instance.TestInstanceReinstall, instance)
  RunTestIf(["instance-reinstall", qa_rapi.Enabled],
            qa_rapi.TestRapiInstanceReinstall, instance)

  if qa_config.TestEnabled("instance-rename"):
    tgt_instance = qa_config.AcquireInstance()
    try:
      rename_source = instance.name
      rename_target = tgt_instance.name
      # perform instance rename to the same name
      RunTest(qa_instance.TestInstanceRenameAndBack,
              rename_source, rename_source)
      RunTestIf(qa_rapi.Enabled, qa_rapi.TestRapiInstanceRenameAndBack,
                rename_source, rename_source)
      if rename_target is not None:
        # perform instance rename to a different name, if we have one configured
        RunTest(qa_instance.TestInstanceRenameAndBack,
                rename_source, rename_target)
        RunTestIf(qa_rapi.Enabled, qa_rapi.TestRapiInstanceRenameAndBack,
                  rename_source, rename_target)
    finally:
      tgt_instance.Release()

  RunTestIf(["instance-grow-disk"], qa_instance.TestInstanceGrowDisk, instance)

  # and now start the instance again
  RunTestIf(DOWN_TESTS, qa_instance.TestInstanceStartup, instance)

  RunTestIf("instance-reboot", qa_instance.TestInstanceReboot, instance)

  RunTestIf("tags", qa_tags.TestInstanceTags, instance)

  if instance.disk_template == constants.DT_DRBD8:
    RunTestIf("cluster-verify",
              qa_cluster.TestClusterVerifyDisksBrokenDRBD, instance, inst_nodes)
  RunTestIf("cluster-verify", qa_cluster.TestClusterVerify)

  RunTestIf(qa_rapi.Enabled, qa_rapi.TestInstance, instance)

  # Lists instances, too
  RunTestIf("node-list", qa_node.TestNodeList)

  # Some jobs have been run, let's test listing them
  RunTestIf("job-list", qa_job.TestJobList)

def RunCommonNodeTests():
  """Run a few common node tests.

  """
  RunTestIf("node-volumes", qa_node.TestNodeVolumes)
  RunTestIf("node-storage", qa_node.TestNodeStorage)
  RunTestIf(["node-oob", qa_config.NoVirtualCluster], qa_node.TestOutOfBand)

def RunGroupListTests():
  """Run tests for listing node groups.

  """
  RunTestIf("group-list", qa_group.TestGroupList)
  RunTestIf("group-list", qa_group.TestGroupListFields)

def RunNetworkTests():
  """Run tests for network management.

  """
  RunTestIf("network", qa_network.TestNetworkAddRemove)
  RunTestIf("network", qa_network.TestNetworkConnect)
  RunTestIf(["network", "tags"], qa_network.TestNetworkTags)

def RunGroupRwTests():
  """Run tests for adding/removing/renaming groups.

  """
  RunTestIf("group-rwops", qa_group.TestGroupAddRemoveRename)
  RunTestIf("group-rwops", qa_group.TestGroupAddWithOptions)
  RunTestIf("group-rwops", qa_group.TestGroupModify)
  RunTestIf(["group-rwops", qa_rapi.Enabled], qa_rapi.TestRapiNodeGroups)
  RunTestIf(["group-rwops", "tags"], qa_tags.TestGroupTags,
            qa_group.GetDefaultGroup())

def RunExportImportTests(instance, inodes):
  """Tries to export and import the instance.

  @type inodes: list of nodes
  @param inodes: current nodes of the instance

  """
  # FIXME: export explicitly bails out on file based storage. other non-lvm
  # based storage types are untested, though. Also note that import could still
  # work, but is deeply embedded into the "export" case.
  if (qa_config.TestEnabled("instance-export") and
      instance.disk_template not in [constants.DT_FILE,
                                     constants.DT_SHARED_FILE]):
    RunTest(qa_instance.TestInstanceExportNoTarget, instance)

    pnode = inodes[0]
    expnode = qa_config.AcquireNode(exclude=pnode)
    try:
      name = RunTest(qa_instance.TestInstanceExport, instance, expnode)

      RunTest(qa_instance.TestBackupList, expnode)

      if qa_config.TestEnabled("instance-import"):
        newinst = qa_config.AcquireInstance()
        try:
          RunTest(qa_instance.TestInstanceImport, newinst, pnode,
                  expnode, name)
          # Check if starting the instance works
          RunTest(qa_instance.TestInstanceStartup, newinst)
          RunTest(qa_instance.TestInstanceRemove, newinst)
        finally:
          newinst.Release()
    finally:
      expnode.Release()

  # FIXME: inter-cluster-instance-move crashes on file based instances :/
  # See Issue 414.
  if (qa_config.TestEnabled([qa_rapi.Enabled, "inter-cluster-instance-move"])
      and (instance.disk_template not in
           [constants.DT_FILE, constants.DT_SHARED_FILE])):
    newinst = qa_config.AcquireInstance()
    try:
      tnode = qa_config.AcquireNode(exclude=inodes)
      try:
        RunTest(qa_rapi.TestInterClusterInstanceMove, instance, newinst,
                inodes, tnode)
      finally:
        tnode.Release()
    finally:
      newinst.Release()

def RunDaemonTests(instance):
  """Test the ganeti-watcher script.

  """
  RunTest(qa_daemon.TestPauseWatcher)

  RunTestIf("instance-automatic-restart",
            qa_daemon.TestInstanceAutomaticRestart, instance)
  RunTestIf("instance-consecutive-failures",
            qa_daemon.TestInstanceConsecutiveFailures, instance)

  RunTest(qa_daemon.TestResumeWatcher)

def RunHardwareFailureTests(instance, inodes):
  """Test cluster internal hardware failure recovery.

  """
  RunTestIf("instance-failover", qa_instance.TestInstanceFailover, instance)
  RunTestIf(["instance-failover", qa_rapi.Enabled],
            qa_rapi.TestRapiInstanceFailover, instance)

  RunTestIf("instance-migrate", qa_instance.TestInstanceMigrate, instance)
  RunTestIf(["instance-migrate", qa_rapi.Enabled],
            qa_rapi.TestRapiInstanceMigrate, instance)

  if qa_config.TestEnabled("instance-replace-disks"):
    # We just need alternative secondary nodes, hence "- 1"
    othernodes = qa_config.AcquireManyNodes(len(inodes) - 1, exclude=inodes)
    try:
      RunTestIf(qa_rapi.Enabled, qa_rapi.TestRapiInstanceReplaceDisks, instance)
      RunTest(qa_instance.TestReplaceDisks,
              instance, inodes, othernodes)
    finally:
      qa_config.ReleaseManyNodes(othernodes)
    del othernodes

  if qa_config.TestEnabled("instance-recreate-disks"):
    try:
      acquirednodes = qa_config.AcquireManyNodes(len(inodes), exclude=inodes)
      othernodes = acquirednodes
    except qa_error.OutOfNodesError:
      if len(inodes) > 1:
        # If the cluster is not big enough, let's reuse some of the nodes, but
        # with different roles. In this way, we can test a DRBD instance even on
        # a 3-node cluster.
        acquirednodes = [qa_config.AcquireNode(exclude=inodes)]
        othernodes = acquirednodes + inodes[:-1]
      else:
        raise
    try:
      RunTest(qa_instance.TestRecreateDisks,
              instance, inodes, othernodes)
    finally:
      qa_config.ReleaseManyNodes(acquirednodes)

  if len(inodes) >= 2:
    RunTestIf("node-evacuate", qa_node.TestNodeEvacuate, inodes[0], inodes[1])
    RunTestIf("node-failover", qa_node.TestNodeFailover, inodes[0], inodes[1])
    RunTestIf("node-migrate", qa_node.TestNodeMigrate, inodes[0], inodes[1])

def RunExclusiveStorageTests():
  """Test exclusive storage."""
  if not qa_config.TestEnabled("cluster-exclusive-storage"):
    return

  node = qa_config.AcquireNode()
  try:
    old_es = qa_cluster.TestSetExclStorCluster(False)
    qa_node.TestExclStorSingleNode(node)

    qa_cluster.TestSetExclStorCluster(True)
    qa_cluster.TestExclStorSharedPv(node)

    if qa_config.TestEnabled("instance-add-plain-disk"):
      # Make sure that the cluster doesn't have any pre-existing problem
      qa_cluster.AssertClusterVerify()

      # Create and allocate instances
      instance1 = qa_instance.TestInstanceAddWithPlainDisk([node])
      try:
        instance2 = qa_instance.TestInstanceAddWithPlainDisk([node])
        try:
          # cluster-verify checks that disks are allocated correctly
          qa_cluster.AssertClusterVerify()

          # Remove instances
          qa_instance.TestInstanceRemove(instance2)
          qa_instance.TestInstanceRemove(instance1)
        finally:
          instance2.Release()
      finally:
        instance1.Release()

    if qa_config.TestEnabled("instance-add-drbd-disk"):
      snode = qa_config.AcquireNode()
      try:
        qa_cluster.TestSetExclStorCluster(False)
        instance = qa_instance.TestInstanceAddWithDrbdDisk([node, snode])
        try:
          qa_cluster.TestSetExclStorCluster(True)
          exp_err = [constants.CV_EINSTANCEUNSUITABLENODE]
          qa_cluster.AssertClusterVerify(fail=True, errors=exp_err)
          qa_instance.TestInstanceRemove(instance)
        finally:
          instance.Release()
      finally:
        snode.Release()
    qa_cluster.TestSetExclStorCluster(old_es)
  finally:
    node.Release()

def _BuildSpecDict(par, mn, st, mx):
  return {
    constants.ISPECS_MINMAX: [{
      constants.ISPECS_MIN: {par: mn},
      constants.ISPECS_MAX: {par: mx},
      }],
    constants.ISPECS_STD: {par: st},
    }

def _BuildDoubleSpecDict(index, par, mn, st, mx):
  new_spec = {
    constants.ISPECS_MINMAX: [{}, {}],
    }
  if st is not None:
    new_spec[constants.ISPECS_STD] = {par: st}
  new_spec[constants.ISPECS_MINMAX][index] = {
    constants.ISPECS_MIN: {par: mn},
    constants.ISPECS_MAX: {par: mx},
    }
  return new_spec

def TestIPolicyPlainInstance():
  """Test instance policy interaction with instances"""
  params = ["memory-size", "cpu-count", "disk-count", "disk-size", "nic-count"]
  if not qa_config.IsTemplateSupported(constants.DT_PLAIN):
    print "Template %s not supported" % constants.DT_PLAIN
    return

  # This test assumes that the group policy is empty
  (_, old_specs) = qa_cluster.TestClusterSetISpecs()
  # We also assume to have only one min/max bound
  assert len(old_specs[constants.ISPECS_MINMAX]) == 1
  node = qa_config.AcquireNode()
  try:
    # Log of policy changes, list of tuples:
    # (full_change, incremental_change, policy_violated)
    history = []
    instance = qa_instance.TestInstanceAddWithPlainDisk([node])
    try:
      policyerror = [constants.CV_EINSTANCEPOLICY]
      for par in params:
        (iminval, imaxval) = qa_instance.GetInstanceSpec(instance.name, par)
        # Some specs must be multiple of 4
        new_spec = _BuildSpecDict(par, imaxval + 4, imaxval + 4, imaxval + 4)
        history.append((None, new_spec, True))
        if iminval > 0:
          # Some specs must be multiple of 4
          if iminval >= 4:
            upper = iminval - 4
          else:
            upper = iminval - 1
          new_spec = _BuildSpecDict(par, 0, upper, upper)
          history.append((None, new_spec, True))
        history.append((old_specs, None, False))

      # Test with two instance specs
      double_specs = copy.deepcopy(old_specs)
      double_specs[constants.ISPECS_MINMAX] = \
          double_specs[constants.ISPECS_MINMAX] * 2
      (par1, par2) = params[0:2]
      (_, imaxval1) = qa_instance.GetInstanceSpec(instance.name, par1)
      (_, imaxval2) = qa_instance.GetInstanceSpec(instance.name, par2)
      old_minmax = old_specs[constants.ISPECS_MINMAX][0]
      history.extend([
        (double_specs, None, False),
        # The first min/max limit is being violated
        (None,
         _BuildDoubleSpecDict(0, par1, imaxval1 + 4, imaxval1 + 4,
                              imaxval1 + 4),
         False),
        # Both min/max limits are being violated
        (None,
         _BuildDoubleSpecDict(1, par2, imaxval2 + 4, None, imaxval2 + 4),
         True),
        # The second min/max limit is being violated
        (None,
         _BuildDoubleSpecDict(0, par1,
                              old_minmax[constants.ISPECS_MIN][par1],
                              old_specs[constants.ISPECS_STD][par1],
                              old_minmax[constants.ISPECS_MAX][par1]),
         False),
        (old_specs, None, False),
        ])

      # Apply the changes, and check policy violations after each change
      qa_cluster.AssertClusterVerify()
      for (new_specs, diff_specs, failed) in history:
        qa_cluster.TestClusterSetISpecs(new_specs=new_specs,
                                        diff_specs=diff_specs)
        if failed:
          qa_cluster.AssertClusterVerify(warnings=policyerror)
        else:
          qa_cluster.AssertClusterVerify()

      qa_instance.TestInstanceRemove(instance)
    finally:
      instance.Release()

    # Now we replay the same policy changes, and we expect that the instance
    # cannot be created for the cases where we had a policy violation above
    for (new_specs, diff_specs, failed) in history:
      qa_cluster.TestClusterSetISpecs(new_specs=new_specs,
                                      diff_specs=diff_specs)
      if failed:
        qa_instance.TestInstanceAddWithPlainDisk([node], fail=True)
      # Instance creation with no policy violation has been tested already
  finally:
    node.Release()

def IsExclusiveStorageInstanceTestEnabled():
  test_name = "exclusive-storage-instance-tests"
  if qa_config.TestEnabled(test_name):
    vgname = qa_config.get("vg-name", constants.DEFAULT_VG)
    vgscmd = utils.ShellQuoteArgs([
      "vgs", "--noheadings", "-o", "pv_count", vgname,
      ])
    nodes = qa_config.GetConfig()["nodes"]
    for node in nodes:
      try:
        pvnum = int(qa_utils.GetCommandOutput(node.primary, vgscmd))
      except Exception, e:
        msg = ("Cannot get the number of PVs on %s, needed by '%s': %s" %
               (node.primary, test_name, e))
        raise qa_error.Error(msg)
      if pvnum < 2:
        raise qa_error.Error("Node %s has not enough PVs (%s) to run '%s'" %
                             (node.primary, pvnum, test_name))
    res = True
  else:
    res = False
  return res

def RunInstanceTests():
  """Create and exercise instances."""
  instance_tests = [
    ("instance-add-plain-disk", constants.DT_PLAIN,
     qa_instance.TestInstanceAddWithPlainDisk, 1),
    ("instance-add-drbd-disk", constants.DT_DRBD8,
     qa_instance.TestInstanceAddWithDrbdDisk, 2),
    ("instance-add-diskless", constants.DT_DISKLESS,
     qa_instance.TestInstanceAddDiskless, 1),
    ("instance-add-file", constants.DT_FILE,
     qa_instance.TestInstanceAddFile, 1),
    ("instance-add-shared-file", constants.DT_SHARED_FILE,
     qa_instance.TestInstanceAddSharedFile, 1),
    ]

  for (test_name, templ, create_fun, num_nodes) in instance_tests:
    if (qa_config.TestEnabled(test_name) and
        qa_config.IsTemplateSupported(templ)):
      inodes = qa_config.AcquireManyNodes(num_nodes)
      try:
        instance = RunTest(create_fun, inodes)
        try:
          RunTestIf("cluster-epo", qa_cluster.TestClusterEpo)
          RunDaemonTests(instance)
          for node in inodes:
            RunTestIf("haskell-confd", qa_node.TestNodeListDrbd, node,
                      templ == constants.DT_DRBD8)
          if len(inodes) > 1:
            RunTestIf("group-rwops", qa_group.TestAssignNodesIncludingSplit,
                      constants.INITIAL_NODE_GROUP_NAME,
                      inodes[0].primary, inodes[1].primary)
          if qa_config.TestEnabled("instance-convert-disk"):
            RunTest(qa_instance.TestInstanceShutdown, instance)
            RunTest(qa_instance.TestInstanceConvertDiskToPlain,
                    instance, inodes)
            RunTest(qa_instance.TestInstanceStartup, instance)
          RunTestIf("instance-modify-disks",
                    qa_instance.TestInstanceModifyDisks, instance)
          RunCommonInstanceTests(instance, inodes)
          if qa_config.TestEnabled("instance-modify-primary"):
            othernode = qa_config.AcquireNode()
            RunTest(qa_instance.TestInstanceModifyPrimaryAndBack,
                    instance, inodes[0], othernode)
            othernode.Release()
          RunGroupListTests()
          RunExportImportTests(instance, inodes)
          RunHardwareFailureTests(instance, inodes)
          RunRepairDiskSizes()
          RunTest(qa_instance.TestInstanceRemove, instance)
        finally:
          instance.Release()
        del instance
      finally:
        qa_config.ReleaseManyNodes(inodes)
      qa_cluster.AssertClusterVerify()
    else:
      test_desc = "Creating instances of template %s" % templ
      if not qa_config.TestEnabled(test_name):
        ReportTestSkip(test_desc, test_name)
      else:
        ReportTestSkip(test_desc, "disk template %s" % templ)

def RunMonitoringTests():
  if qa_config.TestEnabled("mon-collector"):
    RunTest(qa_monitoring.TestInstStatusCollector)

def RunPerformanceTests():
  if not qa_config.TestEnabled("performance"):
    ReportTestSkip("performance related tests", "performance")
    return

  if qa_config.TestEnabled("jobqueue-performance"):
    RunTest(qa_performance.TestParallelMaxInstanceCreationPerformance)
    RunTest(qa_performance.TestParallelNodeCountInstanceCreationPerformance)

    instances = qa_performance.CreateAllInstances()

    RunTest(qa_performance.TestParallelModify, instances)
    RunTest(qa_performance.TestParallelInstanceOSOperations, instances)
    RunTest(qa_performance.TestParallelInstanceQueries, instances)

    qa_performance.RemoveAllInstances(instances)

    RunTest(qa_performance.TestJobQueueSubmissionPerformance)

  if qa_config.TestEnabled("parallel-performance"):
    if qa_config.IsTemplateSupported(constants.DT_DRBD8):
      RunTest(qa_performance.TestParallelDRBDInstanceCreationPerformance)
    if qa_config.IsTemplateSupported(constants.DT_PLAIN):
      RunTest(qa_performance.TestParallelPlainInstanceCreationPerformance)

    if qa_config.IsTemplateSupported(constants.DT_DRBD8):
      inodes = qa_config.AcquireManyNodes(2)
      try:
        instance = qa_instance.TestInstanceAddWithDrbdDisk(inodes)
        try:
          RunTest(qa_performance.TestParallelInstanceFailover, instance)
          RunTest(qa_performance.TestParallelInstanceMigration, instance)
          RunTest(qa_performance.TestParallelInstanceReplaceDisks, instance)
          RunTest(qa_performance.TestParallelInstanceReboot, instance)
          RunTest(qa_performance.TestParallelInstanceReinstall, instance)
          RunTest(qa_performance.TestParallelInstanceRename, instance)
        finally:
          qa_instance.TestInstanceRemove(instance)
          instance.Release()
      finally:
        qa_config.ReleaseManyNodes(inodes)

def RunQa():
  """Main QA body.

  """
  rapi_user = "ganeti-qa"

  RunEnvTests()
  rapi_secret = SetupCluster(rapi_user)

  if qa_rapi.Enabled():
    # Load RAPI certificate
    qa_rapi.Setup(rapi_user, rapi_secret)

  RunClusterTests()
  RunOsTests()

  RunTestIf("tags", qa_tags.TestClusterTags)

  RunCommonNodeTests()
  RunGroupListTests()
  RunGroupRwTests()
  RunNetworkTests()

  # The master shouldn't be readded or put offline; "delay" needs a non-master
  # node to test
  pnode = qa_config.AcquireNode(exclude=qa_config.GetMasterNode())
  try:
    RunTestIf("node-readd", qa_node.TestNodeReadd, pnode)
    RunTestIf("node-modify", qa_node.TestNodeModify, pnode)
    RunTestIf("delay", qa_cluster.TestDelay, pnode)
  finally:
    pnode.Release()

  # Make sure the cluster is clean before running instance tests
  qa_cluster.AssertClusterVerify()

  pnode = qa_config.AcquireNode()
  try:
    RunTestIf("tags", qa_tags.TestNodeTags, pnode)

    if qa_rapi.Enabled():
      RunTest(qa_rapi.TestNode, pnode)

      if (qa_config.TestEnabled("instance-add-plain-disk")
          and qa_config.IsTemplateSupported(constants.DT_PLAIN)):
        # Normal instance allocation via RAPI
        for use_client in [True, False]:
          rapi_instance = RunTest(qa_rapi.TestRapiInstanceAdd, pnode,
                                  use_client)
          try:
            if qa_config.TestEnabled("instance-plain-rapi-common-tests"):
              RunCommonInstanceTests(rapi_instance, [pnode])
            RunTest(qa_rapi.TestRapiInstanceRemove, rapi_instance, use_client)
          finally:
            rapi_instance.Release()
          del rapi_instance

        # Multi-instance allocation
        rapi_instance_one, rapi_instance_two = \
          RunTest(qa_rapi.TestRapiInstanceMultiAlloc, pnode)

        try:
          RunTest(qa_rapi.TestRapiInstanceRemove, rapi_instance_one, True)
          RunTest(qa_rapi.TestRapiInstanceRemove, rapi_instance_two, True)
        finally:
          rapi_instance_one.Release()
          rapi_instance_two.Release()
  finally:
    pnode.Release()

  config_list = [
    ("default-instance-tests", lambda: None, lambda _: None),
    (IsExclusiveStorageInstanceTestEnabled,
     lambda: qa_cluster.TestSetExclStorCluster(True),
     qa_cluster.TestSetExclStorCluster),
  ]
  for (conf_name, setup_conf_f, restore_conf_f) in config_list:
    if qa_config.TestEnabled(conf_name):
      oldconf = setup_conf_f()
      RunInstanceTests()
      restore_conf_f(oldconf)

  pnode = qa_config.AcquireNode()
  try:
    if qa_config.TestEnabled(["instance-add-plain-disk", "instance-export"]):
      for shutdown in [False, True]:
        instance = RunTest(qa_instance.TestInstanceAddWithPlainDisk, [pnode])
        try:
          expnode = qa_config.AcquireNode(exclude=pnode)
          try:
            if shutdown:
              # Stop instance before exporting and removing it
              RunTest(qa_instance.TestInstanceShutdown, instance)
            RunTest(qa_instance.TestInstanceExportWithRemove, instance, expnode)
            RunTest(qa_instance.TestBackupList, expnode)
          finally:
            expnode.Release()
        finally:
          instance.Release()
        del expnode
        del instance
      qa_cluster.AssertClusterVerify()

  finally:
    pnode.Release()

  RunExclusiveStorageTests()
  RunTestIf(["cluster-instance-policy", "instance-add-plain-disk"],
            TestIPolicyPlainInstance)

  RunTestIf(
    "instance-add-restricted-by-disktemplates",
    qa_instance.TestInstanceCreationRestrictedByDiskTemplates)

  # Test removing instance with offline drbd secondary
  if qa_config.TestEnabled(["instance-remove-drbd-offline",
                            "instance-add-drbd-disk"]):
    # Make sure the master is not put offline
    snode = qa_config.AcquireNode(exclude=qa_config.GetMasterNode())
    try:
      pnode = qa_config.AcquireNode(exclude=snode)
      try:
        instance = qa_instance.TestInstanceAddWithDrbdDisk([pnode, snode])
        set_offline = lambda node: qa_node.MakeNodeOffline(node, "yes")
        set_online = lambda node: qa_node.MakeNodeOffline(node, "no")
        RunTest(qa_instance.TestRemoveInstanceOfflineNode, instance, snode,
                set_offline, set_online)
      finally:
        pnode.Release()
    finally:
      snode.Release()
    qa_cluster.AssertClusterVerify()

  RunMonitoringTests()

  RunPerformanceTests()

  RunTestIf("create-cluster", qa_node.TestNodeRemoveAll)

  RunTestIf("cluster-destroy", qa_cluster.TestClusterDestroy)

@UsesRapiClient
def main():
  """Main program.

  """
  parser = optparse.OptionParser(usage="%prog [options] <config-file>")
  parser.add_option("--yes-do-it", dest="yes_do_it",
                    action="store_true",
                    help="Really execute the tests")
  (opts, args) = parser.parse_args()

  if len(args) == 1:
    (config_file, ) = args
  else:
    parser.error("Wrong number of arguments.")

  if not opts.yes_do_it:
    print ("Executing this script irreversibly destroys any Ganeti\n"
           "configuration on all nodes involved. If you really want\n"
           "to start testing, supply the --yes-do-it option.")
    sys.exit(1)

  qa_config.Load(config_file)

  primary = qa_config.GetMasterNode().primary
  qa_utils.StartMultiplexer(primary)
  print ("SSH command for primary node: %s" %
         utils.ShellQuoteArgs(qa_utils.GetSSHCommand(primary, "")))
  print ("SSH command for other nodes: %s" %
         utils.ShellQuoteArgs(qa_utils.GetSSHCommand("NODE", "")))
  try:
    RunQa()
  finally:
    qa_utils.CloseMultiplexers()

if __name__ == "__main__":
  main()


text:
package unidev.uniteam;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class MeetingDetails extends AppCompatActivity implements DatabaseGet.OnJsonTransmissionCompleted {

    private String currentMeetingID;
    private Map<String, String> hashMapMeeting = new HashMap<>(3);
    private Calendar meetingDate = Calendar.getInstance();

    protected void onResume() {
        super.onResume();
        // TODO Uncomment when using DB
        //RefreshMeetingDescription("taches/" + CurrentTaskID);
        //findViewById(R.id.parentTask).invalidate();

        TextView meetingSubject = (TextView) findViewById(R.id.meeting_subject);
        meetingSubject.setText("Grosse réunion");

        TextView meetingDescription = (TextView) findViewById(R.id.meeting_description);
        meetingDescription.setText("Faire fonctionner la base de données");

        TextView meetingPlace = (TextView) findViewById(R.id.meeting_place);
        meetingPlace.setText("Proxima");

        TextView meetingDateField = (TextView) findViewById(R.id.meeting_date);
        String myFormat = "EEE, d MMM yyyy HH:mm";
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);
        meetingDateField.setText(sdf.format(meetingDate.getTime()));
        }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meeting_details);

        if (savedInstanceState != null) {
            // TODO uncomment when using database
            //currentMeetingID = savedInstanceState.getString("currentMeetingID");
        } else {
            Intent intent = getIntent();
            // TODO uncomment when using database
            //currentMeetingID = getIntent().getStringExtra("currentMeetingID");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState.getString("currentProjectID") != null) {
            savedInstanceState.remove("currentProjectID");
        }
        savedInstanceState.putString("currentProjectID", currentMeetingID);
    }

    public void RefreshMeetingDescription(String url) {
        DatabaseGet gj = new DatabaseGet(this);
        gj.execute(url);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_validate, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.validate:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void onTransmissionCompleted(DatabaseGetResult result) {

        JSONArray jsonArray = result.getData();

        try {
            String myFormat = "EEE, d MMM yyyy HH:mm";
            SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);

            // Pour tous les objets on récupère les infos
            for (int i = 0; i < jsonArray.length(); i++) {
                // On récupère un objet JSON du tableau
                JSONObject obj = new JSONObject(jsonArray.getString(i));
                // On fait le lien Projet - Objet JSON
                hashMapMeeting.put("subject", obj.getString("nom"));
                hashMapMeeting.put("description", obj.getString("description"));
                hashMapMeeting.put("date", obj.getString("date"));

                /*
                String dateStr = obj.getString("deadlineField");
                String ackwardRipOff = dateStr.replace("/Date(", "").replace(")/", "");
                Long timeInMillis = Long.valueOf(ackwardRipOff);
                */
            }

            TextView meetingSubject = (TextView) findViewById(R.id.meeting_subject);
            meetingSubject.setText(hashMapMeeting.get("subject"));

            TextView meetingDescription = (TextView) findViewById(R.id.meeting_description);
            meetingDescription.setText(hashMapMeeting.get("description"));

            TextView meetingDate = (TextView) findViewById(R.id.meeting_date);
            meetingDate.setText(hashMapMeeting.get("date"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

      <?php echo  anchor('home', '','class="ui medium image"');?>

        Welcome to Cite Circle Beta

Where you can meet and greet others, chat and make friends.

        Have you explored this site? Please lend this survey a 5 minutes of your time.

      <?php echo anchor('survey','
Take the survey
'); ?>


text:
package org.apache.shardingsphere.shardingjdbc.jdbc.unsupported;

import org.apache.shardingsphere.shardingjdbc.jdbc.adapter.WrapperAdapter;

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.NClob;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * Unsupported {@code Connection} methods.
 */
public abstract class AbstractUnsupportedOperationConnection extends WrapperAdapter implements Connection {

    @Override
    public final CallableStatement prepareCall(final String sql) throws SQLException {
        throw new SQLFeatureNotSupportedException("prepareCall");
    }

    @Override
    public final CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency) throws SQLException {
        throw new SQLFeatureNotSupportedException("prepareCall");
    }

    @Override
    public final CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException {
        throw new SQLFeatureNotSupportedException("prepareCall");
    }

    @Override
    public final String nativeSQL(final String sql) throws SQLException {
        throw new SQLFeatureNotSupportedException("nativeSQL");
    }

    @Override
    public final Savepoint setSavepoint() throws SQLException {
        throw new SQLFeatureNotSupportedException("setSavepoint");
    }

    @Override
    public final Savepoint setSavepoint(final String name) throws SQLException {
        throw new SQLFeatureNotSupportedException("setSavepoint name");
    }

    @Override
    public final void releaseSavepoint(final Savepoint savepoint) throws SQLException {
        throw new SQLFeatureNotSupportedException("releaseSavepoint");
    }

    @Override
    public final void rollback(final Savepoint savepoint) throws SQLException {
        throw new SQLFeatureNotSupportedException("rollback savepoint");
    }

    @Override
    public final void abort(final Executor executor) throws SQLException {
        throw new SQLFeatureNotSupportedException("abort");
    }

    @Override
    public final String getCatalog() {
        return null;
    }

    @Override
    public final void setCatalog(final String catalog) {
    }

    @Override
    public final String getSchema() {
        return null;
    }

    @Override
    public final void setSchema(final String schema) {
    }

    @Override
    public final Map<String, Class<?>> getTypeMap() throws SQLException {
        throw new SQLFeatureNotSupportedException("getTypeMap");
    }

    @Override
    public final void setTypeMap(final Map<String, Class<?>> map) throws SQLException {
        throw new SQLFeatureNotSupportedException("setTypeMap");
    }

    @Override
    public final int getNetworkTimeout() throws SQLException {
        throw new SQLFeatureNotSupportedException("getNetworkTimeout");
    }

    @Override
    public final void setNetworkTimeout(final Executor executor, final int milliseconds) throws SQLException {
        throw new SQLFeatureNotSupportedException("setNetworkTimeout");
    }

    @Override
    public final Clob createClob() throws SQLException {
        throw new SQLFeatureNotSupportedException("createClob");
    }

    @Override
    public final Blob createBlob() throws SQLException {
        throw new SQLFeatureNotSupportedException("createBlob");
    }

    @Override
    public final NClob createNClob() throws SQLException {
        throw new SQLFeatureNotSupportedException("createNClob");
    }

    @Override
    public final SQLXML createSQLXML() throws SQLException {
        throw new SQLFeatureNotSupportedException("createSQLXML");
    }

    @Override
    public final Array createArrayOf(final String typeName, final Object[] elements) throws SQLException {
        throw new SQLFeatureNotSupportedException("createArrayOf");
    }

    @Override
    public final Struct createStruct(final String typeName, final Object[] attributes) throws SQLException {
        throw new SQLFeatureNotSupportedException("createStruct");
    }

    @Override
    public final boolean isValid(final int timeout) throws SQLException {
        throw new SQLFeatureNotSupportedException("isValid");
    }

    @Override
    public final Properties getClientInfo() throws SQLException {
        throw new SQLFeatureNotSupportedException("getClientInfo");
    }

    @Override
    public final String getClientInfo(final String name) throws SQLException {
        throw new SQLFeatureNotSupportedException("getClientInfo name");
    }

    @Override
    public final void setClientInfo(final String name, final String value) {
        throw new UnsupportedOperationException("setClientInfo name value");
    }

    @Override
    public final void setClientInfo(final Properties properties) {
        throw new UnsupportedOperationException("setClientInfo properties");
    }
}


text:
package com.cloud.api.doc;

public class Alert {
    private String type;
    private int value;

    public Alert(String type, int value) {
        this.type = type;
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public int getValue() {
        return value;
    }

}


text:
namespace _04.SoftUniBeerPong
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class Program
    {
        public static void Main()
        {
            var teamsData = new Dictionary<string, Dictionary<string, double>>();

            string inputLine = Console.ReadLine();

            while (inputLine != "stop the game")
            {
                string[] tokens = inputLine.Split('|');
                string player = tokens[0];
                string team = tokens[1];
                double playerPoints = double.Parse(tokens[2]);

                if (!teamsData.ContainsKey(team))
                {
                    teamsData.Add(team, new Dictionary<string, double>());
                }

                if (teamsData[team].Count < 3)
                {
                    if (!teamsData[team].ContainsKey(player))
                    {
                        teamsData[team].Add(player, playerPoints);
                    }
                }

                inputLine = Console.ReadLine();
            }

            int ranking = 1;

            foreach (var team in teamsData.OrderByDescending(x => x.Value.Values.Sum()))
            {
                if (team.Value.Count == 3)
                {
                    Console.WriteLine($"{ranking}. {team.Key}; Players:");
                    foreach (var player in team.Value.OrderByDescending(x => x.Value))
                    {
                        Console.WriteLine($"###{player.Key}: {player.Value}");
                    }
                    ranking++;
                }

            }
        }
    }
}


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Resources;

namespace Azure.ResourceManager.Resources.Models
{
    /// <summary> List of policy set definitions. </summary>
    internal partial class PolicySetDefinitionListResult
    {
        /// <summary> Initializes a new instance of PolicySetDefinitionListResult. </summary>
        internal PolicySetDefinitionListResult()
        {
            Value = new ChangeTrackingList<PolicySetDefinitionData>();
        }

        /// <summary> Initializes a new instance of PolicySetDefinitionListResult. </summary>
        /// <param name="value"> An array of policy set definitions. </param>
        /// <param name="nextLink"> The URL to use for getting the next set of results. </param>
        internal PolicySetDefinitionListResult(IReadOnlyList<PolicySetDefinitionData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> An array of policy set definitions. </summary>
        public IReadOnlyList<PolicySetDefinitionData> Value { get; }
        /// <summary> The URL to use for getting the next set of results. </summary>
        public string NextLink { get; }
    }
}


text:
This eZ Publish legacy extensions provides scripts and modules to help clean up your installation
code- and databasewise.

The work on this extension has just started, so please come back later or watch this repository to
stay in touch.


text:
<?php
/**
 * Contains \jamesiarmes\PhpEws\Type\RoomType.
 */

namespace jamesiarmes\PhpEws\Type;

use \jamesiarmes\PhpEws\Type;

/**
 * Represents a meeting room.
 *
 * @package php-ews\Type
 */
class RoomType extends DirectoryEntryType
{

}


text:
module ActiveHashRelation::ScopeFilters
  def filter_scopes(resource, params, model = nil)
    unless model
      model = model_class_name(resource)
      if model.nil? || engine_name == model.to_s
        model = model_class_name(resource, true)
      end
    end

    model.scope_names.each do |scope|
      if params.include?(scope)
        if params[scope].is_a? Array
          resource = resource.send(scope, *params[scope])
        else
          resource = resource.send(scope)
        end
      end
    end

    return resource
  end
end


text:
<?php

namespace Admin\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Hojadevida
 *
 * @ORM\Table(name="hojadevida")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity
 */
class Hojadevida {

    /**
     * @var integer
     *
     * @ORM\Column(name="idHv", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idhv;

    /**
     * @var string
     *
     * @ORM\Column(name="Nombre", type="string", length=30, nullable=false)
     */
    private $nombre;

    /**
     * @var string
     *
     * @ORM\Column(name="Apellido", type="string", length=30, nullable=false)
     */
    private $apellido;

    /**
     * @var string
     *
     * @ORM\Column(name="Tel_Casa", type="string", length=30, nullable=true)
     */
    private $telCasa;

    /**
     * @var string
     *
     * @ORM\Column(name="Tel_Ce", type="string", length=30, nullable=false)
     */
    private $telCe;

    /**
     * @var string
     *
     * @ORM\Column(name="Telefono_Adic", type="string", length=30, nullable=true)
     */
    private $telefonoAdic;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="Fecha_Nac", type="date", nullable=false)
     */
    private $fechaNac;

    /**
     * @var string
     *
     * @ORM\Column(name="Tipo_Documento", type="string", length=2, nullable=false)
     */
    private $tipoDocumento;

    /**
     * @var string
     *
     * @ORM\Column(name="Nit", type="string", length=15, nullable=false)
     */
    private $nit;

    /**
     * @var string
     *
     * @ORM\Column(name="Sexo", type="string", length=30, nullable=false)
     */
    private $sexo;

    /**
     * @var string
     *
     * @ORM\Column(name="Lugar_Nacimiento", type="string", length=40, nullable=true)
     */
    private $lugarNacimiento;

    /**
     * @var string
     *
     * @ORM\Column(name="Ciudad", type="string", length=25, nullable=true)
     */
    private $ciudad;

    /**
     * @var string
     *
     * @ORM\Column(name="Dir_Casa", type="string", length=40, nullable=true)
     */
    private $dirCasa;

    /**
     * @var string
     *
     * @ORM\Column(name="Email_Personal", type="string", length=40, nullable=false)
     */
    private $emailPersonal;

    /**
     * @var string
     *
     * @ORM\Column(name="Estatura", type="string", length=20, nullable=true)
     */
    private $estatura;

    /**
     * @var string
     *
     * @ORM\Column(name="Piel", type="string", length=30, nullable=true)
     */
    private $piel;

    /**
     * @var string
     *
     * @ORM\Column(name="Ojos", type="string", length=30, nullable=true)
     */
    private $ojos;

    /**
     * @var string
     *
     * @ORM\Column(name="Pelo", type="string", length=30, nullable=true)
     */
    private $pelo;

    /**
     * @var string
     *
     * @ORM\Column(name="Peso", type="string", length=30, nullable=true)
     */
    private $peso;

    /**
     * @var string
     *
     * @ORM\Column(name="Experiencia_TV", type="text", nullable=true)
     */
    private $experienciaTv;

    /**
     * @var string
     *
     * @ORM\Column(name="Deportes", type="string", length=80, nullable=true)
     */
    private $deportes;

    /**
     * @var string
     *
     * @ORM\Column(name="Habilidades", type="string", length=80, nullable=true)
     */
    private $habilidades;

    /**
     * @var string
     *
     * @ORM\Column(name="Idiomas", type="string", length=80, nullable=true)
     */
    private $idiomas;

    /**
     * @var string
     *
     * @ORM\Column(name="Maneja", type="string", length=80, nullable=true)
     */
    private $maneja;

    /**
     * @var string
     *
     * @ORM\Column(name="Entidad_Salud", type="string", length=80, nullable=true)
     */
    private $entidadSalud;

    /**
     * @var string
     *
     * @ORM\Column(name="Categoria", type="string", length=30, nullable=true)
     */
    private $categoria;

    /**
     * @var string
     *
     * @ORM\Column(name="Talla_Camisa", type="string", length=30, nullable=true)
     */
    private $tallaCamisa;

    /**
     * @var string
     *
     * @ORM\Column(name="Talla_Chaqueta", type="string", length=30, nullable=true)
     */
    private $tallaChaqueta;

    /**
     * @var string
     *
     * @ORM\Column(name="Talla_Pantalon", type="string", length=30, nullable=true)
     */
    private $tallaPantalon;

    /**
     * @var string
     *
     * @ORM\Column(name="Talla_Zapato", type="string", length=30, nullable=true)
     */
    private $tallaZapato;

    /**
     * @var string
     *
     * @ORM\Column(name="DV", type="string", length=2, nullable=true)
     */
    private $dv;

    /**
     * @var string
     *
     * @ORM\Column(name="Estado", type="string", length=10, nullable=true)
     */
    private $Estado;

    /**
     * @var string
     *
     * @ORM\Column(name="Tags", type="string", length=255, nullable=true)
     */
    private $Tags;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="Fecha", type="datetime", nullable=false)
     */
    private $fecha;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="FechaUpdate", type="datetime", nullable=true)
     */
    private $fechaupdate;

    /**
     * @var string $image
     * @Assert\File( maxSize = "1024k",
     * mimeTypesMessage = "Carge una imagen valida")
     * @ORM\Column(name="image", type="string", length=255)
     */
    public $image;

    /**
     * @var string $image1
     * @Assert\File( maxSize = "1024k",
     * mimeTypesMessage = "Carge una imagen valida")
     * @ORM\Column(name="image1", type="string", length=255)
     */
    private $image1;

    /**
     * @var string $image2
     * @Assert\File( maxSize = "1024k",
     * mimeTypesMessage = "Carge una imagen valida")
     * @ORM\Column(name="image2", type="string", length=255)
     */
    private $image2;
    private $imagename;
    private $image1name;
    private $image2name;

    /**

      /**
     * Set image
     *
     * @param string $imagename
     * @return Hojadevida
     */
    public function setImageName($imagename) {
        $this->imagename = $imagename;

        return $this;
    }

    /**
     * Set image
     *
     * @param string $imagename
     * @return Hojadevida
     */
    public function setImage1Name($image1name) {
        $this->image1name = $image1name;

        return $this;
    }

    /**
     * Set image
     *
     * @param string $imagename
     * @return Hojadevida
     */
    public function setImage2Name($image2name) {
        $this->image2name = $image2name;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImageName() {
        return $this->imagename;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage1Name() {
        return $this->image1name;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage2Name() {
        return $this->image2name;
    }

////
    public function getFullImagePath() {
        return null === $this->image ? null : $this->getUploadRootDir() . $this->image;
        //retorna la imagen para mostrar en web
    }

    public function getFullImage1Path() {
        return null === $this->image1 ? null : $this->getUploadRootDir() . $this->image1;
        //retorna la imagen para mostrar en web
    }

    public function getFullImage2Path() {
        return null === $this->image2 ? null : $this->getUploadRootDir() . $this->image2;
        //retorna la imagen para mostrar en web
    }

    protected function getUploadRootDir() {
        //ruta del dicrectorio donde se van a guardar los archivos

        return $this->getTmpUploadRootDir()."/../" . $this->nit . "/";
    }

    protected function getTmpUploadRootDir() {
        //la ruta del directorio absoluta donde se deben guardar los documentos cargados
        return __DIR__ . '/../../../../web/upload/Hojasdevida/tmp/';
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function uploadImage() {
        //validamos si es una actualizacion o una nueva
        //si las fehcas son diferentes es actualizacion de lo contrario es nuevo
        if ($this->fechaupdate != $this->fecha) {
            if ($this->image != null) {
                ///asignamos los nombres nuevos
                $tempImageName = time() . '_1.' . pathinfo((string) $this->image->getClientOriginalName(), PATHINFO_EXTENSION);
                //borramos imagenes viejas
                $dir = $this->getUploadRootDir();
                if (is_file($dir . $this->aux)) {
                    unlink($dir . $this->aux);
                }
                /// guardamos en el servidor los archivos
                $this->setImageName($this->image->getClientOriginalName());
                $this->image->move($this->getUploadRootDir(), $tempImageName);

                //grabamos los nombres de archivo en el servidor
                $this->setImage($tempImageName);
            } else {
                $this->setImage($this->aux);
            }
            if ($this->image1 != null) {
                ///asignamos los nombres nuevos
                $tempImageName1 = time() . '_2.' . pathinfo((string) $this->image1->getClientOriginalName(), PATHINFO_EXTENSION);

                //borramos imagenes viejas
                $dir = $this->getUploadRootDir();
                if (is_file($dir . $this->aux1)) {
                    unlink($dir . $this->aux1);
                }
                /// guardamos en el servidor los archivos
                $this->setImage1Name($this->image1->getClientOriginalName());
                $this->image1->move($this->getUploadRootDir(), $tempImageName1);

                //grabamos los nombres de archivo en el servidor
                $this->setImage1($tempImageName1);
            } else {
                $this->setImage1($this->aux1);
            }
            if ($this->image2 != Null) {
                ///asignamos los nombres nuevos
                $tempImageName2 = time() . '_3.' . pathinfo((string) $this->image2->getClientOriginalName(), PATHINFO_EXTENSION);
                //borramos imagenes viejas
                $dir = $this->getUploadRootDir();
                if (is_file($dir . $this->aux2)) {
                    unlink($dir . $this->aux2);
                }
                /// guardamos en el servidor los archivos
                $this->setImage2Name($this->image2->getClientOriginalName());
                $this->image2->move($this->getUploadRootDir(), $tempImageName2);

                //grabamos los nombres de archivo en el servidor
                $this->setImage2($tempImageName2);
            } else {
                $this->setImage2($this->aux2);
            }
        } else {
            if ((null === $this->image)or ( null === $this->image1)or ( null === $this->image2)) {
                return;
            }

            $tempImageName = time() . '_1.' . pathinfo((string) $this->image->getClientOriginalName(), PATHINFO_EXTENSION);
            $tempImageName1 = time() . '_2.' . pathinfo((string) $this->image1->getClientOriginalName(), PATHINFO_EXTENSION);
            $tempImageName2 = time() . '_3.' . pathinfo((string) $this->image2->getClientOriginalName(), PATHINFO_EXTENSION);
            if (!$this->idhv) {
                $this->setImageName($this->image->getClientOriginalName());
                $this->setImage1Name($this->image1->getClientOriginalName());
                $this->setImage2Name($this->image2->getClientOriginalName());
                $this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
                $this->image1->move($this->getTmpUploadRootDir(), $this->image1->getClientOriginalName());
                $this->image2->move($this->getTmpUploadRootDir(), $this->image2->getClientOriginalName());
            } else {
                $this->image->move($this->getUploadRootDir(), $tempImageName);
                $this->image1->move($this->getUploadRootDir(), $tempImageName1);
                $this->image2->move($this->getUploadRootDir(), $tempImageName2);
                unlink($this->getUploadRootDir() . $tempImageName);
                unlink($this->getUploadRootDir() . $tempImageName1);
                unlink($this->getUploadRootDir() . $tempImageName2);
            }

            $this->setImage($tempImageName);
            $this->setImage1($tempImageName1);
            $this->setImage2($tempImageName2);
        }
    }

    /**
     * @ORM\PostPersist()
     */
    public function moveImage() {
        if ((null === $this->image)or ( null === $this->image1)or ( null === $this->image2)) {
            return;
        }
        if (!is_dir($this->getUploadRootDir())) {
            mkdir($this->getUploadRootDir(), 0777, true);
        }

        copy($this->getTmpUploadRootDir() . $this->getImageName(), $this->getFullImagePath());
        unlink($this->getTmpUploadRootDir() . $this->getImageName());
        copy($this->getTmpUploadRootDir() . $this->getImage1Name(), $this->getFullImage1Path());
        unlink($this->getTmpUploadRootDir() . $this->getImage1Name());
        copy($this->getTmpUploadRootDir() . $this->getImage2Name(), $this->getFullImage2Path());
        unlink($this->getTmpUploadRootDir() . $this->getImage2Name());
    }

    private $aux;
    private $aux1;
    private $aux2;

    /**
     * Set nombre
     *
     * @param string $nombre
     *
     * @return Hojadevida
     */
    public function setAux($aux) {
        $this->aux = $aux;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getAux() {
        return $this->aux;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     *
     * @return Hojadevida
     */
    public function setAux1($aux1) {
        $this->aux1 = $aux1;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getAux1() {
        return $this->aux1;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     *
     * @return Hojadevida
     */
    public function setAux2($aux2) {
        $this->aux2 = $aux2;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getAux2() {
        return $this->aux2;
    }

    /**
     *
     * @ORM\PreRemove()
     */
    public function removeImage() {
        unlink($this->getFullImagePath());
        unlink($this->getFullImage1Path());
        unlink($this->getFullImage2Path());
        rmdir($this->getUploadRootDir());
    }

////////

    /**
     * Get idhv
     *
     * @return integer
     */
    public function getIdhv() {
        return $this->idhv;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     *
     * @return Hojadevida
     */
    public function setNombre($nombre) {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre() {
        return $this->nombre;
    }

    /**
     * Set apellido
     *
     * @param string $apellido
     *
     * @return Hojadevida
     */
    public function setApellido($apellido) {
        $this->apellido = $apellido;

        return $this;
    }

    /**
     * Get apellido
     *
     * @return string
     */
    public function getApellido() {
        return $this->apellido;
    }

    /**
     * Set telCasa
     *
     * @param string $telCasa
     *
     * @return Hojadevida
     */
    public function setTelCasa($telCasa) {
        $this->telCasa = $telCasa;

        return $this;
    }

    /**
     * Get telCasa
     *
     * @return string
     */
    public function getTelCasa() {
        return $this->telCasa;
    }

    /**
     * Set telCe
     *
     * @param string $telCe
     *
     * @return Hojadevida
     */
    public function setTelCe($telCe) {
        $this->telCe = $telCe;

        return $this;
    }

    /**
     * Get telCe
     *
     * @return string
     */
    public function getTelCe() {
        return $this->telCe;
    }

    /**
     * Set telefonoAdic
     *
     * @param string $telefonoAdic
     *
     * @return Hojadevida
     */
    public function setTelefonoAdic($telefonoAdic) {
        $this->telefonoAdic = $telefonoAdic;

        return $this;
    }

    /**
     * Get telefonoAdic
     *
     * @return string
     */
    public function getTelefonoAdic() {
        return $this->telefonoAdic;
    }

    /**
     * Set fechaNac
     *
     * @param \DateTime $fechaNac
     *
     * @return Hojadevida
     */
    public function setFechaNac($fechaNac) {
        $this->fechaNac = $fechaNac;

        return $this;
    }

    /**
     * Get fechaNac
     *
     * @return \DateTime
     */
    public function getFechaNac() {
        return $this->fechaNac;
    }

    /**
     * Set tipoDocumento
     *
     * @param string $tipoDocumento
     *
     * @return Hojadevida
     */
    public function setTipoDocumento($tipoDocumento) {
        $this->tipoDocumento = $tipoDocumento;

        return $this;
    }

    /**
     * Get tipoDocumento
     *
     * @return string
     */
    public function getTipoDocumento() {
        return $this->tipoDocumento;
    }

    /**
     * Set nit
     *
     * @param string $nit
     *
     * @return Hojadevida
     */
    public function setNit($nit) {
        $this->nit = $nit;

        return $this;
    }

    /**
     * Get nit
     *
     * @return string
     */
    public function getNit() {
        return $this->nit;
    }

    /**
     * Set sexo
     *
     * @param string $sexo
     *
     * @return Hojadevida
     */
    public function setSexo($sexo) {
        $this->sexo = $sexo;

        return $this;
    }

    /**
     * Get sexo
     *
     * @return string
     */
    public function getSexo() {
        return $this->sexo;
    }

    /**
     * Set lugarNacimiento
     *
     * @param string $lugarNacimiento
     *
     * @return Hojadevida
     */
    public function setLugarNacimiento($lugarNacimiento) {
        $this->lugarNacimiento = $lugarNacimiento;

        return $this;
    }

    /**
     * Get lugarNacimiento
     *
     * @return string
     */
    public function getLugarNacimiento() {
        return $this->lugarNacimiento;
    }

    /**
     * Set ciudad
     *
     * @param string $ciudad
     *
     * @return Hojadevida
     */
    public function setCiudad($ciudad) {
        $this->ciudad = $ciudad;

        return $this;
    }

    /**
     * Get ciudad
     *
     * @return string
     */
    public function getCiudad() {
        return $this->ciudad;
    }

    /**
     * Set dirCasa
     *
     * @param string $dirCasa
     *
     * @return Hojadevida
     */
    public function setDirCasa($dirCasa) {
        $this->dirCasa = $dirCasa;

        return $this;
    }

    /**
     * Get dirCasa
     *
     * @return string
     */
    public function getDirCasa() {
        return $this->dirCasa;
    }

    /**
     * Set emailPersonal
     *
     * @param string $emailPersonal
     *
     * @return Hojadevida
     */
    public function setEmailPersonal($emailPersonal) {
        $this->emailPersonal = $emailPersonal;

        return $this;
    }

    /**
     * Get emailPersonal
     *
     * @return string
     */
    public function getEmailPersonal() {
        return $this->emailPersonal;
    }

    /**
     * Set estatura
     *
     * @param string $estatura
     *
     * @return Hojadevida
     */
    public function setEstatura($estatura) {
        $this->estatura = $estatura;

        return $this;
    }

    /**
     * Get estatura
     *
     * @return string
     */
    public function getEstatura() {
        return $this->estatura;
    }

    /**
     * Set piel
     *
     * @param string $piel
     *
     * @return Hojadevida
     */
    public function setPiel($piel) {
        $this->piel = $piel;

        return $this;
    }

    /**
     * Get piel
     *
     * @return string
     */
    public function getPiel() {
        return $this->piel;
    }

    /**
     * Set ojos
     *
     * @param string $ojos
     *
     * @return Hojadevida
     */
    public function setOjos($ojos) {
        $this->ojos = $ojos;

        return $this;
    }

    /**
     * Get ojos
     *
     * @return string
     */
    public function getOjos() {
        return $this->ojos;
    }

    /**
     * Set pelo
     *
     * @param string $pelo
     *
     * @return Hojadevida
     */
    public function setPelo($pelo) {
        $this->pelo = $pelo;

        return $this;
    }

    /**
     * Get pelo
     *
     * @return string
     */
    public function getPelo() {
        return $this->pelo;
    }

    /**
     * Set peso
     *
     * @param string $peso
     *
     * @return Hojadevida
     */
    public function setPeso($peso) {
        $this->peso = $peso;

        return $this;
    }

    /**
     * Get peso
     *
     * @return string
     */
    public function getPeso() {
        return $this->peso;
    }

    /**
     * Set experienciaTv
     *
     * @param string $experienciaTv
     *
     * @return Hojadevida
     */
    public function setExperienciaTv($experienciaTv) {
        $this->experienciaTv = $experienciaTv;

        return $this;
    }

    /**
     * Get experienciaTv
     *
     * @return string
     */
    public function getExperienciaTv() {
        return $this->experienciaTv;
    }

    /**
     * Set deportes
     *
     * @param string $deportes
     *
     * @return Hojadevida
     */
    public function setDeportes($deportes) {
        $this->deportes = $deportes;

        return $this;
    }

    /**
     * Get deportes
     *
     * @return string
     */
    public function getDeportes() {
        return $this->deportes;
    }

    /**
     * Set habilidades
     *
     * @param string $habilidades
     *
     * @return Hojadevida
     */
    public function setHabilidades($habilidades) {
        $this->habilidades = $habilidades;

        return $this;
    }

    /**
     * Get habilidades
     *
     * @return string
     */
    public function getHabilidades() {
        return $this->habilidades;
    }

    /**
     * Set idiomas
     *
     * @param string $idiomas
     *
     * @return Hojadevida
     */
    public function setIdiomas($idiomas) {
        $this->idiomas = $idiomas;

        return $this;
    }

    /**
     * Get idiomas
     *
     * @return string
     */
    public function getIdiomas() {
        return $this->idiomas;
    }

    /**
     * Set maneja
     *
     * @param string $maneja
     *
     * @return Hojadevida
     */
    public function setManeja($maneja) {
        $this->maneja = $maneja;

        return $this;
    }

    /**
     * Get maneja
     *
     * @return string
     */
    public function getManeja() {
        return $this->maneja;
    }

    /**
     * Set entidadSalud
     *
     * @param string $entidadSalud
     *
     * @return Hojadevida
     */
    public function setEntidadSalud($entidadSalud) {
        $this->entidadSalud = $entidadSalud;

        return $this;
    }

    /**
     * Get entidadSalud
     *
     * @return string
     */
    public function getEntidadSalud() {
        return $this->entidadSalud;
    }

    /**
     * Set categoria
     *
     * @param string $categoria
     *
     * @return Hojadevida
     */
    public function setCategoria($categoria) {
        $this->categoria = $categoria;

        return $this;
    }

    /**
     * Get categoria
     *
     * @return string
     */
    public function getCategoria() {
        return $this->categoria;
    }

    /**
     * Set tallaCamisa
     *
     * @param string $tallaCamisa
     *
     * @return Hojadevida
     */
    public function setTallaCamisa($tallaCamisa) {
        $this->tallaCamisa = $tallaCamisa;

        return $this;
    }

    /**
     * Get tallaCamisa
     *
     * @return string
     */
    public function getTallaCamisa() {
        return $this->tallaCamisa;
    }

    /**
     * Set tallaChaqueta
     *
     * @param string $tallaChaqueta
     *
     * @return Hojadevida
     */
    public function setTallaChaqueta($tallaChaqueta) {
        $this->tallaChaqueta = $tallaChaqueta;

        return $this;
    }

    /**
     * Get tallaChaqueta
     *
     * @return string
     */
    public function getTallaChaqueta() {
        return $this->tallaChaqueta;
    }

    /**
     * Set tallaPantalon
     *
     * @param string $tallaPantalon
     *
     * @return Hojadevida
     */
    public function setTallaPantalon($tallaPantalon) {
        $this->tallaPantalon = $tallaPantalon;

        return $this;
    }

    /**
     * Get tallaPantalon
     *
     * @return string
     */
    public function getTallaPantalon() {
        return $this->tallaPantalon;
    }

    /**
     * Set tallaZapato
     *
     * @param string $tallaZapato
     *
     * @return Hojadevida
     */
    public function setTallaZapato($tallaZapato) {
        $this->tallaZapato = $tallaZapato;

        return $this;
    }

    /**
     * Get tallaZapato
     *
     * @return string
     */
    public function getTallaZapato() {
        return $this->tallaZapato;
    }

    /**
     * Set dv
     *
     * @param string $dv
     *
     * @return Hojadevida
     */
    public function setDv($dv) {
        $this->dv = $dv;

        return $this;
    }

    /**
     * Get dv
     *
     * @return string
     */
    public function getDv() {
        return $this->dv;
    }

    /**
     * Set fecha
     *
     * @param \DateTime $fecha
     *
     * @return Hojadevida
     */
    public function setFecha($fecha) {
        $this->fecha = $fecha;

        return $this;
    }

    /**
     * Get fecha
     *
     * @return \DateTime
     */
    public function getFecha() {
        return $this->fecha;
    }

    /**
     * Set fechaupdate
     *
     * @param \DateTime $fechaupdate
     *
     * @return Hojadevida
     */
    public function setFechaupdate($fechaupdate) {
        $this->fechaupdate = $fechaupdate;

        return $this;
    }

    /**
     * Get fechaupdate
     *
     * @return \DateTime
     */
    public function getFechaupdate() {
        return $this->fechaupdate;
    }

    /**
     * Set image2
     *
     * @param string $image2
     *
     * @return Hojadevida
     */
    public function setImage2($image2) {
        $this->image2 = $image2;

        return $this;
    }

    /**
     * Get image2
     *
     * @return string
     */
    public function getImage2() {
        return $this->image2;
    }

    /**
     * Set image
     *
     * @param string $image
     *
     * @return Hojadevida
     */
    public function setImage($image) {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage() {
        return $this->image;
    }

    /**
     * Set image1
     *
     * @param string $image1
     *
     * @return Hojadevida
     */
    public function setImage1($image1) {
        $this->image1 = $image1;

        return $this;
    }

    /**
     * Get image1
     *
     * @return string
     */
    public function getImage1() {
        return $this->image1;
    }

    public function __toString() {
        return $this->nombre;
    }

    /**
     * Set estado
     *
     * @param string $estado
     *
     * @return Hojadevida
     */
    public function setEstado($estado) {
        $this->Estado = $estado;

        return $this;
    }

    /**
     * Get estado
     *
     * @return string
     */
    public function getEstado() {
        return $this->Estado;
    }
    /**
     * Set Tags
     *
     * @param string $Tags
     *
     * @return Hojadevida
     */
    public function setTags($Tags) {
        $this->Tags = $Tags;

        return $this;
    }

    /**
     * Get estado
     *
     * @return Tags
     */
    public function getTags() {
        return $this->Tags;

    }

}


text:
from pyspark import SparkConf, SparkContext
import collections
import os

# print(os.environ)
data_file="file:///"+os.environ['GIT_REPO']+"/misc-examples/spark/data/movielens/ml-100k/u.data"
#data_file="file:///c:/arbeit/git/misc-examples/spark/data/movielens/ml-100k/u.data"

conf = SparkConf().setMaster("local").setAppName("RatingsHistogram")
sc = SparkContext(conf = conf)

conf.set("spark.sql.shuffle.partitions", 50)
lines = sc.textFile(data_file)
splitted_line =lines.map(lambda x: x.split()[:]).map(lambda x: (x[2],(x[0],x[1],x[3]))).groupByKey()
print(type(splitted_line))
print(splitted_line.getNumPartitions())
samples= splitted_line.take(5)

print("Size %d" % len(samples))
for sample in samples :
    print("%s : Type %s" %(sample,type(sample)))
    print("%s:%s : Type %s" %(sample,type(sample)))

ratings = lines.map(lambda x: x.split()[2])
result = ratings.countByValue()

sortedResults = collections.OrderedDict(sorted(result.items()))
for key, value in sortedResults.items():
    print("%s %i" % (key, value))