text:
<?php
namespace LianYue\QQApi;

class Response
{

    protected $statusCode = 200;

    protected $headers = [];

    protected $body;

    public function __construct($statusCode, array $headers = array(), $body = null)
    {
        $this->setStatusCode($statusCode);
        $this->setHeaders($headers);
        $this->setBody($body);
    }

    public function getStatusCode()
    {
        return $this->statusCode;
    }

    public function setStatusCode($statusCode)
    {
        $this->statusCode = (int) $statusCode;
        return $this;
    }

    public function getHeaders()
    {
        return $this->headers;
    }

    public function setHeaders(array $headers)
    {
        $this->headers = $headers;
        return $this;
    }

    public function getHeader($name)
    {
        return empty($this->headers[$name]) ? [] : $this->headers[$name];
    }

    public function getHeaderLine($name, $default = null)
    {
        return empty($this->headers[$name]) ? $default : implode(',', $this->headers[$name]);
    }

    public function getBody()
    {
        return $this->body;
    }

    public function setBody($body)
    {
        $this->body = (string) $body;
        return $this;
    }

    public function get()
    {
        return $this->body;
    }

    public function set($body)
    {
        $this->body = $body;
        return $this;
    }

    public function getJson($assoc = false)
    {
        if (!$this->body) {
            return [];
        }
        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
            $json = json_decode(trim($this->body), $assoc, 512, JSON_BIGINT_AS_STRING);
        } else {
            $json = json_decode(trim($this->body), $assoc);
        }
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new RequestException(function_exists('json_last_error_msg') ? json_last_error_msg() : 'Json decode error', json_last_error());
        }
        return $json;
    }
}


text:
package com.nishionline.test.dynamicFactorial;

import java.util.Scanner;

import static java.lang.String.format;

/**
 * @author shuklaalok7
 * @since 28/4/15 11:57
 */
public class Driver {

    public static void main(String[] args) {
        // args[0] should be a boolean: true for enabling logging in console
        // args[1] should be a number to calculate the factorial

        Calculator calculator = new Calculator(Boolean.parseBoolean(args[0]));
        int number = Integer.parseInt(args[1]);
        Scanner inputScanner = new Scanner(System.in);

        do {
            long startTime = System.currentTimeMillis();
            System.out.println(format("The factorial of %d is %s.", number, calculator.factorial(number)));
            System.out.println(format("Calculated factorial(%d) in %d ms.", number, System.currentTimeMillis() - startTime));
            System.out.print("\nEnter another number: ");
            number = inputScanner.nextInt();
        } while(number >=0);
    }

}

redpajama_set_name: RedPajamaGithub


text:
import sys, argparse, re
from FileBasics import GenericFileReader

# Pre: Takes a genepred file name as an input and an output file name for where to write the output
# Post:  Outputs a genepred file to your output location that now has each transcript uniquely named
#        Also outputs a file at your outputlocation ".key_file" that contains a key
#        with unique_transcript_name followed by the original genepred line.
#  Modifies: FIle IO

def main():
  parser = argparse.ArgumentParser(description="Make a gpd with unique transcript names and a key to their original gpd entry\n")
  parser.add_argument("gpd_infile",help="FILENAME genepred file")
  parser.add_argument("gpd_outfile",help="FILENAME genepred file")
  args = parser.parse_args()
  gfr = GenericFileReader(args.gpd_infile)
  seen = {}
  while True:
    line = gfr.readline()
    if not line: break
    if re.match('^#',line): continue
    line = line.rstrip()
    f = line.split("\t")
    if f[1] not in seen:
      seen[f[1]] = []
    seen[f[1]].append(line)
  gfr.close()
  of_gpd = open(args.gpd_outfile,'w')
  of_key = open(args.gpd_outfile+".key_file",'w')
  for tx in seen:
    for i in range(0,len(seen[tx])):
      name = tx
      if len(seen[tx]) > 1:
        name = tx + '['+str(i+1)+'/'+str(len(seen[tx]))+']'
      f = seen[tx][i].split("\t")
      f[1] = name
      newline = "\t".join(f)
      of_key.write(name + "\t" + seen[tx][i] + "\n")
      of_gpd.write(newline + "\n")
  of_key.close()
  of_gpd.close()
main()


text:
CKEDITOR.plugins.setLang( 'forms', 'nl', {
	button: {
		title: 'Eigenschappen knop',
		text: 'Tekst (waarde)',
		type: 'Soort',
		typeBtn: 'Knop',
		typeSbm: 'Versturen',
		typeRst: 'Leegmaken'
	},
	checkboxAndRadio: {
		checkboxTitle: 'Eigenschappen aanvinkvakje',
		radioTitle: 'Eigenschappen selectievakje',
		value: 'Waarde',
		selected: 'Geselecteerd'
	},
	form: {
		title: 'Eigenschappen formulier',
		menu: 'Eigenschappen formulier',
		action: 'Actie',
		method: 'Methode',
		encoding: 'Codering'
	},
	hidden: {
		title: 'Eigenschappen verborgen veld',
		name: 'Naam',
		value: 'Waarde'
	},
	select: {
		title: 'Eigenschappen selectieveld',
		selectInfo: 'Informatie',
		opAvail: 'Beschikbare opties',
		value: 'Waarde',
		size: 'Grootte',
		lines: 'Regels',
		chkMulti: 'Gecombineerde selecties toestaan',
		opText: 'Tekst',
		opValue: 'Waarde',
		btnAdd: 'Toevoegen',
		btnModify: 'Wijzigen',
		btnUp: 'Omhoog',
		btnDown: 'Omlaag',
		btnSetValue: 'Als geselecteerde waarde instellen',
		btnDelete: 'Verwijderen'
	},
	textarea: {
		title: 'Eigenschappen tekstvak',
		cols: 'Kolommen',
		rows: 'Rijen'
	},
	textfield: {
		title: 'Eigenschappen tekstveld',
		name: 'Naam',
		value: 'Waarde',
		charWidth: 'Breedte (tekens)',
		maxChars: 'Maximum aantal tekens',
		type: 'Soort',
		typeText: 'Tekst',
		typePass: 'Wachtwoord',
		typeEmail: 'E-mail',
		typeSearch: 'Zoeken',
		typeTel: 'Telefoonnummer',
		typeUrl: 'URL'
	}
} );


text:
layout: post
title: "A propósito"
date: 2017-07-19
tags: [Filosofía, Política, Literatura]
categories: [Ecuador, Quincenal]
preview: https://ia601505.us.archive.org/4/items/unionpod/aproposito300.jpg
---

