text:
package org.ovirt.engine.ui.uicommonweb;

import org.ovirt.engine.core.common.businessentities.NetworkStatistics;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VdsNetworkInterface;
import org.ovirt.engine.core.common.businessentities.VdsNetworkStatistics;
import org.ovirt.engine.core.common.businessentities.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.VmNetworkStatistics;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.network;
import org.ovirt.engine.core.common.businessentities.storage_domain_static;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.common.businessentities.vm_pools;
import org.ovirt.engine.core.compat.NotImplementedException;
import org.ovirt.engine.core.compat.Version;

@SuppressWarnings("unused")
public final class Cloner
{
    public static Object clone(Object instance)
    {
        if (instance instanceof VM)
        {
            return CloneVM((VM) instance);
        }
        if (instance instanceof VDS)
        {
            return CloneVDS((VDS) instance);
        }
        if (instance instanceof VDSGroup)
        {
            return CloneVDSGroup((VDSGroup) instance);
        }
        if (instance instanceof storage_pool)
        {
            return CloneStorage_pool((storage_pool) instance);
        }
        if (instance instanceof network)
        {
            return CloneNetwork((network) instance);
        }
        if (instance instanceof vm_pools)
        {
            return CloneVmPool((vm_pools) instance);
        }
        if (instance instanceof storage_domain_static)
        {
            return CloneStorageDomainStatic((storage_domain_static) instance);
        }
        if (instance instanceof VmTemplate)
        {
            return CloneVmTemplate((VmTemplate) instance);
        }
        if (instance instanceof VmNetworkInterface)
        {
            return CloneVmNetworkInterface((VmNetworkInterface) instance);
        }
        if (instance instanceof VdsNetworkInterface)
        {
            return CloneVdsNetworkInterface((VdsNetworkInterface) instance);
        }
        if (instance instanceof VmStatic)
        {
            return CloneVmStatic((VmStatic) instance);
        }
        if (instance instanceof Version)
        {
            return CloneVersion((Version) instance);
        }

        // Throw exception to determine development needs.
        throw new NotImplementedException();
    }

    private static Object CloneVM(VM instance)
    {
        if (instance == null)
        {
            return null;
        }

        VM vm = new VM();

        vm.setacpi_enable(instance.getacpi_enable());
        // TODO: this field is read only in serialization - not sure why it is cloned
        // vm.ActualDiskWithSnapshotsSize = instance.ActualDiskWithSnapshotsSize;
        vm.setapp_list(instance.getapp_list());
        vm.setauto_startup(instance.getauto_startup());
        vm.setboot_sequence(instance.getboot_sequence());
        vm.setclient_ip(instance.getclient_ip());
        vm.setcpu_per_socket(instance.getcpu_per_socket());
        vm.setcpu_sys(instance.getcpu_sys());
        vm.setcpu_user(instance.getcpu_user());
        vm.setdedicated_vm_for_vds(instance.getdedicated_vm_for_vds());
        vm.setdefault_boot_sequence(instance.getdefault_boot_sequence());
        vm.setdefault_display_type(instance.getdefault_display_type());
        // TODO: 1. DiskList is an array - CopyTo should be considered (if it can be converted to java, otherwise a
        // simple loop is needed)
        // TODO: 2. it is also read only in serialization, so not sure why it is cloned. it is manipulated via
        // addDriveToImageMap
        // vm.DiskList = instance.DiskList;
        vm.setDiskSize(instance.getDiskSize());
        // TODO: this is also an object, so needs to be cloned as well. while it is only accessed via VM.DiskMap, which
        // creates a dictionary
        // from it - actually the DiskImage's themselves are probably sharing the same reference...
        vm.setDiskValueObjectMap(instance.getDiskValueObjectMap());
        vm.setdisplay(instance.getdisplay());
        vm.setdisplay_ip(instance.getdisplay_ip());
        vm.setdisplay_secure_port(instance.getdisplay_secure_port());
        vm.setdisplay_type(instance.getdisplay_type());
        vm.setelapsed_time(instance.getelapsed_time());
        vm.setRoundedElapsedTime(instance.getRoundedElapsedTime());
        vm.setExitMessage(instance.getExitMessage());
        vm.setExitStatus(instance.getExitStatus());
        vm.setfail_back(instance.getfail_back());
        vm.setguest_cur_user_id(instance.getguest_cur_user_id());
        vm.setguest_cur_user_name(instance.getguest_cur_user_name());
        vm.setguest_last_login_time(instance.getguest_last_login_time());
        vm.setguest_last_logout_time(instance.getguest_last_logout_time());
        vm.setguest_os(instance.getguest_os());
        vm.setguest_requested_memory(instance.getguest_requested_memory());
        // TODO: Object, should be "cloned" (probably easiest via new Version(instance.GuestAgentVersion.ToString())
        // pay attention NOT to use lower case version in UICommon code.
        vm.setGuestAgentVersion(instance.getGuestAgentVersion());
        vm.setinitrd_url(instance.getinitrd_url());
        // TODO: array - need to consider cloning of array, and of actual interfaces
        vm.setInterfaces(instance.getInterfaces());
        vm.setis_auto_suspend(instance.getis_auto_suspend());
        vm.setis_initialized(instance.getis_initialized());
        vm.setis_stateless(instance.getis_stateless());
        vm.setiso_path(instance.getiso_path());
        vm.setkernel_params(instance.getkernel_params());
        vm.setkernel_url(instance.getkernel_url());
        vm.setkvm_enable(instance.getkvm_enable());
        // TODO: Guid/NGuid is an object, but code should treat it as immutable, and not change it's uuid directly.
        // (quick skim of code shows this should be safe with current code)
        vm.setlast_vds_run_on(instance.getlast_vds_run_on());
        vm.setmigrating_to_vds(instance.getmigrating_to_vds());
        vm.setMigrationSupport(instance.getMigrationSupport());
        vm.setnice_level(instance.getnice_level());
        // TODO: this is readonly in java, since it is computed.
        // options: use calculation here in cloner, or still wrap this in VM instead of serializing it
        // vm.num_of_cpus = instance.num_of_cpus;
        vm.setnum_of_monitors(instance.getnum_of_monitors());
        vm.setnum_of_sockets(instance.getnum_of_sockets());
        vm.setorigin(instance.getorigin());
        vm.setVmPauseStatus(instance.getVmPauseStatus());
        vm.setpriority(instance.getpriority());
        vm.setrun_on_vds(instance.getrun_on_vds());
        vm.setrun_on_vds_name(instance.getrun_on_vds_name());
        vm.setsession(instance.getsession());
        // TODO: see version comment above
        vm.setSpiceDriverVersion(instance.getSpiceDriverVersion());
        vm.setstatus(instance.getstatus());
        vm.setstorage_pool_id(instance.getstorage_pool_id());
        vm.setstorage_pool_name(instance.getstorage_pool_name());
        vm.settime_zone(instance.gettime_zone());
        vm.setTransparentHugePages(instance.getTransparentHugePages());
        vm.setusage_cpu_percent(instance.getusage_cpu_percent());
        vm.setusage_mem_percent(instance.getusage_mem_percent());
        vm.setusage_network_percent(instance.getusage_network_percent());
        vm.setusb_policy(instance.getusb_policy());
        vm.setutc_diff(instance.getutc_diff());
        vm.setvds_group_compatibility_version(instance.getvds_group_compatibility_version());
        vm.setvds_group_id(instance.getvds_group_id());
        vm.setvds_group_name(instance.getvds_group_name());
        vm.setvm_creation_date(instance.getvm_creation_date());
        vm.setvm_description(instance.getvm_description());
        vm.setvm_domain(instance.getvm_domain());
        vm.setvm_guid(instance.getvm_guid());
        vm.setvm_host(instance.getvm_host());
        vm.setvm_ip(instance.getvm_ip());
        vm.setvm_last_boot_time(instance.getvm_last_boot_time());
        vm.setvm_last_up_time(instance.getvm_last_up_time());
        vm.setvm_mem_size_mb(instance.getvm_mem_size_mb());
        vm.setvm_name(instance.getvm_name());
        vm.setvm_os(instance.getvm_os());
        vm.setvm_pid(instance.getvm_pid());
        vm.setvm_type(instance.getvm_type());
        vm.setVmPoolId(instance.getVmPoolId());
        vm.setVmPoolName(instance.getVmPoolName());
        vm.setvmt_guid(instance.getvmt_guid());
        vm.setvmt_name(instance.getvmt_name());

        return vm;
    }

    private static Object CloneVersion(Version instance)
    {
        return new Version(instance.toString());
    }

    private static Object CloneVDS(VDS instance)
    {
        VDS obj = new VDS();

        obj.sethost_name(instance.gethost_name());
        obj.setManagmentIp(instance.getManagmentIp());
        obj.setpm_enabled(instance.getpm_enabled());
        obj.setPmOptionsMap(instance.getPmOptionsMap());
        obj.setpm_password(instance.getpm_password());
        obj.setpm_port(instance.getpm_port());
        obj.setpm_type(instance.getpm_type());
        obj.setpm_user(instance.getpm_user());
        obj.setport(instance.getport());
        obj.setserver_SSL_enabled(instance.getserver_SSL_enabled());
        obj.setvds_group_id(instance.getvds_group_id());
        obj.setvds_id(instance.getvds_id());
        obj.setvds_name(instance.getvds_name());
        obj.setvds_strength(instance.getvds_strength());
        obj.setvds_type(instance.getvds_type());
        obj.setUniqueId(instance.getUniqueId());

        return obj;
    }

    private static storage_pool CloneStorage_pool(storage_pool instance)
    {
        storage_pool obj = new storage_pool();

        obj.setdescription(instance.getdescription());
        obj.setId(instance.getId());
        obj.setname(instance.getname());
        obj.setstorage_pool_type(instance.getstorage_pool_type());
        obj.setstatus(instance.getstatus());

        obj.setmaster_domain_version(instance.getmaster_domain_version());
        obj.setLVER(instance.getLVER());
        obj.setrecovery_mode(instance.getrecovery_mode());
        obj.setspm_vds_id(instance.getspm_vds_id());
        obj.setcompatibility_version(instance.getcompatibility_version());

        return obj;
    }

