text:
from __future__ import absolute_import
from typing import Any, Callable

from zerver.lib.sessions import (
    user_sessions,
    delete_session,
    delete_user_sessions,
    delete_realm_user_sessions,
    delete_all_user_sessions,
    delete_all_deactivated_user_sessions,
)

from zerver.models import (
    UserProfile, get_user_profile_by_id,
    get_user_profile_by_email, get_realm
)

from zerver.lib.test_classes import ZulipTestCase

class TestSessions(ZulipTestCase):

    def do_test_session(self, user, action, expected_result):
        # type: (str, Callable[[], Any], bool) -> None
        self.login(user)
        self.assertIn('_auth_user_id', self.client.session)
        action()
        if expected_result:
            result = self.client_get('/')
            self.assertEqual('/login', result.url)
        else:
            self.assertIn('_auth_user_id', self.client.session)

    def test_delete_session(self):
        # type: () -> None
        self.login('hamlet@zulip.com')
        self.assertIn('_auth_user_id', self.client.session)
        user_profile = get_user_profile_by_email('hamlet@zulip.com')
        for session in user_sessions(user_profile):
            delete_session(session)
        result = self.client_get("/")
        self.assertEqual('/login', result.url)

    def test_delete_user_sessions(self):
        # type: () -> None
        user_profile = get_user_profile_by_email('hamlet@zulip.com')
        self.do_test_session('hamlet@zulip.com', lambda: delete_user_sessions(user_profile), True)
        self.do_test_session('othello@zulip.com', lambda: delete_user_sessions(user_profile), False)

    def test_delete_realm_user_sessions(self):
        # type: () -> None
        realm = get_realm('zulip')
        self.do_test_session('hamlet@zulip.com', lambda: delete_realm_user_sessions(realm), True)
        self.do_test_session('sipbtest@mit.edu', lambda: delete_realm_user_sessions(realm), False)

    def test_delete_all_user_sessions(self):
        # type: () -> None
        self.do_test_session('hamlet@zulip.com', lambda: delete_all_user_sessions(), True)
        self.do_test_session('sipbtest@mit.edu', lambda: delete_all_user_sessions(), True)

    def test_delete_all_deactivated_user_sessions(self):
        # type: () -> None

        # Test that no exception is thrown with a logged-out session
        self.login('hamlet@zulip.com')
        self.assertIn('_auth_user_id', self.client.session)
        self.client_post('/accounts/logout/')
        delete_all_deactivated_user_sessions()
        result = self.client_get("/")
        self.assertEqual('/login', result.url)

        # Test nothing happens to an active user's session
        self.login('othello@zulip.com')
        self.assertIn('_auth_user_id', self.client.session)
        delete_all_deactivated_user_sessions()
        self.assertIn('_auth_user_id', self.client.session)

        # Test that a deactivated session gets logged out
        self.login('cordelia@zulip.com')
        self.assertIn('_auth_user_id', self.client.session)
        user_profile_3 = get_user_profile_by_email('cordelia@zulip.com')
        user_profile_3.is_active = False
        user_profile_3.save()
        delete_all_deactivated_user_sessions()
        result = self.client_get("/")
        self.assertEqual('/login', result.url)


text:
import sys
sys.path.append('..')

import os
# Make a backup of DJANGO_SETTINGS_MODULE environment variable to restore later.
backup = os.environ.get('DJANGO_SETTINGS_MODULE', '')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from django.test.simple import run_tests

if __name__ == "__main__":
    failures = run_tests(['oembed',], verbosity=9)
    if failures:
        sys.exit(failures)
    # Reset the DJANGO_SETTINGS_MODULE to what it was before running tests.
    os.environ['DJANGO_SETTINGS_MODULE'] = backup

redpajama_set_name: RedPajamaGithub


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

using OpenTK;
using OpenTK.Graphics.OpenGL;

using KailashEngine.Render.Shader;
using KailashEngine.Render.Objects;
using KailashEngine.Output;

namespace KailashEngine.Render.FX
{
    class fx_Crosshair : RenderEffect
    {

        // Programs
        private Program _pCrosshair;

        // Frame Buffers
        private int _vao_crosshair;

        // Textures
        private Image _iCrosshair;

        public fx_Crosshair(ProgramLoader pLoader, StaticImageLoader tLoader, string resource_folder_name, Resolution full_resolution)
            : base(pLoader, tLoader, resource_folder_name, full_resolution)
        { }

        protected override void load_Programs()
        {
            // Rendering Geometry into gBuffer
            _pCrosshair = _pLoader.createProgram(new ShaderFile[]
            {
                new ShaderFile(ShaderType.VertexShader, _path_glsl_effect + "crosshair_Render.vert", null),
                new ShaderFile(ShaderType.FragmentShader, _path_glsl_effect + "crosshair_Render.frag", null)
            });
            _pCrosshair.enable_Samplers(1);
            _pCrosshair.addUniform("rotation");
        }

        protected override void load_Buffers()
        {
            // Load Crosshair texture
            _iCrosshair = _tLoader.createImage(_path_static_textures + "crosshair.png", TextureTarget.Texture2D, TextureWrapMode.ClampToEdge, false);

            // Create dummy VAO for point rendering
            GL.GenVertexArrays(1, out _vao_crosshair);
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
        }

        public override void load()
        {
            load_Programs();
            load_Buffers();
        }

        public override void unload()
        {

        }

        public override void reload()
        {

        }

        public void render(float animation_time)
        {
            if (!enabled) return;

            GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, 0);

            _pCrosshair.bind();

            // Blend with default frame buffer
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            GL.Enable(EnableCap.VertexProgramPointSize);

            // Bind Crosshair Texture
            _iCrosshair.bind(_pCrosshair.getSamplerUniform(0), 0);

            // Rotate Crosshair
            float angle = animation_time * 100.0f;
            float[] rotations = EngineHelper.createRotationFloats(angle);
            GL.Uniform2(_pCrosshair.getUniform("rotation"), rotations[0], rotations[1]);

            // Render Point Sprite
            GL.BindVertexArray(_vao_crosshair);
            GL.DrawArrays(PrimitiveType.Points, 0, 1);
            GL.BindVertexArray(0);

            GL.Disable(EnableCap.Blend);
        }

    }
}


text:
'use strict';

const assert = require('assert');
const mockRequire = require('mock-require');
const mockBindings = require('./mocks/bindings');
const mockLinux = require('./mocks/linux');
const mockI2c = require('./mocks/i2c.node');
const sinon = require('sinon');

mockRequire('bindings', mockBindings);
const i2c = require('../i2c-bus');

describe('writeWordSync', () => {
  let i2c1;

  beforeEach(() => {
    mockLinux.mockI2c1();

    i2c1 = i2c.openSync(1);

    sinon.stub(mockI2c, 'setAddrSync').callsFake(() => {});
    sinon.stub(mockI2c, 'writeWordSync').callsFake(() => {});
  });

  it('writes word to register', () => {
    const addr = 0x1;
    const cmd = 0x2;
    const word = 0xaa55;

    i2c1.writeWordSync(addr, cmd, word);

    assert(mockI2c.setAddrSync.calledOnce);
    assert.strictEqual(mockI2c.setAddrSync.firstCall.args.length, 3);
    const actualAddr = mockI2c.setAddrSync.firstCall.args[1];
    assert.strictEqual(addr, actualAddr);

    assert(mockI2c.writeWordSync.calledOnce);
    assert.strictEqual(mockI2c.writeWordSync.firstCall.args.length, 3);
    const actualCmd = mockI2c.writeWordSync.firstCall.args[1];
    const actualWord = mockI2c.writeWordSync.firstCall.args[2];
    assert.strictEqual(cmd, actualCmd);
    assert.strictEqual(word, actualWord);
  });

  it('returns this', () => {
    const addr = 0x1;
    const cmd = 0x2;
    const word = 0xaa55;

    assert.strictEqual(i2c1, i2c1.writeWordSync(addr, cmd, word));
  });

  afterEach(() => {
    mockI2c.setAddrSync.restore();
    mockI2c.writeWordSync.restore();

    i2c1.closeSync();

    mockLinux.restore();
  });
});


text:
import logging

from datetime import datetime
from myarchive.libs.livejournal import lj
from myarchive.libs.livejournal.backup import (
    DEFAULT_JOURNAL, update_journal_entries, update_journal_comments,
    datetime_from_string)
from sqlalchemy.orm.exc import NoResultFound

from myarchive.db.tag_db.tables.ljtables import (
    LJComment, LJEntry, LJHost, LJUser)

LOGGER = logging.getLogger(__name__)

class LJAPIConnection(object):

    def __init__(self, db_session, host, user_agent, username, password):
        """
        WARNING: MUST use HTTPS since this API uses *md5sum* for
        authentication! D:
        :param db_session:
        :param host:
        :param user_agent:
        :param username:
        :param password:
        """
        self.journal = DEFAULT_JOURNAL.copy()
        self._server = lj.LJServer(
            "Python-Blog3/1.0",
            user_agent=user_agent,
            host=host)
        self.journal['login'] = self.login = self._server.login(
            user=username,
            password=password)
        try:
            self.ljhost = db_session.query(LJHost).filter_by(url=host).one()
        except NoResultFound:
            self.ljhost = LJHost(url=host)
            db_session.add(self.ljhost)
            db_session.commit()

    def post_journal(self, subject, post, tags):
        """
        Posts a journal to the specified LJ server.
        """
        self._server.postevent(
            event=post,
            subject=subject,
            props={"taglist": ",".join(tags)})

    def download_journals_and_comments(self, db_session):
        """Downloads journals and comments to a defined dictionary."""

        # Sync entries from the server
        print("Downloading journal entries")
        new_journals = \
            update_journal_entries(server=self._server, journal=self.journal)

        # Sync comments from the server
        # print("Downloading comments")
        # new_comments = update_journal_comments(
        #     server=self._server, journal=self.journal)

        # print("Updated %d entries and %d comments" % (nj, nc))
        print(self.journal['login'])

        users = {
            int(self.journal['login']["userid"]):
                self.journal['login']["fullname"],
                # self.journal['login']["username"],
        }
        # for user_id, username in self.journal["comment_posters"].items():
        #     users[int(user_id)] = username

        poster = None
        lj_users = dict()
        for user_id, username in users.items():
            ljuser = LJUser.get_user(
                db_session=db_session, user_id=user_id, username=username)
            self.ljhost.users.append(ljuser)
            lj_users[user_id] = ljuser
            if user_id == int(self.journal['login']["userid"]):
                poster = ljuser
        db_session.commit()

        lj_entries = dict()
        for entry_id, entry in self.journal["entries"].items():
            LOGGER.critical(entry)
            LOGGER.critical(entry["event"])
            lj_entry = LJEntry.get_or_add_entry(
                db_session=db_session,
                lj_user=poster,
                itemid=entry_id,
                eventtime=datetime_from_string(entry["eventtime"]),
                subject=entry["subject"],
                text=str(entry["event"]),
                current_music=entry["props"].get("current_music"),
                tag_list=entry["props"].get("taglist")
            )
            lj_entries[entry_id] = lj_entry
        db_session.commit()

        # for comment_id, comment in self.journal["comments"].items():
        #     LJComment.get_or_add_comment(
        #         db_session=db_session,
        #         lj_user=lj_users[int(comment["posterid"])],
        #         lj_entry=lj_entries[int(comment["jitemid"])],
        #         itemid=int(comment_id),
        #         subject=comment["subject"],
        #         body=comment["body"],
        #         date=datetime.strptime(comment["date"], "%Y-%m-%dT%H:%M:%SZ"),
        #         parent_id=comment["parentid"]
        #     )
        db_session.commit()

