text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Button Effect - Basic</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

  <ion-app>

        <ion-header>
          <ion-toolbar>
            <ion-title>Button Effect - Basic</ion-title>
          </ion-toolbar>
        </ion-header>

        <ion-content padding no-bounce>

            <ion-button size="small">Small</ion-button>

            <ion-button size="large">Large</ion-button>

            <ion-button size="large" fill="outline">Large</ion-button>

            <ion-button size="large" fill="clear">Large</ion-button>

            <ion-ripple-effect></ion-ripple-effect>
            This is just a div + effect behind
            <ion-button onclick="buttonClicked()">Nested button</ion-button>

            This is just a div + effect on top
            <ion-button onclick="buttonClicked()">Nested button</ion-button>
            <ion-ripple-effect></ion-ripple-effect>

            This is just a div + effect
            <ion-ripple-effect></ion-ripple-effect>

        </ion-content>

  </ion-app>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Xunit;

namespace System.ComponentModel.Tests
{
    public class LicenseExceptionTests
    {
        [Theory]
        [InlineData(null)]
        [InlineData(typeof(int))]
        public void Ctor_Type(Type type)
        {
            var exception = new LicenseException(type);
            Assert.Null(exception.InnerException);
            Assert.Equal(-2146232063, exception.HResult);
            Assert.Equal(type, exception.LicensedType);
            Assert.NotEmpty(exception.Message);
        }

        public static IEnumerable<object[]> Ctor_Type_Object_TestData()
        {
            yield return new object[] { null, null };
            yield return new object[] { typeof(int), new object() };
        }

        [Theory]
        [MemberData(nameof(Ctor_Type_Object_TestData))]
        public void Ctor_Type_Object(Type type, object instance)
        {
            var exception = new LicenseException(type, instance);
            Assert.Null(exception.InnerException);
            Assert.Equal(-2146232063, exception.HResult);
            Assert.Equal(type, exception.LicensedType);
            Assert.NotEmpty(exception.Message);
        }

        public static IEnumerable<object[]> Ctor_Type_Object_String_TestData()
        {
            yield return new object[] { null, null, "message" };
            yield return new object[] { typeof(LicenseException), new object(), "message" };
        }

        [Theory]
        [MemberData(nameof(Ctor_Type_Object_String_TestData))]
        public void Ctor_Type_Object_String(Type type, object instance, string message)
        {
            var exception = new LicenseException(type, instance, message);
            Assert.Null(exception.InnerException);
            Assert.Equal(-2146232063, exception.HResult);
            Assert.Equal(type, exception.LicensedType);
            Assert.Equal(message, exception.Message);
        }

        public static IEnumerable<object[]> Ctor_Type_Object_String_Exception_TestData()
        {
            yield return new object[] { null, null, "message", null };
            yield return new object[] { typeof(LicenseException), new object(), "message", new DivideByZeroException() };
        }

        [Theory]
        [MemberData(nameof(Ctor_Type_Object_String_Exception_TestData))]
        public void Ctor_Type_Object_String_Exception(Type type, object instance, string message, Exception innerException)
        {
            var exception = new LicenseException(type, instance, message, innerException);
            Assert.Same(innerException, exception.InnerException);
            Assert.Equal(-2146232063, exception.HResult);
            Assert.Equal(type, exception.LicensedType);
            Assert.Equal(message, exception.Message);
        }

