text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Various table operations
 *
 * @package PhpMyAdmin
 */
use PhpMyAdmin\Index;
use PhpMyAdmin\Message;
use PhpMyAdmin\Partition;
use PhpMyAdmin\Operations;
use PhpMyAdmin\Relation;
use PhpMyAdmin\Response;
use PhpMyAdmin\Table;
use PhpMyAdmin\Util;

/**
 *
 */
require_once 'libraries/common.inc.php';

/**
 * functions implementation for this script
 */
require_once 'libraries/check_user_privileges.inc.php';

// lower_case_table_names=1 `DB` becomes `db`
$lowerCaseNames = $GLOBALS['dbi']->getLowerCaseNames() === '1';

if ($lowerCaseNames) {
    $GLOBALS['table'] = mb_strtolower(
        $GLOBALS['table']
    );
}

$pma_table = new Table($GLOBALS['table'], $GLOBALS['db']);

/**
 * Load JavaScript files
 */
$response = Response::getInstance();
$header   = $response->getHeader();
$scripts  = $header->getScripts();
$scripts->addFile('tbl_operations.js');

/**
 * Runs common work
 */
require 'libraries/tbl_common.inc.php';
$url_query .= '&goto=tbl_operations.php&back=tbl_operations.php';
$url_params['goto'] = $url_params['back'] = 'tbl_operations.php';

/**
 * Gets relation settings
 */
$relation = new Relation();
$cfgRelation = $relation->getRelationsParam();

// reselect current db (needed in some cases probably due to
// the calling of PhpMyAdmin\Relation)
$GLOBALS['dbi']->selectDb($GLOBALS['db']);

/**
 * Gets tables information
 */
$pma_table = $GLOBALS['dbi']->getTable(
    $GLOBALS['db'],
    $GLOBALS['table']
);
$reread_info = $pma_table->getStatusInfo(null, false);
$GLOBALS['showtable'] = $pma_table->getStatusInfo(null, (isset($reread_info) && $reread_info ? true : false));
if ($pma_table->isView()) {
    $tbl_is_view = true;
    $tbl_storage_engine = __('View');
    $show_comment = null;
} else {
    $tbl_is_view = false;
    $tbl_storage_engine = $pma_table->getStorageEngine();
    $show_comment = $pma_table->getComment();
}
$tbl_collation = $pma_table->getCollation();
$table_info_num_rows = $pma_table->getNumRows();
$row_format = $pma_table->getRowFormat();
$auto_increment = $pma_table->getAutoIncrement();
$create_options = $pma_table->getCreateOptions();

