text:
import atexit
import logging.handlers
import grp
import os
import pwd
import signal
import sys
from syslog import LOG_DAEMON

# For becoming the daemon, django.utils.daemonize.become_daemon() is used.
# The additional daemon-stuff utilities follow:

def drop_privileges(user='nobody', group='nogroup'):
    """
    Drop privileges if we're superuser by changing UID/GID to given user/group.
    """
    if os.geteuid() == 0:
        # Remove group privileges
        os.setgroups([])

        if group != 'root':
            try:
                newgid = grp.getgrnam(group).gr_gid
            except KeyError:
                raise RuntimeError("System group '%s' not found." % group)

            os.setgid(newgid)
            os.setegid(newgid)

        if user != 'root':
            try:
                newuid = pwd.getpwnam(user).pw_uid
            except KeyError:
                raise RuntimeError("System user '%s' not found." % user)

            os.setuid(newuid)
            os.seteuid(newuid)

def install_termination_logging_signal_handlers():
    """
    Install the handler for every reconfigurable signal (except some
    ignorables). On signal, the event is logged and process is terminated.
    """

    # noinspection PyUnusedLocal
    def sig_handler(signum, frame):
        signames = [
            n for n, v in signal.__dict__.items()
            if n.startswith('SIG') and v == signum
        ]
        signame = signames and ' (%s)' % signames[0] or ''
        logging.info("Terminating with signal %d%s." % (signum, signame))
        sys.exit(2)     # calls exit_function

    for s in range(100):
        if s not in (signal.SIGCHLD, signal.SIGURG, signal.SIGWINCH):
            try:
                signal.signal(s, sig_handler)
            except:  # noqa
                pass

def init_syslog(level, process_ident, address='/dev/log', facility=LOG_DAEMON):
    """
    Set the root logger to be directed to syslog from the given level
    and with given ident string (which will get prepended to every message).
    """
    logging.root.setLevel(level)
    if len(logging.root.handlers) == 0:
        fmt = '%s %%(levelname)s: %%(message)s' % process_ident
        hdlr = logging.handlers.SysLogHandler(address, facility)
        hdlr.setFormatter(logging.Formatter(fmt))
        logging.root.addHandler(hdlr)

def setup_pidfile(pidfile_path):
    """
    Fails if there is something at the given path. Otherwise, writes
    the current PID to file at that path. Also sets the atexit
    handler to automatically remove the file upon exit.

    Note: The process needs to have file removing privileges in the end.
    """
    def exit_function(pidfile_path_):
        try:
            logging.debug("Removing PID file %s." % pidfile_path_)
            os.unlink(pidfile_path_)
        except:  # noqa
            logging.error("Cannot remove PID file %s." % pidfile_path_)

    if os.path.exists(pidfile_path):
        logging.error("Pid file %s exists, aborting daemonization. "
                      "Please assure that I'm not already running." % pidfile_path)
        sys.exit(3)

    atexit.register(exit_function, pidfile_path)
    open(pidfile_path, 'w').write('%d\n' % os.getpid())


text:
@implementation History

@dynamic channel;
@dynamic message;
@dynamic time;
@dynamic nickname;
@dynamic server;

@end

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.curso.basico.nio;

import java.io.IOException;
import static java.lang.System.out;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;
import static java.util.Arrays.asList;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;

/**
 *
 * @author usuario
 */
public class Nio2Demo {

    private static final String FILEINPUT = "texto";
    private static final String FILEOUTPUT = "otro";
    private static final String TESTFILE = "test.txt";

    public static void fileSystems() {
        FileSystem fs = FileSystems.getDefault();
        System.out.println("Solo lectura: " + fs.isReadOnly());
        System.out.println("Separador: " + fs.getSeparator());
        System.out.println("\nFileStores");
        fs.getFileStores().forEach(Nio2Demo::detalle);
        System.out.println("\nUnidades");
        fs.getRootDirectories().forEach(out::println);
    }

