text:
var express = require('express');
var path = require('path');
var fs = require('fs');
var format = require('util').format;
var MongoClient = require('mongodb').MongoClient;
var swig  = require('swig');

var app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);
server.listen(8005);
app.use(express.static(path.join(__dirname, "/public")));
app.configure('production', function(){
    var logFile = fs.createWriteStream('planeFight.log', {flags: 'a'});
    app.use(express.logger({stream:logFile}));
});
app.configure('development', function(){
    app.use(express.logger());
});
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, '/public/templates'));
swig.setDefaults({ cache: false });

var mydb;
MongoClient.connect("mongodb://localhost:27017/planeFight", function(err, db) {
    if(err) { console.log(format('db error:%s', err)); }
    mydb = db;
});
app.get('/', function(req, res) {
    var msg = '';
    mydb.collection('rooms').find({}).toArray(function(err, rooms) {
        if(err){ msg = format('find err:%s', err); }
        res.render('index', {rooms:rooms, msg:msg});
    });
});

app.get('/:roomid/:playerNumber/create', function(req, res) {
    var roomid = req.params.roomid;
    var playerNumber = req.params.playerNumber;
    mydb.collection('rooms').insert({roomid:roomid, players:[], playerNumber:playerNumber}, {safe:true}, function(err, records) {
        if(err){ console.log(format('insert error:%s', err)); }
    });
    res.render('room', {roomid:roomid, playerNumber:playerNumber, players:[]});
});

app.get('/:roomid/:playerid/join', function(req, res) {
    var roomid = req.params.roomid;
    var playerid = req.params.playerid;
    var msg = '';
    mydb.collection('rooms').findOne({roomid:roomid}, function(err, room) {
        if(err){
            msg = format('fetch room error:%s', err);
            res.render('player', {roomid:roomid, playerid:playerid, players:room.players, msg:msg});
        }
        else {
            mydb.collection('rooms').update({roomid:roomid}, {$push:{players:playerid}}, function(err, room) {
                if(err){ msg = format('update room error:%s', err); }
                console.log('new players:'+room.players);
                res.render('player', {roomid:roomid, playerid:playerid, players:room.players, msg:msg});
            });
        }
    });
});
var roomSocket = io
    .of('/room')
    .on('connection', function (socket) {
        socket.on('createRoom', function(roomid) {
            socket.roomid = roomid;
        });
        /*socket.on('close', function() {
            console.log(format('socket closed.'));
            mydb.collection('rooms').remove({'roomid':socket.roomid});
            socket.destroy();
        });*/
    });
var playerSocket = io
    .of('/player')
    .on('connection', function (socket) {
        socket.on('addPlayer', function(idObj) {
            roomSocket.sockets.forEach(function(s) {
                if(s.roomid == idObj.roomid) {
                    s.emit('updateMsg', {playerid:idObj.playerid});
                }
            });
            socket.idObj = idObj;
        });
    });


text:
package org.scalajs.testsuite.javalib.security

import org.junit.Test

class ThrowablesTest {
  @Test def should_define_all_java_security_Errors_and_Exceptions(): Unit = {
    import java.security._
    new AccessControlException("", null)
  }
}

redpajama_set_name: RedPajamaGithub


text:
#ifdef HAVE_CONFIG_H
# include "config.h"                   /* for _GNU_SOURCE */
#endif
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <qthread/qthread.h>
#include <qthread/qtimer.h>
#include "argparsing.h"

#include <pthread.h>

#define NUM_THREADS 1000000

static aligned_t qincr(void *arg)
{
    return 0;
}

int main(int argc, char *argv[])
{
    aligned_t rets[NUM_THREADS];
    qtimer_t timer = qtimer_create();
    double cumulative_time = 0.0;

    if (qthread_initialize() != QTHREAD_SUCCESS) {
        fprintf(stderr, "qthread library could not be initialized!\n");
        exit(EXIT_FAILURE);
    }
    CHECK_VERBOSE();

    for (int iteration = 0; iteration < 10; iteration++) {
        qtimer_start(timer);
        for (int i = 0; i < NUM_THREADS; i++) {
            qthread_fork(qincr, NULL, &(rets[i]));
        }
        for (int i = 0; i < NUM_THREADS; i++) {
            qthread_readFF(NULL, &(rets[i]));
        }
        qtimer_stop(timer);
        iprintf("\ttest iteration %i: %f secs\n", iteration,
                qtimer_secs(timer));
        cumulative_time += qtimer_secs(timer);
    }
    printf("qthread time: %f\n", cumulative_time / 10.0);

    return 0;
}

/* vim:set expandtab */


text:
package com.google.android.exoplayer2.offline;

import static com.google.android.exoplayer2.offline.DownloadRequest.TYPE_PROGRESSIVE;
import static com.google.common.truth.Truth.assertThat;

import android.net.Uri;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.database.ExoDatabaseProvider;
import com.google.android.exoplayer2.testutil.TestUtil;
import com.google.android.exoplayer2.util.Util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

/** Unit tests for {@link ActionFileUpgradeUtil}. */
@RunWith(AndroidJUnit4.class)
public class ActionFileUpgradeUtilTest {

  private static final long NOW_MS = 1234;

  private File tempFile;
  private ExoDatabaseProvider databaseProvider;
  private DefaultDownloadIndex downloadIndex;

  @Before
  public void setUp() throws Exception {
    tempFile = Util.createTempFile(ApplicationProvider.getApplicationContext(), "ExoPlayerTest");
    databaseProvider = new ExoDatabaseProvider(ApplicationProvider.getApplicationContext());
    downloadIndex = new DefaultDownloadIndex(databaseProvider);
  }

  @After
  public void tearDown() {
    databaseProvider.close();
    tempFile.delete();
  }

  @Test
  public void upgradeAndDelete_createsDownloads() throws IOException {
    // Copy the test asset to a file.
    byte[] actionFileBytes =
        TestUtil.getByteArray(
            ApplicationProvider.getApplicationContext(),
            "offline/action_file_for_download_index_upgrade.exi");
    try (FileOutputStream output = new FileOutputStream(tempFile)) {
      output.write(actionFileBytes);
    }

    StreamKey expectedStreamKey1 =
        new StreamKey(/* periodIndex= */ 3, /* groupIndex= */ 4, /* trackIndex= */ 5);
    StreamKey expectedStreamKey2 =
        new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 1, /* trackIndex= */ 2);
    DownloadRequest expectedRequest1 =
        new DownloadRequest(
            "key123",
            /* type= */ "test",
            Uri.parse("https://www.test.com/download1"),
            asList(expectedStreamKey1),
            /* customCacheKey= */ "key123",
            new byte[] {1, 2, 3, 4});
    DownloadRequest expectedRequest2 =
        new DownloadRequest(
            "key234",
            /* type= */ "test",
            Uri.parse("https://www.test.com/download2"),
            asList(expectedStreamKey2),
            /* customCacheKey= */ "key234",
            new byte[] {5, 4, 3, 2, 1});

    ActionFileUpgradeUtil.upgradeAndDelete(
        tempFile,
        /* downloadIdProvider= */ null,
        downloadIndex,
        /* deleteOnFailure= */ true,
        /* addNewDownloadsAsCompleted= */ false);

    assertDownloadIndexContainsRequest(expectedRequest1, Download.STATE_QUEUED);
    assertDownloadIndexContainsRequest(expectedRequest2, Download.STATE_QUEUED);
  }

  @Test
  public void mergeRequest_nonExistingDownload_createsNewDownload() throws IOException {
    byte[] data = new byte[] {1, 2, 3, 4};
    DownloadRequest request =
        new DownloadRequest(
            "id",
            TYPE_PROGRESSIVE,
            Uri.parse("https://www.test.com/download"),
            asList(
                new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 1, /* trackIndex= */ 2),
                new StreamKey(/* periodIndex= */ 3, /* groupIndex= */ 4, /* trackIndex= */ 5)),
            /* customCacheKey= */ "key123",
            data);

    ActionFileUpgradeUtil.mergeRequest(
        request, downloadIndex, /* addNewDownloadAsCompleted= */ false, NOW_MS);

    assertDownloadIndexContainsRequest(request, Download.STATE_QUEUED);
  }

  @Test
  public void mergeRequest_existingDownload_createsMergedDownload() throws IOException {
    StreamKey streamKey1 =
        new StreamKey(/* periodIndex= */ 3, /* groupIndex= */ 4, /* trackIndex= */ 5);
    StreamKey streamKey2 =
        new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 1, /* trackIndex= */ 2);
    DownloadRequest request1 =
        new DownloadRequest(
            "id",
            TYPE_PROGRESSIVE,
            Uri.parse("https://www.test.com/download1"),
            asList(streamKey1),
            /* customCacheKey= */ "key123",
            new byte[] {1, 2, 3, 4});
    DownloadRequest request2 =
        new DownloadRequest(
            "id",
            TYPE_PROGRESSIVE,
            Uri.parse("https://www.test.com/download2"),
            asList(streamKey2),
            /* customCacheKey= */ "key123",
            new byte[] {5, 4, 3, 2, 1});
    ActionFileUpgradeUtil.mergeRequest(
        request1, downloadIndex, /* addNewDownloadAsCompleted= */ false, NOW_MS);
    ActionFileUpgradeUtil.mergeRequest(
        request2, downloadIndex, /* addNewDownloadAsCompleted= */ false, NOW_MS);

    Download download = downloadIndex.getDownload(request2.id);
    assertThat(download).isNotNull();
    assertThat(download.request.type).isEqualTo(request2.type);
    assertThat(download.request.customCacheKey).isEqualTo(request2.customCacheKey);
    assertThat(download.request.data).isEqualTo(request2.data);
    assertThat(download.request.uri).isEqualTo(request2.uri);
    assertThat(download.request.streamKeys).containsExactly(streamKey1, streamKey2);
    assertThat(download.state).isEqualTo(Download.STATE_QUEUED);
  }

  @Test
  public void mergeRequest_addNewDownloadAsCompleted() throws IOException {
    StreamKey streamKey1 =
        new StreamKey(/* periodIndex= */ 3, /* groupIndex= */ 4, /* trackIndex= */ 5);
    StreamKey streamKey2 =
        new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 1, /* trackIndex= */ 2);
    DownloadRequest request1 =
        new DownloadRequest(
            "id1",
            TYPE_PROGRESSIVE,
            Uri.parse("https://www.test.com/download1"),
            asList(streamKey1),
            /* customCacheKey= */ "key123",
            new byte[] {1, 2, 3, 4});
    DownloadRequest request2 =
        new DownloadRequest(
            "id2",
            TYPE_PROGRESSIVE,
            Uri.parse("https://www.test.com/download2"),
            asList(streamKey2),
            /* customCacheKey= */ "key123",
            new byte[] {5, 4, 3, 2, 1});
    ActionFileUpgradeUtil.mergeRequest(
        request1, downloadIndex, /* addNewDownloadAsCompleted= */ false, NOW_MS);

    // Merging existing download, keeps it queued.
    ActionFileUpgradeUtil.mergeRequest(
        request1, downloadIndex, /* addNewDownloadAsCompleted= */ true, NOW_MS);
    assertThat(downloadIndex.getDownload(request1.id).state).isEqualTo(Download.STATE_QUEUED);

    // New download is merged as completed.
    ActionFileUpgradeUtil.mergeRequest(
        request2, downloadIndex, /* addNewDownloadAsCompleted= */ true, NOW_MS);
    assertThat(downloadIndex.getDownload(request2.id).state).isEqualTo(Download.STATE_COMPLETED);
  }

  private void assertDownloadIndexContainsRequest(DownloadRequest request, int state)
      throws IOException {
    Download download = downloadIndex.getDownload(request.id);
    assertThat(download.request).isEqualTo(request);
    assertThat(download.state).isEqualTo(state);
  }

  private static List<StreamKey> asList(StreamKey... streamKeys) {
    return Arrays.asList(streamKeys);
  }
}