        [Fact]
        public void Ctor_SerializationInfo_StreamingContext()
        {
            using (var stream = new MemoryStream())
            {
                var binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(stream, new LicenseException(typeof(int)));

                stream.Seek(0, SeekOrigin.Begin);
                Assert.IsType<LicenseException>(binaryFormatter.Deserialize(stream));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import SandboxSlide from "../framework/sandbox-slide";

class HtmlExercise extends SandboxSlide {
  validateContext(context) {
    let button = context.document.querySelector("button");
    return button && button.innerText === "Buy Now!" &&
      button.attributes.id &&
      button.attributes.id.value === "cta-buy-now" &&
      button.classList.length == 1 &&
      button.classList.contains("call-to-action");
  }
}

export default HtmlExercise;


text: This tests the ability to make more than one canvas simultaneously. There should be a copy of each image below, and each copy should have the ink filter applied.


text:
return {
  name        = "geoip",
  version     = "0.0.1",
  description = "A pure Lua fast lookup in maxmind GeoIP database",
  url         = "https://github.com/dvv/luvit-geoip/",
  keywords    = { "geo", "geoip", "maxmind", "pure", "lua", "luvit" },
  author      = "Vladimir Dronnikov <dronnikov@gmail.com>",
  main        = "lib/geoip",
}


text:
<?php

namespace Ekyna\Bundle\DemoBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Ekyna\Bundle\AdminBundle\Operator\ResourceOperatorInterface;
use Ekyna\Bundle\CmsBundle\Entity\MenuRepository;
use Ekyna\Bundle\CmsBundle\Entity\PageRepository;
use Ekyna\Bundle\CmsBundle\Entity\SeoRepository;
use Ekyna\Bundle\CmsBundle\Model\PageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class LoadCustomPageData
 * @package Ekyna\Bundle\DemoBundle\DataFixtures\ORM
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class LoadCustomPageData extends AbstractFixture
{
    /**
     * @var ObjectManager
     */
    private $om;

    /**
     * @var ResourceOperatorInterface
     */
    private $pageOperator;

    /**
     * @var PageRepository
     */
    private $pageRepository;

    /**
     * @var MenuRepository
     */
    private $menuRepository;

    /**
     * @var SeoRepository
     */
    private $seoRepository;

    /**
     * @var bool
     */
    private $subTree = false;

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        parent::setContainer($container);

        $this->pageOperator = $this->container->get('ekyna_cms.page.operator');
        $this->pageRepository = $this->container->get('ekyna_cms.page.repository');
        $this->menuRepository = $this->container->get('ekyna_cms.menu.repository');
        $this->seoRepository = $this->container->get('ekyna_cms.seo.repository');
    }

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $om)
    {
        $this->om = $om;

        $unlockedPages = $this->pageRepository->findBy(['locked' => false], ['left' => 'desc']);
        foreach ($unlockedPages as $unlockedPage) {
            $this->createPageChildren($unlockedPage);
            if ($this->subTree) {
                return;
            }
        }
    }

    private function createPageChildren(PageInterface $page, $level = 0)
    {
        for ($p = 0; $p < rand(1,3); $p++) {
            /** @var PageInterface $child */
            $child = $this->pageRepository->createNew();
            $name = $this->faker->sentence(rand(4,6), false);
            $child
                ->setName($name)
                ->setTitle($name)
                ->setBreadcrumb($name)
                ->setStatic(false)
                ->setLocked(false)
                ->setController('default')
                ->setAdvanced(true)
                ->setDynamicPath(false)
            ;

            /** @var \Ekyna\Bundle\CmsBundle\Model\SeoInterface $seo */
            $seo = $this->seoRepository->createNew();
            $seo
                ->setTitle($name)
                ->setDescription($this->faker->sentence(rand(4,6), false))
            ;
            $child->setSeo($seo);

            $this->pageRepository->persistAsLastChildOf($child, $page);
            $this->pageOperator->persist($child);

            $this->createMenu($page, $child);

            if (!$this->subTree && $level < 2) {
                $this->createPageChildren($child, $level + 1);
            }
            if ($level >= 2) {
                $this->subTree = true;
            }
        }
    }

    /**
     * Creates the child page menu.
     *
     * @param PageInterface $page
     * @param PageInterface $childPage
     */
    private  function createMenu(PageInterface $page, PageInterface $childPage)
    {
        if (null !== $menu = $this->menuRepository->findOneByName('main:'.$page->getRoute())) {
            /** @var \Ekyna\Bundle\CmsBundle\Model\MenuInterface $childMenu */
            $childMenu = $this->menuRepository->createNew();
            $childMenu
                ->setName($childPage->getRoute())
                ->setTitle($childPage->getTitle())
                ->setRoute($childPage->getRoute())
                ->setEnabled(true)
            ;
            $this->menuRepository->persistAsLastChildOf($childMenu, $menu);
            $this->om->persist($menu);
            $this->om->flush();
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 99;
    }
}


text:
#ifndef _ODP_TEST_POOL_H_
#define _ODP_TEST_POOL_H_

#include <odp_cunit_common.h>

/* test functions: */
void pool_test_create_destroy_buffer(void);
void pool_test_create_destroy_packet(void);
void pool_test_create_destroy_timeout(void);
void pool_test_create_destroy_buffer_shm(void);
void pool_test_lookup_info_print(void);

/* test arrays: */
extern odp_testinfo_t pool_suite[];

/* test registry: */
extern odp_suiteinfo_t pool_suites[];

/* main test program: */
int pool_main(int argc, char *argv[]);

#endif


text:
use std::string::String;

struct StringBuffer {
    s: String,
}

impl StringBuffer {
    pub fn append(&mut self, v: &str) {
        self.s.push_str(v);
    }
}

fn to_string(sb: StringBuffer) -> String {
    sb.s
}

pub fn main() {
    let mut sb = StringBuffer {
        s: String::new(),
    };
    sb.append("Hello, ");
    sb.append("World!");
    let str = to_string(sb);
    assert_eq!(str, "Hello, World!");
}


text:
import Node from './node'
var reduce = Array.prototype.reduce
var leadingNewLinesRegExp = /^\n*/
var trailingNewLinesRegExp = /\n*$/

export default function Replacement (node, converters, options) {
  this.node = node
}

Replacement.prototype = {
  toString: function () {
    var _this = this

    return reduce.call(this.childNodes, function (output, node) {
      node = new Node(node)

      var replacement
      switch (node.nodeType) {
        case 3:
          replacement = new TextReplacement(node).toString()
          break
        case 8:
          replacement = new CommentReplacement(node).toString()
          break
        default:
          replacement = new ElementReplacement(node).toString()
      }

      return _this.join(output, replacement)
    }, '')
  },

  join: function (string1, string2) {
    var separator = separatingNewlines(string1, string2)

    // Remove trailing/leading newlines and replace with separator
    string1 = string1.replace(trailingNewLinesRegExp, '')
    string2 = string2.replace(leadingNewLinesRegExp, '')

    return string1 + separator + string2
  }
}

function separatingNewlines (string1, string2) {
  var newlines = [
    string1.match(trailingNewLinesRegExp)[0],
    string2.match(leadingNewLinesRegExp)[0]
  ].sort()

  return newlines[newlines.length - 1]
}


text:
var express = require('express');
// To be able to decipher post request, we need to require body-parser
var bodyParser = require('body-parser');
// Refer our server to 'app'
// Reference at http://expressjs.com/api.html
// http://erichonorez.wordpress.com/2013/02/04/a-basic-web-server-with-node-js-and-express/
var app = express();

// very few methods being used here: .use and .get
// .use is a middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
    extended: false
}));
// parse application/json
app.use(bodyParser.json());
app.use(function(req, res, next) {
    // Setup a Cross Origin Resource sharing
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    // var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    // console.log('incoming request from ---> ' + ip);
    // Show the target URL that the user just hit
    var url = req.originalUrl;
    console.log('### requesting ---> ' + url);
    next();
});

app.use('/', express.static(__dirname + '/public'));

// Routing a specific url
// http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
var messages = [];
// API test
app.get('/myApi', function(request, response) {
    var query = request.query;
    var msgToReply = {
        pong: 'You just ping the API. Welcome!, stranger.',
        pingMessage: query
    };
    response.json(msgToReply);
});
// Specify parameter
app.post('/myApi/message', function(request, response) {
    var body = request.body;
    console.log(body.name + ' says: ' + body.message);
    messages.push(body);
    response.json({
        status: 'ok',
        allMessage: messages
    });
});
app.get('/myApi/message/all', function(request, response) {

});
// get messages sent by specific username
// http://expressjs.com/api.html#request
app.get('/myApi/message/:username', function(request, response) {
    var username = request.params.username;
    // search array for name: username
    var itemsToSend = [];
    messages.forEach(function(item) {
        if(item.name === username) {
            itemsToSend.push(item);
        }
    });
    response.json({
        status: 'ok',
        items: items
    });
});
//
var PORT = 3000;
app.listen(PORT, function() {
    console.log('Server running at port ' + PORT + '. Ctrl+C to terminate.');
}); //the port you want to use


text:
package com.centurylink.mdw.workflow.task.notifier;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import com.centurylink.mdw.config.PropertyManager;
import com.centurylink.mdw.constant.PropertyNames;
import com.centurylink.mdw.constant.TaskAttributeConstant;
import com.centurylink.mdw.dataaccess.DataAccessException;
import com.centurylink.mdw.email.TemplatedEmail;
import com.centurylink.mdw.model.task.TaskAction;
import com.centurylink.mdw.model.task.TaskInstance;
import com.centurylink.mdw.model.task.TaskRuntimeContext;
import com.centurylink.mdw.observer.ObserverException;
import com.centurylink.mdw.observer.task.TemplatedNotifier;
import com.centurylink.mdw.services.user.ContextEmailRecipients;
import com.centurylink.mdw.util.MiniCrypter;
import com.centurylink.mdw.util.ParseException;
import com.centurylink.mdw.util.log.LoggerUtil;
import com.centurylink.mdw.util.log.StandardLogger;

public class TaskEmailNotifier extends TemplatedNotifier {

    private static StandardLogger logger = LoggerUtil.getStandardLogger();

    private TaskRuntimeContext context;

    public void sendNotice(TaskRuntimeContext runtimeContext, String taskAction, String outcome)
    throws ObserverException {
        this.context = runtimeContext;
        if (taskAction == null ||
                (!taskAction.equals(TaskAction.CLAIM) && !taskAction.equals(TaskAction.RELEASE))) {
            // avoid nuisance notice to claimer and releaser
            sendEmail(runtimeContext, outcome);
        }
    }