    private static void detalle(FileStore store) {
        try {
            String desc = store.toString();
            String tipo = store.type();
            long espacioTotal = store.getTotalSpace();
            long espacioSinAsignar = store.getUnallocatedSpace();
            long espacioLibre = store.getUsableSpace();
            System.out.println(desc + ", Total: " + espacioTotal
                    + ", sin asignar: " + espacioSinAsignar
                    + ", Disponible: " + espacioLibre);
        } catch (IOException ex) {
            Logger.getLogger(Nio2Demo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void paths() {
        Path p = FileSystems.getDefault().getPath(FILEINPUT);
        System.out.println("Detalles del path: " + p);
        int contador = p.getNameCount();
        System.out.println("Elementos: " + contador);
        for (int i = 0; i < contador; i++) {
            Path nombre = p.getName(i);
            System.out.println("Nombre en posición " + i + " es " + nombre);
        }
        Path ancestro = p.getParent();
        Path raiz = p.getRoot();
        Path nombreArchivo = p.getFileName();
        System.out.println("Ancestro: " + ancestro + ", Raíz: " + raiz
                + ", Nombre del archivo: " + nombreArchivo);
        System.out.println("El path es absoluto: " + p.isAbsolute());
    }

    public static void crearArchivo() {
        Path p1 = Paths.get(TESTFILE);
        try {
            Files.createFile(p1);
            System.out.format("Archivo creado: %s%n", p1.toRealPath());
        } catch (FileAlreadyExistsException e) {
            System.out.format("El archivo %s ya existe.%n",
                    p1.normalize());
        } catch (NoSuchFileException ex) {
            System.out.format("El directorio %s no existe.%n",
                    p1.normalize().getParent());
        } catch (IOException ex) {
            Logger.getLogger(Nio2Demo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void borrarArchivo() {
        Path p = Paths.get(TESTFILE);
        try {
            Files.delete(p);
            System.out.println(p + " borrado.");
        } catch (NoSuchFileException e) {
            System.out.println(p + " not existe.");
        } catch (DirectoryNotEmptyException ex) {
            System.out.println("El directorio " + p + " no está vacío.");
        } catch (IOException ex) {
            Logger.getLogger(Nio2Demo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void leerContenido() {
        Charset cs = Charset.forName("UTF-8");
        Path origen = Paths.get(FILEINPUT);
        try {
//            List<String> lines = Files.readAllLines(source, StandardCharsets.UTF_8);
            List<String> lines = Files.readAllLines(origen, cs);
            lines.forEach(out::println);
        } catch (NoSuchFileException e) {
            System.out.println(origen.toAbsolutePath() + " no existe.");
        } catch (IOException ex) {
            Logger.getLogger(Nio2Demo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void leerContenidoLazy(String palabra) {
        Objects.requireNonNull(palabra, "La palabra buscada no puede set nula");
        try (Stream<String> s = Files.lines(Paths.get(FILEINPUT))) {
            String str = s.filter(linea -> linea.contains(palabra))
                    .onClose(() -> System.out.println("Archivo cerrado"))
                    .findFirst()
                    .map(linea -> "Esta línea \"" + linea + "\" contiene la palabra dos")
                    .orElse("La palabra \"" + palabra + "\" no se encuentra");
            System.out.println("Resultado de la búsqueda: " + str);
        } catch (IOException ex) {
            Logger.getLogger(Nio2Demo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void escribirContenido() {
        List<String> texto = asList("seis", "siete", "ocho", "nueve", "diez");
        Path destino = Paths.get(FILEOUTPUT);
        try {
            Path p = Files.write(destino, texto, StandardCharsets.UTF_8, WRITE, CREATE);
            System.out.println("Se ha escrito en " + p.toAbsolutePath());
        } catch (IOException ex) {
            Logger.getLogger(Nio2Demo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


text:
<!DOCTYPE html>

<?php
session_start();
require_once('../mysql_connect.php');
$currentEmployeeNum = $_SESSION['emp_number'];
if(isset($_POST['link'])){
	$formNum = $_POST['link'];
}
if(isset($_POST['submit'])){
	$formNum = $_POST['submit'];
}
$currentDate = date('Y-m-d');
//Getting Employees who has pending absent reversal
$queryForEmployees="SELECT 	*
							FROM 	APPLICANTS A JOIN 	EMPLOYEES E ON A.APPNO = E.APPNO
												 JOIN	MANPOWER M ON E.EMPLOYEENUMBER = M.EMPLOYEENUMBER
						   WHERE 	M.FORMNUMBER = '{$formNum}'";
$result=mysqli_query($dbc,$queryForEmployees);
$rows=mysqli_fetch_array($result,MYSQLI_ASSOC);
$names = $rows['FIRSTNAME'].' '.$rows['LASTNAME'];
$dateFiled = $rows['DATE'];
$dateNeeded = $rows['DATENEEDED'];
$reason = $rows['REASON'];
$empNum = $rows['EMPLOYEENUMBER'];
$position = $rows['POSITION'];
$department = $rows['DEPARTMENT'];
$description = $rows['JOBDESCRIPTION'];
$ageStart = $rows['AGESTART'];
$ageEnd = $rows['AGEEND'];
$education = $rows['EDUCATION'];

//Getting Actual Position from Position code
//get all actual position
$queryForActualPosition="SELECT 	*
							FROM 	emp_positions";
$resultP=mysqli_query($dbc,$queryForActualPosition);
while($rows=mysqli_fetch_array($resultP,MYSQLI_ASSOC))
{
	$actualPos[] = $rows['EPOSITION'];
	$codePos[] = $rows['POSITION'];
}
//create array containing actual position
$positionName = "";
for ($x=0;$x<count($actualPos);$x++)
{
	if($position==$codePos[$x])
	{
		$positionName = $actualPos[$x];
	}
}
$queryForActualDepartment="SELECT 	*
							FROM 	emp_dept";
$resultD=mysqli_query($dbc,$queryForActualDepartment);
while($rows=mysqli_fetch_array($resultD,MYSQLI_ASSOC))
{
	$actualDept[] = $rows['EDEPT'];
	$codeDept[] = $rows['DEPT'];
}
$deptName = "";
for ($x=0;$x<count($actualDept);$x++)
{
	if($department==$codeDept[$x])
	{
		$deptName = $actualDept[$x];
	}
}

if (isset($_POST['submit'])){
	$message=NULL;

	if (empty($_POST['HRremarks'])){
		$remarks=NULL;
		$message.='
You forgot to enter the time reversal!';
	}else
		$remarks=$_POST['HRremarks'];

if(!isset($message)){
require_once('../mysql_connect.php');
$query="UPDATE 	manpower
		   SET	HRREMARKS = '{$remarks}', HRAPPROVERID = '{$currentEmployeeNum}', HRAPPROVEDDATE = '{$currentDate}'
		 WHERE	FORMNUMBER = '{$formNum}' ";
$result=mysqli_query($dbc,$query);

echo "

  		Success! Timetable Updated!

";
									}
}

if (isset($message)){
	echo ''.$message. '';
}
?>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/morris.css">

    <link rel="stylesheet" href="css/custom.css">
    <link rel="stylesheet" href="css/custom-theme.css">

    <title>Manpower Request</title>

Logout

Welcome!

HR Manager

                 Home

                 Recruitment

                 Employees

				 Attendance

				 Calendar

                     Reports

                         &#x25cf Leave
                         &#x25cf Overtime
                         &#x25cf Undertime
                         &#x25cf Absent Reversal
                        &#x25cf Itinerary Authorization

                     Visual Reports

                         &#x25cf Employee Tardiness
                         &#x25cf Employee Tenure
                         &#x25cf Manpower Architects
                         &#x25cf Manpower Engineers
                        &#x25cf Recruitment Newly Hired

                     Requests

                         &#x25cf Leave
                         &#x25cf Overtime
                         &#x25cf Undertime
                         &#x25cf Absent Reversal
                        &#x25cf Itinerary Authorization
                         &#x25cf Manpower
                         &#x25cf Resignation
                        &#x25cf Change Record

                 About

Detailed Manpower Request

                              <form id="wizard-validation-form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

											 Position

												<?php echo $positionName?>

											 Department

												<?php echo $deptName?>

											Date Needed

												<?php echo $dateNeeded?>

											Age Bracket

													<?php echo $ageStart?>

													<?php echo $ageEnd?>

											Education

													<?php echo $education?>

											Job Description

												<?php echo $description?>

											Reason for Request

													<?php echo $reason?>

											HR Manager Remarks

													<input type="text" name="HRremarks" class="form-control">

												<button class="btn btn-success" type="submit" name="submit" value="<?php echo $formNum?>">Approve</button>

												<button class="btn btn-danger"  name="reject" >Reject</button>

                              </form>


text:
using System;
class chapter05_03_02
{
	public static void Main(string [] args)
	{
		int countstar = 5;
		int countline = 5;

		do
		{
			do
			{
				Console.Write("* ");
				countstar--;
			}while(countstar > 0);

			Console.WriteLine();
			countline--;
			countstar = countline;
		}while(countline > 0);
	}
}


text:
package com.helger.dao.wal;

import javax.annotation.Nonnull;

import com.helger.commons.callback.ICallback;
import com.helger.commons.id.IHasID;

/**
 * Callback interface for DAO stuff
 *
 * @author Philip Helger
 * @param <INTERFACETYPE>
 *        DAO manager interface type
 */
public interface IDAOChangeCallback <INTERFACETYPE extends IHasID <String>> extends ICallback
{
  /**
   * Called after a new item was created.
   *
   * @param aNewItem
   *        The newly created item. Never null.
   */
  default void onCreateItem (@Nonnull final INTERFACETYPE aNewItem)
  {}

  /**
   * Called after an item was updated.
   *
   * @param aItem
   *        The updated item. Never null.
   */
  default void onUpdateItem (@Nonnull final INTERFACETYPE aItem)
  {}

  /**
   * Called after an item was removed.
   *
   * @param aItem
   *        The removed item. Never null.
   */
  default void onDeleteItem (@Nonnull final INTERFACETYPE aItem)
  {}

  /**
   * Called after an item was marked as deleted (but is still present - special
   * case of update!).
   *
   * @param aItem
   *        The item that was marked as deleted. Never null.
   */
  default void onMarkItemDeleted (@Nonnull final INTERFACETYPE aItem)
  {}

  /**
   * Called after an item was marked as undeleted.
   *
   * @param aItem
   *        The item that was marked as not deleted anymore. Never
   *        null.
   */
  default void onMarkItemUndeleted (@Nonnull final INTERFACETYPE aItem)
  {}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1"/>

  <title>Champagne</title>
  <meta name="author" content="" />
  <meta name="description"
        content="Champagne é uma divertida comédia dramática que esbanja críticas à alta sociedade. Em seu núcleo está a figura carismática e intensa de Betty Balfour, que faz, conforme o IMDB, “The Girl”...."/>

  <meta name="yandex-verification" content="48a8210fc043c5e8" />

  <meta name="generator" content="Hugo 0.54.0" />

  <meta itemprop="name" content="Champagne"/>
  <meta itemprop="description"
        content="Champagne é uma divertida comédia dramática que esbanja críticas à alta sociedade. Em seu núcleo está a figura carismática e intensa de Betty Balfour, que faz, conforme o IMDB, “The Girl”...."/>
  <meta itemprop="image"
        content="/img/logo.svg"/>

  <meta property="og:title" content="Champagne"/>
  <meta property="og:type"
        content="article"/>
  <meta property="og:url" content="http://www.cinetenisverde.com.br/champagne/"/>
  <meta property="og:image"
        content="/img/logo.svg"/>
  <meta property="og:description"
        content="Champagne é uma divertida comédia dramática que esbanja críticas à alta sociedade. Em seu núcleo está a figura carismática e intensa de Betty Balfour, que faz, conforme o IMDB, “The Girl”...."/>
  <meta property="og:site_name" content="Cine Tênis Verde"/>
  <meta property="article:published_time"
        content="2017-01-18T00:00:00+00:00"/>
  <meta property="article:section" content="post"/>

  <meta name="twitter:card" content="summary"/>
  <meta name="twitter:site"
        content=""/>
  <meta name="twitter:title" content="Champagne"/>
  <meta name="twitter:description"
        content="Champagne é uma divertida comédia dramática que esbanja críticas à alta sociedade. Em seu núcleo está a figura carismática e intensa de Betty Balfour, que faz, conforme o IMDB, “The Girl”...."/>
  <meta name="twitter:creator"
        content=""/>
  <meta name="twitter:image:src"
        content="/img/logo.svg"/>

  <link rel="stylesheet" type="text/css" href="/css/capsule.min.css"/>
  <link rel="stylesheet" type="text/css" href="/css/custom.css"/>

  <link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/>
  <link rel="icon" href="/img/favicon.ico"/>

 Cine Tênis Verde

    <input type="checkbox" id="navbar-burger-state"/>

      search

      twitter

      rss

Champagne

    ★★★★☆

 Wanderley Caloni, January 18, 2017

Champagne é uma divertida comédia dramática que esbanja críticas à alta sociedade. Em seu núcleo está a figura carismática e intensa de Betty Balfour, que faz, conforme o IMDB, “The Girl”. Em torno dela orbitam as pessoas comuns, que a veem como excêntrica. Mas, tudo bem, já que seu pai é rico. Mesmo se vestindo de empregada ela diverte e se diverte.

As expressões de Betty são as melhores partes do filme. Ela está sempre presente, e vê-la com toda sua energia gera hoje um sentimento melancólico a respeito de tão bons atores da geração do cinema mudo que se perderam. O estilo desse cinema é específico, e as atuações, quando migradas para o cinema falado, raramente funcionavam (O Artista é um filme que conta sobre esse trauma em Hollywood). Porém, Betty aqui brilha, e brilha mais quanto mais caricatas são suas expressões, seu jeito de arquejar os ombros, o olhar ao mesmo tempo doce e divertido. Ela está apenas tendo uma vida boa.

Você conhece pessoas assim. Extrovertidos no coração. Betty é uma delas, e até seus relacionamentos são uma fonte de diversão. Ela flerta com um senhor mais velho enquanto está apaixonada pelo mocinho mais novo. Ela gosta de correr pelo convés do navio onde participa de todas as festas glamorosas (ainda que ligeiramente bêbada pelo balanço do mar). Ela quando vê o pai com olhar preocupado consegue apenas fazer chacota. Ainda assim, ela recebe com uma certa tristeza a notícia de que seu pai está quebrado, e que agora ela terá que se virar como classe trabalhadora.

Ainda assim, a história de Walter C. Mycroft roteirizada por Alfred Hitchcock não estabelece limites para a diversão da garota. Como uma versão feminina de Carlitos, sua força não reside em seu dinheiro, mas em seu espírito. As reviravoltas do roteiro apenas confirmam isso, pois há uma dança de revelações a respeito dos personagens que parecem pouco importar para a garota.

E por outro lado, o diretor Alfred Hitchcock parece se divertir também imensamente. Ele faz transições com toalhas e começa e termina o filme mostrando a trucagem que criou: um ultra-zoom de uma taça de champanhe que mostra o que a pessoa que está bebendo está vendo enquanto bebe. Melhor utilizada em filmes de crime, aqui o artifício funciona justamente por conta da pista que revela sobre o inesperado final.

Hitchcock começa a se especializar em zombar da classe alta. Em determinado momento ele usa o cinema mudo ao seu favor, quando um cliente ricaço lê o cardápio e faz um gesto pedindo o prato. Esse gesto é repetido e repassado por quatro pessoas ao seu redor, como uma forma de comunicação. E logo no começo, quando o pai da moça pressiona todos os botões ao seu dispor em sua mesa, vemos pessoas correndo em fila em sua direção. A criatividade do diretor é sempre usada para estabelecer os ricos, ou pelo menos os multimilionários corporativistas, como criaturas grotescas e hilárias em suas caricaturas.

A mensagem do filme é tão difusa quanto sua protagonista. Não há muito mais personagens do que Betty Balfour. E guarde esse nome para sua próxima festa. Seja como ricaça ou cortesã, com certeza ela fará um enorme sucesso e se divertirá à beça.

           Imagens e créditos no IMDB.

    ★★★★☆

 Champagne ● Champagne. Champagne (UK, 1928). Dirigido por Alfred Hitchcock. Escrito por Alfred Hitchcock, Walter C. Mycroft, Eliot Stannard. Com Betty Balfour (The Girl), Jean Bradin (The Boy), Ferdinand von Alten (The Man), Gordon Harker (The Father), Alexander D'Arcy, Vivian Gibson, Clifford Heatherley (The Manager), Claude Hulbert (Club Guest), Hannah Jones (Club Servant). ● Nota: 4/5. Categoria: movies.  Publicado em 2017-01-18.  Texto escrito por Wanderley Caloni.

Quer comentar?

      Share


text:
require File.expand_path('../../../spec_helper', __FILE__)

describe "Resolv#getnames" do
  before(:all) do
    require 'resolv'
  end

  it "resolves 127.0.0.1" do
    res = Resolv.new([Resolv::Hosts.new])

    names = nil

    lambda {
      names = res.getnames("127.0.0.1")
    }.should_not raise_error(Resolv::ResolvError)

    names.should_not == nil
    names.size.should > 0
  end
end


text:
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const Box = styled.div`
  background-color: ${(props) => props.bg};
`;

Box.propTypes = {
  bg: PropTypes.string,
};

export const MyBox = (props) => <Box {...props} />;

MyBox.propTypes = {
  bg: PropTypes.string,
};

export const component = MyBox;


text:
package org.projectfloodlight.openflow.protocol.ver13;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import org.jboss.netty.buffer.ChannelBuffer;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;

class OFOxmMplsBosVer13 implements OFOxmMplsBos {
    private static final Logger logger = LoggerFactory.getLogger(OFOxmMplsBosVer13.class);
    // version: 1.3
    final static byte WIRE_VERSION = 4;
    final static int LENGTH = 5;

        private final static OFBooleanValue DEFAULT_VALUE = OFBooleanValue.FALSE;

    // OF message fields
    private final OFBooleanValue value;
//
    // Immutable default instance
    final static OFOxmMplsBosVer13 DEFAULT = new OFOxmMplsBosVer13(
        DEFAULT_VALUE
    );

    // package private constructor - used by readers, builders, and factory
    OFOxmMplsBosVer13(OFBooleanValue value) {
        if(value == null) {
            throw new NullPointerException("OFOxmMplsBosVer13: property value cannot be null");
        }
        this.value = value;
    }

    // Accessors for OF message fields
    @Override
    public long getTypeLen() {
        return 0x80004801L;
    }

    @Override
    public OFBooleanValue getValue() {
        return value;
    }

    @Override
    public MatchField<OFBooleanValue> getMatchField() {
        return MatchField.MPLS_BOS;
    }

    @Override
    public boolean isMasked() {
        return false;
    }

    public OFOxm<OFBooleanValue> getCanonical() {
        // exact match OXM is always canonical
        return this;
    }

    @Override
    public OFBooleanValue getMask()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property mask not supported in version 1.3");
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_13;
    }

    public OFOxmMplsBos.Builder createBuilder() {
        return new BuilderWithParent(this);
    }

    static class BuilderWithParent implements OFOxmMplsBos.Builder {
        final OFOxmMplsBosVer13 parentMessage;

        // OF message fields
        private boolean valueSet;
        private OFBooleanValue value;

        BuilderWithParent(OFOxmMplsBosVer13 parentMessage) {
            this.parentMessage = parentMessage;
        }

    @Override
    public long getTypeLen() {
        return 0x80004801L;
    }

    @Override
    public OFBooleanValue getValue() {
        return value;
    }

    @Override
    public OFOxmMplsBos.Builder setValue(OFBooleanValue value) {
        this.value = value;
        this.valueSet = true;
        return this;
    }
    @Override
    public MatchField<OFBooleanValue> getMatchField() {
        return MatchField.MPLS_BOS;
    }

    @Override
    public boolean isMasked() {
        return false;
    }

    @Override
    public OFOxm<OFBooleanValue> getCanonical()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property canonical not supported in version 1.3");
    }

    @Override
    public OFBooleanValue getMask()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property mask not supported in version 1.3");
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_13;
    }

        @Override
        public OFOxmMplsBos build() {
                OFBooleanValue value = this.valueSet ? this.value : parentMessage.value;
                if(value == null)
                    throw new NullPointerException("Property value must not be null");

                //
                return new OFOxmMplsBosVer13(
                    value
                );
        }

    }

    static class Builder implements OFOxmMplsBos.Builder {
        // OF message fields
        private boolean valueSet;
        private OFBooleanValue value;

    @Override
    public long getTypeLen() {
        return 0x80004801L;
    }

    @Override
    public OFBooleanValue getValue() {
        return value;
    }

    @Override
    public OFOxmMplsBos.Builder setValue(OFBooleanValue value) {
        this.value = value;
        this.valueSet = true;
        return this;
    }
    @Override
    public MatchField<OFBooleanValue> getMatchField() {
        return MatchField.MPLS_BOS;
    }

    @Override
    public boolean isMasked() {
        return false;
    }

    @Override
    public OFOxm<OFBooleanValue> getCanonical()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property canonical not supported in version 1.3");
    }

    @Override
    public OFBooleanValue getMask()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property mask not supported in version 1.3");
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_13;
    }

//
        @Override
        public OFOxmMplsBos build() {
            OFBooleanValue value = this.valueSet ? this.value : DEFAULT_VALUE;
            if(value == null)
                throw new NullPointerException("Property value must not be null");

            return new OFOxmMplsBosVer13(
                    value
                );
        }

    }

    final static Reader READER = new Reader();
    static class Reader implements OFMessageReader<OFOxmMplsBos> {
        @Override
        public OFOxmMplsBos readFrom(ChannelBuffer bb) throws OFParseError {
            // fixed value property typeLen == 0x80004801L
            int typeLen = bb.readInt();
            if(typeLen != (int) 0x80004801)
                throw new OFParseError("Wrong typeLen: Expected=0x80004801L(0x80004801L), got="+typeLen);
            OFBooleanValue value = OFBooleanValue.of(bb.readByte() != 0);

            OFOxmMplsBosVer13 oxmMplsBosVer13 = new OFOxmMplsBosVer13(
                    value
                    );
            if(logger.isTraceEnabled())
                logger.trace("readFrom - read={}", oxmMplsBosVer13);
            return oxmMplsBosVer13;
        }
    }

    public void putTo(PrimitiveSink sink) {
        FUNNEL.funnel(this, sink);
    }

    final static OFOxmMplsBosVer13Funnel FUNNEL = new OFOxmMplsBosVer13Funnel();
    static class OFOxmMplsBosVer13Funnel implements Funnel<OFOxmMplsBosVer13> {
        private static final long serialVersionUID = 1L;
        @Override
        public void funnel(OFOxmMplsBosVer13 message, PrimitiveSink sink) {
            // fixed value property typeLen = 0x80004801L
            sink.putInt((int) 0x80004801);
            message.value.putTo(sink);
        }
    }

    public void writeTo(ChannelBuffer bb) {
        WRITER.write(bb, this);
    }

    final static Writer WRITER = new Writer();
    static class Writer implements OFMessageWriter<OFOxmMplsBosVer13> {
        @Override
        public void write(ChannelBuffer bb, OFOxmMplsBosVer13 message) {
            // fixed value property typeLen = 0x80004801L
            bb.writeInt((int) 0x80004801);
            bb.writeByte(message.value.getInt());

        }
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFOxmMplsBosVer13(");
        b.append("value=").append(value);
        b.append(")");
        return b.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        OFOxmMplsBosVer13 other = (OFOxmMplsBosVer13) obj;

        if (value == null) {
            if (other.value != null)
                return false;
        } else if (!value.equals(other.value))
            return false;
        return true;
    }

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

        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }

}


text:
class CreateEnvironments < ActiveRecord::Migration
  def change
    create_table :environments do |t|
      t.references :user
      t.foreign_key :users, on_delete: :cascade, on_update: :cascade
      t.string :name
      t.string :url
      t.boolean :default

      t.timestamps null: false
    end
  end
end


text:
/*
 * Non-callback-based SWIG wrapper for
 * parsing Byfl binary output files
 *
 * By Scott Pakin <pakin@lanl.gov>
 */

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <inttypes.h>
#include <pthread.h>
#include <bfbin.h>
#include <bfbin-swig.h>

/* Abort the parsing thread. */
static void abort_parsing_thread (parse_state_t *lstate, const char *message)
{
  lstate->data.item_type = ERROR;
  lstate->data.string = strdup(message);
  (void) pthread_exit(NULL);
}

/* Transmit data from the library to the SWIG-invoked thread.  Invoke
 * abort_parsing_thread() on error. */
static void transfer_data (parse_state_t *lstate)
{
  if (write(lstate->channel[1], &lstate->data, sizeof(table_item_t)) != sizeof(table_item_t))
    abort_parsing_thread(lstate, "Failed to send data between threads");
}

/* Clear the previous data. */
static void clear_data (table_item_t *data)
{
  memset((void *) data, 0, sizeof(table_item_t));
}

/* Return a nullary value to the SWIG-invoked thread. */
static void return_null_value (parse_state_t *lstate, int item_type)
{
  clear_data(&lstate->data);
  lstate->data.item_type = item_type;
  transfer_data(lstate);
}

/* Return a string value to the SWIG-invoked thread. */
static void return_string_value (parse_state_t *lstate, int item_type, const char *value)
{
  clear_data(&lstate->data);
  lstate->data.item_type = item_type;
  lstate->data.string = strdup(value);
  transfer_data(lstate);
}

/* Return an unsigned 64-bit integer value to the SWIG-invoked thread. */
static void return_integer_value (parse_state_t *lstate, int item_type, uint64_t value)
{
  clear_data(&lstate->data);
  lstate->data.item_type = item_type;
  lstate->data.integer = (unsigned long) value;
  transfer_data(lstate);
}

/* Return a Boolean as an unsigned 8-bit integer value to the SWIG-invoked thread. */
static void return_boolean_value (parse_state_t *lstate, int item_type, uint8_t value)
{
  clear_data(&lstate->data);
  lstate->data.item_type = item_type;
  lstate->data.boolean = (int)value;
  transfer_data(lstate);
}

/* Callback for table_begin_basic_cb */
static void begin_basic_table (void *state, const char *name)
{
  return_string_value((parse_state_t *)state, TABLE_BEGIN_BASIC, name);
}

/* Callback for table_end_basic_cb */
static void end_basic_table (void *state)
{
  return_null_value((parse_state_t *)state, TABLE_END_BASIC);
}

/* Callback for table_begin_keyval_cb */
static void begin_keyval_table (void *state, const char *name)
{
  return_string_value((parse_state_t *)state, TABLE_BEGIN_KEYVAL, name);
}

/* Callback for table_end_keyval_cb */
static void end_keyval_table (void *state)
{
  return_null_value((parse_state_t *)state, TABLE_END_KEYVAL);
}

/* Callback for column_begin_cb */
static void begin_column (void *state)
{
  return_null_value((parse_state_t *)state, COLUMN_BEGIN);
}

/* Callback for column_uint64_cb */
static void column_integer_type (void *state, const char *name)
{
  return_string_value((parse_state_t *)state, COLUMN_UINT64, name);
}

/* Callback for column_string_cb */
static void column_string_type (void *state, const char *name)
{
  return_string_value((parse_state_t *)state, COLUMN_STRING, name);
}

/* Callback for column_bool_cb */
static void column_boolean_type (void *state, const char *name)
{
  return_string_value((parse_state_t *)state, COLUMN_BOOL, name);
}

/* Callback for column_end_cb */
static void end_column (void *state)
{
  return_null_value((parse_state_t *)state, COLUMN_END);
}

/* Callback for row_begin_cb */
static void begin_row (void *state)
{
  return_null_value((parse_state_t *)state, ROW_BEGIN);
}

/* Callback for row_uint64_cb */
static void row_integer_type (void *state, uint64_t value)
{
  return_integer_value((parse_state_t *)state, DATA_UINT64, value);
}

/* Callback for row_string_cb */
static void row_string_type (void *state, const char *value)
{
  return_string_value((parse_state_t *)state, DATA_STRING, value);
}

/* Callback for row_bool_cb */
static void row_boolean_type (void *state, uint8_t value)
{
  return_boolean_value((parse_state_t *)state, DATA_BOOL, value);
}

/* Callback for row_end_cb */
static void end_row (void *state)
{
  return_null_value((parse_state_t *)state, ROW_END);
}

/* Callback for error_cb */
static void handle_parse_error (void *state, const char *message)
{
  return_string_value((parse_state_t *)state, ERROR, message);
}

/* Thread entry point for invoking bf_process_byfl_file() in a
 * separate thread. */
static void *parse_byfl_file (void *state)
{
  bfbin_callback_t callback_list;

  /* Prepare a callback list. */
  parse_state_t *lstate = (parse_state_t *)state;
  memset(&callback_list, 0, sizeof(bfbin_callback_t));
  callback_list.error_cb = handle_parse_error;
  callback_list.table_begin_basic_cb = begin_basic_table;
  callback_list.table_end_basic_cb = end_basic_table;
  callback_list.table_begin_keyval_cb = begin_keyval_table;
  callback_list.table_end_keyval_cb = end_keyval_table;
  callback_list.column_begin_cb = begin_column;
  callback_list.column_uint64_cb = column_integer_type;
  callback_list.column_string_cb = column_string_type;
  callback_list.column_bool_cb = column_boolean_type;
  callback_list.column_end_cb = end_column;
  callback_list.row_begin_cb = begin_row;
  callback_list.data_uint64_cb = row_integer_type;
  callback_list.data_string_cb = row_string_type;
  callback_list.data_bool_cb = row_boolean_type;
  callback_list.row_end_cb = end_row;

  /* Announce that we're ready to go. */
  return_string_value((parse_state_t *)state, FILE_BEGIN, lstate->filename);

  /* Invoke the Byfl library function to parse the entire file. */
  bf_process_byfl_file(lstate->filename, &callback_list, state, lstate->patient);

  /* Indicate that we've finished parsing. */
  return_null_value(lstate, FILE_END);
  return NULL;
}

/* Create, initialize, and return new parsing state.  Return NULL on
 * failure. */
parse_state_t *bf_open_byfl_file (const char *byfl_filename, int live_data)
{
  parse_state_t *state;

  /* Allocate parse state. */
  state = (parse_state_t *) malloc(sizeof(parse_state_t));
  if (!state)
    return NULL;
  memset((void *) state, 0, sizeof(parse_state_t));

  /* Initialize the state. */
  if (pipe(state->channel) == -1)
    return NULL;
  state->filename = strdup(byfl_filename);
  state->data.item_type = FILE_BEGIN;    /* Must be anything other than ERROR or FILE_END, or bf_read_byfl_item will lock onto that. */
  state->patient = live_data;

  /* Process the file in the background. */
  if (pthread_create(&state->tid, NULL, parse_byfl_file, state) != 0) {
    free(state->filename);
    free(state);
    return NULL;
  }
  return state;
}

/* Block until the library thread returns data then return a copy of
 * that to the caller. */
table_item_t bf_read_byfl_item (parse_state_t *lstate)
{
  static table_item_t result = {0};   /* Copy of the data to return */

  /* Free the *previous* string value, if any, now that we no longer
   * need it. */
  if (result.string != NULL) {
    free((void *) result.string);
    result.string = NULL;
  }

  /* Wait for data from the library thread then return it. */
  if (read(lstate->channel[0], &result, sizeof(table_item_t)) != sizeof(table_item_t)) {
    clear_data(&result);
    result.item_type = ERROR;
    result.string = strdup("pthread_barrier_wait() failed");
  }
  return result;
}

/* Free resources that were needed for parsing. */
void bf_close_byfl_file (parse_state_t *lstate)
{
  (void) pthread_cancel(lstate->tid);  /* It's not an error if the thread already exited. */
  (void) close(lstate->channel[0]);
  (void) close(lstate->channel[1]);
  clear_data(&lstate->data);
  free((void *)lstate->filename);
  free((void *)lstate);
}


text:
package com.cloudcoders.gestaca.model;

public abstract class Person {
  private int zip;
  private String address;
  private String id;
  private String name;

  public Person(int zip, String address, String id, String name) {
    this.zip = zip;
    this.address = address;
    this.id = id;
    this.name = name;
  }

  public int getZip() {
    return zip;
  }

  public String getAddress() {
    return address;
  }

  public String getId() {
    return id;
  }

  public String getName() {
    return name;
  }

}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>changeImageOnSelect </title>

Change image on select change - demo using addEventListener()

change option to change image

					<select name="select-product">
						<option value="https://picsum.photos/id/238/200/300">Option 1</option>
						<option value="https://picsum.photos/id/239/200/300">Option 2</option>
					</select>

change option to change image

					<select name="select-product">
						<option value="https://picsum.photos/id/100/200/300">Option 1</option>
						<option value="https://picsum.photos/id/101/200/300">Option 2</option>
					</select>


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

namespace RimTrans.Framework.Step2 {
    class Program {
        static void Main(string[] args) {
            Console.OutputEncoding = Encoding.Unicode;
            string configFile = "Config.xml";
            if (File.Exists(configFile)) {
                XDocument configDoc = XDocument.Load(configFile);
                string frameworkPath = configDoc.Root.Element("FrameworkPath").Value;
                string modPath = configDoc.Root.Element("ModPath").Value;
                string language = configDoc.Root.Element("Language").Value;
                bool overrideMode = true;
                bool autoTranslateNicks = true;
                bool autoCommentInvalidFields = true;
                bool trimFields = true;
                XElement step2 = configDoc.Root.Element("Step2");
                if (step2 != null) {
                    XElement overrideModeEle = step2.Element("OverrideMode");
                    if (overrideModeEle != null && overrideModeEle.Value.ToLower() == "true")
                        overrideMode = true;
                    XElement autoTranslateNicksEle = step2.Element("OverrideMode");
                    if (autoTranslateNicksEle != null && autoTranslateNicksEle.Value.ToLower() == "true")
                        autoTranslateNicks = true;
                    XElement autoCommentInvalidFieldsEle = step2.Element("OverrideMode");
                    if (autoCommentInvalidFieldsEle != null && autoCommentInvalidFieldsEle.Value.ToLower() == "true")
                        autoCommentInvalidFields = true;
                    XElement trimFieldsEle = step2.Element("TrimFields");
                    if (trimFieldsEle != null && trimFieldsEle.Value.ToLower() == "true")
                        trimFields = true;
                }
                if (!Directory.Exists(frameworkPath)) {
                    Console.Write($"[ERROR] '{frameworkPath}' no found.");
                } else if (!Directory.Exists(modPath)) {
                    Console.Write($"[ERROR] '{modPath}' no found.");
                } else {
                    Generate(frameworkPath, modPath, language, overrideMode, autoTranslateNicks, autoCommentInvalidFields, trimFields);
                }
                Console.Write("[Completed] Press any key to exit.");
                Console.ReadKey();
            } else {
                Console.Write("[ERROR] Config.xml no found.");
                Console.ReadKey();
            }
        }

        static void Generate(string frameworkPath, string modPath, string language, bool overrideMode, bool autoTranslateNicks, bool autoCommentInvalidFields, bool trimFields) {
            Console.WriteLine("Please wait...");
            string sourcePath = Path.Combine(modPath, "Source", language);
            XDocument map_Last = XDocument.Load(Path.Combine(sourcePath, "SolidNames_Last.xml"));
            XDocument map_First_Male = XDocument.Load(Path.Combine(sourcePath, "SolidNames_First_Male.xml"));
            XDocument map_First_Female = XDocument.Load(Path.Combine(sourcePath, "SolidNames_First_Female.xml"));
            XDocument map_First_Either = XDocument.Load(Path.Combine(sourcePath, "SolidNames_First_Either.xml"));
            XDocument uniqueNames = XDocument.Load(Path.Combine(sourcePath, "SolidNames_Unique.xml"));

            XDocument solidNamesDoc_Framework = XDocument.Load(Path.Combine(frameworkPath, "Languages", "English", "DefInjected", "SolidNameDef", "SolidNames.xml"), LoadOptions.PreserveWhitespace);

            string solidNamesPath_Mod = Path.Combine(modPath, "Languages", language, "DefInjected", "SolidNameDef", "SolidNames.xml");
            XDocument solidNamesDoc_Mod = XDocument.Load(solidNamesPath_Mod);
            Merge(solidNamesDoc_Framework, solidNamesDoc_Mod, autoCommentInvalidFields);

            MassTransByMap(solidNamesDoc_Framework, map_Last);
            MassTransByMap(solidNamesDoc_Framework, map_First_Male);
            MassTransByMap(solidNamesDoc_Framework, map_First_Female);
            MassTransByMap(solidNamesDoc_Framework, map_First_Either);
            TransUniqueNames(solidNamesDoc_Framework, uniqueNames);

            if (autoTranslateNicks) {
                TransNikcs(frameworkPath, solidNamesDoc_Framework);
            }
            if (overrideMode) {
                string overrideNicks_Path = Path.Combine(sourcePath, "Override.xml");
                if (File.Exists(overrideNicks_Path)) {
                    XDocument doc_Framework = XDocument.Load(overrideNicks_Path);
                    OverrideNicks(solidNamesDoc_Framework, doc_Framework);
                }
            }
            if (trimFields) {
                Trim(solidNamesDoc_Framework);
            }

            solidNamesDoc_Framework.Save(solidNamesPath_Mod);
        }

        static void MassTransByMap(XDocument doc_Framework, XDocument map) {
            XElement root = doc_Framework.Root;
            foreach (XElement curSubMap in map.Root.Elements()) {
                string translation = curSubMap.Element("Translation").Value;
                foreach (XElement curField_Map in curSubMap.Element("Fields").Elements()) {
                    XElement curField_Framework = root.Element(curField_Map.Name);
                    if (curField_Framework != null) {
                        curField_Framework.Value = translation;
                    }
                }
            }
        }

        static void TransUniqueNames(XDocument doc_Framework, XDocument uniqueNames) {
            XElement root = doc_Framework.Root;
            foreach (XElement curItem_Unique in uniqueNames.Root.Elements()) {
                foreach (XElement curField_Unique in curItem_Unique.Elements()) {
                    XElement curField_Framework = root.Element(curField_Unique.Name);
                    if (curField_Framework != null) {
                        curField_Framework.Value = curField_Unique.Value;
                    }
                }
            }
        }

        static void TransNikcs(string frameworkPath, XDocument doc_Framework) {
            XElement root = doc_Framework.Root;
            foreach (XElement curDef in XDocument.Load(Path.Combine(frameworkPath, "Defs", "VanillaNames", "SolidNames.xml")).Root.Elements()) {
                string defName = curDef.Element("defName").Value;
                XElement nick = curDef.Element("nick");
                if (nick != null) {
                    if (nick.Value == curDef.Element("first").Value) {
                        root.Element(defName + ".nick").Value = root.Element(defName + ".first").Value;
                    } else if (nick.Value == curDef.Element("last").Value) {
                        root.Element(defName + ".nick").Value = root.Element(defName + ".last").Value;
                    }
                }
            }
        }

        static void Merge(XDocument doc_Framework, XDocument doc_Mod, bool autoCommentInvalidFields) {
            XElement root = doc_Framework.Root;
            int count = 0;
            foreach (XElement curField_Mod in doc_Mod.Root.Elements()) {
                XElement curField_Framework = root.Element(curField_Mod.Name);
                if (curField_Framework != null) {
                    curField_Framework.Value = curField_Mod.Value;
                } else if (autoCommentInvalidFields) {
                    root.Add("  ", new XComment(curField_Mod.ToString()), "\n");
                    count++;
                }
            }
            XElement lastField = doc_Mod.Root.Elements().Last();
            foreach (XNode curNode in lastField.NodesAfterSelf()) {
                if (curNode.NodeType == System.Xml.XmlNodeType.Comment) {
                    root.Add("  ", curNode, "\n");
                    count++;
                }
            }
            if (count > 0) {
                root.Add("\n");
            }
        }

        static void OverrideNicks(XDocument doc_Framework, XDocument doc_Override) {
            XElement root = doc_Framework.Root;
            foreach (XElement curField_Override in doc_Override.Root.Elements()) {
                XElement curField_Framework = root.Element(curField_Override.Name);
                if (curField_Framework != null) {
                    curField_Framework.Value = curField_Override.Value;
                }
            }
        }

        static void Trim(XDocument doc_Framework) {
            foreach (XElement curField in doc_Framework.Root.Elements()) {
                curField.Value = curField.Value.Trim();
            }
        }
    }
}


text:
package cpuscraper // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/cpuscraper"

import (
	"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal"
	"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/internal/metadata"
)

// Config relating to CPU Metric Scraper.
type Config struct {
	Metrics metadata.MetricsSettings `mapstructure:"metrics"`
	internal.ScraperConfig
}


text:
import subspaceEnhancer from '../../src/enhancers/subspaceEnhancer'
import { NAMESPACE_ROOT, CHILD } from '../../src/enhancers/subspaceTypesEnhancer'

describe('subspaceEnhancer tests', () => {

    it('should enhance getState with sub-state', () => {
        const store = {
            getState: sinon.stub().returns({ parent: { child: { value: 'expected' } }, other: 'value' }),
            dispatch: sinon.spy()
        }

        const subspace = {
            getState: store.getState,
            dispatch: store.dispatch,
            rootStore: store,
            subspaceTypes: [NAMESPACE_ROOT, CHILD]
        }

        const createSubspace = sinon.mock().withArgs(store).returns(subspace)

        const enhancedSubspace = subspaceEnhancer((state, rootState) => ({ ...state.parent, other: rootState.other }))(createSubspace)(store)

        expect(enhancedSubspace.getState()).to.deep.equal({ child: { value: 'expected' }, other: 'value' })
    })

    it('should raise error if getState returns undefined', () => {
        const store = {
            getState: sinon.stub().returns({ parent: { child: { value: 'expected' } } }),
            dispatch: sinon.spy()
        }

        const subspace = {
            getState: store.getState,
            dispatch: store.dispatch,
            rootStore: store,
            subspaceTypes: [NAMESPACE_ROOT, CHILD]
        }

        const createSubspace = sinon.mock().withArgs(store).returns(subspace)

        const enhancedSubspace = subspaceEnhancer(() => undefined)(createSubspace)(store)

        expect(() => enhancedSubspace.getState()).to.throw('mapState must not return undefined.')
    })

    it('should not raise error if getState returns undefined in production', () => {
        const store = {
            getState: sinon.stub().returns({ parent: { child: { value: 'expected' } } }),
            dispatch: sinon.spy()
        }

        const subspace = {
            getState: store.getState,
            dispatch: store.dispatch,
            rootStore: store,
            subspaceTypes: [NAMESPACE_ROOT, CHILD]
        }

        const createSubspace = sinon.mock().withArgs(store).returns(subspace)

        const enhancedSubspace = subspaceEnhancer(() => undefined)(createSubspace)(store)

        const nodeEnv = process.env.NODE_ENV

        try {
            process.env.NODE_ENV = 'production'

            expect(enhancedSubspace.getState()).to.be.undefined
        } finally {
            process.env.NODE_ENV = nodeEnv
        }
    })

    it('should enhance dispatch with namepace', () => {
        const store = {
            getState: sinon.stub().returns({ unique: 'value' }),
            dispatch: sinon.spy()
        }

        const subspace = {
            getState: store.getState,
            dispatch: store.dispatch,
            subspaceTypes: [NAMESPACE_ROOT, CHILD]
        }

        const createSubspace = sinon.mock().withArgs(store).returns(subspace)

        const enhancedSubspace = subspaceEnhancer((state) => state, 'test')(createSubspace)(store)

        enhancedSubspace.dispatch({ type: 'TEST', value: 'expected' })

        expect(subspace.dispatch).to.be.calledWithMatch({ type: 'test/TEST', value: 'expected' })
    })
})


text:
function [data_train, labels_train, data_test, labels_test] = load_preprocess_cifar10()
  data_train = []; labels_train = [];
  for i=1:5
    name = ['data_batch_', int2str(i), '.mat'];
    data = load(strcat(name));
    data_train = [data_train, double(data.data') / 255];
    labels_train = [labels_train; double(data.labels + 1)];
  end

  data6 = load('test_batch.mat');
  data_test = double(data6.data') / 255;
  labels_test = double(data6.labels + 1);


text:
package May2021Leetcode;

public class _0273IntegerToEnglishWords {

	public static void main(String[] args) {
		System.out.println(numberToWords(123));
		System.out.println(numberToWords(12345));
		System.out.println(numberToWords(1234567));
		System.out.println(numberToWords(1234567891));
	}

	public static String numberToWords(int num) {
		if (num == 0)
			return "Zero";

		int noOfBillions = num / 1000000000;
		int noOfMillions = (num - noOfBillions * 1000000000) / 1000000;
		int noOfThousands = (num - noOfBillions * 1000000000 - noOfMillions * 1000000) / 1000;
		int restVal = (num - noOfBillions * 1000000000 - noOfMillions * 1000000 - noOfThousands * 1000);

		StringBuilder sb = new StringBuilder();
		if (noOfBillions > 0) {
			sb.append(threes(noOfBillions) + " Billion ");
		}

		if (noOfMillions > 0) {
			sb.append(threes(noOfMillions) + " Million ");
		}

		if (noOfThousands > 0) {
			sb.append(threes(noOfThousands) + " Thousand ");
		}

		if (restVal > 0) {
			sb.append(threes(restVal));
		}

		return sb.toString().trim();
	}

	public static String threes(int num) {
		int noOfHundreds = num / 100;
		int tensVal = num - noOfHundreds * 100;
		int noOfTens = tensVal / 10;
		int twosVal = noOfTens * 10;
		int restVal = num - noOfHundreds * 100 - noOfTens * 10;

		StringBuilder sb = new StringBuilder();
		if (noOfHundreds > 0) {
			sb.append(ones(noOfHundreds) + " Hundred ");
		}

		if (tensVal > 10 && tensVal < 20) {
			sb.append(lessThan20(tensVal));
		} else {
			if (twosVal > 0) {
				sb.append(twos(twosVal));
			}
			sb.append(" " + ones(restVal));
		}
		return sb.toString();
	}

	public static String lessThan20(int num) {
		switch (num) {
		case 11:
			return "Eleven";
		case 12:
			return "Twelve";
		case 13:
			return "Thirteen";
		case 14:
			return "Fourteen";
		case 15:
			return "Fifteen";
		case 16:
			return "Sixteen";
		case 17:
			return "Seventeen";
		case 18:
			return "Eighteen";
		case 19:
			return "Nineteen";
		}
		return "";
	}

	public static String twos(int num) {
		switch (num) {
		case 10:
			return "Ten";
		case 20:
			return "Twenty";
		case 30:
			return "Thirty";
		case 40:
			return "Forty";
		case 50:
			return "Fifty";
		case 60:
			return "Sixty";
		case 70:
			return "Seventy";
		case 80:
			return "Eighty";
		case 90:
			return "Ninety";
		}
		return "";
	}

	public static String ones(int num) {
		switch (num) {
		case 1:
			return "One";
		case 2:
			return "Two";
		case 3:
			return "Three";
		case 4:
			return "Four";
		case 5:
			return "Five";
		case 6:
			return "Six";
		case 7:
			return "Seven";
		case 8:
			return "Eight";
		case 9:
			return "Nine";
		}
		return "";
	}

}


text:
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////

package gnu.trove.set.hash;

import gnu.trove.set.TFloatSet;
import gnu.trove.iterator.TFloatIterator;
import gnu.trove.impl.*;
import gnu.trove.impl.hash.*;
import gnu.trove.TFloatCollection;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Externalizable;
import java.util.Arrays;
import java.util.Collection;

//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////

/**
 * An open addressed set implementation for float primitives.
 *
 * @author Eric D. Friedman
 * @author Rob Eden
 * @author Jeff Randall
 */

public class TFloatHashSet extends TFloatHash implements TFloatSet, Externalizable {
	static final long serialVersionUID = 1L;

    /**
     * Creates a new TFloatHashSet instance with the default
     * capacity and load factor.
     */
    public TFloatHashSet() {
        super();
    }

    /**
     * Creates a new TFloatHashSet instance with a prime
     * capacity equal to or greater than <tt>initialCapacity</tt> and
     * with the default load factor.
     *
     * @param initialCapacity an int value
     */
    public TFloatHashSet( int initialCapacity ) {
        super( initialCapacity );
    }

    /**
     * Creates a new TIntHash instance with a prime
     * value at or near the specified capacity and load factor.
     *
     * @param initialCapacity used to find a prime capacity for the table.
     * @param load_factor used to calculate the threshold over which
     * rehashing takes place.
     */
    public TFloatHashSet( int initialCapacity, float load_factor ) {
        super( initialCapacity, load_factor );
    }

    /**
     * Creates a new TFloatHashSet instance with a prime
     * capacity equal to or greater than <tt>initial_capacity</tt> and
     * with the specified load factor.
     *
     * @param initial_capacity an int value
     * @param load_factor a float value
     * @param no_entry_value a float value that represents null.
     */
    public TFloatHashSet( int initial_capacity, float load_factor,
            float no_entry_value ) {
        super( initial_capacity, load_factor, no_entry_value );
        //noinspection RedundantCast
        if ( no_entry_value != ( float ) 0 ) {
            Arrays.fill( _set, no_entry_value );
        }
    }

    /**
      * Creates a new TFloatHashSet instance that is a copy
      * of the existing Collection.
      *
      * @param collection a <tt>Collection</tt> that will be duplicated.
      */
     public TFloatHashSet( Collection<? extends Float> collection ) {
        this( Math.max( collection.size(), DEFAULT_CAPACITY ) );
        addAll( collection );
     }

    /**
     * Creates a new TFloatHashSet instance that is a copy
     * of the existing set.
     *
     * @param collection a <tt>TFloatSet</tt> that will be duplicated.
     */
    public TFloatHashSet( TFloatCollection collection ) {
        this( Math.max( collection.size(), DEFAULT_CAPACITY ) );
        if ( collection instanceof TFloatHashSet ) {
            TFloatHashSet hashset = ( TFloatHashSet ) collection;
            this._loadFactor = hashset._loadFactor;
            this.no_entry_value = hashset.no_entry_value;
            //noinspection RedundantCast
            if ( this.no_entry_value != ( float ) 0 ) {
                Arrays.fill( _set, this.no_entry_value );
            }
            setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
        }
        addAll( collection );
    }

    /**
     * Creates a new TFloatHashSet instance containing the
     * elements of <tt>array</tt>.
     *
     * @param array an array of float primitives
     */
    public TFloatHashSet( float[] array ) {
        this( Math.max( array.length, DEFAULT_CAPACITY ) );
        addAll( array );
    }

    /** {@inheritDoc} */
    public TFloatIterator iterator() {
        return new TFloatHashIterator( this );
    }

    /** {@inheritDoc} */
    public float[] toArray() {
        float[] result = new float[ size() ];
        float[] set = _set;
        byte[] states = _states;

        for ( int i = states.length, j = 0; i-- > 0; ) {
            if ( states[i] == FULL ) {
                result[j++] = set[i];
            }
        }
        return result;
    }

    /** {@inheritDoc} */
    public float[] toArray( float[] dest ) {
        float[] set = _set;
        byte[] states = _states;

        for ( int i = states.length, j = 0; i-- > 0; ) {
            if ( states[i] == FULL ) {
                dest[j++] = set[i];
            }
        }

        if ( dest.length > _size ) {
            dest[_size] = no_entry_value;
        }
        return dest;
    }

    /** {@inheritDoc} */
    public boolean add( float val ) {
        int index = insertionIndex(val);

        if ( index < 0 ) {
            return false;       // already present in set, nothing to add
        }

        byte previousState = _states[index];
        _set[index] = val;
        _states[index] = FULL;
        postInsertHook( previousState == FREE );

        return true;            // yes, we added something
    }

    /** {@inheritDoc} */
    public boolean remove( float val ) {
        int index = index(val);
        if ( index >= 0 ) {
            removeAt( index );
            return true;
        }
        return false;
    }

    /** {@inheritDoc} */
    public boolean containsAll( Collection<?> collection ) {
        for ( Object element : collection ) {
            if ( element instanceof Float ) {
                float c = ( ( Float ) element ).floatValue();
                if ( ! contains( c ) ) {
                    return false;
                }
            } else {
                return false;
            }

        }
        return true;
    }

    /** {@inheritDoc} */
    public boolean containsAll( TFloatCollection collection ) {
        TFloatIterator iter = collection.iterator();
        while ( iter.hasNext() ) {
            float element = iter.next();
            if ( ! contains( element ) ) {
                return false;
            }
        }
        return true;
    }

    /** {@inheritDoc} */
    public boolean containsAll( float[] array ) {
        for ( int i = array.length; i-- > 0; ) {
            if ( ! contains( array[i] ) ) {
                return false;
            }
        }
        return true;
    }

    /** {@inheritDoc} */
    public boolean addAll( Collection<? extends Float> collection ) {
        boolean changed = false;
        for ( Float element : collection ) {
            float e = element.floatValue();
            if ( add( e ) ) {
                changed = true;
            }
        }
        return changed;
    }

    /** {@inheritDoc} */
    public boolean addAll( TFloatCollection collection ) {
        boolean changed = false;
        TFloatIterator iter = collection.iterator();
        while ( iter.hasNext() ) {
            float element = iter.next();
            if ( add( element ) ) {
                changed = true;
            }
        }
        return changed;
    }

    /** {@inheritDoc} */
    public boolean addAll( float[] array ) {
        boolean changed = false;
        for ( int i = array.length; i-- > 0; ) {
            if ( add( array[i] ) ) {
                changed = true;
            }
        }
        return changed;
    }

    /** {@inheritDoc} */
    @SuppressWarnings({"SuspiciousMethodCalls"})
    public boolean retainAll( Collection<?> collection ) {
        boolean modified = false;
	    TFloatIterator iter = iterator();
	    while ( iter.hasNext() ) {
	        if ( ! collection.contains( Float.valueOf ( iter.next() ) ) ) {
		        iter.remove();
		        modified = true;
	        }
	    }
	    return modified;
    }

    /** {@inheritDoc} */
    public boolean retainAll( TFloatCollection collection ) {
        if ( this == collection ) {
            return false;
        }
        boolean modified = false;
	    TFloatIterator iter = iterator();
	    while ( iter.hasNext() ) {
	        if ( ! collection.contains( iter.next() ) ) {
		        iter.remove();
		        modified = true;
	        }
	    }
	    return modified;
    }

    /** {@inheritDoc} */
    public boolean retainAll( float[] array ) {
        boolean changed = false;
        Arrays.sort( array );
        float[] set = _set;
        byte[] states = _states;

        for ( int i = set.length; i-- > 0; ) {
            if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
                removeAt( i );
                changed = true;
            }
        }
        return changed;
    }

    /** {@inheritDoc} */
    public boolean removeAll( Collection<?> collection ) {
        boolean changed = false;
        for ( Object element : collection ) {
            if ( element instanceof Float ) {
                float c = ( ( Float ) element ).floatValue();
                if ( remove( c ) ) {
                    changed = true;
                }
            }
        }
        return changed;
    }

    /** {@inheritDoc} */
    public boolean removeAll( TFloatCollection collection ) {
        boolean changed = false;
        TFloatIterator iter = collection.iterator();
        while ( iter.hasNext() ) {
            float element = iter.next();
            if ( remove( element ) ) {
                changed = true;
            }
        }
        return changed;
    }

    /** {@inheritDoc} */
    public boolean removeAll( float[] array ) {
        boolean changed = false;
        for ( int i = array.length; i-- > 0; ) {
            if ( remove(array[i]) ) {
                changed = true;
            }
        }
        return changed;
    }

    /** {@inheritDoc} */
    public void clear() {
        super.clear();
        float[] set = _set;
        byte[] states = _states;

        for ( int i = set.length; i-- > 0; ) {
            set[i] = no_entry_value;
            states[i] = FREE;
        }
    }

    /** {@inheritDoc} */
    protected void rehash( int newCapacity ) {
        int oldCapacity = _set.length;

        float oldSet[] = _set;
        byte oldStates[] = _states;

        _set = new float[newCapacity];
        _states = new byte[newCapacity];

        for ( int i = oldCapacity; i-- > 0; ) {
            if( oldStates[i] == FULL ) {
                float o = oldSet[i];
                int index = insertionIndex(o);
                _set[index] = o;
                _states[index] = FULL;
            }
        }
    }

    /** {@inheritDoc} */
    public boolean equals( Object other ) {
        if ( ! ( other instanceof TFloatSet ) ) {
            return false;
        }
        TFloatSet that = ( TFloatSet ) other;
        if ( that.size() != this.size() ) {
            return false;
        }
        for ( int i = _states.length; i-- > 0; ) {
            if ( _states[i] == FULL ) {
                if ( ! that.contains( _set[i] ) ) {
                    return false;
                }
            }
        }
        return true;
    }

    /** {@inheritDoc} */
    public int hashCode() {
        int hashcode = 0;
        for ( int i = _states.length; i-- > 0; ) {
            if ( _states[i] == FULL ) {
                hashcode += HashFunctions.hash( _set[i] );
            }
        }
        return hashcode;
    }

    /** {@inheritDoc} */
    public String toString() {
        StringBuilder buffy = new StringBuilder( _size * 2 + 2 );
        buffy.append("{");
        for ( int i = _states.length, j = 1; i-- > 0; ) {
            if ( _states[i] == FULL ) {
                buffy.append( _set[i] );
                if ( j++ < _size ) {
                    buffy.append( "," );
                }
            }
        }
        buffy.append("}");
        return buffy.toString();
    }

    class TFloatHashIterator extends THashPrimitiveIterator implements TFloatIterator {

        /** the collection on which the iterator operates */
        private final TFloatHash _hash;

        /** {@inheritDoc} */
        public TFloatHashIterator( TFloatHash hash ) {
            super( hash );
            this._hash = hash;
        }

        /** {@inheritDoc} */
        public float next() {
            moveToNextIndex();
            return _hash._set[_index];
        }
    }

    /** {@inheritDoc} */
    public void writeExternal( ObjectOutput out ) throws IOException {

    	// VERSION
    	out.writeByte( 1 );

    	// SUPER
    	super.writeExternal( out );

    	// NUMBER OF ENTRIES
    	out.writeInt( _size );

        // LOAD FACTOR -- Added version 1
        out.writeFloat( _loadFactor );

        // NO ENTRY VALUE -- Added version 1
        out.writeFloat( no_entry_value );

    	// ENTRIES
        for ( int i = _states.length; i-- > 0; ) {
            if ( _states[i] == FULL ) {
                out.writeFloat( _set[i] );
            }
        }
    }

    /** {@inheritDoc} */
    public void readExternal( ObjectInput in )
    	throws IOException, ClassNotFoundException {

    	// VERSION
    	int version = in.readByte();

        // SUPER
    	super.readExternal( in );

    	// NUMBER OF ENTRIES
        int size = in.readInt();

        if ( version >= 1 ) {
            // LOAD FACTOR
            _loadFactor = in.readFloat();

            // NO ENTRY VALUE
            no_entry_value = in.readFloat();
            //noinspection RedundantCast
            if ( no_entry_value != ( float ) 0 ) {
                Arrays.fill( _set, no_entry_value );
            }
        }

    	// ENTRIES
        setUp( size );
        while ( size-- > 0 ) {
            float val = in.readFloat();
            add( val );
        }
    }
} // TIntHashSet


text:
<offhost-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/offhostService">
    <aid-group>
        <!-- OBTH card manager AID -->
        <aid-filter android:name="A000000151000000"/>
        <!-- NXP card manager AID -->
        <aid-filter android:name="A000000003000000"/>
    </aid-group>
</offhost-apdu-service>


text:
package com.mindcognition.mindraider.utils;

import java.io.File;
import java.io.IOException;

import javax.swing.JTextArea;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

/**
 * Load file to text area.
 */
public class FileLoader extends Thread {
    private static final Logger logger = Logger.getLogger(FileLoader.class);

    JTextArea doc;
    File file;

    public FileLoader(File file, JTextArea doc) {
        this.file = file;
        this.doc = doc;

        setPriority(4);
        setDaemon(true);
    }

    public void run() {
        try {
            doc.setText(FileUtils.readFileToString(file, "UTF-8"));
        } catch (IOException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("run(): " + e.getMessage());
            }
        }
    }

    public static void loadFile(String url, JTextArea doc) {
        File f = new File(url);
        if (f.exists()) {
            Thread loader = new FileLoader(f, doc);
            loader.start();
        }
    }
}


text:
'''
Created by 15 cm on 11/22/15 3:28 PM
Copyright © 2015 15cm. All rights reserved.
'''

__author__ = '15cm'

from sklearn.ensemble import RandomForestClassifier
from sklearn.externals import joblib
from feature.sift import Sift
import os

CURPATH = os.path.split(os.path.realpath(__file__))[0]

class RandomForest:
    def __init__(self):
        self.rf = RandomForestClassifier()
        self.model_path =os.path.join(os.path.join(CURPATH,'model'),'random_forest.pkl')

    def fit(self,X,y):
        self.rf.fit(X,y)

    def save(self):
        joblib.dump(self.rf,self.model_path)

    def load(self):
        self.rf = joblib.load(self.model_path)

    def predict(self,kmeans,file):
        pass
        # if hasattr(file,'__iter__'):
        #
        # if image:
        #     X = bow.compute_bow(kmeans,image)
        # elif image_list:
        #     descriptors_list = [sift.get_descriptors(os.path.join('test',x)) for x in image_list] # 128-dimension descriptors for every image
        #     X = bow.compute_bow_matrix(kmeans,descriptors_list)
        # else:
        #     print 'image or image_list should be provided'
        #     exit(1)
        # return self.rf.predict(X)


text:
namespace Google.Cloud.Tasks.V2.Snippets
{
    // [START cloudtasks_v2_generated_CloudTasks_SetIamPolicy_sync]
    using Google.Api.Gax;
    using Google.Cloud.Iam.V1;
    using Google.Cloud.Tasks.V2;
    using Google.Protobuf.WellKnownTypes;

    public sealed partial class GeneratedCloudTasksClientSnippets
    {
        /// <summary>Snippet for SetIamPolicy</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void SetIamPolicyRequestObject()
        {
            // Create client
            CloudTasksClient cloudTasksClient = CloudTasksClient.Create();
            // Initialize request argument(s)
            SetIamPolicyRequest request = new SetIamPolicyRequest
            {
                ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
                Policy = new Policy(),
                UpdateMask = new FieldMask(),
            };
            // Make the request
            Policy response = cloudTasksClient.SetIamPolicy(request);
        }
    }
    // [END cloudtasks_v2_generated_CloudTasks_SetIamPolicy_sync]
}


text:
package com.razorfish.ponghacksscorekeeper.bus.events;

import java.util.ArrayList;

/**
 * Created by Tim on 2015-06-07.
 */
public class PlayersListResponse {
    ArrayList response;
    String queryType;
    String playerType;

    public PlayersListResponse(ArrayList response, String queryType, String playerType) {
        this.response = response;
        this.queryType = queryType;
        this.playerType = playerType;
    }

    public ArrayList getResponse() {
        return response;
    }

    public String getQueryType() {
        return queryType;
    }

    public String getPlayerType() {
        return playerType;
    }
}


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

namespace SGLibrary.Extend
{
    /// <summary>
    /// 会递归找到所有子控件
    /// </summary>
    public class ListChildControlInfo
    {
        public ListChildControlInfo(IntPtr parentHwnd)
        {
            this.ParentHwnd = parentHwnd;
            this.Values = new List<ControlInfo>();

            this.ChildProc = new Win32Api.EnumWindowProc(AddChildHwndToValues);
            Win32Api.EnumChildWindows(this.ParentHwnd, ChildProc, IntPtr.Zero);
            this.FillControlInfo();
        }

        private IntPtr ParentHwnd;
        private Win32Api.EnumWindowProc ChildProc;

        public IList<ControlInfo> Values;

        private bool AddChildHwndToValues(IntPtr hWnd, IntPtr parameter)
        {
            Win32Api.EnumChildWindows(hWnd, ChildProc, IntPtr.Zero);

            this.Values.Add(new ControlInfo { Hwnd = hWnd, });
            return true;
        }

        private void FillControlInfo()
        {
            var classNameSb = new StringBuilder();
            var textSb = new StringBuilder();

            foreach (var item in this.Values)
            {
                item.CtrlID = Win32Api.GetDlgCtrlID(item.Hwnd);
                Win32Api.GetClassName(item.Hwnd, classNameSb, 260);
                item.ClassName = classNameSb.ToString();

                if (item.ClassName == "ComboBox"
                    || item.ClassName == "Edit")
                {
                    var size = Win32Api.SendMessage(item.Hwnd, Win32Api.WM_GETTEXTLENGTH, (IntPtr)0, (IntPtr)0).ToInt32();
                    textSb = new StringBuilder(size + 1);
                    Win32Api.SendMessage(item.Hwnd, Win32Api.WM_GETTEXT, (IntPtr)textSb.Capacity, textSb);
                }
                else
                    Win32Api.GetWindowText(item.Hwnd, textSb, 1024);

                item.Text = textSb.ToString();
            }
        }
    }

    public class FindWindows
    {
        public FindWindows(Func<String, bool> textPredicate)
        {
            this.TextPredicate = textPredicate;

            var hildProc = new Win32Api.EnumWindowProc(EnumWindowsProc);
            Win32Api.EnumWindows(hildProc, IntPtr.Zero);
        }

        private Func<String, bool> TextPredicate;
        public IntPtr WindowsHwnd { get; private set; }
        public String WindowsText { get; private set; }

        private bool EnumWindowsProc(IntPtr hWnd, IntPtr parameter)
        {
            var textSb = new StringBuilder();
            Win32Api.GetWindowText(hWnd, textSb, 1024);
            var text = textSb.ToString();

            if (this.TextPredicate(text))
            {
                this.WindowsHwnd = hWnd;
                this.WindowsText = text;
                return false;  //终止遍历
            }
            else
                return true;
        }
    }

    public class ControlInfo
    {
        public IntPtr Hwnd { get; set; }
        public Int32 CtrlID { get; set; }

        public String ClassName { get; set; }
        public String Text { get; set; }
    }
}


text:
/*
 * LabelledTimestamp Messages
 *
 * This contains all the text for the LabelledTimestamp component.
 */
import { defineMessages } from 'react-intl';

export default defineMessages({
  header: {
    id: 'app.components.LabelledTimestamp.header',
    defaultMessage: 'Start time',
  },
});


text:
lambda-functions
================

AWS Lambda functions


text:
package com.hkd.ithome.tools;

import java.util.ArrayList;

import com.hkd.ithome.bean.NewsClassify;

public class Constants {
	public static ArrayList<NewsClassify> getData() {
		ArrayList<NewsClassify> newsClassify = new ArrayList<NewsClassify>();
		NewsClassify classify = new NewsClassify();
		classify.setId(0);
		classify.setTitle("推荐");
		newsClassify.add(classify);
		classify = new NewsClassify();
		classify.setId(1);
		classify.setTitle("热点");
		newsClassify.add(classify);
		classify = new NewsClassify();
		classify.setId(2);
		classify.setTitle("数码");
		newsClassify.add(classify);
		classify = new NewsClassify();
		classify.setId(3);
		classify.setTitle("杭州");
		newsClassify.add(classify);
		classify = new NewsClassify();
		classify.setId(4);
		classify.setTitle("社会");
		newsClassify.add(classify);
		classify = new NewsClassify();
		classify.setId(5);
		classify.setTitle("娱乐");
		newsClassify.add(classify);
		classify = new NewsClassify();
		classify.setId(6);
		classify.setTitle("科技");
		newsClassify.add(classify);
		classify = new NewsClassify();
		classify.setId(7);
		classify.setTitle("汽车");
		newsClassify.add(classify);
		return newsClassify;
	}
}


text:
/** @file
    @brief Header

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// 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.

#ifndef INCLUDED_JSONResolvePossibleRef_h_GUID_64F277A1_33F0_4986_6EEE_09E17C09AA52
#define INCLUDED_JSONResolvePossibleRef_h_GUID_64F277A1_33F0_4986_6EEE_09E17C09AA52

// Internal Includes
// - none

// Library/third-party includes
#include <json/value.h>

// Standard includes
#include <vector>
#include <string>

namespace osvr {
namespace server {
    enum class FileLoadStatus {
        CouldNotOpenFile,
        CouldNotParseFile,
        FileOpenedAndParsed
    };
    enum class ValueHandledAs { Filename, String, JsonRefToFile, Other };
    struct FileLoadAttempt {
        std::string path;
        FileLoadStatus status;
        std::string details;
    };
    using FileLoadAttempts = std::vector<FileLoadAttempt>;

    struct ResolveRefResult {
        Json::Value result;
        bool resolved = false;
        ValueHandledAs handledAs = ValueHandledAs::Other;
        FileLoadAttempts fileAttempts;
    };

    const char *fileLoadStatusToString(FileLoadStatus status);

    /// @brief Given an input that might be a filename, might be a JSON
    /// Pointer-style $ref object, and might just directly be an object, return
    /// the object desired.
    ///
    /// If just a string (suggesting it was intended to be a reference), returns
    /// null.
    ///
    /// @param stringAcceptableResult Determines whether a string that we can't
    /// resolve to a loadable JSON reference should be returned as itself
    /// (valid, true), or should be signaled as an error by returning null
    /// (false, default)
    /// @param searchPath Optional list of directories to look for any mentioned
    /// files.
    Json::Value resolvePossibleRef(Json::Value const &input,
                                   bool stringAcceptableResult = false,
                                   std::vector<std::string> const &searchPath =
                                       std::vector<std::string>());

    ResolveRefResult
    resolvePossibleRefWithDetails(Json::Value const &input,
                                  bool stringAcceptableResult = false,
                                  std::vector<std::string> const &searchPath =
                                      std::vector<std::string>());

} // namespace server
} // namespace osvr

#endif // INCLUDED_JSONResolvePossibleRef_h_GUID_64F277A1_33F0_4986_6EEE_09E17C09AA52


text:
using System.Collections.Generic;
using System.Linq;
using Typewriter.CodeModel.Collections;
using Typewriter.Metadata.Interfaces;
using static Typewriter.CodeModel.Helpers;

namespace Typewriter.CodeModel.Implementation
{
    public sealed class EventImpl : Event
    {
        private readonly IEventMetadata _metadata;

        private EventImpl(IEventMetadata metadata, Item parent)
        {
            _metadata = metadata;
            Parent = parent;
        }

        public override Item Parent { get; }

        public override string name => CamelCase(_metadata.Name.TrimStart('@'));
        public override string Name => _metadata.Name.TrimStart('@');
        public override string FullName => _metadata.FullName;

        private AttributeCollection _attributes;
        public override AttributeCollection Attributes => _attributes ?? (_attributes = AttributeImpl.FromMetadata(_metadata.Attributes, this));

        private Type _type;
        public override Type Type => _type ?? (_type = TypeImpl.FromMetadata(_metadata.Type, this));

        public override string ToString()
        {
            return Name;
        }

        public static EventCollection FromMetadata(IEnumerable<IEventMetadata> metadata, Item parent)
        {
            return new EventCollectionImpl(metadata.Select(e => new EventImpl(e, parent)));
        }
    }
}


text: require 'sensu-handlers-elasticsearch/version'


text:
<o2 use O2Doc::Tutorial />

<o2 docSection title="MakeFlipper">
  Creates a variable that changes value each time it is accessed.
  <o2 docSection title="Syntax">
    <o2 docCode lang="o2ml">
      <o2 makeFlipper var="bgColor" values="#444444, #888888, #bbbbbb" />
    </o2:docCode>
    The first time \$bgColor is used, the value will be #444444, the next time #888888, then #bbbbbb, then #444444 and so on.
  </o2:docSection>
  <o2 docSection title="Attributes">
    <o2 docList class="attributes">
      <o2 docListItem class="required">var</o2:docListItem>
      <o2 docListItem class="required">values</o2:docListItem>
    </o2:docList>
  </o2:docSection>
</o2:docSection>


text:
<?php

$lan = array(
  'Process Next Batch' => 'Przetwórz następn± porcję',
  'Process Killed by other process' => 'Proces zabity przez inny proces',
  'Hmm, duplicate entry, ' => 'Hmm, zduplikowany wpis, ',
  'new rules found' => 'znaleziono nowe reguły',
  'bounces not matched' => 'zwrotĂłw nie pasuje',
  'bounces matched to existing rules' => 'zwroty dopasowane do istniej±cych reguł',
‾
);

?>


text:
<!--

    Copyright (C) 2015 Orange
    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.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<import resource="classpath:/META-INF/spring/config-probe-context.xml" />

	<bean name="/configProbe"
		class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
		<property name="service" ref="configProbe" />
		<property name="serviceInterface"
			value="com.francetelecom.clara.cloud.sample.probe.ConfigProbe" />
	</bean>

</beans>


text:
package commands

type CompressorOptions struct {
	SameOwner bool
}

type Compressor interface {
	// CompressFilesInDir returns path to a compressed file
	CompressFilesInDir(dir string) (path string, err error)

	DecompressFileToDir(path string, dir string, options CompressorOptions) (err error)

	// CleanUp cleans up compressed file after it was used
	CleanUp(path string) error
}


text:
class Browser;

namespace extensions {

// A helper object for extensions-related management for Browser* objects.
class ExtensionBrowserWindowHelper : public ExtensionRegistryObserver {
 public:
  // Note: |browser| must outlive this object.
  explicit ExtensionBrowserWindowHelper(Browser* browser);

  ExtensionBrowserWindowHelper(const ExtensionBrowserWindowHelper&) = delete;
  ExtensionBrowserWindowHelper& operator=(const ExtensionBrowserWindowHelper&) =
      delete;

  ~ExtensionBrowserWindowHelper() override;

 private:
  // ExtensionRegistryObserver:
  void OnExtensionLoaded(content::BrowserContext* browser_context,
                         const Extension* extension) override;
  void OnExtensionUnloaded(content::BrowserContext* browser_context,
                           const Extension* extension,
                           UnloadedExtensionReason reason) override;

  // Closes any tabs owned by the extension and unmutes others if necessary.
  void CleanUpTabsOnUnload(const Extension* extension);

  // The associated browser. Must outlive this object.
  const raw_ptr<Browser> browser_ = nullptr;

  base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver>
      registry_observation_{this};
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_EXTENSION_BROWSER_WINDOW_HELPER_H_


text:
//
//  NuanceSpeech.m
//  SmartHomeSampleriOS
//
//  Created by Ibrahim Adnan on 3/4/15.
//  Copyright (c) 2015 LG Electronics.
//
//  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.
//

#import "NuanceSpeech.h"
#import "Secret.h"

@interface NuanceSpeech()

@property(nonatomic,strong) SKRecognizer* voiceSearch;
@property BOOL isSpeaking;
@property(nonatomic,strong) SKVocalizer* vocalizer;
@property(assign) TransactionState state;
@property (nonatomic,strong) SpeechResponse response;
@end

@implementation NuanceSpeech

- (void)configure {
    [SpeechKit setupWithID:kNuanceAppId
                      host:kNuanceAppHost
                      port:kNuanceAppPort
                    useSSL:YES
                  delegate:nil];

    SKEarcon* earconStart	= [SKEarcon earconWithName:@"earcon_listening.wav"];
    SKEarcon* earconStop	= [SKEarcon earconWithName:@"earcon_done_listening.wav"];
    SKEarcon* earconCancel	= [SKEarcon earconWithName:@"earcon_cancel.wav"];

    [SpeechKit setEarcon:earconStart forType:SKStartRecordingEarconType];
    [SpeechKit setEarcon:earconStop forType:SKStopRecordingEarconType];
    [SpeechKit setEarcon:earconCancel forType:SKCancelRecordingEarconType];
}

-(void)recordVoiceWithResponse:(SpeechResponse)response{

    self.response = response;
    if (self.state == TS_RECORDING) {
        [self.voiceSearch stopRecording];
    }
    else if (self.state == TS_IDLE) {
        SKEndOfSpeechDetection detectionType;
        NSString* recoType;
        NSString* langType;

        self.state = TS_INITIAL;
        detectionType = SKShortEndOfSpeechDetection; /* Searches tend to be short utterances free of pauses. */
        recoType = SKSearchRecognizerType; /* Optimize recognition performance for search text. */
        langType = @"en_US";
        /* Nuance can also create a custom recognition type optimized for your application if neither search nor dictation are appropriate. */

        NSLog(@"Recognizing type:'%@' Language Code: '%@' using end-of-speech detection:%d.", recoType, langType, detectionType);

        self.voiceSearch = [[SKRecognizer alloc] initWithType:recoType
                                               detection:detectionType
                                                language:langType
                                                delegate:self];
    }
}

-(void)readAMessage:(NSString *)message{
    if (self.isSpeaking) {
        [self.vocalizer cancel];
        self.isSpeaking = NO;
    }
    else {
        self.isSpeaking = YES;
        self.vocalizer = [[SKVocalizer alloc] initWithLanguage:@"en_US" delegate:self];
        [self.vocalizer speakString:message];
    }
}

#pragma mark -
#pragma mark SKRecognizerDelegate methods

- (void)recognizerDidBeginRecording:(SKRecognizer *)recognizer
{
    NSLog(@"Recording started.");
    self.state = TS_RECORDING;
}

- (void)recognizerDidFinishRecording:(SKRecognizer *)recognizer
{
    NSLog(@"Recording finished.");
    self.state = TS_PROCESSING;
}

- (void)recognizer:(SKRecognizer *)recognizer didFinishWithResults:(SKRecognition *)results
{
    NSLog(@"Got results.");
    NSLog(@"Session id [%@].", [SpeechKit sessionID]); // for debugging purpose: printing out the speechkit session id

    long numOfResults = [results.results count];

    self.state = TS_IDLE;
    NSString *outputString;
    if (numOfResults > 0)
        outputString = [results firstResult];

    self.voiceSearch = nil;

    self.response(outputString,nil);
}

- (void)recognizer:(SKRecognizer *)recognizer didFinishWithError:(NSError *)error suggestion:(NSString *)suggestion
{
    NSLog(@"Got error. %@",error.description);
    NSLog(@"Session id [%@].", [SpeechKit sessionID]); // for debugging purpose: printing out the speechkit session id

    self.state = TS_IDLE;
    self.voiceSearch = nil;
    self.response(nil,error);
}

#pragma mark -
#pragma mark SKVocalizerDelegate methods

- (void)vocalizer:(SKVocalizer *)vocalizer willBeginSpeakingString:(NSString *)text {
    self.isSpeaking = YES;

}

- (void)vocalizer:(SKVocalizer *)vocalizer willSpeakTextAtCharacter:(NSUInteger)index ofString:(NSString *)text {
    NSLog(@"Session id [%@].", [SpeechKit sessionID]); // for debugging purpose: printing out the speechkit session id
}

- (void)vocalizer:(SKVocalizer *)vocalizer didFinishSpeakingString:(NSString *)text withError:(NSError *)error {
    NSLog(@"Session id [%@]. \n  Error :%@", [SpeechKit sessionID],error.description); // for debugging purpose: printing out the speechkit session id
    self.isSpeaking = NO;

}

@end