    private static VDSGroup CloneVDSGroup(VDSGroup instance)
    {
        VDSGroup obj = new VDSGroup();
        obj.setID(instance.getID());
        obj.setname(instance.getname());
        obj.setdescription(instance.getdescription());
        obj.setcpu_name(instance.getcpu_name());

        obj.setselection_algorithm(instance.getselection_algorithm());
        obj.sethigh_utilization(instance.gethigh_utilization());
        obj.setlow_utilization(instance.getlow_utilization());
        obj.setcpu_over_commit_duration_minutes(instance.getcpu_over_commit_duration_minutes());
        obj.sethypervisor_type(instance.gethypervisor_type());
        obj.setcompatibility_version(instance.getcompatibility_version());
        obj.setMigrateOnError(instance.getMigrateOnError());
        obj.setTransparentHugepages(instance.getTransparentHugepages());

        obj.setstorage_pool_id(instance.getstorage_pool_id());
        obj.setmax_vds_memory_over_commit(instance.getmax_vds_memory_over_commit());

        return obj;
    }

    private static network CloneNetwork(network instance)
    {
        network obj = new network(null);

        obj.setaddr(instance.getaddr());
        obj.setdescription(instance.getdescription());
        obj.setId(instance.getId());
        obj.setname(instance.getname());
        obj.setsubnet(instance.getsubnet());
        obj.setgateway(instance.getgateway());
        obj.settype(instance.gettype());
        obj.setvlan_id(instance.getvlan_id());
        obj.setstp(instance.getstp());
        obj.setStatus(instance.getStatus());
        obj.setstorage_pool_id(instance.getstorage_pool_id());
        obj.setis_display(instance.getis_display());

        return obj;
    }

    private static vm_pools CloneVmPool(vm_pools instance)
    {
        vm_pools obj = new vm_pools();

        obj.setvm_pool_description(instance.getvm_pool_description());
        obj.setvm_pool_id(instance.getvm_pool_id());
        obj.setvm_pool_name(instance.getvm_pool_name());
        obj.setvm_pool_type(instance.getvm_pool_type());
        obj.setvds_group_id(instance.getvds_group_id());

        obj.setvm_pool_type(instance.getvm_pool_type());
        obj.setparameters(instance.getparameters());
        obj.setDefaultEndTime(instance.getDefaultEndTime());
        obj.setDefaultStartTime(instance.getDefaultStartTime());
        obj.setDefaultTimeInDays(instance.getDefaultTimeInDays());
        obj.setvds_group_name(instance.getvds_group_name());
        obj.setvm_assigned_count(instance.getvm_assigned_count());
        obj.setvm_pool_description(instance.getvm_pool_description());
        obj.setvm_running_count(instance.getvm_running_count());

        return obj;
    }

    private static storage_domain_static CloneStorageDomainStatic(storage_domain_static instance)
    {
        storage_domain_static obj = new storage_domain_static();
        obj.setConnection(instance.getConnection());
        obj.setId(instance.getId());
        obj.setstorage(instance.getstorage());
        obj.setstorage_domain_type(instance.getstorage_domain_type());
        obj.setstorage_type(instance.getstorage_type());
        obj.setstorage_name(instance.getstorage_name());
        obj.setStorageFormat(instance.getStorageFormat());

        return obj;
    }

    private static VmTemplate CloneVmTemplate(VmTemplate instance)
    {
        VmTemplate obj = new VmTemplate();
        obj.setstorage_pool_id(instance.getstorage_pool_id());
        obj.setstorage_pool_name(instance.getstorage_pool_name());
        obj.setdefault_display_type(instance.getdefault_display_type());
        obj.setpriority(instance.getpriority());
        obj.setiso_path(instance.getiso_path());
        obj.setorigin(instance.getorigin());
        obj.setSizeGB(instance.getSizeGB());
        // TODO: see comments above on DiskImageMap
        obj.setDiskImageMap(instance.getDiskImageMap());
        obj.setInterfaces(instance.getInterfaces());
        obj.setauto_startup(instance.getauto_startup());
        obj.setchild_count(instance.getchild_count());
        obj.setcpu_per_socket(instance.getcpu_per_socket());
        obj.setcreation_date(instance.getcreation_date());
        obj.setdefault_boot_sequence(instance.getdefault_boot_sequence());
        obj.setdescription(instance.getdescription());
        obj.setdomain(instance.getdomain());
        obj.setfail_back(instance.getfail_back());
        obj.sethypervisor_type(instance.gethypervisor_type());
        obj.setis_auto_suspend(instance.getis_auto_suspend());
        obj.setis_stateless(instance.getis_stateless());
        obj.setmem_size_mb(instance.getmem_size_mb());
        obj.setname(instance.getname());
        obj.setnice_level(instance.getnice_level());
        obj.setnum_of_monitors(instance.getnum_of_monitors());
        obj.setnum_of_sockets(instance.getnum_of_sockets());
        obj.setoperation_mode(instance.getoperation_mode());
        obj.setstatus(instance.getstatus());
        obj.settime_zone(instance.gettime_zone());
        obj.setusb_policy(instance.getusb_policy());
        obj.setvds_group_id(instance.getvds_group_id());
        obj.setvds_group_name(instance.getvds_group_name());
        obj.setvm_type(instance.getvm_type());
        obj.setId(instance.getId());

        return obj;
    }

    private static VmStatic CloneVmStatic(VmStatic instance)
    {
        VmStatic obj = new VmStatic();

        obj.setfail_back(instance.getfail_back());
        obj.setdefault_boot_sequence(instance.getdefault_boot_sequence());
        obj.setvm_type(instance.getvm_type());
        obj.setdefault_display_type(instance.getdefault_display_type());
        obj.setpriority(instance.getpriority());
        obj.setiso_path(instance.getiso_path());
        obj.setorigin(instance.getorigin());
        obj.setauto_startup(instance.getauto_startup());
        obj.setcpu_per_socket(instance.getcpu_per_socket());
        obj.setcreation_date(instance.getcreation_date());
        obj.setdedicated_vm_for_vds(instance.getdedicated_vm_for_vds());
        obj.setdescription(instance.getdescription());
        obj.setdomain(instance.getdomain());
        obj.setis_auto_suspend(instance.getis_auto_suspend());
        obj.setis_initialized(instance.getis_initialized());
        obj.setis_stateless(instance.getis_stateless());
        obj.setmem_size_mb(instance.getmem_size_mb());
        obj.setDiskSize(instance.getDiskSize());
        obj.setnice_level(instance.getnice_level());
        obj.setnum_of_monitors(instance.getnum_of_monitors());
        obj.setnum_of_sockets(instance.getnum_of_sockets());
        obj.settime_zone(instance.gettime_zone());
        obj.setusb_policy(instance.getusb_policy());
        obj.setvds_group_id(instance.getvds_group_id());
        obj.setId(instance.getId());
        obj.setvm_name(instance.getvm_name());
        obj.setvmt_guid(instance.getvmt_guid());

        return obj;
    }

    private static void CloneNetworkStatisticss(NetworkStatistics instance, NetworkStatistics obj)
    {
        obj.setId(instance.getId());
        obj.setReceiveDropRate(instance.getReceiveDropRate());
        obj.setReceiveRate(instance.getReceiveRate());
        obj.setTransmitDropRate(instance.getTransmitDropRate());
        obj.setTransmitRate(instance.getTransmitRate());
        obj.setStatus(instance.getStatus());
    }

    private static VdsNetworkStatistics CloneVdsNetworkStatistics(VdsNetworkStatistics instance)
    {
        VdsNetworkStatistics obj = new VdsNetworkStatistics();

        CloneNetworkStatisticss(instance, obj);
        obj.setVdsId(instance.getVdsId());

        return obj;
    }

    private static Object CloneVdsNetworkInterface(VdsNetworkInterface vdsNetworkInterface)
    {
        VdsNetworkInterface obj = new VdsNetworkInterface();

        obj.setAddress(vdsNetworkInterface.getAddress());
        obj.setBonded(vdsNetworkInterface.getBonded());
        obj.setBondName(vdsNetworkInterface.getBondName());
        obj.setBondOptions(vdsNetworkInterface.getBondOptions());
        obj.setBondType(vdsNetworkInterface.getBondType());
        obj.setBootProtocol(vdsNetworkInterface.getBootProtocol());
        obj.setGateway(vdsNetworkInterface.getGateway());
        obj.setId(vdsNetworkInterface.getId());
        obj.setMacAddress(vdsNetworkInterface.getMacAddress());
        obj.setName(vdsNetworkInterface.getName());
        obj.setNetworkName(vdsNetworkInterface.getNetworkName());
        obj.setSpeed(vdsNetworkInterface.getSpeed());
        obj.setStatistics(CloneVdsNetworkStatistics(vdsNetworkInterface.getStatistics()));

        return obj;
    }

    private static VmNetworkStatistics CloneVmNetworkStatistics(VmNetworkStatistics instance)
    {
        VmNetworkStatistics obj = new VmNetworkStatistics();

        CloneNetworkStatisticss(instance, obj);
        obj.setVmId(instance.getVmId());

        return obj;
    }

    private static Object CloneVmNetworkInterface(VmNetworkInterface vmNetworkInterface)
    {
        VmNetworkInterface obj = new VmNetworkInterface();
        obj.setId(vmNetworkInterface.getId());
        obj.setMacAddress(vmNetworkInterface.getMacAddress());
        obj.setName(vmNetworkInterface.getName());
        obj.setNetworkName(vmNetworkInterface.getNetworkName());
        obj.setSpeed(vmNetworkInterface.getSpeed());
        obj.setType(vmNetworkInterface.getType());
        obj.setVmId(vmNetworkInterface.getVmId());
        obj.setVmName(vmNetworkInterface.getVmName());
        obj.setVmTemplateId(vmNetworkInterface.getVmTemplateId());
        obj.setStatistics(CloneVmNetworkStatistics(vmNetworkInterface.getStatistics()));

        return obj;
    }
}


text:
package org.mrgeo.cmd;