text:
package dev.kkorolyov.simplefuncs.stream;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Objects;

import static java.util.Collections.singleton;

/**
 * Additional utility methods for generating or otherwise working with {@link Iterable}s.
 */
public final class Iterables {
	private Iterables() {}

	/**
	 * Checks whether two iterables are composed of the same elements in the same iteration order.
	 * @param iterable first iterable
	 * @param iterable1 second iterable
	 * @return whether {@code iterable} and {@code iterable1} are composed of the same elements in the same iteration order
	 */
	public static boolean matches(Iterable<?> iterable, Iterable<?> iterable1) {
		Iterator<?> it = iterable.iterator();
		Iterator<?> it1 = iterable1.iterator();

		while (it.hasNext() && it1.hasNext()) {
			if (!Objects.equals(it.next(), it1.next())) return false;
		}
		return !(it.hasNext() || it1.hasNext());
	}

	/** @see #concat(Iterable) */
	@SafeVarargs
	public static <T> Iterable<T> concat(Iterable<? extends T>... iterables) {
		return concat(Arrays.asList(iterables));
	}
	/**
	 * Returns an iterable which iterates over all elements of the given iterables in sequence.
	 * @param iterables iterables to iterate
	 * @param <T> iterated elements type
	 * @return iterable which iterates over all {@code iterables} in sequence
	 */
	public static <T> Iterable<T> concat(Iterable<Iterable<? extends T>> iterables) {
		return () -> new MultiIterator<>(iterables);
	}

	/**
	 * Convenience overload of {@link #append(Iterable, Object[])} for "at least one" var-args usages.
	 * @see #append(Iterable, Object[])
	 */
	@SafeVarargs
	public static <T> Iterable<T> append(T initial, T... others) {
		return append(singleton(initial), others);
	}
	/**
	 * Returns an iterable which iterates first over all elements in {@code iterable}, then over all {@code others}
	 * @param initial initial iterable to iterate
	 * @param others subsequent elements to iterate
	 * @param <T> iterated element type
	 * @return iterable which iterates over {@code iterable} elements, then over {@code others}
	 */
	@SafeVarargs
	public static <T> Iterable<T> append(Iterable<? extends T> initial, T... others) {
		return () -> new ExtraArrayIterator<>(initial.iterator(), others);
	}

	private static class MultiIterator<T> implements Iterator<T> {
		private final Iterator<Iterable<? extends T>> delegates;
		private Iterator<? extends T> current;

		MultiIterator(Iterable<Iterable<? extends T>> delegates) {
			this.delegates = delegates.iterator();
		}

		@Override
		public boolean hasNext() {
			return (current != null && current.hasNext())
					|| findNext();
		}
		@Override
		public T next() {
			if (current == null || !current.hasNext()) findNext();
			return current.next();
		}

		private boolean findNext() {
			while (current == null || !current.hasNext()) {
				if (delegates.hasNext()) {
					current = delegates.next().iterator();
				} else {
					return false;
				}
			}
			return true;
		}
	}

	private static class ExtraArrayIterator<T> implements Iterator<T> {
		private final Iterator<? extends T> delegate;
		private final T[] array;
		private int arrayIndex;

		ExtraArrayIterator(Iterator<? extends T> delegate, T[] array) {
			this.delegate = delegate;
			this.array = array;
		}

		@Override
		public boolean hasNext() {
			return delegate.hasNext() || arrayIndex < array.length;
		}
		@Override
		public T next() {
			return delegate.hasNext()
					? delegate.next()
					: array[arrayIndex++];
		}
	}
}


text:
class Relationship(object):
    """Class to represent a relationship between dataframes

    See Also:
        :class:`.EntitySet`
    """

    def __init__(self, entityset, parent_dataframe_name, parent_column_name,
                 child_dataframe_name, child_column_name):
        """ Create a relationship

        Args:
            entityset (:class:`.EntitySet`): EntitySet to which the relationship belongs
            parent_dataframe_name (str): Name of the parent dataframe in the EntitySet
            parent_column_name (str): Name of the parent column
            child_dataframe_name (str): Name of the child dataframe in the EntitySet
            child_column_name (str): Name of the child column
        """

        self.entityset = entityset
        self._parent_dataframe_name = parent_dataframe_name
        self._child_dataframe_name = child_dataframe_name
        self._parent_column_name = parent_column_name
        self._child_column_name = child_column_name

        if (self.parent_dataframe.ww.index is not None and
                self._parent_column_name != self.parent_dataframe.ww.index):
            raise AttributeError(f"Parent column '{self._parent_column_name}' is not the index of "
                                 f"dataframe {self._parent_dataframe_name}")

    @classmethod
    def from_dictionary(cls, arguments, es):
        parent_dataframe = arguments['parent_dataframe_name']
        child_dataframe = arguments['child_dataframe_name']
        parent_column = arguments['parent_column_name']
        child_column = arguments['child_column_name']
        return cls(es, parent_dataframe, parent_column, child_dataframe, child_column)

    def __repr__(self):
        ret = u"<Relationship: %s.%s -> %s.%s>" % \
            (self._child_dataframe_name, self._child_column_name,
             self._parent_dataframe_name, self._parent_column_name)

        return ret

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return False

        return self._parent_dataframe_name == other._parent_dataframe_name and \
            self._child_dataframe_name == other._child_dataframe_name and \
            self._parent_column_name == other._parent_column_name and \
            self._child_column_name == other._child_column_name

    def __hash__(self):
        return hash((self._parent_dataframe_name,
                     self._child_dataframe_name,
                     self._parent_column_name,
                     self._child_column_name))

    @property
    def parent_dataframe(self):
        """Parent dataframe object"""
        return self.entityset[self._parent_dataframe_name]

    @property
    def child_dataframe(self):
        """Child dataframe object"""
        return self.entityset[self._child_dataframe_name]

    @property
    def parent_column(self):
        """Column in parent dataframe"""
        return self.parent_dataframe.ww[self._parent_column_name]

    @property
    def child_column(self):
        """Column in child dataframe"""
        return self.child_dataframe.ww[self._child_column_name]

    @property
    def parent_name(self):
        """The name of the parent, relative to the child."""
        if self._is_unique():
            return self._parent_dataframe_name
        else:
            return '%s[%s]' % (self._parent_dataframe_name, self._child_column_name)

    @property
    def child_name(self):
        """The name of the child, relative to the parent."""
        if self._is_unique():
            return self._child_dataframe_name
        else:
            return '%s[%s]' % (self._child_dataframe_name, self._child_column_name)

    def to_dictionary(self):
        return {
            'parent_dataframe_name': self._parent_dataframe_name,
            'child_dataframe_name': self._child_dataframe_name,
            'parent_column_name': self._parent_column_name,
            'child_column_name': self._child_column_name,
        }

    def _is_unique(self):
        """Is there any other relationship with same parent and child dataframes?"""
        es = self.entityset
        relationships = es.get_forward_relationships(self._child_dataframe_name)
        n = len([r for r in relationships
                 if r._parent_dataframe_name == self._parent_dataframe_name])

        assert n > 0, 'This relationship is missing from the entityset'

        return n == 1