def download_journals_and_comments(config, db_session):
    for config_section in config.sections():
        if config_section.startswith("LJ_"):
            LOGGER.info(config.get(section=config_section, option="host"))
            LOGGER.info(config.get(section=config_section, option="username"))
            ljapi = LJAPIConnection(
                db_session=db_session,
                host=config.get(
                    section=config_section, option="host"),
                user_agent=config.get(
                    section=config_section, option="user_agent"),
                username=config.get(
                    section=config_section, option="username"),
                password=config.get(
                    section=config_section, option="password"),
            )
            ljapi.download_journals_and_comments(db_session=db_session)


text:
require 'injectorize/text_utils'

module Injectorize
  module Injector

    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods

      def inject(klass)
        build_accessor klass
      end

      private

      def build_accessor(klass)
        klass_name = TextUtils.pascal_to_snake(klass.name)
        attr_name = "@#{klass_name}".to_sym
        build_getter(attr_name, klass_name, klass)
        build_setter(attr_name, klass_name)
      end

      def build_getter(attr_name, klass_name, klass)
        getter_name = klass_name.to_sym
        class_eval do
          define_method(getter_name) do
            klass_instance = instance_variable_get(attr_name) || klass.new
            instance_variable_set(attr_name, klass_instance)
          end
        end
      end

      def build_setter(attr_name, klass_name)
        setter_name = "#{klass_name}=".to_sym
        class_eval do
          define_method(setter_name) do |new_instance|
            instance_variable_set(attr_name, new_instance)
          end
        end
      end
    end
  end
end


text:
MDNSResponder::hMDNSServiceQuery hMDNSServiceQuery;

void MDNSServiceQueryCallback(MDNSResponder::MDNSServiceInfo serviceInfo, MDNSResponder::AnswerType answerType, bool p_bSetContent) {
    switch (answerType) {
        case MDNSResponder::AnswerType::IP4Address: {
            IPAddress localIP = WiFi.localIP();
            for (IPAddress ip : serviceInfo.IP4Adresses()) {
                if (localIP[0] == ip[0] && localIP[1] == ip[1] && localIP[2] == ip[2]) {
                    esp::ServerConnection::instance().setServer(ip, serviceInfo.hostPort());
                    break;
                }
            };
        }
        break;
        default:
        break;
    }
}

esp::ServerConnection::ServerConnection() {
    this->tcp = new WiFiClient();
    this->serverIP = new IPAddress();
}

esp::ServerConnection::~ServerConnection() {
    // this will never happen (as long as this class is a singleton) and generates warnings.
    //delete this->tcp;
}

esp::ServerConnection& esp::ServerConnection::instance() {
    static esp::ServerConnection _instance;
    return _instance;
}

bool esp::ServerConnection::connected() {
    return this->tcp->connected();
}

void esp::ServerConnection::disconnect() {
    this->tcp->stop();
}

void esp::ServerConnection::setServer(IPAddress &ip, uint16_t port) {
    *(this->serverIP) = ip;
    this->serverPort = port;
}

void esp::ServerConnection::loop(bool isWiFiConnected) {
    if (!isWiFiConnected) {
        if (this->tcp->connected()) {
            this->tcp->stop();
        }
        return;
    }
    if (!hMDNSServiceQuery) {
        hMDNSServiceQuery = MDNS.installServiceQuery("ipocs", "tcp", MDNSServiceQueryCallback);
    }
    if (!this->tcp->connected()) {
        if (this->serverPort != 0 && *(this->serverIP) != IPAddress()) {
            //esp::Http::instance().log("Connecting to: " + this->serverIP.toString() + ":" + String(this->serverPort));
            char unitName[32];
            Configuration::getUnitName(unitName);
            byte returnVal = this->tcp->connect(*(this->serverIP), this->serverPort);
            if (returnVal == 1) {
                LedControl::instance().setState(ON);
                this->tcp->keepAlive(5, 1, 4);
                IPOCS::Message *msg = IPOCS::Message::create();
                msg->setObject(unitName);
                IPOCS::ConnectionRequestPacket *pkt = (IPOCS::ConnectionRequestPacket *)IPOCS::ConnectionRequestPacket::create();
                pkt->RM_PROTOCOL_VERSION = 0x0101;
                char sdVersion[10];
                sprintf(sdVersion, "%d", Configuration::getSiteDataCrc());
                pkt->RXID_SITE_DATA_VERSION = sdVersion;
                msg->setPacket(pkt);
                this->send(msg);
                delete msg;

                IPC::Message *ipcPing = IPC::Message::create();
                ipcPing->RT_TYPE = IPC::CESTAB;
                ipcPing->setPayload();
                esp::ArduinoConnection::instance().send(ipcPing);
                delete ipcPing;
            }
        }
    } else {
        while (this->tcp->available()) {
            // Read the header
            byte RL_MESSAGE = 0;
            int numRead = this->tcp->read(&RL_MESSAGE, 1);
            if (numRead != 1) {
                // Close connection - error in reading.
                this->tcp->stop();
                return;
            }
            // Define the message
            byte message[RL_MESSAGE];
            message[0] = RL_MESSAGE;
            // Read the rest of the message
            numRead += this->tcp->read(message + 1, RL_MESSAGE - 1);
            if (numRead != RL_MESSAGE) {
                // Close connection - error in reading.
                this->tcp->stop();
                return;
            }
            // Now parse it.
            IPOCS::Message* msg = IPOCS::Message::create(message);
            IPC::Message* ipcMsg = IPC::Message::create();
            ipcMsg->RT_TYPE = IPC::IPOCS;
            ipcMsg->setPayload(message, msg->RL_MESSAGE);

            char unitName[32];
            Configuration::getUnitName(unitName);
            if (strcmp(msg->getObject(), unitName) == 0) {
                if (msg->packet->RNID_PACKET == 5) {
                    IPOCS::ApplicationDataPacket* dataPkt = (IPOCS::ApplicationDataPacket* const)msg->packet;
                    uint8_t dataLength = dataPkt->RL_PACKET - 5;
                    Configuration::setSD(dataPkt->data, dataLength);
                    handleRestart(true);
                }
            } else {
                ArduinoConnection::instance().send(ipcMsg);
            }
            delete msg;
            delete ipcMsg;
        }
    }
}

void esp::ServerConnection::send(IPOCS::Message* msg) {
    if (!this->tcp->connected()) {
        //esp::Http::instance().log("Not connected, throwing message");
        return;
    }
    uint8_t buffer[255];
    uint8_t len = msg->serialize(buffer);
    this->tcp->write(buffer, len);
}


