text:
/*
 * ITimer.h
 *
 *  Created on: 2013-7-20
 *      Author: gangz
 */

#ifndef ITIMER_H_
#define ITIMER_H_

#include "ITimerEventListener.h"

class ITimer {
public:
	virtual ~ITimer(){};
    virtual void registerEventListener(ITimerEventListener *listener)=0;
    virtual void start()=0;
};

#endif /* ITIMER_H_ */


text:
---
uid: SolidEdgeFramework.LinearStyles.Active
summary:
remarks:
example: [*content]
---
[!code-vb[Main](..\snippets\SolidEdgeFramework.LinearStyles.Active.vb]
[!code-csharp[Main](..\snippets\SolidEdgeFramework.LinearStyles.Active.cs]

redpajama_set_name: RedPajamaGithub


text:
var qs = require('querystring');

module.exports = function(request, response, callback) {
  if (request.method == 'POST' || request.method == 'PUT') {
      var body = '';
      request.on('data', function (data) {
          body += data;
          // ~1MB - use something else for bigger files
          if (body.length > 1e6) {
              // Body is too long
              request.connection.destroy();
              callback(new Error('Body too big'));
          }
      });
      request.on('end', function () {
          var data = qs.parse(body);
          callback(null, data);
      });
  }
}


text:
/*
 * FRC 4931 (http://www.evilletech.com)
 *
 * Open source software. Licensed under the FIRST BSD license file in the
 * root directory of this project's Git repository.
 */
package org.frc4931.robot.command.drive;

import org.frc4931.robot.command.TimedCommand;
import org.frc4931.robot.subsystem.DriveSystem;

/**
 * Turns the drive system rightward for a certain amount of time.
 *
 * @author Adam Gausmann
 * @see org.frc4931.robot.subsystem.DriveSystem
 */
@Deprecated
public class TurnRightWithDuration extends TimedCommand {
    private final DriveSystem driveSystem;
    private final double turnSpeed;

    /**
     * Creates a new instance of this command
     * @param driveSystem The {@link org.frc4931.robot.subsystem.DriveSystem} to operate upon.
     * @param turnSpeed The speed at which to turn.
     * @param timeout The command timeout in seconds.
     */
    public TurnRightWithDuration(DriveSystem driveSystem, double turnSpeed, double timeout) {
        super(timeout);
        this.driveSystem = driveSystem;
        this.turnSpeed = turnSpeed;
        requires(driveSystem);
    }

    @Override
    protected void initialize() {

    }

    @Override
    protected void execute() {
        driveSystem.arcade(0.0, -Math.abs(turnSpeed));
    }

    @Override
    protected void end() {
        driveSystem.stop();
    }
}


text:
from CIM14.IEC61970.Dynamics.ExcitationSystems.ExcitationSystem import ExcitationSystem

class ExcBBC(ExcitationSystem):
    """Static Excitation System Model with ABB regulator
    """

    def __init__(self, *args, **kw_args):
        """Initialises a new 'ExcBBC' instance.

        """
        super(ExcBBC, self).__init__(*args, **kw_args)

    _attrs = []
    _attr_types = {}
    _defaults = {}
    _enums = {}
    _refs = []
    _many_refs = []


text:
using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace CountingApp.Droid
{
	[Activity (Label = "CountingApp", Icon = "@drawable/icon", Theme="@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
	public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
	{
		protected override void OnCreate (Bundle bundle)
		{
		    AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
		    {

		    };

            TabLayoutResource = Resource.Layout.Tabbar;
			ToolbarResource = Resource.Layout.Toolbar;

			base.OnCreate (bundle);

			global::Xamarin.Forms.Forms.Init (this, bundle);
		    global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this, bundle);
            LoadApplication (new CountingApp.App ());
		}
	}
}


text:
1. [Overview](#overview)
2. [Module Description](#module-description)
3. [Setup](#setup)
    * [What Nscd affects](#what-nscd-affects)
    * [Setup requirements](#setup-requirements)
    * [Beginning with Nscd](#beginning-with-Nscd)
4. [Usage](#usage)
5. [Limitations](#limitations)
6. [TODOs](#TODOs)

##Overview

This small nscd module manages the nscd service.

Written for Puppet >= 3.4.0.

##Module Description

See [Overview](#overview) for now.

##Setup

###What Nscd affects

* nscd :-)

###Setup Requirements

Nothing special.

###Beginning with Nscd

Simply include it.

##Usage

Just include the module by

```puppet
include nscd
```

Configure it through hiera or declare it resource-like with the parameters set, e.g.:

```puppet
class { 'nscd':
  service => 'stopped',
}
```

##Limitations:

Debian like systems.
Tested on:

* Debian 7
* CentOs 6

Puppet Version >= 3.4.0, due to specific hiera usage.

##TODOs:

* make it work on RedHat like systems.
* make it work with puppet pre 3.4


text:
"use strict";

var plugin = {};

plugin.parse = function(data, callback) {
	if (!data || !data.postData || !data.postData.content) {
		return callback(null, data);
	}

	data.postData.content = data.postData.content
		.replace(/!\[([\S\s]*?)\]\(http:\/\/(\S*?)\)/, '![$1](https://$2)');

	callback(null, data);
};

module.exports = plugin;


text:
#pragma once
#include <aws/sqs/SQS_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/sqs/model/ResponseMetadata.h>
#include <aws/sqs/model/QueueAttributeName.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace SQS
{
namespace Model
{
  /*
    A list of returned queue attributes.
  */
  class AWS_SQS_API GetQueueAttributesResult
  {
  public:
    GetQueueAttributesResult();
    GetQueueAttributesResult(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    GetQueueAttributesResult& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    /*

A map of attributes to the respective values.

    */
    inline const Aws::Map<QueueAttributeName, Aws::String>& GetAttributes() const{ return m_attributes; }

    /*

A map of attributes to the respective values.

    */
    inline void SetAttributes(const Aws::Map<QueueAttributeName, Aws::String>& value) { m_attributes = value; }

    /*

A map of attributes to the respective values.

    */
    inline void SetAttributes(Aws::Map<QueueAttributeName, Aws::String>&& value) { m_attributes = value; }

    /*

A map of attributes to the respective values.

    */
    inline GetQueueAttributesResult& WithAttributes(const Aws::Map<QueueAttributeName, Aws::String>& value) { SetAttributes(value); return *this;}

    /*

A map of attributes to the respective values.

    */
    inline GetQueueAttributesResult& WithAttributes(Aws::Map<QueueAttributeName, Aws::String>&& value) { SetAttributes(value); return *this;}

    /*

A map of attributes to the respective values.

    */
    inline GetQueueAttributesResult& AddAttributes(const QueueAttributeName& key, const Aws::String& value) { m_attributes[key] = value; return *this; }

    /*

A map of attributes to the respective values.

    */
    inline GetQueueAttributesResult& AddAttributes(QueueAttributeName&& key, const Aws::String& value) { m_attributes[key] = value; return *this; }

    /*

A map of attributes to the respective values.

    */
    inline GetQueueAttributesResult& AddAttributes(const QueueAttributeName& key, Aws::String&& value) { m_attributes[key] = value; return *this; }

    /*

A map of attributes to the respective values.

    */
    inline GetQueueAttributesResult& AddAttributes(QueueAttributeName&& key, Aws::String&& value) { m_attributes[key] = value; return *this; }

    /*

A map of attributes to the respective values.

    */
    inline GetQueueAttributesResult& AddAttributes(QueueAttributeName&& key, const char* value) { m_attributes[key] = value; return *this; }

    /*

A map of attributes to the respective values.

    */
    inline GetQueueAttributesResult& AddAttributes(const QueueAttributeName& key, const char* value) { m_attributes[key] = value; return *this; }

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = value; }

    inline GetQueueAttributesResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline GetQueueAttributesResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(value); return *this;}

  private:
    Aws::Map<QueueAttributeName, Aws::String> m_attributes;
    ResponseMetadata m_responseMetadata;
  };

} // namespace Model
} // namespace SQS
} // namespace Aws


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__placement_new_alloca_44.cpp
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__placement_new.label.xml
Template File: sources-sinks-44.tmpl.cpp
*/
/*
 * @description
 * CWE: 121 Stack Based Buffer Overflow
 * BadSource:  Initialize data to a small buffer
 * GoodSource: Initialize data to a buffer large enough to hold a TwoIntsClass
 * Sinks:
 *    GoodSink: Allocate a new class using placement new and a buffer that is large enough to hold the class
 *    BadSink : Allocate a new class using placement new and a buffer that is too small
 * Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer
 *
 * */

#include "std_testcase.h"

namespace CWE121_Stack_Based_Buffer_Overflow__placement_new_alloca_44
{

#ifndef OMITBAD

static void badSink(char * data)
{
    {
        /* The Visual C++ compiler generates a warning if you initialize the class with ().
         * This will cause the compile to default-initialize the object.
         * See http://msdn.microsoft.com/en-us/library/wewb47ee%28v=VS.100%29.aspx
         */
        /* POTENTIAL FLAW: data may not be large enough to hold a TwoIntsClass */
        TwoIntsClass * classTwo = new(data) TwoIntsClass;
        /* Initialize and make use of the class */
        classTwo->intOne = 5;
        classTwo->intTwo = 10; /* POTENTIAL FLAW: If sizeof(data) < sizeof(TwoIntsClass) then this line will be a buffer overflow */
        printIntLine(classTwo->intOne);
        /* skip printing classTwo->intTwo since that could be a buffer overread */
    }
}

void bad()
{
    char * data;
    /* define a function pointer */
    void (*funcPtr) (char *) = badSink;
    char * dataBadBuffer = (char *)ALLOCA(sizeof(OneIntClass));
    char * dataGoodBuffer = (char *)ALLOCA(sizeof(TwoIntsClass));
    /* POTENTIAL FLAW: Initialize data to a buffer smaller than the sizeof(TwoIntsClass) */
    data = dataBadBuffer;
    /* use the function pointer */
    funcPtr(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSink(char * data)
{
    {
        /* The Visual C++ compiler generates a warning if you initialize the class with ().
         * This will cause the compile to default-initialize the object.
         * See http://msdn.microsoft.com/en-us/library/wewb47ee%28v=VS.100%29.aspx
         */
        /* POTENTIAL FLAW: data may not be large enough to hold a TwoIntsClass */
        TwoIntsClass * classTwo = new(data) TwoIntsClass;
        /* Initialize and make use of the class */
        classTwo->intOne = 5;
        classTwo->intTwo = 10; /* POTENTIAL FLAW: If sizeof(data) < sizeof(TwoIntsClass) then this line will be a buffer overflow */
        printIntLine(classTwo->intOne);
        /* skip printing classTwo->intTwo since that could be a buffer overread */
    }
}

static void goodG2B()
{
    char * data;
    void (*funcPtr) (char *) = goodG2BSink;
    char * dataBadBuffer = (char *)ALLOCA(sizeof(OneIntClass));
    char * dataGoodBuffer = (char *)ALLOCA(sizeof(TwoIntsClass));
    /* FIX: Initialize to a buffer at least the sizeof(TwoIntsClass) */
    data = dataGoodBuffer;
    funcPtr(data);
}

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2GSink(char * data)
{
    {
        /* The Visual C++ compiler generates a warning if you initialize the class with ().
         * This will cause the compile to default-initialize the object.
         * See http://msdn.microsoft.com/en-us/library/wewb47ee%28v=VS.100%29.aspx
         */
        /* FIX: data will at least be the sizeof(OneIntClass) */
        OneIntClass * classOne = new(data) OneIntClass;
        /* Initialize and make use of the class */
        classOne->intOne = 5;
        printIntLine(classOne->intOne);
    }
}

static void goodB2G()
{
    char * data;
    void (*funcPtr) (char *) = goodB2GSink;
    char * dataBadBuffer = (char *)ALLOCA(sizeof(OneIntClass));
    char * dataGoodBuffer = (char *)ALLOCA(sizeof(TwoIntsClass));
    /* POTENTIAL FLAW: Initialize data to a buffer smaller than the sizeof(TwoIntsClass) */
    data = dataBadBuffer;
    funcPtr(data);
}

void good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE121_Stack_Based_Buffer_Overflow__placement_new_alloca_44; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
package org.dasein.cloud.compute;

public enum VolumeState {
    PENDING,
    AVAILABLE,
    DELETED,
    ERROR
}


text:
package org.egzi.springconfigurator.locator;

/**
 * Converter that convert ConfigDefinition to some other object
 * @param <T>- object type
 */
public interface ContextConverter<T> {

    /**
     * Convert definition to some other object type
     * @param definition -  definition of context
     * @return specified type
     */
    T convert(ConfigDefinition definition);
}


text:
layout: post
title: "Long Run with Tempo Surges with MetroRun #9 - End of Training Week 9"
date: 2022-08-07 08:05:19
author: multishiv19
comments: true
category: [runs]
tags: [Run]
description: |
    Gear: Saucony Endorphin Speed 2
Finally hit a 120km week 😃🙌
I'm pleased that I could safely hit this mileage with workouts and tempo runs.
I'm not gonna work towards hitting 160 for AKL marathon training. I'll try it after the marathon.
For now I have decided that it is better for me to focus on quality workouts than focusing on mileage.
RIP to Relative Effort this week 😂
---

## Gear
Saucony Endorphin Speed 2

## Activity Description
Finally hit a 120km week 😃🙌
I'm pleased that I could safely hit this mileage with workouts and tempo runs.
I'm not gonna work towards hitting 160 for AKL marathon training. I'll try it after the marathon.
For now I have decided that it is better for me to focus on quality workouts than focusing on mileage.
RIP to Relative Effort this week 😂


text:
@interface UserNetworkPersistenceStore (Private)

+ (NSString *)plistName;
+ (NSString *)primaryUserFollowingKey;
+ (NSString *)primaryUserFollowersKey;

@end

@implementation UserNetworkPersistenceStore

- (void)dealloc
{
    [userNetworkCacheReader release];
    [userNetworkCacheSetter release];
    [super dealloc];
}

- (void)load
{
    NSDictionary * dict =
        [PlistUtils getDictionaryFromPlist:[[self class] plistName]];

    NSArray * primaryUserFollowing =
        [dict objectForKey:[[self class] primaryUserFollowingKey]];
    [userNetworkCacheSetter setFollowingForPrimaryUser:primaryUserFollowing];

    NSArray * primaryUserFollowers =
        [dict objectForKey:[[self class] primaryUserFollowersKey]];
    [userNetworkCacheSetter setFollowersForPrimaryUser:primaryUserFollowers];
}

- (void)save
{
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];

    NSArray * primaryUserFollowing =
        [userNetworkCacheReader followingForPrimaryUser];

    if (primaryUserFollowing)
        [dict setObject:primaryUserFollowing
            forKey:[[self class] primaryUserFollowingKey]];

    NSArray * primaryUserFollowers =
        [userNetworkCacheReader followersForPrimaryUser];
    if (primaryUserFollowers)
        [dict setObject:primaryUserFollowers
             forKey:[[self class] primaryUserFollowersKey]];

    [PlistUtils saveDictionary:dict toPlist:[[self class] plistName]];
}

+ (NSString *)plistName
{
    return @"UserNetworkCache";
}

+ (NSString *)primaryUserFollowingKey
{
    return @"primaryUserFollowing";
}

+ (NSString *)primaryUserFollowersKey
{
    return @"primaryUserFollowers";
}

@end


text:
layout: front
permalink: /uk/
lang: uk
fronttitle: "OpenStreetMap — це вільна мапа світу, створена зростаючою спільнотою маперів."
frontintro: "Будь-хто може редагувати OpenStreetMap. Тут ви можете ознайомитись з простими покроковими посібниками від LearnOSM, що допомагають всім бажаючим почати робити свій внесок в розвиток OpenStreetMap, використовувати OpenStreetMap, а також використовувати дані OpenStreetMap. Якщо у вас є бажання провести семінар з OpenStreetMap, ознайомтесь із навчальними матеріалами."
ourguides: "Наші керівництва"
searchtext: "Що ви шукаєте?"
begspan: "Новачок в OpenStreetMap?"
beg: "керівництво для початківців"
interspan: "Більше підручників (зараз англійською)"
interspanlink: "https://github.com/hotosm/learnosm/wiki/English-Learning-Guides"
inter: "Середній, Поглиблений, QGIS …"
advspan: "Організація семінару?"
adv: "Ознайомтесь з нашими навчальними матеріалами"
faq: "Загальні питання"
faqA: "Що таке OpenStreetMap?"
faqB: "Хто створив LearnOSM?"
faqC: "Як я можу почати мапити?"
faqD: "Де я можу знайти додаткову допомогу?"
nosearch: true
---


text:
namespace nu {

TEST_CASE("ThreadLocal") {
  SECTION("basic") {
    auto id = current_thread::create_storage();

    nu::DynamicArray<JoinHandle> handles;
    for (int i = 0; i < 30; ++i) {
      handles.emplaceBack(spawn_thread([id, i]() {
        auto value = (const void*)(MemSize)i;
        current_thread::set_storage(id, value);
        REQUIRE(current_thread::get_storage(id) == value);
      }));
    }

    for (auto& handle : handles) {
      handle.join();
    }
  }
}

}  // namespace nu


text:
Submission failed

For some reason, your submission failed.

Please contact us about your interest at helpdesk@gbif.org.


text:
import sys

def CheckChange(input_api, output_api):
  original_sys_path = sys.path
  try:
    sys.path += [input_api.PresubmitLocalPath()]
    from hooks import pre_commit
    results = pre_commit.GetResults('@{u}')
    return map(output_api.PresubmitError, results)
  finally:
    sys.path = original_sys_path

def CheckChangeOnUpload(input_api, output_api):
  return CheckChange(input_api, output_api)

def CheckChangeOnCommit(input_api, output_api):
  return CheckChange(input_api, output_api)


text:
import os, sys, random
import logging as log
from optparse import OptionParser
import numpy as np
import text.util, unsupervised.nmf, unsupervised.rankings, unsupervised.util

# --------------------------------------------------------------

def main():
	parser = OptionParser(usage="usage: %prog [options] corpus_file")
	parser.add_option("--seed", action="store", type="int", dest="seed", help="initial random seed", default=1000)
	parser.add_option("--kmin", action="store", type="int", dest="kmin", help="minimum number of topics", default=5)
	parser.add_option("--kmax", action="store", type="int", dest="kmax", help="maximum number of topics", default=5)
	parser.add_option("-r","--runs", action="store", type="int", dest="runs", help="number of runs", default=1)
	parser.add_option("--maxiters", action="store", type="int", dest="maxiter", help="maximum number of iterations", default=10)
	parser.add_option("-s", "--sample", action="store", type="float", dest="sample_ratio", help="sampling ratio of documents to include in each run (range is 0 to 1)", default=0.8)
	parser.add_option("-o","--outdir", action="store", type="string", dest="dir_out", help="base output directory (default is current directory)", default=None)
	parser.add_option("-w","--writefactors", action="store_true", dest="write_factors", help="write complete factorization results")
	parser.add_option('-d','--debug',type="int",help="Level of log output; 0 is less, 5 is all", default=3)
	(options, args) = parser.parse_args()
	if len(args) < 1:
		parser.error( "Must specify at least one corpus file" )
	log.basicConfig(level=max(50 - (options.debug * 10), 10), format='%(asctime)-18s %(levelname)-10s %(message)s', datefmt='%d/%m/%Y %H:%M',)
	# use nimfa instead of sklearn?
	use_nimfa = True

	if options.dir_out is None:
		dir_out_base = os.getcwd()
	else:
		dir_out_base = options.dir_out

	# Load the cached corpus
	corpus_path = args[0]
	(X,terms,doc_ids,classes) = text.util.load_corpus( corpus_path )

	# Choose implementation
	if use_nimfa:
		impl = unsupervised.nmf.NimfaNMF( max_iters = options.maxiter, init_strategy = "random", update = "euclidean" )
	else:
		impl = unsupervised.nmf.SklNMF( max_iters = options.maxiter, init_strategy = "random" )

	n_documents = X.shape[0]
	n_sample = int( options.sample_ratio * n_documents )
	indices = np.arange(n_documents)

	# Generate all NMF topic models for the specified numbers of topics
	log.info( "Testing models in range k=[%d,%d]" % ( options.kmin, options.kmax ) )
	log.info( "Sampling ratio = %.2f - %d/%d documents per run" % ( options.sample_ratio, n_sample, n_documents ) )
	for k in range(options.kmin, options.kmax+1):
		# Set random state
		np.random.seed( options.seed )
		random.seed( options.seed )
		log.info( "Applying NMF (k=%d, runs=%d, seed=%s - %s) ..." % ( k, options.runs, options.seed, impl.__class__.__name__ ) )
		dir_out_k = os.path.join( dir_out_base, "nmf_k%02d" % k )
		if not os.path.exists(dir_out_k):
			os.makedirs(dir_out_k)
		log.debug( "Results will be written to %s" % dir_out_k )
		# Run NMF
		for r in range(options.runs):
			log.info( "NMF run %d/%d (k=%d, max_iters=%d)" % (r+1, options.runs, k, options.maxiter ) )
			file_suffix = "%s_%03d" % ( options.seed, r+1 )
			# sub-sample data
			np.random.shuffle(indices)
			sample_indices = indices[0:n_sample]
			S = X[sample_indices,:]
			sample_doc_ids = []
			for doc_index in sample_indices:
				sample_doc_ids.append( doc_ids[doc_index] )
			# apply NMF
			impl.apply( S, k )
			# Get term rankings for each topic
			term_rankings = []
			for topic_index in range(k):
				ranked_term_indices = impl.rank_terms( topic_index )
				term_ranking = [terms[i] for i in ranked_term_indices]
				term_rankings.append(term_ranking)
			log.debug( "Generated ranking set with %d topics covering up to %d terms" % ( len(term_rankings), unsupervised.rankings.term_rankings_size( term_rankings ) ) )
			# Write term rankings
			ranks_out_path = os.path.join( dir_out_k, "ranks_%s.pkl" % file_suffix )
			log.debug( "Writing term ranking set to %s" % ranks_out_path )
			unsupervised.util.save_term_rankings( ranks_out_path, term_rankings )
			# Write document partition
			partition = impl.generate_partition()
			partition_out_path = os.path.join( dir_out_k, "partition_%s.pkl" % file_suffix )
			log.debug( "Writing document partition to %s" % partition_out_path )
			unsupervised.util.save_partition( partition_out_path, partition, sample_doc_ids )
			# Write the complete factorization?
			if options.write_factors:
				factor_out_path = os.path.join( dir_out_k, "factors_%s.pkl" % file_suffix )
				# NB: need to make a copy of the factors
				log.debug( "Writing factorization to %s" % factor_out_path )
				unsupervised.util.save_nmf_factors( factor_out_path, np.array( impl.W ), np.array( impl.H ), sample_doc_ids )

# --------------------------------------------------------------

if __name__ == "__main__":
	main()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>D-Index</title>
<meta name="date" content="2017-06-06">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G I K L M N O P S T V W

D

DEBUG - Static variable in class MonsterQuest.MonsterQuestMain

This enables the debug mode, use -d to enable.

Defense - Variable in class MonsterQuest.game.Player

Defense - Variable in class MonsterQuest.game.player.Player

The defense of the player.

DefenseLv - Variable in class MonsterQuest.game.player.Player

description - Variable in class MonsterQuest.game.items.Weapon

A B C D E F G I K L M N O P S T V W

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?php

namespace Assely\Sidebar;

use Illuminate\Config\Repository;

class SidebarsCollection extends Repository
{
    //
}


text:
from __future__ import print_function
import torch.utils.data as data
from PIL import Image
import os
import os.path
import errno
import numpy as np
import torch
import codecs

class MNIST(data.Dataset):
    """`MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset.

    Args:
        root (string): Root directory of dataset where ``processed/training.pt``
            and  ``processed/test.pt`` exist.
        train (bool, optional): If True, creates dataset from ``training.pt``,
            otherwise from ``test.pt``.
        download (bool, optional): If true, downloads the dataset from the internet and
            puts it in root directory. If dataset is already downloaded, it is not
            downloaded again.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
    """
    urls = [
        'http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz',
        'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz',
        'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz',
        'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz',
    ]
    raw_folder = 'raw'
    processed_folder = 'processed'
    training_file = 'training.pt'
    test_file = 'test.pt'

    def __init__(self, root, train=True, transform=None, target_transform=None, download=False):
        self.root = os.path.expanduser(root)
        self.transform = transform
        self.target_transform = target_transform
        self.train = train  # training set or test set

        if download:
            self.download()

        if not self._check_exists():
            raise RuntimeError('Dataset not found.' +
                               ' You can use download=True to download it')

        if self.train:
            self.train_data, self.train_labels = torch.load(
                os.path.join(self.root, self.processed_folder, self.training_file))
        else:
            self.test_data, self.test_labels = torch.load(
                os.path.join(self.root, self.processed_folder, self.test_file))

    def __getitem__(self, index):
        """
        Args:
            index (int): Index

        Returns:
            tuple: (image, target) where target is index of the target class.
        """
        if self.train:
            img, target = self.train_data[index], self.train_labels[index]
        else:
            img, target = self.test_data[index], self.test_labels[index]

        # doing this so that it is consistent with all other datasets
        # to return a PIL Image
        img = Image.fromarray(img.numpy(), mode='L')

        if self.transform is not None:
            img = self.transform(img)

        if self.target_transform is not None:
            target = self.target_transform(target)

        return img, target

    def __len__(self):
        if self.train:
            return len(self.train_data)
        else:
            return len(self.test_data)

    def _check_exists(self):
        return os.path.exists(os.path.join(self.root, self.processed_folder, self.training_file)) and \
            os.path.exists(os.path.join(self.root, self.processed_folder, self.test_file))

    def download(self):
        """Download the MNIST data if it doesn't exist in processed_folder already."""
        from six.moves import urllib
        import gzip

        if self._check_exists():
            return

        # download files
        try:
            os.makedirs(os.path.join(self.root, self.raw_folder))
            os.makedirs(os.path.join(self.root, self.processed_folder))
        except OSError as e:
            if e.errno == errno.EEXIST:
                pass
            else:
                raise

        for url in self.urls:
            print('Downloading ' + url)
            data = urllib.request.urlopen(url)
            filename = url.rpartition('/')[2]
            file_path = os.path.join(self.root, self.raw_folder, filename)
            with open(file_path, 'wb') as f:
                f.write(data.read())
            with open(file_path.replace('.gz', ''), 'wb') as out_f, \
                    gzip.GzipFile(file_path) as zip_f:
                out_f.write(zip_f.read())
            os.unlink(file_path)

        # process and save as torch files
        print('Processing...')

        training_set = (
            read_image_file(os.path.join(self.root, self.raw_folder, 'train-images-idx3-ubyte')),
            read_label_file(os.path.join(self.root, self.raw_folder, 'train-labels-idx1-ubyte'))
        )
        test_set = (
            read_image_file(os.path.join(self.root, self.raw_folder, 't10k-images-idx3-ubyte')),
            read_label_file(os.path.join(self.root, self.raw_folder, 't10k-labels-idx1-ubyte'))
        )
        with open(os.path.join(self.root, self.processed_folder, self.training_file), 'wb') as f:
            torch.save(training_set, f)
        with open(os.path.join(self.root, self.processed_folder, self.test_file), 'wb') as f:
            torch.save(test_set, f)

        print('Done!')

    def __repr__(self):
        fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
        fmt_str += '    Number of datapoints: {}\n'.format(self.__len__())
        tmp = 'train' if self.train is True else 'test'
        fmt_str += '    Split: {}\n'.format(tmp)
        fmt_str += '    Root Location: {}\n'.format(self.root)
        tmp = '    Transforms (if any): '
        fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
        tmp = '    Target Transforms (if any): '
        fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
        return fmt_str

class FashionMNIST(MNIST):
    """`Fashion-MNIST <https://github.com/zalandoresearch/fashion-mnist>`_ Dataset.

    Args:
        root (string): Root directory of dataset where ``processed/training.pt``
            and  ``processed/test.pt`` exist.
        train (bool, optional): If True, creates dataset from ``training.pt``,
            otherwise from ``test.pt``.
        download (bool, optional): If true, downloads the dataset from the internet and
            puts it in root directory. If dataset is already downloaded, it is not
            downloaded again.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
    """
    urls = [
        'http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz',
        'http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz',
        'http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz',
        'http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz',
    ]

class EMNIST(MNIST):
    """`EMNIST <https://www.nist.gov/itl/iad/image-group/emnist-dataset/>`_ Dataset.

    Args:
        root (string): Root directory of dataset where ``processed/training.pt``
            and  ``processed/test.pt`` exist.
        split (string): The dataset has 6 different splits: ``byclass``, ``bymerge``,
            ``balanced``, ``letters``, ``digits`` and ``mnist``. This argument specifies
            which one to use.
        train (bool, optional): If True, creates dataset from ``training.pt``,
            otherwise from ``test.pt``.
        download (bool, optional): If true, downloads the dataset from the internet and
            puts it in root directory. If dataset is already downloaded, it is not
            downloaded again.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
    """
    url = 'http://www.itl.nist.gov/iaui/vip/cs_links/EMNIST/gzip.zip'
    splits = ('byclass', 'bymerge', 'balanced', 'letters', 'digits', 'mnist')

    def __init__(self, root, split, **kwargs):
        if split not in self.splits:
            raise ValueError('Split "{}" not found. Valid splits are: {}'.format(
                split, ', '.join(self.splits),
            ))
        self.split = split
        self.training_file = self._training_file(split)
        self.test_file = self._test_file(split)
        super(EMNIST, self).__init__(root, **kwargs)

    def _training_file(self, split):
        return 'training_{}.pt'.format(split)

    def _test_file(self, split):
        return 'test_{}.pt'.format(split)

    def download(self):
        """Download the EMNIST data if it doesn't exist in processed_folder already."""
        from six.moves import urllib
        import gzip
        import shutil
        import zipfile

        if self._check_exists():
            return

        # download files
        try:
            os.makedirs(os.path.join(self.root, self.raw_folder))
            os.makedirs(os.path.join(self.root, self.processed_folder))
        except OSError as e:
            if e.errno == errno.EEXIST:
                pass
            else:
                raise

        print('Downloading ' + self.url)
        data = urllib.request.urlopen(self.url)
        filename = self.url.rpartition('/')[2]
        raw_folder = os.path.join(self.root, self.raw_folder)
        file_path = os.path.join(raw_folder, filename)
        with open(file_path, 'wb') as f:
            f.write(data.read())

        print('Extracting zip archive')
        with zipfile.ZipFile(file_path) as zip_f:
            zip_f.extractall(raw_folder)
        os.unlink(file_path)
        gzip_folder = os.path.join(raw_folder, 'gzip')
        for gzip_file in os.listdir(gzip_folder):
            if gzip_file.endswith('.gz'):
                print('Extracting ' + gzip_file)
                with open(os.path.join(raw_folder, gzip_file.replace('.gz', '')), 'wb') as out_f, \
                        gzip.GzipFile(os.path.join(gzip_folder, gzip_file)) as zip_f:
                    out_f.write(zip_f.read())
        shutil.rmtree(gzip_folder)

        # process and save as torch files
        for split in self.splits:
            print('Processing ' + split)
            training_set = (
                read_image_file(os.path.join(raw_folder, 'emnist-{}-train-images-idx3-ubyte'.format(split))),
                read_label_file(os.path.join(raw_folder, 'emnist-{}-train-labels-idx1-ubyte'.format(split)))
            )
            test_set = (
                read_image_file(os.path.join(raw_folder, 'emnist-{}-test-images-idx3-ubyte'.format(split))),
                read_label_file(os.path.join(raw_folder, 'emnist-{}-test-labels-idx1-ubyte'.format(split)))
            )
            with open(os.path.join(self.root, self.processed_folder, self._training_file(split)), 'wb') as f:
                torch.save(training_set, f)
            with open(os.path.join(self.root, self.processed_folder, self._test_file(split)), 'wb') as f:
                torch.save(test_set, f)

        print('Done!')

def get_int(b):
    return int(codecs.encode(b, 'hex'), 16)

def read_label_file(path):
    with open(path, 'rb') as f:
        data = f.read()
        assert get_int(data[:4]) == 2049
        length = get_int(data[4:8])
        parsed = np.frombuffer(data, dtype=np.uint8, offset=8)
        return torch.from_numpy(parsed).view(length).long()

def read_image_file(path):
    with open(path, 'rb') as f:
        data = f.read()
        assert get_int(data[:4]) == 2051
        length = get_int(data[4:8])
        num_rows = get_int(data[8:12])
        num_cols = get_int(data[12:16])
        images = []
        parsed = np.frombuffer(data, dtype=np.uint8, offset=16)
        return torch.from_numpy(parsed).view(length, num_rows, num_cols)


text:
/*							polevl.c
 *							p1evl.c
 *
 *	Evaluate polynomial
 *
 *
 *
 * SYNOPSIS:
 *
 * int N;
 * double x, y, coef[N+1], polevl[];
 *
 * y = polevl( x, coef, N );
 *
 *
 *
 * DESCRIPTION:
 *
 * Evaluates polynomial of degree N:
 *
 *                     2          N
 * y  =  C  + C x + C x  +...+ C x
 *        0    1     2          N
 *
 * Coefficients are stored in reverse order:
 *
 * coef[0] = C  , ..., coef[N] = C  .
 *            N                   0
 *
 * The function p1evl() assumes that C_N = 1.0 and is
 * omitted from the array.  Its calling arguments are
 * otherwise the same as polevl().
 *
 *
 * SPEED:
 *
 * In the interest of speed, there are no checks for out
 * of bounds arithmetic.  This routine is used by most of
 * the functions in the library.  Depending on available
 * equipment features, the user may wish to rewrite the
 * program in microcode or assembly language.
 *
 */

/*
Cephes Math Library Release 2.1:  December, 1988
Copyright 1984, 1987, 1988 by Stephen L. Moshier
Direct inquiries to 30 Frost Street, Cambridge, MA 02140
*/

static
double polevl( double x, pconstant double *coef, int N )
{

    int i = 0;
    double ans = coef[i];

    while (i < N) {
        i++;
        ans = ans * x + coef[i];
    }

    return ans;
}

/*							p1evl()	*/
/*                                          N
 * Evaluate polynomial when coefficient of x  is 1.0.
 * Otherwise same as polevl.
 */

static
double p1evl( double x, pconstant double *coef, int N )
{
    int i=0;
    double ans = x+coef[i];

    while (i < N-1) {
        i++;
        ans = ans*x + coef[i];
    }

    return ans;
}


text:
/*
 | PC-LISP (C) 1984-1989 Peter J.Ashwood-Smith
 */
#include <stdio.h>
#include <math.h>
#include "lisp.h"

/*************************************************************************
 ** buhunk: (hunk e1 e2 ... eN) Turn the list (e1 ... eN) into a hunk of**
 ** N elements. Just call the ListToHunk function with the parm list.   **
 *************************************************************************/
struct conscell *buhunk(form)
struct conscell *form;
{      if (form != NULL)
           return(LIST(ListToHunk(form)));
       ierror("hunk");  /*  doesn't return  */
       return NULL;   /*  keep compiler happy  */
}


text:
"""Msgpack Base Results Phase 2

Revision ID: 05ceea11b78a
Revises: 8b0cd9accaf2
Create Date: 2019-08-11 22:30:51.453746

"""
from alembic import op
import sqlalchemy as sa

import os
import sys

sys.path.insert(1, os.path.dirname(os.path.abspath(__file__)))
from migration_helpers import msgpack_migrations
from qcelemental.util import msgpackext_dumps, msgpackext_loads

# revision identifiers, used by Alembic.
revision = "05ceea11b78a"
down_revision = "8b0cd9accaf2"
branch_labels = None
depends_on = None

table_name = "base_result"
update_columns = {"extras"}

nullable = {"extras"}

def upgrade():
    msgpack_migrations.json_to_msgpack_table_altercolumns(table_name, update_columns, nullable_true=nullable)

def downgrade():
    raise ValueError("Cannot downgrade json to msgpack conversions")


text:
package org.apache.juddi.example.browse;

import java.util.List;
import org.apache.juddi.api_v3.AccessPointType;
import org.apache.juddi.v3.client.UDDIConstants;
import org.apache.juddi.v3.client.config.UDDIClient;
import org.apache.juddi.v3.client.transport.Transport;
import org.uddi.api_v3.AuthToken;
import org.uddi.api_v3.BindingTemplates;
import org.uddi.api_v3.BusinessDetail;
import org.uddi.api_v3.BusinessInfos;
import org.uddi.api_v3.BusinessList;
import org.uddi.api_v3.BusinessService;
import org.uddi.api_v3.CategoryBag;
import org.uddi.api_v3.Contacts;
import org.uddi.api_v3.Description;
import org.uddi.api_v3.DiscardAuthToken;
import org.uddi.api_v3.FindBusiness;
import org.uddi.api_v3.GetAuthToken;
import org.uddi.api_v3.GetBusinessDetail;
import org.uddi.api_v3.GetServiceDetail;
import org.uddi.api_v3.KeyedReference;
import org.uddi.api_v3.Name;
import org.uddi.api_v3.ServiceDetail;
import org.uddi.api_v3.ServiceInfos;
import org.uddi.v3_service.UDDIInquiryPortType;
import org.uddi.v3_service.UDDISecurityPortType;

/**
 * A Simple UDDI Browser that dumps basic information to console
 *
 * @author Alex O'Ree
 */
public class SimpleBrowse {

        private UDDISecurityPortType security = null;
        private UDDIInquiryPortType inquiry = null;

        /**
         * This sets up the ws proxies using uddi.xml in META-INF
         */
        public SimpleBrowse() {
                try {
                        // create a manager and read the config in the archive;
                        // you can use your config file name
                        UDDIClient client = new UDDIClient("META-INF/simple-browse-uddi.xml");
                        // a UDDIClient can be a client to multiple UDDI nodes, so
                        // supply the nodeName (defined in your uddi.xml.
                        // The transport can be WS, inVM, RMI etc which is defined in the uddi.xml
                        Transport transport = client.getTransport("default");
                        // Now you create a reference to the UDDI API
                        security = transport.getUDDISecurityService();
                        inquiry = transport.getUDDIInquiryService();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

        /**
         * Main entry point
         *
         * @param args
         */
        public static void main(String args[]) {

                SimpleBrowse sp = new SimpleBrowse();
                sp.Browse(args);
        }

        public void Browse(String[] args) {
                try {

                        String token = GetAuthKey("uddi", "uddi");
                        BusinessList findBusiness = GetBusinessList(token);
                        PrintBusinessInfo(findBusiness.getBusinessInfos());
                        PrintBusinessDetails(findBusiness.getBusinessInfos(), token);
                        PrintServiceDetailsByBusiness(findBusiness.getBusinessInfos(), token);

                        security.discardAuthToken(new DiscardAuthToken(token));

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

        /**
         * Find all of the registered businesses. This list may be filtered
         * based on access control rules
         *
         * @param token
         * @return
         * @throws Exception
         */
        private BusinessList GetBusinessList(String token) throws Exception {
                FindBusiness fb = new FindBusiness();
                fb.setAuthInfo(token);
                org.uddi.api_v3.FindQualifiers fq = new org.uddi.api_v3.FindQualifiers();
                fq.getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);

                fb.setFindQualifiers(fq);
                Name searchname = new Name();
                searchname.setValue(UDDIConstants.WILDCARD);
                fb.getName().add(searchname);
                BusinessList findBusiness = inquiry.findBusiness(fb);
                return findBusiness;

        }

        /**
         * Converts category bags of tmodels to a readable string
         *
         * @param categoryBag
         * @return
         */
        private String CatBagToString(CategoryBag categoryBag) {
                StringBuilder sb = new StringBuilder();
                if (categoryBag == null) {
                        return "no data";
                }
                for (int i = 0; i < categoryBag.getKeyedReference().size(); i++) {
                        sb.append(KeyedReferenceToString(categoryBag.getKeyedReference().get(i)));
                }
                for (int i = 0; i < categoryBag.getKeyedReferenceGroup().size(); i++) {
                        sb.append("Key Ref Grp: TModelKey=");
                        for (int k = 0; k < categoryBag.getKeyedReferenceGroup().get(i).getKeyedReference().size(); k++) {
                                sb.append(KeyedReferenceToString(categoryBag.getKeyedReferenceGroup().get(i).getKeyedReference().get(k)));
                        }
                }
                return sb.toString();
        }

        private String KeyedReferenceToString(KeyedReference item) {
                StringBuilder sb = new StringBuilder();
                sb.append("Key Ref: Name=").
                        append(item.getKeyName()).
                        append(" Value=").
                        append(item.getKeyValue()).
                        append(" tModel=").
                        append(item.getTModelKey()).
                        append(System.getProperty("line.separator"));
                return sb.toString();
        }

        private void PrintContacts(Contacts contacts) {
                if (contacts == null) {
                        return;
                }
                for (int i = 0; i < contacts.getContact().size(); i++) {
                        System.out.println("Contact " + i + " type:" + contacts.getContact().get(i).getUseType());
                        for (int k = 0; k < contacts.getContact().get(i).getPersonName().size(); k++) {
                                System.out.println("Name: " + contacts.getContact().get(i).getPersonName().get(k).getValue());
                        }
                        for (int k = 0; k < contacts.getContact().get(i).getEmail().size(); k++) {
                                System.out.println("Email: " + contacts.getContact().get(i).getEmail().get(k).getValue());
                        }
                        for (int k = 0; k < contacts.getContact().get(i).getAddress().size(); k++) {
                                System.out.println("Address sort code " + contacts.getContact().get(i).getAddress().get(k).getSortCode());
                                System.out.println("Address use type " + contacts.getContact().get(i).getAddress().get(k).getUseType());
                                System.out.println("Address tmodel key " + contacts.getContact().get(i).getAddress().get(k).getTModelKey());
                                for (int x = 0; x < contacts.getContact().get(i).getAddress().get(k).getAddressLine().size(); x++) {
                                        System.out.println("Address line value " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getValue());
                                        System.out.println("Address line key name " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getKeyName());
                                        System.out.println("Address line key value " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getKeyValue());
                                }
                        }
                        for (int k = 0; k < contacts.getContact().get(i).getDescription().size(); k++) {
                                System.out.println("Desc: " + contacts.getContact().get(i).getDescription().get(k).getValue());
                        }
                        for (int k = 0; k < contacts.getContact().get(i).getPhone().size(); k++) {
                                System.out.println("Phone: " + contacts.getContact().get(i).getPhone().get(k).getValue());
                        }
                }

        }

        private void PrintServiceDetail(BusinessService get) {
                if (get == null) {
                        return;
                }
                System.out.println("Name " + ListToString(get.getName()));
                System.out.println("Desc " + ListToDescString(get.getDescription()));
                System.out.println("Key " + (get.getServiceKey()));
                System.out.println("Cat bag " + CatBagToString(get.getCategoryBag()));
                if (!get.getSignature().isEmpty()) {
                        System.out.println("Item is digitally signed");
                } else {
                        System.out.println("Item is not digitally signed");
                }
                PrintBindingTemplates(get.getBindingTemplates());
        }

        /**
         * This function is useful for translating UDDI's somewhat complex data
         * format to something that is more useful.
         *
         * @param bindingTemplates
         */
        private void PrintBindingTemplates(BindingTemplates bindingTemplates) {
                if (bindingTemplates == null) {
                        return;
                }
                for (int i = 0; i < bindingTemplates.getBindingTemplate().size(); i++) {
                        System.out.println("Binding Key: " + bindingTemplates.getBindingTemplate().get(i).getBindingKey());
                        //TODO The UDDI spec is kind of strange at this point.
                        //An access point could be a URL, a reference to another UDDI binding key, a hosting redirector (which is
                        //esscentially a pointer to another UDDI registry) or a WSDL Deployment
                        //From an end client's perspective, all you really want is the endpoint.
                        //http://uddi.org/pubs/uddi_v3.htm#_Ref8977716
                        //So if you have a wsdlDeployment useType, fetch the wsdl and parse for the invocation URL
                        //If its hosting director, you'll have to fetch that data from uddi recursively until the leaf node is found
                        //Consult the UDDI specification for more information

                        if (bindingTemplates.getBindingTemplate().get(i).getAccessPoint() != null) {
                                System.out.println("Access Point: " + bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getValue() + " type " + bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getUseType());
                                if (bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getUseType() != null) {
                                        if (bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getUseType().equalsIgnoreCase(AccessPointType.END_POINT.toString())) {
                                                System.out.println("Use this access point value as an invocation endpoint.");
                                        }
                                        if (bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getUseType().equalsIgnoreCase(AccessPointType.BINDING_TEMPLATE.toString())) {
                                                System.out.println("Use this access point value as a reference to another binding template.");
                                        }
                                        if (bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getUseType().equalsIgnoreCase(AccessPointType.WSDL_DEPLOYMENT.toString())) {
                                                System.out.println("Use this access point value as a URL to a WSDL document, which presumably will have a real access point defined.");
                                        }
                                        if (bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getUseType().equalsIgnoreCase(AccessPointType.HOSTING_REDIRECTOR.toString())) {
                                                System.out.println("Use this access point value as an Inquiry URL of another UDDI registry, look up the same binding template there (usage varies).");
                                        }
                                }
                        }

                }
        }

        private enum AuthStyle {

                HTTP_BASIC,
                HTTP_DIGEST,
                HTTP_NTLM,
                UDDI_AUTH,
                HTTP_CLIENT_CERT
        }

        /**
         * Gets a UDDI style auth token, otherwise, appends credentials to the
         * ws proxies (not yet implemented)
         *
         * @param username
         * @param password
         * @param style
         * @return
         */
        private String GetAuthKey(String username, String password) {
                try {

                        GetAuthToken getAuthTokenRoot = new GetAuthToken();
                        getAuthTokenRoot.setUserID(username);
                        getAuthTokenRoot.setCred(password);

                        // Making API call that retrieves the authentication token for the user.
                        AuthToken rootAuthToken = security.getAuthToken(getAuthTokenRoot);
                        System.out.println(username + " AUTHTOKEN = (don't log auth tokens!");
                        return rootAuthToken.getAuthInfo();
                } catch (Exception ex) {
                        System.out.println("Could not authenticate with the provided credentials " + ex.getMessage());
                }
                return null;
        }

        private void PrintBusinessInfo(BusinessInfos businessInfos) {
                if (businessInfos == null) {
                        System.out.println("No data returned");
                } else {
                        for (int i = 0; i < businessInfos.getBusinessInfo().size(); i++) {
                                System.out.println("===============================================");
                                System.out.println("Business Key: " + businessInfos.getBusinessInfo().get(i).getBusinessKey());
                                System.out.println("Name: " + ListToString(businessInfos.getBusinessInfo().get(i).getName()));

                                System.out.println("Description: " + ListToDescString(businessInfos.getBusinessInfo().get(i).getDescription()));
                                System.out.println("Services:");
                                PrintServiceInfo(businessInfos.getBusinessInfo().get(i).getServiceInfos());
                        }
                }
        }

        private String ListToString(List<Name> name) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < name.size(); i++) {
                        sb.append(name.get(i).getValue()).append(" ");
                }
                return sb.toString();
        }

        private String ListToDescString(List<Description> name) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < name.size(); i++) {
                        sb.append(name.get(i).getValue()).append(" ");
                }
                return sb.toString();
        }

        private void PrintServiceInfo(ServiceInfos serviceInfos) {
                for (int i = 0; i < serviceInfos.getServiceInfo().size(); i++) {
                        System.out.println("-------------------------------------------");
                        System.out.println("Service Key: " + serviceInfos.getServiceInfo().get(i).getServiceKey());
                        System.out.println("Owning Business Key: " + serviceInfos.getServiceInfo().get(i).getBusinessKey());
                        System.out.println("Name: " + ListToString(serviceInfos.getServiceInfo().get(i).getName()));
                }
        }

        private void PrintBusinessDetails(BusinessInfos businessInfos, String token) throws Exception {
                GetBusinessDetail gbd = new GetBusinessDetail();
                gbd.setAuthInfo(token);
                for (int i = 0; i < businessInfos.getBusinessInfo().size(); i++) {
                        gbd.getBusinessKey().add(businessInfos.getBusinessInfo().get(i).getBusinessKey());
                }
                BusinessDetail businessDetail = inquiry.getBusinessDetail(gbd);
                for (int i = 0; i < businessDetail.getBusinessEntity().size(); i++) {
                        System.out.println("Business Detail - key: " + businessDetail.getBusinessEntity().get(i).getBusinessKey());
                        System.out.println("Name: " + ListToString(businessDetail.getBusinessEntity().get(i).getName()));
                        System.out.println("CategoryBag: " + CatBagToString(businessDetail.getBusinessEntity().get(i).getCategoryBag()));
                        PrintContacts(businessDetail.getBusinessEntity().get(i).getContacts());
                }
        }

        private void PrintServiceDetailsByBusiness(BusinessInfos businessInfos, String token) throws Exception {
                for (int i = 0; i < businessInfos.getBusinessInfo().size(); i++) {
                        GetServiceDetail gsd = new GetServiceDetail();
                        for (int k = 0; k < businessInfos.getBusinessInfo().get(i).getServiceInfos().getServiceInfo().size(); k++) {
                                gsd.getServiceKey().add(businessInfos.getBusinessInfo().get(i).getServiceInfos().getServiceInfo().get(k).getServiceKey());
                        }
                        gsd.setAuthInfo(token);
                        System.out.println("Fetching data for business " + businessInfos.getBusinessInfo().get(i).getBusinessKey());
                        ServiceDetail serviceDetail = inquiry.getServiceDetail(gsd);
                        for (int k = 0; k < serviceDetail.getBusinessService().size(); k++) {
                                PrintServiceDetail(serviceDetail.getBusinessService().get(k));
                        }
                        System.out.println("................");

                }
        }
}


text:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;

namespace RNCryptor
{
	public enum Schema : short {V0, V1, V2, V3};
	public enum AesMode : short {CTR, CBC};
	public enum Pbkdf2Prf : short {SHA1};
	public enum HmacAlgorithm : short {SHA1, SHA256};
	public enum Algorithm : short {AES};
	public enum Options : short {V0, V1};

	public struct PayloadComponents {
		public byte[] schema;
		public byte[] options;
		public byte[] salt;
		public byte[] hmacSalt;
		public byte[] iv;
		public int headerLength;
		public byte[] hmac;
		public byte[] ciphertext;
	};

	abstract public class Cryptor
	{
		protected AesMode aesMode;
		protected Options options;
		protected bool hmac_includesHeader;
		protected bool hmac_includesPadding;
		protected HmacAlgorithm hmac_algorithm;

		protected const Algorithm algorithm = Algorithm.AES;
		protected const short saltLength = 8;
		protected const short ivLength = 16;
		protected const Pbkdf2Prf pbkdf2_prf = Pbkdf2Prf.SHA1;
		protected const int pbkdf2_iterations = 10000;
		protected const short pbkdf2_keyLength = 32;
		protected const short hmac_length = 32;

        /// <summary>
        ///Gets or sets the Encoding
        /// </summary>
        public Encoding TextEncoding { set; get; }

	    public Cryptor()
	    {
            // set default encoding for UTF8
	        TextEncoding = Encoding.UTF8;
	    }

		protected void configureSettings(Schema schemaVersion)
		{
			switch (schemaVersion) {
			    case Schema.V0:
				    aesMode = AesMode.CTR;
				    options = Options.V0;
				    hmac_includesHeader = false;
				    hmac_includesPadding = true;
				    hmac_algorithm = HmacAlgorithm.SHA1;
				    break;

			    case Schema.V1:
				    aesMode = AesMode.CBC;
				    options = Options.V1;
				    hmac_includesHeader = false;
				    hmac_includesPadding = false;
				    hmac_algorithm = HmacAlgorithm.SHA256;
				    break;

			    case Schema.V2:
                case Schema.V3:
				    aesMode = AesMode.CBC;
				    options = Options.V1;
				    hmac_includesHeader = true;
				    hmac_includesPadding = false;
				    hmac_algorithm = HmacAlgorithm.SHA256;
				    break;
			}
		}

		protected byte[] generateHmac (PayloadComponents components, string password)
		{
			List<byte> hmacMessage = new List<byte>();
			if (this.hmac_includesHeader) {
				hmacMessage.AddRange (this.assembleHeader(components));
			}
			hmacMessage.AddRange (components.ciphertext);

			byte[] key = this.generateKey (components.hmacSalt, password);

			HMAC hmacAlgo = null;
			switch (this.hmac_algorithm) {
				case HmacAlgorithm.SHA1:
					hmacAlgo = new HMACSHA1(key);
					break;

				case HmacAlgorithm.SHA256:
					hmacAlgo = new HMACSHA256(key);
					break;
			}
			List<byte> hmac = new List<byte>();
			hmac.AddRange (hmacAlgo.ComputeHash(hmacMessage.ToArray()));

			if (this.hmac_includesPadding) {
				for (int i = hmac.Count; i < Cryptor.hmac_length; i++) {
					hmac.Add (0x00);
				}
			}

			return hmac.ToArray ();
		}

		protected byte[] assembleHeader (PayloadComponents components)
		{
			List<byte> headerBytes = new List<byte>();
			headerBytes.AddRange (components.schema);
			headerBytes.AddRange (components.options);
			headerBytes.AddRange (components.salt);
			headerBytes.AddRange (components.hmacSalt);
			headerBytes.AddRange (components.iv);

			return headerBytes.ToArray();
		}

		protected byte[] generateKey (byte[] salt, string password)
		{
			var pbkdf2 = new Rfc2898DeriveBytes(password, salt, Cryptor.pbkdf2_iterations);
			return pbkdf2.GetBytes (Cryptor.pbkdf2_keyLength);
		}

		protected byte[] encryptAesCtrLittleEndianNoPadding (byte[] plaintextBytes, byte[] key, byte[] iv)
		{
			byte[] counter = this.computeAesCtrLittleEndianCounter(plaintextBytes.Length, iv);
			byte[] encrypted = this.encryptAesEcbNoPadding(counter, key);
			return this.bitwiseXOR(plaintextBytes, encrypted);
		}

		private byte[] computeAesCtrLittleEndianCounter (int payloadLength, byte[] iv)
		{
			byte[] incrementedIv = new byte[iv.Length];
			iv.CopyTo(incrementedIv, 0);

			int blockCount = (int)Math.Ceiling ((decimal)payloadLength / (decimal)iv.Length);

			List<byte> counter = new List<byte>();

			for (int i = 0; i < blockCount; ++i) {
				counter.AddRange (incrementedIv);

				// Yes, the next line only ever increments the first character
				// of the counter string, ignoring overflow conditions.  This
				// matches CommonCrypto's behavior!
				incrementedIv[0]++;
			}

			return counter.ToArray();
		}

		private byte[] encryptAesEcbNoPadding (byte[] plaintext, byte[] key)
		{
			byte[] encrypted;

			var aes = Aes.Create();
			aes.Mode = CipherMode.ECB;
			aes.Padding = PaddingMode.None;
			var encryptor = aes.CreateEncryptor(key, null);

			using (var ms = new MemoryStream())
			{
				using (var cs1 = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) {
					cs1.Write(plaintext, 0, plaintext.Length);
				}
				encrypted = ms.ToArray();
			}
			return encrypted;
		}

		private byte[] bitwiseXOR (byte[] first, byte[] second)
		{
			byte[] output = new byte[first.Length];
			ulong klen = (ulong)second.Length;
			ulong vlen = (ulong)first.Length;
			ulong k = 0;
			ulong v = 0;
			for (; v < vlen; v++) {
				output[v] = (byte)(first[v] ^ second[k]);
				k = (++k < klen ? k : 0);
			}
			return output;
		}

		protected string hex_encode (byte[] input)
		{
			string hex = "";
			foreach (byte c in input)
			{
				hex += String.Format("{0:x2}", c);
			}
			return hex;
		}

	}

}


text:
module System.Console.Ansigraph.Internal.Matrix (
    matShow
  , displayMat
  , displayCMat
) where

import System.Console.Ansigraph.Internal.Core

import Data.Complex
import Data.List (intersperse)
import Control.Monad.IO.Class (MonadIO, liftIO)
-- for GHC <= 7.8
import Control.Applicative

---- Matrices ----

mmap :: (a -> b) -> [[a]] -> [[b]]
mmap = map . map

mmax :: (Num a, Ord a) => [[a]] -> a
mmax = maximum . map maximum . mmap abs

densityChars = "█▓▒░"

densityVals :: [Double]
densityVals = (+ 0.125) . (/4) <$> [3,2,1,0]
         -- = [7/8, 5/8, 3/8, 1/8]

blocks :: [(Double,Char)]
blocks = zip densityVals densityChars

data MatElement = MatElement !Bool {-# UNPACK #-} !Char

elemChar :: MatElement -> Char
elemChar (MatElement _ c) = c

putRealElement :: MonadIO m => GraphSettings -> MatElement -> m ()
putRealElement s (MatElement b c) = colorStr clring (c : " ")
  where clr    = if b then realNegColor s else realColor s
        clring = mkColoring clr (realBG s)

putImagElement :: MonadIO m => GraphSettings -> MatElement -> m ()
putImagElement s (MatElement b c) = colorStr clring $ c : " "
  where clr    = if b then imagNegColor s else imagColor s
        clring = mkColoring clr (imagBG s)

selectMatElement :: Double -> MatElement
selectMatElement x = let l = filter (\p -> fst p < abs x) blocks in case l of
  []    -> MatElement False   ' '
  (p:_) -> MatElement (x < 0) (snd p)

matElements :: [[Double]] -> [[MatElement]]
matElements m = let mx = mmax m
                in  mmap (selectMatElement . (/ mx)) m

-- | Given a matrix of Doubles, return the list of strings illustrating the absolute value
--   of each entry relative to the largest, via unicode chars that denote a particular density.
--   Used for testing purposes.
matShow :: [[Double]] -> [String]
matShow = mmap elemChar . matElements

newline = putStrLn' ""

intersperse' x l = intersperse x l ++ [x]

-- | Use ANSI coloring (specified by an 'GraphSettings') to visually display a Real matrix.
displayMat :: MonadIO m => GraphSettings -> [[Double]] -> m ()
displayMat s = liftIO . sequence_ . concat . intersperse' [newline] . displayRealMat s

-- | Use ANSI coloring (specified by a 'GraphSettings') to visually display a Real matrix.
displayRealMat :: MonadIO m => GraphSettings -> [[Double]] -> [[m ()]]
displayRealMat s = mmap (putRealElement s) . matElements

-- | Use ANSI coloring (specified by a 'GraphSettings') to visually display a Real matrix.
displayImagMat :: MonadIO m => GraphSettings -> [[Double]] -> [[m ()]]
displayImagMat s = mmap (putImagElement s) . matElements

-- | Use ANSI coloring (specified by an 'GraphSettings') to visually display a Complex matrix.
displayCMat :: MonadIO m => GraphSettings -> [[Complex Double]] -> m ()
displayCMat s m = liftIO . sequence_ . concat . intersperse' [newline] $
  zipWith (\xs ys -> xs ++ putStr " " : ys)
          (displayRealMat s $ mmap realPart m)
          (displayImagMat s $ mmap imagPart m)


text:
module GHCApi (
    withGHC
  , withGHCDummyFile
  , initializeFlags
  , initializeFlagsWithCradle
  , setTargetFile
  , getDynamicFlags
  , checkSlowAndSet
  ) where

import CabalApi
import Control.Applicative
import Control.Exception
import Control.Monad
import CoreMonad
import Data.Maybe (isJust)
import DynFlags
import ErrMsg
import Exception
import GHC
import GHC.Paths (libdir)
import System.Exit
import System.IO
import Types

----------------------------------------------------------------

withGHCDummyFile :: Alternative m => Ghc (m a) -> IO (m a)
withGHCDummyFile = withGHC "Dummy"

withGHC :: Alternative m => FilePath -> Ghc (m a) -> IO (m a)
withGHC file body = ghandle ignore $ runGhc (Just libdir) $ do
    dflags <- getSessionDynFlags
    defaultCleanupHandler dflags body
  where
    ignore :: Alternative m => SomeException -> IO (m a)
    ignore e = do
        hPutStr stderr $ file ++ ":0:0:Error:"
        hPrint stderr e
        exitSuccess

----------------------------------------------------------------

importDirs :: [IncludeDir]
importDirs = [".","..","../..","../../..","../../../..","../../../../.."]

initializeFlagsWithCradle :: Options -> Cradle -> [GHCOption] -> Bool -> Ghc LogReader
initializeFlagsWithCradle opt cradle ghcOptions logging
  | cabal     = do
      (gopts,idirs,depPkgs) <- liftIO $ fromCabalFile ghcOptions cradle
      initSession opt gopts idirs (Just depPkgs) logging
  | otherwise =
      initSession opt ghcOptions importDirs Nothing logging
  where
    cabal = isJust $ cradleCabalFile cradle

----------------------------------------------------------------

initSession :: Options
            -> [GHCOption]
            -> [IncludeDir]
            -> Maybe [Package]
            -> Bool
            -> Ghc LogReader
initSession opt cmdOpts idirs mDepPkgs logging = do
    dflags0 <- getSessionDynFlags
    (dflags1,readLog) <- setupDynamicFlags dflags0
    _ <- setSessionDynFlags dflags1
    return readLog
  where
    setupDynamicFlags df0 = do
        df1 <- modifyFlagsWithOpts df0 cmdOpts
        let fast = True
        let df2 = modifyFlags df1 idirs mDepPkgs fast (expandSplice opt)
        df3 <- modifyFlagsWithOpts df2 $ ghcOpts opt
        liftIO $ setLogger logging df3

----------------------------------------------------------------

initializeFlags :: Options -> Ghc ()
initializeFlags opt = do
    dflags0 <- getSessionDynFlags
    dflags1 <- modifyFlagsWithOpts dflags0 $ ghcOpts opt
    void $ setSessionDynFlags dflags1

----------------------------------------------------------------

-- FIXME removing Options
modifyFlags :: DynFlags -> [IncludeDir] -> Maybe [Package] -> Bool -> Bool -> DynFlags
modifyFlags d0 idirs mDepPkgs fast splice
  | splice    = setSplice d3
  | otherwise = d3
  where
    d1 = d0 { importPaths = idirs }
    d2 = setFastOrNot d1 fast
    d3 = maybe d2 (addDevPkgs d2) mDepPkgs

setSplice :: DynFlags -> DynFlags
setSplice dflag = dopt_set dflag Opt_D_dump_splices

addDevPkgs :: DynFlags -> [Package] -> DynFlags
addDevPkgs df pkgs = df''
  where
    df' = dopt_set df Opt_HideAllPackages
    df'' = df' {
        packageFlags = map ExposePackage pkgs ++ packageFlags df
      }

----------------------------------------------------------------

setFastOrNot :: DynFlags -> Bool -> DynFlags
setFastOrNot dflags False = dflags {
    ghcLink   = LinkInMemory
  , hscTarget = HscInterpreted
  }
setFastOrNot dflags True = dflags {
    ghcLink   = NoLink
  , hscTarget = HscNothing
  }

setSlowDynFlags :: Ghc ()
setSlowDynFlags = (flip setFastOrNot False <$> getSessionDynFlags)
                  >>= void . setSessionDynFlags

-- To check TH, a session module graph is necessary.
-- "load" sets a session module graph using "depanal".
-- But we have to set "-fno-code" to DynFlags before "load".
-- So, this is necessary redundancy.
checkSlowAndSet :: Ghc ()
checkSlowAndSet = do
    slow <- needsTemplateHaskell <$> depanal [] False
    when slow setSlowDynFlags

----------------------------------------------------------------

modifyFlagsWithOpts :: DynFlags -> [String] -> Ghc DynFlags
modifyFlagsWithOpts dflags cmdOpts =
    tfst <$> parseDynamicFlags dflags (map noLoc cmdOpts)
  where
    tfst (a,_,_) = a

----------------------------------------------------------------

setTargetFile :: (GhcMonad m) => String -> m ()
setTargetFile file = do
    target <- guessTarget file Nothing
    setTargets [target]

----------------------------------------------------------------

getDynamicFlags :: IO DynFlags
getDynamicFlags = runGhc (Just libdir) getSessionDynFlags


text:
<TITLE>Review for Bean (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Bean (1997)

reviewed by
Steve Kong

BEAN (1997)

A film review by Steve Kong
Copyright 1997 Steve Kong

Mr. Bean is an internationally known character, but like all
internationally known things he's not as well known here in the US. Sure,
he has been shown on PBS from time to time, but for most of us, who's Mr.
Bean? Mr. Bean is a clumsy bumbling soft mumbling man. The hilarious Rowan
Atkinson portrays him.

In Bean, Mr. Bean (Rowan Atkinson) is a guard of some sort, though I could
be wrong because the position is unspecified, at the London National Art
Gallery. When a rich man in the US donates enough money to buy back the
Whistler's Mother from the London National Art Gallery, the US Grierson
Gallery requests that an expert accompany it to introduce it to the public.
What the Gallery gets is Mr. Bean. The curator of the Gallery (Peter
MacNicol) unknowingly volunteers to host Mr. Bean at his house, to the
dismay of his family and wife (Pamela Reed).

Rowan Atkinson is a great physical comedian who is funny but not annoying
(as with the case of Jim Carrey). The comedy bits in Bean are hilarious and
most of them had me laughing out loud. The problem was that there was too
much quiet time between the bits. Taking a TV show that's based on short
skits and stretching that out to a 90 minute feature film is a tough thing
to do. Though Bean comes close to pulling it off it fails in two ways.

The first is that there are, like I said, too many quiet moments between
the comedy bits. These expository moments put the movie into the real world
setting and this leads to the second reason why Bean fails. The Mr. Bean
character is a character that lives best in his own world. The things that
he does do not live too well in the real world, and by taking the Mr. Bean
character and sticking him in the real world, it takes a lot away from the
comedy. The most apparent place where the comedy just feels awful because
it's set in the real world is the hospital scene. If that had been done in
Mr. Bean's world, it would have been hilarious, but as it is in the film,
there is a kind of uneasy that follows the scene.

But, don't get me wrong, Bean is a funny funny movie that in parts almost
had me in tears laughing. These scenes include Bean in the restroom, Bean
at the park, and Bean with a turkey. Rowan Atkinson is perfect as Mr. Bean.
I would recommend seeing Bean during a matinee showing, it is good silly
fun that is somewhat flawed.

!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!
 steve kong                                        reviews@boiled.sbay.org
           find the latest movie reviews at
           the hard boiled movie page
           http://boiled.sbay.org/boiled/
!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!=!

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


text:
package org.hisp.dhis.datavalue;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.List;

import org.hisp.dhis.DhisSpringTest;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.hisp.dhis.dataelement.DataElementService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.Period;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Sets;

/**
 * @author Kristian Nordal
 */
public class DataValueServiceTest
    extends DhisSpringTest
{
    @Autowired
    private DataElementCategoryService categoryService;

    @Autowired
    private DataElementService dataElementService;

    @Autowired
    private DataValueService dataValueService;

    @Autowired
    private OrganisationUnitService organisationUnitService;

    // -------------------------------------------------------------------------
    // Supporting data
    // -------------------------------------------------------------------------

    private DataElement dataElementA;
    private DataElement dataElementB;
    private DataElement dataElementC;
    private DataElement dataElementD;

    private DataElementCategoryOptionCombo optionCombo;

    private Period periodA;
    private Period periodB;
    private Period periodC;

    private OrganisationUnit sourceA;
    private OrganisationUnit sourceB;
    private OrganisationUnit sourceC;
    private OrganisationUnit sourceD;

    // -------------------------------------------------------------------------
    // Set up/tear down
    // -------------------------------------------------------------------------

    @Override
    public void setUpTest()
        throws Exception
    {
        // ---------------------------------------------------------------------
        // Add supporting data
        // ---------------------------------------------------------------------

        dataElementA = createDataElement( 'A' );
        dataElementB = createDataElement( 'B' );
        dataElementC = createDataElement( 'C' );
        dataElementD = createDataElement( 'D' );

        dataElementService.addDataElement( dataElementA );
        dataElementService.addDataElement( dataElementB );
        dataElementService.addDataElement( dataElementC );
        dataElementService.addDataElement( dataElementD );

        periodA = createPeriod( getDay( 5 ), getDay( 6 ) );
        periodB = createPeriod( getDay( 6 ), getDay( 7 ) );
        periodC = createPeriod( getDay( 7 ), getDay( 8 ) );

        sourceA = createOrganisationUnit( 'A' );
        sourceB = createOrganisationUnit( 'B' );
        sourceC = createOrganisationUnit( 'C' );
        sourceD = createOrganisationUnit( 'D' );

        organisationUnitService.addOrganisationUnit( sourceA );
        organisationUnitService.addOrganisationUnit( sourceB );
        organisationUnitService.addOrganisationUnit( sourceC );
        organisationUnitService.addOrganisationUnit( sourceD );

        optionCombo = categoryService.getDefaultDataElementCategoryOptionCombo();
    }

    // -------------------------------------------------------------------------
    // Basic DataValue
    // -------------------------------------------------------------------------

    @Test
    public void testAddDataValue()
    {
        DataValue dataValueA = new DataValue( dataElementA, periodA, sourceA, optionCombo, optionCombo, "1" );
        DataValue dataValueB = new DataValue( dataElementB, periodA, sourceA, optionCombo, optionCombo, "2" );
        DataValue dataValueC = new DataValue( dataElementC, periodC, sourceA, optionCombo, optionCombo, "3" );

        dataValueService.addDataValue( dataValueA );
        dataValueService.addDataValue( dataValueB );
        dataValueService.addDataValue( dataValueC );

        dataValueA = dataValueService.getDataValue( dataElementA, periodA, sourceA, optionCombo );
        assertNotNull( dataValueA );
        assertNotNull( dataValueA.getCreated() );
        assertEquals( sourceA.getId(), dataValueA.getSource().getId() );
        assertEquals( dataElementA, dataValueA.getDataElement() );
        assertEquals( periodA, dataValueA.getPeriod() );
        assertEquals( "1", dataValueA.getValue() );

        dataValueB = dataValueService.getDataValue( dataElementB, periodA, sourceA, optionCombo );
        assertNotNull( dataValueB );
        assertNotNull( dataValueB.getCreated() );
        assertEquals( sourceA.getId(), dataValueB.getSource().getId() );
        assertEquals( dataElementB, dataValueB.getDataElement() );
        assertEquals( periodA, dataValueB.getPeriod() );
        assertEquals( "2", dataValueB.getValue() );

        dataValueC = dataValueService.getDataValue( dataElementC, periodC, sourceA, optionCombo );
        assertNotNull( dataValueC );
        assertNotNull( dataValueC.getCreated() );
        assertEquals( sourceA.getId(), dataValueC.getSource().getId() );
        assertEquals( dataElementC, dataValueC.getDataElement() );
        assertEquals( periodC, dataValueC.getPeriod() );
        assertEquals( "3", dataValueC.getValue() );
    }

    @Test
    public void testUpdataDataValue()
    {
        DataValue dataValueA = new DataValue( dataElementA, periodA, sourceA, optionCombo, optionCombo, "1" );
        DataValue dataValueB = new DataValue( dataElementB, periodA, sourceB, optionCombo, optionCombo, "2" );

        dataValueService.addDataValue( dataValueA );
        dataValueService.addDataValue( dataValueB );

        assertNotNull( dataValueService.getDataValue( dataElementA, periodA, sourceA, optionCombo ) );
        assertNotNull( dataValueService.getDataValue( dataElementB, periodA, sourceB, optionCombo ) );

        dataValueA.setValue( "5" );
        dataValueService.updateDataValue( dataValueA );

        dataValueA = dataValueService.getDataValue( dataElementA, periodA, sourceA, optionCombo );
        assertNotNull( dataValueA );
        assertEquals( "5", dataValueA.getValue() );

        dataValueB = dataValueService.getDataValue( dataElementB, periodA, sourceB, optionCombo );
        assertNotNull( dataValueB );
        assertEquals( "2", dataValueB.getValue() );
    }

    @Test
    public void testDeleteAndGetDataValue()
    {
        DataValue dataValueA = new DataValue( dataElementA, periodA, sourceA, optionCombo, optionCombo, "1" );
        DataValue dataValueB = new DataValue( dataElementB, periodA, sourceA, optionCombo, optionCombo, "2" );
        DataValue dataValueC = new DataValue( dataElementC, periodC, sourceD, optionCombo, optionCombo, "3" );
        DataValue dataValueD = new DataValue( dataElementD, periodC, sourceB, optionCombo, optionCombo, "4" );

        dataValueService.addDataValue( dataValueA );
        dataValueService.addDataValue( dataValueB );
        dataValueService.addDataValue( dataValueC );
        dataValueService.addDataValue( dataValueD );

        assertNotNull( dataValueService.getDataValue( dataElementA, periodA, sourceA, optionCombo ) );
        assertNotNull( dataValueService.getDataValue( dataElementB, periodA, sourceA, optionCombo ) );
        assertNotNull( dataValueService.getDataValue( dataElementC, periodC, sourceD, optionCombo ) );
        assertNotNull( dataValueService.getDataValue( dataElementD, periodC, sourceB, optionCombo ) );

        dataValueService.deleteDataValue( dataValueA );
        assertNull( dataValueService.getDataValue( dataElementA, periodA, sourceA, optionCombo ) );
        assertNotNull( dataValueService.getDataValue( dataElementB, periodA, sourceA, optionCombo ) );
        assertNotNull( dataValueService.getDataValue( dataElementC, periodC, sourceD, optionCombo ) );
        assertNotNull( dataValueService.getDataValue( dataElementD, periodC, sourceB, optionCombo ) );

        dataValueService.deleteDataValue( dataValueB );
        assertNull( dataValueService.getDataValue( dataElementA, periodA, sourceA, optionCombo ) );
        assertNull( dataValueService.getDataValue( dataElementB, periodA, sourceA, optionCombo ) );
        assertNotNull( dataValueService.getDataValue( dataElementC, periodC, sourceD, optionCombo ) );
        assertNotNull( dataValueService.getDataValue( dataElementD, periodC, sourceB, optionCombo ) );

        dataValueService.deleteDataValue( dataValueC );
        assertNull( dataValueService.getDataValue( dataElementA, periodA, sourceA, optionCombo ) );
        assertNull( dataValueService.getDataValue( dataElementB, periodA, sourceA, optionCombo ) );
        assertNull( dataValueService.getDataValue( dataElementC, periodC, sourceD, optionCombo ) );
        assertNotNull( dataValueService.getDataValue( dataElementD, periodC, sourceB, optionCombo ) );

        dataValueService.deleteDataValue( dataValueD );
        assertNull( dataValueService.getDataValue( dataElementA, periodA, sourceA, optionCombo ) );
        assertNull( dataValueService.getDataValue( dataElementB, periodA, sourceA, optionCombo ) );
        assertNull( dataValueService.getDataValue( dataElementC, periodC, sourceD, optionCombo ) );
        assertNull( dataValueService.getDataValue( dataElementD, periodC, sourceB, optionCombo ) );
    }

    // -------------------------------------------------------------------------
    // Collections of DataValues
    // -------------------------------------------------------------------------

    @Test
    public void testGetDataValuesDataExportParamsA()
    {
        DataValue dataValueA = new DataValue( dataElementA, periodA, sourceA, optionCombo, optionCombo, "1" );
        DataValue dataValueB = new DataValue( dataElementA, periodA, sourceB, optionCombo, optionCombo, "2" );
        DataValue dataValueC = new DataValue( dataElementA, periodB, sourceA, optionCombo, optionCombo, "3" );
        DataValue dataValueD = new DataValue( dataElementA, periodB, sourceB, optionCombo, optionCombo, "4" );
        DataValue dataValueE = new DataValue( dataElementB, periodA, sourceA, optionCombo, optionCombo, "5" );
        DataValue dataValueF = new DataValue( dataElementB, periodA, sourceB, optionCombo, optionCombo, "6" );
        DataValue dataValueG = new DataValue( dataElementB, periodB, sourceA, optionCombo, optionCombo, "7" );
        DataValue dataValueH = new DataValue( dataElementB, periodB, sourceB, optionCombo, optionCombo, "8" );
        DataValue dataValueI = new DataValue( dataElementA, periodC, sourceA, optionCombo, optionCombo, "9" );
        DataValue dataValueJ = new DataValue( dataElementA, periodC, sourceB, optionCombo, optionCombo, "10" );

        dataValueService.addDataValue( dataValueA );
        dataValueService.addDataValue( dataValueB );
        dataValueService.addDataValue( dataValueC );
        dataValueService.addDataValue( dataValueD );
        dataValueService.addDataValue( dataValueE );
        dataValueService.addDataValue( dataValueF );
        dataValueService.addDataValue( dataValueG );
        dataValueService.addDataValue( dataValueH );
        dataValueService.addDataValue( dataValueI );
        dataValueService.addDataValue( dataValueJ );

        DataExportParams params = new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA ) )
            .setOrganisationUnits( Sets.newHashSet( sourceA ) );

        List<DataValue> values = dataValueService.getDataValues( params );

        assertEquals( 3, values.size() );
        assertTrue( values.contains( dataValueA ) );
        assertTrue( values.contains( dataValueC ) );
        assertTrue( values.contains( dataValueI ) );

        params = new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementB ) )
            .setPeriods( Sets.newHashSet( periodA ) );

        values = dataValueService.getDataValues( params );

        assertEquals( 2, values.size() );
        assertTrue( values.contains( dataValueE ) );
        assertTrue( values.contains( dataValueF ) );

        params = new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA ) )
            .setLimit( 2 );

        values = dataValueService.getDataValues( params );

        assertEquals( 2, values.size() );

        params = new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA, dataElementB ) );

        values = dataValueService.getDataValues( params );

        assertEquals( 10, values.size() );

        //TODO more tests
    }

    @Test
    public void testGetDataValuesDataExportParamsB()
    {
        DataValue dataValueA = new DataValue( dataElementA, periodA, sourceA, optionCombo, optionCombo, "1" );
        DataValue dataValueB = new DataValue( dataElementA, periodA, sourceB, optionCombo, optionCombo, "2" );
        DataValue dataValueC = new DataValue( dataElementA, periodB, sourceA, optionCombo, optionCombo, "3" );
        DataValue dataValueD = new DataValue( dataElementA, periodB, sourceB, optionCombo, optionCombo, "4" );
        DataValue dataValueE = new DataValue( dataElementB, periodA, sourceA, optionCombo, optionCombo, "5" );
        DataValue dataValueF = new DataValue( dataElementB, periodA, sourceB, optionCombo, optionCombo, "6" );
        DataValue dataValueG = new DataValue( dataElementB, periodB, sourceA, optionCombo, optionCombo, "7" );
        DataValue dataValueH = new DataValue( dataElementB, periodB, sourceB, optionCombo, optionCombo, "8" );
        DataValue dataValueI = new DataValue( dataElementA, periodC, sourceA, optionCombo, optionCombo, "9" );
        DataValue dataValueJ = new DataValue( dataElementA, periodC, sourceB, optionCombo, optionCombo, "10" );

        dataValueService.addDataValue( dataValueA );
        dataValueService.addDataValue( dataValueB );
        dataValueService.addDataValue( dataValueC );
        dataValueService.addDataValue( dataValueD );
        dataValueService.addDataValue( dataValueE );
        dataValueService.addDataValue( dataValueF );
        dataValueService.addDataValue( dataValueG );
        dataValueService.addDataValue( dataValueH );
        dataValueService.addDataValue( dataValueI );
        dataValueService.addDataValue( dataValueJ );

        assertEquals( 6, dataValueService.getDataValues( new DataExportParams().setDataElements( Sets.newHashSet( dataElementA ) ) ).size() );
        assertEquals( 4, dataValueService.getDataValues( new DataExportParams().setDataElements( Sets.newHashSet( dataElementB ) ) ).size() );

        assertEquals( 4, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA, dataElementB ) ).setPeriods( Sets.newHashSet( periodB ) ) ).size() );
        assertEquals( 2, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA, dataElementB ) ).setPeriods( Sets.newHashSet( periodA ) ).setOrganisationUnits( Sets.newHashSet( sourceB ) ) ).size() );
        assertEquals( 4, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA, dataElementB ) ).setPeriods( Sets.newHashSet( periodB ) ) ).size() );

        assertEquals( 4, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA ) ).setPeriods( Sets.newHashSet( periodA, periodC ) ) ).size() );
        assertEquals( 4, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementB ) ).setOrganisationUnits( Sets.newHashSet( sourceA, sourceB ) ) ).size() );

        assertEquals( 1, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementB ) ).setPeriods( Sets.newHashSet( periodB ) ).setOrganisationUnits( Sets.newHashSet( sourceA ) ) ).size() );
        assertEquals( 1, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA ) ).setPeriods( Sets.newHashSet( periodA ) ).setOrganisationUnits( Sets.newHashSet( sourceB ) ) ).size() );
    }

    @Test
    public void testGetAllDataValues()
    {
        DataValue dataValueA = new DataValue( dataElementA, periodA, sourceA, optionCombo, optionCombo );
        dataValueA.setValue( "1" );
        DataValue dataValueB = new DataValue( dataElementB, periodA, sourceA, optionCombo, optionCombo );
        dataValueB.setValue( "2" );
        DataValue dataValueC = new DataValue( dataElementC, periodC, sourceD, optionCombo, optionCombo );
        dataValueC.setValue( "3" );
        DataValue dataValueD = new DataValue( dataElementD, periodC, sourceB, optionCombo, optionCombo );
        dataValueD.setValue( "4" );

        dataValueService.addDataValue( dataValueA );
        dataValueService.addDataValue( dataValueB );
        dataValueService.addDataValue( dataValueC );
        dataValueService.addDataValue( dataValueD );

        List<DataValue> dataValues = dataValueService.getAllDataValues();
        assertNotNull( dataValues );
        assertEquals( 4, dataValues.size() );
    }

    @Test
    public void testGetDataValuesDataElementsPeriodsOrgUnits()
    {
        DataValue dataValueA = new DataValue( dataElementA, periodA, sourceA, optionCombo, optionCombo, "1" );
        DataValue dataValueB = new DataValue( dataElementA, periodA, sourceB, optionCombo, optionCombo, "2" );
        DataValue dataValueC = new DataValue( dataElementA, periodB, sourceA, optionCombo, optionCombo, "3" );
        DataValue dataValueD = new DataValue( dataElementA, periodB, sourceB, optionCombo, optionCombo, "4" );
        DataValue dataValueE = new DataValue( dataElementB, periodA, sourceA, optionCombo, optionCombo, "5" );
        DataValue dataValueF = new DataValue( dataElementB, periodA, sourceB, optionCombo, optionCombo, "6" );
        DataValue dataValueG = new DataValue( dataElementB, periodB, sourceA, optionCombo, optionCombo, "7" );
        DataValue dataValueH = new DataValue( dataElementB, periodB, sourceB, optionCombo, optionCombo, "8" );
        DataValue dataValueI = new DataValue( dataElementA, periodC, sourceA, optionCombo, optionCombo, "9" );
        DataValue dataValueJ = new DataValue( dataElementA, periodC, sourceB, optionCombo, optionCombo, "10" );

        dataValueService.addDataValue( dataValueA );
        dataValueService.addDataValue( dataValueB );
        dataValueService.addDataValue( dataValueC );
        dataValueService.addDataValue( dataValueD );
        dataValueService.addDataValue( dataValueE );
        dataValueService.addDataValue( dataValueF );
        dataValueService.addDataValue( dataValueG );
        dataValueService.addDataValue( dataValueH );
        dataValueService.addDataValue( dataValueI );
        dataValueService.addDataValue( dataValueJ );

        assertEquals( 6, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA ) ) ).size() );

        assertEquals( 4, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementB ) ) ).size() );

        assertEquals( 4, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA, dataElementB ) )
            .setPeriods( Sets.newHashSet( periodB ) ) ).size() );

        assertEquals( 2, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA, dataElementB ) )
            .setPeriods( Sets.newHashSet( periodA ) )
            .setOrganisationUnits( Sets.newHashSet( sourceB ) ) ).size() );

        assertEquals( 2, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA ) )
            .setPeriods( Sets.newHashSet( periodC ) ) ).size() );

        assertEquals( 4, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA ) )
            .setPeriods( Sets.newHashSet( periodA, periodC ) ) ).size() );

        assertEquals( 4, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementB ) )
            .setOrganisationUnits( Sets.newHashSet( sourceA, sourceB ) ) ).size() );

        assertEquals( 1, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementB ) )
            .setPeriods( Sets.newHashSet( periodB ) )
            .setOrganisationUnits( Sets.newHashSet( sourceA ) ) ).size() );

        assertEquals( 1, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementB ) )
            .setPeriods( Sets.newHashSet( periodB ) )
            .setOrganisationUnits( Sets.newHashSet( sourceA ) ) ).size() );

        assertEquals( 1, dataValueService.getDataValues( new DataExportParams()
            .setDataElements( Sets.newHashSet( dataElementA ) )
            .setPeriods( Sets.newHashSet( periodA ) )
            .setOrganisationUnits( Sets.newHashSet( sourceB ) ) ).size() );
    }

    @Test
    public void testGetDataValueCountLastUpdatedBetween()
    {
        DataValue dataValueA = new DataValue( dataElementA, periodA, sourceA, optionCombo, optionCombo, "1" );
        DataValue dataValueB = new DataValue( dataElementA, periodA, sourceB, optionCombo, optionCombo, "2" );
        DataValue dataValueC = new DataValue( dataElementB, periodA, sourceB, optionCombo, optionCombo, "3" );

        dataValueService.addDataValue( dataValueA );
        dataValueService.addDataValue( dataValueB );
        dataValueService.addDataValue( dataValueC );

        assertEquals( 3, dataValueService.getDataValueCountLastUpdatedBetween( getDate( 1970, 1, 1 ), null, false ) );
        assertEquals( 3, dataValueService.getDataValueCountLastUpdatedBetween( getDate( 1970, 1, 1 ), null, true ) );

        dataValueService.deleteDataValue( dataValueC );

        assertEquals( 3, dataValueService.getDataValueCountLastUpdatedBetween( getDate( 1970, 1, 1 ), null, true ) );
        assertEquals( 2, dataValueService.getDataValueCountLastUpdatedBetween( getDate( 1970, 1, 1 ), null, false ) );

        dataValueService.deleteDataValue( dataValueB );

        assertEquals( 3, dataValueService.getDataValueCountLastUpdatedBetween( getDate( 1970, 1, 1 ), null, true ) );
        assertEquals( 1, dataValueService.getDataValueCountLastUpdatedBetween( getDate( 1970, 1, 1 ), null, false ) );
    }
}