class RelationshipPath(object):
    def __init__(self, relationships_with_direction):
        self._relationships_with_direction = relationships_with_direction

    @property
    def name(self):
        relationship_names = [_direction_name(is_forward, r)
                              for is_forward, r in self._relationships_with_direction]

        return '.'.join(relationship_names)

    def dataframes(self):
        if self:
            # Yield first dataframe.
            is_forward, relationship = self[0]
            if is_forward:
                yield relationship._child_dataframe_name
            else:
                yield relationship._parent_dataframe_name

        # Yield the dataframe pointed to by each relationship.
        for is_forward, relationship in self:
            if is_forward:
                yield relationship._parent_dataframe_name
            else:
                yield relationship._child_dataframe_name

    def __add__(self, other):
        return RelationshipPath(self._relationships_with_direction +
                                other._relationships_with_direction)

    def __getitem__(self, index):
        return self._relationships_with_direction[index]

    def __iter__(self):
        for is_forward, relationship in self._relationships_with_direction:
            yield is_forward, relationship

    def __len__(self):
        return len(self._relationships_with_direction)

    def __eq__(self, other):
        return isinstance(other, RelationshipPath) and \
            self._relationships_with_direction == other._relationships_with_direction

    def __ne__(self, other):
        return not self == other

    def __repr__(self):
        if self._relationships_with_direction:
            path = '%s.%s' % (next(self.dataframes()), self.name)
        else:
            path = '[]'
        return '<RelationshipPath %s>' % path

def _direction_name(is_forward, relationship):
    if is_forward:
        return relationship.parent_name
    else:
        return relationship.child_name


text:
<?php
/**
 * Created by PhpStorm.
 * User: Gumacs
 * Date: 2016-11-14
 * Time: 01:23 AM
 */

namespace Tests\Unit\Rules;

use Processor\Rules\Abstraction\AbstractRule;
use Processor\Rules\Abstraction\Errors;
use Processor\Rules\SetTypeStringRule;

class SetTypeStringRuleTest extends \PHPUnit_Framework_TestCase
{
    /* @var AbstractRule $rule */
    private $rule;

    public function setUp()
    {
        $this->rule = new SetTypeStringRule();
    }

    public function testSetTypeStringTrueFromInt()
    {
        $return = $this->rule->process(10);

        $this->assertEquals(true, $return);
    }

    public function testSetTypeStringTrueFromFloat()
    {
        $return = $this->rule->process(10.1);

        $this->assertEquals(true, $return);
    }

    public function testSetTypeStringTrueFromIntWithError()
    {
        $return = $this->rule->process(10, Errors::ALL);

        $this->assertEquals(true, $return);
    }

    public function testSetTypeStringTrueFromBoolWithError()
    {
        $return = $this->rule->process(false, Errors::ALL);

        $this->assertEquals(true, $return);
    }
}


text:
> A React component for the Entypo SVG icon library.