text:
FactoryBot.define do
  factory :ext_management_system,
          :class   => "ManageIQ::Providers::Vmware::InfraManager" do
    sequence(:name)      { |n| "ems_#{seq_padded_for_sorting(n)}" }
    sequence(:hostname)  { |n| "ems-#{seq_padded_for_sorting(n)}" }
    sequence(:ipaddress) { |n| ip_from_seq(n) }
    zone                 { FactoryBot.create(:zone) }
    storage_profiles     { [] }

    # authorizations

    transient do
      authtype { nil }
    end

    after(:create) do |ems, ev|
      Array(ev.authtype).each { |a| ems.authentications << FactoryBot.create(:authentication, :authtype => a) }
    end

    # Traits

    trait :with_clusters do
      transient do
        cluster_count { 3 }
      end

      after :create do |ems, evaluator|
        create_list :ems_cluster, evaluator.cluster_count, :ext_management_system => ems
      end
    end

    trait :with_storages do
      transient do
        storage_count { 3 }
      end

      after :create do |ems, evaluator|
        create_list :storage, evaluator.storage_count, :ext_management_system => ems
      end
    end

    trait :with_authentication do
      authtype { "default" }
    end

    trait :with_unvalidated_authentication do
      after(:create) do |x|
        x.authentications << FactoryBot.create(:authentication, :status => nil)
      end
    end

    trait :with_invalid_authentication do
      after(:create) do |x|
        x.authentications << FactoryBot.create(:authentication, :status => "invalid")
      end
    end
  end

  # Intermediate classes
  # using leaf classes...
  factory :ems_infra,
          :aliases => ["manageiq/providers/infra_manager"],
          :class   => "ManageIQ::Providers::Vmware::InfraManager",
          :parent  => :ext_management_system

  factory :ems_physical_infra,
          :aliases => ["manageiq/providers/physical_infra_manager"],
          :class   => "ManageIQ::Providers::Redfish::PhysicalInfraManager",
          :parent  => :ext_management_system

  factory(:ems_cloud,
          :aliases => ["manageiq/providers/cloud_manager"],
          :class   => "ManageIQ::Providers::Amazon::CloudManager",
          :parent  => :ext_management_system) do
    provider_region { "us-east-1" }
  end

  factory :ems_network,
          :aliases => ["manageiq/providers/network_manager"],
          :class   => "ManageIQ::Providers::Openstack::NetworkManager",
          :parent  => :ext_management_system do
    parent_manager { FactoryBot.create(:ext_management_system) }
  end

  factory :ems_storage,
          :aliases => ["manageiq/providers/storage_manager"],
          :class   => "ManageIQ::Providers::StorageManager::SwiftManager",
          :parent  => :ext_management_system

  factory :ems_cinder,
          :aliases => ["manageiq/providers/storage_manager/cinder_manager"],
          :class   => "ManageIQ::Providers::StorageManager::CinderManager",
          :parent  => :ext_management_system

  factory :ems_swift,
          :aliases => ["manageiq/providers/storage_manager/swift_manager"],
          :class   => "ManageIQ::Providers::StorageManager::SwiftManager",
          :parent  => :ext_management_system

  factory :ems_container,
          :aliases => ["manageiq/providers/container_manager"],
          :class   => "ManageIQ::Providers::Openshift::ContainerManager",
          :parent  => :ext_management_system

  factory :configuration_manager,
          :aliases => ["manageiq/providers/configuration_manager"],
          :class   => "ManageIQ::Providers::Foreman::ConfigurationManager",
          :parent  => :ext_management_system

  # Automation managers

  factory :automation_manager,
          :aliases => ["manageiq/providers/automation_manager"],
          :class   => "ManageIQ::Providers::AnsibleTower::AutomationManager",
          :parent  => :ext_management_system

  factory :provisioning_manager,
          :aliases => ["manageiq/providers/provisioning_manager"],
          :class   => "ManageIQ::Providers::Foreman::ProvisioningManager",
          :parent  => :ext_management_system

  # Leaf classes for ems_infra

  factory :ems_vmware,
          :aliases => ["manageiq/providers/vmware/infra_manager"],
          :class   => "ManageIQ::Providers::Vmware::InfraManager",
          :parent  => :ems_infra

  factory :ems_vmware_with_authentication,
          :parent => :ems_vmware do
    authtype { "default" }
  end

  factory :ems_microsoft,
          :aliases => ["manageiq/providers/microsoft/infra_manager"],
          :class   => "ManageIQ::Providers::Microsoft::InfraManager",
          :parent  => :ems_infra

  factory :ems_microsoft_with_authentication,
          :parent => :ems_microsoft do
    authtype { "default" }
  end

  factory :ems_redhat,
          :aliases => ["manageiq/providers/redhat/infra_manager"],
          :class   => "ManageIQ::Providers::Redhat::InfraManager",
          :parent  => :ems_infra

  factory :ems_redhat_v3,
          :parent => :ems_redhat do
    api_version { '3.5' }
  end

  factory :ems_redhat_v4,
          :parent => :ems_redhat do
    api_version { '4.0' }
  end

  factory :ems_redhat_with_authentication,
          :parent => :ems_redhat do
    authtype { "default" }
  end

  trait :skip_validate do
    to_create { |instance| instance.save(:validate => false) }
  end

  factory :ems_redhat_with_authentication_with_ca,
          :parent => :ems_redhat do
    certificate_authority { "cert108" }
    authtype { "default" }
  end

  factory :ems_redhat_with_metrics_authentication,
          :parent => :ems_redhat do
    after(:create) do |x|
      x.authentications << FactoryBot.create(:authentication_redhat_metric)
    end
  end

  factory :ems_openstack_infra,
          :aliases => ["manageiq/providers/openstack/infra_manager"],
          :class   => "ManageIQ::Providers::Openstack::InfraManager",
          :parent  => :ems_infra

  factory :ems_openstack_infra_with_stack,
          :parent => :ems_openstack_infra do
    after :create do |x|
      x.orchestration_stacks << FactoryBot.create(:orchestration_stack_openstack_infra)
      4.times { x.hosts << FactoryBot.create(:host_openstack_infra) }
    end
  end

  factory :ems_openstack_infra_with_stack_and_compute_nodes,
          :parent => :ems_openstack_infra do
    after :create do |x|
      x.orchestration_stacks << FactoryBot.create(:orchestration_stack_openstack_infra)
      x.hosts += [FactoryBot.create(:host_openstack_infra_compute),
                  FactoryBot.create(:host_openstack_infra_compute_maintenance)]
    end
  end

  factory :ems_openstack_infra_with_authentication,
          :parent => :ems_openstack_infra do
    authtype { %w(default amqp) }
  end

  factory :ems_vmware_cloud,
          :aliases => ["manageiq/providers/vmware/cloud_manager"],
          :class   => "ManageIQ::Providers::Vmware::CloudManager",
          :parent  => :ems_cloud

  factory :ems_vmware_cloud_network,
          :aliases => ["manageiq/providers/vmware/network_manager"],
          :class   => "ManageIQ::Providers::Vmware::NetworkManager",
          :parent  => :ems_cloud

  # Leaf classes for ems_cloud

  factory :ems_amazon,
          :aliases => ["manageiq/providers/amazon/cloud_manager"],
          :class   => "ManageIQ::Providers::Amazon::CloudManager",
          :parent  => :ems_cloud do
    provider_region { "us-east-1" }
  end

  factory :ems_amazon_network,
          :aliases => ["manageiq/providers/amazon/network_manager"],
          :class   => "ManageIQ::Providers::Amazon::NetworkManager",
          :parent  => :ems_network do
    provider_region { "us-east-1" }
  end

  factory :ems_amazon_with_authentication,
          :parent => :ems_amazon do
    authtype { "default" }
  end

  factory :ems_amazon_with_cloud_networks,
          :parent => :ems_amazon do
    after(:create) do |x|
      2.times { x.cloud_networks << FactoryBot.create(:cloud_network_amazon) }
    end
  end

  factory :ems_azure,
          :aliases => ["manageiq/providers/azure/cloud_manager"],
          :class   => "ManageIQ::Providers::Azure::CloudManager",
          :parent  => :ems_cloud do
    provider_region { "eastus" }
  end

  factory :ems_azure_network,
          :aliases => ["manageiq/providers/azure/network_manager"],
          :class   => "ManageIQ::Providers::Azure::NetworkManager",
          :parent  => :ems_network do
    provider_region { "eastus" }
  end

  factory :ems_azure_with_authentication,
          :parent => :ems_azure do
    azure_tenant_id { "ABCDEFGHIJABCDEFGHIJ0123456789AB" }
    subscription { "0123456789ABCDEFGHIJABCDEFGHIJKL" }
    authtype { "default" }
  end

  factory :ems_openstack,
          :aliases => ["manageiq/providers/openstack/cloud_manager"],
          :class   => "ManageIQ::Providers::Openstack::CloudManager",
          :parent  => :ext_management_system

  factory :ems_openstack_with_authentication,
          :parent => :ems_openstack do
    authtype { %w(default amqp) }
  end

  factory :ems_openstack_network,
          :aliases => ["manageiq/providers/openstack/network_manager"],
          :class   => "ManageIQ::Providers::Openstack::NetworkManager",
          :parent  => :ems_network

  factory :ems_nuage_network,
          :aliases => ["manageiq/providers/nuage/network_manager"],
          :class   => "ManageIQ::Providers::Nuage::NetworkManager",
          :parent  => :ems_network

  factory :ems_google,
          :aliases => ["manageiq/providers/google/cloud_manager"],
          :class   => "ManageIQ::Providers::Google::CloudManager",
          :parent  => :ems_cloud

  factory :ems_google_with_authentication,
          :parent => :ems_google do
    authtype { "default" }
  end

  factory :ems_google_network,
          :aliases => ["manageiq/providers/google/network_manager"],
          :class   => "ManageIQ::Providers::Google::NetworkManager",
          :parent  => :ems_network

  # Leaf classes for ems_container

  factory :ems_kubernetes,
          :aliases => ["manageiq/providers/kubernetes/container_manager"],
          :class   => "ManageIQ::Providers::Kubernetes::ContainerManager",
          :parent  => :ems_container

  factory :ems_kubernetes_with_authentication_err,
          :parent => :ems_kubernetes do
    after :create do |x|
      x.authentications << FactoryBot.create(:authentication_status_error)
    end
  end

  factory :ems_openshift,
          :aliases => ["manageiq/providers/openshift/container_manager"],
          :class   => "ManageIQ::Providers::Openshift::ContainerManager",
          :parent  => :ems_container

  # Leaf classes for configuration_manager

  factory :configuration_manager_foreman,
          :aliases => ["manageiq/providers/foreman/configuration_manager"],
          :class   => "ManageIQ::Providers::Foreman::ConfigurationManager",
          :parent  => :configuration_manager

  trait(:provider) do
    after(:build, &:create_provider)
  end

  trait(:configuration_script) do
    after(:create) do |x|
      type = (x.type.split("::")[0..2] + ["AutomationManager", "ConfigurationScript"]).join("::")
      x.configuration_scripts << FactoryBot.create(:configuration_script, :type => type)
    end
  end

  trait(:configuration_workflow) do
    after(:create) do |x|
      type = (x.type.split("::")[0..2] + %w(AutomationManager ConfigurationWorkflow)).join("::")
      x.configuration_scripts << FactoryBot.create(:configuration_workflow, :type => type)
    end
  end

  # Leaf classes for automation_manager

  factory :embedded_automation_manager_ansible,
          :aliases => ["manageiq/providers/embedded_ansible/automation_manager"],
          :class   => "ManageIQ::Providers::EmbeddedAnsible::AutomationManager",
          :parent  => :automation_manager

  # Leaf classes for provisioning_manager

  factory :provisioning_manager_foreman,
          :aliases => ["manageiq/providers/foreman/provisioning_manager"],
          :class   => "ManageIQ::Providers::Foreman::ProvisioningManager",
          :parent  => :provisioning_manager
end


text:
package com.mohanathas.spiffer.util;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * Implements a dynamic array (similar in operation to java.util.ArrayList<T>).
 *
 * @param <T> Type of element held in this array.
 */
public class DynamicArray<T> implements List<T> {
    private T[] mElements;
    private int mSize = 0;

    public DynamicArray(int initialCapacity) {
        mElements = (T[])new Object[initialCapacity];
    }

    public DynamicArray() {
        this(8);
    }