import org.apache.commons.cli.*;

import java.util.Collection;

public class OptionsParser
{
  private final CommandLine line;

  public OptionsParser(final String[] args) throws ParseException
  {
    this(args, new Options());
  }

  public OptionsParser(final String[] args, final Options options) throws ParseException
  {
    final CommandLineParser parser = new GnuParser();

    // start with default options
    final Options allOptions = getOptions();

    // add any provided by user
    final Collection<Option> userOptions = (options.getOptions());
    for (final Option option : userOptions)
    {
      allOptions.addOption(option);
    }
    line = parser.parse(allOptions, args);
  }

  @SuppressWarnings("static-access")
  private static Options getOptions()
  {
    final Options options = new Options();
    options.addOption(OptionBuilder.withArgName("instance").hasArg().withDescription(
      "accumulo instance name").create("instance"));
    options.addOption(OptionBuilder.withArgName("zooservers").hasArg().withDescription(
      "comma separated list of server:port").create("zooservers"));
    options.addOption(OptionBuilder.withArgName("user").hasArg().withDescription(
      "accumulo user name").create("user"));
    options.addOption(OptionBuilder.withArgName("password").hasArg().withDescription(
      "accumulo password").create("password"));
    options.addOption(OptionBuilder.withArgName("table").hasArg()
      .withDescription("use given table").create("table"));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
      .withDescription("path to key file").create("keyfile"));
    options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription(
      "path to directory used to cache random key file").create("randomkeyfiledir"));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription(
      "number of scan threads").create("threads"));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of tiles")
      .create("tiles"));
    options.addOption(OptionBuilder.withArgName("tileid").hasArg().withDescription(
      "minimum tileId in range").create("mintile"));
    options.addOption(OptionBuilder.withArgName("tileid").hasArg().withDescription(
      "maximum tileId in range").create("maxtile"));
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription(
      "path to input pyramid").create("inputpyramid"));
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription(
      "path to output pyramid").create("outputpyramid"));
    options.addOption(OptionBuilder.withArgName("inputs").hasArg().withDescription(
      "list of input paths or tables").create("inputs"));
    options.addOption(OptionBuilder.withArgName("source").hasArg().withDescription(
      "accumulo, hdfs, or hdfs_old").create("datasource"));
    options.addOption(OptionBuilder.withArgName("zoomlevel").hasArg().withDescription("zoom level")
      .create("zoomlevel"));
    options.addOption(OptionBuilder.withArgName("workers").hasArg().withDescription(
      "number of giraph workers").create("workers"));
    options.addOption(OptionBuilder.withArgName("supersteps").hasArg().withDescription(
      "number of supersteps").create("supersteps"));
    options.addOption(OptionBuilder.withArgName("points").hasArg().withDescription(
      "comma-separated list of source points (e.g., \"(33.34,100.34),(30.39,90.34)\"").create(
      "sourcepoints"));
    options.addOption(OptionBuilder.withArgName("cost").hasArg().withDescription("maximum cost")
      .create("maxcost"));
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription(
      "Raster output by RasterizeVector").create("rvpyramid"));
    return options;
  }

  public String getOptionValue(final String option) throws ParseException
  {
    final String value = line.getOptionValue(option);
    if (value == null)
    {
      throw new ParseException("expected option \"" + option + "\" is missing");
    }
    return value;
  }

  public boolean isOptionProvided(final String option)
  {
    return ((line.getOptionValue(option) == null) ? false : true);
  }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'

import * as ChatActions from '../ChatActions'

import classnames from 'classnames'

import AsideChatUser from './AsideChatUser'

class AsideChatWidget extends React.Component {

  state = {
    open: false,
    filter: ''
  };

  componentWillMount() {}

  openToggle = (e) => {
    this.setState({
      open: !this.state.open
    });
    $(this.refs.chatUsersList).slideToggle();
    e.preventDefault()
  };

  onFilterChange = (value) =>{
    this.setState({
      filter: value
    })
  };

  render = ()=> {
    const users = this.props.chat.users || [];

    return (

          ! Smart Chat API beta

                <input className="form-control chat-user-filter"
                       placeholder="Filter" type="text"
                       value={this.state.filter}
                       onChange={event => this.onFilterChange(event.target.value) }/>

                  { users.filter( (user)  => {
                    const filter = this.state.filter.trim();
                    return !filter || user.username.toLowerCase().search(filter.toLowerCase()) > -1
                  }).map((user, idx) => {
                    return <AsideChatUser key={'aside-chat-user-' + idx} user={user}/>
                  }) }

    )
  }
}

export default connect(
  (state)=> {
    const {chat, user} = {...state};
    return {
      chat, user
    }
  },
  (dispatch) => {
    return bindActionCreators(ChatActions, dispatch)
  }
)(AsideChatWidget)


text:
<?php
$dir = dirname(__FILE__);$dir = dirname($dir.'../');$dir = dirname($dir.'../');$dir = dirname($dir.'../');$dir = dirname($dir.'../');
$dir = substr($dir, strlen($_SERVER['DOCUMENT_ROOT']));
$servername = str_replace('\\', '/', 'http://'.$_SERVER['SERVER_NAME'].'/'.$dir.'/');
?>

Database and Config Details

 Step 1

»

 Step 2

»

 Step 3

»

Step 4

»

 Step 5

<form id="form1" name="form1" method="post" enctype="multipart/form-data" action="index.php?c=install&m=step4">

Website Address

Enter your website address here.

						Make sure this is correct:

							Please make sure it starts with http:// This is the address of all your files EG: http://www.yoursite.com/upload

Trailing slash is required!

						<input class="required" type='text' size="45" name='url' value='<?php echo $servername;?>' />

Website Settings

This allows you to set custom cookie prefixes and a custom encryption key. Leave blank to autogenerate these values.

						Cookie Prefix

							This prevents session collisions with other XU installs around the internet

					<input type='text' size="45" name='cookie_prefix' />

						Encryption Key

							This is the key that will be used to encrypt sensitive data in XU

					<input type='text' size="45" name='encryption_key'/>

						SEO Urls

							Remove the index.php/ from generated urls, creating more SQO friendly links.

					<input type='checkbox' value='true' name='seo'/> Yes

SQL Data

Please enter the correct MySQL info below for the tables to install correctly.

			  SQL Host

Localhost is default, but in some cases it can be your Server IP Address

			  <input class="required" name="sql_server" type="text" id="sql_server" value="localhost" size="45" />

			  SQL User

			  <input class="required" name="sql_user" type="text" id="sql_user" size="45" />

			  SQL Database Name
			  <input class="required" name="sql_name" type="text" id="sql_database" size="45" />

			  SQL Password
			  <input name="sql_pass" type="password" id="sql_pass" size="45" />

			  Database Prefix
Optional

			  <input name="sql_prefix" type="text" id="sql_prefix" size="45" value="xu2_" />

			  SQL Engine

You can choose from 7 different SQL database engines. MySQL is the most popular.

				  <select name="sql_engine">
					<option selected="selected" value="mysql">MySQL</option>
					<option value="mysqli">MySQLi</option>
					<option value="mssql">MSSQL</option>
					<option value="postgre">Postgre SQL</option>
					<option value="oci8">OCI v8</option>
					<option value="odbc">ODBC</option>
					<option value="sqlite">SQLite</option>
				  </select>

							 Go Back

							 Continue

</form>


text:
IF(NOT DEFINED CMAKE_INSTALL_PREFIX)
  SET(CMAKE_INSTALL_PREFIX "/home/rafa/cws/install")
ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX)
STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")

# Set the install configuration name.
IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
  IF(BUILD_TYPE)
    STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
           CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
  ELSE(BUILD_TYPE)
    SET(CMAKE_INSTALL_CONFIG_NAME "")
  ENDIF(BUILD_TYPE)
  MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)

# Set the component getting installed.
IF(NOT CMAKE_INSTALL_COMPONENT)
  IF(COMPONENT)
    MESSAGE(STATUS "Install component: \"${COMPONENT}\"")
    SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
  ELSE(COMPONENT)
    SET(CMAKE_INSTALL_COMPONENT)
  ENDIF(COMPONENT)
ENDIF(NOT CMAKE_INSTALL_COMPONENT)

# Install shared libraries without execute permission?
IF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)
  SET(CMAKE_INSTALL_SO_NO_EXE "1")
ENDIF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/quad/cmake" TYPE FILE FILES "/home/rafa/cws/build/quad/catkin_generated/installspace/quad-msg-paths.cmake")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  execute_process(COMMAND "/usr/bin/python" -m compileall "/home/rafa/cws/devel/lib/python2.7/dist-packages/quad")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/python2.7/dist-packages" TYPE DIRECTORY FILES "/home/rafa/cws/devel/lib/python2.7/dist-packages/quad")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/pkgconfig" TYPE FILE FILES "/home/rafa/cws/build/quad/catkin_generated/installspace/quad.pc")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/quad/cmake" TYPE FILE FILES "/home/rafa/cws/build/quad/catkin_generated/installspace/quad-msg-extras.cmake")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/quad/cmake" TYPE FILE FILES
    "/home/rafa/cws/build/quad/catkin_generated/installspace/quadConfig.cmake"
    "/home/rafa/cws/build/quad/catkin_generated/installspace/quadConfig-version.cmake"
    )
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/quad" TYPE FILE FILES "/home/rafa/cws/src/quad/package.xml")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")


text:
set -e

LND_DIR=$HOME/.lnd

[[ -f $HOME/.testnet-lnd.pid ]] && kill -0 `cat $HOME/.testnet-lnd.pid` &>/dev/null && echo "You must to stop testnet lnd before update!" && exit 1
[[ -f $HOME/.mainnet-lnd.pid ]] && kill -0 `cat $HOME/.mainnet-lnd.pid` &>/dev/null && echo "You must to stop mainnet lnd before update!" && exit 2
[[ -f $HOME/.testnet-lncli-web.pid ]] && kill -0 `cat $HOME/.testnet-lncli-web.pid` &>/dev/null && echo "You must to stop testnet lncli-web before update!" && exit 1
[[ -f $HOME/.mainnet-lncli-web.pid ]] && kill -0 `cat $HOME/.mainnet-lncli-web.pid` &>/dev/null && echo "You must to stop mainnet lncli-web before update!" && exit 2