**NO LONGER MAINTAINED** - See [https://github.com/kevcenteno/react-entypo-icons](https://github.com/kevcenteno/react-entypo-icons) instead.

React-Entypo sets up all the icons of the [Entypo SVG library](http://www.entypo.com/ "Entypo") to be used as components which will render as inline SVGs. Both the main set and the Social Extension are included. This component is designed to use Entypo SVGs as inline icons and are set with default inline styling to be the same size as the base text in the container they're placed. No CSS is supplied by 'react-entypo'; therefore, any other styles will have to be passed to the component or set by style declarations elsewhere.

The SVGs use the same names as the files in the Entypo SVG library, but camel-cased instead of hyphens, and any special characters removed.

## Demo

[https://cox-auto-kc.github.io/react-entypo/](https://cox-auto-kc.github.io/react-entypo/)

## Install

```
npm install --save react-entypo
```

## Usage

Just import each icon you want to reference (and React, of course).

```js
var React = require('react');
var {EntypoArrowBoldRight, EntypoCalculator} = require('react-entypo');
```

or, import the ES6 way...

```js
import React from 'react';
import {EntypoArrowBoldRight, EntypoCalculator} from 'react-entypo';
```

...or, reference the icon by file. Initial path is 'react-entypo/lib/entypo/[ICONNAME]' where ICONNAME is the name of the icon (PascalCased).**[1]**
```js
import React from 'react';
import EntypoArrowBoldRight from 'react-entypo/lib/entypo/ArrowBoldRight';
import EntypoCalculator from 'react-entypo/lib/entypo/Calculator';
```

...then reference like any other component: `<EntypoArrowBoldRight />`, `<EntypoCalculator/>`.

Examples:
```
<Button>This Way! <EntypoArrowBoldRight/></Button>

<div><EntypoArrowBoldRight style/></div>

<Button><EntypoCalculator className="my-calc-icon" valign style{{'fill':'white','box-shadow':'0 0 5px rgba(0,0,0,.8)'}}/></Button>
```

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [style] | `String` |  | Additional inline styles, adds to:
`display:inline-block;`
`height:1em;`
`width:1em; user-select:none;`
`fill:currentColor;` |
| [valign] | `String | Boolean` | `'text-top'` | Adds `vertical-align:[valign]` to the standard styles (above, see **[2]**).
If `false`, does not output `'vertical-align:...'` to style attribute.
If `true` or used without a value, will set to  `vertical-align:middle`. |
| [className] | `String` |  | An extra set of CSS classes to add to the component.
Default is "entypo-icon entypo--[ICONNAME]" |
| [viewBox] | `String` | `'0 0 20 20'` | Default viewbox |

Other attributes can be passed but have no defaults. Examples include `data-` or `id` attributes.

> **[1]** - This will reduce the final package size.  Using the object notation in the above examples brings with them all the icons in that object (all 411 of them).  By referencing with the path name to the icon specifically means that only those specified will be in the final build file.  The downside is notation; however, as it's much easier to use the object notation as noted above to reference the icons and leaves fewer lines of code in your development files.

> **[2]** - The default of "vertical-align:text-top" is due to the way the icons are created and being presented.  Since the icons are usually used inline with text, forcing alignment to base off text-top allows for better vertical spacing.  However, if an icon is used alone, setting vertical-alignment to "middle" works better visually since there's no text adjacent to provide any contextual vertical spacing issues.

---
## TODO

- Create docs page to reference icons and names.

---
## Attribution
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) @ [Daniel Bruce](http://www.entypo.com/ "Entypo")


text:
package atree.metrics;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;

public class PrintStatATMetrics {
	StatATMetrics m;
	NumberFormat formatter, stdFormat;

	public PrintStatATMetrics(StatATMetrics m) {
		super();
		this.m = m;
		formatter = new DecimalFormat("#0.000");
		stdFormat = new DecimalFormat("#.00");
	}

	public static String toLatex(ArrayList<String> heads, ArrayList<ArrayList<String>> cols, String tableCaption) {
		StringBuffer sb = new StringBuffer();
		sb.append("\\begin{table}[!hpb]\n");
		sb.append("\\begin{center}\n");
		sb.append("\\begin{tabular}{@{}l@{\\hspace{1pt}}||@{\\hspace{1pt}}");
		for (int i=0;i<heads.size();i++) {
			sb.append("@{\\hspace{1pt}}r");
			if (i<(heads.size()-1))sb.append("@{\\hspace{1pt}} | ");
			else sb.append("} \n ");
		}
		sb.append("Metrics &");
		for (int i=0;i<heads.size();i++) {
			sb.append(heads.get(i));
			if (i<(heads.size()-1))sb.append(" & ");
			else sb.append("\\\\ \\hline\\hline\n");
		}
		for (int j=0;j<cols.get(0).size();j++) {
		  for (int i=0;i<cols.size();i++) {
				sb.append(cols.get(i).get(j));
				if (i<(cols.size()-1))sb.append(" & ");
				else sb.append("\\\\ \\hline\n");
			}
		}

		sb.append("\\end{tabular}\n");
		sb.append("\\caption{"+tableCaption+"}\n");
		sb.append("\\label{smalldatatable}\n");
		sb.append("\\end{center}\n");
		sb.append("\\end{table}\n");
		return sb.toString();
	}

	public ArrayList<String> getColumn() {
		ArrayList<String> data = new ArrayList<String>();
		data.add(m.getExplorRatio().toString());
		data.add(m.getExplorGap_1().toString());
		data.add(m.getExplorGap_1_std().toString());
		data.add(m.getExplorProgressiveness().toString());
		data.add(m.getExplorProgressiveness_std().toString());
		data.add(m.getExploreSelectionPressure().toString());
		//
		data.add(m.getExploitRatio().toString());
		data.add(m.getExploitProgressiveness().toString());
		data.add(m.getExploitProgressiveness_std().toString());
		data.add(m.getExploitSelectionPressure().toString());
		data.add(m.getCountAllNodes().toString());
		data.add(m.getNonRevisitedRatio().toString());
		return data;

	}
	public ArrayList<String> getDoubleColumn() {
		ArrayList<String> data = new ArrayList<String>();
		data.add(m.getBestFitness().toStringMean());
		data.add(m.getBestFitness().toStringStDev());
		data.add(m.getExplorRatio().toStringMean());
		data.add(m.getExplorRatio().toStringStDev());
		data.add(m.getExplorGap_1().toStringMean());
		data.add(m.getExplorGap_1().toStringStDev());
		//data.add(m.getExplorDynamic_1_std().toString());
		data.add(m.getExplorProgressiveness().toStringMean());
		data.add(m.getExplorProgressiveness().toStringStDev());
		data.add(m.getExploreSelectionPressure().toStringMean());
		data.add(m.getExploreSelectionPressure().toStringStDev());
		//data.add(m.getExplorDynamic_2_std().toString());
		data.add(m.getExploitRatio().toStringMean());
		data.add(m.getExploitRatio().toStringStDev());
		data.add(m.getExploitProgressiveness().toStringMean());
		data.add(m.getExploitProgressiveness().toStringStDev());
		data.add(m.getExploitSelectionPressure().toStringMean());
		data.add(m.getExploitSelectionPressure().toStringStDev());
		data.add(m.getNonRevisitedRatio().toStringMean());
		data.add(m.getNonRevisitedRatio().toStringStDev());
		//data.add(""+(int)m.getCountAllNodes().getMean());
		return data;

	}
	public static ArrayList<String> getInfoColumn() {
		ArrayList<String> data = new ArrayList<String>();
		data.add("{\\footnotesize$explorRatio$"+"}");
		data.add("{\\footnotesize$explorGap$"+"}");
		data.add("{\\footnotesize$\\hspace{15mm}stdev$"+"}");
		data.add("{\\footnotesize$explorProgressiveness$"+"}");
		data.add("{\\footnotesize$\\hspace{15mm}stdev$"+"}");
		data.add("{\\footnotesize$exploreSelectionPressure$"+"}");
		data.add("{\\footnotesize$exploitRatio$"+"}");
		data.add("{\\footnotesize$exploitProgressiveness$"+"}");
		data.add("{\\footnotesize$\\hspace{15mm}stdev$"+"}");
		data.add("{\\footnotesize$exploitSelectionPressure$"+"}");
		data.add("{\\footnotesize$countAllNodes$"+"}");
		data.add("{\\footnotesize$nonRevisitedRatio$"+"}");
		return data;
	}
	public static ArrayList<String> getDoubleInfoColumn() {
		ArrayList<String> data = new ArrayList<String>();
		data.add("{\\footnotesize$Fitness$"+"}");
		data.add("");
		data.add("{\\footnotesize$explorRatio$"+"}");
		data.add("");
		data.add("{\\footnotesize$explorGap$"+"}");
		data.add("");
		//data.add("{\\footnotesize$\\hspace{15mm}stdev$"+"}");
		data.add("{\\footnotesize$explorProgressiveness$"+"}");
		data.add("");
		data.add("{\\footnotesize$explorSelectionPressure$"+"}");
		data.add("");
		//data.add("{\\footnotesize$\\hspace{15mm}stdev$"+"}");
		data.add("{\\footnotesize$exploitRatio$"+"}");
		data.add("");
		data.add("{\\footnotesize$exploitProgressiveness$"+"}");
		data.add("");
		data.add("{\\footnotesize$exploitSelectionPressure$"+"}");
		data.add("");
		data.add("{\\footnotesize$nonRevisitedRatio$"+"}");
		data.add("");
		//data.add("{\\footnotesize$countAllNodes$"+"}");
		return data;
	}

	public void printToScreen() {
		System.out.println("Not implemented yet!");
	}

}


text:
import logging
from dataclasses import dataclass, field
from typing import Optional

import torch
from .dummy_dataset import DummyDataset
from fairseq.data import Dictionary
from fairseq.dataclass import FairseqDataclass
from fairseq.tasks import FairseqTask, register_task
from omegaconf import II

logger = logging.getLogger(__name__)

@dataclass
class DummyLMConfig(FairseqDataclass):
    dict_size: int = 49996
    dataset_size: int = 100000
    tokens_per_sample: int = field(
        default=512, metadata={"help": "max sequence length"}
    )
    add_bos_token: bool = False
    batch_size: Optional[int] = II("dataset.batch_size")
    max_tokens: Optional[int] = II("dataset.max_tokens")
    max_target_positions: int = II("task.tokens_per_sample")

@register_task("dummy_lm", dataclass=DummyLMConfig)
class DummyLMTask(FairseqTask):
    def __init__(self, cfg: DummyLMConfig):
        super().__init__(cfg)

        # load dictionary
        self.dictionary = Dictionary()
        for i in range(cfg.dict_size):
            self.dictionary.add_symbol("word{}".format(i))
        self.dictionary.pad_to_multiple_(8)  # often faster if divisible by 8
        logger.info("dictionary: {} types".format(len(self.dictionary)))

        seq = torch.arange(cfg.tokens_per_sample + 1) + self.dictionary.pad() + 1

        self.dummy_src = seq[:-1]
        self.dummy_tgt = seq[1:]

    def load_dataset(self, split, epoch=1, combine=False, **kwargs):
        """Load a given dataset split.
        Args:
            split (str): name of the split (e.g., train, valid, test)
        """
        if self.cfg.batch_size is not None:
            bsz = self.cfg.batch_size
        else:
            bsz = max(1, self.cfg.max_tokens // self.cfg.tokens_per_sample)
        self.datasets[split] = DummyDataset(
            {
                "id": 1,
                "net_input": {
                    "src_tokens": torch.stack([self.dummy_src for _ in range(bsz)]),
                    "src_lengths": torch.full(
                        (bsz,), self.cfg.tokens_per_sample, dtype=torch.long
                    ),
                },
                "target": torch.stack([self.dummy_tgt for _ in range(bsz)]),
                "nsentences": bsz,
                "ntokens": bsz * self.cfg.tokens_per_sample,
            },
            num_items=self.cfg.dataset_size,
            item_size=self.cfg.tokens_per_sample,
        )

    @property
    def source_dictionary(self):
        return self.dictionary

    @property
    def target_dictionary(self):
        return self.dictionary


text:
cask 'sourcetree-beta' do
  version '2.7b3'
  sha256 'f5090be7a602b84e0c8c6abfcf854e2ff693c517a3b873d353695f807b0fb6ab'

  # atlassian.com was verified as official when first introduced to the cask
  url "https://downloads.atlassian.com/software/sourcetree/Sourcetree_#{version}.zip"
  appcast 'https://www.sourcetreeapp.com/update/SparkleAppcastBeta.xml',
          checkpoint: 'e30525c55d530bf7d672ce356bcd09e7d9ddbc52084dfd02454501890e5ade9c'
  name 'Atlassian SourceTree'
  homepage 'https://www.sourcetreeapp.com/'

  auto_updates true
  depends_on macos: '>= :yosemite'

  app 'SourceTree-Beta.app'
  binary "#{appdir}/SourceTree-Beta.app/Contents/Resources/stree"

  uninstall launchctl: 'com.atlassian.SourceTreePrivilegedHelper2',
            quit:      'com.torusknot.SourceTreeNotMAS'

  zap trash: [
               '~/Library/Application Support/SourceTree',
               '~/Library/Caches/com.torusknot.SourceTreeNotMAS',
               '~/Library/Preferences/com.torusknot.SourceTreeNotMAS.plist',
               '~/Library/Preferences/com.torusknot.SourceTreeNotMAS.LSSharedFileList.plist',
               '~/Library/Saved Application State/com.torusknot.SourceTreeNotMAS.savedState',
             ]
end


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

		<meta charset="utf-8"/>
		<title>FJME - Etat <?php if(isset($titre_fonds))echo $titre_fonds; ?></title>
		<link rel="stylesheet" href="<?php echo base_url("assets/css/tacit-css.min.css");?>"/>

<?php if(isset($titre_fonds)) echo $titre_fonds; ?>

Pièces numériques manquantes

Liste des cotes n'ayant pas de pièce numérique diffusable. Avec mention si il y a une présensence de pièces dans le dossier de préservation et/ou mezzanine.

Nombre de cotes manquantes : <?php echo $nb; ?>.

            Cote
            Intitulé
            Présence dans préservation
            Présence dans mezzanine

          <?php foreach ($uds as $cote_id => $detail): ?>

            <a href='<?php echo base_url("fonds/$radical/$cote_id");?>'><?php if(isset($detail['cote']))echo $detail['cote']; ?>
            <?php if(isset($detail['titre'])) echo $detail['titre']; ?>
            <?php if(isset($detail['preservation'])) echo "X"; ?>
            <?php if(isset($detail['mezzanine'])) echo "X"; ?>

        <?php endforeach; ?>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
 Copyright (c) 2010 International Business Machines Corporation and others. All rights reserved.
-->
<!DOCTYPE ldml SYSTEM "http://www.unicode.org/repos/cldr/trunk/common/dtd/ldml.dtd"
[
   <!ENTITY % icu SYSTEM "http://www.unicode.org/repos/cldr/trunk/common/dtd/ldmlICU.dtd">
   %icu;
]
>
<ldml>
	<identity>
		<version number="$Revision: 1.27 $"/>
		<generation date="$Date: 2008/05/25 01:05:51 $"/>
		<language type="en"/>
    <territory type="US"/>
    <variant type="POSIX"/>
	</identity>
</ldml>


text:
// Copyright 2015 The Project Buendia Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distrib-
// uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied.  See the License for
// specific language governing permissions and limitations under the License.

package org.projectbuendia.openmrs;

import org.openmrs.BaseOpenmrsObject;

import java.io.Serializable;

/**
 * Model class, which is currently unused. This only exists to give us a
 * sample to extend if/when we need to store our own model classes in OpenMRS.
 */
public class ProjectBuendia extends BaseOpenmrsObject implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer id;

    @Override public Integer getId() {
        return id;
    }

    @Override public void setId(Integer id) {
        this.id = id;
    }
}


text:
var uniqueID = (function () {
  var id = 100;
  return function () {
    return id++;
  };
})();

var getItemObj = (function (idx, params) {
  console.log(idx);
  var items = [];
  if (!idx) {
    idx = uniqueID();
  }
  return function (idx, params) {
    if (items[idx] == undefined) {
      console.log('NEW ' + idx);
      item = new ItemChild();
      console.log('getItemObj: Is item an instance of ItemChild?', item instanceof ItemChild);
      item.init(params);
      items[idx] = item;
    } else {
      console.log('FOUND ' + idx);
    }
    return items[idx];
  };
})();

function getItem(e) {
  e.preventDefault();
  var idx = Math.round(Math.random(1, 9) * 10);
  var params = {
    id: idx,
    label: 'label' + idx,
    foo: 'bar ' + idx,
  };
  var item = getItemObj(idx, params);
  console.log('Returned item id: ' + item.getId());
  console.log('Returned item label: ' + item.getLabel());
  console.log('Returned item foo: ' + item.getId());
}


text:
package com.toedter.calendar;

import java.beans.PropertyChangeListener;
import java.util.Date;
import java.util.Locale;

import javax.swing.JComponent;

/**
 * All date editors that should be used by a JDateChooser have to implement this
 * interface.
 *
 * @author Kai Toedter
 * @version $LastChangedRevision: 142 $
 * @version $LastChangedDate: 2011-06-05 07:06:03 +0200 (Sun, 05 Jun 2011) $
 *
 */
public interface IDateEditor {

    /**
     *
     * Returns the date.
     *
     * @return the date
     */
    public Date getDate();

    /**
     * Sets the date. This should be implemented as a bound property, firing the
     * "date" property.
     *
     * @param date the date to set
     */
    public void setDate(Date date);

    /**
     * Sets the date format string, e.g. "MM/dd/yy". If the date format string
     * is null or invalid, the date format string will be set to the MEDIUM
     * Simple date format of the current locale.
     *
     * @param dateFormatString the date format string
     */
    public void setDateFormatString(String dateFormatString);

    /**
     * Returns the date format string.
     *
     * @return the date format string
     */
    public String getDateFormatString();

    /**
     * Sets a valid date range for selectable dates. If max is before min, the
     * default range with no limitation is set.
     *
     * @param min the minimum selectable date or null (then the minimum date
     * should be set to 01\01\0001)
     * @param max the maximum selectable date or null (then the maximum date
     * should be set to 01\01\9999)
     */
    public void setSelectableDateRange(Date min, Date max);

    /**
     * Gets the minimum selectable date.
     *
     * @return the minimum selectable date
     */
    public Date getMaxSelectableDate();

    /**
     * Gets the maximum selectable date.
     *
     * @return the maximum selectable date
     */
    public Date getMinSelectableDate();

    /**
     * Sets the maximum selectable date.
     *
     * @param max maximum selectable date
     */
    public void setMaxSelectableDate(Date max);

    /**
     * Sets the minimum selectable date.
     *
     * @param min minimum selectable date
     */
    public void setMinSelectableDate(Date min);

    /**
     * Returns the UI component, e.g. the actual JTextField implementing the
     * editor.
     *
     * @return the UI component
     */
    public JComponent getUiComponent();

    /**
     * Sets the locale. Usually this should have impact on the current date
     * format string.
     *
     * @param locale the locale to set
     */
    public void setLocale(Locale locale);

    /**
     * Enables or disables the UI compoment.
     *
     * @param enabled true, if the UI component should be enabled.
     */
    public void setEnabled(boolean enabled);

    /**
     * Adds a property change listener that should be added to the implementing
     * UI component. The UI component should fire a "date" property if the date
     * changes.
     *
     * @param listener the property change listener.
     */
    public void addPropertyChangeListener(PropertyChangeListener listener);

    /**
     * Adds a property change listener that should be added to the implementing
     * UI component. The UI component should fire a "date" property if the date
     * changes.
     *
     * @param propertyName the property name, e.g. "date"
     * @param listener the property change listener.
     */
    public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener);

    /**
     * Removes a property change listener.
     *
     * @param listener the property change listener.
     */
    public void removePropertyChangeListener(PropertyChangeListener listener);

    /**
     * Removes the listener from the date editor's property change listeners for
     * the specific property.
     *
     * @param propertyName the property to listen for, e.g. "date"
     * @param listener the listener
     */
    public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener);
}


text:
#ifndef QSCRIPTDEBUGGERCODEWIDGET_P_H
#define QSCRIPTDEBUGGERCODEWIDGET_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include "qscriptdebuggercodewidgetinterface_p.h"

QT_BEGIN_NAMESPACE

class QScriptDebuggerCodeWidgetPrivate;
class Q_AUTOTEST_EXPORT QScriptDebuggerCodeWidget:
    public QScriptDebuggerCodeWidgetInterface
{
    Q_OBJECT
public:
    QScriptDebuggerCodeWidget(QWidget *parent = 0);
    ~QScriptDebuggerCodeWidget();

    QScriptDebuggerScriptsModel *scriptsModel() const;
    void setScriptsModel(QScriptDebuggerScriptsModel *model);

    void setToolTipProvider(QScriptToolTipProviderInterface *toolTipProvider);

    qint64 currentScriptId() const;
    void setCurrentScript(qint64 scriptId);

    void invalidateExecutionLineNumbers();

    QScriptBreakpointsModel *breakpointsModel() const;
    void setBreakpointsModel(QScriptBreakpointsModel *model);

    QScriptDebuggerCodeViewInterface *currentView() const;

private:
    Q_DECLARE_PRIVATE(QScriptDebuggerCodeWidget)
    Q_DISABLE_COPY(QScriptDebuggerCodeWidget)

    Q_PRIVATE_SLOT(d_func(), void _q_onBreakpointToggleRequest(int,bool))
    Q_PRIVATE_SLOT(d_func(), void _q_onBreakpointEnableRequest(int,bool))
    Q_PRIVATE_SLOT(d_func(), void _q_onBreakpointsAboutToBeRemoved(const QModelIndex &,int,int))
    Q_PRIVATE_SLOT(d_func(), void _q_onBreakpointsInserted(const QModelIndex &,int,int))
    Q_PRIVATE_SLOT(d_func(), void _q_onBreakpointsDataChanged(const QModelIndex &, const QModelIndex &))
    Q_PRIVATE_SLOT(d_func(), void _q_onScriptsChanged())
    Q_PRIVATE_SLOT(d_func(), void _q_onToolTipRequest(const QPoint &, int, const QStringList &))
};

QT_END_NAMESPACE

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatchTableImport
{
    static class LinqExtensions
    {
        public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
        {
            int i = 0;
            var splits = from item in list
                         group item by i++ % parts into part
                         select part.AsEnumerable();
            return splits;
        }
    }
}


text:
- RabbitMQ : An empty routing key was throwing an ArgumentNullException on DeclareBinding.

## 0.5.2 - 2018-11-21
### Added
- 2 new parameters on rabbitMq connection: friendlyName & requestedChannelMax

## 0.5.1 - 2018-09-25
### Fixed
- SharedConnection is disposable to properly close rabbitMq connection

## 0.4.2 - 2018-08-08
### Fixed
- RabbitMQ Consumer : consumer lock was static

## 0.4.1 - 2018-08-01
### Changed
- Samples.Startup

## 0.4.0 - 2018-07-31
### Changed
- .Net standard 2.0
### Added
- MerQureConfiguration
### Deleted
- RabbitMqConfigurationSection

## 0.3.1 - 2017-10-23
### Added
- Prefetch count support
- Publisher acknowledgement support
- Publishing without IMessage support
- Publishing many messages with transaction support

## 0.3.0 - 2017-03-08
### Changed
- HeaderProperties' values as object
### Added
- Message Priority Support
- DeadLetter Policy Support
- Exchange type support: direct, fanout, topic, headers

## 0.2.2 - 2017-01-11
### Changed
- IPublisher and IConsumer are IDisposable

## 0.2.1 - 2016-12-21
### Added
- Sonar ruleset

## 0.2.0 - 2016-12-21
### Removed
- ISubcriber: was ambiguous, replaced by specific methods
### Added
- IMessagingService.DeclareExchange
- IMessagingService.DeclareQueue
- IMessagingService.DeclareBinding
- IMessagingService.CancelBinding

## 0.1.6 - 2016-12-07
### Added
- IsConsuming: indicates when a consumer is registered
- StopConsuming: unregister a consumer

## 0.1.5 - 2016-12-02
### Changed
- HeaderProperties' values as string

## 0.1.4 - 2016-12-02
### Added
- logo

## 0.1.2 - 2016-11-22
### Changed
- IMessage interface has only methods

## 0.1.1 - 2016-11-21
### Added
- Nuget package definition

## 0.1.0 - 2016-11-14
### Added
- First version of the library


text:
package protocols;

import java.awt.event.KeyEvent;

/**
 * --------------------------------------------------------
 * Created by Carlos Bedoy on 11/04/14.
 * CBGameEnine
 * Mobile Developer
 * Aguascalientes Mexico
 * Email:       carlos.bedoy@gmail.com
 * Facebook:    https://www.facebook.com/carlos.bedoy
 * ---------CODE && MUSIC ----------------------------------
 */
public interface CBIKeyBoardDelegate {

    public void didUserPressKey(KeyEvent ke);

}


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

class User_approval extends Root_Controller
{
    public $permissions;
    public $message;
    public $controller_url;
    public $current_action;
    function __construct()
    {
        parent::__construct();
        $this->message='';
        $this->permissions=Menu_helper::get_permission('approval/User_approval');
        $this->controller_url='approval/User_approval';
        $this->load->model("approval/User_approval_model");
        $this->lang->load('website_lang');
    }

    public function index($action='add',$id=0)
    {
        $this->current_action=$action;

        if($action=='list')
        {
            $this->dcms_list();
        }
        elseif($action=='add')
        {
            $this->dcms_add();
        }
        elseif($action=='edit')
        {
            $this->dcms_edit($id);
        }
        elseif($action=='save')
        {
            $this->dcms_save();
        }
        else
        {
            $this->current_action='list';
            $this->dcms_list();
        }
    }

    private function dcms_list()
    {
        if($this->permissions['list'])
        {
            $this->current_action='list';
            $ajax['status']=true;

            $session_data['approval'] = $this->input->post();
            $this->session->set_userdata($session_data);

            $ajax['system_content'][]=array("id"=>"#load_list","html"=>$this->load_view("approval/user_approval/dcms_list",'',true));

            if($this->message)
            {
                $ajax['system_message']=$this->message;
            }

            $ajax['system_page_url']=$this->get_encoded_url('approval/User_approval');
            $ajax['system_page_title']=$this->lang->line("USER_APPROVAL");
            $this->jsonReturn($ajax);
        }
        else
        {
            $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
            $this->jsonReturn($ajax);
        }
    }

    private function dcms_add()
    {
        if($this->permissions['add'])
        {
            $this->current_action='add';
            $ajax['status']=true;
            $data=array();

            $data['divisions'] = $this->User_approval_model->get_divisions_by_user();
            $ajax['system_content'][]=array("id"=>"#system_wrapper_top_menu","html"=>$this->load_view("top_menu","",true));
            $ajax['system_content'][]=array("id"=>"#system_wrapper","html"=>$this->load_view("approval/user_approval/dcms_search",$data,true));

            if($this->message)
            {
                $ajax['system_message']=$this->message;
            }

            $ajax['system_page_url']=$this->get_encoded_url('approval/user_approval/index/add');
            $this->jsonReturn($ajax);
        }
        else
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
            $this->jsonReturn($ajax);
        }
    }

    private function dcms_edit($id)
    {
        $detail_info = $this->User_approval_model->fetch_uisc_detail_info($id);
        $uisc_id = $this->User_approval_model->get_uisc_id_for_user($id);
        $detail_info['equips'] = $this->User_approval_model->fetch_uisc_equipments($id);
        $data['uisc_detail'] = $detail_info;

        if($this->permissions['edit'])
        {
            if($data['uisc_detail'])
            {
                $ajax['status']=true;
                $ajax['system_content'][]=array("id"=>"#modal_data","html"=>$this->load_view("approval/user_approval/dcms_edit",$data,true));
                $this->jsonReturn($ajax);
            }
            else
            {
                $ajax['status']=true;
                $ajax['system_content'][]=array("id"=>"#modal_data","html"=>'',array(),true);
                $this->jsonReturn($ajax);
            }
        }
        else
        {
            $ajax['status']=true;
            $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
            $this->jsonReturn($ajax);
        }
    }

    private function dcms_save()
    {
        $user = User_helper::get_user();
        $id = $this->input->post("id");
        $status = $this->input->post("approval_status");

        if(!$this->check_validation())
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->message;
            $this->jsonReturn($ajax);
        }
        else
        {
            $user_data = Array('status'=>$status);
            $user_data['update_by'] = $user->id;
            $user_data['update_date'] = time();

            if($id>0)
            {
                $this->db->trans_start();  //DB Transaction Handle START

                Query_helper::update($this->config->item('table_users'),$user_data,array("id = ".$id));

                $this->db->trans_complete();   //DB Transaction Handle END

                if($this->db->trans_status() === TRUE)
                {
                    $ajax['status']=true;

                    if($status==1)
                    {
                        $ajax['system_message']=$this->lang->line("MSG_SUCCESSFULLY_APPROVED");
                    }
                    else
                    {
                        $ajax['system_message']=$this->lang->line("MSG_SUCCESSFULLY_DENIED");
                    }

                    $this->jsonReturn($ajax);
                }
                else
                {
                    $ajax['status']=false;
                    $ajax['system_message']=$this->lang->line("MSG_CREATE_FAIL");
                    $this->jsonReturn($ajax);
                }
            }
        }
    }

    private function check_validation()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('id',$this->lang->line('ID'),'required');

        if($this->form_validation->run() == FALSE)
        {
            $this->message=validation_errors();
            return false;
        }
        return true;
    }

    public function get_uiscs()
    {
        $session_data = $this->session->userdata('approval');
        $uiscs = array();

        if($this->permissions['list'])
        {
            $entrepreneur_type = isset($session_data['entrepreneur_type'])?$session_data['entrepreneur_type']:0;
            $division = isset($session_data['division'])?$session_data['division']:0;
            $zilla = isset($session_data['zilla'])?$session_data['zilla']:0;
            $upazilla = isset($session_data['upazilla'])?$session_data['upazilla']:0;
            $municipal = isset($session_data['municipal'])?$session_data['municipal']:0;
            $municipalward = isset($session_data['municipalward'])?$session_data['municipalward']:0;
            $citycorporation = isset($session_data['citycorporation'])?$session_data['citycorporation']:0;
            $citycorporationward = isset($session_data['citycorporationward'])?$session_data['citycorporationward']:0;
            $union = isset($session_data['union'])?$session_data['union']:0;
            $year = isset($session_data['year'])?$session_data['year']:0;
            $month = isset($session_data['month'])?$session_data['month']:0;
            $date = isset($session_data['date'])?$session_data['date']:0;
            $status = isset($session_data['status'])?$session_data['status']:'';
        }

        $uiscs = $this->User_approval_model->get_approval_uisc_detail($entrepreneur_type, $division, $zilla, $upazilla, $municipal, $municipalward, $citycorporation, $citycorporationward, $union, $year, $month, $date, $status);
        $this->session->unset_userdata('approval'); // unset session approval data.
        $this->jsonReturn($uiscs);
    }

    public function get_zilla()
    {
        $user = User_helper::get_user();
        $user_group_id = $user->user_group_id;

        $division_id=$this->input->post('division_id');

        if($user_group_id == $this->config->item('DISTRICT_GROUP_ID') || $user_group_id == $this->config->item('UPAZILLA_GROUP_ID') || $user_group_id == $this->config->item('UNION_GROUP_ID') || $user_group_id == $this->config->item('CITY_CORPORATION_GROUP_ID') || $user_group_id == $this->config->item('CITY_CORPORATION_WORD_GROUP_ID') || $user_group_id == $this->config->item('MUNICIPAL_GROUP_ID') || $user_group_id == $this->config->item('MUNICIPAL_WORD_GROUP_ID') || $user_group_id == $this->config->item('UISC_GROUP_ID'))
        {
            $zillas = Query_helper::get_info($this->config->item('table_zillas'),array('zillaid value', 'zillaname text'), array('visible = 1', 'divid = '.$division_id, 'zillaid = '.$user->zilla));
        }
        else
        {
            $zillas = Query_helper::get_info($this->config->item('table_zillas'),array('zillaid value', 'zillaname text'), array('visible = 1', 'divid = '.$division_id));
        }

        $ajax['status']=true;
        $ajax['system_content'][]=array("id"=>"#user_zilla_id","html"=>$this->load_view("dropdown",array('drop_down_options'=>$zillas),true));
        $this->jsonReturn($ajax);
    }

    public function get_upazila()
    {
        $user = User_helper::get_user();
        $user_group_id = $user->user_group_id;
        $zilla_id=$this->input->post('zilla_id');

        if($user_group_id == $this->config->item('UPAZILLA_GROUP_ID') || $user_group_id == $this->config->item('UNION_GROUP_ID') || $user_group_id == $this->config->item('CITY_CORPORATION_GROUP_ID') || $user_group_id == $this->config->item('CITY_CORPORATION_WORD_GROUP_ID') || $user_group_id == $this->config->item('MUNICIPAL_GROUP_ID') || $user_group_id == $this->config->item('MUNICIPAL_WORD_GROUP_ID') || $user_group_id == $this->config->item('UISC_GROUP_ID'))
        {
            $upazilas=Query_helper::get_info($this->config->item('table_upazilas'),array('upazilaid value', 'upazilaname text'), array('visible = 1', 'zillaid = '.$zilla_id, 'upazilaid = '.$user->upazila));
        }
        else
        {
            $upazilas=Query_helper::get_info($this->config->item('table_upazilas'),array('upazilaid value', 'upazilaname text'), array('visible = 1', 'zillaid = '.$zilla_id));
        }

        $ajax['status']=true;
        $ajax['system_content'][]=array("id"=>"#user_upazila_id","html"=>$this->load_view("dropdown",array('drop_down_options'=>$upazilas),true));
        $this->jsonReturn($ajax);
    }

    public function get_union()
    {
        $user = User_helper::get_user();
        $user_group_id = $user->user_group_id;

        $zilla_id=$this->input->post('zilla_id');
        $upazila_id=$this->input->post('upazila_id');
        $unions=Query_helper::get_info($this->config->item('table_unions'),array('unionid value', 'unionname text'), array('visible = 1', 'zillaid = '.$zilla_id, 'upazilaid='.$upazila_id));
        $ajax['status']=true;
        $ajax['system_content'][]=array("id"=>"#user_unioun_id","html"=>$this->load_view("dropdown",array('drop_down_options'=>$unions),true));
        $this->jsonReturn($ajax);
    }

    public function get_city_corporation()
    {
        $user = User_helper::get_user();
        $user_group_id = $user->user_group_id;

        $division_id=$this->input->post('division_id');
        $zilla_id=$this->input->post('zilla_id');

        if($user_group_id == $this->config->item('UPAZILLA_GROUP_ID') || $user_group_id == $this->config->item('UNION_GROUP_ID') || $user_group_id == $this->config->item('CITY_CORPORATION_GROUP_ID') || $user_group_id == $this->config->item('CITY_CORPORATION_WORD_GROUP_ID') || $user_group_id == $this->config->item('MUNICIPAL_GROUP_ID') || $user_group_id == $this->config->item('MUNICIPAL_WORD_GROUP_ID') || $user_group_id == $this->config->item('UISC_GROUP_ID'))
        {
            $city_corporations=Query_helper::get_info($this->config->item('table_city_corporations'),array('citycorporationid value', 'citycorporationname text'), array('visible = 1', 'zillaid = '.$zilla_id, 'divid='.$division_id, 'citycorporationid = '.$user->citycorporation));
        }
        else
        {
            $city_corporations=Query_helper::get_info($this->config->item('table_city_corporations'),array('citycorporationid value', 'citycorporationname text'), array('visible = 1', 'zillaid = '.$zilla_id, 'divid='.$division_id));
        }

        $ajax['status']=true;
        $ajax['system_content'][]=array("id"=>"#user_citycorporation_id","html"=>$this->load_view("dropdown",array('drop_down_options'=>$city_corporations),true));
        $this->jsonReturn($ajax);
    }

    public function get_city_corporation_word()
    {
        $user = User_helper::get_user();
        $user_group_id = $user->user_group_id;

        $division_id=$this->input->post('division_id');
        $zilla_id=$this->input->post('zilla_id');
        $city_corporation_id=$this->input->post('city_corporation_id');
        $city_corporation_words=Query_helper::get_info($this->config->item('table_city_corporation_wards'),array('citycorporationwardid value', 'wardname text'), array('visible = 1', 'zillaid = '.$zilla_id, 'divid='.$division_id, 'citycorporationid = '.$city_corporation_id));
        $ajax['status']=true;
        $ajax['system_content'][]=array("id"=>"#user_city_corporation_ward_id","html"=>$this->load_view("dropdown",array('drop_down_options'=>$city_corporation_words),true));
        $this->jsonReturn($ajax);
    }

    public function get_municipal()
    {
        $user = User_helper::get_user();
        $user_group_id = $user->user_group_id;

        $zilla_id=$this->input->post('zilla_id');

        if($user_group_id == $this->config->item('UPAZILLA_GROUP_ID') || $user_group_id == $this->config->item('UNION_GROUP_ID') || $user_group_id == $this->config->item('CITY_CORPORATION_GROUP_ID') || $user_group_id == $this->config->item('CITY_CORPORATION_WORD_GROUP_ID') || $user_group_id == $this->config->item('MUNICIPAL_GROUP_ID') || $user_group_id == $this->config->item('MUNICIPAL_WORD_GROUP_ID') || $user_group_id == $this->config->item('UISC_GROUP_ID'))
        {
            $municipals=Query_helper::get_info($this->config->item('table_municipals'),array('municipalid value', 'municipalname text'), array('visible = 1', 'zillaid = '.$zilla_id, 'municipalid = '.$user->municipal));
        }
        else
        {
            $municipals=Query_helper::get_info($this->config->item('table_municipals'),array('municipalid value', 'municipalname text'), array('visible = 1', 'zillaid = '.$zilla_id));
        }

        $ajax['status']=true;
        $ajax['system_content'][]=array("id"=>"#user_municipal_id","html"=>$this->load_view("dropdown",array('drop_down_options'=>$municipals),true));
        $this->jsonReturn($ajax);
    }

    public function get_municipal_ward()
    {
        $user = User_helper::get_user();
        $user_group_id = $user->user_group_id;

        $zilla_id=$this->input->post('zilla_id');
        $municipal_id=$this->input->post('municipal_id');
        $municipal_wards=Query_helper::get_info($this->config->item('table_municipal_wards'),array('wardid value', 'wardname text'), array('visible = 1', 'zillaid = '.$zilla_id, 'municipalid = '.$municipal_id));
        $ajax['status']=true;
        $ajax['system_content'][]=array("id"=>"#user_municipal_ward_id","html"=>$this->load_view("dropdown",array('drop_down_options'=>$municipal_wards),true));
        $this->jsonReturn($ajax);
    }
}