    /**
     * Returns <tt>true</tt> if this list contains the specified element.
     *
     * @param o Element whose presence in this list is to be tested.
     * @return <tt>true</tt> if this list contains the specified element.
     */
    @Override
    public boolean contains(Object o) {
        for (int i = 0; i < mSize; ++i) {
            if (mElements[i].equals(o)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * @param element Element to be appended to this list.
     * @return <tt>true</tt>.
     */
    @Override
    public boolean add(T element) {
        ensureCapacity();
        mElements[mSize] = element;
        ++mSize;
        return true;
    }

    /**
     * Returns the element at the specified position in this list.
     *
     * @param index Index of the element to return.
     * @return The element at the specified position in this list.
     */
    @Override
    public T get(int index) {
        return mElements[index];
    }

    /**
     * Removes the element at the specified position in this list.
     *
     * @param index The index of the element to be removed.
     * @return The element previously at the specified position.
     */
    @Override
    public T remove(int index) {
        final T t = mElements[index];
        --mSize;
        for (int i = index; i < mSize; ++i) {
            mElements[i] = mElements[i + 1];
        }
        mElements[mSize] = null;
        return t;
    }

    /**
     * Replaces the element at the specified position in this list with the specified element.
     *
     * @param index Index of the element to replace.
     * @param element Element to be stored at the specified position.
     * @return The element previously at the specified position.
     */
    @Override
    public T set(int index, T element) {
        final T prevElement = mElements[index];
        mElements[index] = element;
        return prevElement;
    }

    /**
     * Reverses the elements of this list.
     */
    public void reverse() {
        for (int i = 0; i < mSize / 2; ++i){
            final T temp = mElements[i];
            mElements[i] = mElements[mSize - i - 1];
            mElements[mSize - i - 1] = temp;
        }
    }

    /**
     * Returns <tt>true</tt> if this list contains no elements.
     *
     * @return <tt>true</tt> if this list contains no elements.
     */
    @Override
    public boolean isEmpty() {
        return mSize == 0;
    }

    /**
     * Returns the number of elements in this list.
     *
     * @return The number of elements in this list.
     */
    @Override
    public int size() {
        return mSize;
    }

    /**
     * Returns an iterator over the elements in this list in proper sequence.
     *
     * @return An iterator over the elements in this list in proper sequence.
     */
    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            private int mPosition = 0;

            @Override
            public boolean hasNext() {
                return mPosition < mSize;
            }

            @Override
            public T next() {
                final T t = (T)mElements[mPosition];
                ++mPosition;
                return t;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }

    private void ensureCapacity() {
        if (mSize < mElements.length) return;

         mElements = Arrays.copyOf(mElements, mElements.length * 2);
    }

    @Override
    public Object[] toArray() {
        throw new UnsupportedOperationException();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean remove(Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean addAll(Collection<? extends T> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean addAll(int index, Collection<? extends T> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void clear() {
        throw new UnsupportedOperationException();
    }

    @Override
    public void add(int index, T element) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int indexOf(Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int lastIndexOf(Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public ListIterator<T> listIterator() {
        throw new UnsupportedOperationException();
    }

    @Override
    public ListIterator<T> listIterator(int index) {
        throw new UnsupportedOperationException();
    }

    @Override
    public List<T> subList(int fromIndex, int toIndex) {
        throw new UnsupportedOperationException();
    }
}


text:
/*
 * This file is part of COMPASS. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this distribution.
 * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
 * You may not use this file except in compliance with the License.
 */
package de.dfki.asr.compass.rest.serialization;

import de.dfki.asr.compass.business.api.ComponentManager;
import de.dfki.asr.compass.business.exception.EntityNotFoundException;
import de.dfki.asr.compass.model.SceneNodeComponent;
import javax.inject.Inject;

public class SceneNodeComponentListDeserializer extends AbstractIDListDeserializer<SceneNodeComponent> {

	@Inject
	private ComponentManager manager;

	@Override
	protected SceneNodeComponent referenceById(final long id) throws EntityNotFoundException {
		return manager.referenceById(id);
	}
}


text:
package com.bvakili.portlet.integration.box.model;

import com.liferay.portal.model.PersistedModel;

/**
 * The extended model interface for the BoxToken service. Represents a row in the "BoxToken" database table, with each column mapped to a property of this class.
 *
 * @author Bijan Vakili
 * @see BoxTokenModel
 * @see com.bvakili.portlet.integration.box.model.impl.BoxTokenImpl
 * @see com.bvakili.portlet.integration.box.model.impl.BoxTokenModelImpl
 * @generated
 */
public interface BoxToken extends BoxTokenModel, PersistedModel {
	/*
	 * NOTE FOR DEVELOPERS:
	 *
	 * Never modify this interface directly. Add methods to {@link com.bvakili.portlet.integration.box.model.impl.BoxTokenImpl} and rerun ServiceBuilder to automatically copy the method declarations to this interface.
	 */
}


text:
<!doctype html>

		<meta charset='utf-8' />
		<meta name='viewport' content='width=device-width' />
		<meta http-equiv='X-UA-Compatible' content='ie=edge'>
		<title>Caffeinate in your macOS menu bar</title>
		<link rel='stylesheet' href='/public/css/xbar.css?cb=08%20Mar%2021%2015%3a22%20GMT'>
		<link rel='preconnect' href='https://fonts.gstatic.com'>
		<link rel='preconnect' href='https://fonts.googleapis.com'>
		<link rel='stylesheet' href='https://fonts.googleapis.com/css2?family=Bodoni+Moda:wght@500&display=swap'>

	<meta name='description' content=' - install xbar for free to get started.'>
	<meta name='author' content='Steffen Froehlich'>
	<meta name='keywords' content='macos,menubar,xbar,bitbar'>
	<meta itemprop='image' content='https://i.imgur.com/vsCWLwX.png'>
	<meta itemprop='name' content='Caffeinate in your macOS menu bar'>
	<meta itemprop='description' content=' - install xbar for free to get started.'>
	<meta name='twitter:card' content='summary_large_image'>
	<meta name='twitter:title' content='Caffeinate in your macOS menu bar'>
	<meta name='twitter:description' content=' - install xbar for free to get started.'>
	<meta name='twitter:image' content='https://i.imgur.com/vsCWLwX.png'>
	<meta name='twitter:creator' content='matryer'>
	<meta property='og:title' content='Caffeinate in your macOS menu bar'>
	<meta property='og:description' content=' - install xbar for free to get started.'>
	<meta property='og:url' content='https://xbarapp.com/plugins/System/caffeinate.1h.sh.html'>
	<meta property='og:site_name' content='xbar lets you put anything into your macOS menu bar'>
	<meta property='og:type' content='article'>
	<meta property='og:image' content='https://i.imgur.com/vsCWLwX.png'>
	<link rel='apple-touch-icon' sizes='180x180' href='https://i.imgur.com/vsCWLwX.png'>
	<link rel='icon' type='image/png' sizes='32x32' href='https://i.imgur.com/vsCWLwX.png'>
	<link rel='shortcut icon' href='https://i.imgur.com/vsCWLwX.png'>
	<meta name='msapplication-TileColor' content='#ffffff'>
	<meta name='msapplication-config' content='/public/browserconfig.xml'>
	<meta name='theme-color' content='#ffffff'>

						xbar

						💜 Sponsor

						Coming soon

					AWS

					Cryptocurrency

					Dev

					E-Commerce

					Email

					Environment

					Finance

					Games

					IoT

					Lifestyle

					Music

					Network

					Politics

					Science

					Sports

					System

					Time

					Tools

					Travel

					Weather

					Web

Caffeinate

										Steffen (@citoki on GitHub)

						🖥 Open in xbar app

Requires xbar app

							caffeinate.1h.sh

						Edit

						Open on GitHub

#!/bin/bash

# <bitbar.title>Caffeinate</bitbar.title>
# <bitbar.version>v0.2</bitbar.version>
# <bitbar.author>Steffen Froehlich</bitbar.author>
# <bitbar.author.github>citoki</bitbar.author.github>
# <bitbar.desc>This plugin will give some caffeine, with lots of sugar, to your Mac to stay awake.
# Technically the commandline tool 'caffeinate' is executed.</bitbar.desc>
# <bitbar.image>https://i.imgur.com/vsCWLwX.png</bitbar.image>
# <bitbar.dependencies></bitbar.dependencies>

function get_program_state {
  instances=$(pgrep caffeinate)

  # set state
  if [[ $instances = 1 ]]; then
    state="stopped";
  else
    state="running";
  fi
}

function set_program_icon {
  get_program_state;

  if [[ "$state" = "stopped" ]]; then
    icon="☕";
  else
    icon="🍵";
  fi
}

# stop all previous processes
function terminate_caffeinate_instances {
  /usr/bin/killall caffeinate &> /dev/null
}

if [[ "$1" = "caffeine" ]]; then
  terminate_caffeinate_instances;
  # start caffeinate program and prevent the system and display
  # from idle sleeping
  /usr/bin/caffeinate -di;

  exit
fi

if [[ "$1" = "stop" ]]; then
  terminate_caffeinate_instances;

  exit
fi

# set program icon to default: 'not active state'
set_program_icon;

echo "$icon"
echo "---"
echo "program state: ${state}"
echo "---"
echo "Prevent machine from idle sleep | bash='$0' param1=caffeine terminal=false"
echo "Stop program | bash='$0' param1=stop terminal=false"

						GitHub project
						•
						Writing plugins guide

						Copyright ©2021 Mat Ryer + contributors • @matryer

						Last updated on 08 Mar 21 15:22 GMT


text:
package org.apache.taverna.workflowmodel.impl;

import org.apache.taverna.invocation.WorkflowDataToken;
import org.apache.taverna.workflowmodel.Dataflow;

public class DummyDataflowInputPort extends DataflowInputPortImpl {

	public String tokenOwningProcess;

	public DummyDataflowInputPort(String name, int depth, int granularDepth,
			Dataflow df) {
		super(name, depth, granularDepth, df);
	}

	@Override
	public void receiveEvent(WorkflowDataToken t) {
		tokenOwningProcess=t.getOwningProcess();
	}
}


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

import com.facebook.presto.spi.Connector;
import com.facebook.presto.spi.ConnectorHandleResolver;
import com.facebook.presto.spi.ConnectorIndexResolver;
import com.facebook.presto.spi.ConnectorMetadata;
import com.facebook.presto.spi.ConnectorPageSourceProvider;
import com.facebook.presto.spi.ConnectorRecordSetProvider;
import com.facebook.presto.spi.ConnectorRecordSinkProvider;
import com.facebook.presto.spi.ConnectorSplitManager;

import javax.inject.Inject;

import static com.google.common.base.Preconditions.checkNotNull;

public class RaptorConnector
        implements Connector
{
    private final RaptorMetadata metadata;
    private final RaptorSplitManager splitManager;
    private final RaptorPageSourceProvider pageSourceProvider;
    private final RaptorRecordSinkProvider recordSinkProvider;
    private final RaptorHandleResolver handleResolver;

    @Inject
    public RaptorConnector(
            RaptorMetadata metadata,
            RaptorSplitManager splitManager,
            RaptorPageSourceProvider pageSourceProvider,
            RaptorRecordSinkProvider recordSinkProvider,
            RaptorHandleResolver handleResolver)
    {
        this.metadata = checkNotNull(metadata, "metadata is null");
        this.splitManager = checkNotNull(splitManager, "splitManager is null");
        this.pageSourceProvider = checkNotNull(pageSourceProvider, "pageSourceProvider is null");
        this.recordSinkProvider = checkNotNull(recordSinkProvider, "recordSinkProvider is null");
        this.handleResolver = checkNotNull(handleResolver, "handleResolver is null");
    }

    @Override
    public ConnectorPageSourceProvider getPageSourceProvider()
    {
        return pageSourceProvider;
    }

    @Override
    public ConnectorHandleResolver getHandleResolver()
    {
        return handleResolver;
    }

    @Override
    public ConnectorMetadata getMetadata()
    {
        return metadata;
    }

    @Override
    public ConnectorSplitManager getSplitManager()
    {
        return splitManager;
    }

    @Override
    public ConnectorRecordSinkProvider getRecordSinkProvider()
    {
        return recordSinkProvider;
    }

    @Override
    public ConnectorRecordSetProvider getRecordSetProvider()
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public ConnectorIndexResolver getIndexResolver()
    {
        throw new UnsupportedOperationException();
    }
}


text:
#ifndef ART_RUNTIME_ARCH_ARM_QUICK_METHOD_FRAME_INFO_ARM_H_
#define ART_RUNTIME_ARCH_ARM_QUICK_METHOD_FRAME_INFO_ARM_H_

#include "base/bit_utils.h"
#include "quick/quick_method_frame_info.h"
#include "registers_arm.h"
#include "runtime.h"  // for Runtime::CalleeSaveType.

namespace art {
namespace arm {

static constexpr uint32_t kArmCalleeSaveAlwaysSpills =
    (1 << art::arm::LR);
static constexpr uint32_t kArmCalleeSaveRefSpills =
    (1 << art::arm::R5) | (1 << art::arm::R6)  | (1 << art::arm::R7) | (1 << art::arm::R8) |
    (1 << art::arm::R10) | (1 << art::arm::R11);
static constexpr uint32_t kArmCalleeSaveArgSpills =
    (1 << art::arm::R1) | (1 << art::arm::R2) | (1 << art::arm::R3);
static constexpr uint32_t kArmCalleeSaveAllSpills =
    (1 << art::arm::R4) | (1 << art::arm::R9);

static constexpr uint32_t kArmCalleeSaveFpAlwaysSpills = 0;
static constexpr uint32_t kArmCalleeSaveFpRefSpills = 0;
static constexpr uint32_t kArmCalleeSaveFpArgSpills =
    (1 << art::arm::S0)  | (1 << art::arm::S1)  | (1 << art::arm::S2)  | (1 << art::arm::S3)  |
    (1 << art::arm::S4)  | (1 << art::arm::S5)  | (1 << art::arm::S6)  | (1 << art::arm::S7)  |
    (1 << art::arm::S8)  | (1 << art::arm::S9)  | (1 << art::arm::S10) | (1 << art::arm::S11) |
    (1 << art::arm::S12) | (1 << art::arm::S13) | (1 << art::arm::S14) | (1 << art::arm::S15);
static constexpr uint32_t kArmCalleeSaveFpAllSpills =
    (1 << art::arm::S16) | (1 << art::arm::S17) | (1 << art::arm::S18) | (1 << art::arm::S19) |
    (1 << art::arm::S20) | (1 << art::arm::S21) | (1 << art::arm::S22) | (1 << art::arm::S23) |
    (1 << art::arm::S24) | (1 << art::arm::S25) | (1 << art::arm::S26) | (1 << art::arm::S27) |
    (1 << art::arm::S28) | (1 << art::arm::S29) | (1 << art::arm::S30) | (1 << art::arm::S31);

constexpr uint32_t ArmCalleeSaveCoreSpills(Runtime::CalleeSaveType type) {
  return kArmCalleeSaveAlwaysSpills | kArmCalleeSaveRefSpills |
      (type == Runtime::kRefsAndArgs ? kArmCalleeSaveArgSpills : 0) |
      (type == Runtime::kSaveAll ? kArmCalleeSaveAllSpills : 0);
}

constexpr uint32_t ArmCalleeSaveFpSpills(Runtime::CalleeSaveType type) {
  return kArmCalleeSaveFpAlwaysSpills | kArmCalleeSaveFpRefSpills |
      (type == Runtime::kRefsAndArgs ? kArmCalleeSaveFpArgSpills: 0) |
      (type == Runtime::kSaveAll ? kArmCalleeSaveFpAllSpills : 0);
}

constexpr uint32_t ArmCalleeSaveFrameSize(Runtime::CalleeSaveType type) {
  return RoundUp((POPCOUNT(ArmCalleeSaveCoreSpills(type)) /* gprs */ +
                  POPCOUNT(ArmCalleeSaveFpSpills(type)) /* fprs */ +
                  1 /* Method* */) * kArmPointerSize, kStackAlignment);
}

constexpr QuickMethodFrameInfo ArmCalleeSaveMethodFrameInfo(Runtime::CalleeSaveType type) {
  return QuickMethodFrameInfo(ArmCalleeSaveFrameSize(type),
                              ArmCalleeSaveCoreSpills(type),
                              ArmCalleeSaveFpSpills(type));
}

constexpr size_t ArmCalleeSaveFpr1Offset(Runtime::CalleeSaveType type) {
  return ArmCalleeSaveFrameSize(type) -
         (POPCOUNT(ArmCalleeSaveCoreSpills(type)) +
          POPCOUNT(ArmCalleeSaveFpSpills(type))) * kArmPointerSize;
}

constexpr size_t ArmCalleeSaveGpr1Offset(Runtime::CalleeSaveType type) {
  return ArmCalleeSaveFrameSize(type) -
         POPCOUNT(ArmCalleeSaveCoreSpills(type)) * kArmPointerSize;
}

constexpr size_t ArmCalleeSaveLrOffset(Runtime::CalleeSaveType type) {
  return ArmCalleeSaveFrameSize(type) -
      POPCOUNT(ArmCalleeSaveCoreSpills(type) & (-(1 << LR))) * kArmPointerSize;
}

}  // namespace arm
}  // namespace art

#endif  // ART_RUNTIME_ARCH_ARM_QUICK_METHOD_FRAME_INFO_ARM_H_


text:
#region Copyright (c) 2013 Jens Thiel, http://thielj.github.io/MetroFramework

#endregion

using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;

using MetroFramework.Drawing;

namespace MetroFramework.Controls
{
    [Designer("MetroFramework.Design.MetroLabelDesigner, " + AssemblyRef.MetroFrameworkDesignSN)]
    [ToolboxBitmap(typeof(Label))]
    public partial class MetroLabel : MetroLabelBase
    {
        public MetroLabel()
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
            UseTransparency();
            UseStyleColor();
            UseFontStyle();
        }

        protected override void OnPaintForeground(PaintEventArgs e)
        {
            TextRenderer.DrawText(e.Graphics, Text, EffectiveFont, ClientRectangle, EffectiveForeColor, TextAlign.AsTextFormatFlags() | TextFormatFlags.EndEllipsis);
        }

        public override Size GetPreferredSize(Size proposedSize)
        {
            using (var g = CreateGraphics())
            {
                proposedSize = new Size(int.MaxValue, int.MaxValue);
                return TextRenderer.MeasureText(g, Text, EffectiveFont, proposedSize, TextAlign.AsTextFormatFlags() | TextFormatFlags.EndEllipsis);
            }
        }
    }
}


text:
package com.opensource.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.DisplayMetrics;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class CustomDialog extends Dialog {

	/**
	 * The identifier for the close button.
	 */
	public static final int BUTTON_CLOSE = -4;

	private RelativeLayout mRlTitle = null;

	private FrameLayout mFlBody = null;

	private LinearLayout mLlFoot = null;

	private ImageView mIvIcon = null;

	private TextView mTvTitle = null;

	private Button mBtnClose = null;

	private TextView mTvMessage = null;

	private EditText mEtInput = null;

	private ListView mListView = null;

	private Button mBtnPositive = null;

	private Button mBtnNegative = null;

	private OnClickListener mColseClickListener = null;

	private OnClickListener mPositiveClickListener = null;

	private OnClickListener mNegativeClickListener = null;

	private OnClickListener mItemClickListener = null;

	private OnMultiChoiceClickListener mMultiChoiceClickListener = null;

	public CustomDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
		super(context, cancelable, cancelListener);
		init(context);
	}

	public CustomDialog(Context context, int theme) {
		super(context, theme);
		init(context);
	}

	public CustomDialog(Context context) {
		this(context, R.style.CustomDialogTheme);
	}

	private void init(Context context) {
		setContentView(R.layout.layout_dialog);

		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		LayoutParams lp = getWindow().getAttributes();
		lp.width = dm.widthPixels * 7 / 8;
		lp.height = LayoutParams.WRAP_CONTENT;
		lp.gravity = Gravity.CENTER;
		getWindow().setAttributes(lp);

		initView();
	}

	private void initView() {
		mRlTitle = (RelativeLayout) findViewById(R.id.rl_dialog_title);
		mFlBody = (FrameLayout) findViewById(R.id.fl_dialog_body);
		mLlFoot = (LinearLayout) findViewById(R.id.ll_dialog_foot);

		mIvIcon = (ImageView) findViewById(R.id.iv_dialog_icon);
		mTvTitle = (TextView) findViewById(R.id.tv_dialog_title);
		mBtnClose = (Button) findViewById(R.id.btn_dialog_close);
		mTvMessage = (TextView) findViewById(R.id.tv_dialog_message);
		mEtInput = (EditText) findViewById(R.id.tv_dialog_input);
		mListView = (ListView) findViewById(R.id.lv_dialog_items);
		mBtnPositive = (Button) findViewById(R.id.btn_dialog_positive);
		mBtnNegative = (Button) findViewById(R.id.btn_dialog_negative);
	}

	/**
	 * Set dialog icon.
	 * @param resId
	 * @return
	 */
	public CustomDialog setIcon(int resId) {
		if(resId != 0) {
			mIvIcon.setVisibility(View.VISIBLE);
			mIvIcon.setImageResource(resId);
			mTvTitle.setGravity(Gravity.LEFT);
		}
		return this;
	}

	@Override
	public void setTitle(CharSequence title) {
		setTitleText(title);
	}

	@Override
	public void setTitle(int titleId) {
		setTitleText(titleId);
	}

	/**
	 * Set dialog title text.
	 * @param resId
	 * @return
	 */
	public CustomDialog setTitleText(int resId) {
		if(resId != 0) {
			mTvTitle.setVisibility(View.VISIBLE);
			mTvTitle.setText(resId);
		}
		return this;
	}

	/**
	 * Set dialog title text.
	 * @param text
	 * @return
	 */
	public CustomDialog setTitleText(CharSequence text) {
		if(text != null) {
			mTvTitle.setVisibility(View.VISIBLE);
			mTvTitle.setText(text);
		}
		return this;
	}

	/**
	 * Set dialog title text gravity.
	 * Note:If the icon has been set, title text always Gravity.LEFT.
	 * @param gravity
	 * @return
	 */
	public CustomDialog setTitleTextGravity(int gravity) {
		mTvTitle.setGravity(mIvIcon.getVisibility() == View.VISIBLE ? Gravity.LEFT : gravity);
		return this;
	}

	/**
	 * Set close button.
	 * @param resid
	 * @param listener
	 * @return
	 */
	public CustomDialog setCloseButton(int resid, OnClickListener listener) {
		mBtnClose.setVisibility(View.VISIBLE);
		mBtnClose.setBackgroundResource(resid);
		this.mColseClickListener = listener;
		mBtnClose.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mColseClickListener != null) {
					mColseClickListener.onClick(CustomDialog.this, BUTTON_CLOSE);
				}
			}
		});
		return this;
	}

	/**
	 * Set close button, with default listener
	 * @param resid
	 * @return
	 */
	public CustomDialog setCloseButton(int resid) {
		return setCloseButton(resid, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
	}

	/**
	 * Set dialog message text.
	 * @param resId
	 * @return
	 */
	public CustomDialog setMessage(int resId) {
		if(resId != 0) {
			mFlBody.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
			mTvMessage.setVisibility(View.VISIBLE);
			mTvMessage.setText(resId);
		}
		return this;
	}

	/**
	 * Set dialog message text.
	 * @param message
	 * @return
	 */
	public CustomDialog setMessage(CharSequence message) {
		if(message != null) {
			mFlBody.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
			mTvMessage.setVisibility(View.VISIBLE);
			mTvMessage.setText(message);
		}
		return this;
	}
	/**
	 * Set dialog input.
	 * @param hint
	 * @return
	 */
	public CustomDialog setInput(CharSequence hint) {
		mFlBody.setVisibility(View.VISIBLE);
		mListView.setVisibility(View.GONE);
		mEtInput.setVisibility(View.VISIBLE);
		mEtInput.setText("");
		if(hint != null) {
			mEtInput.setHint(hint);
		}
		return this;
	}

	/**
	 * @param hintRes
	 * Set dialog input.
	 * @return
	 */
	public CustomDialog setInput(int hintRes) {
		mFlBody.setVisibility(View.VISIBLE);
		mListView.setVisibility(View.GONE);
		mEtInput.setVisibility(View.VISIBLE);
		mEtInput.setText("");
		if(hintRes > 0) {
			mEtInput.setHint(hintRes);
		}
		return this;
	}

	/**
	 * Get dialog input text.
	 * @return The text in input EditText, but null text when input EditText is not visibility.
	 */
	public CharSequence getInputText() {
		if(mEtInput.getVisibility() == View.VISIBLE) {
			return mEtInput.getText();
		}
		return "";
	}

	/**
	 * Set dialog input text. If input EditText dose not visibility, it would't set.
	 * @param text
	 */
	public void setInputText(CharSequence text) {
		if(mEtInput.getVisibility() == View.VISIBLE) {
			mEtInput.setText(text);
		}
	}

	/**
	 * Set dialog input text. If input EditText dose not visibility, it would't set.
	 * @param resId
	 */
	public void setInputText(int resId) {
		if(mEtInput.getVisibility() == View.VISIBLE) {
			mEtInput.setText(resId);
		}
	}

	/**
	 * Set positive button text and listener.
	 * @param resId
	 * @param listener
	 * @return
	 */
	public CustomDialog setPositiveButton(int resId, OnClickListener listener) {
		mBtnPositive.setVisibility(View.VISIBLE);
		mBtnPositive.setText(resId);
		mPositiveClickListener = listener;
		mBtnPositive.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mPositiveClickListener != null) {
					mPositiveClickListener.onClick(CustomDialog.this, DialogInterface.BUTTON_POSITIVE);
				}
			}
		});
		layoutButtons();
		return this;
	}