if [[ `openssl x509 -in $LND_DIR/tls.cert -text -noout |grep 'lnd autogenerated cert'` == "" ]]; then
    # Need to update!
    rm -f $LND_DIR/tls.cert
    rm -f $LND_DIR/tls.key
    if [[ -d $HOME/opt/lncli-web && -f $HOME/opt/lncli-web/lnd.cert ]]; then
	rm -f $HOME/opt/lncli-web/lnd.cert
	# Now tls.cert file doesn't exist but it will be recreated after lnd start
	ln -s $LND_DIR/tls.cert $HOME/opt/lncli-web/lnd.cert
    fi
fi


text:
"""
A check to run relevant diagnostics via `oc adm diagnostics`.
"""

import os

from openshift_checks import OpenShiftCheck, OpenShiftCheckException

DIAGNOSTIC_LIST = (
    "AggregatedLogging ClusterRegistry ClusterRoleBindings ClusterRoles "
    "ClusterRouter DiagnosticPod NetworkCheck"
).split()

class DiagnosticCheck(OpenShiftCheck):
    """A check to run relevant diagnostics via `oc adm diagnostics`."""

    name = "diagnostics"
    tags = ["health"]

    def is_active(self):
        return super(DiagnosticCheck, self).is_active() and self.is_first_master()

    def run(self):
        if self.exec_diagnostic("ConfigContexts"):
            # only run the other diagnostics if that one succeeds (otherwise, all will fail)
            diagnostics = self.get_var("openshift_check_diagnostics", default=DIAGNOSTIC_LIST)
            for diagnostic in self.normalize(diagnostics):
                self.exec_diagnostic(diagnostic)
        return {}

    def exec_diagnostic(self, diagnostic):
        """
        Execute an 'oc adm diagnostics' command on the remote host.
        Raises OcNotFound or registers OcDiagFailed.
        Returns True on success or False on failure (non-zero rc).
        """
        config_base = self.get_var("openshift.common.config_base")
        args = {
            "config_file": os.path.join(config_base, "master", "admin.kubeconfig"),
            "cmd": "adm diagnostics",
            "extra_args": [diagnostic],
        }

        result = self.execute_module("ocutil", args, save_as_name=diagnostic + ".failure.json")
        self.register_file(diagnostic + ".txt", result['result'])
        if result.get("failed"):
            if result['result'] == '[Errno 2] No such file or directory':
                raise OpenShiftCheckException(
                    "OcNotFound",
                    "This host is supposed to be a master but does not have the `oc` command where expected.\n"
                    "Has an installation been run on this host yet?"
                )

            self.register_failure(OpenShiftCheckException(
                'OcDiagFailed',
                'The {diag} diagnostic reported an error:\n'
                '{error}'.format(diag=diagnostic, error=result['result'])
            ))
            return False
        return True


text:
import { StorageType } from './StorageType'
import { isBoolean } from 'illa/Type'

export class StorageWrapper {

	private storage: Storage | null
	private static isSupported: boolean[] = []

	constructor(private type: StorageType) {
		this.storage = this.getNativeStorage(type)
	}

	static getIsSupported(t: StorageType): boolean {
		if (!isBoolean(this.isSupported[t])) {
			var storageWrapper = new StorageWrapper(t)
			try {
				var itemName = 'berek_StorageUtil_test'
				var value = '1'
				storageWrapper.setItem(itemName, value)
				this.isSupported[t] = storageWrapper.getItem(itemName) === value
				storageWrapper.removeItem(itemName)
			} catch (e) {
				this.isSupported[t] = false
			}
		}
		return this.isSupported[t]
	}

	getNativeStorage(type: StorageType): Storage | null {
		var result: Storage | null = null
		try {
			switch (type) {
				case StorageType.LOCAL:
					result = window.localStorage
					break
				case StorageType.SESSION:
					result = window.sessionStorage
					break
			}
		} catch (e) {}
		return result
	}

	getKeys(): string[] {
		var result: string[] = []
		if (this.storage) {
			for (var i = 0, n = this.storage.length; i < n; i++) {
				let value = this.storage.key(i)
				if (value) result.push(value)
			}
		}
		return result
	}

	getItem(k: string): string | null {
		var result: string | null = null
		if (this.storage) {
			result = this.storage.getItem(k)
		}
		return result
	}

	setItem(k: string, v: string): boolean {
		var success = false
		if (this.storage) {
			try {
				this.storage.setItem(k, v)
				success = true
			} catch (e) {}
		}
		return success
	}

	removeItem(k: string): void {
		if (this.storage) {
			this.storage.removeItem(k)
		}
	}

	clear(type: StorageType): void {
		if (this.storage) {
			this.storage.clear()
		}
	}

	getType() { return this.type }
	getStorage() { return this.storage }
}


text:
package com.zhuohua.systemadmin.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Commenttype entity. @author MyEclipse Persistence Tools
 */
@Entity(name="systemAdminCommentType")
@Table(name="commenttype"
    ,catalog="newstudentmis"
)
public class CommentType  implements java.io.Serializable {
    // Fields
     private Integer commentTypeId;
     private String content;
     private String role;
     private Integer score;
    // Constructors
    /** default constructor */
    public CommentType() {
    }
	/** minimal constructor */
    public CommentType(Integer commentTypeId) {
        this.commentTypeId = commentTypeId;
    }
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="CommentTypeId", unique=true, nullable=false)
    public Integer getCommentTypeId() {
        return this.commentTypeId;
    }
    public void setCommentTypeId(Integer commentTypeId) {
        this.commentTypeId = commentTypeId;
    }

    @Column(name="Content", length=200)

    public String getContent() {
        return this.content;
    }
    public void setContent(String content) {
        this.content = content;
    }

    @Column(name="Role", length=20)

    public String getRole() {
        return this.role;
    }
    public void setRole(String role) {
        this.role = role;
    }

    @Column(name="Score")

    public Integer getScore() {
        return this.score;
    }
    public void setScore(Integer score) {
        this.score = score;
    }
}


text:
layout: post
title: Python - A little bit about List
subtitle: Why lists are pretty awesome
preview: Python has a "batteries included" philosophy as demonstrated with its extensive standard library and included modules. One part of the standard library that I use very often are iterators, or more specifically, lists. Here I'm going to explain a bit about lists in Python and why they're awesome.
---
Python has a "[batteries included](https://docs.python.org/2/tutorial/stdlib.html#batteries-included)" philosophy as demonstrated with its extensive standard library and included modules. One part of the standard library that I use very often are iterators, or more specifically, lists. Here I'm going to explain a bit about lists in Python and why they're awesome.

## Firstly, what is an iterator?
An iterator is a datatype that represents a stream of data which will, when iterated over, return its elements one at a time. There are multiple iterable types in Python such as `list`, `str` and `tuple`, for this article I am going to focus on `list`.

## Onto the List
A `list` is exactly how it sounds - just a list of things. In other programming languages the equivalent datatype would be an `array`, however an `array` would be of a fixed length and only capable of storing elements of the same type. Python does not have this restriction, a `list` can grow in size as more elements are added to it and it is able to store objects of different types.

List indices start at 0 and are constructed with square brackets, separating items with a comma like `[42, 'magrathea']` or if you already have a sequence you are able to call `list()` on it.

~~~python
>>> list('vogon')
['v', 'o', 'g', 'o', 'n']
~~~

### List Slicing
Slicing a list allows you to define a start and an end to return subsets and is rather powerful.

~~~python
L[start:end] # start index to end-1 index
L[start:] # start index to end of list
L[:end] # beginning of list to end-1 index
L[:] # the full list (creates a copy)