text:
"""Support for Telldus Live."""
import asyncio
from functools import partial
import logging

from tellduslive import DIM, TURNON, UP, Session
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_SCAN_INTERVAL
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_call_later

from .const import (
    CONF_HOST,
    DOMAIN,
    KEY_SCAN_INTERVAL,
    KEY_SESSION,
    MIN_UPDATE_INTERVAL,
    NOT_SO_PRIVATE_KEY,
    PUBLIC_KEY,
    SCAN_INTERVAL,
    SIGNAL_UPDATE_ENTITY,
    TELLDUS_DISCOVERY_NEW,
)

APPLICATION_NAME = "Home Assistant"

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.Schema(
            {
                vol.Optional(CONF_HOST, default=DOMAIN): cv.string,
                vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): vol.All(
                    cv.time_period, vol.Clamp(min=MIN_UPDATE_INTERVAL)
                ),
            }
        )
    },
    extra=vol.ALLOW_EXTRA,
)

DATA_CONFIG_ENTRY_LOCK = "tellduslive_config_entry_lock"
CONFIG_ENTRY_IS_SETUP = "telldus_config_entry_is_setup"

NEW_CLIENT_TASK = "telldus_new_client_task"
INTERVAL_TRACKER = f"{DOMAIN}_INTERVAL"