	/**
	 * Set positive button text and listener.
	 * @param text
	 * @param listener
	 * @return
	 */
	public CustomDialog setPositiveButton(CharSequence text, OnClickListener listener) {
		mBtnPositive.setVisibility(View.VISIBLE);
		mBtnPositive.setText(text);
		mPositiveClickListener = listener;
		mBtnPositive.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mPositiveClickListener != null) {
					mPositiveClickListener.onClick(CustomDialog.this, DialogInterface.BUTTON_POSITIVE);
				}
			}
		});
		layoutButtons();
		return this;
	}

	/**
	 * Set negative button text and listener.
	 * @param resId
	 * @param listener
	 * @return
	 */
	public CustomDialog setNegativeButton(int resId, OnClickListener listener) {
		mBtnNegative.setVisibility(View.VISIBLE);
		mBtnNegative.setText(resId);
		mNegativeClickListener = listener;
		mBtnNegative.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mNegativeClickListener != null) {
					mNegativeClickListener.onClick(CustomDialog.this, DialogInterface.BUTTON_NEGATIVE);
				}
			}
		});
		layoutButtons();
		return this;
	}

	/**
	 * Set negative button text and listener.
	 * @param text
	 * @param listener
	 * @return
	 */
	public CustomDialog setNegativeButton(CharSequence text, OnClickListener listener) {
		mBtnNegative.setVisibility(View.VISIBLE);
		mBtnNegative.setText(text);
		mNegativeClickListener = listener;
		mBtnNegative.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mNegativeClickListener != null) {
					mNegativeClickListener.onClick(CustomDialog.this, DialogInterface.BUTTON_NEGATIVE);
				}
			}
		});
		layoutButtons();
		return this;
	}

	/**
	 * ReLayout the buttons according to the their visibility.
	 */
	private void layoutButtons() {
		int windowWidth = getWindow().getAttributes().width;
		if(mBtnPositive.getVisibility() == View.VISIBLE && mBtnNegative.getVisibility() != View.VISIBLE) {
			LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mBtnPositive.getLayoutParams();
			lp.leftMargin = windowWidth / 6;
			lp.rightMargin = windowWidth / 6;
			mBtnPositive.setLayoutParams(lp);
		} else if(mBtnPositive.getVisibility() != View.VISIBLE && mBtnNegative.getVisibility() == View.VISIBLE) {
			LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mBtnNegative.getLayoutParams();
			lp.leftMargin = windowWidth / 6;
			lp.rightMargin = windowWidth / 6;
			mBtnNegative.setLayoutParams(lp);
		} else if(mBtnPositive.getVisibility() == View.VISIBLE && mBtnNegative.getVisibility() == View.VISIBLE) {
			LinearLayout.LayoutParams positiveLp = (LinearLayout.LayoutParams) mBtnPositive.getLayoutParams();
			positiveLp.rightMargin = 0;
			positiveLp.leftMargin = getContext().getResources().getDimensionPixelSize(R.dimen.custom_dialog_button_margin);
			mBtnPositive.setLayoutParams(positiveLp);
			LinearLayout.LayoutParams negativeLp = (LinearLayout.LayoutParams) mBtnNegative.getLayoutParams();
			negativeLp.leftMargin = 0;
			negativeLp.rightMargin = getContext().getResources().getDimensionPixelSize(R.dimen.custom_dialog_button_margin);
			mBtnNegative.setLayoutParams(negativeLp);
		}
	}

	/**
	 * Set dialog items. with item icons.
	 * @param items Items array.
	 * @param icons Icons array.
	 * @param textGravity Item text align. Only effect when icons is null, others it would be Gravity.LEFT.
	 * @param listener
	 * @return
	 */
	public CustomDialog setItems(CharSequence [] items, int [] icons, int textGravity, OnClickListener listener) {
		this.mItemClickListener = listener;
		if(items != null && items.length > 0) {
			if(icons != null && icons.length != items.length) {
				throw new IllegalArgumentException("The items length dosen't equals to icons length.");
			}
			mFlBody.setVisibility(View.VISIBLE);
			mTvMessage.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
			mListView.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
			ItemsAdapter adapter = new ItemsAdapter(getContext(), icons, items, textGravity);
			mListView.setAdapter(adapter);
			mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					if(mItemClickListener != null) {
						mItemClickListener.onClick(CustomDialog.this, position);
					}
				}
			});
		}
		return this;
	}

	/**
	 * Set dialog items. with no item icons.
	 * @param items Items array.
	 * @param textGravity Item text align.
	 * @param listener
	 * @return
	 */
	public CustomDialog setItems(CharSequence [] items, int textGravity, OnClickListener listener) {
		return setItems(items, null, textGravity, listener);
	}

	/**
	 * Set dialog items. with item icons.
	 * @param items Items array.
	 * @param icons Icons array.
	 * @param listener
	 * @return
	 */
	public CustomDialog setItems(CharSequence [] items, int [] icons, OnClickListener listener) {
		return setItems(items, icons, Gravity.LEFT, listener);
	}

	/**
	 * Set dialog items, with no item icons.
	 * @param items
	 * @param listener
	 * @return
	 */
	public CustomDialog setItems(CharSequence [] items, OnClickListener listener) {
		return setItems(items, null, Gravity.LEFT, listener);
	}

	/**
	 * Set dialog single choice items, with item icons.
	 * @param items
	 * @param icons
	 * @param checkedItem The item which checked default.
	 * @param listener
	 * @return
	 */
	public CustomDialog setSingleChoiceItems(CharSequence [] items, int [] icons, int checkedItem, OnClickListener listener) {
		this.mItemClickListener = listener;
		if(items != null && items.length > 0) {
			if(icons != null && icons.length != items.length) {
				throw new IllegalArgumentException("The items length dosen't equals to icons length.");
			}
			mFlBody.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.VISIBLE);
			mTvMessage.setVisibility(View.GONE);
			SingleChoiceAdapter adapter = new SingleChoiceAdapter(getContext(), icons, items);
			mListView.setAdapter(adapter);
			mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			mListView.setItemChecked(checkedItem, true);
			mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					if(mItemClickListener != null) {
						mItemClickListener.onClick(CustomDialog.this, position);
					}
				}
			});
		}
		return this;
	}

	/**
	 * Set dialog single choice item, with no item icons.
	 * @param items
	 * @param checkedItem
	 * @param listener
	 * @return
	 */
	public CustomDialog setSingleChoiceItems(CharSequence [] items, int checkedItem, OnClickListener listener) {
		return setSingleChoiceItems(items, null, checkedItem, listener);
	}

	/**
	 * Set dialog single choice item, with no item icons, the string and icons get from resources.
	 * @param textResId
	 * @param checkedItem
	 * @param listener
	 * @return
	 */
	public CustomDialog setSingleChoiceItems(int textResId, int checkedItem, OnClickListener listener) {
		CharSequence [] items = getContext().getResources().getStringArray(textResId);
		return setSingleChoiceItems(items, null, checkedItem, listener);
	}

	/**
	 * Returns the currently checked item.
	 * Note: The result is only valid if the items is {@link CustomDialog#setSingleChoiceItems(CharSequence[], int, android.content.DialogInterface.OnClickListener)}(include all of method named setSingleChoiceItems())
	 * @return The position of the currently checked item or INVALID_POSITION if nothing is selected
	 */
	public int getCheckedPosition() {
		if(mListView.getChoiceMode() == AbsListView.CHOICE_MODE_SINGLE) {
			return mListView.getCheckedItemPosition();
		}
		return AbsListView.INVALID_POSITION;
	}

	/**
	 * Set dialog multiple choice items, with item icons.
	 * @param items
	 * @param icons
	 * @param checkedItems The item those checked default.
	 * @param listener
	 * @return
	 */
	public CustomDialog setMultiChoiceItems(CharSequence [] items, int [] icons, int [] checkedItems, OnMultiChoiceClickListener listener) {
		this.mMultiChoiceClickListener = listener;
		if(items != null && items.length > 0) {
			if(icons != null && icons.length != items.length) {
				throw new IllegalArgumentException("The length of items dosen't equals to icons'.");
			}
			if(checkedItems != null && checkedItems.length > items.length) {
				throw new IllegalArgumentException("The length of checkedItems should not larger then items'");
			}
			mFlBody.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.VISIBLE);
			mTvMessage.setVisibility(View.GONE);
			MuiltiChoiceAdapter adapter = new MuiltiChoiceAdapter(getContext(), icons, items);
			mListView.setAdapter(adapter);
			mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			if(checkedItems != null) {
				for (int i : checkedItems) {
					mListView.setItemChecked(i, true);
				}
			}
			mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					if(mMultiChoiceClickListener != null) {
						SparseBooleanArray array = mListView.getCheckedItemPositions();
						mMultiChoiceClickListener.onClick(CustomDialog.this, position, array.get(position, false));
					}
				}
			});
		}
		return this;
	}

	/**
	 * Set dialog multiple choice item, with no item icons.
	 * @param items
	 * @param checkedItems
	 * @param listener
	 * @return
	 */
	public CustomDialog setMultiChoiceItems(CharSequence [] items, int [] checkedItems, OnMultiChoiceClickListener listener) {
		return setMultiChoiceItems(items, null, checkedItems, listener);
	}

	/**
	 * Set dialog multiple choice item, with no item icons, the string and icons get from resources.
	 * @param textResId
	 * @param checkedItems
	 * @param listener
	 * @return
	 */
	public CustomDialog setMultiChoiceItems(int textResId, int [] checkedItems, OnMultiChoiceClickListener listener) {
		CharSequence [] items = getContext().getResources().getStringArray(textResId);
		return setMultiChoiceItems(items, null, checkedItems, listener);
	}

	/**
	 * Set title background resource
	 * @param resid
	 * @return
	 */
	public CustomDialog setTitleBackgroundResource(int resid) {
		mRlTitle.setBackgroundResource(resid);
		return this;
	}

	/**
	 * Set title background color
	 * @param color
	 * @return
	 */
	public CustomDialog setTitleBackgroudColor(int color) {
		mRlTitle.setBackgroundColor(color);
		return this;
	}

	/**
	 * Set content background resource
	 * @param resid
	 * @return
	 */
	public CustomDialog setContentBackgroundResource(int resid) {
		mFlBody.setBackgroundResource(resid);
		return this;
	}

	/**
	 * Set content background color
	 * @param color
	 * @return
	 */
	public CustomDialog setContentBackgroudColor(int color) {
		mFlBody.setBackgroundColor(color);
		return this;
	}

	/**
	 * Set foot background resource
	 * @param resid
	 * @return
	 */
	public CustomDialog setFootBackgroundResource(int resid) {
		mLlFoot.setBackgroundResource(resid);
		return this;
	}

	/**
	 * Set foot background color
	 * @param color
	 * @return
	 */
	public CustomDialog setFootBackgroudColor(int color) {
		mLlFoot.setBackgroundColor(color);
		return this;
	}

	/**
	 * Set background resources.
	 * @param title
	 * @param content
	 * @param foot
	 * @return
	 */
	public CustomDialog setBackgroudResources(int title, int content, int foot) {
		mRlTitle.setBackgroundResource(title);
		mFlBody.setBackgroundResource(content);
		mLlFoot.setBackgroundResource(foot);
		return this;
	}

	/**
	 * Set Background colors.
	 * @param title
	 * @param content
	 * @param foot
	 * @return
	 */
	public CustomDialog setBackgroudColors(int title, int content, int foot) {
		mRlTitle.setBackgroundColor(title);
		mFlBody.setBackgroundColor(content);
		mLlFoot.setBackgroundColor(foot);
		return this;
	}

	/**
	 * Set title default text color.
	 * @param color value -1 to use default color.
	 * @return
	 */
	public CustomDialog setTitleTextColor(int color) {
		if(color > -1) {
			mTvTitle.setTextColor(color);
		}
		return this;
	}

	/**
	 * Set title default text size
	 * @param size value 0 to use default size.
	 * @return
	 */
	public CustomDialog setTitleTextSize(float size) {
		if(size > 0) {
			mTvTitle.setTextSize(size);
		}
		return this;
	}

	/**
	 * Set the title default text size to a given unit and value. <br>
	 * See {@link android.util.TypedValue} for the possible dimension units.
	 * @param size
	 * @return
	 */
	public CustomDialog setTitleTextSize(int unit, float size) {
		if(size > 0) {
			mTvTitle.setTextSize(unit, size);;
		}
		return this;
	}

	/**
	 * Set message default text color
	 * @param color, value -1 to use default color.
	 * @return
	 */
	public CustomDialog setMessageTextColor(int color) {
		if(color > -1) {
			mTvMessage.setTextColor(color);
		}
		return this;
	}

	/**
	 * Set message text default size
	 * @param size value 0 to use default size.
	 * @return
	 */
	public CustomDialog setMessageTextSize(float size) {
		if(size > 0) {
			mTvMessage.setTextSize(size);
		}
		return this;
	}

	/**
	 * Set the message default text size to a given unit and value. <br>
	 * See {@link android.util.TypedValue} for the possible dimension units.
	 * @param size
	 * @return
	 */
	public CustomDialog setMessageTextSize(int unit, float size) {
		if(size > 0) {
			mTvMessage.setTextSize(unit, size);;
		}
		return this;
	}

	/**
	 * Set the title default text style<br>
	 * <p>the text size to a given unit and value. See {@link android.util.TypedValue} for the possible dimension units.
	 * @param textColor text color, value -1 to user default.
	 * @param unit
	 * @param textSize value 0 to use default size.
	 * @return
	 */
	public CustomDialog setTitleStyle(int textColor, int unit, float textSize) {
		if(textColor > -1) {
			mTvTitle.setTextColor(textColor);
		}
		if(textSize > 0) {
			mTvTitle.setTextSize(unit, textSize);
		}
		return this;
	}

	/**
	 * Set the title default text style<br>
	 * <p>the text size to a given unit and value. See {@link android.util.TypedValue} for the possible dimension units.
	 * @param textColor value -1 to use default color
	 * @param unit
	 * @param textSize value 0 to use default size.
	 * @return
	 */
	public CustomDialog setMessageStyle(int textColor, int unit, float textSize) {
		if(textColor > -1) {
			mTvMessage.setTextColor(textColor);
		}
		if(textSize > 0) {
			mTvMessage.setTextSize(unit, textSize);
		}
		return this;
	}

	/**
	 * Set positive button style
	 * @param bgRes background resource. value 0 to use default backgroud
	 * @param textColor value -1 to use default color
	 * @param unit
	 * @param textSize value 0 to use default size.
	 * @return
	 */
	public CustomDialog setPositiveButtonStyle(int bgRes, int textColor, int unit, float textSize) {
		if(bgRes > 0) {
			mBtnPositive.setBackgroundResource(bgRes);
		}
		if(textColor > -1) {
			mBtnPositive.setTextColor(textColor);
		}
		if(textSize > 0) {
			mBtnPositive.setTextSize(unit, textSize);
		}
		return this;
	}

	/**
	 * Set negative button style
	 * @param bgRes background resource. value 0 to use default backgroud
	 * @param textColor value -1 to use default color
	 * @param unit
	 * @param textSize value 0 to use default size.
	 * @return
	 */
	public CustomDialog setnNegativeButtonStyle(int bgRes, int textColor, int unit, float textSize) {
		if(bgRes > 0) {
			mBtnNegative.setBackgroundResource(bgRes);
		}
		if(textColor > -1) {
			mBtnNegative.setTextColor(textColor);
		}
		if(textSize > 0) {
			mBtnNegative.setTextSize(unit, textSize);
		}
		return this;
	}

	/**
	 * Set close button backgroud resource
	 * @param resid
	 * @return
	 */
	public CustomDialog setCloseButtonBackgroud(int resid) {
		mBtnClose.setBackgroundResource(resid);
		return this;
	}

	/**
	 * Set custom view to the custom dialog.
	 * @param view
	 * @return
	 */
	public CustomDialog setCustomView(View view) {
		mTvMessage.setVisibility(View.GONE);
		mEtInput.setVisibility(View.GONE);
		mListView.setVisibility(View.GONE);
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
				FrameLayout.LayoutParams.MATCH_PARENT);
		mFlBody.addView(view, lp);
		mFlBody.bringChildToFront(view);
		return this;
	}

	/**
	 * Returns the currently checked items.
	 * Note: The result is only valid if the items is {@link CustomDialog#setMultiChoiceItems(CharSequence[], int[], android.content.DialogInterface.OnMultiChoiceClickListener)}(include all of method named setMultiChoiceItems())
	 * @return The position of the currently checked item or null if items are not multiple choice.
	 */
	public SparseBooleanArray getCheckedItemPositions() {
		return mListView.getCheckedItemPositions();
	}

	/**
	 * Adapter for simple item view.
	 * @author xiaoying
	 *
	 */
	private class ItemsAdapter extends BaseAdapter {

		private Context mmContext = null;
		private int [] mmIcons = null;
		private CharSequence [] mmItems = null;
		private int mmTextGravity = Gravity.LEFT;

		public ItemsAdapter(Context context, int [] icons, CharSequence [] items, int gravity) {
			this.mmContext = context;
			this.mmIcons = icons;
			this.mmItems = items;
			this.mmTextGravity = icons == null ? gravity : Gravity.LEFT;
		}

		@Override
		public int getCount() {
			return mmItems.length;
		}

		@Override
		public CharSequence getItem(int position) {
			return mmItems[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if(convertView == null) {
				viewHolder = new ViewHolder();
				convertView = View.inflate(mmContext, R.layout.item_dialog, null);
				viewHolder.icon = (ImageView) convertView.findViewById(R.id.iv_item_dialog_icon);
				viewHolder.text = (TextView) convertView.findViewById(R.id.tv_item_dialog_text);
				viewHolder.icon.setVisibility(mmIcons == null ? View.GONE : View.VISIBLE);
				viewHolder.text.setGravity(mmTextGravity);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			if(mmIcons != null) {
				viewHolder.icon.setImageResource(mmIcons[position]);
			}
			viewHolder.text.setText(mmItems[position]);
			return convertView;
		}

		private class ViewHolder {
			ImageView icon;
			TextView text;
		}

	}

	/**
	 * Adapter for single choice item view.
	 * @author xiaoying
	 *
	 */
	private class SingleChoiceAdapter extends BaseAdapter {
		private Context mmContext = null;
		private int [] mmIcons = null;
		private CharSequence [] mmItems = null;

		public SingleChoiceAdapter(Context context, int [] icons, CharSequence [] items) {
			this.mmContext = context;
			this.mmIcons = icons;
			this.mmItems = items;
		}

		@Override
		public int getCount() {
			return mmItems.length;
		}

		@Override
		public CharSequence getItem(int position) {
			return mmItems[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			SingleChoiceItem item = null;
			if(convertView == null) {
				item = new SingleChoiceItem(mmContext);
				if(mmIcons == null) {
					item.setIconVisibility(View.GONE);
				}
				convertView = item;
			} else {
				item = (SingleChoiceItem) convertView;
			}
			if(mmIcons != null) {
				item.setIcon(mmIcons[position]);
			}
			item.setText(mmItems[position]);
			return convertView;
		}
	}

	/**
	 * Adapter for multiple choice item view.
	 * @author xiaoying
	 *
	 */
	private class MuiltiChoiceAdapter extends BaseAdapter {
		private Context mmContext = null;
		private int [] mmIcons = null;
		private CharSequence [] mmItems = null;

		public MuiltiChoiceAdapter(Context context, int [] icons, CharSequence [] items) {
			this.mmContext = context;
			this.mmIcons = icons;
			this.mmItems = items;
		}

		@Override
		public int getCount() {
			return mmItems.length;
		}

		@Override
		public CharSequence getItem(int position) {
			return mmItems[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			MultiChoiceItem item = null;
			if(convertView == null) {
				item = new MultiChoiceItem(mmContext);
				if(mmIcons == null) {
					item.setIconVisibility(View.GONE);
				}
				convertView = item;
			} else {
				item = (MultiChoiceItem) convertView;
			}
			if(mmIcons != null) {
				item.setIcon(mmIcons[position]);
			}
			item.setText(mmItems[position]);
			return convertView;
		}
	}
}


text:
<purl-config>
	<!--  TODO: Parameterize all server references -->
	<serverInfo>2.0; http://localhost:8080</serverInfo>
	$USERAUTOCREATION
	$TOPLEVELDOMAINAUTOCREATION
	<allowPublicDomains/>
	<publicDomains>
		<domain>/net</domain>
	</publicDomains>
	<adminUsers>
		<user>admin</user>
	</adminUsers>
	<goneURIs>
		<gone-uri type="404">ffcpl:/pub/404-gone.html</gone-uri>
		<gone-uri type="410">ffcpl:/pub/410-gone.html</gone-uri>
	</goneURIs>
	<invalidPURLURI>ffcpl:/pub/invalid-purl.html</invalidPURLURI>
	<errorResolvingPURL>ffcpl:/pub/error-resolving-purl.html</errorResolvingPURL>
	<dateFormat>yyyy/MM/dd HH:mm:ss</dateFormat>
	<!-- Do we still need this?? -->
	<topLevelRedirects>
	<!-- 		<redirect from="ffcpl:/metadata" to="ffcpl:/static/metadata"/>-->
	</topLevelRedirects>
</purl-config>


text:
<#
    .SYNOPSIS
        Tests if the current machine is a Nano server.
#>
function Test-IsNanoServer
{
    [OutputType([Boolean])]
    [CmdletBinding()]
    param ()

    $isNanoServer = $false

    if (Test-CommandExists -Name 'Get-ComputerInfo')
    {
        $computerInfo = Get-ComputerInfo -ErrorAction 'SilentlyContinue'

        if ($null -ne $computerInfo)
        {
            $computerIsServer = 'Server' -ieq $computerInfo.OsProductType

            if ($computerIsServer)
            {
                $isNanoServer = 'NanoServer' -ieq $computerInfo.OsServerLevel
            }
        }
    }

    return $isNanoServer
}

<#
    .SYNOPSIS
        Tests whether or not the command with the specified name exists.

    .PARAMETER Name
        The name of the command to test for.
#>
function Test-CommandExists
{
    [OutputType([Boolean])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String] $Name
    )

    $command = Get-Command -Name $Name -ErrorAction 'SilentlyContinue'
    return ($null -ne $command)
}

<#
    .SYNOPSIS
        Creates and throws an invalid argument exception

    .PARAMETER Message
        The message explaining why this error is being thrown

    .PARAMETER ArgumentName
        The name of the invalid argument that is causing this error to be thrown
#>
function New-InvalidArgumentException
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Message,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ArgumentName
    )

    $argumentException = New-Object -TypeName 'ArgumentException' `
                                    -ArgumentList @($Message, $ArgumentName)
    $newObjectParams = @{
        TypeName = 'System.Management.Automation.ErrorRecord'
        ArgumentList = @($argumentException, $ArgumentName, 'InvalidArgument', $null)
    }
    $errorRecord = New-Object @newObjectParams

    throw $errorRecord
}

<#
    .SYNOPSIS
        Creates and throws an invalid operation exception

    .PARAMETER Message
        The message explaining why this error is being thrown

    .PARAMETER ErrorRecord
        The error record containing the exception that is causing this terminating error
#>
function New-InvalidOperationException
{
    [CmdletBinding()]
    param
    (
        [ValidateNotNullOrEmpty()]
        [String]
        $Message,

        [ValidateNotNull()]
        [System.Management.Automation.ErrorRecord]
        $ErrorRecord
    )

    if ($null -eq $Message)
    {
        $invalidOperationException = New-Object -TypeName 'InvalidOperationException'
    }
    elseif ($null -eq $ErrorRecord)
    {
        $invalidOperationException = New-Object -TypeName 'InvalidOperationException' `
                                                -ArgumentList @($Message)
    }
    else
    {
        $invalidOperationException = New-Object -TypeName 'InvalidOperationException' `
                                                -ArgumentList @($Message, $ErrorRecord.Exception)
    }

    $newObjectParams = @{
        TypeName = 'System.Management.Automation.ErrorRecord'
        ArgumentList = @( $invalidOperationException.ToString(), 'MachineStateIncorrect',
                          'InvalidOperation', $null )
    }

    $errorRecordToThrow = New-Object @newObjectParams
    throw $errorRecordToThrow
}

<#
    .SYNOPSIS
        Retrieves the localized string data based on the machine's culture.
        Falls back to en-US strings if the machine's culture is not supported.

    .PARAMETER ResourceName
        The name of the resource as it appears before '.strings.psd1' of the localized string file.
        For example:
            For WindowsOptionalFeature: MSFT_WindowsOptionalFeature
            For Service: MSFT_ServiceResource
            For Registry: MSFT_RegistryResource
#>
function Get-LocalizedData
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ResourceName
    )

    $resourceDirectory = Join-Path -Path $PSScriptRoot -ChildPath $ResourceName
    $localizedStringFileLocation = Join-Path -Path $resourceDirectory -ChildPath $PSUICulture

    if (-not (Test-Path -Path $localizedStringFileLocation))
    {
        # Fallback to en-US
        $localizedStringFileLocation = Join-Path -Path $resourceDirectory -ChildPath 'en-US'
    }

    Import-LocalizedData `
        -BindingVariable 'localizedData' `
        -FileName "$ResourceName.strings.psd1" `
        -BaseDirectory $localizedStringFileLocation

    return $localizedData
}