    protected String getFromAddress() {
        String fromAddress = getProperty(PropertyNames.TASK_NOTICE_EMAIL_FROM);
        if (fromAddress == null)
            fromAddress = "mdw@example.com";
        return fromAddress;
    }

    protected String getProperty(String name) {
        return PropertyManager.getProperty(name);
    }

    protected String getSubject(TaskInstance taskInstance, String outcome) {
        return taskInstance.getTaskName() + " ";
    }

    /**
     * Creates the mime message for the e-mail.
     * @param outcome the resulting task status or state
     * @return the message
     */
    protected void sendEmail(TaskRuntimeContext context, String outcome)
    throws ObserverException {
        TaskInstance taskInstance = context.getTaskInstance();
        TemplatedEmail templatedEmail = new TemplatedEmail();
        templatedEmail.setFromAddress(getFromAddress());
        templatedEmail.setSubject(getSubject(taskInstance, outcome));
        templatedEmail.setHtml(true);
        templatedEmail.setTemplateAssetVerSpec(getTemplateSpec());
        templatedEmail.setRuntimeContext(context);

        try {
            List<Address> recipients = getRecipientAddresses(outcome);
            List<Address> ccRecipients = getCcRecipientAddresses(outcome);

            if (templatedEmail.getTemplateBody().contains("${taskActionUrl}")) {

                // send individual e-mails
                for (Address recip : recipients) {
                    String cuid = recip.toString().substring(0, recip.toString().indexOf('@'));
                    String userIdentifier = MiniCrypter.encrypt(cuid);
                    taskInstance.setUserIdentifier(userIdentifier);
                    templatedEmail.setRecipients(new Address[]{recip});
                    templatedEmail.setCcRecipients(new Address[0]);
                    try {
                        templatedEmail.sendEmail();
                    }
                    catch (MessagingException ex) {
                        logger.error(ex.getMessage(), ex);  // do not rethrow
                    }
                }
                if (ccRecipients != null) {
                    for (Address ccRecip : ccRecipients) {
                        String cuid = ccRecip.toString().substring(0, ccRecip.toString().indexOf('@'));
                        String userIdentifier = MiniCrypter.encrypt(cuid);
                        taskInstance.setUserIdentifier(userIdentifier);
                        templatedEmail.setRecipients(new Address[0]);
                        templatedEmail.setCcRecipients(new Address[]{ccRecip});
                        try {
                            templatedEmail.sendEmail();
                        }
                        catch (MessagingException ex) {
                            logger.error(ex.getMessage(), ex);  // do not rethrow
                        }
                    }
                }
            }
            else {
                if ((recipients != null && !recipients.isEmpty()) || (ccRecipients != null && !ccRecipients.isEmpty())) {
                    if (recipients != null)
                        templatedEmail.setRecipients(recipients.toArray(new Address[0]));
                    if (ccRecipients != null)
                        templatedEmail.setCcRecipients(ccRecipients.toArray(new Address[0]));
                    try {
                        templatedEmail.sendEmail();
                    }
                    catch (MessagingException ex) {
                        logger.error(ex.getMessage(), ex);  // do not rethrow
                    }
                }
                else {
                    logger.warn("WARNING: No email recipients for task " + context.getTaskInstanceId() + " " + outcome);
                }
            }
        }
        catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            throw new ObserverException(-1, ex.getMessage(), ex);
        }
    }

    protected List<Address> getRecipientAddresses(String outcome)
    throws ObserverException, AddressException {
        List<Address> addresses = new ArrayList<>();
        for (String email : getRecipients(outcome)) {
            addresses.add(new InternetAddress(email));
        }
        return addresses;
    }

    protected List<Address> getCcRecipientAddresses(String outcome)
    throws ObserverException, AddressException {
        List<Address> addresses = new ArrayList<>();
        for (String email : getCcRecipients(outcome)) {
            addresses.add(new InternetAddress(email));
        }
        return addresses;
    }

    /**
     * Default implementation: If outcome is "Assigned", send only to assignee's email.
     * Otherwise, if Notice Groups attribute is present, the groups so specified
     * are unioned with any recipients resulting from evaluation of the Recipients Expression attribute.
     * If no Notice Groups are specified, any workgroups associated with the task are added to the
     * Recipients Expression outcome.
     */
    protected List<String> getRecipients(String outcome) throws ObserverException {
        if ("Assigned".equals(outcome)) {
            // send e-mail only to assignee
            return Arrays.asList(new String[]{context.getAssignee().getEmail()});
        }
        else {
            try {
                ContextEmailRecipients contextRecipients = new ContextEmailRecipients(context);
                String groups = context.getAttribute(TaskAttributeConstant.NOTICE_GROUPS);
                if (groups != null && !groups.isEmpty() && !groups.equals("[]")) {
                    return contextRecipients.getRecipients(TaskAttributeConstant.NOTICE_GROUPS,
                            TaskAttributeConstant.RECIPIENT_EMAILS);
                }
                else {
                    List<String> emails = contextRecipients.getGroupEmails(context.getTaskInstance().getWorkgroups());
                    for (String email : contextRecipients.getRecipients(null, TaskAttributeConstant.RECIPIENT_EMAILS)) {
                        if (!emails.contains(email))
                            emails.add(email);
                    }
                    return emails;
                }
            }
            catch (DataAccessException | ParseException ex) {
                throw new ObserverException(ex.getMessage(), ex);
            }
        }
    }

    protected List<String> getCcRecipients(String outcome) throws ObserverException {
        if ("Assigned".equals(outcome)) {
            // send e-mail only to assignee
            return Arrays.asList(new String[]{context.getAssignee().getEmail()});
        }
        else {
            try {
                ContextEmailRecipients contextRecipients = new ContextEmailRecipients(context);
                return contextRecipients.getRecipients(TaskAttributeConstant.CC_GROUPS, null);
            }
            catch (DataAccessException | ParseException ex) {
                throw new ObserverException(ex.getMessage(), ex);
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Favolus ohioensis Berk. & Mont.

### Remarks
null


text:
using System.Collections.Generic;

namespace osu.Game.Audio
{
    public interface ISampleInfo
    {
        /// <summary>
        /// Retrieve all possible filenames that can be used as a source, returned in order of preference (highest first).
        /// </summary>
        IEnumerable<string> LookupNames { get; }

        int Volume { get; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.eebbk.mynews"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.eebbk.mynews.activity.Subscription"></activity>
        <activity android:name="com.eebbk.mynews.activity.HotSpot"></activity>
        <activity android:name="com.eebbk.mynews.activity.Fun"></activity>
        <activity android:name="com.eebbk.mynews.activity.Community"></activity>
        <activity android:name="com.eebbk.mynews.subscription.HotDetails"></activity>
    </application>

</manifest>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="Last command" />
<meta name="abstract" content="The Last command moves the cursor to the last row in the ResultSet, then fetches the row." />
<meta name="description" content="The Last command moves the cursor to the last row in the ResultSet, then fetches the row." />
<meta content="Last command, Cursors, fetching next row" name="DC.subject" />
<meta content="Last command, Cursors, fetching next row" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref25570.html" />
<meta scheme="URI" name="DC.Relation" content="ctoolsijcomref23268.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref94092.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref11943.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref37862.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref25753.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref79286.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref24423.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref31510.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref22318.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomrefdescribe.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref20382.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref39042.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref18077.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref30679.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref33358.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref61708.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref36618.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref62772.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref10316.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomrefhold.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref88554.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref12281.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref11128.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomrefnohold.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref12333.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref44032.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref27997.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref61092.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref97975.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref33373.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref12297.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref28886.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref39198.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomrefshow.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref17631.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref16653.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref40155.html" />
<meta scheme="URI" name="DC.Relation" content="rtoolsijcomref34110.html" />
<meta scheme="URI" name="DC.Relation" content="ctoolsijcomref18998.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rtoolsijcomref53869" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Last command</title>

Last command

The <samp class="codeph">Last</samp> command moves the cursor to the last row in
the ResultSet, then fetches the row.

The command displays a banner and the values of the row. The cursor must have
been created with the <samp class="codeph">Get Scroll
Insensitive Cursor</samp> command.

Syntax

LAST Identifier

Example

ij> get scroll insensitive cursor scrollCursor as
'SELECT * FROM menu FOR UPDATE OF price';
ij> absolute 5 scrollCursor;
COURSE    |ITEM                |PRICE
-----------------------------------------------
entree    |lamb chop           |14
ij> last scrollcursor;
COURSE    |ITEM                |PRICE
-----------------------------------------------
dessert   |creme brulee        |6

Parent topic: ij commands and errors reference

Related concepts

ij commands

ij errors

Related reference

Absolute command

After Last command

Async command

Autocommit command

Before First command

Close command

Commit command

Connect command

Describe command

Disconnect command

Driver command

Elapsedtime command

Execute command

Exit command

First command

Get Cursor command

Get Scroll Insensitive Cursor command

Help command

HoldForConnection command

LocalizedDisplay command

MaximumDisplayWidth command

Next command

NoHoldForConnection command

Prepare command

Previous command

Protocol command

Readonly command

Relative command

Remove command

Rollback command

Run command

Set Connection command

Show command

Wait For command

Syntax for comments in ij commands

Syntax for identifiers in ij commands

Syntax for strings in ij commands


text:
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Mets_Mongo_Mapper (MeMoMa)</display-name>

    <servlet>

        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/mvc-dispatcher-servlet.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--
    <context-param>
        <param-name> contextConfigLocation </param-name>
        <param-value>
            classpath*:spring-config.xml
        </param-value>
    </context-param>
        -->

    <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>

    <!-- for older web container (Servlet 2.3)
    <filter>
        <filter-name>requestContextFilter</filter-name>
        <filter-class>org.springframework.web.filter.RequestContextFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>requestContextFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
        -->
</web-app>


text:
/** This is generated, do not edit by hand. **/

#include <jni.h>

#include "Proxy.h"

		namespace titanium {
			namespace xml {

class DocumentProxy : public titanium::Proxy
{
public:
	explicit DocumentProxy(jobject javaObject);

	static void bindProxy(v8::Handle<v8::Object> exports);
	static v8::Handle<v8::FunctionTemplate> getProxyTemplate();
	static void dispose();

	static v8::Persistent<v8::FunctionTemplate> proxyTemplate;
	static jclass javaClass;

private:
	// Methods -----------------------------------------------------------
	static v8::Handle<v8::Value> getElementById(const v8::Arguments&);
	static v8::Handle<v8::Value> createEntityReference(const v8::Arguments&);
	static v8::Handle<v8::Value> getImplementation(const v8::Arguments&);
	static v8::Handle<v8::Value> importNode(const v8::Arguments&);
	static v8::Handle<v8::Value> getElementsByTagNameNS(const v8::Arguments&);
	static v8::Handle<v8::Value> createTextNode(const v8::Arguments&);
	static v8::Handle<v8::Value> createElementNS(const v8::Arguments&);
	static v8::Handle<v8::Value> getDoctype(const v8::Arguments&);
	static v8::Handle<v8::Value> createDocumentFragment(const v8::Arguments&);
	static v8::Handle<v8::Value> createComment(const v8::Arguments&);
	static v8::Handle<v8::Value> createAttributeNS(const v8::Arguments&);
	static v8::Handle<v8::Value> getDocumentElement(const v8::Arguments&);
	static v8::Handle<v8::Value> getElementsByTagName(const v8::Arguments&);
	static v8::Handle<v8::Value> createAttribute(const v8::Arguments&);
	static v8::Handle<v8::Value> createCDATASection(const v8::Arguments&);
	static v8::Handle<v8::Value> createProcessingInstruction(const v8::Arguments&);
	static v8::Handle<v8::Value> createElement(const v8::Arguments&);

	// Dynamic property accessors ----------------------------------------
	static v8::Handle<v8::Value> getter_implementation(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_doctype(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_documentElement(v8::Local<v8::String> property, const v8::AccessorInfo& info);

};

			} // namespace xml
		} // titanium


text:
require('apollojs');

var fs = require('fs');
var urlUtil = require('url');
var pathUtil = require('path');
var async = require('async');
var ftp = require('ftp');

var Prefix = require('./prefix');

var kDelegationDbPath = pathUtil.resolve(__dirname, '../db/delegation.json');
var kDelegationDbLifeTime = 24*60*60*1000;  // 1d

var kRegionalDelegationFiles = [{
  name: 'apnic',
  url: 'ftp://ftp.apnic.net/pub/stats/apnic/delegated-apnic-latest'
}, {
  name: 'arin',
  url: 'ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest'
}, {
  name: 'ripencc',
  url: 'ftp://ftp.ripe.net/pub/stats/ripencc/delegated-ripencc-latest'
}, {
  name: 'lacnic',
  url: 'ftp://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest'
}];

function downloadFile(url, callback) {
  url = urlUtil.parse(url);
  var client = new ftp();
  async.waterfall([
    function(callback) {
      client.on('ready', callback);
    },
    function(callback) {
      client.size(url.pathname, callback);
    },
    function(size, callback) {
      client.get(url.pathname, function(err, stream) {
        if (err)
          return callback(err);
        stream.once('close', function() {
          client.end();
        });
        stream.length = size;
        callback(null, stream);
      });
    }
  ], function(err, stream) {
    if (err)
      client.end();
    callback(err, stream);
  });
  client.on('error', callback);
  client.connect({
    host: url.host
  });
  // DEBUG
  // var path = pathUtil.join(
  //     pathUtil.resolve(__dirname, '../db'),
  //     pathUtil.basename(url.pathname).replace(/^[a-z]+-|-[a-z-]+$/g, ''));
  // var stream = fs.createReadStream(path);
  // stream.length = fs.statSync(path).size;
  // callback(null, stream);
}

var kDelegationEntryPattern = /^[a-z]+\|([A-Z]{2})\|ipv4\|([\d.]+)\|(\d+)/mg;

function processRegionalDelegationFile(bufs, callback) {
  var content = Buffer.concat(bufs).toString();
  bufs.length = 0;
  var delegationsByCountry = {};
  for (var match; match = kDelegationEntryPattern.exec(content); ) {
    if (!delegationsByCountry[match[1]])
      delegationsByCountry[match[1]] = [];
    var maskLength = Prefix.getMaskLength(~(parseInt(match[3], 10) - 1));
    delegationsByCountry[match[1]].push(new Prefix(match[2], maskLength));
  }
  callback(null, delegationsByCountry);
}

var pDelegationDb;
var pDbUpdatingQueue = [];

function generateDb(options, callback) {

  if (pDbUpdatingQueue.push(callback) > 1)
    return;

  var progressBar = options.progressBar;
  if (progressBar) {
    // Preventing ProgressBar terminates before finish downloading all files,
    // in case that one db file finishes downloading before all others establish
    // connections to the servers.
    progressBar.total = kRegionalDelegationFiles.length;
  }

  function handleDownloadStream(stream, callback) {
    if (progressBar) {
      progressBar.total += stream.length - 1;
      progressBar.tick(0);
    }
    var bufs = [];
    stream.on('data', function(chunk) {
      if (progressBar)
        progressBar.tick(chunk.length);
      bufs.push(chunk);
    });
    stream.on('error', function(err) {
      callback(err);
    });
    stream.on('end', function() {
      callback(null, bufs);
    });
    stream.resume();
  }

  async.map(kRegionalDelegationFiles, function(file, callback) {
    async.waterfall([
      downloadFile.bind(null, file.url),
      handleDownloadStream,
      processRegionalDelegationFile
    ], callback);
  }, function(err, regionalDbs) {
    // Make sure progress bar is terminated.
    if (progressBar)
      progressBar.terminate();
    if (!err) {
      var unsortedDb = {};
      regionalDbs.forEach(function(regionalDb) {
        for (var country in regionalDb) {
          if (!unsortedDb[country])
            unsortedDb[country] = [];
          [].push.apply(unsortedDb[country], regionalDb[country]);
        }
      });
      var sortedDb = {};
      Object.keys(unsortedDb).sort().forEach(function(country) {
        sortedDb[country] = unsortedDb[country].sort(Prefix.comparator);
      });
      pDelegationDb = DelegationDb.parse({
        byCountry: sortedDb,
        lastUpdate: Date.now()
      });
      // output as readable JSON file, making it diff friendly.
      fs.writeFileSync(kDelegationDbPath, pDelegationDb.toJSON());
    }
    while (pDbUpdatingQueue.length > 0)
      pDbUpdatingQueue.shift()(err);
  });

}

function getInstance() {
  if (!pDelegationDb)
    pDelegationDb = DelegationDb.parse(
        fs.readFileSync(kDelegationDbPath).toString());
  return pDelegationDb;
}

function DelegationDb() {
  throw new Error('This class cannot be instantiated, use getInstance instead.');
}
$declare(DelegationDb, {
  /**
   * Override default toJSON method, to output a consistent JSON format
   * @return {string} stringified db
   */
  toJSON: function() {
    return JSON.stringify($clone(this), function(key, value) {
      return key[0] != '_' ? value : undefined;
    }, 1);
  },
  /**
   * getter if db is stale
   */
  get isStale() {
    return !this.lastUpdate ||
        Date.now() - this.lastUpdate >= kDelegationDbLifeTime;
  },
  /**
   * getter version of db
   */
  get version() {
    return new Date(this.lastUpdate).toISOString().replace(/\..+$|\D/g, '');
  },
  /**
   * get prefixes of country
   * @param  {string}   country country code
   * @return {[Prefix]}         prefixes delegated to given country
   */
  getPrefixesOfCountry: function(country) {
    this._unwrap();
    country = country.toUpperCase();
    if (!this.byCountry[country])
      throw $error('cannot find country with initial %j', country);
    return this.byCountry[country].map(function(prefix) {
      return prefix.clone();
    });
  },
  /**
   * get country list
   * @return {[string]} country initials
   */
  getCountryList: function() {
    return Object.keys(this.byCountry);
  },
  /**
   * unwrap data in the db.
   */
  _unwrap: function() {
    if (this._unwrapped)
      return;
    var byCountry = this.byCountry;
    for (var country in byCountry) {
      byCountry[country] = byCountry[country].map(Prefix.parse);
    }
    this._unwrapped = true;
  }
});
$define(DelegationDb, {
  /**
   * get delegation db instance, which might be stale.
   */
  getInstance: getInstance,
  /**
   * parse a db
   * @param  {string} db    db
   * @return {DelegationDb} db instance
   */
  parse: function(db) {
    if (!Object.isObjectStrict(db))
      db = JSON.parse(db);
    else
      db._unwrapped = true;
    return $wrap(db, DelegationDb);
  },
  /**
   * update or fix db
   * @param  {object}   options  optional, options see below
   * @param  {Function} callback callback(err, db) when done
   */
  update: function(options, callback) {
    if (!Object.isObjectStrict(options)) {
      callback = options;
      options = {};
    }
    $extend(options, {
      progressBar: null,  // output progress to progress bar
      force: false,       // force update, disregard version check
      useStale: false     // force to use stale data
    });
    try {
      // try load db from file system.
      var db = getInstance();
      if (options.useStale || !options.force && !db.isStale)
        return callback(null);
    } catch(e) {
      // db is corrupted
      // console.error(e.stack);
    }
    generateDb(options, callback);
  }
});

module.exports = DelegationDb;


text:
package org.apache.beam.examples.complete.twitterstreamgenerator;

import static org.junit.Assert.assertArrayEquals;
import static org.mockito.Mockito.when;

import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.IntStream;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.PCollection;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import twitter4j.Status;

@RunWith(JUnit4.class)
public class ReadFromTwitterDoFnTest {
  @Rule public final transient TestPipeline pipeline = TestPipeline.create();
  @Rule public final ExpectedException expectedException = ExpectedException.none();
  @Mock TwitterConnection twitterConnection1;
  @Mock TwitterConnection twitterConnection2;
  @Mock Status status1;
  @Mock Status status2;
  @Mock Status status3;
  @Mock Status status4;
  @Mock Status status5;
  LinkedBlockingQueue<Status> queue1 = new LinkedBlockingQueue<>();
  LinkedBlockingQueue<Status> queue2 = new LinkedBlockingQueue<>();

  @Before
  public void setUp() throws JsonProcessingException {
    MockitoAnnotations.initMocks(this);
    when(status1.getText()).thenReturn("Breaking News1");
    when(status1.getCreatedAt()).thenReturn(new Date());
    when(status2.getText()).thenReturn("Breaking News2");
    when(status2.getCreatedAt()).thenReturn(new Date());
    when(status3.getText()).thenReturn("Breaking News3");
    when(status3.getCreatedAt()).thenReturn(new Date());
    when(status4.getText()).thenReturn("Breaking News4");
    when(status4.getCreatedAt()).thenReturn(new Date());
    when(status5.getText()).thenReturn("Breaking News5");
    when(status5.getCreatedAt()).thenReturn(new Date());
    queue1.offer(status1);
    queue1.offer(status2);
    queue1.offer(status3);
    queue2.offer(status4);
    queue2.offer(status5);
  }

  @Test
  public void testTwitterRead() {
    TwitterConfig twitterConfig = new TwitterConfig.Builder().setTweetsCount(3L).build();
    TwitterConnection.INSTANCE_MAP.put(twitterConfig, twitterConnection1);
    when(twitterConnection1.getQueue()).thenReturn(queue1);
    PCollection<String> result =
        pipeline
            .apply("Create Twitter Connection Configuration", Create.of(twitterConfig))
            .apply(ParDo.of(new ReadFromTwitterDoFn()));
    PAssert.that(result)
        .satisfies(
            pcollection -> {
              List<String> output = new ArrayList<>();
              pcollection.forEach(output::add);
              String[] expected = {"Breaking News1", "Breaking News2", "Breaking News3"};
              String[] actual = new String[output.size()];
              IntStream.range(0, output.size()).forEach((i) -> actual[i] = output.get(i));
              assertArrayEquals("Mismatch found in output", actual, expected);
              return null;
            });
    pipeline.run();
  }

  @Test
  public void testMultipleTwitterConfigs() {
    TwitterConfig twitterConfig1 = new TwitterConfig.Builder().setTweetsCount(3L).build();
    TwitterConfig twitterConfig2 = new TwitterConfig.Builder().setTweetsCount(2L).build();
    TwitterConnection.INSTANCE_MAP.put(twitterConfig1, twitterConnection1);
    TwitterConnection.INSTANCE_MAP.put(twitterConfig2, twitterConnection2);
    when(twitterConnection1.getQueue()).thenReturn(queue1);
    when(twitterConnection2.getQueue()).thenReturn(queue2);
    PCollection<String> result =
        pipeline
            .apply(
                "Create Twitter Connection Configuration",
                Create.of(twitterConfig1, twitterConfig2))
            .apply(ParDo.of(new ReadFromTwitterDoFn()));
    PAssert.that(result)
        .satisfies(
            pcollection -> {
              List<String> output = new ArrayList<>();
              pcollection.forEach(output::add);
              String[] expected = {
                "Breaking News1",
                "Breaking News2",
                "Breaking News3",
                "Breaking News4",
                "Breaking News5"
              };
              String[] actual = new String[output.size()];
              Collections.sort(output);
              IntStream.range(0, output.size()).forEach((i) -> actual[i] = output.get(i));
              assertArrayEquals("Mismatch found in output", actual, expected);
              return null;
            });
    pipeline.run();
  }
}


text:
/* globals module require */

module.exports = (models) => {
    const Thread = models.Thread,
        Post = models.Post,
        User = models.User,
        Category = models.ForumCategory,
        pageCalculator = require('../utils/page-calculator');

    return {
        createNewThread(title, content, imageUrl, category, tagsStr, authorId, authorUsername, authorAvatar) {
            return new Promise((resolve, reject) => {
                let createdOn = new Date();
                let lastPostCreatedOn = new Date();
                let tags = tagsStr.split(',').map(x => x.trim()).filter(x => x != '');
                let author = {
                    username: authorUsername,
                    userId: authorId,
                    userAvatar: authorAvatar
                };

                let thread = new Thread({ title, content, createdOn, lastPostCreatedOn, imageUrl, author, category, tags });
                thread.save((error, dbThread) => {
                    if (error) {
                        return reject(error);
                    }

                    Category.findOne({ linkName: category }, (error, category) => {
                        category.lastPost = {
                            author: author.username,
                            createdOn: new Date(),
                            thread: title
                        };

                        category.threads += 1;
                        category.save();
                    });

                    return resolve(dbThread);
                });
            });
        },
        getNotDeletedThreadsByCategory(category, page) {
            const pageSize = 8;

            return new Promise((resolve, reject) => {
                Thread.find({ category: category })
                    .where({ isDeleted: false })
                    .sort({ lastPostCreatedOn: -1 })
                    .skip((page - 1) * pageSize)
                    .limit(pageSize)
                    .exec((error, threads) => {
                        if (error) {
                            return reject(error);
                        }

                        Thread.count({ category: category }, (error, count) => {
                            if (error) {
                                return reject(error);
                            }

                            let pagesCount = pageCalculator.getPagesCount(count, pageSize);
                            let data = {
                                threads,
                                pagesCount
                            };

                            return resolve(data);
                        });
                    });
            });
        },
        getThreadById(id) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: id }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    }

                    if (!thread) {
                        return resolve();
                    }

                    thread.views += 1;
                    thread.save();

                    return resolve(thread);
                });
            });
        },
        getThreadByIdWithoutRecordingViews(id) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: id }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    }

                    return resolve(thread);
                });
            });
        },
        createNewPost(threadId, content, username, userId, userAvatar) {
            return new Promise((resolve, reject) => {
                let createdOn = new Date();
                let author = {
                    username,
                    userAvatar,
                    userId
                };

                let post = new Post({ content, author, createdOn });
                Thread.findOne({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    } else if (!thread) {
                        return reject('No such thread found!');
                    }

                    thread.posts.push(post);

                    thread.lastPost.author = post.author.username;
                    thread.lastPost.userId = post.author.userId;
                    thread.lastPostCreatedOn = post.createdOn;

                    thread.save((error, success) => {
                        if (error) {
                            return reject(error);
                        }

                        Category.findOne({ linkName: thread.category }, (error, category) => {
                            category.lastPost = {
                                author: author.username,
                                createdOn: new Date(),
                                thread: thread.title
                            };

                            category.posts += 1;
                            category.save();
                        });

                        User.findOne({ _id: userId }, (error, user) => {
                            user.forumPosts += 1;
                            user.save();
                        });

                        return resolve(success);
                    });
                });
            });
        },
        editThread(threadId, title, content, imageUrl, category, tagsStr) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    } else if (!thread) {
                        return reject('No such thread found!');
                    }

                    let tags = tagsStr.split(',').map(x => x.trim()).filter(x => x != '');

                    thread.title = title;
                    thread.content = content;
                    thread.imageUrl = imageUrl;
                    thread.category = category;
                    thread.tags = tags;

                    thread.save((error, result) => {
                        if (error) {
                            return reject(error);
                        }

                        return resolve(result);
                    });
                });
            });
        },
        flagThreadAsDeleted(threadId) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    }

                    thread.isDeleted = true;
                    thread.save((error, success) => {
                        if (error) {
                            console.log(error);
                            return reject(error);
                        }

                        Category.findOne({ linkName: thread.category }, (error, category) => {
                            category.threads -= 1;
                            category.posts -= thread.posts.length;

                            Thread.findOne({ category: thread.category })
                                .where({ isDeleted: false })
                                .exec((error, resThread) => {
                                    if (error || !resThread) {
                                        category.lastPost = null;
                                    } else {
                                        category.lastPost.author = resThread.author.username;
                                        category.lastPost.thread = resThread.title;
                                        category.lastPost.createdOn = resThread.lastPostCreatedOn;
                                    }

                                    category.save();
                                });
                        });

                        return resolve(success);
                    });
                });
            });
        },
        flagThreadAsActive(threadId) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    }

                    thread.isDeleted = false;
                    thread.save((error, success) => {
                        if (error) {
                            return reject(error);
                        }

                        Category.findOne({ linkName: thread.category }, (error, category) => {
                            category.threads += 1;
                            category.posts += thread.posts.length;

                            Thread.findOne({ category: thread.category })
                                .where({ isDeleted: false })
                                .exec((error, resThread) => {
                                    if (error || !resThread) {
                                        category.lastPost = null;
                                    } else {
                                        category.lastPost.author = resThread.author.username;
                                        category.lastPost.thread = resThread.title;
                                        category.lastPost.createdOn = resThread.lastPostCreatedOn;
                                    }

                                    category.save();
                                });
                        });

                        return resolve(success);
                    });
                });
            });
        },
        deleteThread(threadId) {
            return new Promise((resolve, reject) => {
                Thread.findOneAndRemove({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    }

                    if (!thread.isDeleted) {
                        Category.findOne({ linkName: thread.category }, (error, category) => {
                            category.threads -= 1;
                            category.posts -= thread.posts.length;

                            Thread.findOne({ category: thread.category })
                                .where({ isDeleted: false })
                                .exec((error, resThread) => {
                                    if (error || !resThread) {
                                        category.lastPost = null;
                                    } else {
                                        category.lastPost.author = resThread.author.username;
                                        category.lastPost.thread = resThread.title;
                                        category.lastPost.createdOn = resThread.lastPostCreatedOn;
                                    }

                                    category.save();
                                });
                        });
                    }

                    return resolve(thread);
                });
            });
        },
        editPost(threadId, postId, content) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    } else if (!thread) {
                        return reject('No such thread found!');
                    } else if (!thread.posts) {
                        return reject('No such post found!');
                    }

                    let post = thread.posts.find(p => p._id.toString() == postId);
                    if (!post) {
                        return reject('No such post found!');
                    }

                    post.content = content;

                    thread.save((error, result) => {
                        if (error) {
                            return reject(error);
                        }

                        return resolve(post);
                    });
                });
            });
        },
        deletePost(threadId, postId) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    } else if (!thread) {
                        return reject('No such thread found!');
                    } else if (!thread.posts) {
                        return reject('No such post found!');
                    }

                    let post = thread.posts.find(p => p._id.toString() == postId);
                    if (!post) {
                        return reject('No such post found!');
                    }

                    let index = thread.posts.indexOf(post);
                    thread.posts.splice(index, 1);

                    if (thread.posts.length) {
                        let lastPost = thread.posts[thread.posts.length - 1];
                        thread.lastPost.author = lastPost.author.username;
                        thread.lastPost.userId = lastPost.author.userId;
                        thread.lastPostCreatedOn = lastPost.createdOn;
                    } else {
                        thread.lastPost = null;
                        thread.lastPostCreatedOn = thread.createdOn;
                    }

                    thread.save((error, result) => {
                        if (error) {
                            return reject(error);
                        }

                        Category.findOne({ linkName: thread.category }, (error, category) => {
                            category.posts -= 1;

                            Thread.findOne({ category: thread.category })
                                .where({ isDeleted: false })
                                .exec((error, resThread) => {
                                    if (error || !resThread) {
                                        category.lastPost = null;
                                    } else {
                                        category.lastPost.author = resThread.author.username;
                                        category.lastPost.thread = resThread.title;
                                        category.lastPost.createdOn = resThread.lastPostCreatedOn;
                                    }

                                    category.save();
                                });
                        });

                        User.findOne({ _id: post.author.userId }, (error, user) => {
                            user.forumPosts -= 1;
                            user.save();
                        });

                        return resolve(result);
                    });
                });
            });
        },
        toggleLikeThread(threadId, username) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    } else if (!thread) {
                        return reject('No such thread found!');
                    }

                    if (!thread.likes || !thread.likes.includes(username)) {
                        thread.likes.push(username);

                        if (thread.dislikes && thread.dislikes.includes(username)) {
                            let index = thread.dislikes.indexOf(username);
                            thread.dislikes.splice(index, 1);
                        }
                    } else {
                        let index = thread.likes.indexOf(l => l == username);
                        thread.likes.splice(index, 1);
                    }

                    thread.save((error, result) => {
                        if (error) {
                            return reject(error);
                        }

                        return resolve(result);
                    });
                });
            });
        },
        toggleDislikeThread(threadId, username) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    } else if (!thread) {
                        return reject('No such thread found!');
                    }

                    if (!thread.dislikes || !thread.dislikes.includes(username)) {
                        thread.dislikes.push(username);

                        if (thread.likes && thread.likes.includes(username)) {
                            let index = thread.likes.indexOf(username);
                            thread.likes.splice(index, 1);
                        }
                    } else {
                        let index = thread.dislikes.indexOf(l => l == username);
                        thread.dislikes.splice(index, 1);
                    }

                    thread.save((error, result) => {
                        if (error) {
                            return reject(error);
                        }

                        return resolve(result);
                    });
                });
            });
        },
        toggleLikePost(threadId, postId, username) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    } else if (!thread) {
                        return reject('No such thread found!');
                    } else if (!thread.posts) {
                        return reject('No such post found!');
                    }

                    let post = thread.posts.find(p => p._id.toString() == postId);
                    if (!post) {
                        return reject('No such post found!');
                    }

                    if (!post.likes || !post.likes.includes(username)) {
                        post.likes.push(username);

                        if (post.dislikes && post.dislikes.includes(username)) {
                            let index = post.dislikes.indexOf(username);
                            post.dislikes.splice(index, 1);
                        }
                    } else {
                        let index = post.likes.indexOf(l => l == username);
                        post.likes.splice(index, 1);
                    }

                    thread.save((error, result) => {
                        if (error) {
                            return reject(error);
                        }

                        return resolve(post);
                    });
                });
            });
        },
        toggleDislikePost(threadId, postId, username) {
            return new Promise((resolve, reject) => {
                Thread.findOne({ _id: threadId }, (error, thread) => {
                    if (error) {
                        return reject(error);
                    } else if (!thread) {
                        return reject('No such thread found!');
                    } else if (!thread.posts) {
                        return reject('No such post found!');
                    }

                    let post = thread.posts.find(p => p._id.toString() == postId);
                    if (!post) {
                        return reject('No such post found!');
                    }

                    if (!post.dislikes || !post.dislikes.includes(username)) {
                        post.dislikes.push(username);

                        if (post.likes && post.likes.includes(username)) {
                            let index = post.likes.indexOf(username);
                            post.likes.splice(index, 1);
                        }
                    } else {
                        let index = post.dislikes.indexOf(l => l == username);
                        post.dislikes.splice(index, 1);
                    }

                    thread.save((error, result) => {
                        if (error) {
                            return reject(error);
                        }

                        return resolve(post);
                    });
                });
            });
        },
        getAllThreadsAdmin(page, query, sort) {
            let pageSize = 10;

            let sortMethod = sort == 'status' ? { isDeleted: -1, lastPostCreatedOn: -1 } : sort == 'category' ? { category: 1, lastPostCreatedOn: -1, } : { lastPostCreatedOn: -1 };
            let queryObj = query.trim() ? { title: { '$regex': query.trim(), '$options': 'i' } } : {};

            return new Promise((resolve, reject) => {
                Thread.find(queryObj)
                    .sort(sortMethod)
                    .skip((page - 1) * pageSize)
                    .limit(pageSize)
                    .exec((error, threads) => {
                        if (error) {
                            return reject(error);
                        }

                        Thread.count(queryObj, (error, count) => {
                            if (error) {
                                return reject(error);
                            }

                            let pagesCount = pageCalculator.getPagesCount(count, pageSize);
                            let result = {
                                threads,
                                pagesCount
                            };

                            return resolve(result);
                        });
                    });
            });
        },
        searchThreads(page, query) {
            let pageSize = 5;

            let queryObj = query.trim() ? { title: { '$regex': query.trim(), '$options': 'i' } } : {};

            return new Promise((resolve, reject) => {
                Thread.find(queryObj)
                    .where({ isDeleted: false })
                    .sort({ lastPostCreatedOn: -1 })
                    .skip((page - 1) * pageSize)
                    .limit(pageSize)
                    .exec((error, threads) => {
                        if (error) {
                            return reject(error);
                        }

                        Thread.count(queryObj, (error, count) => {
                            if (error) {
                                return reject(error);
                            }

                            let pagesCount = pageCalculator.getPagesCount(count, pageSize);
                            let result = {
                                threads,
                                pagesCount
                            };

                            return resolve(result);
                        });
                    });
            });
        }
    };
};