async def async_setup_entry(hass, entry):
    """Create a tellduslive session."""

    conf = entry.data[KEY_SESSION]

    if CONF_HOST in conf:
        # Session(**conf) does blocking IO when
        # communicating with local devices.
        session = await hass.async_add_executor_job(partial(Session, **conf))
    else:
        session = Session(
            PUBLIC_KEY, NOT_SO_PRIVATE_KEY, application=APPLICATION_NAME, **conf
        )

    if not session.is_authorized:
        _LOGGER.error("Authentication Error")
        return False

    hass.data[DATA_CONFIG_ENTRY_LOCK] = asyncio.Lock()
    hass.data[CONFIG_ENTRY_IS_SETUP] = set()
    hass.data[NEW_CLIENT_TASK] = hass.loop.create_task(
        async_new_client(hass, session, entry)
    )

    return True

async def async_new_client(hass, session, entry):
    """Add the hubs associated with the current client to device_registry."""
    interval = entry.data[KEY_SCAN_INTERVAL]
    _LOGGER.debug("Update interval %s seconds", interval)
    client = TelldusLiveClient(hass, entry, session, interval)
    hass.data[DOMAIN] = client
    dev_reg = await hass.helpers.device_registry.async_get_registry()
    for hub in await client.async_get_hubs():
        _LOGGER.debug("Connected hub %s", hub["name"])
        dev_reg.async_get_or_create(
            config_entry_id=entry.entry_id,
            identifiers={(DOMAIN, hub["id"])},
            manufacturer="Telldus",
            name=hub["name"],
            model=hub["type"],
            sw_version=hub["version"],
        )
    await client.update()