>>> numbers = list(range(10))
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[4:8]
[4, 5, 6, 7]
>>> numbers[2:]
[2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[:3]
[0, 1, 2]
>>> numbers[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
~~~

There is also a third argument you can use when slicing - `step`. This specifies how often to step through the list. By default, this is 1 which means it will iterate over every single element in the list, however you can change this to be any integer, positive or negative. If `step` is a negative integer it will iterate through the list backwards (which is often using when determining if a string is a palindrome).

~~~python
>>> numbers = list(range(10))
>>> numbers[::2]
[0, 2, 4, 6, 8]
>>> answer = list('forty two')
>>> answer[::-1]
['o', 'w', 't', ' ', 'y', 't', 'r', 'o', 'f']
~~~

### Joining Elements in a List
If you have a list of strings it's a task to join them together to create a single string. Instead of using a `for` loop to iterate over each string in the list to concatenate it with another string, it's possible to use the `join()` function with a delimiter.

~~~python
>>> words = ['There\'s', 'a', 'frood', 'who', 'really', 'knows', 'where', 'his', 'towel', 'is']
>>> ' '.join(words)
"There's a frood who really knows where his towel is"
~~~

### Adding Elements in a List
Using the Python built-in function `sum()` we're able to pass an iterable and it will add each element together.

~~~python
>>> numbers = [1, 2, 4, 8, 12, 15]
>>> sum(numbers)
42
~~~

### Sorting a List
Another Python built-in function makes this a doddle - `sorted()`.

~~~python
>>> numbers = [15, 2, 12, 1, 8, 4]
>>> sorted(numbers)
[1, 2, 4, 8, 12, 15]
~~~

### Finding the max and min values in a List
Again, the batteries-included Python standard library has provided us with more built-in functions to make our lives easier - `max()` and `min()`.

~~~python
>>> numbers = [15, 2, 12, 1, 8, 4]
>>> max(numbers)
15
>>> min(numbers)
1
~~~

### Concatenating Lists
Suppose we have multiple separate lists and we want to concatenate them into a single one, we can simply use the `+` operator.

~~~python
>>> humans = ['arthur', 'trillian']
>>> betelgeuseans = ['ford', 'zaphod']
>>> robots = ['marvin']
>>> humans + betalgeuseans + robots
['arthur', 'trillian', 'ford', 'zaphod', 'marvin']
~~~

### Counting the frequency of elements in a List
We can easily count the frequency of elements in a list with the built-in function [`Counter()`](https://docs.python.org/2.7/library/collections.html?highlight=counter#counter-objects) from `collections`.

~~~python
# Setting up our list
>>> h2g2 = """For instance, on the planet Earth, man had always assumeed that he was more intelligent than dolphins because he had achieved so much — the wheel, New York, wars and so on — whilst all the dolphins had ever done was muck about in the water having a good time. But conversely, the dolphins had always believed that they were far more intelligent than man - for precisely the same reasons.

Time is an illusion. Lunchtime doubley so.
"""
>>> words = h2g2.split(' ')

>>> from collections import Counter
>>> Counter(words).most_common(5)
[('had', 4), ('the', 4), ('he', 2), ('was', 2), ('than', 2)]
~~~

### Using a List as a Stack
In Computer Science a stack is a first-in-last-out abstract datatype which allows you to push elements into a list and pop them out (like putting paper into a pile, the first sheet goes to the bottom and will be the last you get to when picking from the top). The `pop()` method on the `list` datatype removes the element at the specified index and returns it, if no index is specified then it gets the last element in the list.

~~~python
>>> stack = []  # Creating our stack
>>> stack.append('arthur')
>>> stack.append('ford')
>>> stack.append('trillian')
>>> stack.pop()
'trillian'
>>> stack.pop()
'ford'
>>> stack
['arthur']
>>> stack.pop()
'arthur'
>>> stack
[]
~~~

### Using a List as a Queue
In Computer Science a queue is a first-in-first-out abstract datatype which allows you to push elements into a list and retrieve them in the order they were inserted (like a normal queue at a shop). There are two methods to implement a queue, we can use the `pop()` method similar as used when implementing a Stack by specifying the index to be 0 (and therefore the first element in the list) or we can use [`deque`](https://docs.python.org/2.7/library/collections.html?highlight=counter#deque-objects) from the `collections` module. A `list` incurs O(n) costs for `pop(0)` so is not suitable to use for large datasets. `deque` gives O(1) performance and behaves in a similar fashion as a `list`.

~~~python
>>> from collections import deque
>>> queue = deque()
>>> queue.append('arthur')
>>> queue.append('ford')
>>> queue.append('trillian')
>>> queue.popleft()
'arthur'
>>> queue.popleft()
'ford'
>>> queue
deque(['trillian'])
>>> queue.popleft()
'trillian'
>>> queue
deque([])
~~~

### List Comprehension
Finally, we can't talk about the `list` datatype without discussing list comprehensions. List comprehensions are an *awesome* Pythonic way of creating lists.

Previously you may have created a list using something like this:

~~~python
new_list = []
for something in old_list:
    if condition(something):
        new_list.append(something)
~~~

However, with a list comprehension are able to rewrite the above into a simple one-liner to enhance readability:

~~~python
new_list = [something for something in old_list if condition(something)]
~~~

Some examples for why List Comprehensions are pretty awesome:

#### List of numbers divisible by 3
For loop:

~~~python
numbers = []
for x in range(50):
    if x % 3 == 0:
        numbers.append(x)
~~~

List Comprehension:

~~~python
numbers = [x for x in range(50) if x % 3 == 0]
~~~

#### List of squares
For loop:

~~~python
squares = []
for x in range(50):
	squares.append(x**2)
~~~

List Comprehension:

~~~python
squares = [x**2 for x in range(50)]
~~~

#### Remove vowels from a sentence
For loop:

~~~python
>>> vowels = 'aeiou'
>>> h2g2 = "Time is an illusion. Lunchtime doubley so."
>>> no_vowels = []
>>> for letter in h2g2:
... 	if not letter in vowels:
... 		no_vowels.append(letter)
>>> ''.join(no_vowels)
'Tm s n llsn. Lnchtm dbly s.'
~~~

List Comprehension:

~~~python
>>> vowels = 'aeiou'
>>> h2g2 = "Time is an illusion. Lunchtime doubley so."
>>> ''.join([letter for letter in h2g2 if not letter in vowels])
'Tm s n llsn. Lnchtm dbly s.'
~~~

----------
Please see the Python Docs [on lists](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) and [sequences in general](https://docs.python.org/2/library/stdtypes.html#iterator-types)) for further info as the basics are thoroughly explained there.

**PS:-** For another great list, check out the [**Awesome Python**](http://awesome-python.com/) list full awesome of frameworks, libraries and software.


text:
package VMOMI::ArrayOfHostScsiTopologyInterface;
use parent 'VMOMI::ComplexType';

use strict;
use warnings;

our @class_ancestors = ( );

our @class_members = (
    ['HostScsiTopologyInterface', 'HostScsiTopologyInterface', 1, 1],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;


text:
<?php

class XML_Model extends Memory_Model
{
    //---------------------------------------------------------------------------
    //  Housekeeping methods
    //---------------------------------------------------------------------------

    /**
     * Constructor.
     * @param string $origin Filename of the XML file
     * @param string $keyfield  Name of the primary key field
     * @param string $entity	Entity name meaningful to the persistence
     */
    public function __construct($origin = null, $keyfield = 'id', $entity = null)
    {
        parent::__construct();

        // guess at persistent name if not specified
        if ($origin == null) {
            $this->_origin = get_class($this);
        } else {
            $this->_origin = $origin;
        }

        // remember the other constructor fields
        $this->_keyfield = $keyfield;
        $this->_entity = $entity;

        // start with an empty collection
        $this->_data = array(); // an array of objects
        $this->_fields = array(); // an array of strings
        // and populate the collection
        $this->load();
    }

    /**
     * Load the collection state appropriately, depending on persistence choice.
     * OVER-RIDE THIS METHOD in persistence choice implementations
     */
    protected function load()
    {
        if (file_exists('../data/tasks.xml')) {
            $xml = simplexml_load_file('../data/tasks.xml');

            $tasktiles = array();

            // get & store titles
            foreach ($xml->children()->children() as $column) {
                $tasktitles[] = $column->getName();
            }
            $this->_fields = $tasktitles;
            //print_r($this->_fields);

            // cast and store objects
            foreach ($xml->children() as $task) {
                $record = new stdClass();
                $record->id = (int) $task->id;
                $record->task = (string) $task->task;
                $record->priority = (int) $task->priority;
                $record->size = (int) $task->size;
                $record->group = (int) $task->group;
                $record->deadline = (int) $task->deadline;
                $record->status = (int) $task->status;
                $record->flag = (int) $task->flag;

                //$tasklist[] = $task;
                $key = $record->{$this->_keyfield};
                $this->_data[$key] = $record;
            }
        } else {
            exit('Failed to open tasks.xml.');
        }
        $this->reindex();
    }

    /**
     * Store the collection state appropriately, depending on persistence choice.
     * OVER-RIDE THIS METHOD in persistence choice implementations
     */
    protected function store()
    {
        // rebuild the keys table
        $this->reindex();

        $document = new DOMDocument('1.0', 'UTF-8');
				$tasks = $document->createElement('tasks');
				$document->appendChild($tasks);

				foreach ($this->_data as $key => $record) {
						$todo = $document->createElement('todo');
						$tasks->appendChild($todo);

						foreach($record as $keyname => $value) {
								$todo->appendChild($document->createElement($keyname, $value));
						}
				}

				$document->formatOutput = true;
        $document->save('../data/tasks.xml');
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>com.hazelcast.transaction.client (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.hazelcast.transaction.client

Classes

BaseTransactionRequest

ClientTxnPortableHook

CommitTransactionRequest

CreateTransactionRequest

PrepareTransactionRequest

RecoverAllTransactionsRequest

RecoverTransactionRequest

RollbackTransactionRequest


text:
class CreateDanvanthiriCoreDoctorsPlans < ActiveRecord::Migration
  def change
    create_table :danvanthiri_core_doctors_plans do |t|
      t.integer :doctor_id
      t.integer :plan_id
      t.integer :city_number, default: 1
      t.integer :area_number, default: 1
      t.integer :status
      t.integer :price
      t.datetime :expired_date

      t.timestamps null: false
    end
  end
end


text:
package com.example.android.actionbarcompat.basic;

import android.app.TabActivity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

/**
 * This sample shows you how to use ActionBarCompat to create a basic Activity which displays
 * action items. It covers inflating items from a menu resource, as well as adding an item in code.
 *
 * This Activity extends from {@link ActionBarActivity}, which provides all of the function
 * necessary to display a compatible Action Bar on devices running Android v2.1+.
 */
public class MainActivity extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_main);

        TabHost tabHost = getTabHost();

        // setNewTab(tabHost, tag, title, icon, contentID, viewID);
        this.setNewTab(tabHost, "tab1", R.string.textTabTitle1, android.R.drawable.ic_menu_crop, R.id.tab1, R.id.tab_id_1);
        this.setNewTab(tabHost, "tab2", R.string.textTabTitle2, android.R.drawable.ic_menu_add, R.id.tab2, R.id.tab_id_2);
        this.setNewTab(tabHost, "tab3", R.string.textTabTitle3, android.R.drawable.ic_menu_delete, R.id.tab3, R.id.tab_id_3);
    }

    private void setNewTab(TabHost tabHost, String tag, int title, int icon, int contentID, int viewId ){
        TabHost.TabSpec tabSpec = tabHost.newTabSpec(tag);
        tabSpec.setIndicator(getTabIndicator(tabHost.getContext(), title, icon, viewId, tag));
        tabSpec.setContent(contentID);
        tabHost.addTab(tabSpec);
    }

    private View getTabIndicator(Context context, int title, int icon, int viewId, String viewTag) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_layout, null);
        ImageView iv = (ImageView) view.findViewById(R.id.image_view);
        iv.setImageResource(icon);
        TextView tv = (TextView) view.findViewById(R.id.text_view);
        tv.setText(title);

        tv.setId(viewId);
        tv.setTag(viewTag);

        return view;
    }

    // BEGIN_INCLUDE(create_menu)
    /**
     * Use this method to instantiate your menu, and add your items to it. You
     * should return true if you have added items to it and want the menu to be displayed.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate our menu from the resources by using the menu inflater.
        getMenuInflater().inflate(R.menu.main, menu);

        // It is also possible add items here. Use a generated id from
        // resources (ids.xml) to ensure that all menu ids are distinct.
        MenuItem locationItem = menu.add(0, R.id.menu_location, 0, R.string.menu_location);
        locationItem.setIcon(R.drawable.ic_action_location);

        // Need to use MenuItemCompat methods to call any action item related methods
        MenuItemCompat.setShowAsAction(locationItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);

        return true;
    }
    // END_INCLUDE(create_menu)

    // BEGIN_INCLUDE(menu_item_selected)
    /**
     * This method is called when one of the menu items to selected. These items
     * can be on the Action Bar, the overflow menu, or the standard options menu. You
     * should return true if you handle the selection.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_refresh:
                // Here we might start a background refresh task
                return true;

            case R.id.menu_location:
                // Here we might call LocationManager.requestLocationUpdates()
                return true;

            case R.id.menu_settings:
                // Here we would open up our settings activity
                return true;
        }

        return super.onOptionsItemSelected(item);
    }
    // END_INCLUDE(menu_item_selected)
}


text:
namespace luabind
{
    class type_id;

    typedef void(*error_callback_fun)(lua_State*);
    typedef void(*cast_failed_callback_fun)(lua_State*, type_id const&);
    typedef int(*pcall_callback_fun)(lua_State*);
}

#endif // INCLUDED_error_callback_fun_hpp_GUID_1150976a_4348_495f_99ce_9d7edd00a0b8


text:
<?xml version="1.0" ?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.
-->

<!-- Example exchange rates file.  -->

<currencyConfig version="1.0">
  <rates>
    <!-- Example -->
    <rate from="USD" to="JPY" rate="81.29"/>

    <!-- Fake rates for testing -->
    <rate from="USD" to="EUR" rate="2.5"/>
    <rate from="USD" to="GBP" rate="0.5"/>
    <rate from="EUR" to="GBP" rate="0.5"/>

    <!-- Asymmetric rate -->
    <rate from="EUR" to="USD" rate="0.5"/>
  </rates>
</currencyConfig>


text:
package co.cask.cdap.explore.guice;

import co.cask.cdap.common.conf.CConfiguration;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.common.runtime.RuntimeModule;
import co.cask.cdap.data2.datafabric.dataset.RemoteDatasetFramework;
import co.cask.cdap.data2.util.hbase.HBaseTableUtilFactory;
import co.cask.cdap.explore.executor.ExploreExecutorHttpHandler;
import co.cask.cdap.explore.executor.ExploreExecutorService;
import co.cask.cdap.explore.executor.ExploreMetadataHttpHandler;
import co.cask.cdap.explore.executor.ExploreStatusHandler;
import co.cask.cdap.explore.executor.NamespacedExploreMetadataHttpHandler;
import co.cask.cdap.explore.executor.NamespacedQueryExecutorHttpHandler;
import co.cask.cdap.explore.executor.QueryExecutorHttpHandler;
import co.cask.cdap.explore.service.ExploreService;
import co.cask.cdap.explore.service.ExploreServiceUtils;
import co.cask.cdap.explore.service.hive.BaseHiveExploreService;
import co.cask.cdap.explore.service.hive.Hive14ExploreService;
import co.cask.cdap.format.RecordFormats;
import co.cask.cdap.gateway.handlers.CommonHandlers;
import co.cask.cdap.hive.datasets.DatasetStorageHandler;
import co.cask.http.HttpHandler;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.inject.Exposed;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.PrivateModule;
import com.google.inject.Provider;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.Singleton;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import com.google.inject.util.Modules;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.MRConfig;
import org.apache.twill.api.ClassAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * Guice runtime module for the explore functionality.
 */
public class ExploreRuntimeModule extends RuntimeModule {
  private static final Logger LOG = LoggerFactory.getLogger(ExploreRuntimeModule.class);

  @Override
  public Module getInMemoryModules() {
    // Turning off assertions for Hive packages, since some assertions in StandardStructObjectInspector do not work
    // when outer joins are run. It is okay to turn off Hive assertions since we assume Hive is a black-box that does
    // the right thing, and we only want to test our/our user's code.
    getClass().getClassLoader().setPackageAssertionStatus("org.apache.hadoop.hive", false);
    getClass().getClassLoader().setPackageAssertionStatus("org.apache.hive", false);
    return Modules.combine(new ExploreExecutorModule(), new ExploreLocalModule(true));
  }

  @Override
  public Module getStandaloneModules() {
    return Modules.combine(new ExploreExecutorModule(), new ExploreLocalModule(false));
  }

  @Override
  public Module getDistributedModules() {
    return Modules.combine(new ExploreExecutorModule(), new ExploreDistributedModule());
  }

  private static final class ExploreExecutorModule extends PrivateModule {

    @Override
    protected void configure() {
      Named exploreSeriveName = Names.named(Constants.Service.EXPLORE_HTTP_USER_SERVICE);
      Multibinder<HttpHandler> handlerBinder =
          Multibinder.newSetBinder(binder(), HttpHandler.class, exploreSeriveName);
      handlerBinder.addBinding().to(NamespacedQueryExecutorHttpHandler.class);
      handlerBinder.addBinding().to(QueryExecutorHttpHandler.class);
      handlerBinder.addBinding().to(NamespacedExploreMetadataHttpHandler.class);
      handlerBinder.addBinding().to(ExploreMetadataHttpHandler.class);
      handlerBinder.addBinding().to(ExploreExecutorHttpHandler.class);
      handlerBinder.addBinding().to(ExploreStatusHandler.class);
      CommonHandlers.add(handlerBinder);

      bind(ExploreExecutorService.class).in(Scopes.SINGLETON);
      expose(ExploreExecutorService.class);
    }
  }

  private static final class ExploreLocalModule extends PrivateModule {
    private final boolean isInMemory;

    ExploreLocalModule(boolean isInMemory) {
      this.isInMemory = isInMemory;
    }

    @Override
    protected void configure() {
      // Current version of hive used in standalone is Hive 14
      bind(ExploreService.class).annotatedWith(Names.named("explore.service.impl")).to(Hive14ExploreService.class);
      bind(ExploreService.class).toProvider(ExploreServiceProvider.class).in(Scopes.SINGLETON);
      expose(ExploreService.class);
      bind(boolean.class).annotatedWith(Names.named("explore.inmemory")).toInstance(isInMemory);

      bind(File.class).annotatedWith(Names.named(Constants.Explore.PREVIEWS_DIR_NAME))
        .toProvider(PreviewsDirProvider.class);
    }

    private static final class PreviewsDirProvider implements Provider<File> {
      private final CConfiguration cConf;

      @Inject
      PreviewsDirProvider(CConfiguration cConf) {
        this.cConf = cConf;
      }

      @Override
      public File get() {
        String localDirStr = cConf.get(Constants.Explore.LOCAL_DATA_DIR);
        File previewsDir = new File(localDirStr, "previewsDir");
        previewsDir.mkdirs();
        return previewsDir;
      }
    }

    @Singleton
    private static final class ExploreServiceProvider implements Provider<ExploreService> {
      private final CConfiguration cConf;
      private final Configuration hConf;
      private final ExploreService exploreService;
      private final boolean isInMemory;

      @Inject
      ExploreServiceProvider(CConfiguration cConf, Configuration hConf,
                                    @Named("explore.service.impl") ExploreService exploreService,
                                    @Named("explore.inmemory") boolean isInMemory) {
        this.exploreService = exploreService;
        this.cConf = cConf;
        this.hConf = hConf;
        this.isInMemory = isInMemory;
      }

      private static final long seed = System.currentTimeMillis();
      @Override
      public ExploreService get() {
        File hiveDataDir = new File(cConf.get(Constants.Explore.LOCAL_DATA_DIR));

        // The properties set using setProperty will be included to any new HiveConf object created,
        // at the condition that the configuration is known by Hive, and so is one of the HiveConf.ConfVars
        // variables.

        System.setProperty(HiveConf.ConfVars.SCRATCHDIR.toString(),
                           new File(hiveDataDir, cConf.get(Constants.AppFabric.TEMP_DIR)).getAbsolutePath());

        // Reset hadoop tmp dir because Hive does not pick it up from hConf
        System.setProperty("hadoop.tmp.dir", hConf.get("hadoop.tmp.dir"));

        File warehouseDir = new File(cConf.get(Constants.Explore.LOCAL_DATA_DIR), "warehouse");
        File databaseDir = new File(cConf.get(Constants.Explore.LOCAL_DATA_DIR), "database");

        if (isInMemory) {
          // This seed is required to make all tests pass when launched together, and when several of them
          // start a hive metastore / hive server.
          warehouseDir = new File(warehouseDir, Long.toString(seed));
          databaseDir = new File(databaseDir, Long.toString(seed));
        }

        LOG.debug("Setting {} to {}",
                  HiveConf.ConfVars.METASTOREWAREHOUSE.toString(), warehouseDir.getAbsoluteFile());
        System.setProperty(HiveConf.ConfVars.METASTOREWAREHOUSE.toString(), warehouseDir.getAbsolutePath());

        // Set derby log location
        System.setProperty("derby.stream.error.file",
                           cConf.get(Constants.Explore.LOCAL_DATA_DIR) + File.separator + "derby.log");

        String connectUrl = String.format("jdbc:derby:;databaseName=%s;create=true", databaseDir.getAbsoluteFile());
        LOG.debug("Setting {} to {}", HiveConf.ConfVars.METASTORECONNECTURLKEY.toString(), connectUrl);
        System.setProperty(HiveConf.ConfVars.METASTORECONNECTURLKEY.toString(), connectUrl);

        // Some more local mode settings
        System.setProperty(HiveConf.ConfVars.LOCALMODEAUTO.toString(), "true");
        System.setProperty(HiveConf.ConfVars.SUBMITVIACHILD.toString(), "false");
        System.setProperty(MRConfig.FRAMEWORK_NAME, "local");

        // Disable security
        // Also need to disable security by making HiveAuthFactory.loginFromKeytab a no-op, since Hive >=0.14
        // ignores the HIVE_SERVER2_AUTHENTICATION property and instead uses UserGroupInformation.isSecurityEnabled()
        // (rewrite to HiveAuthFactory.loginFromKeytab bytecode is done in ExploreServiceUtils.traceDependencies)
        System.setProperty(HiveConf.ConfVars.HIVE_SERVER2_AUTHENTICATION.toString(), "NONE");
        System.setProperty(HiveConf.ConfVars.HIVE_SERVER2_ENABLE_DOAS.toString(), "false");
        System.setProperty(HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL.toString(), "false");

        return exploreService;
      }
    }
  }

  private static final class ExploreDistributedModule extends PrivateModule {
    private static final Logger LOG = LoggerFactory.getLogger(ExploreDistributedModule.class);

    @Override
    protected void configure() {
      try {
        CConfiguration cConf = CConfiguration.create();
        File tmpDir = new File(new File(cConf.get(Constants.CFG_LOCAL_DATA_DIR)),
                               cConf.get(Constants.AppFabric.TEMP_DIR)).getAbsoluteFile();
        tmpDir.mkdirs();
        setupClasspath(tmpDir);

        // Set local tmp dir to an absolute location in the twill runnable otherwise Hive complains
        String localScratchPath = System.getProperty("java.io.tmpdir") + File.separator +
          "hive-" + System.getProperty("user.name");
        System.setProperty(HiveConf.ConfVars.LOCALSCRATCHDIR.toString(),
                           new File(localScratchPath).getAbsolutePath());
        LOG.info("Setting {} to {}", HiveConf.ConfVars.LOCALSCRATCHDIR.toString(),
                 System.getProperty(HiveConf.ConfVars.LOCALSCRATCHDIR.toString()));

        File previewDir = Files.createTempDir();
        LOG.info("Storing preview files in {}", previewDir.getAbsolutePath());
        bind(File.class).annotatedWith(Names.named(Constants.Explore.PREVIEWS_DIR_NAME)).toInstance(previewDir);
      } catch (Throwable e) {
        throw Throwables.propagate(e);
      }
    }

    @Provides
    @Singleton
    @Exposed
    public ExploreService providesExploreService(Injector injector) {
      // Figure out which HiveExploreService class to load
      Class<? extends ExploreService> hiveExploreServiceCl = ExploreServiceUtils.getHiveService();
      LOG.info("Using Explore service class {}", hiveExploreServiceCl.getName());
      return injector.getInstance(hiveExploreServiceCl);
    }
  }

  private static void setupClasspath(File tmpDir) throws IOException {
    // Here we find the transitive dependencies and remove all paths that come from the boot class path -
    // those paths are not needed because the new JVM will have them in its boot class path.
    // It could even be wrong to keep them because in the target container, the boot class path may be different
    // (for example, if Hadoop uses a different Java version than CDAP).

    final Set<String> bootstrapClassPaths = ExploreServiceUtils.getBoostrapClasses();

    ClassAcceptor classAcceptor = new ClassAcceptor() {
       /* Excluding any class contained in the bootstrapClassPaths and Kryo classes and hive-exec.jar
        * We need to remove Kryo dependency in the Explore container. Spark introduced version 2.21 version of Kryo,
        * which would be normally shipped to the Explore container. Yet, Hive requires Kryo 2.22,
        * and gets it from the Hive jars - hive-exec.jar to be precise.
        * we also exclude hive jars as hive dependencies are found in job.jar.
        * */
      @Override
      public boolean accept(String className, URL classUrl, URL classPathUrl) {
        if (bootstrapClassPaths.contains(classPathUrl.getFile()) ||
          className.startsWith("com.esotericsoftware.kryo") || classPathUrl.getFile().contains("hive")) {
          return false;
        }
        return true;
      }
    };

    Set<File> hBaseTableDeps = ExploreServiceUtils.traceDependencies(
      null, classAcceptor, tmpDir, HBaseTableUtilFactory.getHBaseTableUtilClass().getName());

    // Note the order of dependency jars is important so that HBase jars come first in the classpath order
    // LinkedHashSet maintains insertion order while removing duplicate entries.
    Set<File> orderedDependencies = new LinkedHashSet<>();
    orderedDependencies.addAll(hBaseTableDeps);
    orderedDependencies.addAll(ExploreServiceUtils.traceDependencies(null, classAcceptor, tmpDir,
                                                                     RemoteDatasetFramework.class.getName(),
                                                                     DatasetStorageHandler.class.getName(),
                                                                     RecordFormats.class.getName()));

    // Note: the class path entries need to be prefixed with "file://" for the jars to work when
    // Hive starts local map-reduce job.
    ImmutableList.Builder<String> builder = ImmutableList.builder();
    for (File dep : orderedDependencies) {
      builder.add("file://" + dep.getAbsolutePath());
    }
    List<String> orderedDependenciesStr = builder.build();

    // These dependency files need to be copied over to spark container
    System.setProperty(BaseHiveExploreService.SPARK_YARN_DIST_FILES,
                       Joiner.on(',').join(Iterables.transform(orderedDependencies, new Function<File, String>() {
                         @Override
                         public String apply(File input) {
                           return input.getAbsolutePath();
                         }
                       })));
    LOG.debug("Setting {} to {}", BaseHiveExploreService.SPARK_YARN_DIST_FILES,
              System.getProperty(BaseHiveExploreService.SPARK_YARN_DIST_FILES));

    // These dependency files need to be copied over to hive job container
    System.setProperty(HiveConf.ConfVars.HIVEAUXJARS.toString(), Joiner.on(',').join(orderedDependenciesStr));
    LOG.debug("Setting {} to {}", HiveConf.ConfVars.HIVEAUXJARS.toString(),
              System.getProperty(HiveConf.ConfVars.HIVEAUXJARS.toString()));

    // add hive-exec.jar to the HADOOP_CLASSPATH, which is used by the local mapreduce job launched by hive ,
    // we need to add this, otherwise when hive runs a MapRedLocalTask it cannot find
    // "org.apache.hadoop.hive.serde2.SerDe" class in its classpath.
    List<String> orderedDependenciesWithHiveJar = Lists.newArrayList(orderedDependenciesStr);
    String hiveExecJar = new JobConf(org.apache.hadoop.hive.ql.exec.Task.class).getJar();
    Preconditions.checkNotNull(hiveExecJar, "Couldn't locate hive-exec.jar to be included in HADOOP_CLASSPATH " +
      "for MapReduce jobs launched by Hive");
    orderedDependenciesWithHiveJar.add(hiveExecJar);
    LOG.debug("Added hive-exec.jar {} to HADOOP_CLASSPATH to be included for MapReduce jobs launched by Hive",
              hiveExecJar);

    //TODO: Setup HADOOP_CLASSPATH hack, more info on why this is needed, see CDAP-9
    LocalMapreduceClasspathSetter classpathSetter =
      new LocalMapreduceClasspathSetter(new HiveConf(), tmpDir.getAbsolutePath(),
                                        orderedDependenciesWithHiveJar);
    for (File jar : hBaseTableDeps) {
      classpathSetter.accept(jar.getAbsolutePath());
    }
    classpathSetter.setupClasspathScript();
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".sample.WechatActivity">
    <android.support.v7.widget.Toolbar
            android:id="@+id/wechat_contact_toolbar"
            android:layout_width="match_parent"
            android:background="@color/colorToolbar"
            android:layout_height="wrap_content"
            app:title="微信通讯录"/>

    <ListView
            android:id="@+id/wechat_contact_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</LinearLayout>


text:
{% extends 'chess_layout.html' %}
{% block title %}Create game{% endblock %}

{% block chess_content %}

Create a new game

<form action="{% url chess.views.create_game %}" method="post">
  {{ form.white_player.errors }}
  White: {{ form.white_player }}

  {{ form.black_player.errors }}
  Black: {{ form.black_player }}

  {% if object %}
    <input type="submit" name="edit" value="Edit">
  {% else %}
    <input type="submit" name="create" value="Create"/>
  {% endif %}
</form>

{% endblock %}


text:
package com.srotya.sidewinder.core.storage.compression.gorilla;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;

import com.srotya.sidewinder.core.storage.LinkedByteString;
import com.srotya.sidewinder.core.storage.compression.Reader;
import com.srotya.sidewinder.core.storage.compression.TimeCodec;
import com.srotya.sidewinder.core.storage.compression.TimeWriter;
import com.srotya.sidewinder.core.utils.ByteUtils;

@TimeCodec(id = 4, name = "gorilla")
public class GorillaTimestampWriter implements TimeWriter {

	public static final int MD5_PADDING = 32;
	private boolean full;
	private LinkedByteString bufferId;
	private ByteBuffer buf;
	private GorillaTimestampCompressor compressor;
	private int counter;
	private long timestamp;
	private ByteBufferBitOutput output;
	private int startOffset;
	private int position;
	private int checkSumLocaltion;

	@Override
	public void configure(ByteBuffer buf, boolean isNew, int startOffset) throws IOException {
		this.buf = buf;
		this.checkSumLocaltion = startOffset;
		this.startOffset = startOffset + MD5_PADDING;
		buf.position(this.startOffset);
		if (!isNew) {
			counter = buf.getInt();
			// forward to the end
			position = buf.getInt();
			// forwardToEnd();
		} else {
			buf.putInt(0);
			buf.putInt(0);
		}
	}

	@SuppressWarnings("unused")
	private void forwardToEnd() throws IOException {
		GorillaValueReader reader = new GorillaValueReader(buf, startOffset, MD5_PADDING);
		for (int i = 0; i < counter; i++) {
			reader.read();
		}
	}

	@Override
	public void add(long timestamp) throws IOException {
		compressor.addValue(timestamp);
		counter++;
	}

	private void updateCount() {
		buf.putInt(startOffset, counter);
		position = buf.position();
		buf.putInt(startOffset + 4, position);
	}

	@Override
	public Reader getReader() throws IOException {
		ByteBuffer duplicate = buf.duplicate();
		duplicate.rewind();
		GorillaTimestampReader reader = new GorillaTimestampReader(duplicate, startOffset, checkSumLocaltion);
		return reader;
	}

	@Override
	public double getCompressionRatio() {
		return (double) position / counter;
	}

	@Override
	public void bootstrap(ByteBuffer buf) throws IOException {
	}

	@Override
	public ByteBuffer getRawBytes() {
		ByteBuffer duplicate = buf.duplicate();
		return duplicate;
	}

	@Override
	public void setCounter(int counter) {
		this.counter = counter;
	}

	@Override
	public void makeReadOnly(boolean recovery) throws IOException {
		// this writer is always readonly
		full = true;
		if (compressor != null && !recovery) {
			compressor.close();
			updateCount();
			// compute md5 and store
			try {
				// cache old position so the buf position can be reset
				int oldPosition = buf.position();
				byte[] bufferToHash = bufferToHash();
				buf.position(checkSumLocaltion);
				// save hash
				buf.put(bufferToHash);
				buf.position(oldPosition);
			} catch (NoSuchAlgorithmException e) {
				throw new IOException(e);
			}
		}
	}

	private byte[] bufferToHash() throws NoSuchAlgorithmException {
		ByteBuffer duplicate = buf.duplicate();
		duplicate.rewind();
		ByteBuffer copy = ByteBuffer.allocate(duplicate.capacity());
		copy.put(duplicate);
		byte[] array = copy.array();
		return ByteUtils.md5(array);
	}

	@Override
	public int currentOffset() {
		return position;
	}

	@Override
	public int getCount() {
		return counter;
	}

	@Override
	public boolean isFull() {
		return full;
	}

	@Override
	public boolean isReadOnly() {
		return true;
	}

	@Override
	public long getHeaderTimestamp() {
		return timestamp;
	}

	@Override
	public void setHeaderTimestamp(long timestamp) throws IOException {
		this.timestamp = timestamp;
		this.output = new ByteBufferBitOutput(buf);
		compressor = new GorillaTimestampCompressor(timestamp, output);
	}

	@Override
	public int getPosition() {
		return position;
	}

	@Override
	public void setBufferId(LinkedByteString key) {
		bufferId = key;
	}

	@Override
	public LinkedByteString getBufferId() {
		return bufferId;
	}

}


text:
"""Script to create aggregated results from an hparam set.

This script can be run after the corresponding baselines have been created,
or while the baselines are being run. In the case that the baselines are being
run this will continuously retry until all baselines are finished and only
finish at this point.
"""
from concurrent import futures
import time
from typing import Any, Mapping, Optional, Callable

from absl import app
from absl import logging
import gin
import jax
from learned_optimization import setup_experiment
from learned_optimization.baselines import hparam_sets  # pylint: disable=unused-import
from learned_optimization.baselines import utils
import numpy as onp

@gin.configurable
def maybe_get_hparam_set(
    task_name,
    hparam_set_name,
    hparam_set_fn: Optional[Callable[[str], hparam_sets.HParamSet]] = None,
    clear_bad_files: bool = False,
) -> Optional[Mapping[str, Any]]:
  """Attempt to get the data for a given task_name and hparam set.

  Args:
    task_name: Name of task to get hparam set of.
    hparam_set_name: Name of the hparam set.
    hparam_set_fn: Optional function which is called with tak_name to return the
      values of the hparam set. If not specified we look up the hparam_set_name
      from gin. This value is designed to be injected with gin.
    clear_bad_files: If this is True, and we comes across a file it cannot load,
      we assume it is corrupt and delete it.

  Returns:
    Either None if no values could be obtained, or a stacked dictionary
      containing the results from inner-training.
  """
  if hparam_set_fn is None:
    hparam_set_fn = gin.get_configurable(hparam_set_name)
  unused_cfgs, paths_reps = hparam_set_fn(task_name)
  paths, unused_reps = zip(*paths_reps)

  def load_one(p):
    return utils.load_baseline_results_from_dir(
        save_dir=p, output_type="curves", clear_bad_files=clear_bad_files)

  with futures.ThreadPoolExecutor(32) as executor:
    results = list(executor.map(load_one, paths))

  def stack(*xs):
    if isinstance(xs[0], str):
      return xs
    elif isinstance(xs[0], (onp.ndarray, int, float)):
      return onp.asarray(xs)
    else:
      raise ValueError(f"Unsupported type: {type(xs[0])}.")

  # ensure that we have the right amount of data for each.
  trimmed_results = []
  for (path, rep), res in zip(paths_reps, results):
    if len(res) < rep:
      logging.info(f"Failed to find enough results in dir {path}. "  # pylint: disable=logging-fstring-interpolation
                   f"Expected {len(res)}")
      return None
    trimmed_results.append(jax.tree_util.tree_map(stack, *res[0:rep]))
  stacked = jax.tree_util.tree_map(stack, *trimmed_results)
  return stacked

def maybe_archive_hparam_set(task_name: str, hparam_set_name: str) -> bool:
  data = maybe_get_hparam_set(task_name, hparam_set_name)
  if data is None:
    return False

  utils.write_archive(task_name, hparam_set_name, data)
  return True

@gin.configurable
def wait_until_ready_then_archive_task(task_name: str = gin.REQUIRED,
                                       hparam_set_name: str = gin.REQUIRED):
  """Continually try to create and save an archive of hparam set + task_name.

  This function is designed to be run while the baselines are being computed
  and will finish once all the baseline data has been run. By blocking in this
  function we can run all baselines and an archive job at the same time instead
  of leveraging a more sophisticated dependency system.

  Args:
    task_name: Name of task to archive
    hparam_set_name: the name of the hparam set to archive.
  """
  while True:
    r = maybe_archive_hparam_set(task_name, hparam_set_name)
    if r:
      logging.info(f"Saved success! Wrote {hparam_set_name} {task_name}.")  # pylint: disable=logging-fstring-interpolation
      return
    else:
      logging.info(f"Saved Failed! {hparam_set_name} {task_name}.")  # pylint: disable=logging-fstring-interpolation
      logging.info("Waiting 10 seconds and trying again.")
      time.sleep(10)

def main(argv):
  if len(argv) > 1:
    raise app.UsageError("Too many command-line arguments.")
  unused_dir = setup_experiment.setup_experiment(make_dir=False)

  wait_until_ready_then_archive_task()

if __name__ == "__main__":
  app.run(main)


text:
package com.hardik.javase;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/**
 * Writer Class Example
 *
 * Java FileWriter class is used to write character-oriented data to a file. It
 * is character-oriented class which is used for file handling in java.
 *
 * @author HARDIK HIRAPARA
 *
 */
public class WriterDemo {
	/**
	 * App Main Method
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		Writer writer = null;

		try {
			writer = new FileWriter("E:\\Hardik\\temp\\temp.txt");
			writer.write("I love India.");
			writer.flush();
			System.out.println("Success!");
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (writer != null)
					writer.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}


text:
class ExtensionService;

namespace extensions {
class Extension;
}

namespace content_settings {

// A content settings provider which disables certain plugins for platform apps.
class InternalExtensionProvider : public ObservableProvider,
                            public content::NotificationObserver {
 public:
  explicit InternalExtensionProvider(ExtensionService* extension_service);

  virtual ~InternalExtensionProvider();

  // ProviderInterface methods:
  virtual RuleIterator* GetRuleIterator(
      ContentSettingsType content_type,
      const ResourceIdentifier& resource_identifier,
      bool incognito) const OVERRIDE;

  virtual bool SetWebsiteSetting(
      const ContentSettingsPattern& primary_pattern,
      const ContentSettingsPattern& secondary_pattern,
      ContentSettingsType content_type,
      const ResourceIdentifier& resource_identifier,
      base::Value* value) OVERRIDE;

  virtual void ClearAllContentSettingsRules(ContentSettingsType content_type)
      OVERRIDE;

  virtual void ShutdownOnUIThread() OVERRIDE;

  // content::NotificationObserver implementation.
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;
 private:
  void SetContentSettingForExtension(const extensions::Extension* extension,
                                     ContentSetting setting);
  void SetContentSettingForExtensionAndResource(
      const extensions::Extension* extension,
      const ResourceIdentifier& resource,
      ContentSetting setting);

  OriginIdentifierValueMap value_map_;

  // Used around accesses to the |value_map_| list to guarantee thread safety.
  mutable base::Lock lock_;
  scoped_ptr<content::NotificationRegistrar> registrar_;

  DISALLOW_COPY_AND_ASSIGN(InternalExtensionProvider);
};

}  // namespace content_settings

#endif  // CHROME_BROWSER_CONTENT_SETTINGS_CONTENT_SETTINGS_INTERNAL_EXTENSION_PROVIDER_H_


text:
namespace MassTransit.RabbitMqTransport.Topology.Conventions.RoutingKey
{
    using MassTransit.Topology;

    public class RoutingKeyMessageSendTopologyConvention<TMessage> :
        IRoutingKeyMessageSendTopologyConvention<TMessage>
        where TMessage : class
    {
        IMessageRoutingKeyFormatter<TMessage> _formatter;

        public RoutingKeyMessageSendTopologyConvention(IRoutingKeyFormatter formatter)
        {
            if (formatter != null)
                SetFormatter(formatter);
        }

        bool IMessageSendTopologyConvention<TMessage>.TryGetMessageSendTopology(out IMessageSendTopology<TMessage> messageSendTopology)
        {
            if (_formatter != null)
            {
                messageSendTopology = new SetRoutingKeyMessageSendTopology<TMessage>(_formatter);
                return true;
            }

            messageSendTopology = null;
            return false;
        }

        bool IMessageSendTopologyConvention.TryGetMessageSendTopologyConvention<T>(out IMessageSendTopologyConvention<T> convention)
        {
            convention = this as IMessageSendTopologyConvention<T>;

            return convention != null;
        }

        public void SetFormatter(IRoutingKeyFormatter formatter)
        {
            _formatter = new MessageRoutingKeyFormatter<TMessage>(formatter);
        }

        public void SetFormatter(IMessageRoutingKeyFormatter<TMessage> formatter)
        {
            _formatter = formatter;
        }
    }
}