![A propósito](https://ia601505.us.archive.org/4/items/unionpod/aproposito500.jpg)

## Escucha su más reciente episodio

<audio id="audio" preload="auto" controls="" src="http://api.spreaker.com/download/episode/12727150/revolucionarios_y_la_distincion_entre_cultura_y_civilizacion.mp3"></audio>

Comentarios cortos, opinión sobre filosofía, política, arte y literatura.

_ _ _

Autor: **Fermín Sandoval**
[web](https://socialtegia.com)
[Feed](http://www.spreaker.com/show/2598481/episodes/feed)

**Contacta:**
Twitter: [@ferminhsandoval](https://twitter.com/ferminhsandoval)
Correo: [ferminhomero@hotmail.com](mailto:ferminhomero@hotmail.com)


text:
<?php

namespace ConferenceSchedulerBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TimeType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use ConferenceSchedulerBundle\Entity\ConferenceProgram;

class ConferenceProgramType extends AbstractType {

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('start', TimeType::class)
                ->add('end', TimeType::class)
                ->add('name')
                ->add('description')
                ->add('type', ChoiceType::class, [
                    'choices' => ConferenceProgram::TYPES
                ])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults([
            'data_class' => ConferenceProgram::class
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix() {
        return 'conferenceschedulerbundle_conference_program';
    }

}


text:
package de.galan.snake.core.source.file;

import static org.assertj.core.api.Assertions.*;

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

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;

import com.google.common.base.StandardSystemProperty;
import com.google.common.io.Resources;

import de.galan.commons.test.AbstractTestParent;
import de.galan.commons.test.Tests;
import de.galan.commons.time.Sleeper;
import de.galan.snake.core.DefaultSnakeInstance;
import de.galan.snake.core.source.EventBean;
import de.galan.snake.core.source.TestSourceListener;
import de.galan.snake.core.source.UpdatedBean;

/**
 * CUT FileSnakeSource
 *
 * @author galan
 */
public class FileSnakeSourceTest extends AbstractTestParent {

	private FileSnakeSource source;
	private TestSourceListener listener;
	String dirTest;
	private String userPropertiesFile;

	@Before
	public void setup() {
		System.getProperties().remove(FileSnakeSource.PROPERTY_OBSERVE); // reset
		userPropertiesFile = StandardSystemProperty.USER_NAME.value() + ".properties";
		dirTest = Tests.getTestDirectory(true).getAbsolutePath();
		System.setProperty(DefaultSnakeInstance.SNAKE_DIR_CONFIGURATION, dirTest);
		source = new FileSnakeSource();
		listener = new TestSourceListener();
		source.addListener(listener);
	}

	@Test
	public void noInstanceFile() throws Exception {
		try {
			source.initialize(new DefaultSnakeInstance());
			fail("should have terminated");
		}
		catch (RuntimeException rex) {
			assertThat(rex.getMessage()).isEqualTo("No snake instance properties-file exists.\n(searched in " + dirTest + "/instance.properties)");
		}
	}

	@Test
	public void removeInstanceFile() throws Exception {
		copy("instance.properties", "instance.properties");
		source.initialize(new DefaultSnakeInstance());
		remove("instance.properties");
		Sleeper.sleep("200ms");

		assertThat(listener.listAdded).hasSize(0);
		assertThat(listener.listRemoved).hasSize(2);
		assertThat(listener.listUpdated).hasSize(0);
		assertThat(listener.refreshed).isEqualTo(1);
		assertThat(listener.listRemoved).containsOnly(new EventBean("aaa", "111"), new EventBean("bbb", "222"));
	}

	@Test
	public void onlyInstanceFile() throws Exception {
		copy("instance.properties", "instance.properties");
		source.initialize(new DefaultSnakeInstance());
		assertThat(source.getProperties()).containsOnly(entry("aaa", "111"), entry("bbb", "222"));

		assertThat(listener.listAdded).hasSize(0);
		assertThat(listener.listRemoved).hasSize(0);
		assertThat(listener.listUpdated).hasSize(0);
		assertThat(listener.refreshed).isEqualTo(0);
	}

	@Test
	public void instanceAndUserProperties() throws Exception {
		copy("instance.properties", "instance.properties");
		copy("user.properties", userPropertiesFile);
		source.initialize(new DefaultSnakeInstance());
		assertThat(source.getProperties()).containsOnly(entry("aaa", "111"), entry("bbb", "333"), entry("ccc", "444"));

		assertThat(listener.listAdded).hasSize(0);
		assertThat(listener.listRemoved).hasSize(0);
		assertThat(listener.listUpdated).hasSize(0);
		assertThat(listener.refreshed).isEqualTo(0);
	}

	@Test
	public void onlyInstanceFileAddingUserFileLater() throws Exception {
		copy("instance.properties", "instance.properties");
		source.initialize(new DefaultSnakeInstance());
		copy("user.properties", userPropertiesFile);
		Sleeper.sleep("200ms");
		assertThat(source.getProperties()).containsOnly(entry("aaa", "111"), entry("bbb", "333"), entry("ccc", "444"));

		assertThat(listener.listAdded).hasSize(1);
		assertThat(listener.listRemoved).hasSize(0);
		assertThat(listener.listUpdated).hasSize(1);
		assertThat(listener.refreshed).isEqualTo(1);
		assertThat(listener.listAdded).containsOnly(new EventBean("ccc", "444"));
		assertThat(listener.listUpdated).containsOnly(new UpdatedBean("bbb", "333", "222"));
	}

	@Test
	public void removeUserPropertiesLater() throws Exception {
		copy("instance.properties", "instance.properties");
		copy("user.properties", userPropertiesFile);
		source.initialize(new DefaultSnakeInstance());
		remove(userPropertiesFile);
		Sleeper.sleep("200ms");

		assertThat(listener.listAdded).hasSize(0);
		assertThat(listener.listRemoved).hasSize(1);
		assertThat(listener.listUpdated).hasSize(1);
		assertThat(listener.refreshed).isEqualTo(1);
		assertThat(listener.listRemoved).containsOnly(new EventBean("ccc", "444"));
		assertThat(listener.listUpdated).containsOnly(new UpdatedBean("bbb", "222", "333"));
	}

	@Test
	public void notObserving() throws Exception {
		System.setProperty(FileSnakeSource.PROPERTY_OBSERVE, "false");
		copy("instance.properties", "instance.properties");
		copy("user.properties", userPropertiesFile);
		source.initialize(new DefaultSnakeInstance());
		Sleeper.sleep("200ms");

	}

	protected void copy(String from, String to) throws IOException {
		FileUtils.copyFile(new File(Resources.getResource(getClass(), from).getFile()), new File(dirTest, to));
	}

	protected void remove(String file) {
		new File(dirTest, file).delete();
	}

}


text:
For the input `11` the code will output:
```text
Please enter a decimal number:
The binary representation for the number 11 is 1011
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

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

  <camelContext xmlns="http://camel.apache.org/schema/spring">

    <!-- ************************************* -->
    <!-- Routes                                -->
    <!-- ************************************* -->

    <route id="scall">
      <from uri="direct:start"/>
      <serviceCall name="http-service" component="http">
        <zookeeperServiceDiscovery nodes="{{container:host:zookeeper}}:{{container:port:2181@zookeeper}}" basePath="/camel"/>
      </serviceCall>
      <to uri="mock:result"/>
    </route>

    <route>
      <from uri="jetty:http://localhost:{{available-port:service-1}}"/>
      <transform>
        <simple>${body} svc1</simple>
      </transform>
    </route>

    <route>
      <from uri="jetty:http://localhost:{{available-port:service-2}}"/>
      <transform>
        <simple>${body} svc2</simple>
      </transform>
    </route>

    <route>
      <from uri="jetty:http://localhost:{{available-port:service-3}}"/>
      <transform>
        <simple>${body} svc3</simple>
      </transform>
    </route>

  </camelContext>

</beans>


text:
class LocationsController < ApplicationController

  before_filter :find_all_locations
  before_filter :find_page

  def index
    # you can use meta fields from your model instead (e.g. browser_title)
    # by swapping @page for @location in the line below:
    present(@page)
  end

  def show
    @location = Location.find(params[:id])

    # you can use meta fields from your model instead (e.g. browser_title)
    # by swapping @page for @location in the line below:
    present(@page)
  end

protected

  def find_all_locations
    @locations = Location.find(:all, :order => "position ASC")
  end

  def find_page
    @page = Page.find_by_link_url("/locations")
  end

end


text:
{% extends "front_layout.html" %}

{% block content %}

 Future health assessment

Accessibility

    {% include "includes/prototype_banner.html" %}

Edit these files on GitHub.

Case study

Case list

View

Prototype

Review

View review

Prototype

Assessment

View assessment

Prototype

Appointment

View appointment

Prototype

MVP journey

View MVP

</>
{% endblock %}


text:
package co.cask.cdap.internal.app.mapreduce;

import co.cask.cdap.api.Resources;
import co.cask.cdap.api.mapreduce.MapReduce;
import co.cask.cdap.api.mapreduce.MapReduceConfigurer;
import co.cask.cdap.api.mapreduce.MapReduceSpecification;
import co.cask.cdap.internal.app.DefaultPluginConfigurer;
import co.cask.cdap.internal.app.runtime.artifact.ArtifactRepository;
import co.cask.cdap.internal.app.runtime.plugin.PluginInstantiator;
import co.cask.cdap.proto.Id;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import java.util.Map;
import java.util.Set;

/**
 * Default implementation of {@link MapReduceConfigurer}.
 */
public final class DefaultMapReduceConfigurer extends DefaultPluginConfigurer implements MapReduceConfigurer {

  private final String className;
  private String name;
  private String description;
  private Map<String, String> properties;
  private Set<String> datasets;
  private String inputDataset;
  private String outputDataset;
  private Resources driverResources;
  private Resources mapperResources;
  private Resources reducerResources;

  public DefaultMapReduceConfigurer(MapReduce mapReduce, Id.Namespace deployNamespace, Id.Artifact artifactId,
                                    ArtifactRepository artifactRepository,
                                    PluginInstantiator pluginInstantiator) {
    super(deployNamespace, artifactId, artifactRepository, pluginInstantiator);
    this.className = mapReduce.getClass().getName();
    this.name = mapReduce.getClass().getSimpleName();
    this.description = "";
    this.datasets = ImmutableSet.of();
  }

  @Override
  public void setName(String name) {
    this.name = name;
  }

  @Override
  public void setDescription(String description) {
    this.description = description;
  }

  @Override
  public void setProperties(Map<String, String> properties) {
    this.properties = ImmutableMap.copyOf(properties);
  }

  @Override
  public void useDatasets(Iterable<String> datasets) {
    this.datasets = ImmutableSet.copyOf(datasets);
  }

  @Override
  public void setInputDataset(String dataset) {
    this.inputDataset = dataset;
  }

  @Override
  public void setOutputDataset(String dataset) {
    this.outputDataset = dataset;
  }

  @Override
  public void setDriverResources(Resources resources) {
    this.driverResources = resources;
  }

  @Override
  public void setMapperResources(Resources resources) {
    this.mapperResources = resources;
  }

  @Override
  public void setReducerResources(Resources resources) {
    this.reducerResources = resources;
  }

  public MapReduceSpecification createSpecification() {
    return new MapReduceSpecification(className, name, description, inputDataset, outputDataset, datasets,
                                      properties, driverResources, mapperResources, reducerResources);
  }
}


text:
package org.apache.archiva.indexer.maven.search;

import junit.framework.TestCase;
import org.apache.archiva.indexer.search.SearchResultHit;
import org.apache.archiva.indexer.search.SearchResultLimits;
import org.apache.archiva.indexer.search.SearchResults;
import org.apache.archiva.indexer.util.SearchUtil;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;

import java.util.Arrays;

/**
 * @author Olivier Lamy
 */
@RunWith( ArchivaSpringJUnit4ClassRunner.class )
@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
public class MavenRepositorySearchPaginateTest
    extends TestCase
{

    @Autowired
    RepositoryRegistry repositoryRegistry;

    @After
    public void endTests() {
        assert repositoryRegistry!=null;
        repositoryRegistry.destroy();
    }

    @Test
    public void nonPaginatedResult()
        throws Exception
    {
        MavenRepositorySearch search = new MavenRepositorySearch();

        SearchResults searchResults = build( 10, new SearchResultLimits( 0 ) );

        searchResults = search.paginate( searchResults );

        assertEquals( 10, searchResults.getReturnedHitsCount() );

    }

    @Test
    public void nonPaginatedHugeResult()
        throws Exception
    {
        MavenRepositorySearch search = new MavenRepositorySearch();

        SearchResults origSearchResults = build( 63, new SearchResultLimits( 0 ) );

        SearchResults searchResults = search.paginate( origSearchResults );

        assertEquals( 30, searchResults.getReturnedHitsCount() );

        origSearchResults = build( 63, new SearchResultLimits( 1 ) );

        searchResults = search.paginate( origSearchResults );

        assertEquals( 30, searchResults.getReturnedHitsCount() );

    }

    @Test
    public void paginatedResult()
        throws Exception
    {
        MavenRepositorySearch search = new MavenRepositorySearch();

        SearchResults searchResults = build( 32, new SearchResultLimits( 1 ) );

        searchResults = search.paginate( searchResults );

        assertEquals( 2, searchResults.getReturnedHitsCount() );

    }

    SearchResults build( int number, SearchResultLimits limits )
    {
        SearchResults searchResults = new SearchResults();
        searchResults.setLimits( limits );
        for ( int i = 0; i < number; i++ )
        {
            SearchResultHit hit = new SearchResultHit();
            hit.setGroupId( "commons-foo" );
            hit.setArtifactId( "commons-bar-" + i );
            hit.setPackaging( "jar" );
            hit.setVersions( Arrays.asList( "1.0" ) );
            String id =
                SearchUtil.getHitId( hit.getGroupId(), hit.getArtifactId(), hit.getClassifier(), hit.getPackaging() );
            searchResults.addHit( id, hit );
        }

        searchResults.setTotalHits( number );
        return searchResults;

    }
}


text:
package com.twitter.scalding

import cascading.pipe._
import cascading.pipe.joiner._
import cascading.tuple._

import java.lang.reflect.Method
import java.lang.reflect.Constructor

import scala.reflect.Manifest

/** Base class for classes which pack a Tuple into a serializable object.
  *
  * @author Argyris Zymnis
  * @author Oscar Boykin
  */
object TuplePacker extends CaseClassPackers
abstract class TuplePacker[T] extends java.io.Serializable {
  def newConverter(fields : Fields) : TupleConverter[T]
}

trait CaseClassPackers extends LowPriorityTuplePackers {
  implicit def caseClassPacker[T <: Product](implicit mf : Manifest[T]) = new OrderedTuplePacker[T]
}

trait LowPriorityTuplePackers extends TupleConversions {
  implicit def genericTuplePacker[T : Manifest] = new ReflectionTuplePacker[T]
}

/** Packs a tuple into any object with set methods, e.g. thrift or proto objects.
  * TODO: verify that protobuf setters for field camel_name are of the form setCamelName.
  * In that case this code works for proto.
  *
  * @author Argyris Zymnis
  * @author Oscar Boykin
  */
class ReflectionTuplePacker[T](implicit m : Manifest[T]) extends TuplePacker[T] {
  override def newConverter(fields : Fields) = new ReflectionTupleConverter[T](fields)(m)
}

class ReflectionTupleConverter[T](fields : Fields)(implicit m : Manifest[T]) extends TupleConverter[T] {
  override val arity = fields.size

  def lowerFirst(s : String) = s.substring(0,1).toLowerCase + s.substring(1)
  // Cut out "set" and lower case the first after
  def setterToFieldName(setter : Method) = lowerFirst(setter.getName.substring(3))

  def validate {
    //We can't touch setters because that shouldn't be accessed until map/reduce side, not
    //on submitter.
    val missing = Dsl.asList(fields).filter { f => !getSetters.contains(f.toString) }.headOption
    assert(missing.isEmpty, "Field: " + missing.get.toString + " not in setters")
  }
  validate

  def getSetters = m.erasure
    .getDeclaredMethods
    .filter { _.getName.startsWith("set") }
    .groupBy { setterToFieldName(_) }
    .mapValues { _.head }

  // Do all the reflection for the setters we need:
  // This needs to be lazy because Method is not serializable
  // TODO: filter by isAccessible, which somehow seems to fail
  lazy val setters = getSetters

  override def apply(input : TupleEntry) : T = {
    val newInst = m.erasure.newInstance()
    val fields = input.getFields
    (0 until fields.size).map { idx =>
      val thisField = fields.get(idx)
      val setMethod = setters(thisField.toString)
      setMethod.invoke(newInst, input.getObject(thisField))
    }
    newInst.asInstanceOf[T]
  }
}

/**
 * This just blindly uses the first public constructor with the same arity as the fields size
 */
class OrderedTuplePacker[T](implicit m : Manifest[T]) extends TuplePacker[T] {
  override def newConverter(fields : Fields) = new OrderedConstructorConverter[T](fields)(m)
}

class OrderedConstructorConverter[T](fields : Fields)(implicit mf : Manifest[T]) extends TupleConverter[T] {
  override val arity = fields.size
  // Keep this as a method, so we can validate by calling, but don't serialize it, and keep it lazy
  // below
  def getConstructor = mf.erasure
    .getConstructors
    .filter { _.getParameterTypes.size == fields.size }
    .head.asInstanceOf[Constructor[T]]

  //Make sure we can actually get a constructor:
  getConstructor

  lazy val cons = getConstructor

  override def apply(input : TupleEntry) : T = {
    val tup = input.getTuple
    val args = (0 until tup.size).map { tup.getObject(_) }
    cons.newInstance(args : _*)
  }
}


text:
package org.apache.kafka.streams.scala
package kstream

import org.apache.kafka.streams.kstream.{KGroupedTable => KGroupedTableJ, _}
import org.apache.kafka.streams.scala.ImplicitConversions._
import org.apache.kafka.streams.scala.FunctionConversions._

/**
 * Wraps the Java class KGroupedTable and delegates method calls to the underlying Java object.
 *
 * @param [K] Type of keys
 * @param [V] Type of values
 * @param inner The underlying Java abstraction for KGroupedTable
 *
 * @see `org.apache.kafka.streams.kstream.KGroupedTable`
 */
class KGroupedTable[K, V](inner: KGroupedTableJ[K, V]) {

  /**
   * Count number of records of the original [[KTable]] that got [[KTable#groupBy]] to
   * the same key into a new instance of [[KTable]].
   *
   * @return a [[KTable]] that contains "update" records with unmodified keys and `Long` values that
   * represent the latest (rolling) count (i.e., number of records) for each key
   * @see `org.apache.kafka.streams.kstream.KGroupedTable#count`
   */
  def count(): KTable[K, Long] = {
    val c: KTable[K, java.lang.Long] = inner.count()
    c.mapValues[Long](Long2long(_))
  }

  /**
   * Count number of records of the original [[KTable]] that got [[KTable#groupBy]] to
   * the same key into a new instance of [[KTable]].
   *
   * @param materialized  an instance of `Materialized` used to materialize a state store.
   * @return a [[KTable]] that contains "update" records with unmodified keys and `Long` values that
   * represent the latest (rolling) count (i.e., number of records) for each key
   * @see `org.apache.kafka.streams.kstream.KGroupedTable#count`
   */
  def count(materialized: Materialized[K, Long, ByteArrayKeyValueStore]): KTable[K, Long] =
    inner.count(materialized)

  /**
   * Combine the value of records of the original [[KTable]] that got [[KTable#groupBy]]
   * to the same key into a new instance of [[KTable]].
   *
   * @param adder      a function that adds a new value to the aggregate result
   * @param subtractor a function that removed an old value from the aggregate result
   * @return a [[KTable]] that contains "update" records with unmodified keys, and values that represent the
   * latest (rolling) aggregate for each key
   * @see `org.apache.kafka.streams.kstream.KGroupedTable#reduce`
   */
  def reduce(adder: (V, V) => V,
             subtractor: (V, V) => V): KTable[K, V] = {

    // need this explicit asReducer for Scala 2.11 or else the SAM conversion doesn't take place
    // works perfectly with Scala 2.12 though
    inner.reduce(adder.asReducer, subtractor.asReducer)
  }

  /**
   * Combine the value of records of the original [[KTable]] that got [[KTable#groupBy]]
   * to the same key into a new instance of [[KTable]].
   *
   * @param adder      a function that adds a new value to the aggregate result
   * @param subtractor a function that removed an old value from the aggregate result
   * @param materialized  an instance of `Materialized` used to materialize a state store.
   * @return a [[KTable]] that contains "update" records with unmodified keys, and values that represent the
   * latest (rolling) aggregate for each key
   * @see `org.apache.kafka.streams.kstream.KGroupedTable#reduce`
   */
  def reduce(adder: (V, V) => V,
             subtractor: (V, V) => V,
             materialized: Materialized[K, V, ByteArrayKeyValueStore]): KTable[K, V] = {

    // need this explicit asReducer for Scala 2.11 or else the SAM conversion doesn't take place
    // works perfectly with Scala 2.12 though
    inner.reduce(adder.asReducer, subtractor.asReducer, materialized)
  }

  /**
   * Aggregate the value of records of the original [[KTable]] that got [[KTable#groupBy]]
   * to the same key into a new instance of [[KTable]] using default serializers and deserializers.
   *
   * @param initializer a function that provides an initial aggregate result value
   * @param adder       a function that adds a new record to the aggregate result
   * @param subtractor  an aggregator function that removed an old record from the aggregate result
   * @return a [[KTable]] that contains "update" records with unmodified keys, and values that represent the
   * latest (rolling) aggregate for each key
   * @see `org.apache.kafka.streams.kstream.KGroupedTable#aggregate`
   */
  def aggregate[VR](initializer: () => VR,
                    adder: (K, V, VR) => VR,
                    subtractor: (K, V, VR) => VR): KTable[K, VR] = {

    inner.aggregate(initializer.asInitializer, adder.asAggregator, subtractor.asAggregator)
  }

  /**
   * Aggregate the value of records of the original [[KTable]] that got [[KTable#groupBy]]
   * to the same key into a new instance of [[KTable]] using default serializers and deserializers.
   *
   * @param initializer a function that provides an initial aggregate result value
   * @param adder       a function that adds a new record to the aggregate result
   * @param subtractor  an aggregator function that removed an old record from the aggregate result
   * @param materialized  an instance of `Materialized` used to materialize a state store.
   * @return a [[KTable]] that contains "update" records with unmodified keys, and values that represent the
   * latest (rolling) aggregate for each key
   * @see `org.apache.kafka.streams.kstream.KGroupedTable#aggregate`
   */
  def aggregate[VR](initializer: () => VR,
                    adder: (K, V, VR) => VR,
                    subtractor: (K, V, VR) => VR,
                    materialized: Materialized[K, VR, ByteArrayKeyValueStore]): KTable[K, VR] = {

    inner.aggregate(initializer.asInitializer, adder.asAggregator, subtractor.asAggregator, materialized)
  }
}


text:
//============================================================================
//
// Copyright (C) 2006-2022 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
//============================================================================
package org.talend.components.jdbc.tjdbcconnection;

import java.util.EnumSet;
import java.util.Set;

import org.talend.components.api.component.AbstractComponentDefinition;
import org.talend.components.api.component.ConnectorTopology;
import org.talend.components.api.component.runtime.ExecutionEngine;
import org.talend.components.api.properties.ComponentProperties;
import org.talend.components.jdbc.JdbcRuntimeInfo;
import org.talend.components.jdbc.wizard.JDBCConnectionWizardProperties;
import org.talend.daikon.properties.property.Property;
import org.talend.daikon.runtime.RuntimeInfo;

/**
 * JDBC connection component
 *
 */
public class TJDBCConnectionDefinition extends AbstractComponentDefinition {

    public static final String COMPONENT_NAME = "tJDBCConnection";

    public TJDBCConnectionDefinition() {
        super(COMPONENT_NAME, ExecutionEngine.DI);
    }

    @Override
    public Class<? extends ComponentProperties> getPropertyClass() {
        return TJDBCConnectionProperties.class;
    }

    @Override
    public String[] getFamilies() {
        return new String[] { "Databases/DB Specifics/JDBC", "ELT/Connections" };
    }

    @SuppressWarnings("rawtypes")
    @Override
    public Property[] getReturnProperties() {
        return new Property[] { RETURN_ERROR_MESSAGE_PROP };
    }

    @Override
    public boolean isStartable() {
        return true;

    }

    @Override
    public RuntimeInfo getRuntimeInfo(ExecutionEngine engine, ComponentProperties properties,
            ConnectorTopology connectorTopology) {
        assertEngineCompatibility(engine);
        if (connectorTopology == ConnectorTopology.NONE) {
            return new JdbcRuntimeInfo((TJDBCConnectionProperties) properties,
                    "org.talend.components.jdbc.runtime.JDBCSourceOrSink");
        }
        return null;
    }

    @Override
    public Set<ConnectorTopology> getSupportedConnectorTopologies() {
        return EnumSet.of(ConnectorTopology.NONE);
    }

    @Override
    public Class<? extends ComponentProperties>[] getNestedCompatibleComponentPropertiesClass() {
        return new Class[] { JDBCConnectionWizardProperties.class };
    }

}


text:
#include "chipmunk/chipmunk_private.h"

static cpFloat
defaultSpringForce(cpDampedSpring *spring, cpFloat dist){
	return (spring->restLength - dist)*spring->stiffness;
}

static void
preStep(cpDampedSpring *spring, cpFloat dt)
{
	cpBody *a = spring->constraint.a;
	cpBody *b = spring->constraint.b;

	spring->r1 = cpTransformVect(a->transform, cpvsub(spring->anchr1, a->cog));
	spring->r2 = cpTransformVect(b->transform, cpvsub(spring->anchr2, b->cog));

	cpVect delta = cpvsub(cpvadd(b->p, spring->r2), cpvadd(a->p, spring->r1));
	cpFloat dist = cpvlength(delta);
	spring->n = cpvmult(delta, 1.0f/(dist ? dist : INFINITY));

	cpFloat k = k_scalar(a, b, spring->r1, spring->r2, spring->n);
	cpAssertSoft(k != 0.0, "Unsolvable spring.");
	spring->nMass = 1.0f/k;

	spring->target_vrn = 0.0f;
	spring->v_coef = 1.0f - cpfexp(-spring->damping*dt*k);

	// apply spring force
	cpFloat f_spring = spring->springForceFunc((cpConstraint *)spring, dist);
	cpFloat j_spring = spring->jAcc = f_spring*dt;
	apply_impulses(a, b, spring->r1, spring->r2, cpvmult(spring->n, j_spring));
}

static void applyCachedImpulse(cpDampedSpring *spring, cpFloat dt_coef){}

static void
applyImpulse(cpDampedSpring *spring, cpFloat dt)
{
	cpBody *a = spring->constraint.a;
	cpBody *b = spring->constraint.b;

	cpVect n = spring->n;
	cpVect r1 = spring->r1;
	cpVect r2 = spring->r2;

	// compute relative velocity
	cpFloat vrn = normal_relative_velocity(a, b, r1, r2, n);

	// compute velocity loss from drag
	cpFloat v_damp = (spring->target_vrn - vrn)*spring->v_coef;
	spring->target_vrn = vrn + v_damp;

	cpFloat j_damp = v_damp*spring->nMass;
	spring->jAcc += j_damp;
	apply_impulses(a, b, spring->r1, spring->r2, cpvmult(spring->n, j_damp));
}

static cpFloat
getImpulse(cpDampedSpring *spring)
{
	return spring->jAcc;
}

static const cpConstraintClass klass = {
	(cpConstraintPreStepImpl)preStep,
	(cpConstraintApplyCachedImpulseImpl)applyCachedImpulse,
	(cpConstraintApplyImpulseImpl)applyImpulse,
	(cpConstraintGetImpulseImpl)getImpulse,
};
CP_DefineClassGetter(cpDampedSpring)

cpDampedSpring *
cpDampedSpringAlloc(void)
{
	return (cpDampedSpring *)cpcalloc(1, sizeof(cpDampedSpring));
}

cpDampedSpring *
cpDampedSpringInit(cpDampedSpring *spring, cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping)
{
	cpConstraintInit((cpConstraint *)spring, cpDampedSpringGetClass(), a, b);

	spring->anchr1 = anchr1;
	spring->anchr2 = anchr2;

	spring->restLength = restLength;
	spring->stiffness = stiffness;
	spring->damping = damping;
	spring->springForceFunc = (cpDampedSpringForceFunc)defaultSpringForce;

	spring->jAcc = 0.0f;

	return spring;
}

cpConstraint *
cpDampedSpringNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping)
{
	return (cpConstraint *)cpDampedSpringInit(cpDampedSpringAlloc(), a, b, anchr1, anchr2, restLength, stiffness, damping);
}


text:
title: 'Slides From My DevIgnition Polyglot AS Presentation'
author: Toby Crawley
layout: news
tags: [ presentations, event, polyglot, torquebox ]
---

This past Friday I had the pleasure of presenting "The Polyglot Future of JBoss AS" to an audience of
mostly Java developers at [DevIgnition](http://devignition.com/)
in [NoVA](http://en.wikipedia.org/wiki/Northern_Virginia).

Thanks to [Gray Herter](http://www.linkedin.com/pub/gray-herter/a/60a/111) for organizing a
great conference, and to [Booz Allen Hamilton](http://www.boozallen.com/) for sharing their
kick-butt conference center.

If you are interested in the code for the demo, that's [here](https://github.com/tobias/dev-ignition-demo).

The talk was recorded, so once that recording is available I'll update this post to point to it.

Here are my slides from that presentation for the enjoyment of all:


text:
class Reader;

class CategoriesHolder
{
public:
  struct Category
  {
    static constexpr uint8_t kEmptyPrefixLength = 10;

    struct Name
    {
      string m_name;
      /// This language/locale code is completely different from our built-in langs in multilang_utf8_string.cpp
      /// and is only used for mapping user's input language to our values in categories.txt file
      int8_t m_locale;
      uint8_t m_prefixLengthToSuggest;
    };

    deque<Name> m_synonyms;

    inline void Swap(Category & r)
    {
      m_synonyms.swap(r.m_synonyms);
    }
  };

  struct Mapping
  {
    char const * m_name;
    int8_t m_code;
  };

  using GroupTranslations = unordered_map<string, vector<Category::Name>>;

private:
  using String = strings::UniString;
  using Type2CategoryCont = multimap<uint32_t, shared_ptr<Category>>;
  using Trie = base::MemTrie<String, base::VectorValues<uint32_t>>;

  Type2CategoryCont m_type2cat;

  // Maps locale and category token to the list of corresponding types.
  // Locale is treated as a special symbol prepended to the token.
  Trie m_name2type;

  GroupTranslations m_groupTranslations;

public:
  static int8_t constexpr kEnglishCode = 1;
  static int8_t constexpr kUnsupportedLocaleCode = -1;
  static uint8_t constexpr kMaxSupportedLocaleIndex = 31;
  static vector<Mapping> const kLocaleMapping;

  // List of languages that are currently disabled in the application
  // because their translations are not yet complete.
  static vector<string> kDisabledLanguages;

  explicit CategoriesHolder(unique_ptr<Reader> && reader);
  void LoadFromStream(istream & s);

  template <class ToDo>
  void ForEachCategory(ToDo && toDo) const
  {
    for (auto const & p : m_type2cat)
      toDo(*p.second);
  }

  template <class ToDo>
  void ForEachTypeAndCategory(ToDo && toDo) const
  {
    for (auto const it : m_type2cat)
      toDo(it.first, *it.second);
  }

  template <class ToDo>
  void ForEachName(ToDo && toDo) const
  {
    for (auto const & p : m_type2cat)
    {
      for (auto const & synonym : p.second->m_synonyms)
        toDo(synonym);
    }
  }

  template <class ToDo>
  void ForEachNameByType(uint32_t type, ToDo && toDo) const
  {
    auto it = m_type2cat.find(type);
    if (it == m_type2cat.end())
      return;
    for (auto const & name : it->second->m_synonyms)
      toDo(name);
  }

  template <class ToDo>
  void ForEachTypeByName(int8_t locale, String const & name, ToDo && toDo) const
  {
    auto const localePrefix = String(1, static_cast<strings::UniChar>(locale));
    m_name2type.ForEachInNode(localePrefix + name, forward<ToDo>(toDo));
  }

  inline GroupTranslations const & GetGroupTranslations() const { return m_groupTranslations; }

  /// Search name for type with preffered locale language.
  /// If no name for this language, return en name.
  /// @return false if no categories for type.
  bool GetNameByType(uint32_t type, int8_t locale, string & name) const;

  /// @returns raw classificator type if it's not localized in categories.txt.
  string GetReadableFeatureType(uint32_t type, int8_t locale) const;

  // Exposes the tries that map category tokens to types.
  Trie const & GetNameToTypesTrie() const { return m_name2type; }
  bool IsTypeExist(uint32_t type) const;

  inline void Swap(CategoriesHolder & r)
  {
    m_type2cat.swap(r.m_type2cat);
    std::swap(m_name2type, r.m_name2type);
  }

  // Converts any language |locale| from UI to the corresponding
  // internal integer code.
  static int8_t MapLocaleToInteger(string const & locale);

  // Returns corresponding string representation for an internal
  // integer |code|. Returns an empty string in case of invalid
  // |code|.
  static string MapIntegerToLocale(int8_t code);

private:
  void AddCategory(Category & cat, vector<uint32_t> & types);
  static bool ValidKeyToken(String const & s);
};

inline void swap(CategoriesHolder & a, CategoriesHolder & b)
{
  return a.Swap(b);
}

// Defined in categories_holder_loader.cpp.
CategoriesHolder const & GetDefaultCategories();


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.sakaiproject</groupId>
        <artifactId>master</artifactId>
        <version>10.1</version>
        <relativePath>../master/pom.xml</relativePath>
    </parent>

    <name>Sakai Hierarchy</name>
    <groupId>org.sakaiproject</groupId>
    <artifactId>hierarchy</artifactId>
    <version>10.1</version>

    <packaging>pom</packaging>

    <organization>
        <name>Apereo Foundation</name>
        <url>http://apereo.org</url>
    </organization>
    <inceptionYear>2007</inceptionYear>

    <description>
        Hierarchy is meant to provide a high performance basic hierarchy to associate data
        with, no data is stored in the hierarchy itself, it is simply there to allow you
        to maintain the hierarchical structure and to provide methods to manipulate it and
        query it
    </description>

    <profiles>
        <profile>
            <id>full</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <modules>
                <module>api</module>
                <module>impl</module>
                <module>pack</module>
            </modules>
        </profile>
        <profile>
            <id>api</id>
            <modules>
                <module>api</module>
            </modules>
        </profile>
        <profile>
            <id>ddl</id>
            <modules>
                <module>impl/src/ddl</module>
            </modules>
        </profile>
    </profiles>

    <developers>
        <developer>
            <id>aaronz</id>
            <name>Aaron Zeckoski</name>
            <email>azeckoski@unicon.net</email>
            <roles>
                <role>Project Manager</role>
                <role>Architect</role>
                <role>Developer</role>
            </roles>
            <timezone>0</timezone>
        </developer>
    </developers>

    <contributors>
        <contributor>
            <name>Anthony Whyte</name>
            <email>arwhyte@umich.edu</email>
        </contributor>
    </contributors>

    <scm>
        <connection>scm:svn:https://source.sakaiproject.org/svn/hierarchy/trunk</connection>
        <developerConnection>scm:svn:https://source.sakaiproject.org/svn/hierarchy/trunk</developerConnection>
        <url>https://source.sakaiproject.org/svn/hierarchy/</url>
    </scm>

    <dependencyManagement>
        <dependencies>
            <dependency>
                 <groupId>org.sakaiproject.hierarchy</groupId>
                 <artifactId>hierarchy-api</artifactId>
                 <version>${project.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                 <groupId>org.sakaiproject.hierarchy</groupId>
                 <artifactId>hierarchy-impl</artifactId>
                <version>${project.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>


text: Two fingers are pinching


text:
package tv.savageboy74.fluxutils.common.block;

import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import tv.savageboy74.fluxutils.common.creativetab.FluxCreativeTab;

public abstract class FluxBlockContainer extends FluxBlock implements ITileEntityProvider
{

    public FluxBlockContainer(Material material)
    {
        super(material);
        this.isBlockContainer = true;
        this.setCreativeTab(FluxCreativeTab.fluxTab);
    }

    public FluxBlockContainer()
    {
        super(Material.rock);
    }

    @Override
    public boolean onBlockEventReceived(World world, int x, int y, int z, int eventNumber, int arg)
    {
        super.onBlockEventReceived(world, x, y, z, eventNumber, arg);
        TileEntity tileentity = world.getTileEntity(x, y, z);
        if (tileentity != null)
        {
            return tileentity.receiveClientEvent(eventNumber, arg);
        }
        return false;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall;
using FlatRedBall.Input;
using FlatRedBall.Instructions;
using FlatRedBall.AI.Pathfinding;
using FlatRedBall.Graphics.Animation;
using FlatRedBall.Graphics.Particle;

using FlatRedBall.Math.Geometry;
using FlatRedBall.Math.Splines;

using Cursor = FlatRedBall.Gui.Cursor;
using GuiManager = FlatRedBall.Gui.GuiManager;
using FlatRedBall.Localization;
using FlatRedBall.IO;

#if FRB_XNA || SILVERLIGHT
using Keys = Microsoft.Xna.Framework.Input.Keys;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
using FlatRedBall.Content.Scene;
#endif

namespace GlueTestProject.Screens
{
	public partial class XmlScreen
	{

		void CustomInitialize()
		{
            SpriteSave spriteSave = new SpriteSave();
            spriteSave.X = 4;
            FileManager.InitializeUserFolder("Global");

            string directory = FileManager.GetUserFolder("Global");
            string fileName = directory + "TestSave.xml";
            FileManager.XmlSerialize(spriteSave, fileName);

            if(FileManager.FileExists(fileName) == false)
            {
                throw new Exception("The file " + fileName + " does not exist");
            }

            var loaded = FileManager.XmlDeserialize<SpriteSave>(fileName);

            if (loaded.X != 4)
            {
                throw new Exception("XML serialization is not working properly");
            }

            string fileToAddAndDelete = directory + "DeleteMe.xml";
            FileManager.XmlSerialize<SpriteSave>(spriteSave, fileName);
            FileManager.DeleteFile(fileName);

		}

		void CustomActivity(bool firstTimeCalled)
		{
            if (!firstTimeCalled)
            {
                IsActivityFinished = true;
            }

		}

		void CustomDestroy()
		{

		}

        static void CustomLoadStaticContent(string contentManagerName)
        {

        }

	}
}


text:
package org.kaazing.gateway.transport.http.bridge.filter;

import org.kaazing.gateway.resource.address.ResourceAddress;
import org.kaazing.gateway.transport.http.bridge.HttpRequestMessage;
import org.kaazing.gateway.transport.http.bridge.HttpResponseMessage;
import org.kaazing.mina.core.future.DefaultWriteFutureEx;
import org.kaazing.mina.core.write.DefaultWriteRequestEx;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;

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

import static org.kaazing.gateway.transport.http.HttpStatus.CLIENT_NOT_FOUND;
import static org.kaazing.gateway.transport.http.HttpVersion.HTTP_1_1;

/**
 * This filter matches entire request path with bind address path in certain cases.
 *
 * In WSE case, binding contains /echo, /echo/;e/db/sessionid1, /echo/;e/db/sessionid2 etc.
 * If there is a request with /echo/;e/db/sessionid-foo, it matches /echo binding.
 * This catches it and sends 404 earlier before the request go to wse layer.
 */
public class HttpPathMatchingFilter extends HttpFilterAdapter<IoSession> {

    private static final List<String> WSE_FULL_MATCHING_PATHS = Arrays.asList("/;e/ub", "/;e/db", "/;e/ut", "/;e/dt",
            "/;e/ute", "/;e/dte", "/;e/ubm", "/;e/dbm", "/;e/utm", "/;e/dtm", "/;e/utem", "/;e/dtem");

    @Override
    protected void httpRequestReceived(NextFilter nextFilter, IoSession session, HttpRequestMessage httpRequest)
            throws Exception {

        ResourceAddress bindAddress = httpRequest.getLocalAddress();
        String nextProtocol = bindAddress.getOption(ResourceAddress.NEXT_PROTOCOL);
        if (nextProtocol == null || !nextProtocol.equals("httpxe/1.1")) {
            super.httpRequestReceived(nextFilter, session, httpRequest);
            return;
        }

        String bindPath = bindAddress.getResource().getPath();
        String requestPath = httpRequest.getRequestURI().getPath();
        // Fix requestPath to overcome javascript client bug (which sends URI with & )
        // for e.g. /echo/;e/utm/waGcY3k5CDLMxy0mNvijdpXRtHxFjt5Z&.krn=0.7393842079985082)
        int index = requestPath.indexOf('&');
        if (index != -1) {
            requestPath = requestPath.substring(0, index);
        }

        boolean match = true;
        for(String wsePath : WSE_FULL_MATCHING_PATHS) {
            if (requestPath.contains(wsePath)) {
                match = requestPath.equals(bindPath);
            }
        }

        if (match) {
            super.httpRequestReceived(nextFilter, session, httpRequest);
        } else {
            HttpResponseMessage httpResponse = new HttpResponseMessage();
            httpResponse.setVersion(HTTP_1_1);
            httpResponse.setStatus(CLIENT_NOT_FOUND);

            DefaultWriteFutureEx writeFuture = new DefaultWriteFutureEx(session);
            DefaultWriteRequestEx writeRequest = new DefaultWriteRequestEx(httpResponse, writeFuture);
            nextFilter.filterWrite(session, writeRequest);

            // Close after write
            writeRequest.getFuture().addListener(new IoFutureListener<WriteFuture>() {
                @Override
                public void operationComplete(WriteFuture future) {
                    IoSession session = future.getSession();

                    // close on flush at server
                    session.close(false);
                }
            });
        }
    }

}


text:
/*------------------------------Summary------------------------------------------------------
 * Product Name : REM
 * File Name	: UomConstant.cs
 * Author	    : Aries Zhang
 * Date Created : 2012-05-14
 * Description  : System constant UOM ids
--------------------------------------------------------------------------------------------*/

using SE.DSP.Foundation.Infrastructure.Enumerations;
using SE.DSP.Foundation.Infrastructure.Interception;
using SE.DSP.Foundation.Infrastructure.Utils;
using System;
namespace SE.DSP.Foundation.Infrastructure.Constant
{

    /// <summary>
    /// System constant UOM ids
    /// </summary>
    public class UomConstant
    {
        /// <summary>
        /// People count uom for hierarchy dynamic property
        /// </summary>
        public const long CONSTUOM_PEOPLECOUNT = 21;

        /// <summary>
        /// Area uom for hierarchy dynamic property
        /// </summary>
        public const long CONSTUOM_AREA = 13;

        /// <summary>
        /// Standard coal uom for carbon usage
        /// </summary>
        public const long CONSTUOM_STANDARDCOAL = 18;
        public const string CONSTUOM_STANDARDCOAL_CODE = "kgce";

        /// <summary>
        /// CO2 uom for carbon usage
        /// </summary>
        public const long CONSTUOM_CO2 = 19;
        public string CONSTUOM_CO2_CODE = "kgCO" + Convert.ToChar(0x2082);

        /// <summary>
        /// Tree uom for carbon usage
        /// </summary>
        public const long CONSTUOM_TREE = 20;
       // public const string CONSTUOM_TREE_CODE = "树";

        public static string CONSTUOM_TREE_CODE
        {
            get
            {
                return I18nHelper.GetValue(ServiceContext.Language, I18nResourceType.App, "Administration_CONSTUOM_TREE_CODE");
            }
        }

        /// <summary>
        /// Commodity that holds the constant UOMs
        /// </summary>
        public const long CONSTCOMMODITY_OTHER = 0;

        public const long CONSTCOMMODITY_Electricity = 1;

        public const long CONSTCOMMODITY_AIR = 12;

        public const long CONSTUOM_AIRQUALITY = 37;

        public const long CONSTUOM_KWH = 1;
        public const string CONSTUOM_KWH_CODE = "KWH";

        public const long CONSTUOM_T = 9;

        public string CONSTUOM_M2_CODE = "M" + Convert.ToChar(0x00b2);

        public const long CONSTUOM_M3 = 5;

        public const long CONSTUOM_RMB = 12;
        public const string CONSTUOM_RMB_CODE = "RMB";

        public const long CONSTUOM_PERSON = 21;
       // public const string CONSTUOM_PERSON_CODE = "人";

        public static string CONSTUOM_PERSON_CODE
        {
            get
            {
                return I18nHelper.GetValue(ServiceContext.Language, I18nResourceType.App, "Administration_CONSTUOM_PERSON_CODE");
            }
        }

        public const int COSTPRECISION = 2;
        public const int RATIOPRECISION = 2;
    }
}


text:
<com.tle.beans.item.Item>
  <id>35640</id>
  <uuid>5633cf6b-67a7-7734-9ebe-8f7e54fbf07f</uuid>
  <version>1</version>
  <owner>TLE_ADMINISTRATOR</owner>
  <dateModified class="sql-timestamp">2003-03-06 17:01:07.0</dateModified>
  <dateCreated class="sql-timestamp">2003-03-06 16:28:58.0</dateCreated>
  <dateForIndex class="sql-timestamp">1970-01-01 11:00:00.171</dateForIndex>
  <rating>-1.0</rating>
  <moderating>false</moderating>
  <status>LIVE</status>
  <attachments/>
  <searchDetails/>
  <itemDefinition entityclass="com.tle.beans.entity.itemdef.ItemDefinition" uuid="e8f050dd-f6c0-4cec-559f-e54d7ef19836"/>
  <collaborators/>
  <referencedUrls>
    <com.tle.beans.ReferencedURL>
      <id>16800</id>
      <url>http://boorah/dev/vanilla/item/image/3a5d1faf-f308-2112-1fc4-75002b0e1b3d/1/realset.gif</url>
      <urlHash>ebac2d41d00f357d36b8385ac123f89c</urlHash>
      <success>false</success>
      <status>404</status>
      <message><!DOCTYPE html>
<html lang="en-AU"  >
	<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge" >
	<base href="http://boorah/">

	<link rel="apple-touch-icon" href="p/r/1.0.643</message>
      <tries>2</tries>
      <lastChecked class="sql-timestamp">2014-03-27 23:14:57.811</lastChecked>
      <lastIndexed class="sql-timestamp">1970-01-01 11:00:00.0</lastIndexed>
    </com.tle.beans.ReferencedURL>
  </referencedUrls>
  <moderation>
    <id>35645</id>
    <start class="sql-timestamp">2011-08-30 12:05:10.82</start>
    <resumeModerating>false</resumeModerating>
    <unarchiveModerating>false</unarchiveModerating>
    <deletedModerating>false</deletedModerating>
    <needsReset>false</needsReset>
    <statuses/>
  </moderation>
  <history/>
  <comments/>
  <sharePasses/>
  <acceptances/>
  <treeNodes/>
  <notifications/>
  <name>
    <id>35646</id>
    <strings>
      <entry>
        <string>en</string>
        <com.tle.beans.entity.LanguageString>
          <id>35647</id>
          <locale>en</locale>
          <priority>1</priority>
          <text>Real Set</text>
          <bundle reference="../../../.."/>
        </com.tle.beans.entity.LanguageString>
      </entry>
    </strings>
  </name>
  <description>
    <id>35642</id>
    <strings>
      <entry>
        <string>en</string>
        <com.tle.beans.entity.LanguageString>
          <id>35643</id>
          <locale>en</locale>
          <priority>1</priority>
          <text>The symbol for the set of all real numbers.</text>
          <bundle reference="../../../.."/>
        </com.tle.beans.entity.LanguageString>
      </entry>
    </strings>
  </description>
  <totalFileSize>0</totalFileSize>
  <navigationSettings>
    <showNextPrev>false</showNextPrev>
    <showSplitOption>false</showSplitOption>
    <manualNavigation>false</manualNavigation>
  </navigationSettings>
</com.tle.beans.item.Item>


text:
<?php
use CpPress\CpPress;

/**
 * Plugin Name: CpPress Commonhelp App
 * Plugin URI: https://github.com/marcoski/cp-press
 * Description: Commonhelp Plugin App
 * Version: 1.1.6
 * Author: Marco Trognoni
 * Author URI: http://www.commonhelp.it
 * License: MIT
 */

$filename = __DIR__.'/vendor/autoload.php';
if (!file_exists($filename)) {
	echo 'You must first install the vendors using composer.'.PHP_EOL;
	exit(1);
}

require_once $filename;

require_once 'convenience.php';
require_once 'functions.php';
register_activation_hook(__FILE__, function(){
	CpPress::install();
});
CpPress::start();

?>


text:
package org.apache.hadoop.hive.ql;

import java.io.File;

/**
 * Base class for testing queries.
 */
public abstract class BaseTestQueries {

  protected final String inpDir = System
      .getProperty("hive.root") + "/ql/src/test/queries/clientpositive";
  protected final String resDir = System
      .getProperty("hive.root") + "/ql/src/test/results/clientpositive";
  protected final String logDir = System
      .getProperty("build.dir") + "/junit-qfile-results/clientpositive";

  /**
   * Create a file for each test name in the inpDir.
   * @param testNames
   * @return files corresponding to each test name
   */
  protected File[] setupQFiles(String[] testNames) {
    File[] qfiles = new File[testNames.length];
    for (int i = 0; i < testNames.length; i++) {
      qfiles[i] = new File(inpDir, testNames[i]);
    }
    return qfiles;
  }
}


text:
.. _arch_overview_http_dynamic_forward_proxy:

HTTP dynamic forward proxy
==========================

.. attention::

  HTTP dynamic forward proxy support should be considered alpha and not production ready.

Through the combination of both an :ref:`HTTP filter <config_http_filters_dynamic_forward_proxy>` and
:ref:`custom cluster <envoy_api_msg_config.cluster.dynamic_forward_proxy.v2alpha.ClusterConfig>`,
Envoy supports HTTP dynamic forward proxy. This means that Envoy can perform the role of an HTTP
proxy without prior knowledge of all configured DNS addresses, while still retaining the vast
majority of Envoy's benefits including asynchronous DNS resolution. The implementation works as
follows:

* The dynamic forward proxy HTTP filter is used to pause requests if the target DNS host is not
  already in cache.
* Envoy will begin asynchronously resolving the DNS address, unblocking any requests waiting on
  the response when the resolution completes.
* Any future requests will not be blocked as the DNS address is already in cache. The resolution
  process works similarly to the :ref:`logical DNS
  <arch_overview_service_discovery_types_logical_dns>` service discovery type with a single target
  address being remembered at any given time.
* All known hosts are stored in the dynamic forward proxy cluster such that they can be displayed
  in :ref:`admin output <operations_admin_interface>`.
* A special load balancer will select the right host to use based on the HTTP host/authority header
  during forwarding.
* Hosts that have not been used for a period of time are subject to a TTL that will purge them.
* When the upstream cluster has been configured with a TLS context, Envoy will automatically perform
  SAN verification for the resolved host name as well as specify the host name via SNI.

The above implementation details mean that at steady state Envoy can forward a large volume of
HTTP proxy traffic while all DNS resolution happens asynchronously in the background. Additionally,
all other Envoy filters and extensions can be used in conjunction with dynamic forward proxy support
including authentication, RBAC, rate limiting, etc.

For further configuration information see the :ref:`HTTP filter configuration documentation
<config_http_filters_dynamic_forward_proxy>`.

Memory usage details
--------------------

Memory usage detail's for Envoy's dynamic forward proxy support are as follows:

* Each resolved host/port pair uses a fixed amount of memory global to the server and shared
  amongst all workers.
* Address changes are performed inline using read/write locks and require no host reallocations.
* Hosts removed via TTL are purged once all active connections stop referring to them and all used
  memory is regained.
* The :ref:`max_hosts
  <envoy_api_field_config.common.dynamic_forward_proxy.v2alpha.DnsCacheConfig.max_hosts>` field can
  be used to limit the number of hosts that the DNS cache will store at any given time.
* The cluster's :ref:`max_pending_requests
  <envoy_api_field_cluster.CircuitBreakers.Thresholds.max_pending_requests>` circuit breaker can
  be used to limit the number of requests that are pending waiting for the DNS cache to load
  a host.
* Long lived upstream connections can have the underlying logical host expire via TTL while the
  connection is still open. Upstream requests and connections are still bound by other cluster
  circuit breakers such as :ref:`max_requests
  <envoy_api_field_cluster.CircuitBreakers.Thresholds.max_requests>`. The current assumption is that
  host data shared between connections uses a marginal amount of memory compared to the connections
  and requests themselves, making it not worth controlling independently.


text:
 <link type="text/css" rel="stylesheet" href="styles/semantic-tags.css" />

This is the Header

					Nav 1

					Nav 2

					Nav 3

					Nav 4

					Item 1

					Item 2

					Item 3

					Item 4

					Item 5

					Item 6

					Item 7

Lorem Ipsum

			Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sed sodales dui. Integer posuere odio vel augue porta quis viverra odio tempor. Vestibulum vitae mi metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae velit neque. Pellentesque eleifend sem vel nisi rhoncus sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent vel iaculis orci.

Donec non quam euismod mauris congue interdum

Cras elementum mi eget sapien accumsan gravida. Duis non leo massa. Proin mattis gravida quam, at ultrices dui bibendum ac. Aliquam varius mi sed ligula aliquam sed mattis arcu lacinia. Phasellus aliquam adipiscing sem sit amet viverra. Proin eu metus nunc, a laoreet est. Donec id urna dui. Fusce ut lectus sit amet lorem vulputate cursus et pretium justo. Vestibulum consequat scelerisque rhoncus. Curabitur varius pretium mollis. Sed gravida mattis odio ut posuere.

			Nunc a justo consequat ipsum luctus malesuada et vel sem. Proin tempor aliquet nunc, vulputate rutrum turpis pulvinar quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris tellus nisl, gravida sed pulvinar quis, convallis sit amet tellus. Sed tempus tempus felis, ac laoreet dolor iaculis ac. Nulla quis dolor ante, et dapibus nulla. Etiam sollicitudin est quis dolor auctor sit amet consequat metus vehicula. Sed magna ipsum, sollicitudin eu sollicitudin in, bibendum ac leo. Fusce eget dui in eros tempor hendrerit. Sed ut neque turpis. Praesent sapien magna, lobortis sed ullamcorper sed, iaculis imperdiet nisl. Ut quis ante tortor.

			Curabitur mattis viverra venenatis. Nunc eu lorem ligula. Praesent vehicula fermentum nulla, et malesuada erat lacinia hendrerit. Nulla tristique ultrices gravida. Vestibulum tempus, ipsum quis accumsan fermentum, ipsum ligula posuere lectus, sit amet vulputate leo lectus id dui. Nam placerat leo vitae lorem suscipit a dictum neque luctus. Etiam justo elit, eleifend sed viverra at, imperdiet ut lectus. Vivamus cursus blandit arcu, sit amet pretium neque consequat sed. Donec consequat lorem in orci hendrerit vel pharetra augue tincidunt. Fusce at est risus, sed lacinia elit. Pellentesque eros tellus, condimentum nec interdum sit amet, cursus eget urna.

			Sed scelerisque mattis imperdiet. Ut varius magna nec lacus mattis dictum. Etiam ultricies, ligula eget laoreet cursus, erat ante congue tellus, sit amet dapibus tortor mi ac ante. Integer ultricies, diam quis molestie lobortis, leo ligula pellentesque diam, non tempus magna augue egestas lectus. Fusce orci tortor, auctor sed viverra ullamcorper, aliquet sed justo. Aenean gravida tristique bibendum. Donec non odio orci, at consectetur dui. Proin nec tellus tellus. Aliquam enim elit, feugiat eu aliquam sit amet, convallis in nulla. Fusce nisi ligula, placerat vel ultricies in, pulvinar et enim. Ut mollis eros id elit convallis ac volutpat urna auctor. Donec quis urna tellus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean quis lacus ut lectus rhoncus vestibulum eget id enim. Integer et pellentesque sem. Donec tristique lacus eu risus suscipit vitae consectetur elit elementum.

This is the Footer


text:
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
//    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.
//
#endregion -- License Terms --

using System;

namespace MsgPack.Rpc.Client.Protocols
{
	/// <summary>
	///		Null object for the <see cref="ClientTransport"/>.
	/// </summary>
	internal sealed class NullClientTransport : ClientTransport
	{
		protected override bool CanResumeReceiving
		{
			get { return true; }
		}

		/// <summary>
		///		Initializes a new instance of the <see cref="NullClientTransport"/> class.
		/// </summary>
		/// <param name="manager">The manager which will manage this instance.</param>
		/// <exception cref="ArgumentNullException">
		///		<paramref name="manager"/> is <c>null</c>.
		/// </exception>
		public NullClientTransport( ClientTransportManager<NullClientTransport> manager ) : base( manager ) { }

		/// <summary>
		///		Performs protocol specific asynchronous 'Send' operation.
		/// </summary>
		/// <param name="context">Context information.</param>
		protected override void SendCore( ClientRequestContext context )
		{
			this.OnSent( context );
		}

		/// <summary>
		///		Performs protocol specific asynchronous 'Receive' operation.
		/// </summary>
		/// <param name="context">Context information.</param>
		protected override void ReceiveCore( ClientResponseContext context )
		{
			this.OnReceived( context );
		}
	}
}


text:
using System;

namespace Foreach
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Method1();
            Method2();
        }

        public static void Method1()
        {
            foreach (var i in new MyClass().GetSequence())
            {
                Console.WriteLine("Method1: {0}", i);
            }
        }

        public static void Method2()
        {
            var anotherClass = new AnotherClass();
            foreach (var i in anotherClass)
            {
                Console.WriteLine("Method2: {0}", i);
            }
        }
    }
}


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

<TITLE>
XSSFShape (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.poi.xssf.usermodel

Class XSSFShape

java.lang.Object
  org.apache.poi.xssf.usermodel.XSSFShape

All Implemented Interfaces:
Shape

Direct Known Subclasses:
XSSFConnector, XSSFGraphicFrame, XSSFPicture, XSSFShapeGroup, XSSFSimpleShape

public abstract class XSSFShape
extends java.lang.Object
implements Shape

Represents a shape in a SpreadsheetML drawing.

Field Summary

protected  XSSFAnchor
anchor

          anchor that is used by this shape

protected  XSSFDrawing
drawing

          Parent drawing

static int
EMU_PER_PIXEL

          Deprecated. POI 3.17 beta 1

static int
EMU_PER_POINT

          Deprecated. POI 3.17 beta 1

protected  XSSFShapeGroup
parent

          The parent shape, always not-null for shapes in groups

static int
PIXEL_DPI

          Deprecated. POI 3.17 beta 1

static int
POINT_DPI

          Deprecated. POI 3.17 beta 1

Constructor Summary

XSSFShape()

Method Summary

 XSSFAnchor
getAnchor()

 XSSFDrawing
getDrawing()

          Return the drawing that owns this shape

 XSSFShapeGroup
getParent()

protected abstract  org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties
getShapeProperties()

          Returns xml bean with shape properties.

 boolean
isNoFill()

          Whether this shape is not filled with a color

 void
setFillColor(int red,
             int green,
             int blue)

          Sets the color used to fill this shape using the solid fill pattern.

 void
setLineStyle(int lineStyle)

          Sets the line style.

 void
setLineStyleColor(int red,
                  int green,
                  int blue)

          The color applied to the lines of this shape.

 void
setLineWidth(double lineWidth)

          Specifies the width to be used for the underline stroke.

 void
setNoFill(boolean noFill)

          Sets whether this shape is filled or transparent.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface org.apache.poi.ss.usermodel.Shape

getShapeName

Field Detail

EMU_PER_PIXEL

@Removal(version="3.19")
public static final int EMU_PER_PIXEL

Deprecated. POI 3.17 beta 1

See Also:
Units.EMU_PER_PIXEL,
Constant Field Values

EMU_PER_POINT

@Removal(version="3.19")
public static final int EMU_PER_POINT

Deprecated. POI 3.17 beta 1

See Also:
Units.EMU_PER_POINT,
Constant Field Values

POINT_DPI

@Removal(version="3.19")
public static final int POINT_DPI

Deprecated. POI 3.17 beta 1

See Also:
Units.POINT_DPI,
Constant Field Values

PIXEL_DPI

@Removal(version="3.19")
public static final int PIXEL_DPI

Deprecated. POI 3.17 beta 1

See Also:
Units.PIXEL_DPI,
Constant Field Values

drawing

protected XSSFDrawing drawing

Parent drawing

parent

protected XSSFShapeGroup parent

The parent shape, always not-null for shapes in groups

anchor

protected XSSFAnchor anchor

anchor that is used by this shape

Constructor Detail

XSSFShape

public XSSFShape()

Method Detail

getDrawing

public XSSFDrawing getDrawing()

Return the drawing that owns this shape

Returns:
the parent drawing that owns this shape

getParent

public XSSFShapeGroup getParent()

Specified by:
getParent in interface Shape

Returns:
the parent shape.

getAnchor

public XSSFAnchor getAnchor()

Specified by:
getAnchor in interface Shape

Returns:
the anchor that is used by this shape.

getShapeProperties

protected abstract org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties getShapeProperties()

Returns xml bean with shape properties.

Returns:
xml bean with shape properties.

isNoFill

public boolean isNoFill()

Description copied from interface: Shape

Whether this shape is not filled with a color

Specified by:
isNoFill in interface Shape

Returns:
true if this shape is not filled with a color.

setNoFill

public void setNoFill(boolean noFill)

Description copied from interface: Shape

Sets whether this shape is filled or transparent.

Specified by:
setNoFill in interface Shape

Parameters:
noFill - if true then no fill will be applied to the shape element.

setFillColor

public void setFillColor(int red,
                         int green,
                         int blue)

Description copied from interface: Shape

Sets the color used to fill this shape using the solid fill pattern.

Specified by:
setFillColor in interface Shape

setLineStyleColor

public void setLineStyleColor(int red,
                              int green,
                              int blue)

Description copied from interface: Shape

The color applied to the lines of this shape.

Specified by:
setLineStyleColor in interface Shape

setLineWidth

public void setLineWidth(double lineWidth)

Specifies the width to be used for the underline stroke.

Parameters:
lineWidth - width in points

setLineStyle

public void setLineStyle(int lineStyle)

Sets the line style.

Parameters:
lineStyle -

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                Copyright 2017 The Apache Software Foundation or
        its licensors, as applicable.


text:
package org.jboss.resteasy.test.providers.jaxb.resource;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "test-data")
public class CharacterSetData {
    private String text = "Text \u0100.";

    public String getText() {
        return text;
    }

    public void setText(String value) {
        text = value;
    }
}


text:
'''
This file describes the process for computing weighted climate data
'''

import xarray as xr
import numpy as np
import pandas as pd
from scipy import interpolate
from scipy.ndimage import label
from scipy.interpolate import griddata
from six import string_types
import itertools
import toolz
import os
import datafs
import click
import dill
import json
import pipelines

WEIGHTS_FILE = (
    'GCP/spatial/world-combo-new/segment_weights/' +
    'agglomerated-world-new_BCSD_grid_segment_weights_area_pop.csv')

'''
=================
Private Functions
=================
'''

def _fill_holes_xr(
        ds,
        varname,
        broadcast_dims=('time',),
        lon_name='lon',
        lat_name='lat',
        gridsize=0.25,
        minlat=-85,
        maxlat=85):
    '''
    Fill NA values inplace in a gridded dataset

    Parameters
    ----------

    ds : xarray.Dataset
        name of the dataset with variable to be modified

    varname : str
        name of the variable to be interpolated

    broadcast_dims : tuple of strings, optional
        tuple of dimension names to broadcast the interpolation step over
        (default 'time')

    lon_name : str, optional
        name of the longitude dimension (default 'lon')

    lat_name : str, optional
        name of the latitude dimension (default 'lat')

    gridsize : float, optional
        size of the lat/lon grid. Important for creating a bounding box around
        NaN regions (default 0.25)

    minlat : float, optional
        latitude below which no values will be interpolated (default -85)

    minlon : float, optional
        latitude above which no values will be interpolated (default 85)

    '''
    if isinstance(broadcast_dims, string_types):
        broadcast_dims = (broadcast_dims, )

    ravel_lons, ravel_lats = (
        np.meshgrid(ds.coords[lon_name].values, ds.coords[lat_name].values))

    # remove infinite values
    ds[varname] = ds[varname].where((ds[varname] < 1e30))

    for indexers in itertools.product(*tuple(
            [range(len(ds.coords[c])) for c in broadcast_dims])):

        slicer_dict = dict(zip(broadcast_dims, indexers))

        slicer = tuple([
                slicer_dict[c]
                if c in broadcast_dims
                else slice(None, None, None)
                for c in ds[varname].dims])

        sliced = ds[varname].values.__getitem__(slicer)

        if not np.isnan(sliced).any():
            continue

        filled = _fill_holes(
            var=np.ma.masked_invalid(sliced),
            lat=ravel_lats,
            lon=ravel_lons,
            gridsize=0.25,
            minlat=-85,
            maxlat=85)

        ds[varname][slicer_dict] = filled

def _fill_holes(var, lat, lon, gridsize=0.25, minlat=-85, maxlat=85):
    '''
    Interpolates the missing values between points on grid

    Parameters
    ----------
    var: masked np.array
        array of climate values

    lat: masked np.array
        array of latitude values

    lon: masked np. array
        array of longitude values

    gridsize: int
        corresponds to degrees on the grid for climate data

    minlat: int
        corresponds to min latitude values to include. Used to remove poles

    maxlat: int
        corresponds to max lat values to include. Used to remove poles

    '''
    # fill the missing value regions by linear interpolation
    # pass if no missing values
    if not np.ma.is_masked(var):
        return var
    # or the missing values are only in polar regions
    if not var.mask[20: -20, :].any():
        return var

    # fill the holes
    var_filled = var[:]
    missing = np.where((var.mask) & (lat > minlat) & (lat < maxlat))
    mp = np.zeros(var.shape)
    mp[missing] = 1
    ptch, n_ptch = label(mp)

    for p in range(1, n_ptch+1):

        ind_ptch = np.where(ptch == p)
        lat_ptch = lat[ind_ptch]
        lon_ptch = lon[ind_ptch]

        ind_box = np.where(
                (lat <= np.max(lat_ptch)+gridsize) &
                (lat >= np.min(lat_ptch)-gridsize) &
                (lon <= np.max(lon_ptch)+gridsize) &
                (lon >= np.min(lon_ptch)-gridsize))

        var_box = var[ind_box]
        lat_box = lat[ind_box]
        lon_box = lon[ind_box]
        not_missing = np.where(var_box.mask == False)
        points = np.column_stack([lon_box[not_missing], lat_box[not_missing]])
        values = var_box[var_box.mask == False]
        var_filled[ind_box] = griddata(
                points,
                values,
                (lon_box, lat_box),
                method='linear')

    return var_filled

def _standardize_longitude_dimension(ds, lon_names=['lon', 'longitude']):
    '''
    Rescales the lat and lon coordinates to ensure lat is within (-90,90)
    and lon is within (-180, 180). Renames coordinates
    from lon to longitude and from lat to latitude. Sorts any new
    rescaled coordinated.

    Parameters
    ----------
    ds: xarray.DataSet

    Returns
    -------
    ds: xarray.DataSet

    .. note:: this will be unnecessary if we standardize inputs. We can
    scale the longitude dim to between (-180, 180)

    '''

    coords = np.array(ds.coords.keys())

    assert len(coords[np.in1d(coords, lon_names)]) == 1
    _lon_coord = coords[np.in1d(coords, ['longitude', 'lon'])][0]

    ds = ds.rename({_lon_coord: '_longitude'})

    # Adjust lat and lon to make sure they are within (-90, 90) and (-180, 180)
    ds['_longitude_adjusted'] = (
        (ds._longitude - 360)
            .where(ds._longitude > 180)
            .fillna(ds._longitude))

    # reassign the new coords to as the main lon coords
    ds = (ds
        .swap_dims({'_longitude': '_longitude_adjusted'})
        .reindex({'_longitude_adjusted': sorted(ds._longitude_adjusted)}))

    if '_longitude' in ds.coords:
        ds = ds.drop('_longitude')

    ds = ds.rename({'_longitude_adjusted': _lon_coord})

    return ds

@toolz.memoize
def _prepare_spatial_weights_data(weights_file=WEIGHTS_FILE):
    '''
    Rescales the pix_cent_x colum values

    Parameters
    ----------
    weights_file: str
        location of file used for weighting

    .. note:: unnecessary if we can standardize our input
    '''

    api = datafs.get_api()
    archive = api.get_archive(weights_file)

    with archive.open('r') as f:
        df = pd.read_csv(f)

    # Re-label out-of-bounds pixel centers
    df.set_value((df['pix_cent_x'] == 180.125), 'pix_cent_x', -179.875)

    #probably totally unnecessary
    df.drop_duplicates()
    df.index.names = ['reshape_index']

    df.rename(
        columns={'pix_cent_x': 'lon', 'pix_cent_y': 'lat'},
        inplace=True)

    return df

def _reindex_spatial_data_to_regions(ds, df):
    '''
    Reindexes spatial and segment weight data to regions

    Enables region index-based math operations

    Parameters
    ----------
    ds: xarray Dataset
    df: pandas DataFrame

    Returns
    -------
    Xarray DataArray

    '''
    res = ds.sel_points(
        'reshape_index',
        lat=df.lat.values,
        lon=df.lon.values)

    return res

def _aggregate_reindexed_data_to_regions(
        ds,
        variable,
        aggwt,
        agglev,
        weights,
        backup_aggwt='areawt'):
    '''
    Performs weighted avg for climate variable by region

    Parameters
    ----------

    ds: xarray.DataArray

    variable: str
        name of the data variable

    aggwt: str
        variable to weight by (i.e popwt, areawt, cropwt)

    agglev: str
        indicates which regional id scheme to select in the dataframe

    weight: pd.DataFrame
        pandas DataFrame of weights

    backup_aggwt: str, optional
        aggregation weight to use in regions with no aggwt data (default
        'areawt')

    '''

    ds.coords[agglev] = xr.DataArray(
                weights[agglev].values,
                dims={'reshape_index': weights.index.values})

    # format weights
    ds[aggwt] = xr.DataArray(
                weights[aggwt].values,
                dims={'reshape_index': weights.index.values})

    ds[aggwt].where(ds[aggwt] > 0).fillna(weights[backup_aggwt].values)

    weighted = xr.Dataset({
        variable: (
            (ds[variable]*ds[aggwt])
                .groupby(agglev)
                .sum(dim='reshape_index') /
            ds[aggwt]
                .groupby(agglev)
                .sum(dim='reshape_index'))})

    return weighted

'''
================
Public Functions
================
'''

def load_climate_data(fp, varname, lon_name='lon', broadcast_dims=('time',)):
    '''
    Read and prepare climate data

    After reading data, this method also fills NA values using linear
    interpolation, and standardizes longitude to -180:180

    Parameters
    ----------
    fp: str
        File path to dataset

    varname: str
        Variable name to be read

    lon_name : str, optional
        Name of the longitude dimension (defualt selects from ['lon' or
        'longitude'])

    Returns
    -------
    xr.Dataset
         xarray dataset loaded into memory
    '''

    if lon_name is not None:
        lon_names = [lon_name]

    with xr.open_dataset(fp) as ds:

        _fill_holes_xr(ds.load(), varname, broadcast_dims=broadcast_dims)
        return _standardize_longitude_dimension(ds, lon_names=lon_names)

def weighted_aggregate_grid_to_regions(
        ds,
        variable,
        aggwt,
        agglev,
        weights=None):
    '''
    Computes the weighted reshape of gridded data

    Parameters
    ----------
    ds : xr.Dataset
        xarray Dataset to be aggregated. Must have 'lat' and 'lon' in the
        coordinates.

    variable : str
        name of the variable to be aggregated

    aggwt : str
        Weighting variable (e.g. 'popwt', 'areawt'). This must be a column name
        in the weights file.

    agglev : str
        Target regional aggregation level (e.g. 'ISO', 'hierid'). This must be
        a column name in the weights file.

    weights : str, optional
        Regional aggregation weights (default agglomerated-world-new BCSD
        segment weights)

    Returns
    -------
    ds: xr.Dataset
        weighted and averaged dataset based on agglev
    '''

    if weights is None:
        weights = _prepare_spatial_weights_data()

    ds = _reindex_spatial_data_to_regions(ds, weights)
    ds = _aggregate_reindexed_data_to_regions(
        ds,
        variable,
        aggwt,
        agglev,
        weights)

    return ds

class bcsd_transform(object):

    @staticmethod
    @toolz.memoize
    def create_dummy_data(tmp, variable, **kwargs):

        tmp_path_in = os.path.join(tmp, 'sample_in.nc')

        time = pd.date_range('1/1/1981', periods=4, freq='3M')
        lats = np.arange(-89.875, 90, 0.25)
        lons = np.arange(-179.875, 180, 0.25)

        ds = xr.Dataset({
            variable: xr.DataArray(
                np.random.random((len(time), len(lats), len(lons))),
                dims=('time', 'lat', 'lon'),
                coords={
                    'time': time,
                    'lat': lats,
                    'lon': lons})
            })

        ds.to_netcdf(tmp_path_in)

        return {'read_file': tmp_path_in}

    @staticmethod
    @toolz.memoize
    def create_dummy_data_small(tmp, variable, **kwargs):

        tmp_path_in = os.path.join(tmp, 'sample_in_small.nc')

        time = pd.date_range('1/1/1981', periods=4, freq='3M')
        lats = np.arange(-0.875, 5, 1)
        lons = np.arange(20.875, 25, 1)

        ds = xr.Dataset({
            variable: xr.DataArray(
                np.random.random((len(time), len(lats), len(lons))),
                dims=('time', 'lat', 'lon'),
                coords={
                    'time': time,
                    'lat': lats,
                    'lon': lons})
            })

        ds.to_netcdf(tmp_path_in)

        return {'read_file': tmp_path_in}

    @staticmethod
    def run(
            read_file,
            write_file,
            variable,
            transformation,
            metadata,
            rcp,
            pername,
            years,
            model,
            agglev,
            aggwt,
            weights=None):

        # Load pickled transformation
        transformation = pipelines.load_func(transformation)

        # Add to job metadata
        metadata.update(dict(
            time_horizon='{}-{}'.format(years[0], years[-1])))

        # Get transformed data
        ds = xr.Dataset({variable: xr.concat([
            (load_climate_data(
                    read_file.format(year=y),
                    variable,
                    broadcast_dims=('time',))
                .pipe(transformation))
            for y in years],
            dim=pd.Index(years, name='year')).mean(dim='year')})

        # Reshape to regions
        if not agglev.startswith('grid'):
            ds = weighted_aggregate_grid_to_regions(
                    ds, variable, aggwt, agglev, weights=weights)

        # Update netCDF metadata
        ds.attrs.update(**metadata)

        # Write output
        if not os.path.isdir(os.path.dirname(write_file)):
            os.makedirs(os.path.dirname(write_file))

        ds.to_netcdf(write_file)

    @classmethod
    def run_test_small(cls, *args, **kwargs):
        weights = pd.read_pickle('pipelines/climate/test/data/weightsfile.pkl')
        with xr.open_dataset(kwargs['read_file']) as ds:
            weights = weights.loc[
                np.in1d(weights['lat'], ds.lat) &
                np.in1d(weights['lon'], ds.lon)]

        cls.run(*args, weights=weights, **kwargs)

    @classmethod
    def run_test(cls, *args, **kwargs):
        weights = pd.read_pickle('pipelines/climate/test/data/weightsfile.pkl')
        cls.run(*args, weights=weights, **kwargs)

class pattern_transform(object):

    @staticmethod
    @toolz.memoize
    def create_dummy_data(tmp, variable, **kwargs):

        days = np.arange(1, 30)
        lats = np.arange(-89.875, 90, 0.25)
        lons = np.arange(-179.875, 180, 0.25)

        tmp_path_in = os.path.join(tmp, 'sample_in.nc')

        ds = xr.Dataset({
            variable: xr.DataArray(
                np.random.random((len(days), len(lats), len(lons))),
                dims=('day', 'lat', 'lon'),
                coords={
                    'day': days,
                    'lat': lats,
                    'lon': lons})
            })

        ds.to_netcdf(tmp_path_in)

        tmp_baseline = os.path.join(tmp, 'sample_baseline.nc')

        ds = xr.Dataset({
            variable: xr.DataArray(
                np.random.random((len(lats), len(lons))),
                dims=('lat', 'lon'),
                coords={
                    'lat': lats,
                    'lon': lons})
            })

        ds.to_netcdf(tmp_baseline)

        return {'pattern_file': tmp_path_in, 'baseline_file': tmp_baseline}

    @staticmethod
    @toolz.memoize
    def create_dummy_data_small(tmp, variable, **kwargs):

        days = np.arange(1, 3)
        lats = np.arange(-0.875, 5, 1)
        lons = np.arange(20.875, 25, 1)

        tmp_path_in = os.path.join(tmp, 'sample_in_small.nc')

        ds = xr.Dataset({
            variable: xr.DataArray(
                np.random.random((len(days), len(lats), len(lons))),
                dims=('day', 'lat', 'lon'),
                coords={
                    'day': days,
                    'lat': lats,
                    'lon': lons})
            })

        ds.to_netcdf(tmp_path_in)

        tmp_baseline = os.path.join(tmp, 'sample_baseline_small.nc')

        ds = xr.Dataset({
            variable: xr.DataArray(
                np.random.random((len(lats), len(lons))),
                dims=('lat', 'lon'),
                coords={
                    'lat': lats,
                    'lon': lons})
            })

        ds.to_netcdf(tmp_baseline)

        return {'pattern_file': tmp_path_in, 'baseline_file': tmp_baseline}

    @staticmethod
    def run(
            pattern_file,
            baseline_file,
            write_file,
            metadata,
            variable,
            transformation,
            rcp,
            pername,
            years,
            model,
            baseline_model,
            season,
            agglev,
            aggwt,
            weights=None):

        # Load pickled transformation
        transformation = pipelines.load_func(transformation)

        # Add to job metadata
        metadata.update(dict(
            time_horizon='{}-{}'.format(years[0], years[-1])))

        # Get transformed data
        ds = xr.Dataset({variable: xr.concat([
            (load_climate_data(
                    pattern_file.format(year=y),
                    variable,
                    broadcast_dims=('day',))
                .pipe(transformation))
            for y in years],
            dim=pd.Index(years, name='year')).mean(dim='year')})

        # load baseline
        with xr.open_dataset(baseline_file) as base:
            ds = (ds + base).load()

        # Reshape to regions
        if not agglev.startswith('grid'):
            ds = weighted_aggregate_grid_to_regions(
                    ds, variable, aggwt, agglev, weights=weights)

        # Update netCDF metadata
        ds.attrs.update(**metadata)

        # Write output
        if not os.path.isdir(os.path.dirname(write_file)):
            os.makedirs(os.path.dirname(write_file))

        ds.to_netcdf(write_file)

    @classmethod
    def run_test_small(cls, *args, **kwargs):
        weights = pd.read_pickle('pipelines/climate/test/data/weightsfile.pkl')
        with xr.open_dataset(kwargs['pattern_file']) as ds:
            weights = weights.loc[
                (np.in1d(weights['lat'].values, ds.lat) &
                                np.in1d(weights['lon'].values, ds.lon))].copy()

        cls.run(*args, weights=weights, **kwargs)

    @classmethod
    def run_test(cls, *args, **kwargs):
        weights = pd.read_pickle('pipelines/climate/test/data/weightsfile.pkl')
        cls.run(*args, weights=weights, **kwargs)

@click.command()
@click.argument('command')
@click.argument('kwargs')
def main(command, kwargs):

    kwargs = json.loads(kwargs)

    if command in globals():
        globals()[command].run(**kwargs)
    else:
        raise ValueError('command not recognized: "{}"'.format(command))

if __name__ == '__main__':
    main()


text:
namespace neam::cr
{
  /// \brief Construct a container from a list of move-only objects
  /// usage: \code construct<std::vector<int>>(a, b, c); \endcode
  template<typename Cont, typename... Types>
  auto construct(Types &&... v)
  {
    Cont r;
    (r.push_back(std::forward<Types>(v)), ...);
    return r;
  }

  /// \brief Construct a container from a list of move-only objects
  /// usage: \code construct<std::vector>(a, b, c); \endcode
  template<template<typename...> typename Cont, typename Type, typename... Types>
  auto construct(Type&& v0, Types &&... v)
  {
    Cont<std::remove_const_t<std::remove_reference_t<Type>>> r;
    r.push_back(std::forward<Type>(v0));
    (r.push_back(std::forward<Types>(v)), ...);
    return r;
  }

  template<typename Fnc, typename... Args>
  void for_each(std::tuple<Args...>& t, Fnc&& fnc)
  {
    std::apply([&](auto&&... args)
    {
      (fnc(std::forward<Args>(args)), ...);
    }, t);
  }
  template<typename Fnc, typename... Args>
  void for_each(const std::tuple<Args...>& t, Fnc&& fnc)
  {
    std::apply([&](auto&&... args)
    {
      (fnc(args), ...);
    }, t);
  }

  static std::vector<std::string> split_string(const std::string& input, const std::string& regex)
  {
    // passing -1 as the submatch index parameter performs splitting
    std::regex re(regex);
    std::sregex_token_iterator
        first{input.begin(), input.end(), re, -1},
        last;
    return {first, last};
  }
}


text:
package com.ofg.infrastructure.correlationid;

import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Trace;
import org.springframework.cloud.sleuth.TraceContextHolder;

/**
 * Component that stores correlation id using {@link ThreadLocal}
 */
public class CorrelationIdHolder {
    public static final String CORRELATION_ID_HEADER = Trace.TRACE_ID_NAME;
    public static final String OLD_CORRELATION_ID_HEADER = "correlationId";

    public static void set(Span span) {
        TraceContextHolder.setCurrentSpan(span);
    }

    public static Span get() {
        return TraceContextHolder.getCurrentSpan();
    }

    public static void remove() {
        TraceContextHolder.removeCurrentSpan();
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.NetApp;

namespace Azure.ResourceManager.NetApp.Models
{
    internal partial class NetAppAccountList
    {
        internal static NetAppAccountList DeserializeNetAppAccountList(JsonElement element)
        {
            Optional<IReadOnlyList<NetAppAccountData>> value = default;
            Optional<string> nextLink = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("value"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<NetAppAccountData> array = new List<NetAppAccountData>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(NetAppAccountData.DeserializeNetAppAccountData(item));
                    }
                    value = array;
                    continue;
                }
                if (property.NameEquals("nextLink"))
                {
                    nextLink = property.Value.GetString();
                    continue;
                }
            }
            return new NetAppAccountList(Optional.ToList(value), nextLink.Value);
        }
    }
}