async def async_setup(hass, config):
    """Set up the Telldus Live component."""
    if DOMAIN not in config:
        return True

    hass.async_create_task(
        hass.config_entries.flow.async_init(
            DOMAIN,
            context={"source": config_entries.SOURCE_IMPORT},
            data={
                CONF_HOST: config[DOMAIN].get(CONF_HOST),
                KEY_SCAN_INTERVAL: config[DOMAIN][CONF_SCAN_INTERVAL],
            },
        )
    )
    return True

async def async_unload_entry(hass, config_entry):
    """Unload a config entry."""
    if not hass.data[NEW_CLIENT_TASK].done():
        hass.data[NEW_CLIENT_TASK].cancel()
    interval_tracker = hass.data.pop(INTERVAL_TRACKER)
    interval_tracker()
    await asyncio.wait(
        [
            hass.config_entries.async_forward_entry_unload(config_entry, platform)
            for platform in hass.data.pop(CONFIG_ENTRY_IS_SETUP)
        ]
    )
    del hass.data[DOMAIN]
    del hass.data[DATA_CONFIG_ENTRY_LOCK]
    return True

class TelldusLiveClient:
    """Get the latest data and update the states."""

    def __init__(self, hass, config_entry, session, interval):
        """Initialize the Tellus data object."""
        self._known_devices = set()
        self._device_infos = {}

        self._hass = hass
        self._config_entry = config_entry
        self._client = session
        self._interval = interval

    async def async_get_hubs(self):
        """Return hubs registered for the user."""
        clients = await self._hass.async_add_executor_job(self._client.get_clients)
        return clients or []

    def device_info(self, device_id):
        """Return device info."""
        return self._device_infos.get(device_id)

    @staticmethod
    def identify_device(device):
        """Find out what type of HA component to create."""
        if device.is_sensor:
            return "sensor"

        if device.methods & DIM:
            return "light"
        if device.methods & UP:
            return "cover"
        if device.methods & TURNON:
            return "switch"
        if device.methods == 0:
            return "binary_sensor"
        _LOGGER.warning("Unidentified device type (methods: %d)", device.methods)
        return "switch"

    async def _discover(self, device_id):
        """Discover the component."""
        device = self._client.device(device_id)
        component = self.identify_device(device)
        self._device_infos.update(
            {device_id: await self._hass.async_add_executor_job(device.info)}
        )
        async with self._hass.data[DATA_CONFIG_ENTRY_LOCK]:
            if component not in self._hass.data[CONFIG_ENTRY_IS_SETUP]:
                await self._hass.config_entries.async_forward_entry_setup(
                    self._config_entry, component
                )
                self._hass.data[CONFIG_ENTRY_IS_SETUP].add(component)
        device_ids = []
        if device.is_sensor:
            for item in device.items:
                device_ids.append((device.device_id, item.name, item.scale))
        else:
            device_ids.append(device_id)
        for _id in device_ids:
            async_dispatcher_send(
                self._hass, TELLDUS_DISCOVERY_NEW.format(component, DOMAIN), _id
            )

    async def update(self, *args):
        """Periodically poll the servers for current state."""
        try:
            if not await self._hass.async_add_executor_job(self._client.update):
                _LOGGER.warning("Failed request")
                return
            dev_ids = {dev.device_id for dev in self._client.devices}
            new_devices = dev_ids - self._known_devices
            # just await each discover as `gather` use up all HTTPAdapter pools
            for d_id in new_devices:
                await self._discover(d_id)
            self._known_devices |= new_devices
            async_dispatcher_send(self._hass, SIGNAL_UPDATE_ENTITY)
        finally:
            self._hass.data[INTERVAL_TRACKER] = async_call_later(
                self._hass, self._interval, self.update
            )

    def device(self, device_id):
        """Return device representation."""
        return self._client.device(device_id)

    def is_available(self, device_id):
        """Return device availability."""
        return device_id in self._client.device_ids