text:
package com.amazonaws.services.ecs.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DiscoverPollEndpointRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The container instance ID or full ARN of the container instance. The ARN contains the arn:aws:ecs
     * namespace, followed by the Region of the container instance, the AWS account ID of the container instance owner,
     * the container-instance namespace, and then the container instance ID. For example,
     * arn:aws:ecs:region:aws_account_id:container-instance/container_instance_ID.
     *

     */
    private String containerInstance;
    /**
     *

     * The short name or full Amazon Resource Name (ARN) of the cluster to which the container instance belongs.
     *

     */
    private String cluster;

    /**
     *

     * The container instance ID or full ARN of the container instance. The ARN contains the arn:aws:ecs
     * namespace, followed by the Region of the container instance, the AWS account ID of the container instance owner,
     * the container-instance namespace, and then the container instance ID. For example,
     * arn:aws:ecs:region:aws_account_id:container-instance/container_instance_ID.
     *

     *
     * @param containerInstance
     *        The container instance ID or full ARN of the container instance. The ARN contains the
     *        arn:aws:ecs namespace, followed by the Region of the container instance, the AWS account ID
     *        of the container instance owner, the container-instance namespace, and then the container
     *        instance ID. For example,
     *        arn:aws:ecs:region:aws_account_id:container-instance/container_instance_ID.
     */

    public void setContainerInstance(String containerInstance) {
        this.containerInstance = containerInstance;
    }

    /**
     *

     * The container instance ID or full ARN of the container instance. The ARN contains the arn:aws:ecs
     * namespace, followed by the Region of the container instance, the AWS account ID of the container instance owner,
     * the container-instance namespace, and then the container instance ID. For example,
     * arn:aws:ecs:region:aws_account_id:container-instance/container_instance_ID.
     *

     *
     * @return The container instance ID or full ARN of the container instance. The ARN contains the
     *         arn:aws:ecs namespace, followed by the Region of the container instance, the AWS account ID
     *         of the container instance owner, the container-instance namespace, and then the container
     *         instance ID. For example,
     *         arn:aws:ecs:region:aws_account_id:container-instance/container_instance_ID.
     */

    public String getContainerInstance() {
        return this.containerInstance;
    }

    /**
     *

     * The container instance ID or full ARN of the container instance. The ARN contains the arn:aws:ecs
     * namespace, followed by the Region of the container instance, the AWS account ID of the container instance owner,
     * the container-instance namespace, and then the container instance ID. For example,
     * arn:aws:ecs:region:aws_account_id:container-instance/container_instance_ID.
     *

     *
     * @param containerInstance
     *        The container instance ID or full ARN of the container instance. The ARN contains the
     *        arn:aws:ecs namespace, followed by the Region of the container instance, the AWS account ID
     *        of the container instance owner, the container-instance namespace, and then the container
     *        instance ID. For example,
     *        arn:aws:ecs:region:aws_account_id:container-instance/container_instance_ID.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DiscoverPollEndpointRequest withContainerInstance(String containerInstance) {
        setContainerInstance(containerInstance);
        return this;
    }

    /**
     *

     * The short name or full Amazon Resource Name (ARN) of the cluster to which the container instance belongs.
     *

     *
     * @param cluster
     *        The short name or full Amazon Resource Name (ARN) of the cluster to which the container instance belongs.
     */

    public void setCluster(String cluster) {
        this.cluster = cluster;
    }

    /**
     *

     * The short name or full Amazon Resource Name (ARN) of the cluster to which the container instance belongs.
     *

     *
     * @return The short name or full Amazon Resource Name (ARN) of the cluster to which the container instance belongs.
     */

    public String getCluster() {
        return this.cluster;
    }

    /**
     *

     * The short name or full Amazon Resource Name (ARN) of the cluster to which the container instance belongs.
     *

     *
     * @param cluster
     *        The short name or full Amazon Resource Name (ARN) of the cluster to which the container instance belongs.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DiscoverPollEndpointRequest withCluster(String cluster) {
        setCluster(cluster);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getContainerInstance() != null)
            sb.append("ContainerInstance: ").append(getContainerInstance()).append(",");
        if (getCluster() != null)
            sb.append("Cluster: ").append(getCluster());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DiscoverPollEndpointRequest == false)
            return false;
        DiscoverPollEndpointRequest other = (DiscoverPollEndpointRequest) obj;
        if (other.getContainerInstance() == null ^ this.getContainerInstance() == null)
            return false;
        if (other.getContainerInstance() != null && other.getContainerInstance().equals(this.getContainerInstance()) == false)
            return false;
        if (other.getCluster() == null ^ this.getCluster() == null)
            return false;
        if (other.getCluster() != null && other.getCluster().equals(this.getCluster()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getContainerInstance() == null) ? 0 : getContainerInstance().hashCode());
        hashCode = prime * hashCode + ((getCluster() == null) ? 0 : getCluster().hashCode());
        return hashCode;
    }

    @Override
    public DiscoverPollEndpointRequest clone() {
        return (DiscoverPollEndpointRequest) super.clone();
    }

}


text: Mapstruct Gradle Plugin