Export-ModuleMember -Function @( 'Test-IsNanoServer', 'New-InvalidArgumentException',
    'New-InvalidOperationException', 'Get-LocalizedData' )


text:
"""
    Copyright (c) 2020 Ad Schellevis <ad@opnsense.org>
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
"""
import re
import datetime
from . import NewBaseLogFormat
squid_ext_timeformat = r'.*(\[\d{1,2}/[A-Za-z]{3}/\d{4}:\d{1,2}:\d{1,2}:\d{1,2} \+\d{4}\]).*'
squid_timeformat = r'^(\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}).*'

class SquidLogFormat(NewBaseLogFormat):
    def __init__(self, filename):
        super().__init__(filename)
        self._priority = 100

    def match(self, line):
        return self._filename.find('squid') > -1 and re.match(squid_timeformat, line) is not  None

    @property
    def timestamp(self):
        tmp = re.match(squid_timeformat, self._line)
        grp = tmp.group(1)
        return datetime.datetime.strptime(grp, "%Y/%m/%d %H:%M:%S").isoformat()

    @property
    def process_name(self):
        return "squid"

    @property
    def line(self):
        return self._line[19:].strip()

class SquidExtLogFormat(NewBaseLogFormat):
    def __init__(self, filename):
        super().__init__(filename)
        self._priority = 120

    def match(self, line):
        return self._filename.find('squid') > -1 and re.match(squid_ext_timeformat, line) is not  None

    @property
    def timestamp(self):
        tmp = re.match(squid_ext_timeformat, self._line)
        grp = tmp.group(1)
        return datetime.datetime.strptime(grp[1:].split()[0], "%d/%b/%Y:%H:%M:%S").isoformat()

    @property
    def process_name(self):
        return "squid"

    @property
    def line(self):
        tmp = re.match(squid_ext_timeformat, self._line)
        grp = tmp.group(1)
        return self._line.replace(grp, '')

class SquidJsonLogFormat(NewBaseLogFormat):
    def __init__(self, filename):
        super().__init__(filename)
        self._priority = 140
        local_now = datetime.datetime.now()
        utc_now = datetime.datetime.utcnow()
        self._localtimezone = datetime.timezone(local_now - utc_now)

    def match(self, line):
        return self._filename.find('squid') > -1 and line.find('"@timestamp"') > -1

    @property
    def timestamp(self, line):
        tmp = line[line.find('"@timestamp"')+13:].split(',')[0].strip().strip('"')
        try:
            return datetime.datetime.strptime(tmp, "%Y-%m-%dT%H:%M:%S%z")\
                    .astimezone(self._localtimezone).isoformat().split('.')[0].split('+')[0]
        except ValueError:
            return None

    @property
    def process_name(self):
        return "squid"

    @property
    def line(self):
        return self._line


text:
<?php

namespace app\models;

use yii\base\Model;

class FeedbackForm extends Model
{
	public $name = 'fuker';
	public $email;
	public $feedback;

	public function rules()
	{
		return
		[
			[['name','email','feedback-form'],'required'],
			['email','email']
		];
	}
}