text:
import java.awt.*;
import java.util.List;

public class Main {
  private static final Point ZERO = new Point(0, 0);

  public static Point find(List<Point> points) {
    for (Point pt : point<caret>s) {
      if (pt != null) return pt;
    }
    return ZERO;
  }
}


text:
 //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
 //                                                                        \\
 //                 Centre for Speech Technology Research                  \\
 //                      University of Edinburgh, UK                       \\
 //                        Copyright (c) 1996,1997                         \\
 //                         All Rights Reserved.                           \\
 //   Permission to use, copy, modify, distribute this software and its    \\
 //   documentation for research, educational and individual use only, is  \\
 //   hereby granted without fee, subject to the following conditions:     \\
 //    1. The code must retain the above copyright notice, this list of    \\
 //       conditions and the following disclaimer.                         \\
 //    2. Any modifications must be clearly marked as such.                \\
 //    3. Original authors' names are not deleted.                         \\
 //   This software may not be used for commercial purposes without        \\
 //   specific prior written permission from the authors.                  \\
 //   THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK        \\
 //   DISCLAIM ALL WARRANTIES With REGARD TO THIS SOFTWARE, INCLUDING      \\
 //   ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT   \\
 //   SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE     \\
 //   FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES    \\
 //   WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN   \\
 //   AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,          \\
 //   ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF       \\
 //   THIS SOFTWARE.                                                       \\
 //                                                                        \\
 //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
 //                                                                        \\
 //                  Author: Richard Caley (rjc@cstr.ed.ac.uk)             \\
 //  --------------------------------------------------------------------  \\
 //  Simple excercise of the java speech API synthesis methods.            \\
 //                                                                        \\
 //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\

package cstr.testPrograms ;

import java.lang.*;
import java.util.*;

import javax.speech.*;
import javax.speech.synthesis.*;

import cstr.festival.jsapi.*;

class MySpeakableListener
		extends SpeakableAdapter
{
  SpeakableEvent lastEvent=null;

  public MySpeakableListener()
    {
      lastEvent=null;
    }

  public synchronized void topOfQueue(SpeakableEvent e)
    {
      lastEvent=e;
      notifyAll();
    }

  public synchronized void markerReached(SpeakableEvent e)
    {
      lastEvent=e;
    }

  public synchronized void speakableStarted(SpeakableEvent e)
    {
      lastEvent=e;
    }

  public synchronized void speakableCancelled(SpeakableEvent e)
    {
      lastEvent=e;
    }

  public synchronized void speakablePaused(SpeakableEvent e)
    {
      lastEvent=e;
    }

  public synchronized void speakableResumed(SpeakableEvent e)
    {
      lastEvent=e;
    }

  public synchronized void speakableEnded(SpeakableEvent e)
    {
      lastEvent=e;
      notifyAll();
    }

  public synchronized void wordStarted(SpeakableEvent e)
    {
      lastEvent=e;
      System.out.println("SpeakableEvent wordStarted");
    }

  public synchronized boolean waitForEnd()
    {
      while (lastEvent == null
	     || ( lastEvent.getId() != SpeakableEvent.SPEAKABLE_ENDED
		  && lastEvent.getId() != SpeakableEvent.SPEAKABLE_CANCELLED
		  )
	      )
	{
	  try { wait(); }
	  catch (InterruptedException e)
	    {
	      return false;
	    }
	}
      return true;
    }
}

class VerboseSpeakableListener
	extends MySpeakableListener
	implements SpeakableListener
{
  public VerboseSpeakableListener()
    {
      super();
    }

  public synchronized void topOfQueue(SpeakableEvent e)
    {
      super.topOfQueue(e);
      System.out.println("SpeakableEvent '"+ e.getSource() +"' topOfQueue");
    }

  public synchronized void markerReached(SpeakableEvent e)
    {
      super. markerReached(e);
      System.out.println("SpeakableEvent '"+ e.getSource() +"' markerReached");
    }

  public synchronized void speakableStarted(SpeakableEvent e)
    {
      super.speakableStarted(e);
      System.out.println("SpeakableEvent '"+ e.getSource() +"' speakableStarted");
    }

  public synchronized void speakableCancelled(SpeakableEvent e)
    {
      super.speakableCancelled(e);
      System.out.println("SpeakableEvent '"+ e.getSource() +"' speakableCancelled");
    }

  public synchronized void speakablePaused(SpeakableEvent e)
    {
      super.speakablePaused(e);
      System.out.println("SpeakableEvent '"+ e.getSource() +"' speakablePaused");
    }

  public synchronized void speakableResumed(SpeakableEvent e)
    {
      super.speakableResumed(e);
      System.out.println("SpeakableEvent '"+ e.getSource() +"' speakableResumed");
    }

  public synchronized void speakableEnded(SpeakableEvent e)
    {
      super.speakableEnded(e);
      System.out.println("SpeakableEvent '"+ e.getSource() +"' speakableEnded");
    }

  public synchronized void wordStarted(SpeakableEvent e)
    {
      super.wordStarted(e);
      System.out.println("SpeakableEvent '"+ e.getSource() +"' wordStarted");
    }

}

public class SayHelloWorld
{
  public static void main(String [] args)
    {
      SynthesizerModeDesc desc=null;
      boolean verbose=false;
      boolean sync=false;
      String [] text;

      int i;
      for(i=0; i<args.length; i++)
	if (args[i].equals("-l"))
	  {
	    listSynthesisers();
	    System.exit(1);
	  }
	else if (args[i].equals("-r"))
	  {
	    registerSynthesizer(args[++i]);
	  }
	else if (args[i].equals("-v"))
	  {
	    verbose=true;
	  }
	else if (args[i].equals("-s"))
	  {
	    sync=true;
	  }
	else if (args[i].substring(0,1).equals("-"))
	  {
	    System.err.println("Unknown option " + args[i]);
	    System.exit(1);
	  }
	else
	  break;

      if (i < args.length)
	{
	  text = new String[args.length-i];
	  for(int j=0; i<args.length; i++, j++)
	    {
	      text[j]=args[i];
	    }
	}
      else
	text = new String [] {"Hello world."};

      Synthesizer synth=null;

      try {
	synth = Central.createSynthesizer(desc);
      } catch (EngineException ex) {
	System.err.println("Engine Exception: "+ex.getMessage());
	System.exit(1);
      }

      if (synth==null)
	{
	  System.err.println("Error creating synthesizer");
	  System.exit(1);
	}

      if (verbose)
	describeSynthesizer((SynthesizerModeDesc)synth.getEngineModeDesc());

      try {
	synth.allocate();
      } catch (EngineException ex) {
	System.err.println("EngineException: "+ex.getMessage());
	System.exit(1);
      }

      MySpeakableListener listener=null;

      for(int k=0; k<text.length; k++)
	{
	  if (verbose)
	    listener = new VerboseSpeakableListener();
	  else
	    listener = new MySpeakableListener();

	  if (verbose)
	    System.out.println("Text is '"+ text[k] +"'");
	  synth.speakPlainText(text[k], listener);

	  if (sync)
	    listener.waitForEnd();
	}
      if (!sync && listener != null)
	listener.waitForEnd();

      if (verbose)
	System.out.println("finishing");

       try {
	 synth.deallocate();
      } catch (EngineException ex) {
	System.err.println("EngineException: "+ex.getMessage());
	System.exit(1);
      }
       // If we get here play has finished, but stupid JMF
      // has left threads running so the *%!%!%!*!* interpreter won't
      // exit.
       System.exit(0);
    }

  static void registerSynthesizer(String cl)
    {
      try {
	Central.registerEngineCentral(cl);
      } catch (EngineException ex) {
	System.err.println("Engine exception: "+ex.getMessage());
	System.exit(1);
      }
    }

  static void listSynthesisers()
    {
      try {
	EngineList synths = Central.availableSynthesizers(null);

	Enumeration them = synths.elements();

	while (them.hasMoreElements())
	  {
	    SynthesizerModeDesc desc= (SynthesizerModeDesc)them.nextElement();
	    describeSynthesizer(desc);
	    System.out.println("");
	  }

      } catch (SecurityException ex) {
	System.err.println("Security exception listing synthesisers: "+ex.getMessage());
	System.exit(1);
      }
    }

  static void describeSynthesizer(SynthesizerModeDesc desc)
    {
      Voice [] voices = desc.getVoices();

      System.out.print("engine=" +desc.getEngineName());

      if (desc instanceof FestivalModeDesc)
	{
	  System.out.print(" [" + ((FestivalModeDesc)desc).getServer() +
			   ":" + Integer.toString(((FestivalModeDesc)desc).getPort()) +
			   "]");
	}
      System.out.println("");
      System.out.println("\tlocale  = " +desc.getLocale());
      System.out.println("\tmode    = " +desc.getModeName());
      System.out.println("\trunning = " +desc.getRunning());
      System.out.print("\tvoices  =");

      for(int i=0; i<voices.length; i++)
	System.out.print((i==0?" ":", ")+voices[i].getName());

      System.out.println("");
    }

}