// set initial value of these variables, based on the current table engine
if ($pma_table->isEngine('ARIA')) {
    // the value for transactional can be implicit
    // (no create option found, in this case it means 1)
    // or explicit (option found with a value of 0 or 1)
    // ($create_options['transactional'] may have been set by Table class,
    // from the $create_options)
    $create_options['transactional'] = (isset($create_options['transactional']) && $create_options['transactional'] == '0')
        ? '0'
        : '1';
    $create_options['page_checksum'] = (isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : '';
}

$pma_table = $GLOBALS['dbi']->getTable(
    $GLOBALS['db'],
    $GLOBALS['table']
);
$reread_info = false;
$table_alters = array();

$operations = new Operations();

/**
 * If the table has to be moved to some other database
 */
if (isset($_POST['submit_move']) || isset($_POST['submit_copy'])) {
    //$_message = '';
    $operations->moveOrCopyTable($db, $table);
    // This was ended in an Ajax call
    exit;
}
/**
 * If the table has to be maintained
 */
if (isset($_POST['table_maintenance'])) {
    include_once 'sql.php';
    unset($result);
}
/**
 * Updates table comment, type and options if required
 */
if (isset($_POST['submitoptions'])) {
    $_message = '';
    $warning_messages = array();

    if (isset($_POST['new_name'])) {
        // lower_case_table_names=1 `DB` becomes `db`
        if ($lowerCaseNames) {
            $_POST['new_name'] = mb_strtolower(
                $_POST['new_name']
            );
        }
        // Get original names before rename operation
        $oldTable = $pma_table->getName();
        $oldDb = $pma_table->getDbName();

        if ($pma_table->rename($_POST['new_name'])) {
            if (isset($_POST['adjust_privileges'])
                && ! empty($_POST['adjust_privileges'])
            ) {
                $operations->adjustPrivilegesRenameOrMoveTable(
                    $oldDb, $oldTable, $_POST['db'], $_POST['new_name']
                );
            }

            // Reselect the original DB
            $GLOBALS['db'] = $oldDb;
            $GLOBALS['dbi']->selectDb($oldDb);
            $_message .= $pma_table->getLastMessage();
            $result = true;
            $GLOBALS['table'] = $pma_table->getName();
            $reread_info = true;
            $reload = true;
        } else {
            $_message .= $pma_table->getLastError();
            $result = false;
        }
    }

    if (! empty($_POST['new_tbl_storage_engine'])
        && mb_strtoupper($_POST['new_tbl_storage_engine']) !== $tbl_storage_engine
    ) {
        $new_tbl_storage_engine = mb_strtoupper($_POST['new_tbl_storage_engine']);

        if ($pma_table->isEngine('ARIA')) {
            $create_options['transactional'] = (isset($create_options['transactional']) && $create_options['transactional'] == '0')
                ? '0'
                : '1';
            $create_options['page_checksum'] = (isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : '';
        }
    } else {
        $new_tbl_storage_engine = '';
    }

    $row_format = (isset($create_options['row_format']))
        ? $create_options['row_format']
        : $pma_table->getRowFormat();

    $table_alters = $operations->getTableAltersArray(
        $pma_table,
        $create_options['pack_keys'],
        (empty($create_options['checksum']) ? '0' : '1'),
        ((isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : ''),
        (empty($create_options['delay_key_write']) ? '0' : '1'),
        $row_format,
        $new_tbl_storage_engine,
        ((isset($create_options['transactional']) && $create_options['transactional'] == '0') ? '0' : '1'),
        $tbl_collation
    );

    if (count($table_alters) > 0) {
        $sql_query      = 'ALTER TABLE '
            . Util::backquote($GLOBALS['table']);
        $sql_query     .= "\r\n" . implode("\r\n", $table_alters);
        $sql_query     .= ';';
        $result        .= $GLOBALS['dbi']->query($sql_query) ? true : false;
        $reread_info    = true;
        unset($table_alters);
        $warning_messages = $operations->getWarningMessagesArray();
    }

    if (isset($_POST['tbl_collation'])
        && ! empty($_POST['tbl_collation'])
        && isset($_POST['change_all_collations'])
        && ! empty($_POST['change_all_collations'])
    ) {
        $operations->changeAllColumnsCollation(
            $GLOBALS['db'], $GLOBALS['table'], $_POST['tbl_collation']
        );
    }

    if (isset($_POST['tbl_collation']) && empty($_POST['tbl_collation'])) {
        $response = Response::getInstance();
        if ($response->isAjax()) {
            $response->setRequestStatus(false);
            $response->addJSON(
                'message',
                Message::error(__('No collation provided.'))
            );
            exit;
        }
    }
}
/**
 * Reordering the table has been requested by the user
 */
if (isset($_POST['submitorderby']) && ! empty($_POST['order_field'])) {
    list($sql_query, $result) = $operations->getQueryAndResultForReorderingTable();
} // end if

/**
 * A partition operation has been requested by the user
 */
if (isset($_POST['submit_partition'])
    && ! empty($_POST['partition_operation'])
) {
    list($sql_query, $result) = $operations->getQueryAndResultForPartition();
} // end if

if ($reread_info) {
    // to avoid showing the old value (for example the AUTO_INCREMENT) after
    // a change, clear the cache
    $GLOBALS['dbi']->clearTableCache();
    $GLOBALS['dbi']->selectDb($GLOBALS['db']);
    $GLOBALS['showtable'] = $pma_table->getStatusInfo(null, true);
    if ($pma_table->isView()) {
        $tbl_is_view = true;
        $tbl_storage_engine = __('View');
        $show_comment = null;
    } else {
        $tbl_is_view = false;
        $tbl_storage_engine = $pma_table->getStorageEngine();
        $show_comment = $pma_table->getComment();
    }
    $tbl_collation = $pma_table->getCollation();
    $table_info_num_rows = $pma_table->getNumRows();
    $row_format = $pma_table->getRowFormat();
    $auto_increment = $pma_table->getAutoIncrement();
    $create_options = $pma_table->getCreateOptions();
}
unset($reread_info);

if (isset($result) && empty($message_to_show)) {
    if (empty($_message)) {
        if (empty($sql_query)) {
            $_message = Message::success(__('No change'));
        } else {
            $_message = $result
                ? Message::success()
                : Message::error();
        }

        if ($response->isAjax()) {
            $response->setRequestStatus($_message->isSuccess());
            $response->addJSON('message', $_message);
            if (!empty($sql_query)) {
                $response->addJSON(
                    'sql_query', Util::getMessage(null, $sql_query)
                );
            }
            exit;
        }
    } else {
        $_message = $result
            ? Message::success($_message)
            : Message::error($_message);
    }

    if (! empty($warning_messages)) {
        $_message = new Message;
        $_message->addMessagesString($warning_messages);
        $_message->isError(true);
        if ($response->isAjax()) {
            $response->setRequestStatus(false);
            $response->addJSON('message', $_message);
            if (!empty($sql_query)) {
                $response->addJSON(
                    'sql_query', Util::getMessage(null, $sql_query)
                );
            }
            exit;
        }
        unset($warning_messages);
    }

    if (empty($sql_query)) {
        $response->addHTML(
            $_message->getDisplay()
        );
    } else {
        $response->addHTML(
            Util::getMessage($_message, $sql_query)
        );
    }
    unset($_message);
}

$url_params['goto']
    = $url_params['back']
        = 'tbl_operations.php';

/**
 * Get columns names
 */
$columns = $GLOBALS['dbi']->getColumns($GLOBALS['db'], $GLOBALS['table']);

/**
 * Displays the page
 */

/**
 * Order the table
 */
$hideOrderTable = false;
// `ALTER TABLE ORDER BY` does not make sense for InnoDB tables that contain
// a user-defined clustered index (PRIMARY KEY or NOT NULL UNIQUE index).
// InnoDB always orders table rows according to such an index if one is present.
if ($tbl_storage_engine == 'INNODB') {
    $indexes = Index::getFromTable($GLOBALS['table'], $GLOBALS['db']);
    foreach ($indexes as $name => $idx) {
        if ($name == 'PRIMARY') {
            $hideOrderTable = true;
            break;
        } elseif (! $idx->getNonUnique()) {
            $notNull = true;
            foreach ($idx->getColumns() as $column) {
                if ($column->getNull()) {
                    $notNull = false;
                    break;
                }
            }
            if ($notNull) {
                $hideOrderTable = true;
                break;
            }
        }
    }
}
if (! $hideOrderTable) {
    $response->addHTML($operations->getHtmlForOrderTheTable($columns));
}

/**
 * Move table
 */
$response->addHTML($operations->getHtmlForMoveTable());

if (mb_strstr($show_comment, '; InnoDB free') === false) {
    if (mb_strstr($show_comment, 'InnoDB free') === false) {
        // only user entered comment
        $comment = $show_comment;
    } else {
        // here we have just InnoDB generated part
        $comment = '';
    }
} else {
    // remove InnoDB comment from end, just the minimal part (*? is non greedy)
    $comment = preg_replace('@; InnoDB free:.*?$@', '', $show_comment);
}

// PACK_KEYS: MyISAM or ISAM
// DELAY_KEY_WRITE, CHECKSUM, : MyISAM only
// AUTO_INCREMENT: MyISAM and InnoDB since 5.0.3, PBXT

// Here should be version check for InnoDB, however it is supported
// in >5.0.4, >4.1.12 and >4.0.11, so I decided not to
// check for version

$response->addHTML(
    $operations->getTableOptionDiv(
        $pma_table, $comment, $tbl_collation, $tbl_storage_engine,
        $create_options['pack_keys'],
        $auto_increment,
        (empty($create_options['delay_key_write']) ? '0' : '1'),
        ((isset($create_options['transactional']) && $create_options['transactional'] == '0') ? '0' : '1'),
        ((isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : ''),
        (empty($create_options['checksum']) ? '0' : '1')
    )
);

/**
 * Copy table
 */
$response->addHTML($operations->getHtmlForCopytable());

/**
 * Table maintenance
 */
$response->addHTML(
    $operations->getHtmlForTableMaintenance($pma_table, $url_params)
);

if (! (isset($db_is_system_schema) && $db_is_system_schema)) {
    $truncate_table_url_params = array();
    $drop_table_url_params = array();

    if (! $tbl_is_view
        && ! (isset($db_is_system_schema) && $db_is_system_schema)
    ) {
        $this_sql_query = 'TRUNCATE TABLE '
            . Util::backquote($GLOBALS['table']);
        $truncate_table_url_params = array_merge(
            $url_params,
            array(
                'sql_query' => $this_sql_query,
                'goto' => 'tbl_structure.php',
                'reload' => '1',
                'message_to_show' => sprintf(
                    __('Table %s has been emptied.'),
                    htmlspecialchars($table)
                ),
            )
        );
    }
    if (! (isset($db_is_system_schema) && $db_is_system_schema)) {
        $this_sql_query = 'DROP TABLE '
            . Util::backquote($GLOBALS['table']);
        $drop_table_url_params = array_merge(
            $url_params,
            array(
                'sql_query' => $this_sql_query,
                'goto' => 'db_operations.php',
                'reload' => '1',
                'purge' => '1',
                'message_to_show' => sprintf(
                    ($tbl_is_view
                        ? __('View %s has been dropped.')
                        : __('Table %s has been dropped.')
                    ),
                    htmlspecialchars($table)
                ),
                // table name is needed to avoid running
                // PhpMyAdmin\RelationCleanup::database() on the whole db later
                'table' => $GLOBALS['table'],
            )
        );
    }
    $response->addHTML(
        $operations->getHtmlForDeleteDataOrTable(
            $truncate_table_url_params,
            $drop_table_url_params
        )
    );
}

if (Partition::havePartitioning()) {
    $partition_names = Partition::getPartitionNames($db, $table);
    // show the Partition maintenance section only if we detect a partition
    if (! is_null($partition_names[0])) {
        $response->addHTML(
            $operations->getHtmlForPartitionMaintenance($partition_names, $url_params)
        );
    } // end if
} // end if
unset($partition_names);

// Referential integrity check

if ($cfgRelation['relwork']) {
    $GLOBALS['dbi']->selectDb($GLOBALS['db']);
    $foreign = $relation->getForeigners($GLOBALS['db'], $GLOBALS['table'], '', 'internal');

    if (! empty($foreign)) {
        $response->addHTML(
            $operations->getHtmlForReferentialIntegrityCheck($foreign, $url_params)
        );
    } // end if ($foreign)

} // end  if (!empty($cfg['Server']['relation']))


text:
package org.jadira.usertype.dateandtime.joda;

import org.jadira.usertype.dateandtime.joda.columnmapper.StringColumnLocalTimeMapper;
import org.jadira.usertype.spi.shared.AbstractSingleColumnUserType;
import org.joda.time.LocalTime;

/**
 * Persist {@link LocalTime} via Hibernate. This type is
 * mostly compatible with org.joda.time.contrib.hibernate.PersistentLocalTimeAsString however
 * you should note that JodaTime's {@link org.joda.time.LocalTime} has only millisecond precision,
 * whilst JSR 310 offers nanosecond precision. When interpreting nanosecond values, Joda Time will
 * round down to the nearest millisecond.
 */
public class PersistentLocalTimeAsString extends AbstractSingleColumnUserType<LocalTime, String, StringColumnLocalTimeMapper> {

    private static final long serialVersionUID = 4782088428301719141L;
}

redpajama_set_name: RedPajamaGithub


text:
import asyncio, discord
from   operator import itemgetter
from   discord.ext import commands
from   Cogs import Utils, DisplayName

def setup(bot):
	# Add the bot and deps
	settings = bot.get_cog("Settings")
	bot.add_cog(DJRoles(bot, settings))

class DJRoles(commands.Cog):

	# Init with the bot reference, and a reference to the settings var and xp var
	def __init__(self, bot, settings):
		self.bot = bot
		self.settings = settings
		global Utils, DisplayName
		Utils = self.bot.get_cog("Utils")
		DisplayName = self.bot.get_cog("DisplayName")

	@commands.command(pass_context=True)
	async def adddj(self, ctx, *, role : str = None):
		"""Adds a new role to the dj list (bot-admin only)."""
		usage = 'Usage: `{}adddj [role]`'.format(ctx.prefix)
		if not await Utils.is_bot_admin_reply(ctx): return

		if role == None:
			return await ctx.send(usage)

		roleName = role
		if type(role) is str:
			if role.lower() == "everyone" or role.lower() == "@everyone":
				role = ctx.guild.default_role
			else:
				role = DisplayName.roleForName(roleName, ctx.guild)
			if not role:
				msg = 'I couldn\'t find *{}*...'.format(roleName)
				return await ctx.send(Utils.suppressed(ctx,msg))

		# Now we see if we already have that role in our list
		promoArray = self.settings.getServerStat(ctx.guild, "DJArray")
		if next((x for x in promoArray if str(x["ID"])==str(role.id)),False):
			msg = '**{}** is already in the list.'.format(role.name)
			return await ctx.send(Utils.suppressed(ctx,msg))

		# If we made it this far - then we can add it
		promoArray.append({ 'ID' : role.id, 'Name' : role.name })
		self.settings.setServerStat(ctx.guild, "DJArray", promoArray)

		msg = '**{}** added to list.'.format(role.name)
		await ctx.send(Utils.suppressed(ctx,msg))

	@commands.command(pass_context=True)
	async def removedj(self, ctx, *, role : str = None):
		"""Removes a role from the dj list (bot-admin only)."""
		usage = 'Usage: `{}removedj [role]`'.format(ctx.prefix)
		if not await Utils.is_bot_admin_reply(ctx): return
		if role == None:
			return await ctx.send(usage)
		# Name placeholder
		roleName = role
		if type(role) is str:
			if role.lower() == "everyone" or role.lower() == "@everyone":
				role = ctx.guild.default_role
			else:
				role = DisplayName.roleForName(role, ctx.guild)
		# If we're here - then the role is a real one
		promoArray = self.settings.getServerStat(ctx.guild, "DJArray")
		# Check by id first, then by name
		found_role = next((x for x in promoArray if str(x["ID"])==str(role.id)),False)
		if not found_role:
			found_role = next((x for x in promoArray if x["Name"].lower()==role.name.lower()),False)
		if found_role:
			promoArray.remove(found_role)
			self.settings.setServerStat(ctx.guild, "DJArray", promoArray)
			msg = '**{}** removed successfully.'.format(found_role['Name'])
			return await ctx.send(Utils.suppressed(ctx,msg))
		# If we made it this far - then we didn't find it
		msg = '**{}** not found in list.'.format(role)
		await ctx.send(Utils.suppressed(ctx,msg))

	@commands.command(pass_context=True)
	async def listdj(self, ctx):
		"""Lists dj roles and id's."""
		promoArray = self.settings.getServerStat(ctx.guild, "DJArray")
		promoSorted = sorted(promoArray, key=itemgetter('Name'))
		if not len(promoSorted):
			roleText = "There are no dj roles set yet.  Use `{}adddj [role]` to add some.".format(ctx.prefix)
			return await ctx.channel.send(roleText)
		roleText = "__**Current DJ Roles:**__\n\n"
		for arole in promoSorted:
			role = ctx.guild.get_role(int(arole["ID"]))
			roleText += "**{}** (removed from server)\n".format(arole["Name"]) if role is None else "**{}** (ID : `{}`)\n".format(role.name, arole["ID"])
		await ctx.send(Utils.suppressed(ctx,roleText))


text:
using System;
using System.Threading.Tasks;
using Kudu.Contracts.Settings;
using Kudu.Core.Tracing;

namespace Kudu.Core.Deployment.Generator
{
    //  Site builder class hierarchy:
    //
    //  ExternalCommandBuilder
    //      CustomBuilder
    //      GeneratorSiteBuilder
    //          BaseBasicBuilder
    //              BasicBuilder
    //              NodeSiteBuilder
    //          WapBuilder
    //          WebSiteBuilder
    //          DotNetConsoleBuilder
    //          CustomGeneratorCommandSiteBuilder

    public abstract class ExternalCommandBuilder : ISiteBuilder
    {
        protected ExternalCommandBuilder(IEnvironment environment, IDeploymentSettingsManager settings, IBuildPropertyProvider propertyProvider, string repositoryPath)
        {
            Environment = environment;

            DeploymentSettings = settings;
            RepositoryPath = repositoryPath;
            PropertyProvider = propertyProvider;

            ExternalCommandFactory = new ExternalCommandFactory(environment, settings, repositoryPath);
        }

        public abstract string ProjectType { get; }

        protected IEnvironment Environment { get; private set; }

        protected IDeploymentSettingsManager DeploymentSettings { get; private set; }

        protected string RepositoryPath { get; private set; }

        protected IBuildPropertyProvider PropertyProvider { get; private set; }

        internal ExternalCommandFactory ExternalCommandFactory { get; private set; }

        public abstract Task Build(DeploymentContext context);

        protected void RunCommand(DeploymentContext context, string command)
        {
            ILogger customLogger = context.Logger.Log("Running deployment command...");
            customLogger.Log("Command: " + command);

            // Creates an executable pointing to cmd and the working directory being
            // the repository root
            var exe = ExternalCommandFactory.BuildExternalCommandExecutable(RepositoryPath, context.OutputPath, customLogger);

            exe.EnvironmentVariables[WellKnownEnvironmentVariables.PreviousManifestPath] = context.PreviousManifestFilePath ?? String.Empty;
            exe.EnvironmentVariables[WellKnownEnvironmentVariables.NextManifestPath] = context.NextManifestFilePath;

            exe.EnvironmentVariables[WellKnownEnvironmentVariables.BuildTempPath] = context.BuildTempPath;

            // Set Commit ID in the environment
            exe.EnvironmentVariables[WellKnownEnvironmentVariables.CommitId] = context.CommitId;

            // Populate the environment with the build properties
            foreach (var property in PropertyProvider.GetProperties())
            {
                exe.EnvironmentVariables[property.Key] = property.Value;
            }

            try
            {
                exe.ExecuteWithProgressWriter(customLogger, context.Tracer, command, String.Empty);
            }
            catch (Exception ex)
            {
                context.Tracer.TraceError(ex);

                // HACK: Log an empty error to the global logger (post receive hook console output).
                // The reason we don't log the real exception is because the 'live output' running
                // msbuild has already been captured.
                context.GlobalLogger.LogError();

                throw;
            }
        }
    }
}


text:
/* $Id: HexUtil.java 750418 2009-03-05 11:03:54Z vhennebert $ */

package org.apache.xmlgraphics.util;

/**
 * Provides helper functions for converting hexadecimal strings.
 */
public class HexUtil {

    private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    /**
     * Converts a byte array to a hexadecimal String
     *
     * @param data
     *            the data to encode
     * @return String the resulting String
     */
    public static final String toHex(final byte[] data) {
        final StringBuilder sb = new StringBuilder(data.length * 2);
        for (final byte element : data) {
            sb.append(DIGITS[element >>> 4 & 0x0F]);
            sb.append(DIGITS[element & 0x0F]);
        }
        return sb.toString();
    }

}


text:
struct SysDevice {
  uint32_t base_addr;
  DeviceIf *device;
};

class SystemBus: public DeviceIf
{
 private:
  std::vector<SysDevice> m_devs;
 public:
  SystemBus();
  void register_device(uint32_t base_addr, DeviceIf *dev);
  uint32_t read32(uint32_t addr);
  void write32(uint32_t addr, uint32_t data);
  uint32_t get_size();
};

#endif


text:
"""
Views which allow users to create and activate accounts.

"""

from django.shortcuts import redirect
from django.shortcuts import render
from django.template import RequestContext
from django.http import HttpResponse

from registration.backends import get_backend

from django.contrib.auth.models import User

def activate(request, backend,
             template_name='registration/activate.html',
             success_url=None, extra_context=None, **kwargs):
    """
    Activate a user's account.

    The actual activation of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    the backend's ``activate()`` method will be called, passing any
    keyword arguments captured from the URL, and will be assumed to
    return a ``User`` if activation was successful, or a value which
    evaluates to ``False`` in boolean context if not.

    Upon successful activation, the backend's
    ``post_activation_redirect()`` method will be called, passing the
    ``HttpRequest`` and the activated ``User`` to determine the URL to
    redirect the user to. To override this, pass the argument
    ``success_url`` (see below).

    On unsuccessful activation, will render the template
    ``registration/activate.html`` to display an error message; to
    override thise, pass the argument ``template_name`` (see below).

    **Arguments**

    ``backend``
        The dotted Python import path to the backend class to
        use. Required.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context. Optional.

    ``success_url``
        The name of a URL pattern to redirect to on successful
        acivation. This is optional; if not specified, this will be
        obtained by calling the backend's
        ``post_activation_redirect()`` method.

    ``template_name``
        A custom template to use. This is optional; if not specified,
        this will default to ``registration/activate.html``.

    ``\*\*kwargs``
        Any keyword arguments captured from the URL, such as an
        activation key, which will be passed to the backend's
        ``activate()`` method.

    **Context:**

    The context will be populated from the keyword arguments captured
    in the URL, and any extra variables supplied in the
    ``extra_context`` argument (see above).

    **Template:**

    registration/activate.html or ``template_name`` keyword argument.

    """
    backend = get_backend(backend)
    account = backend.activate(request, **kwargs)

    if account:
        if success_url is None:
            to, args, kwargs = backend.post_activation_redirect(request, account)
            return redirect(to, *args, **kwargs)
        else:
            return redirect(success_url)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    if not kwargs:
        kwargs = {}
    kwargs['context_instance'] = context
    return render(request, template_name,
                              kwargs,
                              context)

def register(request, backend, success_url=None, form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.

    The actual registration of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    it will be used as follows:

    1. The backend's ``registration_allowed()`` method will be called,
       passing the ``HttpRequest``, to determine whether registration
       of an account is to be allowed; if not, a redirect is issued to
       the view corresponding to the named URL pattern
       ``registration_disallowed``. To override this, see the list of
       optional arguments for this view (below).

    2. The form to use for account registration will be obtained by
       calling the backend's ``get_form_class()`` method, passing the
       ``HttpRequest``. To override this, see the list of optional
       arguments for this view (below).

    3. If valid, the form's ``cleaned_data`` will be passed (as
       keyword arguments, and along with the ``HttpRequest``) to the
       backend's ``register()`` method, which should return the new
       ``User`` object.

    4. Upon successful registration, the backend's
       ``post_registration_redirect()`` method will be called, passing
       the ``HttpRequest`` and the new ``User``, to determine the URL
       to redirect the user to. To override this, see the list of
       optional arguments for this view (below).

    **Required arguments**

    None.

    **Optional arguments**

    ``backend``
        The dotted Python import path to the backend class to use.

    ``disallowed_url``
        URL to redirect to if registration is not permitted for the
        current ``HttpRequest``. Must be a value which can legally be
        passed to ``django.shortcuts.redirect``. If not supplied, this
        will be whatever URL corresponds to the named URL pattern
        ``registration_disallowed``.

    ``form_class``
        The form class to use for registration. If not supplied, this
        will be retrieved from the registration backend.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``success_url``
        URL to redirect to after successful registration. Must be a
        value which can legally be passed to
        ``django.shortcuts.redirect``. If not supplied, this will be
        retrieved from the registration backend.

    ``template_name``
        A custom template to use. If not supplied, this will default
        to ``registration/registration_form.html``.

    **Context:**

    ``form``
        The registration form.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).

    **Template:**

    registration/registration_form.html or ``template_name`` keyword
    argument.

    """
    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render(request, template_name,
                              {'form': form},
                              context)

def ajax_check_username(request):
    response = 'false'
    if request.is_ajax() and request.method == 'GET' and request.GET['username']:
        existing = User.objects.filter(username__iexact=request.GET['username'])
        if not existing.exists():
            response = 'true'

    return HttpResponse(response)

def ajax_check_email(request):
    response = 'false'
    if request.is_ajax() and request.method == 'GET' and request.GET['email']:
        if not User.objects.filter(email__iexact=request.GET['email']):
            response = 'true'

    return HttpResponse(response)


text:
from django.contrib import messages
from proposals.models import TalkProposal, TutorialProposal

def test_proposal_create_login(client):
    response = client.get('/en-us/proposals/submit/', follow=True)
    assert response.redirect_chain == [
        ('/en-us/accounts/login/?next=/en-us/proposals/submit/', 302),
    ]

def test_proposal_create_denied_get(bare_user_client):
    response = bare_user_client.get('/en-us/proposals/submit/')
    assert response.status_code == 403

def test_proposal_create_denied_post(bare_user_client):
    response = bare_user_client.post('/en-us/proposals/submit/')
    assert response.status_code == 403

def test_proposal_create_get(user_client):
    response = user_client.get('/en-us/proposals/submit/')
    assert response.status_code == 200

def test_talk_proposal_create_login(client):
    response = client.get('/en-us/proposals/talk/submit/', follow=True)
    assert response.redirect_chain == [
        ('/en-us/accounts/login/?next=/en-us/proposals/talk/submit/', 302),
    ]

def test_tutorial_proposal_create_login(client):
    response = client.get('/en-us/proposals/tutorial/submit/', follow=True)
    assert response.redirect_chain == [
        ('/en-us/accounts/login/?next=/en-us/proposals/tutorial/submit/', 302),
    ]

def test_talk_proposal_create_denied_get(bare_user_client):
    response = bare_user_client.get('/en-us/proposals/talk/submit/')
    assert response.status_code == 403

def test_tutorial_proposal_create_denied_get(bare_user_client):
    response = bare_user_client.get('/en-us/proposals/tutorial/submit/')
    assert response.status_code == 403

def test_talk_proposal_create_denied_post(bare_user_client):
    response = bare_user_client.post('/en-us/proposals/talk/submit/')
    assert response.status_code == 403

def test_tutorial_proposal_create_denied_post(bare_user_client):
    response = bare_user_client.post('/en-us/proposals/tutorial/submit/')
    assert response.status_code == 403

def test_talk_proposal_create_get(user_client):
    response = user_client.get('/en-us/proposals/talk/submit/')
    assert response.status_code == 200

def test_tutorial_proposal_create_get(user_client):
    response = user_client.get('/en-us/proposals/tutorial/submit/')
    assert response.status_code == 200

def test_talk_proposal_create_post(user, user_client):
    response = user_client.post('/en-us/proposals/talk/submit/', {
        'title': 'Beyond the Style Guides
',
        'category': 'PRAC',
        'duration': 'PREF45',
        'language': 'CHI',
        'python_level': 'INTERMEDIATE',
        'recording_policy': True,
    }, follow=True)

    proposal = TalkProposal.objects.get(
        submitter=user,
        title='Beyond the Style Guides
',
    )
    assert response.redirect_chain == [
        ('/en-us/proposals/talk/{pk}/edit/'.format(pk=proposal.pk), 302),
    ], response.context['form'].errors

    msgs = [(m.level, m.message) for m in response.context['messages']]
    assert msgs == [
        (messages.SUCCESS,
         'Talk proposal '
         'Beyond the Style Guides<br> created.'),
    ]

def test_tutorial_proposal_create_post(user, user_client):
    response = user_client.post('/en-us/proposals/tutorial/submit/', {
        'title': 'Beyond the Style Guides
',
        'category': 'PRAC',
        'duration': 'FULLDAY',
        'language': 'CHI',
        'python_level': 'INTERMEDIATE',
        'recording_policy': True,
    }, follow=True)

    proposal = TutorialProposal.objects.get(
        submitter=user,
        title='Beyond the Style Guides
',
    )
    assert response.redirect_chain == [
        ('/en-us/proposals/tutorial/{pk}/edit/'.format(pk=proposal.pk), 302),
    ], response.context['form'].errors

    msgs = [(m.level, m.message) for m in response.context['messages']]
    assert msgs == [
        (messages.SUCCESS,
         'Tutorial proposal '
         'Beyond the Style Guides<br> created.'),
    ]


text:
package org.jbromo.common.dto;

import org.jbromo.common.dto.IOrderBy.SORT;
import org.junit.Assert;
import org.junit.Test;

/**
 * Define JUnit IOrderBy test.
 * @author qjafcunuas
 */
public class OrderByTest {

    /**
     * Test enum.
     */
    @Test
    public void sort() {
        for (final SORT sort : IOrderBy.SORT.values()) {
            Assert.assertEquals(sort, IOrderBy.SORT.valueOf(sort.name()));
            switch (sort) {
                case ASCENDING:
                case DESCENDING:
                case UNSORTED:
                    break;
                default:
                    Assert.fail("Not tested");
                    break;
            }
        }
    }

}


text:
describe 'get customer number using pure SQL setup' do

  before(:all) do
    plsql.execute <<-SQL
      INSERT INTO customers(customer_id, customer_no,customer_valid_flag)
      VALUES (-1, 123456, '1')
    SQL
  end

  it 'returns expected customer number as a numeric value' do
    expect( plsql.some_table_api.get_customer_no(-1) ).to eq 123456
  end

  it 'returns expected customer number as a numeric value through assignment' do
    result = plsql.some_table_api.get_customer_no(-1)
    expect( result ).to eq 123456
  end

end


text:
<?php

namespace Opendi\Solr\Client\Console\Commands;

use Opendi\Lang\Json;
use Opendi\Solr\Client\Client;
use Opendi\Solr\Client\Console\AbstractCommand;
use SplFileInfo;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;

/**
 * Imports JSON encoded data from a file or a folder into a Solr core.
 */
class ImportCommand extends AbstractCommand
{
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('import')
            ->setDescription("Import JSON encoded data into a Solr core.")
            ->addArgument(
                'core',
                InputArgument::REQUIRED,
                'Name of the core to import into.'
            )
            ->addArgument(
                'source',
                InputArgument::IS_ARRAY,
                'Path to a file or folder to import from (recursively).'
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $core = $input->getArgument('core');
        $sources = $input->getArgument('source');

        $client = $this->getClient($input, $output);

        $output->writeln("Collection: <info>$core</info>");
        $output->writeln("--");

        foreach ($sources as $source) {
            if (!file_exists($source)) {
                throw new \Exception("Source not found: $source");
            }

            if (is_dir($source)) {
                $finder = new Finder();
                $finder->files()->in($source)->sortByName();

                foreach ($finder as $file) {
                    $this->importFile($client, $core, $file, $output);
                }
            } else {
                $file = new SplFileInfo($source);
                $this->importFile($client, $core, $file, $output);
            }
        }

        $output->writeln("<info>Done.</info>");
    }

    private function importFile(Client $client, $core, SplFileInfo $source, $output)
    {
        $output->writeln("Importing data from: <info>$source</info>");

        $fp = fopen($source, 'r');

        $path = "$core/update?" . http_build_query([
            'commit' => 'true',
            'wt' => 'json'
        ]);

        $headers = [
            'Content-Type' => 'application/json'
        ];

        $response = $client->post($path, $fp, $headers);
        $contents = $response->getBody()->getContents();
        $reply = Json::decode($contents);

        if ($reply->responseHeader->status != 0) {
            throw new \Exception("Solr returned an error.");
        }

        $time = $reply->responseHeader->QTime;
        $output->writeln("Time taken: <comment>$time ms</comment>\n");
    }
}


text:
using namespace std;

typedef _leetcode_treenode<int> TreeNode;

class Solution {
public:
    bool isValidBST(TreeNode* root) {
        if (root == nullptr)
            return true;
        return isvalid(root).legal;
    }

    bool isValidBST2(TreeNode *root)
    {
        if (root == nullptr)
            return true;
        bool lr = _isValidBST2(root->left, numeric_limits<long long>::min(), root->val);
        bool rr = _isValidBST2(root->right, root->val, numeric_limits<long long>::max());
        return lr&&rr;
    }

private:

    bool _isValidBST2(TreeNode *root, long long minv, long long maxv)
    {
        if (root == nullptr)
            return true;
        if (root->val<minv || root->val>maxv)
            return false;
        bool lr = _isValidBST2(root->left, minv, root->val);
        bool rr = _isValidBST2(root->right, root->val, maxv);
        return lr && rr;
    }

    struct bstinfo
    {
        bool legal;
        int maxval;
        int minval;
        bstinfo(bool legal, int maxval, int minval) :
            legal(legal),
            maxval(maxval),
            minval(minval){};
        bstinfo(bool legal) :
            legal(legal),
            maxval(numeric_limits<int>::max()),
            minval(numeric_limits<int>::min()){}
        bstinfo():bstinfo(false){};
    };

    bstinfo isvalid(TreeNode *root)
    {
        if (root->left == nullptr&&root->right == nullptr)
            return bstinfo(true, root->val, root->val);
        if (root->left != nullptr && root->right != nullptr)
        {
            auto lr = isvalid(root->left);
            auto rr = isvalid(root->right);
            if (!lr.legal || !rr.legal)
                return bstinfo(false);
            return bstinfo(lr.maxval<root->val && rr.minval>root->val, rr.maxval, lr.minval);
        }
        if (root->right == nullptr)
        {
            auto lr = isvalid(root->left);
            if (!lr.legal)
                return bstinfo(false);
            return bstinfo(root->val > lr.maxval, root->val, lr.minval);
        }
        else
        {
            auto rr = isvalid(root->right);
            if (!rr.legal)
                return bstinfo(false);
            return bstinfo(root->val < rr.minval, rr.maxval, root->val);
        }
    }
};

int main()
{
    Solution s;
    //vector<int> test = { 6, 2, 8, 0, 4, 7, 9, -1, 1, 3, 5 };
    vector<int> test = { numeric_limits<int>::min(), -1, numeric_limits<int>::max()};
    auto root = lc_deserializetree(test, -1);
    cout << s.isValidBST2(root) << endl;
    cout << s.isValidBST(root) << endl;
    lc_destroytree(root);
    system("pause");
    return 0;
}


text:
|  ID   |            Problem statement            |                Solution                |
|:-----:|:----------------------------------------|:--------------------------------------:|
| 11942 | [Lumberjack Sequencing][]               | [lumberjack_sequencing.cpp][]          |
| 11955 | [Binomial Theorem][]                    | [binomial_theorem.cpp][]               |
| 11956 | [Brainfuck][]                           | [brainfuck.cpp][]                      |
| 11988 | [Broken Keyboard (a.k.a. Beiju Text)][] | [broken_keyboard_aka_beiju_text.cpp][] |
| 11991 | [Easy Problem from Rujia Liu?][]        | [easy_problem_from_rujia_liu.cpp][]    |

[Lumberjack Sequencing]:               http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=229&page=show_problem&problem=3093
[Binomial Theorem]:                    http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=229&page=show_problem&problem=3106
[Brainfuck]:                           http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=229&page=show_problem&problem=3107
[Broken Keyboard (a.k.a. Beiju Text)]: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=229&page=show_problem&problem=3139
[Easy Problem from Rujia Liu?]:        https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=229&page=show_problem&problem=3142

[lumberjack_sequencing.cpp]:          lumberjack_sequencing.cpp
[binomial_theorem.cpp]:               binomial_theorem.cpp
[brainfuck.cpp]:                      brainfuck.cpp
[broken_keyboard_aka_beiju_text.cpp]: broken_keyboard_aka_beiju_text.cpp
[easy_problem_from_rujia_liu.cpp]:    easy_problem_from_rujia_liu.cpp


text:
J.addWait(
"test.buildTest"
, [
	"window.console"
	, "test"
]
, function(ref) {

	var dtest = J.test

	// it's here twice
	function subRunTest(path) {
		dtest.lastTest = path
		J.load(path, true)
		console.group(path)
		console.group("tests")
	}

	return function buildTest(/* path, func (Constructor, Test, TestWaiter, tools), isIntegration */) {

		var map = J.mapArguments(arguments)
			, path = map.Str && map.Str[0]
			, func = map.Fun && map.Fun[0]
			, isIntegration = map.Boo && map.Boo[0]
			, thing = J.exists(path)
			, metaInfo = thing._jdog
			, isAddWaitAttach = (metaInfo && metaInfo.fun)
			, isAddAttached = (metaInfo && !metaInfo.fun && metaInfo.thing)
			, thingToTest

			ref.test.codeCoverage

		var scout = {
			syncTests : []
			, asyncTests : []
		}

		// lets load all of the tools dynamically
		// this means that if they are loaded into
		// J.test.tools they will show up here
		// this allows anyone to add their own testing tools
		var tools = J.test.tools
		tools.metaInfo = metaInfo
		delete tools.flag

		var Test = tools.Test = tools.Assert = function Test(testName, resultFunc) {

			scout.syncTests.push(function() {
				var result = {
					name : testName
					, result : resultFunc()
					, test : resultFunc
					, construct : path
					, func : func
					, type : "sync"
					, testName : testName
					, testPath : dtest.lastTest
				}
				dtest.results.push(result)

				// handles external call
				if (dtest.externalCall) {
					dtest.externalCall(result)
				}

				if (result.result) {
					console.groupCollapsed("%c " + result.name + "%c \u2714", "color:gray; font-weight:normal;", "color:rgb(54, 231, 54)")
					console.log(result)
					console.groupEnd()

				} else {
					console.error(result.name + " \u2716 FAILED")
					console.log(result)
				}
			})

			scout.syncTests.shift()()

		}

		var TestWaiter = tools.TestWaiter = tools.AsyncAssert = function TestWaiter(testName, resultFunc /* (series, go, call) */ ) {
			var series = scout.asyncTests

			function go() {
				if (series.length > 0) {

					if (typeof series[0] === "number") {

						setTimeout(function() {
							call({ name : "delay for " + series[0] + " ms", result : true })
							go()
						}, series[0])

					} else {
						series[0].apply(this, arguments)
					}

				}
			}

			function call(arg) {

				var result = arg

				result.type = "async"
				result.testName = testName
				result.seriesCount = series.length
				result.testPath = dtest.lastTest
				dtest.results.push(result)

				// handles external call
				if (dtest.externalCall) {
					dtest.externalCall(result)
				}

				if (result.result) {
					console.groupCollapsed("%c " + testName + ": " + result.name + "%c \u2714", "color:gray; font-weight:normal;", "color:rgb(54, 231, 54)")
					console.log(result)
					console.groupEnd()
				} else {
					console.error(testName + ": ", result.name, "\u2716 failed")
					console.error(result)
				}
				series.shift()
			}

			resultFunc(series, go, call)
		}

		// this is here to help when a test group is finished, clear it up
		var interval = setInterval(function() {
			if (!scout.asyncTests.length) {
				clearInterval(interval)

				if (J.exists("test.codeCoverage")) {
					;(function() {
						var countsCoverage = dtest.codeCoverage.getTotals()
						var temp = {}
						var lastTest = dtest.lastTest
						if (!lastTest) { return alert("oop") }

						var lastTestMap = dtest.allTestMapsFlipped[lastTest]
						var lastConstructorCounts = dtest.codeCoverage.getByPath( lastTestMap.path )

						temp["functions found"] = lastConstructorCounts ? { count : lastConstructorCounts.totalPoints } : 0
						temp["functions tested"] = lastConstructorCounts ? { count : lastConstructorCounts.hitsCount } : 0
						temp["functions missed"] = lastConstructorCounts ? { count : lastConstructorCounts.hitsMissed } : 0
						console.groupEnd()
						console.groupCollapsed("Code Coverage")
						console.table(temp, [ "count" ])

						lastTestMap.coverage = lastConstructorCounts

						console.group("%c Coverage Info", "font-weight:normal; color:#aaa;")

						;(function() {
							var tempMissesList = {}

							if (!lastTestMap.coverage) return

							var misses = lastTestMap.coverage.misses

							for(var x in misses) {
								tempMissesList[x] = {
									lineNumber : misses[x].loc.start.line
									, column : misses[x].loc.start.column
									, name : misses[x].name
								}
							}

							console.group("Misses")
							console.table(tempMissesList, ["name", "lineNumber", "column"])
							console.groupEnd()

						}())

						;(function() {
							var tempHitsList = {}

							if (!lastTestMap.coverage) return

							var hits = lastTestMap.coverage.hits

							for(var x in hits) {
								tempHitsList[x] = {
									lineNumber : hits[x].lineNumber
									, name : hits[x].name
								}
							}

							console.groupCollapsed("Hits")
							console.table(tempHitsList, ["name", "lineNumber"])
							console.groupEnd()

						}())

						console.groupEnd()
						console.groupEnd()
					}())
				}

				console.groupEnd()

				if (dtest.activeTests.length) {
					subRunTest(dtest.activeTests.shift())
				} else {
					for(var x = 0; x < dtest._onFinished.length; x++) {
						dtest._onFinished[x](dtest.results)
					}
				}

			}

		}, 0)

		if (isAddAttached) {
			thingToTest = ref.test.codeCoverage.mapPoints(path, metaInfo.thing)
			return func( thingToTest, tools )
		}

		if (isAddWaitAttach) {
			thingToTest = ref.test.codeCoverage.mapPoints(path, metaInfo.fun)
			return func( thingToTest, metaInfo.ref, tools )
		}

		if (isIntegration) {
			return func(Test, TestWaiter, tools )
		}

		else {
			return J.wait(path, function(Constructor) {
				func( ref.test.codeCoverage.mapPoints(path, Constructor), Test, TestWaiter, tools )
			})
		}

	}

})


text:
#define LOG_TAG "GnssHAL_AGnssInterface"

#include "AGnss.h"

namespace android {
namespace hardware {
namespace gnss {
namespace V1_0 {
namespace implementation {

std::vector<std::unique_ptr<ThreadFuncArgs>> AGnss::sThreadFuncArgsList;
sp<IAGnssCallback> AGnss::sAGnssCbIface = nullptr;
bool AGnss::sInterfaceExists = false;

AGpsCallbacks AGnss::sAGnssCb = {
    .status_cb = statusCb,
    .create_thread_cb = createThreadCb
};

AGnss::AGnss(const AGpsInterface* aGpsIface) : mAGnssIface(aGpsIface) {
    /* Error out if an instance of the interface already exists. */
    LOG_ALWAYS_FATAL_IF(sInterfaceExists);
    sInterfaceExists = true;
}

AGnss::~AGnss() {
    sThreadFuncArgsList.clear();
    sInterfaceExists = false;
}

void AGnss::statusCb(AGpsStatus* status) {
    if (sAGnssCbIface == nullptr) {
        ALOGE("%s: AGNSS Callback Interface configured incorrectly", __func__);
        return;
    }

    if (status == nullptr) {
        ALOGE("AGNSS status is invalid");
        return;
    }

    /*
     * Logic based on AGnssStatus processing by GnssLocationProvider. Size of
     * AGpsStatus is checked for backward compatibility since some devices may
     * be sending out an older version of AGpsStatus that only supports IPv4.
     */
    size_t statusSize = status->size;
    if (status->size == sizeof(AGpsStatus)) {
        switch (status->addr.ss_family)
        {
            case AF_INET:
                {
                    /*
                     * ss_family indicates IPv4.
                     */
                    struct sockaddr_in* in = reinterpret_cast<struct sockaddr_in*>(&(status->addr));
                    IAGnssCallback::AGnssStatusIpV4 aGnssStatusIpV4 = {
                        .type = static_cast<IAGnssCallback::AGnssType>(status->type),
                        .status = static_cast<IAGnssCallback::AGnssStatusValue>(status->status),
                        .ipV4Addr = in->sin_addr.s_addr,
                    };

                    /*
                     * Callback to client with agnssStatusIpV4Cb.
                     */
                    auto ret = sAGnssCbIface->agnssStatusIpV4Cb(aGnssStatusIpV4);
                    if (!ret.isOk()) {
                        ALOGE("%s: Unable to invoke callback", __func__);
                    }
                    break;
                }
            case AF_INET6:
                {
                    /*
                     * ss_family indicates IPv6. Callback to client with agnssStatusIpV6Cb.
                     */
                    IAGnssCallback::AGnssStatusIpV6 aGnssStatusIpV6;

                    aGnssStatusIpV6.type = static_cast<IAGnssCallback::AGnssType>(status->type);
                    aGnssStatusIpV6.status = static_cast<IAGnssCallback::AGnssStatusValue>(
                            status->status);

                    struct sockaddr_in6* in6 = reinterpret_cast<struct sockaddr_in6 *>(
                            &(status->addr));
                    memcpy(&(aGnssStatusIpV6.ipV6Addr[0]), in6->sin6_addr.s6_addr,
                           aGnssStatusIpV6.ipV6Addr.size());
                    auto ret = sAGnssCbIface->agnssStatusIpV6Cb(aGnssStatusIpV6);
                    if (!ret.isOk()) {
                        ALOGE("%s: Unable to invoke callback", __func__);
                    }
                    break;
                }
             default:
                    ALOGE("Invalid ss_family found: %d", status->addr.ss_family);
        }
    } else if (statusSize >= sizeof(AGpsStatus_v2)) {
        AGpsStatus_v2* statusV2 = reinterpret_cast<AGpsStatus_v2*>(status);
        uint32_t ipV4Addr = statusV2->ipaddr;
        IAGnssCallback::AGnssStatusIpV4 aGnssStatusIpV4 = {
            .type = static_cast<IAGnssCallback::AGnssType>(AF_INET),
            .status = static_cast<IAGnssCallback::AGnssStatusValue>(status->status),
            /*
             * For older versions of AGpsStatus, change IP addr to net order. This
             * was earlier being done in GnssLocationProvider.
             */
            .ipV4Addr = htonl(ipV4Addr)
        };
        /*
         * Callback to client with agnssStatusIpV4Cb.
         */
        auto ret = sAGnssCbIface->agnssStatusIpV4Cb(aGnssStatusIpV4);
        if (!ret.isOk()) {
            ALOGE("%s: Unable to invoke callback", __func__);
        }
    } else {
        ALOGE("%s: Invalid size for AGPS Status", __func__);
    }
}

pthread_t AGnss::createThreadCb(const char* name, void (*start)(void*), void* arg) {
    return createPthread(name, start, arg, &sThreadFuncArgsList);
}

/*
 * Implementation of methods from ::android::hardware::gnss::V1_0::IAGnss follow.
 */
Return<void> AGnss::setCallback(const sp<IAGnssCallback>& callback) {
    if (mAGnssIface == nullptr) {
        ALOGE("%s: AGnss interface is unavailable", __func__);
        return Void();
    }

    sAGnssCbIface = callback;

    mAGnssIface->init(&sAGnssCb);
    return Void();
}

Return<bool> AGnss::dataConnClosed()  {
    if (mAGnssIface == nullptr) {
        ALOGE("%s: AGnss interface is unavailable", __func__);
        return false;
    }

    return (mAGnssIface->data_conn_closed() == 0);
}

Return<bool> AGnss::dataConnFailed()  {
    if (mAGnssIface == nullptr) {
        ALOGE("%s: AGnss interface is unavailable", __func__);
        return false;
    }

    return (mAGnssIface->data_conn_failed() == 0);
}

Return<bool> AGnss::setServer(IAGnssCallback::AGnssType type,
                              const hidl_string& hostname,
                              int32_t port) {
    if (mAGnssIface == nullptr) {
        ALOGE("%s: AGnss interface is unavailable", __func__);
        return false;
    }

    return (mAGnssIface->set_server(static_cast<AGpsType>(type), hostname.c_str(), port) == 0);
}

Return<bool> AGnss::dataConnOpen(const hidl_string& apn, IAGnss::ApnIpType apnIpType) {
    if (mAGnssIface == nullptr) {
        ALOGE("%s: AGnss interface is unavailable", __func__);
        return false;
    }

    return (mAGnssIface->data_conn_open_with_apn_ip_type(apn.c_str(),
                                                     static_cast<uint16_t>(apnIpType)) == 0);
}

}  // namespace implementation
}  // namespace V1_0
}  // namespace gnss
}  // namespace hardware
}  // namespace android


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestLib.Entities;
using CodingAbelNu.Utilities.EntityFramework;

namespace TestLibTests
{
    [TestClass]
    public class EnumSeederTests
    {
        [TestMethod]
        public void RunSeedMethod()
        {
            // Not a proper unit test, nor placed in the right unit test lib,
            // but it's a great runner to use to get the code running.

            using (var ctx = new CarsContext())
            {
                ctx.Seed<CarBodyStyle>();
            }
        }

        [TestMethod]
        public void RunSeedMethod_WithoutDescription()
        {
            using (var ctx = new CarsContext())
            {
                ctx.Seed<CarBodyStyle>(descriptionField: null);
            }
        }
    }
}


text:
package org.neo4j.driver.internal.metrics;

import org.neo4j.driver.Logging;
import org.neo4j.driver.Metrics;
import org.neo4j.driver.internal.util.Clock;

public final class InternalMetricsProvider implements MetricsProvider {
    private final InternalMetrics metrics;

    public InternalMetricsProvider(Clock clock, Logging logging) {
        this.metrics = new InternalMetrics(clock, logging);
    }

    @Override
    public Metrics metrics() {
        return metrics;
    }

    @Override
    public MetricsListener metricsListener() {
        return metrics;
    }
}


text:
require 'contractual'

describe Contractual::Interface, "an interface should support a contract" do

  class MockInterface
    include Contractual::Interface

    must_implement :mock_operation
    must :perform_another_mock_operation

  end

  class MockInterfaceImpl < MockInterface; end

  it "should warn about unimplemented methods" do
    mock_object = MockInterfaceImpl.new

    lambda { mock_object.mock_operation }.should raise_error(Contractual::Interface::MethodNotImplementedError, "MockInterfaceImpl is obligated to implement 'mock_operation' for interface MockInterface!")

    lambda { mock_object.perform_another_mock_operation }.should raise_error(Contractual::Interface::MethodNotImplementedError, "MockInterfaceImpl is obligated to implement 'perform_another_mock_operation' for interface MockInterface!")

  end

  class Vehicle
    include Contractual::Interface

    must :load, :passengers
    must :follow, :route
    must :unload, :passengers

    class Route; end

    def take(passengers, destination)
      @passengers = []
      load passengers
      follow Route.new(@current_location, destination)
      unload passengers
    end
  end

  class Zeppelin < Vehicle
    def load(passengers); @passengers << passengers; end
    def unload(passengers); @current_location << passengers; @passengers = []; end
  end

  it "should warn about unimplemented methods with arguments" do
    zeppelin = Zeppelin.new
    us, anywhere = nil, nil
    lambda { zeppelin.take(us, anywhere) }.should raise_error(Contractual::Interface::MethodNotImplementedError, "Zeppelin is obligated to implement 'follow' for interface Vehicle!")
  end
end


text:
extern ConVar fire_extinguisher_debug;

//Networking
IMPLEMENT_SERVERCLASS_ST( CExtinguisherJet, DT_ExtinguisherJet )
	SendPropInt(SENDINFO(m_bEmit), 1, SPROP_UNSIGNED),
	SendPropInt(SENDINFO(m_bUseMuzzlePoint), 1, SPROP_UNSIGNED),
	SendPropInt(SENDINFO(m_nLength), 32, SPROP_UNSIGNED),
	SendPropInt(SENDINFO(m_nSize), 32, SPROP_UNSIGNED),
END_SEND_TABLE()

//Save/restore
BEGIN_DATADESC( CExtinguisherJet )

	//Regular fields
	DEFINE_FIELD( m_bEmit,		FIELD_BOOLEAN ),

	DEFINE_KEYFIELD( m_bEnabled,	FIELD_BOOLEAN, "enabled" ),
	DEFINE_KEYFIELD( m_nLength,	FIELD_INTEGER, "length" ),
	DEFINE_KEYFIELD( m_nSize,		FIELD_INTEGER, "size" ),
	DEFINE_KEYFIELD( m_nRadius,	FIELD_INTEGER, "radius" ),
	DEFINE_KEYFIELD( m_flStrength,FIELD_FLOAT,   "strength" ),

	DEFINE_FIELD( m_bAutoExtinguish,	FIELD_BOOLEAN ),
	DEFINE_FIELD( m_bUseMuzzlePoint,	FIELD_BOOLEAN ),

	DEFINE_INPUTFUNC( FIELD_VOID, "Enable",	InputEnable ),
	DEFINE_INPUTFUNC( FIELD_VOID, "Disable",	InputDisable ),
	DEFINE_INPUTFUNC( FIELD_VOID, "Toggle",	InputToggle ),

	DEFINE_FUNCTION( ExtinguishThink ),

END_DATADESC()

LINK_ENTITY_TO_CLASS( env_extinguisherjet, CExtinguisherJet );

//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CExtinguisherJet::CExtinguisherJet( void )
{
	m_bEmit				= false;
	m_bEnabled			= false;
	m_bAutoExtinguish	= true;

	m_nLength			= 128;
	m_nSize				= 8;
	m_flStrength		= 0.97f;	//FIXME: Stub numbers
	m_nRadius			= 32;

	// Send to the client even though we don't have a model
	AddEFlags( EFL_FORCE_CHECK_TRANSMIT );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CExtinguisherJet::Spawn( void )
{
	Precache();

	if ( m_bEnabled )
	{
		TurnOn();
	}
}

void CExtinguisherJet::Precache()
{
	BaseClass::Precache();

	PrecacheScriptSound( "ExtinguisherJet.TurnOn" );
	PrecacheScriptSound( "ExtinguisherJet.TurnOff" );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CExtinguisherJet::TurnOn( void )
{
	//Turn on sound
	if ( m_bEmit == false )
	{
		EmitSound( "ExtinguisherJet.TurnOn" );
		m_bEnabled = m_bEmit = true;
	}

	SetThink( ExtinguishThink );
	SetNextThink( gpGlobals->curtime + 0.1f );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CExtinguisherJet::TurnOff( void )
{
	//Turn off sound
	if ( m_bEmit )
	{
		EmitSound( "ExtinguisherJet.TurnOff" );
		m_bEnabled = m_bEmit = false;
	}

	SetThink( NULL );
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : &inputdata -
//-----------------------------------------------------------------------------
void CExtinguisherJet::InputEnable( inputdata_t &inputdata )
{
	TurnOn();
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : &inputdata -
//-----------------------------------------------------------------------------
void CExtinguisherJet::InputDisable( inputdata_t &inputdata )
{
	TurnOff();
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : &inputdata -
//-----------------------------------------------------------------------------
void CExtinguisherJet::InputToggle( inputdata_t &inputdata )
{
	if ( m_bEnabled )
	{
		TurnOff();
	}
	else
	{
		TurnOn();
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CExtinguisherJet::Think( void )
{
	CBaseEntity::Think();
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CExtinguisherJet::ExtinguishThink( void )
{
	SetNextThink( gpGlobals->curtime + 0.1f );

	if ( m_bEnabled == false )
		return;

	if ( m_bAutoExtinguish == false )
		return;

	Vector	vTestPos;
	Vector	vForward, vRight, vUp;

	AngleVectors( GetAbsAngles(), &vForward );

	vTestPos = GetAbsOrigin() + ( vForward * m_nLength );

	trace_t	tr;
	UTIL_TraceLine( GetAbsOrigin(), vTestPos, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );

	//Extinguish the fire where we hit
	FireSystem_ExtinguishInRadius( tr.endpos, m_nRadius, m_flStrength );

	//Debug visualization
	if ( fire_extinguisher_debug.GetInt() )
	{
		int	radius = m_nRadius;

		NDebugOverlay::Line( GetAbsOrigin(), tr.endpos, 0, 0, 128, false, 0.1f );

		NDebugOverlay::Box( GetAbsOrigin(), Vector(-1, -1, -1), Vector(1, 1, 1), 0, 0, 128, false, 0.1f );
		NDebugOverlay::Box( tr.endpos, Vector(-2, -2, -2), Vector(2, 2, 2), 0, 0, 128, false, 0.1f );
		NDebugOverlay::Box( tr.endpos, Vector(-radius, -radius, -radius), Vector(radius, radius, radius), 0, 0, 255, false, 0.1f );
	}
}


text:
An up-to-date [Brunch](http://brunch.io) skeleton for developing clean Web App applications with ease.

It was based on the skeleton from Denis Trayzhon [brunch-with-ember-and-express](https://https://github.com/denya133/brunch-with-ember-and-express) and
the skeleton from Jeremy Fowler [ExpressBrunchJade](https://github.com/jerfowler/ExpressBrunchJade) but is now much more updated and complex now, tho I'd prefer to keep my original source.

Also

the skeleton from Elving Rodriguez [brunch-with-hipsters](https://github.com/elving/brunch-with-hipsters)
which was used for organizing code of express application on Node.js

## Versions
- [jQuery v2.0.3](http://jquery.com)
- [HTML5 Boilerplate v4.2.0](http://html5boilerplate.com)
- [Twitter Bootstrap v3.0.0](https://github.com/twitter/bootstrap)
- [Font Awesome v3.1.0](http://fontawesome.io)
- [Underscore v1.4.4](http://underscorejs.org/)

## Features
- **CoffeeScript** - a little language that compiles into JavaScript.
- **Stylus** - Expressive, dynamic, robust CSS pre-processor.
- **auto-reload-brunch** - Adds automatic browser reloading support to brunch.
- **uglify-js-brunch** - Adds UglifyJS support to brunch.
- **keyword-brunch** - Adds Keyword support to brunch to replace some variables in the generated sources.

## Getting started
Create a new project using this skeleton:
```
brunch new gh:AmilKey/brunch-with-express-socketio <appname>
cd <appname>
git init
git add .
git commit -m "repo init"
brunch watch --server
```
Open [http://localhost:3333](http://localhost:3333) on your browser.

## Production release
To create a production release (smaller vendor files, js and css packed), use the cake build command:
```
cake build
```
It'll generate a production ready `public` and create an archive of it in `public.tgz` that you can then backup or send to your servers.

## Generators
This skeleton makes use of [scaffolt](https://github.com/paulmillr/scaffolt#readme) generators to help you create common files quicker. To use first install scaffolt globally with `npm install -g scaffolt`. Then you can use the following command to generate files.

Generating files of Express App

```
scaffolt express_route <name>		→ express/routes/name.coffee
		=> 	exports.name = (options) ->
				  (req, res) ->
				    res.render 'name', {options: options}

scaffolt express_view <name>		→ express/views/name.jade
		=> 	extends layout

				block content

				// {{name}}
```

* There's a few more commands you can use with `scaffolt` and also instruction on how to create your own generators, so make sure you check out the [docs](https://github.com/paulmillr/scaffolt#readme).
* Each generator will automatically add the generated files to the corresponding initializer coffee file so that you won't have to add them yourself.

## Testing
You can write your tests in the `test` folder, just make sure they are named `*_test.coffee`. You can customize the test to user PhantomJS, Chrome, Firefox, Safari or Opera on the `test/karma.conf.js` file. There's a lot of other settings there as well. Run tests with:

```
cake test
```

## Updating
You have some `cake` tasks to help you update *ember*, *ember-data* and *ember-bootstrap*. More to come in the future.
```bash
# update Twitter Bootstrap:
cake update-bootstrap
# update Font Awesome:
cake update-font-awesome
```

## License
All of brunch-with-express-socketio is licensed under the MIT license.

Copyright (c) 2014 Ivan Kobzar

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace NMaier.SimpleDlna.Utilities
{
  public abstract class Repository<TInterface>
    where TInterface : class, IRepositoryItem
  {
    private static readonly Dictionary<string, TInterface> items =
      BuildRepository();

    private static Dictionary<string, TInterface> BuildRepository()
    {
      var found = new Dictionary<string, TInterface>(StringComparer.CurrentCultureIgnoreCase);
      var type = typeof (TInterface).Name;
      var a = typeof (TInterface).Assembly;
      foreach (var t in a.GetTypes()) {
        if (t.GetInterface(type) == null) {
          continue;
        }
        var ctor = t.GetConstructor(new Type[] {});
        if (ctor == null) {
          continue;
        }
        try {
          var item = ctor.Invoke(new object[] {}) as TInterface;
          if (item == null) {
            continue;
          }
          found.Add(item.Name, item);
        }
        catch (Exception) {
          // ignored
        }
      }
      return found;
    }

    public static IDictionary<string, IRepositoryItem> ListItems()
    {
      return items.Values.ToDictionary<TInterface, string, IRepositoryItem>(v => v.Name, v => v);
    }

    public static TInterface Lookup(string name)
    {
      if (string.IsNullOrWhiteSpace(name)) {
        throw new ArgumentException(
          "Invalid repository name",
          nameof(name));
      }
      var argsplit = name.Split(new[] {':'}, 2);
      name = argsplit[0].ToUpperInvariant().Trim();
      TInterface result;
      if (!items.TryGetValue(name, out result)) {
        throw new RepositoryLookupException(name);
      }
      if (argsplit.Length == 1 || !(result is IConfigurable)) {
        return result;
      }
      var parameters = new ConfigParameters(argsplit[1]);
      if (parameters.Count == 0) {
        return result;
      }
      var ctor = result.GetType().GetConstructor(new Type[] {});
      if (ctor == null) {
        throw new RepositoryLookupException(name);
      }
      try {
        var item = ctor.Invoke(new object[] {}) as TInterface;
        if (item == null) {
          throw new RepositoryLookupException(name);
        }
        var configItem = item as IConfigurable;
        configItem?.SetParameters(parameters);
        return item;
      }
      catch (Exception ex) {
        throw new RepositoryLookupException($"Cannot construct repository item: {ex.Message}", ex);
      }
    }
  }
}


text:
#include <winsock2.h>

#include "qhostinfo_p.h"
#include "private/qnativesocketengine_p.h"
#include <ws2tcpip.h>
#include <private/qsystemlibrary_p.h>
#include <qurl.h>

QT_BEGIN_NAMESPACE

//#define QHOSTINFO_DEBUG

// Older SDKs do not include the addrinfo struct declaration, so we
// include a copy of it here.
struct qt_addrinfo
{
    int ai_flags;
    int ai_family;
    int ai_socktype;
    int ai_protocol;
    size_t ai_addrlen;
    char *ai_canonname;
    sockaddr *ai_addr;
    qt_addrinfo *ai_next;
};

//###
#define QT_SOCKLEN_T int
#ifndef NI_MAXHOST // already defined to 1025 in ws2tcpip.h?
#define NI_MAXHOST 1024
#endif

typedef int (__stdcall *getnameinfoProto)(const sockaddr *, QT_SOCKLEN_T, const char *, DWORD, const char *, DWORD, int);
typedef int (__stdcall *getaddrinfoProto)(const char *, const char *, const qt_addrinfo *, qt_addrinfo **);
typedef int (__stdcall *freeaddrinfoProto)(qt_addrinfo *);
static getnameinfoProto local_getnameinfo = 0;
static getaddrinfoProto local_getaddrinfo = 0;
static freeaddrinfoProto local_freeaddrinfo = 0;

static void resolveLibrary()
{
    // Attempt to resolve getaddrinfo(); without it we'll have to fall
    // back to gethostbyname(), which has no IPv6 support.
    static bool triedResolve = false;
    if (triedResolve)
        return;

#if !defined(Q_OS_WINCE)
    QSystemLibrary ws2lib(QLatin1String("ws2_32"));
#else
    QSystemLibrary ws2lib(QLatin1String("ws2"));
#endif
    if (ws2lib.load()) {
        local_getaddrinfo = (getaddrinfoProto)ws2lib.resolve("getaddrinfo");
        local_freeaddrinfo = (freeaddrinfoProto)ws2lib.resolve("freeaddrinfo");
        local_getnameinfo = (getnameinfoProto)ws2lib.resolve("getnameinfo");
    }

    triedResolve = true;
}

#if defined(Q_OS_WINCE)
#include <qmutex.h>
Q_GLOBAL_STATIC(QMutex, qPrivCEMutex)
#endif

static void translateWSAError(int error, QHostInfo *results)
{
    switch (error) {
    case WSAHOST_NOT_FOUND: //authoritative not found
    case WSATRY_AGAIN: //non authoritative not found
    case WSANO_DATA: //valid name, no associated address
        results->setError(QHostInfo::HostNotFound);
        results->setErrorString(QHostInfoAgent::tr("Host not found"));
        return;
    default:
        results->setError(QHostInfo::UnknownError);
        results->setErrorString(QHostInfoAgent::tr("Unknown error (%1)").arg(error));
        return;
    }
}

QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    resolveLibrary();

#if defined(Q_OS_WINCE)
    QMutexLocker locker(qPrivCEMutex());
#endif

    QWindowsSockInit winSock;

    QHostInfo results;

#if defined(QHOSTINFO_DEBUG)
    qDebug("QHostInfoAgent::fromName(%p): looking up \"%s\" (IPv6 support is %s)",
           this, hostName.toLatin1().constData(),
           (local_getaddrinfo && local_freeaddrinfo) ? "enabled" : "disabled");
#endif

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
        if (local_getnameinfo) {
            sockaddr_in sa4;
            qt_sockaddr_in6 sa6;
            sockaddr *sa;
            QT_SOCKLEN_T saSize;
            if (address.protocol() == QAbstractSocket::IPv4Protocol) {
                sa = (sockaddr *)&sa4;
                saSize = sizeof(sa4);
                memset(&sa4, 0, sizeof(sa4));
                sa4.sin_family = AF_INET;
                sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
            } else {
                sa = (sockaddr *)&sa6;
                saSize = sizeof(sa6);
                memset(&sa6, 0, sizeof(sa6));
                sa6.sin6_family = AF_INET6;
                memcpy(sa6.sin6_addr.qt_s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.qt_s6_addr));
            }

            char hbuf[NI_MAXHOST];
            if (local_getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) == 0)
                results.setHostName(QString::fromLatin1(hbuf));
        } else {
            unsigned long addr = inet_addr(hostName.toLatin1().constData());
            struct hostent *ent = gethostbyaddr((const char*)&addr, sizeof(addr), AF_INET);
            if (ent)
                results.setHostName(QString::fromLatin1(ent->h_name));
        }

        if (results.hostName().isEmpty())
            results.setHostName(address.toString());
        results.setAddresses(QList<QHostAddress>() << address);
        return results;
    }

    // IDN support
    QByteArray aceHostname = QUrl::toAce(hostName);
    results.setHostName(hostName);
    if (aceHostname.isEmpty()) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(hostName.isEmpty() ? tr("No host name given") : tr("Invalid hostname"));
        return results;
    }

    if (local_getaddrinfo && local_freeaddrinfo) {
        // Call getaddrinfo, and place all IPv4 addresses at the start
        // and the IPv6 addresses at the end of the address list in
        // results.
        qt_addrinfo *res;
        int err = local_getaddrinfo(aceHostname.constData(), 0, 0, &res);
        if (err == 0) {
            QList<QHostAddress> addresses;
            for (qt_addrinfo *p = res; p != 0; p = p->ai_next) {
                switch (p->ai_family) {
                case AF_INET: {
                    QHostAddress addr;
                    addr.setAddress(ntohl(((sockaddr_in *) p->ai_addr)->sin_addr.s_addr));
                    if (!addresses.contains(addr))
                        addresses.append(addr);
                }
                    break;
                case AF_INET6: {
                    QHostAddress addr;
                    addr.setAddress(((qt_sockaddr_in6 *) p->ai_addr)->sin6_addr.qt_s6_addr);
                    if (!addresses.contains(addr))
                        addresses.append(addr);
                }
                    break;
                default:
                    results.setError(QHostInfo::UnknownError);
                    results.setErrorString(tr("Unknown address type"));
                }
            }
            results.setAddresses(addresses);
            local_freeaddrinfo(res);
        } else {
            translateWSAError(WSAGetLastError(), &results);
        }
    } else {
        // Fall back to gethostbyname, which only supports IPv4.
        hostent *ent = gethostbyname(aceHostname.constData());
        if (ent) {
            char **p;
            QList<QHostAddress> addresses;
            switch (ent->h_addrtype) {
            case AF_INET:
                for (p = ent->h_addr_list; *p != 0; p++) {
                    long *ip4Addr = (long *) *p;
                    QHostAddress temp;
                    temp.setAddress(ntohl(*ip4Addr));
                    addresses << temp;
                }
                break;
            default:
                results.setError(QHostInfo::UnknownError);
                results.setErrorString(tr("Unknown address type"));
                break;
            }
            results.setAddresses(addresses);
        } else {
            translateWSAError(WSAGetLastError(), &results);
        }
    }

#if defined(QHOSTINFO_DEBUG)
    if (results.error() != QHostInfo::NoError) {
        qDebug("QHostInfoAgent::run(%p): error (%s)",
               this, results.errorString().toLatin1().constData());
    } else {
        QString tmp;
        QList<QHostAddress> addresses = results.addresses();
        for (int i = 0; i < addresses.count(); ++i) {
            if (i != 0) tmp += ", ";
            tmp += addresses.at(i).toString();
        }
        qDebug("QHostInfoAgent::run(%p): found %i entries: {%s}",
               this, addresses.count(), tmp.toLatin1().constData());
    }
#endif
    return results;
}

QString QHostInfo::localHostName()
{
    QWindowsSockInit winSock;

    char hostName[512];
    if (gethostname(hostName, sizeof(hostName)) == -1)
        return QString();
    hostName[sizeof(hostName) - 1] = '\0';
    return QString::fromLocal8Bit(hostName);
}

// QString QHostInfo::localDomainName() defined in qnetworkinterface_win.cpp

QT_END_NAMESPACE


text:
/*
 * Unless otherwise indicated, Source Code is licensed under MIT license.
 * See further explanation attached in License Statement (distributed in the file
 * LICENSE).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>
#include <gst/gst.h>

#include "mpegpsmux.h"
#include "psmuxcommon.h"
#include "psmuxstream.h"
#include "psmux.h"
#include "crc.h"

static gboolean psmux_packet_out (PsMux * mux);
static gboolean psmux_write_pack_header (PsMux * mux);
static gboolean psmux_write_system_header (PsMux * mux);
static gboolean psmux_write_program_stream_map (PsMux * mux);

/**
 * psmux_new:
 *
 * Create a new muxer session.
 *
 * Returns: A new #PsMux object.
 */
PsMux *
psmux_new (void)
{
  PsMux *mux;

  mux = g_slice_new0 (PsMux);

  mux->pts = -1;                /* uninitialized values */
  mux->pack_hdr_pts = -1;
  mux->sys_hdr_pts = -1;
  mux->psm_pts = -1;

  mux->bit_pts = 0;

  mux->pes_max_payload = PSMUX_PES_MAX_PAYLOAD;
  mux->bit_rate = 400 * 1024;   /* XXX: better default values? */
  mux->rate_bound = 2 * 1024;   /* 2* bit_rate / (8*50). XXX: any better default? */

  mux->pack_hdr_freq = PSMUX_PACK_HDR_FREQ;
  mux->sys_hdr_freq = PSMUX_SYS_HDR_FREQ;
  mux->psm_freq = PSMUX_PSM_FREQ;

  psmux_stream_id_info_init (&mux->id_info);

  return mux;
}

/**
 * psmux_set_write_func:
 * @mux: a #PsMux
 * @func: a user callback function
 * @user_data: user data passed to @func
 *
 * Set the callback function and user data to be called when @mux has output to
 * produce. @user_data will be passed as user data in @func.
 */
void
psmux_set_write_func (PsMux * mux, PsMuxWriteFunc func, void *user_data)
{
  g_return_if_fail (mux != NULL);

  mux->write_func = func;
  mux->write_func_data = user_data;
}

gboolean
psmux_write_end_code (PsMux * mux)
{
  guint8 end_code[4] = { 0, 0, 1, PSMUX_PROGRAM_END };
  return mux->write_func (end_code, 4, mux->write_func_data);
}

/**
 * psmux_free:
 * @mux: a #PsMux
 *
 * Free all resources associated with @mux. After calling this function @mux can
 * not be used anymore.
 */
void
psmux_free (PsMux * mux)
{
  GList *cur;

  g_return_if_fail (mux != NULL);

  /* Free all streams */
  for (cur = g_list_first (mux->streams); cur != NULL; cur = g_list_next (cur)) {
    PsMuxStream *stream = (PsMuxStream *) cur->data;

    psmux_stream_free (stream);
  }
  g_list_free (mux->streams);

  if (mux->sys_header != NULL)
    gst_buffer_unref (mux->sys_header);

  if (mux->psm != NULL)
    gst_buffer_unref (mux->psm);

  g_slice_free (PsMux, mux);
}

/**
 * psmux_create_stream:
 * @mux: a #PsMux
 * @stream_type: a #PsMuxStreamType
 *
 * Create a new stream of @stream_type in the muxer session @mux.
 *
 * Returns: a new #PsMuxStream.
 */
PsMuxStream *
psmux_create_stream (PsMux * mux, PsMuxStreamType stream_type)
{
  PsMuxStream *stream;
//  guint16 new_pid;

  g_return_val_if_fail (mux != NULL, NULL);

#if 0
  if (pid == PSMUX_PID_AUTO) {
    new_pid = psmux_get_new_pid (mux);
  } else {
    new_pid = pid & 0x1FFF;
  }

  /* Ensure we're not creating a PID collision */
  if (psmux_find_stream (mux, new_pid))
    return NULL;
#endif

  stream = psmux_stream_new (mux, stream_type);

  mux->streams = g_list_prepend (mux->streams, stream);
  if (stream->stream_id_ext) {
    if (!mux->nb_private_streams)
      mux->nb_streams++;
    mux->nb_private_streams++;
  } else
    mux->nb_streams++;

  if (stream->is_video_stream) {
    mux->video_bound++;
    if (mux->video_bound > 32)
      g_critical ("Number of video es exceeds upper limit");
  } else if (stream->is_audio_stream) {
    mux->audio_bound++;
    if (mux->audio_bound > 64)
      g_critical ("Number of audio es exceeds upper limit");
  }

  return stream;
}

static gboolean
psmux_packet_out (PsMux * mux)
{
  gboolean res;
  if (G_UNLIKELY (mux->write_func == NULL))
    return TRUE;

  res = mux->write_func (mux->packet_buf, mux->packet_bytes_written,
      mux->write_func_data);

  if (res) {
    mux->bit_size += mux->packet_bytes_written;
  }
  mux->packet_bytes_written = 0;
  return res;
}

/**
 * psmux_write_stream_packet:
 * @mux: a #PsMux
 * @stream: a #PsMuxStream
 *
 * Write a packet of @stream.
 *
 * Returns: TRUE if the packet could be written.
 */
gboolean
psmux_write_stream_packet (PsMux * mux, PsMuxStream * stream)
{
  gboolean res;

  g_return_val_if_fail (mux != NULL, FALSE);
  g_return_val_if_fail (stream != NULL, FALSE);

  {
    guint64 ts = psmux_stream_get_pts (stream);
    if (ts != -1)
      mux->pts = ts;
  }

  if (mux->pts - mux->pack_hdr_pts > PSMUX_PACK_HDR_INTERVAL
      || mux->pes_cnt % mux->pack_hdr_freq == 0) {
    /* Time to write pack header */
    /* FIXME: currently we write the mux rate of the PREVIOUS pack into the
     * pack header, because of the incapability to calculate the mux_rate
     * before outputing the pack. To calculate the mux_rate for the current
     * pack, we need to put the whole pack into buffer, calculate the
     * mux_rate, and then output the whole trunck.
     */
    if (mux->pts != -1 && mux->pts > mux->bit_pts
        && mux->pts - mux->bit_pts > PSMUX_BITRATE_CALC_INTERVAL) {
      /* XXX: smoothing the rate? */
      mux->bit_rate =
          gst_util_uint64_scale (mux->bit_size, 8 * CLOCKBASE,
          (mux->pts - mux->bit_pts));

      mux->bit_size = 0;
      mux->bit_pts = mux->pts;
    }

    psmux_write_pack_header (mux);
    mux->pack_hdr_pts = mux->pts;
  }

  if (mux->pes_cnt % mux->sys_hdr_freq == 0) {
    /* Time to write system header */
    psmux_write_system_header (mux);
    mux->sys_hdr_pts = mux->pts;
  }

  if (mux->pes_cnt % mux->psm_freq == 0) {
    /* Time to write program stream map (PSM) */
    psmux_write_program_stream_map (mux);
    mux->psm_pts = mux->pts;
  }

  /* Write the packet */
  if (!(mux->packet_bytes_written =
          psmux_stream_get_data (stream, mux->packet_buf,
              mux->pes_max_payload + PSMUX_PES_MAX_HDR_LEN))) {
    return FALSE;
  }

  res = psmux_packet_out (mux);
  if (!res) {
    GST_DEBUG_OBJECT (mux, "packet write false");
    return FALSE;
  }

  mux->pes_cnt += 1;

  return res;
}

static gboolean
psmux_write_pack_header (PsMux * mux)
{
  bits_buffer_t bw;
  guint64 scr = mux->pts;       /* XXX: is this correct? necessary to put any offset? */
  if (mux->pts == -1)
    scr = 0;

  /* pack_start_code */
  bits_initwrite (&bw, 14, mux->packet_buf);
  bits_write (&bw, 24, PSMUX_START_CODE_PREFIX);
  bits_write (&bw, 8, PSMUX_PACK_HEADER);

  /* scr */
  bits_write (&bw, 2, 0x1);
  bits_write (&bw, 3, (scr >> 30) & 0x07);
  bits_write (&bw, 1, 1);
  bits_write (&bw, 15, (scr >> 15) & 0x7fff);
  bits_write (&bw, 1, 1);
  bits_write (&bw, 15, scr & 0x7fff);
  bits_write (&bw, 1, 1);
  bits_write (&bw, 9, 0);       /* system_clock_reference_extension: set to 0 (like what VLC does) */
  bits_write (&bw, 1, 1);

  {
    /* Scale to get the mux_rate, rounding up */
    guint mux_rate =
        gst_util_uint64_scale (mux->bit_rate + 8 * 50 - 1, 1, 8 * 50);
    if (mux_rate > mux->rate_bound / 2)
      mux->rate_bound = mux_rate * 2;
    bits_write (&bw, 22, mux_rate);     /* program_mux_rate */
    bits_write (&bw, 2, 3);
  }

  bits_write (&bw, 5, 0x1f);
  bits_write (&bw, 3, 0);       /* pack_stuffing_length */

  mux->packet_bytes_written = 14;
  return psmux_packet_out (mux);
}

static void
psmux_ensure_system_header (PsMux * mux)
{
  bits_buffer_t bw;
  guint len = 12 + (mux->nb_streams +
      (mux->nb_private_streams > 1 ? mux->nb_private_streams - 1 : 0)) * 3;
  GList *cur;
  gboolean private_hit = FALSE;
  guint8 *data;

  if (mux->sys_header != NULL)
    return;

  data = g_malloc (len);

  bits_initwrite (&bw, len, data);

  /* system_header start code */
  bits_write (&bw, 24, PSMUX_START_CODE_PREFIX);
  bits_write (&bw, 8, PSMUX_SYSTEM_HEADER);

  bits_write (&bw, 16, len - 6);        /* header_length (bytes after this field) */
  bits_write (&bw, 1, 1);       /* marker */
  bits_write (&bw, 22, mux->rate_bound);        /* rate_bound */
  bits_write (&bw, 1, 1);       /* marker */
  bits_write (&bw, 6, mux->audio_bound);        /* audio_bound */
  bits_write (&bw, 1, 0);       /* fixed_flag */
  bits_write (&bw, 1, 0);       /* CSPS_flag */
  bits_write (&bw, 1, 0);       /* system_audio_lock_flag */
  bits_write (&bw, 1, 0);       /* system_video_lock_flag */
  bits_write (&bw, 1, 1);       /* marker */
  bits_write (&bw, 5, mux->video_bound);        /* video_bound */
  bits_write (&bw, 1, 0);       /* packet_rate_restriction_flag */
  bits_write (&bw, 7, 0x7f);    /* reserved_bits */

  for (cur = mux->streams, private_hit = FALSE; cur != NULL; cur = cur->next) {
    PsMuxStream *stream = (PsMuxStream *) cur->data;

    if (private_hit && stream->stream_id == PSMUX_EXTENDED_STREAM)
      continue;

    bits_write (&bw, 8, stream->stream_id);     /* stream_id */
    bits_write (&bw, 2, 0x3);   /* reserved */
    bits_write (&bw, 1, stream->is_video_stream);       /* buffer_bound_scale */
    bits_write (&bw, 13, stream->max_buffer_size / (stream->is_video_stream ? 1024 : 128));     /* buffer_size_bound */

    if (stream->stream_id == PSMUX_EXTENDED_STREAM)
      private_hit = TRUE;
  }

  GST_MEMDUMP ("System Header", data, len);

  mux->sys_header = gst_buffer_new_wrapped (data, len);
}

static gboolean
psmux_write_system_header (PsMux * mux)
{
  GstMapInfo map;

  psmux_ensure_system_header (mux);

  gst_buffer_map (mux->sys_header, &map, GST_MAP_READ);
  memcpy (mux->packet_buf, map.data, map.size);
  mux->packet_bytes_written = map.size;
  gst_buffer_unmap (mux->sys_header, &map);

  return psmux_packet_out (mux);
}

static void
psmux_ensure_program_stream_map (PsMux * mux)
{
  gint psm_size = 16, es_map_size = 0;
  bits_buffer_t bw;
  GList *cur;
  guint16 len;
  guint8 *pos;
  guint8 *data;

  if (mux->psm != NULL)
    return;

  /* pre-write the descriptor loop */
  pos = mux->es_info_buf;
  for (cur = mux->streams; cur != NULL; cur = cur->next) {
    PsMuxStream *stream = (PsMuxStream *) cur->data;
    len = 0;

    *pos++ = stream->stream_type;
    *pos++ = stream->stream_id;

    psmux_stream_get_es_descrs (stream, pos + 2, &len);
    psmux_put16 (&pos, len);

    es_map_size += len + 4;
    pos += len;
#if 0
    if (stream->lang[0] != 0)
      es_map_size += 6;
#endif
  }

  psm_size += es_map_size;

  data = g_malloc (psm_size);

  bits_initwrite (&bw, psm_size, data);

  /* psm start code */
  bits_write (&bw, 24, PSMUX_START_CODE_PREFIX);
  bits_write (&bw, 8, PSMUX_PROGRAM_STREAM_MAP);

  bits_write (&bw, 16, psm_size - 6);   /* psm_length */
  bits_write (&bw, 1, 1);       /* current_next_indicator */
  bits_write (&bw, 2, 0xF);     /* reserved */
  bits_write (&bw, 5, 0x1);     /* psm_version = 1 */
  bits_write (&bw, 7, 0xFF);    /* reserved */
  bits_write (&bw, 1, 1);       /* marker */

  bits_write (&bw, 16, 0);      /* program_stream_info_length */
  /* program_stream_info empty */

  bits_write (&bw, 16, es_map_size);    /* elementary_stream_map_length */

  memcpy (bw.p_data + bw.i_data, mux->es_info_buf, es_map_size);

  /* CRC32 */
  {
    guint32 crc = calc_crc32 (bw.p_data, psm_size - 4);
    guint8 *pos = bw.p_data + psm_size - 4;
    psmux_put32 (&pos, crc);
  }

  GST_MEMDUMP ("Program Stream Map", data, psm_size);

  mux->psm = gst_buffer_new_wrapped (data, psm_size);
}

static gboolean
psmux_write_program_stream_map (PsMux * mux)
{
  GstMapInfo map;

  psmux_ensure_program_stream_map (mux);

  gst_buffer_map (mux->psm, &map, GST_MAP_READ);
  memcpy (mux->packet_buf, map.data, map.size);
  mux->packet_bytes_written = map.size;
  gst_buffer_unmap (mux->psm, &map);

  return psmux_packet_out (mux);
}

GList *
psmux_get_stream_headers (PsMux * mux)
{
  GList *list;

  psmux_ensure_system_header (mux);
  psmux_ensure_program_stream_map (mux);

  list = g_list_append (NULL, gst_buffer_ref (mux->sys_header));
  list = g_list_append (list, gst_buffer_ref (mux->psm));

  return list;
}


text:
import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { TdLoadingService } from '@covalent/core/loading';
import { TokenService, ConfigurationService } from '../services/index';

import { environment } from '../../../environments/environment';
import { MsalService} from "@azure/msal-angular";

@Component({
  selector: 'crm-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent {

  username: string;
  password: string;
  loginError: boolean = false;
  errorMessage: string;
  layoutColor: string;
  constructor(private _router: Router,
              private _loadingService: TdLoadingService,
              private _token: TokenService,
              private _confs: ConfigurationService,
              private authService : MsalService,) {

    this.layoutColor = environment.layoutColor;

  }

  login(): void {
    this._loadingService.register();

    this._token.login(this.username, this.password)
    .subscribe( (res: any) => {
       this._confs.tokenData = res;

       this._loadingService.resolve();
       this.store(res);
       this._token.getUserInfo(() => {
        this._router.navigate(['/']);
       });

     }, (error: any) => {
       let res = error.json();
       this.errorMessage = res.error_description;
       this.loginError = true;
       this._loadingService.resolve();
     });
  }

  loginAzure() {
    this.authService.loginRedirect(environment._scopes);

  }
    /**
   * Stores access token & refresh token.
   *
   * @param body The response of the request to the token endpoint
   */
  private store(body: any): void {
      // Stores access token in local storage to keep user signed in.
      sessionStorage.setItem('tokendata', JSON.stringify(body));
      // Decodes the token.
      //this.decodeToken();
  }
}


text:
using Microsoft.Web.Administration;
using System.Collections.Generic;
using System.Linq;

namespace RMS.IISAgent.Core.Web
{
    public class IISServer : IWebServer
    {
        public IEnumerable<WebAppPool> ActiveAppPools
        {
            get
            {
                using (var serverManager = new ServerManager())
                {
                    var appPools = new List<WebAppPool>();

                    foreach (var appPool in serverManager.ApplicationPools)
                    {
                        var workerProcess = serverManager.WorkerProcesses.SingleOrDefault((worker => worker.AppPoolName.Equals(appPool.Name)));
                        if (workerProcess == null)
                            continue;

                        var webAppPool = new WebAppPool(appPool.Name, workerProcess.ProcessId);

                        appPools.Add(webAppPool);
                    }

                    return appPools;
                }
            }
        }

        public IEnumerable<WebApp> ActiveApps
        {
            get
            {
                using (var serverManager = new ServerManager())
                {
                    var webApps = new List<WebApp>();

                    foreach (var site in serverManager.Sites)
                    {
                        var workerProcess = serverManager.WorkerProcesses.SingleOrDefault(worker => worker.AppPoolName.Equals(site.Name));
                        if (workerProcess == null)
                            continue;

                        var webApp = new WebApp(site.Id, site.Name, workerProcess.ProcessId);

                        webApps.Add(webApp);
                    }

                    return webApps;
                }
            }
        }
    }
}


text:
@interface HomePageViewController : UIViewController <UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITableView *businessTableView;
@property (strong, nonatomic) IBOutlet UIProgressView *progressBar;
@property (strong, nonatomic) IBOutlet UITextField *whatTxtField;
@end


text:
#ifndef	_LOCALE_H
#define	_LOCALE_H

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>

#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */
#ifdef __cplusplus
#define NULL 0L
#else
#define NULL ((void*)0)
#endif
#else
#define __need_NULL
#include <stddef.h>
#endif

#define LC_CTYPE    0
#define LC_NUMERIC  1
#define LC_TIME     2
#define LC_COLLATE  3
#define LC_MONETARY 4
#define LC_MESSAGES 5
#define LC_ALL      6

struct lconv {
	char *decimal_point;
	char *thousands_sep;
	char *grouping;

	char *int_curr_symbol;
	char *currency_symbol;
	char *mon_decimal_point;
	char *mon_thousands_sep;
	char *mon_grouping;
	char *positive_sign;
	char *negative_sign;
	char int_frac_digits;
	char frac_digits;
	char p_cs_precedes;
	char p_sep_by_space;
	char n_cs_precedes;
	char n_sep_by_space;
	char p_sign_posn;
	char n_sign_posn;
	char int_p_cs_precedes;
	char int_p_sep_by_space;
	char int_n_cs_precedes;
	char int_n_sep_by_space;
	char int_p_sign_posn;
	char int_n_sign_posn;
};

char *setlocale (int, const char *);
struct lconv *localeconv(void);

#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)

#define __NEED_locale_t

#include <bits/alltypes.h>

#define LC_GLOBAL_LOCALE ((locale_t)-1)

#define LC_CTYPE_MASK    (1<<LC_CTYPE)
#define LC_NUMERIC_MASK  (1<<LC_NUMERIC)
#define LC_TIME_MASK     (1<<LC_TIME)
#define LC_COLLATE_MASK  (1<<LC_COLLATE)
#define LC_MONETARY_MASK (1<<LC_MONETARY)
#define LC_MESSAGES_MASK (1<<LC_MESSAGES)
#define LC_ALL_MASK      0x7fffffff

locale_t duplocale(locale_t);
void freelocale(locale_t);
locale_t newlocale(int, const char *, locale_t);
locale_t uselocale(locale_t);

#endif

#ifdef __cplusplus
}
#endif

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:evermemo="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/esdk__switch_service"
        android:title=""
        android:showAsAction="always"/>

</menu>