text:
#define _GNU_SOURCE

#include "cmd.h"

#include <getopt.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>

#include "common.h"
#include "compat.h"
#include "libyang.h"

COMMAND commands[];
extern int done;

#ifndef NDEBUG

void
cmd_debug_help(void)
{
    printf("Usage: debug (dict | xpath)+\n");
}

void
cmd_debug(struct ly_ctx **UNUSED(ctx), const char *cmdline)
{
    int argc = 0;
    char **argv = NULL;
    int opt, opt_index;
    struct option options[] = {
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0}
    };
    uint32_t dbg_groups = 0;

    if (parse_cmdline(cmdline, &argc, &argv)) {
        goto cleanup;
    }

    while ((opt = getopt_long(argc, argv, "h", options, &opt_index)) != -1) {
        switch (opt) {
        case 'h':
            cmd_debug_help();
            goto cleanup;
        default:
            YLMSG_E("Unknown option.\n");
            goto cleanup;
        }
    }
    if (argc == optind) {
        /* no argument */
        cmd_debug_help();
        goto cleanup;
    }

    for (int i = 0; i < argc - optind; i++) {
        if (!strcasecmp("dict", argv[optind + i])) {
            dbg_groups |= LY_LDGDICT;
        } else if (!strcasecmp("xpath", argv[optind + i])) {
            dbg_groups |= LY_LDGXPATH;
        } else {
            YLMSG_E("Unknown debug group \"%s\"\n", argv[optind + 1]);
            goto cleanup;
        }
    }

    ly_log_dbg_groups(dbg_groups);

cleanup:
    free_cmdline(argv);
}

#endif

void
cmd_verb_help(void)
{
    printf("Usage: verb (error | warning | verbose | debug)\n");
}

void
cmd_verb(struct ly_ctx **UNUSED(ctx), const char *cmdline)
{
    int argc = 0;
    char **argv = NULL;
    int opt, opt_index;
    struct option options[] = {
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0}
    };

    if (parse_cmdline(cmdline, &argc, &argv)) {
        goto cleanup;
    }

    while ((opt = getopt_long(argc, argv, "h", options, &opt_index)) != -1) {
        switch (opt) {
        case 'h':
            cmd_verb_help();
            goto cleanup;
        default:
            YLMSG_E("Unknown option.\n");
            goto cleanup;
        }
    }

    if (argc - optind > 1) {
        YLMSG_E("Only a single verbosity level can be set.\n");
        cmd_verb_help();
        goto cleanup;
    } else if (argc == optind) {
        /* no argument - print current value */
        LY_LOG_LEVEL level = ly_log_level(LY_LLERR);

        ly_log_level(level);
        printf("Current verbosity level: ");
        if (level == LY_LLERR) {
            printf("error\n");
        } else if (level == LY_LLWRN) {
            printf("warning\n");
        } else if (level == LY_LLVRB) {
            printf("verbose\n");
        } else if (level == LY_LLDBG) {
            printf("debug\n");
        }
        goto cleanup;
    }

    if (!strcasecmp("error", argv[optind]) || !strcmp("0", argv[optind])) {
        ly_log_level(LY_LLERR);
    } else if (!strcasecmp("warning", argv[optind]) || !strcmp("1", argv[optind])) {
        ly_log_level(LY_LLWRN);
    } else if (!strcasecmp("verbose", argv[optind]) || !strcmp("2", argv[optind])) {
        ly_log_level(LY_LLVRB);
    } else if (!strcasecmp("debug", argv[optind]) || !strcmp("3", argv[optind])) {
        ly_log_level(LY_LLDBG);
    } else {
        YLMSG_E("Unknown verbosity \"%s\"\n", argv[optind]);
        goto cleanup;
    }

cleanup:
    free_cmdline(argv);
}

void
cmd_quit(struct ly_ctx **UNUSED(ctx), const char *UNUSED(cmdline))
{
    done = 1;
    return;
}

void
cmd_help_help(void)
{
    printf("Usage: help [cmd ...]\n");
}

void
cmd_help(struct ly_ctx **UNUSED(ctx), const char *cmdline)
{
    int argc = 0;
    char **argv = NULL;
    int opt, opt_index;
    struct option options[] = {
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0}
    };

    if (parse_cmdline(cmdline, &argc, &argv)) {
        goto cleanup;
    }

    while ((opt = getopt_long(argc, argv, "h", options, &opt_index)) != -1) {
        switch (opt) {
        case 'h':
            cmd_help_help();
            goto cleanup;
        default:
            YLMSG_E("Unknown option.\n");
            goto cleanup;
        }
    }

    if (argc == optind) {
generic_help:
        printf("Available commands:\n");
        for (uint16_t i = 0; commands[i].name; i++) {
            if (commands[i].helpstring != NULL) {
                printf("  %-15s %s\n", commands[i].name, commands[i].helpstring);
            }
        }
    } else {
        /* print specific help for the selected command(s) */

        for (int c = 0; c < argc - optind; ++c) {
            int8_t match = 0;

            /* get the command of the specified name */
            for (uint16_t i = 0; commands[i].name; i++) {
                if (strcmp(argv[optind + c], commands[i].name) == 0) {
                    match = 1;
                    if (commands[i].help_func != NULL) {
                        commands[i].help_func();
                    } else {
                        printf("%s: %s\n", argv[optind + c], commands[i].helpstring);
                    }
                    break;
                }
            }
            if (!match) {
                /* if unknown command specified, print the list of commands */
                printf("Unknown command \'%s\'\n", argv[optind + c]);
                goto generic_help;
            }
        }
    }

cleanup:
    free_cmdline(argv);
}

COMMAND commands[] = {
    {"help", cmd_help, cmd_help_help, "Display commands description"},
    {"add", cmd_add, cmd_add_help, "Add a new module from a specific file"},
    {"load", cmd_load, cmd_load_help, "Load a new schema from the searchdirs"},
    {"print", cmd_print, cmd_print_help, "Print a module"},
    {"data", cmd_data, cmd_data_help, "Load, validate and optionally print instance data"},
    {"list", cmd_list, cmd_list_help, "List all the loaded modules"},
    {"feature", cmd_feature, cmd_feature_help, "Print all features of module(s) with their state"},
    {"searchpath", cmd_searchpath, cmd_searchpath_help, "Print/set the search path(s) for schemas"},
    {"clear", cmd_clear, cmd_clear_help, "Clear the context - remove all the loaded modules"},
    {"verb", cmd_verb, cmd_verb_help, "Change verbosity"},
#ifndef NDEBUG
    {"debug", cmd_debug, cmd_debug_help, "Display specific debug message groups"},
#endif
    {"quit", cmd_quit, NULL, "Quit the program"},
    /* synonyms for previous commands */
    {"?", cmd_help, NULL, "Display commands description"},
    {"exit", cmd_quit, NULL, "Quit the program"},
    {NULL, NULL, NULL, NULL}
};


text:
#define GLM_FORCE_RADIANS

#include <jni.h>

#include "rgb-depth-sync/rgb_depth_sync_application.h"

static rgb_depth_sync::SynchronizationApplication app;

#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL
Java_com_projecttango_examples_cpp_rgbdepthsync_TangoJNINative_onCreate(
    JNIEnv* env, jobject, jobject activity) {
  app.OnCreate(env, activity);
}

JNIEXPORT void JNICALL
Java_com_projecttango_examples_cpp_rgbdepthsync_TangoJNINative_onTangoServiceConnected(
    JNIEnv* env, jobject, jobject iBinder) {
  app.OnTangoServiceConnected(env, iBinder);
}

JNIEXPORT void JNICALL
Java_com_projecttango_examples_cpp_rgbdepthsync_TangoJNINative_onPause(
    JNIEnv*, jobject) {
  app.OnPause();
}

JNIEXPORT void JNICALL
Java_com_projecttango_examples_cpp_rgbdepthsync_TangoJNINative_onGlSurfaceCreated(
    JNIEnv*, jobject) {
  app.OnSurfaceCreated();
}

JNIEXPORT void JNICALL
Java_com_projecttango_examples_cpp_rgbdepthsync_TangoJNINative_onGlSurfaceChanged(
    JNIEnv*, jobject, jint width, jint height) {
  app.OnSurfaceChanged(width, height);
}

JNIEXPORT void JNICALL
Java_com_projecttango_examples_cpp_rgbdepthsync_TangoJNINative_onGlSurfaceDrawFrame(
    JNIEnv*, jobject) {
  app.OnDrawFrame();
}

JNIEXPORT void JNICALL
Java_com_projecttango_examples_cpp_rgbdepthsync_TangoJNINative_setDepthAlphaValue(
    JNIEnv*, jobject, jfloat alpha) {
  return app.SetDepthAlphaValue(alpha);
}

JNIEXPORT void JNICALL
Java_com_projecttango_examples_cpp_rgbdepthsync_TangoJNINative_setGPUUpsample(
    JNIEnv*, jobject, jboolean on) {
  return app.SetGPUUpsample(on);
}

JNIEXPORT void JNICALL
Java_com_projecttango_examples_cpp_rgbdepthsync_TangoJNINative_onDisplayChanged(
    JNIEnv*, jobject, jint display_rotation, jint color_camera_rotation) {
  return app.OnDisplayChanged(display_rotation, color_camera_rotation);
}

#ifdef __cplusplus
}
#endif

redpajama_set_name: RedPajamaGithub


text:
/**
 * package-info class.
 *
 * @author Denis
 * @since 20.09.2017
 */
package ru.dega.servlets.json;


text:
.PHONY: clean templates compile
PROCESS_TPL = scripts/process_tpl.js
SOURCES = lib/header.js lib/config.js lib/util.js lib/stats.js lib/loop/loop.js lib/loop/multiloop.js lib/monitoring/collectors.js lib/monitoring/statslogger.js lib/monitoring/monitor.js lib/monitoring/monitorgroup.js lib/http.js lib/reporting/*.tpl.js lib/reporting/template.js lib/reporting/report.js lib/reporting/reportmanager.js lib/reporting/external.js lib/loadtesting.js  lib/remote/endpoint.js lib/remote/endpointclient.js lib/remote/slave.js lib/remote/slaves.js lib/remote/slavenode.js lib/remote/cluster.js lib/remote/httphandler.js lib/remote/remotetesting.js

all: compile

clean:
	rm -rf ./lib-cov
	rm -f ./nodeload.js ./lib/reporting/*.tpl.js
	rm -f results-*-err.log results-*-stats.log results-*-summary.html

templates:
	$(PROCESS_TPL) REPORT_SUMMARY_TEMPLATE lib/reporting/summary.tpl > lib/reporting/summary.tpl.js
	$(PROCESS_TPL) DYGRAPH_SOURCE lib/reporting/dygraph.tpl > lib/reporting/dygraph.tpl.js

compile: templates
	echo "#!/usr/bin/env node" > ./nodeload.js
	cat $(SOURCES) | ./scripts/jsmin.js >> ./nodeload.js
	chmod +x ./nodeload.js


text:
include	EManual.mk

SOURCE=./source/zh
SOURCE_CONFIG_FILE=./source/book.json


text:
	#define FLOATASM //Imago guarded from x64 compilers on 6/20/09
	#define USEASM
#endif

// VS.Net 2003 port: typename is required for template
#if _MSC_VER >= 1310
	#define VSNET_TNFIX typename
#else
	#define VSNET_TNFIX
#endif
//
// Required CRT headers
//

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "math.h"
#include "time.h"
#include "malloc.h"

//
// Required Win32 headers
//

#include "windows.h"
#include "wininet.h"

//
// DirectX Stuff
//

// KGJV - Removed dependancy from DX
#include "OldDXDefns.h"	// Older DX definitions included to get the project to build. At some point,
						// they all become redundant.

//
// Library Headers
//

#include "zassert.h"
#include "alloc.h"
#include "mask.h"
#include "tref.h"
#include "cast.h"
#include "zmath.h"
#include "zadapt.h"

#include "tcompare.h"
#include "tarray.h"
#include "tvector.h"
#include "tstack.h"
#include "tlist.h"
#include "tmap.h"

#include "comobj.h"

//
// Types
//

#include "ztime.h"
#include "zstring.h"
#include "point.h"
#include "rect.h"
#include "vector.h"
#include "vertex.h"
#include "orientation.h"
#include "matrix.h"
#include "quaternion.h"
#include "color.h"

//
// Interfaces
//

#include "event.h"
#include "input.h"
#include "genericlist.h"
#include "FTPSession.h"

//
// Win32 Wrapper Classes
//

#include "base.h"
#include "window.h"
#include "win32app.h"
#include "VersionInfo.h"

//
// Parser
//

#include "token.h"

#include "minidump.h" //Imago 7/10 9/14

#endif


text:
demo to build a jboss war module

http://localhost:8080/hello/test


text:
package com.edugility.jpa.converters;

import java.util.Locale;

import javax.persistence.AttributeConverter;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class TestCaseLocaleRoundTripping {

  private AttributeConverter<Locale, String> converter;

  private Locale[] availableLocales;

  public TestCaseLocaleRoundTripping() {
    super();
  }

  @Before
  public void setUp() {
    this.converter = new LocaleToLanguageTagConverter();
    this.availableLocales = Locale.getAvailableLocales();
    assertNotNull(this.availableLocales);
    assertTrue(this.availableLocales.length > 0);
  }

  @Test
  public void testCaseLocaleRoundTripping() {
    for (final Locale availableLocale : this.availableLocales) {
      assertNotNull(availableLocale);
      final String converterStringRepresentation = this.converter.convertToDatabaseColumn(availableLocale);
      assertNotNull(converterStringRepresentation);
      assertFalse(converterStringRepresentation.isEmpty());
      final Locale converterLocaleRepresentation = this.converter.convertToEntityAttribute(converterStringRepresentation);
      if (!availableLocale.equals(converterLocaleRepresentation) && !"no_NO_NY".equals(availableLocale.toString())) {
        // See "Special Conversions" in http://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#toLanguageTag--
        assertEquals(availableLocale, converterLocaleRepresentation);
      }
    }
  }

}


text:
namespace fm
{
class Window;
class Engine;
class Scene;
class SceneManager;
}

namespace fm
{
	struct Config
	{
		std::string name = "Empty";
		size_t width = 800;
		size_t height = 600;
		size_t fpsWanted = 60;
		bool	standAlone = false;
		size_t windowFlag;
		fm::Folder userDirectory;
	};

	struct ProjectSettings
	{
		std::string name = "Project";
		fm::FilePath path;
		std::string resourcesFolder = "Resources";
	};

	//Could be drastically optimized, but not needed
	template <typename T, size_t P>
	class CircularBuffer
	{
	public:

		CircularBuffer()
		{
		}
		void Push(T & t)
		{
			size_t nextLimit = _currentLimit + 1;
			if (_maxLimit < nextLimit)
			{
				_list.push_back(t);
				_currentLimit = nextLimit;
				_index = nextLimit;
			}
			else
			{
				if (_index + 1 > _maxLimit)
					_index = 0;
				_list[_index] = t;
			}
		}

		size_t Size()
		{
			return _currentLimit;
		}
		bool IsEmpty()
		{
			return _currentLimit != 0;
		}

		const T& operator[](size_t index)
		{
			return _list[index];
		}
	private:
		size_t _index = 0;
		size_t _maxLimit = P;
		size_t _currentLimit = 0;

		std::vector<T> _list;
	};

class Application
{
    public:

        ~Application();
		Application();
		inline static Application& Get()
		{
			static Application app;
			return app;
		}

        bool						Serialize() const;
		bool						SerializeCurrentScene() const;

        bool						Read();

        void						Start();
		void						Stop();
		void						SetConfig(const Config &inConfig);
        void						Init();
        void						DeInit();

        void						Update(bool withEditor);

        fm::Window*					GetWindow() const;
        fm::Engine*					GetEngine() const;

		const fm::Folder&			GetUserDirectory() const;

		const fm::Config&			GetCurrentConfig() const;
		bool						IsRunning() const;

		void						SetProjectName(const std::string& inName);
		std::shared_ptr<fm::Scene>	GetScene(const std::string &inName) const;
		const std::string&			GetCurrentSceneName() const;
		std::shared_ptr<fm::Scene>	GetCurrentScene() const;
		void						LoadProject(const fm::Folder& inPath);
		void						SetUserDirectory(const fm::Folder& inPath);
		std::shared_ptr<fm::Scene>	LoadScene(const fm::FilePath& inPath);

		std::shared_ptr<fm::Scene>	AddNewScene(const fm::FilePath& inPath);
		void						SetCurrentScene(const std::string& name, bool isPrivate);
		std::shared_ptr<fm::Scene>	AddPrivateScene(const std::string& inName);
		bool						ClearScene(const std::string& inName, bool isPrivate, bool remove = false);
		std::shared_ptr<Scene>		RenameScene(std::shared_ptr<Scene> inCurrentScene, const fm::FilePath& inPath);
		void						SerializeCurrentScene(nlohmann::json& outjson);

private:

        fm::Engine*							_engine;
        fm::Window*							_window;
        fm::Config							_currentConfig;
		std::string							_nameLastScene;
		std::unique_ptr<fm::SceneManager>	_sceneManager;
};

}

#endif // APPLICATION_H


text:
package org.drools.compiler.cdi;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.drools.compiler.kproject.AbstractKnowledgeTest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.api.cdi.KReleaseId;
import org.kie.api.cdi.KSession;
import org.kie.api.runtime.KieSession;

@RunWith(CDITestRunner.class)
public class KieSessionInjectionTest {
    public static AbstractKnowledgeTest helper;

    @Inject
    @KSession("jar1.KSession2")
    @KReleaseId( groupId    = "jar1",
                 artifactId = "art1",
                 version    = "1.0" )
    private KieSession kbase1ksession2v10;

    @Inject
    @KSession("jar1.KSession2")
    @KReleaseId( groupId    = "jar1",
                 artifactId = "art1",
                 version    = "1.1" )
    private KieSession kbase1ksession2v11;

    @Inject
    @KSession(value="jar1.KSession2", name="ks1")
    @KReleaseId( groupId    = "jar1",
                 artifactId = "art1",
                 version    = "1.0" )
    private KieSession kbase1ksession2ks1;

    @Inject
    @KSession(value="jar1.KSession2", name="ks2")
    @KReleaseId( groupId    = "jar1",
                 artifactId = "art1",
                 version    = "1.0" )
    private KieSession kbase1ksession2ks2  ;

    @Inject
    @KSession(value="jar1.KSession2", name="ks2")
    @KReleaseId( groupId    = "jar1",
                 artifactId = "art1",
                 version    = "1.0" )
    private KieSession kbase1ksession2ks22;

    @BeforeClass
    public static void beforeClass() {
        helper = new AbstractKnowledgeTest();
        try {
            helper.setUp();
        } catch ( Exception e ) {
            e.printStackTrace();
            fail( e.getMessage() );
        }
        try {
            helper.createKieModule( "jar1", true, "1.0" );
            helper.createKieModule( "jar1", true, "1.1" );
        } catch ( Exception e ) {
            e.printStackTrace();
            fail( "Unable to build dynamic KieModules:\n" + e.toString() );
        }

        CDITestRunner.setUp( );

        CDITestRunner.weld = CDITestRunner.createWeld( KieSessionInjectionTest.class.getName() );

        CDITestRunner.container = CDITestRunner.weld.initialize();
    }

    @AfterClass
    public static void afterClass() {
        CDITestRunner.tearDown();

        try {
            helper.tearDown();
        } catch ( Exception e ) {
            fail( e.getMessage() );
        }
    }

    @Test
    public void testDynamicKieSessionReleaseId() throws IOException, ClassNotFoundException, InterruptedException {
        assertNotNull( kbase1ksession2v10 );
        assertNotNull( kbase1ksession2v10 );

        List<String> list = new ArrayList<String>();
        kbase1ksession2v10.setGlobal( "list", list );
        kbase1ksession2v10.fireAllRules();

        assertEquals( 2, list.size() );
        assertTrue( list.get(0).endsWith( "1.0" ) );
        assertTrue( list.get(1).endsWith( "1.0" ) );

        list = new ArrayList<String>();
        kbase1ksession2v11.setGlobal( "list", list );
        kbase1ksession2v11.fireAllRules();

        assertEquals( 2, list.size() );
        assertTrue( list.get(0).endsWith( "1.1" ) );
        assertTrue( list.get(1).endsWith( "1.1" ) );
    }

    @Test
    public void testNamedKieSessions() throws IOException, ClassNotFoundException, InterruptedException {
        assertNotNull(kbase1ksession2ks1);
        assertNotNull(kbase1ksession2ks2);
        assertNotNull(kbase1ksession2ks22);

        assertNotSame(kbase1ksession2ks1, kbase1ksession2ks2);
        assertSame( kbase1ksession2ks2, kbase1ksession2ks22);

        List<String> list = new ArrayList<String>();
        kbase1ksession2ks1.setGlobal( "list", list );
        kbase1ksession2ks1.fireAllRules();

        assertEquals( 2, list.size() );
        assertTrue( list.get(0).endsWith( "1.0" ) );
        assertTrue( list.get(1).endsWith( "1.0" ) );

        list = new ArrayList<String>();
        kbase1ksession2ks2.setGlobal( "list", list );
        kbase1ksession2ks2.fireAllRules();

        assertEquals( 2, list.size() );
        assertTrue( list.get(0).endsWith( "1.0" ) );
        assertTrue( list.get(1).endsWith( "1.0" ) );
    }

}


text:
'use strict';

var Harness = require('./support');
var customer = Harness.defineCustomerTable();
var post = Harness.definePostTable();

Harness.test({
  query: customer.select().where(customer.age.between(18, 25)),
  pg: {
    text  : 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" BETWEEN $1 AND $2)',
    string: 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" BETWEEN 18 AND 25)'
  },
  sqlite: {
    text  : 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" BETWEEN $1 AND $2)',
    string: 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" BETWEEN 18 AND 25)'
  },
  mysql: {
    text  : 'SELECT `customer`.* FROM `customer` WHERE (`customer`.`age` BETWEEN ? AND ?)',
    string: 'SELECT `customer`.* FROM `customer` WHERE (`customer`.`age` BETWEEN 18 AND 25)'
  },
  mssql: {
    text  : 'SELECT [customer].* FROM [customer] WHERE ([customer].[age] BETWEEN @1 AND @2)',
    string: 'SELECT [customer].* FROM [customer] WHERE ([customer].[age] BETWEEN 18 AND 25)'
  },
  params: [18, 25]
});

Harness.test({
  query: post.select().where(post.userId.between(customer.subQuery().select(customer.id.min()), customer.subQuery().select(customer.id.max()))),
  pg: {
    text  : 'SELECT "post".* FROM "post" WHERE ("post"."userId" BETWEEN (SELECT MIN("customer"."id") AS "id_min" FROM "customer") AND (SELECT MAX("customer"."id") AS "id_max" FROM "customer"))',
    string: 'SELECT "post".* FROM "post" WHERE ("post"."userId" BETWEEN (SELECT MIN("customer"."id") AS "id_min" FROM "customer") AND (SELECT MAX("customer"."id") AS "id_max" FROM "customer"))'
  },
  sqlite: {
    text  : 'SELECT "post".* FROM "post" WHERE ("post"."userId" BETWEEN (SELECT MIN("customer"."id") AS "id_min" FROM "customer") AND (SELECT MAX("customer"."id") AS "id_max" FROM "customer"))',
    string: 'SELECT "post".* FROM "post" WHERE ("post"."userId" BETWEEN (SELECT MIN("customer"."id") AS "id_min" FROM "customer") AND (SELECT MAX("customer"."id") AS "id_max" FROM "customer"))'
  },
  mysql: {
    text  : 'SELECT `post`.* FROM `post` WHERE (`post`.`userId` BETWEEN (SELECT MIN(`customer`.`id`) AS `id_min` FROM `customer`) AND (SELECT MAX(`customer`.`id`) AS `id_max` FROM `customer`))',
    string: 'SELECT `post`.* FROM `post` WHERE (`post`.`userId` BETWEEN (SELECT MIN(`customer`.`id`) AS `id_min` FROM `customer`) AND (SELECT MAX(`customer`.`id`) AS `id_max` FROM `customer`))'
  },
  mssql: {
    text  : 'SELECT [post].* FROM [post] WHERE ([post].[userId] BETWEEN (SELECT MIN([customer].[id]) AS [id_min] FROM [customer]) AND (SELECT MAX([customer].[id]) AS [id_max] FROM [customer]))',
    string: 'SELECT [post].* FROM [post] WHERE ([post].[userId] BETWEEN (SELECT MIN([customer].[id]) AS [id_min] FROM [customer]) AND (SELECT MAX([customer].[id]) AS [id_max] FROM [customer]))'
  },
  params: []
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Calyptridium pygmaeum Parish ex Rydb.

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2017 Capital One Services, LLC and Bitwise, Inc.
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License
 -->
<p:graph name="Mainjob" xmlns:it="hydrograph/engine/jaxb/inputtypes"
		 xmlns:ot="hydrograph/engine/jaxb/outputtypes"
		 xmlns:op="hydrograph/engine/jaxb/operationstypes"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="hydrograph/engine/jaxb/main"
		 xsi:schemaLocation="hydrograph/engine/jaxb/main ../../../../hydrograph.engine.core/src/main/resources/newxmlschema/main/main.xsd  ">

	<inputs id="input1" batch="1" xsi:type="it:textFileDelimited">
		<outSocket id="out0">
			<schema name="schema1">
				<includeExternalSchema uri="testData/XMLFiles/outputSubjob/SchemaForSubjob.xml" />
			</schema>
		</outSocket>
		<path uri="testData/input/delimitedInputFileForSubjob" />
		<delimiter value="," />
		<hasHeader value="false" />
	</inputs>

	<operations id="reformat" batch="0" xsi:type="op:transform">
		<inSocket fromComponentId="input1" fromSocketId="out0" id="in0" />
		<operation id="opt1" class="com.bitwiseglobal.test.TransformTest">
			<inputFields>
				<field name="name" inSocketId="in0" />
			</inputFields>
			<outputFields>
				<field name="name" type="java.lang.String" />
			</outputFields>
		</operation>
		<outSocket id="out0">
			<passThroughField name="*" inSocketId="in0" />
			<mapField sourceName="city" name="new_city" inSocketId="in0" />
			<operationField name="name" operationId="opt1" />
		</outSocket>
	</operations>

	<outputs id="outputSubjob" batch="0" xsi:type="ot:subjob">
		<inSocket fromComponentId="reformat" fromSocketId="out0" id="in0">
			<schema name="schema1">
			</schema>
		</inSocket>
		<path uri="testData/XMLFiles/outputSubjob/OutputSubjob.xml" />
		<subjobParameter>
			<property name="ads" value="schema1" />
			<property name="path"
				value="testData/output/subjob/outputSubjob" />
		</subjobParameter>
	</outputs>

</p:graph>


text:
Projet-devWeb <br>
https://chawki505.github.io/univ-oran-update/


text:
"""Defines class for wrapping an Estimator model function."""
# TODO(kathywu): support remaining outputs from the EstimatorSpec.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import six
import tensorflow as tf
from tensorflow.python.eager import function
from tensorflow.python.eager import wrap_function
from tensorflow.python.framework import func_graph
from tensorflow.python.saved_model.model_utils import export_utils
from tensorflow.python.util import function_utils
from tensorflow_estimator.python.estimator import model_fn as model_fn_lib
from tensorflow_estimator.python.estimator.mode_keys import ModeKeys

class ModelFunction(tf.compat.v2.__internal__.tracking.AutoTrackable):
  """A checkpointable ModelFunction object.

  This object stores a global mapping of variables and functions for each mode.
  """

  def __init__(self, config=None, params=None):
    self._config = config
    self._params = params
    self._functions = {}

    self._variable_holder = wrap_function.VariableHolder(share_variables=True)

    # Add reference to the variable holder's mapping of variables, which is a
    # trackable object.
    self._variables_by_name = self._variable_holder.variables

  @staticmethod
  def from_function(model_fn, all_modes=None, config=None, params=None):
    """Creates a new ModelFunction object from a model function."""
    if all_modes is None:
      all_modes = [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]
    else:
      all_modes = list(all_modes)

    obj = ModelFunction(config=config, params=params)
    for mode in all_modes:
      obj.add_mode(model_fn, mode)
    return obj

  @property
  def variables(self):
    return self._variables_by_name

  def add_mode(self, fn, mode, input_signature=None):
    if mode in self._functions:
      raise ValueError('ModelFunction object has multiple functions with name'
                       ' {}.'.format(mode))

    spec_fn = EstimatorSpecFunction(
        fn,
        mode,
        config=self._config,
        params=self._params,
        variable_holder=self._variable_holder,
        input_signature=input_signature)

    self._functions[mode] = spec_fn

  def train(self, features, labels):
    return self.call(ModeKeys.TRAIN, features, labels)

  def evaluate(self, features, labels):
    return self.call(ModeKeys.EVAL, features, labels)

  def predict(self, features):
    return self.call(ModeKeys.PREDICT, features)

  def call(self, mode, features, labels=None):
    if mode not in self._functions:
      raise ValueError(
          'Mode {} is not defined the ModelFunction. To add modes,'
          ' use the `add_mode()` function. Available modes: {}'.format(
              mode, self._functions.keys()))
    fn = self._functions[mode]
    if fn.expects_labels:
      return fn(features, labels)
    else:
      return fn(features)

def _wrap_and_verify_model_fn(model_fn,
                              mode=None,
                              config=None,
                              params=None,
                              input_signature=None):
  """Returns a function that only has only tensor arguments (features, labels).

  Args:
    model_fn: Model function. Must follow the signature defined in
      `tf.estimator.Estimator`.
    mode: Optional string `tf.estimstor.ModeKey`.
    config: Optional `estimator.RunConfig` object.
    params: Optional `dict` of hyperparameters.
    input_signature: Possibly nested TensorSpec of the tensor arguments.

  Returns:
    tuple of (
      function that only accepts tensor arguments (features and/or labels),
      whether the returned function expects a labels argument)
  """
  model_fn_lib.verify_model_fn_args(model_fn, params)
  args = function_utils.fn_args(model_fn)
  kwargs = {}
  if 'mode' in args:
    kwargs['mode'] = mode
  if 'params' in args:
    kwargs['params'] = params
  if 'config' in args:
    kwargs['config'] = config

  if 'labels' in args:
    if input_signature is None or len(input_signature) == 2:

      def wrapped_model_fn(features, labels=None):
        return model_fn(features=features, labels=labels, **kwargs)
    else:

      def wrapped_model_fn(features):
        return model_fn(features=features, labels=None, **kwargs)
  else:

    def wrapped_model_fn(features):
      return model_fn(features=features, **kwargs)

  return wrapped_model_fn, 'labels' in args

class EstimatorSpecFunction(tf.compat.v2.__internal__.function.Function):
  """Wraps graph functions defined for a function returning an EstimatorSpec.

  Instances of this class are revivable when attached to a checkpointable
  object.
  """

  def __init__(self,
               fn,
               mode,
               config=None,
               params=None,
               variable_holder=None,
               **kwargs):
    """Initializes an EstimatorSpecFunction.

    Args:
      fn: Python model function.
      mode: String mode to run the function.
      config: RunConfig that is passed to the `config` arg in the function.
      params: object that is passed to the `params` argument in the function.
      variable_holder: Optional `wrap_function.VariableHolder` object.
      **kwargs: Optional keyword arguments to pass to tf.function (e.g.
        input_signature).
    """
    python_function, self.expects_labels = _wrap_and_verify_model_fn(
        fn,
        mode=mode,
        config=config,
        params=params,
        input_signature=kwargs.get('input_signature', None))
    super(EstimatorSpecFunction, self).__init__(python_function, mode, **kwargs)
    self._variable_holder = variable_holder

  def _defun(self, fn):
    return _EstimatorSpecFunction(
        fn,
        name=self._name,
        variable_holder=self._variable_holder,
        input_signature=self.input_signature,
        autograph=self._autograph,
        autograph_options=self._experimental_autograph_options)

class _EstimatorSpecFunction(function.Function):
  """Wraps graph functions defined for a function returning an EstimatorSpec.

  This object handles creation of the graph functions.
  """

  def __init__(self, python_function, name, variable_holder=None, **kwargs):
    super(_EstimatorSpecFunction, self).__init__(python_function, name,
                                                 **kwargs)
    self._variable_holder = variable_holder

  def _create_graph_function(self, args, kwargs, **other_kwargs):
    _ = other_kwargs
    wrapped_graph = _EstimatorWrappedGraph(self._variable_holder)
    return wrapped_graph.wrap_model_fn(
        self._python_function,
        self._name,
        signature=self.input_signature,
        args=args,
        kwargs=kwargs)

class _EstimatorWrappedGraph(wrap_function.WrappedGraph):
  """WrappedGraph that handles global step creation and wraps estimator fns."""

  def __init__(self, *args, **kwargs):
    super(_EstimatorWrappedGraph, self).__init__(*args, **kwargs)
    # Create global step variable, which may be used by the input and model fns.
    self._global_step_read_fn = self.wrap_function(
        self._global_step, signature=[])

    self._concrete_model_fn = None

    # Original EstimatorSpec object returned by the model function. Only tensors
    # and ops are returned by the concrete model function.
    self._estimator_spec = None

  def _global_step(self):
    return tf.compat.v1.train.get_or_create_global_step()

  @property
  def global_step(self):
    return self._global_step_read_fn()

  @property
  def model_fn(self):
    return self._concrete_model_fn

  @property
  def estimator_spec(self):
    if self._concrete_model_fn is None:
      raise ValueError('Please wrap a model function first.')
    return self._estimator_spec

  def wrap_model_fn(self,
                    model_fn,
                    mode,
                    args=None,
                    kwargs=None,
                    signature=None):
    """Wraps a model function, and stores the returned estimator spec."""
    if self._concrete_model_fn is not None:
      raise ValueError('`wrap_model_fn` should be only called once per graph.')

    def fn(*args, **kwargs):
      """Returns tensor and op outputs from the returned spec."""
      ret = model_fn(*args, **kwargs)

      if isinstance(ret, model_fn_lib.EstimatorSpec):
        self._estimator_spec = ret
        return _filter_estimator_spec_outputs(ret)
      return ret

    name = 'model_fn_{}'.format(mode)
    self._concrete_model_fn = self._wrap_function(fn, args, kwargs, signature,
                                                  name)
    return self._concrete_model_fn

  def wrap_input_receiver_fn(self, input_receiver_fn):
    """Converts an input receiver function to one or more concrete functions.

    Input receiver functions are python functions with no arguments.
    Placeholders are created within the function and used to receive inputs to
    the model.

    The function (or multiple functions) generated depends on the InputReceiver
    object returned by `input_receiver_fn`.

    Generally, the returned function will have inputs and outputs:
      input_receiver(**receiver_tensors) --> features

    or (if the InputReceiver returns labels):
      input_receiver(**receiver_tensors) --> features, labels

    __Alternate Receiver Tensors__

    The InputReceiver may have alternate receiver tensors, in which case
    additional concrete functions are generated. Example:
      InputReceiver.receiver_tensors_alternatives = {
        'alt_input_1': Tensor,
        'alt_input_2': {
          'tensor_1': Tensor,
          'tensor_2': Tensor
        }
      }

    This will generate concrete functions:
      input_receiver_alt_input_1(input) --> features
      input_receiver_alt_input_2(tensor_1, tensor_2) --> features

    Args:
      input_receiver_fn: a no-argument function that returns an `InputReceiver`
        object.

    Returns:
      A list of tuples of (concrete function, receiver name). The name of the
      default input receiver is `None`.
    """
    ret = [None]

    def fn():
      ret[0] = input_receiver = input_receiver_fn()
      features = input_receiver.features
      labels = getattr(input_receiver, 'labels', None)

      if labels is None:
        return features
      return features, labels

    func_graph.func_graph_from_py_func(
        None,  # Name is unused.
        self._variable_holder.call_with_variable_creator_scope(fn),
        args=None,
        kwargs=None,
        signature=[],
        add_control_dependencies=False,
        func_graph=self.graph)

    functions = []
    input_receiver = ret[0]

    wrapped_input_receiver_fn = _prune_receiver_tensors(
        self._wrapped_function,
        receiver_tensors=input_receiver.receiver_tensors,
        outputs=self.graph.structured_outputs,
        name=_input_receiver_fn_name(None))
    functions.append((wrapped_input_receiver_fn, None))

    receiver_tensors_alternatives = getattr(input_receiver,
                                            'receiver_tensors_alternatives',
                                            None)

    if receiver_tensors_alternatives:
      for receiver_name, receiver_tensors_alt in (
          six.iteritems(receiver_tensors_alternatives)):
        receiver_tensors_alt = _canonicalize_receiver_tensors(
            receiver_tensors_alt)
        wrapped_input_receiver_fn = _prune_receiver_tensors(
            self._wrapped_function,
            receiver_tensors=receiver_tensors_alt,
            outputs=self.graph.structured_outputs,
            name=_input_receiver_fn_name(receiver_name))
        functions.append((wrapped_input_receiver_fn, receiver_name))
    return functions

def _filter_estimator_spec_outputs(spec):
  """Filters tensors and ops from an EstimatorSpec and returns a dictionary."""
  # TODO(kathywu): Add loss, export outputs, eval metrics depending on the mode.
  if spec.mode == ModeKeys.TRAIN:
    return dict(predictions=spec.predictions, train_op=spec.train_op)
  return dict(predictions=spec.predictions)

_RECEIVER_FN_NAME = '_input_receiver'

def _canonicalize_receiver_tensors(receiver_tensors):
  """Converts receiver tensors to the expected format of `as_signature_def`."""
  # TODO(b/129646028): Wrap function doesn't support composite tensors.
  for tensor in tf.nest.flatten(receiver_tensors):
    if not isinstance(tensor, tf.Tensor):
      raise ValueError('All receiver tensors must be tensors (composite '
                       'tensors are not yet supported).')

  if isinstance(receiver_tensors, dict):
    return receiver_tensors
  return {export_utils.SINGLE_RECEIVER_DEFAULT_NAME: receiver_tensors}

def _input_receiver_fn_name(name):
  if name is None:
    return _RECEIVER_FN_NAME
  else:
    return '{}_{}'.format(_RECEIVER_FN_NAME, name)

def _prune_receiver_tensors(wrapped_function, receiver_tensors, outputs, name):
  inputs = _canonicalize_receiver_tensors(receiver_tensors)
  return wrapped_function.prune(
      inputs,
      outputs,
      name=name,
      input_signature=(None, func_graph.convert_structure_to_signature(inputs)))


text:
package com.gikk.twirk.types.mode;

import com.gikk.twirk.types.twitchMessage.TwitchMessage;

/**Constructs a {@link Mode} object. To create a {@link Mode} object, call the {@link #build(TwitchMessage)} method
 *
 * @author Gikkman
 *
 */
public interface ModeBuilder {

    public static ModeBuilder getDefault() {
        return new DefaultModeBuilder();
    }

	/**Constructs a new {@link Mode} object from a {@link TwitchMessage}, received from Twitch. The user
	 * is responsible for making sure that this message can actually be made into a {@link Mode} object.
	 * Make sure that the COMMAND of the message equals "MODE"
	 *
	 * @param message The message we received from Twitch
	 * @return A {@link Mode}, or null if a {@link Mode} could not be created
	 */
	public Mode build(TwitchMessage message);
}


text:
module RecurringWorker
  def self.included kls
    kls.send :alias_method_chain, :perform, :recurring_worker
  end

  def perform_with_recurring_worker data
    begin
      perform_without_recurring_worker(data)
    rescue Exception => ex
      @request.complete = true
      @request.success = false
      @request.error = true
      @request.status_message = "Exception: #{ex.message}"
      if $DEBUG
        puts "----- EXCEPTION DURING PROCESSING"
        puts ex.message
        puts ex.backtrace.join("\n")
      end
    ensure
      reschedule
      @request.save
    end
  end

  def reschedule
    kls = @request.class
    kls.create! :worker_name => @request.worker_name,
                :job_key => @request.job_key,
                :data => @request.data
  end
end


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # Build, load or pull an image, making the image available for creating containers. Also supports tagging an image into a repository and archiving an image to a .tar file.
      class Docker_image < Base
        # @return [String, nil] Use with state C(present) to archive an image to a .tar file.
        attribute :archive_path
        validates :archive_path, type: String

        # @return [String, nil] Use with state C(present) to load an image from a .tar file.
        attribute :load_path
        validates :load_path, type: String

        # @return [Object, nil] Use with state C(present) to provide an alternate name for the Dockerfile to use when building an image.
        attribute :dockerfile

        # @return [Symbol, nil] Use with state I(absent) to un-tag and remove all images matching the specified name. Use with state C(present) to build, load or pull an image when the image already exists.
        attribute :force
        validates :force, type: Symbol

        # @return [Object, nil] Timeout for HTTP requests during the image build operation. Provide a positive integer value for the number of seconds.
        attribute :http_timeout

        # @return [String] Image name. Name format will be one of: name, repository/name, registry_server:port/name. When pushing or pulling an image the name can optionally include the tag by appending ':tag_name'.
        attribute :name
        validates :name, presence: true, type: String

        # @return [String, nil] Use with state 'present' to build an image. Will be the path to a directory containing the context and Dockerfile for building an image.
        attribute :path
        validates :path, type: String

        # @return [Boolean, nil] When building an image downloads any updates to the FROM image in Dockerfile.
        attribute :pull
        validates :pull, expression_inclusion: {:in=>[true, false], :message=>"%{value} needs to be true, false"}, allow_nil: true

        # @return [Symbol, nil] Push the image to the registry. Specify the registry as part of the I(name) or I(repository) parameter.
        attribute :push
        validates :push, type: Symbol

        # @return [Boolean, nil] Remove intermediate containers after build.
        attribute :rm
        validates :rm, expression_inclusion: {:in=>[true, false], :message=>"%{value} needs to be true, false"}, allow_nil: true

        # @return [Symbol, nil] Do not use cache when building an image.
        attribute :nocache
        validates :nocache, type: Symbol

        # @return [String, nil] Full path to a repository. Use with state C(present) to tag the image into the repository. Expects format I(repository:tag). If no tag is provided, will use the value of the C(tag) parameter or I(latest).
        attribute :repository
        validates :repository, type: String

        # @return [:absent, :present, :build, nil] Make assertions about the state of an image.,When C(absent) an image will be removed. Use the force option to un-tag and remove all images matching the provided name.,When C(present) check if an image exists using the provided name and tag. If the image is not found or the force option is used, the image will either be pulled, built or loaded. By default the image will be pulled from Docker Hub. To build the image, provide a path value set to a directory containing a context and Dockerfile. To load an image, specify load_path to provide a path to an archive file. To tag an image to a repository, provide a repository path. If the name contains a repository path, it will be pushed.,NOTE: C(build) is DEPRECATED and will be removed in release 2.3. Specifying C(build) will behave the same as C(present).
        attribute :state
        validates :state, expression_inclusion: {:in=>[:absent, :present, :build], :message=>"%{value} needs to be :absent, :present, :build"}, allow_nil: true

        # @return [String, nil] Used to select an image when pulling. Will be added to the image when pushing, tagging or building. Defaults to I(latest).,If C(name) parameter format is I(name:tag), then tag value from C(name) will take precedence.
        attribute :tag
        validates :tag, type: String

        # @return [Hash, nil] Provide a dictionary of C(key:value) build arguments that map to Dockerfile ARG directive.,Docker expects the value to be a string. For convenience any non-string values will be converted to strings.,Requires Docker API >= 1.21 and docker-py >= 1.7.0.
        attribute :buildargs
        validates :buildargs, type: Hash

        # @return [Object, nil] A dictionary of limits applied to each container created by the build process.
        attribute :container_limits

        # @return [:no, :encrypt, :verify, nil] DEPRECATED. Whether to use tls to connect to the docker server. Set to C(no) when TLS will not be used. Set to C(encrypt) to use TLS. And set to C(verify) to use TLS and verify that the server's certificate is valid for the server. NOTE: If you specify this option, it will set the value of the tls or tls_verify parameters.
        attribute :use_tls
        validates :use_tls, expression_inclusion: {:in=>[:no, :encrypt, :verify], :message=>"%{value} needs to be :no, :encrypt, :verify"}, allow_nil: true
      end
    end
  end
end


text:
package command

import (
	"fmt"
	"github.com/chrislusf/seaweedfs/weed/glog"
	"github.com/chrislusf/seaweedfs/weed/pb"
	"github.com/chrislusf/seaweedfs/weed/replication/source"
	"github.com/chrislusf/seaweedfs/weed/security"
	"github.com/chrislusf/seaweedfs/weed/util"
	"google.golang.org/grpc"
	"strings"
	"time"
)

type FilerBackupOptions struct {
	isActivePassive *bool
	filer           *string
	path            *string
	excludePaths    *string
	debug           *bool
	proxyByFiler    *bool
	timeAgo         *time.Duration
}

var (
	filerBackupOptions FilerBackupOptions
)

func init() {
	cmdFilerBackup.Run = runFilerBackup // break init cycle
	filerBackupOptions.filer = cmdFilerBackup.Flag.String("filer", "localhost:8888", "filer of one SeaweedFS cluster")
	filerBackupOptions.path = cmdFilerBackup.Flag.String("filerPath", "/", "directory to sync on filer")
	filerBackupOptions.excludePaths = cmdFilerBackup.Flag.String("filerExcludePaths", "", "exclude directories to sync on filer")
	filerBackupOptions.proxyByFiler = cmdFilerBackup.Flag.Bool("filerProxy", false, "read and write file chunks by filer instead of volume servers")
	filerBackupOptions.debug = cmdFilerBackup.Flag.Bool("debug", false, "debug mode to print out received files")
	filerBackupOptions.timeAgo = cmdFilerBackup.Flag.Duration("timeAgo", 0, "start time before now. \"300ms\", \"1.5h\" or \"2h45m\". Valid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\"")
}

var cmdFilerBackup = &Command{
	UsageLine: "filer.backup -filer=<filerHost>:<filerPort> ",
	Short:     "resume-able continuously replicate files from a SeaweedFS cluster to another location defined in replication.toml",
	Long: `resume-able continuously replicate files from a SeaweedFS cluster to another location defined in replication.toml

	filer.backup listens on filer notifications. If any file is updated, it will fetch the updated content,
	and write to the destination. This is to replace filer.replicate command since additional message queue is not needed.

	If restarted and "-timeAgo" is not set, the synchronization will resume from the previous checkpoints, persisted every minute.
	A fresh sync will start from the earliest metadata logs. To reset the checkpoints, just set "-timeAgo" to a high value.

`,
}

func runFilerBackup(cmd *Command, args []string) bool {

	util.LoadConfiguration("security", false)
	util.LoadConfiguration("replication", true)

	grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")

	clientId := util.RandomInt32()
	var clientEpoch int32

	for {
		clientEpoch++
		err := doFilerBackup(grpcDialOption, &filerBackupOptions, clientId, clientEpoch)
		if err != nil {
			glog.Errorf("backup from %s: %v", *filerBackupOptions.filer, err)
			time.Sleep(1747 * time.Millisecond)
		}
	}

	return true
}

const (
	BackupKeyPrefix = "backup."
)

func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOptions, clientId int32, clientEpoch int32) error {

	// find data sink
	config := util.GetViper()
	dataSink := findSink(config)
	if dataSink == nil {
		return fmt.Errorf("no data sink configured in replication.toml")
	}

	sourceFiler := pb.ServerAddress(*backupOption.filer)
	sourcePath := *backupOption.path
	excludePaths := strings.Split(*backupOption.excludePaths, ",")
	timeAgo := *backupOption.timeAgo
	targetPath := dataSink.GetSinkToDirectory()
	debug := *backupOption.debug

	// get start time for the data sink
	startFrom := time.Unix(0, 0)
	sinkId := util.HashStringToLong(dataSink.GetName() + dataSink.GetSinkToDirectory())
	if timeAgo.Milliseconds() == 0 {
		lastOffsetTsNs, err := getOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, int32(sinkId))
		if err != nil {
			glog.V(0).Infof("starting from %v", startFrom)
		} else {
			startFrom = time.Unix(0, lastOffsetTsNs)
			glog.V(0).Infof("resuming from %v", startFrom)
		}
	} else {
		startFrom = time.Now().Add(-timeAgo)
		glog.V(0).Infof("start time is set to %v", startFrom)
	}

	// create filer sink
	filerSource := &source.FilerSource{}
	filerSource.DoInitialize(
		sourceFiler.ToHttpAddress(),
		sourceFiler.ToGrpcAddress(),
		sourcePath,
		*backupOption.proxyByFiler)
	dataSink.SetSourceFiler(filerSource)

	processEventFn := genProcessFunction(sourcePath, targetPath, excludePaths, dataSink, debug)

	processEventFnWithOffset := pb.AddOffsetFunc(processEventFn, 3*time.Second, func(counter int64, lastTsNs int64) error {
		glog.V(0).Infof("backup %s progressed to %v %0.2f/sec", sourceFiler, time.Unix(0, lastTsNs), float64(counter)/float64(3))
		return setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, int32(sinkId), lastTsNs)
	})

	return pb.FollowMetadata(sourceFiler, grpcDialOption, "backup_"+dataSink.GetName(), clientId, clientEpoch, sourcePath, nil, startFrom.UnixNano(), 0, 0, processEventFnWithOffset, pb.TrivialOnError)

}


text:
local request = require 'resty.http_ng.request'

describe('request', function()
  describe('headers', function()
    it('normalizes case', function()
      local headers = request.headers.new{ ['content-type'] = 'text/plain' }
      assert.are.same({['Content-Type'] = 'text/plain'}, headers)
    end)

    it('changes them on set', function()
      local headers = request.headers.new{}
      assert.are.same({}, headers)

      headers.host = 'example.com'
      assert.are.same({Host = 'example.com'}, headers)
      assert.equal(headers.Host, headers.host)
    end)
  end)

  it('adds User-Agent header', function()
    local req = request.new{url = 'http://example.com/path', method = 'GET' }

    assert.equal('APIcast (+https://www.apicast.io)',req.headers['User-Agent'])
  end)

  it('adds Host header', function()
    local req = request.new{url = 'http://example.com/path', method = 'GET' }

    assert.equal('example.com',req.headers.Host)
  end)

  it('correct host heder format', function()
    results = {
      ['http://foo.com'] = "foo.com",
      ['http://foo.com:80'] = "foo.com",
      ['http://foo.com:80/test'] = "foo.com",
      ['http://foo.com:8080/test'] = "foo.com:8080",
      ['https://foo.com/'] = "foo.com",
      ['https://foo.com:8043/'] = "foo.com:8043",
      ['https://foo.com:8043/test'] = "foo.com:8043",
    }
    for key, val in pairs(results) do
      local req = request.new{url = key, method = 'GET' }
      assert.equal(val, req.headers.Host)
    end

  end)

  it('has version', function()
    local req = request.new{url = 'http://example.com/path', method = 'GET' }

    assert.equal(1.1, req.version)
  end)
end)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using MGTK.Services;

namespace MGTK.Controls
{
    public class PictureBox : Control
    {
        private PictureBoxSizeMode sizeMode = PictureBoxSizeMode.Normal;

        private Texture2D image;

        protected int imageWidth = 0, imageHeight = 0;
        protected int imageX = 0, imageY = 0;

        public PictureBoxSizeMode SizeMode
        {
            get
            {
                return sizeMode;
            }
            set
            {
                if (sizeMode != value)
                {
                    sizeMode = value;
                    SetInternalImageRepresentation();
                }
            }
        }

        public Texture2D Image
        {
            get
            {
                return image;
            }
            set
            {
                if (image != value)
                {
                    image = value;
                    SetInternalImageRepresentation();
                }
            }
        }

        public PictureBox(Form formowner)
            : base(formowner)
        {
            this.Init += new EventHandler(PictureBox_Init);
        }

        void PictureBox_Init(object sender, EventArgs e)
        {
            SetInternalImageRepresentation();
        }

        private void SetInternalImageRepresentation()
        {/*
            imageX = OwnerX + X;
            imageY = OwnerY + Y;
			*/
			if (Image == null)
				return;

            switch (SizeMode)
            {
                case PictureBoxSizeMode.Normal:
                    imageWidth = Image.Width;
                    imageHeight = Image.Height;

                    if (imageWidth > Width)
                        imageWidth = Width;
                    if (imageHeight > Height)
                        imageHeight = Height;
                    break;

                case PictureBoxSizeMode.Stretch:
                    imageWidth = Width;
                    imageHeight = Height;
                    break;

                case PictureBoxSizeMode.AutoSize:
                    Width = Image.Width;
                    Height = Image.Height;
                    imageWidth = Width;
                    imageHeight = Height;
                    break;

                case PictureBoxSizeMode.CenterImage:
                    imageWidth = Image.Width;
                    imageHeight = Image.Height;

                    imageX = Width / 2 - imageWidth / 2;
                    imageY = Height / 2 - imageHeight / 2;
                    break;
            }
        }

        public override void Draw()
        {
			if (Image != null)
            	DrawingService.Draw(SpriteBatchProvider, Image, OwnerX + X + imageX, OwnerY + Y + imageY,
			                    imageWidth, imageHeight, Color.White, SizeMode == PictureBoxSizeMode.Stretch, Z - 0.0001f);

 	        base.Draw();
        }
    }

    public enum PictureBoxSizeMode
    {
        Normal = 0,
        Stretch = 1,
        AutoSize = 2,
        CenterImage = 3
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 9(2): 106 (1917)

#### Original name
Cercospora acalypharum Tharp

### Remarks
null


text:
function (e, doc, options) {
    e.stopPropagation();

    var $this = $(this);
    var $$this = $$(this);

    $$this.doc = doc;
    $$this.currentDB = doc.db;

    $$this.options = options = options || {};

    var view = options.view? options.view: "regular";

    if (!($$(document).showdown_converter))
        $$(document).showdown_converter = new Showdown.converter();

    API.filterTopics(doc, function(_error, topics) {
        $this.trigger("render-" + view, [topics]);
    });
}


text:
@implementation DEChildCombinator

- (NSString *)description {
    return @">";
}

- (NSArray *)inverseRelativesOfView:(UIView *)subject {
    UIView *parent = [subject superview];
    if (parent) {
        return [NSArray arrayWithObject:parent];
    }
    return [NSArray array];
}

- (NSArray *)relativesOfView:(UIView *)subject {
    return [subject subviews];
}

@end


text:
package fr.xebia.extras.selma.it.mappers;

import fr.xebia.extras.selma.beans.AddressIn;
import fr.xebia.extras.selma.beans.AddressOut;
import fr.xebia.extras.selma.beans.PersonOut;
import fr.xebia.extras.selma.beans.PersonIn;
import fr.xebia.extras.selma.Mapper;

/**
 *
 */
@Mapper(ignoreMissingProperties = true)
public interface BeanMapper {

    PersonOut asPersonOut(PersonIn in);

    AddressOut asAddressOut (AddressIn in);
}


text:
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import fetch from 'isomorphic-fetch';
import { stringify as buildAPIQS } from 'qs';

import config from '../../config';

import LoadingMessage from '../../components/loading-message';
import ErrorMessage from '../../components/error-message';
import Dashboard from './dashboard';

const defaultState = {
  fetched: false,
  fetching: false,
  error: null,
  parameters: null,
  averages: null,
};

function NodesDashboard({
  measurements,
  projectId,
  projectName,
  selectedParams,
  lifecycle,
  dateRange,
  projectDates,
  sources,
  locations,
  country,
}) {
  const [
    { fetched, fetching, error, parameters, averages },
    setState,
  ] = useState(defaultState);

  const [year, month, day] = (dateRange ? dateRange.split('/') : []).map(
    Number
  );

  useEffect(() => {
    fetchLocationAverages();

    return () => {
      setState(defaultState);
    };
  }, [selectedParams, locations]);

  const fetchLocationAverages = () => {
    setState(state => ({ ...state, fetching: true, error: null }));
    let query = {
      parameter: [...new Set(selectedParams)],
      location: [...new Set(locations)],
      ...(dateRange
        ? {
            // In user space, month is 1 indexed
            date_from: new Date(year, month - 1, day || 1),
            date_to: day
              ? new Date(year, month - 1, day + 1)
              : new Date(year, month, 0),
          }
        : {}),
      spatial: 'location',
      temporal: 'day',
      group: true,
    };

    if (country) {
      query.country_id = country;
    }

    let f = buildAPIQS(query, { arrayFormat: 'repeat' });

    fetch(`${config.api}/averages?${f}`)
      .then(response => {
        if (response.status >= 400) {
          throw new Error('Bad response');
        }
        return response.json();
      })
      .then(
        json => {
          const aggregatedLocationAvgs = json.results.reduce((prev, entry) => {
            const paramName = entry.parameter;
            const prevMatchingParam = { ...prev[paramName] };
            return {
              ...prev,
              [paramName]: {
                displayName: entry.displayName,
                averageSum:
                  prevMatchingParam?.averageSum + entry.average ||
                  entry.average,
                totalEntries: prevMatchingParam?.totalEntries + 1 || 1,
                count:
                  prevMatchingParam?.count + entry.measurement_count ||
                  entry.measurement_count,
                parameter: entry.parameter,
                parameterId: entry.parameterId,
                unit: entry.unit,
                firstUpdated:
                  new Date(entry.day) < new Date(prevMatchingParam.firstUpdated)
                    ? entry.day
                    : prevMatchingParam.firstUpdated || entry.day,
                lastUpdated:
                  new Date(entry.day) > new Date(prevMatchingParam.lastUpdated)
                    ? entry.day
                    : prevMatchingParam.lastUpdated || entry.day,
                lastValue:
                  new Date(entry.day) > new Date(prevMatchingParam.lastUpdated)
                    ? entry.average
                    : prevMatchingParam.lastValue || entry.average,
              },
            };
          }, {});
          const calculatedParams = Object.values(aggregatedLocationAvgs)
            .flat()
            .map(param => {
              param.average = param.averageSum / param.totalEntries;
              return param;
            });
          const groupedAverges = json.results.reduce((prev, entry) => {
            const paramName = entry.parameter;
            return {
              ...prev,
              [paramName]: [...(prev[paramName] || []), entry],
            };
          }, {});
          setState(state => ({
            ...state,
            fetched: true,
            fetching: false,
            parameters: calculatedParams,
            averages: groupedAverges,
          }));
        },
        e => {
          console.log('e', e);
          setState(state => ({
            ...state,
            fetched: true,
            fetching: false,
            error: e,
          }));
        }
      );
  };

  if (!fetched && !fetching) {
    return null;
  }

  if (fetching) {
    return <LoadingMessage />;
  }

  if (error || !parameters.length) {
    return (
      <ErrorMessage
        isShowingDiagnosis={false}
        instructions="Please try a different location or parameter"
      />
    );
  }

  return (
    <Dashboard
      measurements={measurements}
      projectParams={parameters}
      projectId={projectId}
      projectName={projectName}
      lifecycle={lifecycle}
      dateRange={dateRange}
      projectDates={projectDates}
      sources={sources}
      timeseriesAverages={averages}
    />
  );
}

NodesDashboard.propTypes = {
  measurements: PropTypes.number,
  projectName: PropTypes.string,
  projectId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  selectedParams: PropTypes.array,
  lifecycle: PropTypes.arrayOf(PropTypes.number),
  dateRange: PropTypes.string,
  projectDates: PropTypes.shape({
    start: PropTypes.string,
    end: PropTypes.string,
  }),
  sources: PropTypes.arrayOf(
    PropTypes.shape({
      name: PropTypes.string,
      sourceURL: PropTypes.string,
      url: PropTypes.string,
      contacts: PropTypes.array,
    })
  ),
  locations: PropTypes.arrayOf(PropTypes.number),
  country: PropTypes.string,
};

export default NodesDashboard;


text:
namespace s3d {

using SampleType = SampsonDistanceFunction::SampleType;
using ModelType = SampsonDistanceFunction::ModelType;

// static
void SampsonDistanceFunction::ComputeDistance(const std::vector<SampleType>& pts1,
                                              const std::vector<SampleType>& pts2,
                                              const ModelType& model,
                                              std::vector<double>* distances) {
  assert(pts1.size() == pts2.size());
  assert(pts1.size() == distances->size());

  // create matrices with pts1h, pts2h
  Eigen::MatrixXd pts1h(3, pts1.size()), pts2h(3, pts2.size());

  // fill matrices
  for (size_t i = 0; i < pts1.size(); ++i) {
    pts1h.block<3, 1>(0, i) = pts1[i];
    pts2h.block<3, 1>(0, i) = pts2[i];
  }

  auto f = StanFundamentalMatrixSolver::FundamentalMatrixFromAlignment(model);
  auto pfp = (pts2h.transpose() * f).transpose();
  auto pfp2 = pfp.cwiseProduct(pts1h);
  auto colSum = pfp2.colwise().sum();
  auto d = colSum.array().pow(2);

  auto epl1 = f * pts1h;
  auto epl2 = f.transpose() * pts2h;
  auto coeff = epl1.row(0).array().square() + epl1.row(1).array().square() +
               epl2.row(0).array().square() + epl2.row(1).array().square();

  Eigen::VectorXd distancesVector = d.array() / coeff.array();
  Eigen::VectorXd::Map(&distances->operator[](0), distancesVector.size()) = distancesVector;
}
}  // namespace s3d


text:
import json

class APIExampleMixin:
    """A TestCase mixin that allows access to API by Example retrieval methods."""

    def api_example_json_file(self, url, method):
        """
        Return the API example at a location generated from the view URL and method.

        All URL kwargs in the URL are given only by their names, no other characters.
        For example:
            for POSTing to a view at `/patients/<pk>`,
            call self.api_example_json_file('/patients/pk', 'post')
            and you'll get 'api-description/patients/pk/post.json'
        """
        return '{base}{url}/{method}.json'.format(
            base=self.EXAMPLES_DIR,
            url=url,
            method=method,
        )

    def api_example_data(self, url, method):
        """Return the API example for this view URL and method, as a dictionary."""
        file_path = self.api_example_json_file(url, method)
        with open(file_path) as data_file:
            return json.load(data_file)

    def adjust_for_pks(self, data, object_pk, pk_to_replace=1, field_names=None):
        """
        Replace <pk_to_replace> with <object_pk> in the given data.

        Generally, the API description will be written with specific, 'hard-coded' pks.
        There's no other real way to do it, but it's a bit fiddly in tests when you
        don't know what the pk of, say, an object created by a POST will be.

        This method fixes that by modifying URL and pk fields in order to match them up
        to the specified <object_pk>.

        The method as written is very dumb.  Rather than trying to guess what a pk or
        a URL field looks like, it just looks for occurrences of '/<pk>' in strings and
        numbers that equal <pk>.  It can be limited to a set of specific fields to
        operate on, if you need to deal with special cases.

        The method copies the data dictionary in order to operate non-destructively,
        since you might need to run it several times with different `field_names` values.
        """
        url_pk_to_replace = '/{}'.format(pk_to_replace)
        url_object_pk = '/{}'.format(object_pk)

        # Copy data rather than modifying it in-place.
        adjusted_data = {}
        adjusted_data.update(data)

        if not field_names:
            field_names = adjusted_data.keys()

        for key in field_names:
            value = adjusted_data[key]
            if isinstance(value, str):
                adjusted_data[key] = value.replace(url_pk_to_replace, url_object_pk)
            elif value == pk_to_replace and not isinstance(value, bool):
                adjusted_data[key] = object_pk

        return adjusted_data


text:
public class MergeSort {
  public static void mergeSort(int[] list) {
    if (list.length > 1) {
      int[] firstHalf = new int[list.length / 2];
      System.arraycopy(list, 0, firstHalf, 0, list.length / 2);
      mergeSort(firstHalf);

      int secondHalfLength = list.length - list.length / 2;
      int[] secondHalf = new int[secondHalfLength];
      System.arraycopy(list, list.length / 2, secondHalf, 0, secondHalfLength);
      mergeSort(secondHalf);

      merge(firstHalf, secondHalf, list);
    }
  }

  public static void merge(int[] list1, int[] list2, int[] temp) {
    int current1 = 0;
    int current2 = 0;
    int current3 = 0;

    while (current1 < list1.length && current2 < list2.length) {
      if (list1[current1] < list2[current2]) {
        temp[current3++] = list1[current1++];
      } else {
        temp[current3++] = list2[current2++];
      }
    }

    while (current1 < list1.length) {
      temp[current3++] = list1[current1++];
    }

    while (current2 < list2.length) {
      temp[current3++] = list2[current2++];
    }
  }

  public static void main(String[] args) {
    int[] list = {2, 3, 2, 5, 6, 1, -2, 3, 14, 12};
    mergeSort(list);
    for (int i = 0; i < list.length; i++) {
      System.out.print(list[i] + " ");
    }
    System.out.println();
  }
}


text:
import React from 'react';
import { Redirect } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import { PageLayout } from '@gqlapp/look-client-react';

import { withStripeSubscription } from './withStripeSubscription';

interface SubscriptionAuthRouterProps {
  component: React.ComponentFactory<any, any>;
  loading: boolean;
  stripeSubscription: {
    active: boolean;
  };
}

/**
 * SubscriptionAuthRouter protects routes only for users with subscription,
 * redirect to add subscription page otherwise.
 */
const SubscriptionAuthRouter = ({
  component: Component,
  loading,
  stripeSubscription,
  ...props
}: SubscriptionAuthRouterProps) => {
  // PageLayout must be used here to prevent showing
  // empty screen when stripe subscription info is loading
  // Important: You don't need to include page layout inside protected routes!
  return (
    <>
      <Helmet>
        <script src="https://js.stripe.com/v3/" type="text/javascript" />
      </Helmet>
      <PageLayout>
        {!loading && stripeSubscription && stripeSubscription.active ? (
          <Component {...props} />
        ) : !loading && stripeSubscription && !stripeSubscription.active ? (
          <Redirect to="/add-subscription" />
        ) : null}
      </PageLayout>
    </>
  );
};

export default withStripeSubscription(SubscriptionAuthRouter as any);


text:
package com.app.tbd.ui.Model.Receive;

import java.util.List;

/**
 * Created by Dell on 9/13/2016.
 */
public class TransactionHistoryReceive {

    private String Message;
    private String Status;
    private List<Transaction> Transaction;

    public TransactionHistoryReceive() {

    }

    public TransactionHistoryReceive(TransactionHistoryReceive data) {
        Message = data.getMessage();
        Status = data.getStatus();
        Transaction = data.getTransaction();
    }

    public List<TransactionHistoryReceive.Transaction> getTransaction() {
        return Transaction;
    }

    public void setTransaction(List<TransactionHistoryReceive.Transaction> transaction) {
        Transaction = transaction;
    }

    public class Transaction{

        private String TxnDate;
        private String Description;
        private String PostDate;
        private String TxnTime;
        private String TxnPts;
        private String MID;
        private String TxnId;
        private String TxnAmt;

        public String getTxnDate() {
            return TxnDate;
        }

        public void setTxnDate(String txnDate) {
            TxnDate = txnDate;
        }

        public String getDescription() {
            return Description;
        }

        public void setDescription(String description) {
            Description = description;
        }

        public String getPostDate() {
            return PostDate;
        }

        public void setPostDate(String postDate) {
            PostDate = postDate;
        }

        public String getTxnTime() {
            return TxnTime;
        }

        public void setTxnTime(String txnTime) {
            TxnTime = txnTime;
        }

        public String getTxnPts() {
            return TxnPts;
        }

        public void setTxnPts(String txnPts) {
            TxnPts = txnPts;
        }

        public String getMID() {
            return MID;
        }

        public void setMID(String MID) {
            this.MID = MID;
        }

        public String getTxnId() {
            return TxnId;
        }

        public void setTxnId(String txnId) {
            TxnId = txnId;
        }

        public String getTxnAmt() {
            return TxnAmt;
        }

        public void setTxnAmt(String txnAmt) {
            TxnAmt = txnAmt;
        }

        /*"TxnDate":"02\/09\/2016",
                "Description":"hello Test redeem",
                "PostDate":"02\/09\/2016",
                "TxnTime":"17:15",
                "TxnPts":-100,
                "MID":"BUDGET",
                "TxnId":38718962,
                "TxnAmt":300*/

    }
    public String getMessage() {
        return Message;
    }

    public void setMessage(String message) {
        Message = message;
    }

    public String getStatus() {
        return Status;
    }

    public void setStatus(String status) {
        Status = status;
    }

}


text:
<?php
	/**
	 * @package Demos
	 */
	class Demo_asGrayscale extends Demo
	{
		public $order = 300;

		function execute($img, $request)
		{
			return $img->asGrayscale();
		}
	}


text:
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var serve = require('./serve-77b71940.js');
require('vite');
require('readline');
require('assert');
require('events');
require('stream');
require('util');
require('buffer');
require('path');
require('fs');
require('punycode');
require('prismjs');
require('url');
require('querystring');
require('tty');
require('net');
require('zlib');
require('constants');
require('os');
require('http');

exports.build = serve.build;
exports.createMarkdownRenderer = serve.createMarkdownRenderer;
exports.createServer = serve.createServer;
exports.defineConfig = serve.defineConfig;
exports.resolveConfig = serve.resolveConfig;
exports.resolveSiteData = serve.resolveSiteData;
exports.resolveSiteDataByRoute = serve.resolveSiteDataByRoute;
exports.serve = serve.serve;


text:
package com.blazebit.persistence.view.impl.entity;

import com.blazebit.persistence.view.impl.update.flush.FetchGraphNode;

/**
 *
 * @author Christian Beikov
 * @since 1.2.0
 */
public interface EntityLoaderFetchGraphNode<T extends EntityLoaderFetchGraphNode<T>> extends FetchGraphNode<T>, EntityLoader {

}


text:
package org.apache.log4j;

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

import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.ErrorCode;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.QuietWriter;
import org.apache.log4j.helpers.LogLog;
//import org.apache.log4j.helpers.TracerPrintWriter;

// Contibutors: Jens Uwe Pipka <jens.pipka@gmx.de>

/**
   FileAppender appends log events to a file.

   Support for java.io.Writer and console appending has been
   deprecated and will be removed in the near future. You are
   strongly encouraged to use the replacement solutions: {@link
   WriterAppender} and {@link ConsoleAppender}.

   @author Ceki Gülcü */
public class FileAppender extends WriterAppender {

 /**
     A string constant used in naming the option for setting the
     output file. Current value of this string constant is
     File.

Note that all option keys are case sensitive.

     @deprecated We now use JavaBeans introspection to configure
     components. Options strings are no longer needed.
  */
  public static final String FILE_OPTION = "File";

  /**
     A string constant used in naming the option that determines whether
     the output file will be truncated or appended to. Current value
     of this string constant is Append.

Note that all option keys are case sensitive.

     @deprecated We now use JavaBeans introspection to configure
     components. Options strings are no longer needed.
  */
  public static final String APPEND_OPTION = "Append";

  /** Append to or truncate the file? The default value for this
      variable is true, meaning that by default a
      FileAppender will append to an existing file and
      not truncate it.

This option is meaningful only if the FileAppender opens the
      file.
  */
  protected boolean fileAppend = true;

  /**
     The name of the log file. */
  protected String fileName = null;

  /**
     Is the QuietWriter ours or was it created and passed by the user?

     @deprecated FileAppender will not support streams passed by the
     user in the future. */
  protected boolean qwIsOurs = false;

  /**
     The default constructor does not do anything.
  */
  public
  FileAppender() {
  }

  /**
     Instantiate a FileAppender and set the output destination to a
     new {@link OutputStreamWriter} initialized with os
     as its {@link OutputStream}.

     @deprecated The functionality of this constructor form has
     been replaced by the {@link WriterAppender}. This constructor
     will be removed in the near term.

  */
  public
  FileAppender(Layout layout, OutputStream os) {
    super(layout, os);
  }

  /**
     Instantiate a FileAppender and set the output destination to
     writer.

The writer must have been opened by the user.

     @deprecated The functionality of constructor form has been
     replaced by the {@link WriterAppender}. This constructor will be
     removed in the near term.
  */
  public
  FileAppender(Layout layout, Writer writer) {
    super(layout, writer);
  }

  /**
    Instantiate a FileAppender and open the file designated by
    filename. The opened filename will become the output
    destination for this appender.

If the append parameter is true, the file will be
    appended to. Otherwise, the file designated by
    filename will be truncated before being opened.
  */
  public
  FileAppender(Layout layout, String filename, boolean append)
                                      throws IOException {
    this.layout = layout;
    this.setFile(filename, append);
  }

  /**
     Instantiate a FileAppender and open the file designated by
    filename. The opened filename will become the output
    destination for this appender.

The file will be appended to.  */
  public
  FileAppender(Layout layout, String filename) throws IOException {
    this(layout, filename, true);
  }

  /**
     The File option takes a string value which should be
     the name of the file to append to. Special values "System.out" or
     "System.err" are interpreted as the standard out and standard
     error streams.

Note that the "System.out" or "System.err"
     options are deprecated. Use {@link ConsoleAppender}
     instead.

If the option is set to "System.out" or "System.err" the
     output will go to the corresponding stream. Otherwise, if the
     option is set to the name of a file, then the file will be opened
     and output will go there.

Note: Actual opening of the file is made when {@link
     #activateOptions} is called, not when the options are set.
   */
  public void setFile(String file) {
    // Trim spaces from both ends. The users probably does not want
    // trailing spaces in file names.
    String val = file.trim();
    if(val.equalsIgnoreCase("System.out")) {
      setWriter(new OutputStreamWriter(System.out));
    } else if(val.equalsIgnoreCase("System.err")) {
      setWriter(new OutputStreamWriter(System.err));
    } else {
      fileName = val;
    }
  }

  /**
      Returns the value of the Append option.
   */
  public
  boolean getAppend() {
    return fileAppend;
  }

  /** Returns the value of the File option. */
  public
  String getFile() {
    return fileName;
  }

  /**
     Returns the option names for this component, namely the string
     array {@link #FILE_OPTION}, {@link #APPEND_OPTION}} in addition
     to the options of its super class {@link WriterAppender}.

     @deprecated We now use JavaBeans introspection to configure
     components. Options strings are no longer needed.

  */
  public
  String[] getOptionStrings() {
    return OptionConverter.concatanateArrays(super.getOptionStrings(),
          new String[] {FILE_OPTION, APPEND_OPTION});
  }

  /**
     The Append option takes a boolean value. It is set to
     true by default. If true, then File
     will be opened in append mode by {@link #setFile setFile} (see
     above). Otherwise, {@link #setFile setFile} will open
     File in truncate mode.

Note: Actual opening of the file is made when {@link
     #activateOptions} is called, not when the options are set.
   */
  public
  void setAppend(boolean flag) {
    fileAppend = flag;
  }

  /**
     If the value of {@link #FILE_OPTION} is not null, then {@link
     #setFile} is called with the values of {@link #FILE_OPTION} and
     {@link #APPEND_OPTION}.

     @since 0.8.1 */
  public
  void activateOptions() {
    if(fileName != null) {
      try {
	setFile(fileName, fileAppend);
      }
      catch(java.io.IOException e) {
	errorHandler.error("setFile("+fileName+","+fileAppend+") call failed.",
			   e, ErrorCode.FILE_OPEN_FAILURE);
      }
    } else {
      //LogLog.error("File option not set for appender ["+name+"].");
      LogLog.warn("File option not set for appender ["+name+"].");
      LogLog.warn("Are you using FileAppender instead of ConsoleAppender?");
    }
  }

 /**
     Closes the previously opened file.
  */
  protected
  void closeFile() {
    // FIXME (remove qwIsOurs)
    if(this.qw != null && this.qwIsOurs) {
      try {
	this.qw.close();
      }
      catch(java.io.IOException e) {
	// Exceptionally, it does not make sense to delegate to an
	// ErrorHandler. Since a closed appender is basically dead.
	LogLog.error("Could not close " + qw, e);
      }
    }
  }

  /**

Sets and opens the file where the log output will
    go. The specified file must be writable.

If there was already an opened file, then the previous file
    is closed first.

    @param fileName The path to the log file.
    @param append   If true will append to fileName. Otherwise will
        truncate fileName.  */
  public
  synchronized
  void setFile(String fileName, boolean append) throws IOException {
    reset();
    this.setQWForFiles(new FileWriter(fileName, append));
    //this.tp = new TracerPrintWriter(qw);
    this.fileName = fileName;
    this.fileAppend = append;
    this.qwIsOurs = true;
    writeHeader();
  }

  /**
     @deprecated Use the setter method for the option directly instead
     of the generic setOption method.  */
  public
  void setOption(String key, String value) {
    if(value == null) return;
    super.setOption(key, value);

    if(key.equalsIgnoreCase(FILE_OPTION)) {
      // Trim spaces from both ends. The users probably does not want
      // trailing spaces in file names.
      String val = value.trim();
      if(val.equalsIgnoreCase("System.out")) {
	setWriter(new OutputStreamWriter(System.out));
      } else if(val.equalsIgnoreCase("System.err")) {
	setWriter(new OutputStreamWriter(System.err));
      } else {
	fileName = val;
      }
    }
    else if (key.equalsIgnoreCase(APPEND_OPTION)) {
      fileAppend = OptionConverter.toBoolean(value, fileAppend);
    }
  }

  /**
     Sets the quiet writer being used.

     This method is overriden by {@link RollingFileAppender}.
   */
  protected
  void setQWForFiles(Writer writer) {
     this.qw = new QuietWriter(writer, errorHandler);
  }

  /**
     Close any previously opened file and call the parent's
     reset.  */
  protected
  void reset() {
    closeFile();
    this.fileName = null;
    if(qwIsOurs) {
      super.reset();
    } else {
      this.qw = null;
      //this.tp = null;
    }
  }
}


text:
package net.sf.sitemonitoring.service.check;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import lombok.extern.slf4j.Slf4j;
import net.sf.sitemonitoring.entity.Check;
import net.sf.sitemonitoring.entity.Credentials;
import net.sf.sitemonitoring.event.AbortCheckEvent;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

import com.google.common.eventbus.Subscribe;

@Slf4j
public abstract class AbstractCheckThread extends Thread {

	protected boolean abort = false;

	protected String output;

	protected Check check;

	protected CloseableHttpClient httpClient;

	public AbstractCheckThread(Check check) {
		this.check = check;
		setDaemon(true);
	}

	@Subscribe
	public void abort(AbortCheckEvent abortCheckEvent) throws IOException {
		log.debug("called abort " + abortCheckEvent.getCheckId());
		if (check.getId() == abortCheckEvent.getCheckId()) {
			log.debug("aborted check " + check.getId());
			abort = true;
			httpClient.close();
		}
	}

	public abstract void performCheck();

	protected CloseableHttpClient buildHttpClient() {
		HttpClientBuilder httpClientBuilder = HttpClients.custom();
		CredentialsProvider credsProvider = new BasicCredentialsProvider();

		try {
			Credentials credentials = check.getCredentials();
			if (credentials != null) {
				basicAuthentication(httpClientBuilder, credsProvider, credentials);
			}
		} catch (Exception ex) {
			throw new RuntimeException("Could not use credentials");
		}
		// set proxy
		if (check.getHttpProxyUsername() != null && !check.getHttpProxyPassword().isEmpty()) {
			credsProvider.setCredentials(new AuthScope(check.getHttpProxyServer(), check.getHttpProxyPort()),
					new UsernamePasswordCredentials(check.getHttpProxyUsername(), check.getHttpProxyPassword()));
			httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
		}
		return httpClientBuilder.build();
	}

	private void basicAuthentication(HttpClientBuilder httpClientBuilder, CredentialsProvider credsProvider, Credentials credentials) throws URISyntaxException {
		URI uri = new URI(check.getUrl());
		credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword()));
		httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
	}

	@Override
	public void run() {
		httpClient = buildHttpClient();
		try {
			performCheck();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				log.error("Error closing HTTP client", e);
			}
		}
	}

	public String getOutput() {
		return output;
	}

	protected void appendMessage(String message) {
		if (output == null) {
			output = "";
		}
		if (message != null && !message.trim().isEmpty()) {
			output += message;
		}
	}

	protected void copyConnectionSettings(Check original, Check result) {
		result.setConnectionTimeout(original.getConnectionTimeout());
		result.setSocketTimeout(original.getSocketTimeout());
		result.setUserAgent(original.getUserAgent());
		result.setHttpProxyServer(original.getHttpProxyServer());
		result.setHttpProxyPort(original.getHttpProxyPort());
		result.setHttpProxyUsername(original.getHttpProxyUsername());
		result.setHttpProxyPassword(original.getHttpProxyPassword());
	}

}


text:
layout: page
title: Topics
---
{% assign groupings=site.categories %}
{% assign groupingClass='category' %}
{% comment %}
Include for adding a categorised list.
Requires 3 variables to be set:
- groupings- The hash that contains the grouping items to use. e.g. site.tags
- title - The title for the page
- groupingClass - The css class to use when displaying the grouping list items.
{% endcomment %}
{% capture grouping_items %}{% for grouping in groupings %}{{ grouping | first | downcase }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %}

{% capture num_words %}
  {{ grouping_items | split:',' | size }}
{% endcapture %}

{% assign grouping_words = grouping_items | split:',' | sort %}

{{ title }}

{% for item in (0..num_words) %}{% unless forloop.last %}{% capture this_word %}{{ grouping_words[item] | strip_newlines }}{% endcapture %}{% for grouping in groupings %}{% capture lower_grouping %}{{ grouping | first | downcase }}{% endcapture %}{% capture display_grouping %}{{ grouping | first }}{% endcapture %}{% if this_word == lower_grouping %}

{{ display_grouping }} {{ groupings[display_grouping].size }}

        {% endif %} {% endfor %}{% endunless %}{% endfor %}

{% for item in (0..num_words) %}{% unless forloop.last %}{% capture this_word %}{{ grouping_words[item] | strip_newlines }}{% endcapture %}{% for grouping in groupings %}{% capture lower_grouping %}{{ grouping | first | downcase }}{% endcapture %}{% capture display_grouping %}{{ grouping | first }}{% endcapture %}{% if this_word == lower_grouping %}

{{ display_grouping }}

{% for post in groupings[display_grouping] %}{% if post.title != null %}

                        <time datetime="{{ post.date | date_to_xmlschema }}" itemprop="datePublished">{{ post.date | date: "%d %b, %Y" }}</time>

                        {{ post.title }}

{% endif %}{% endfor %}

{% endif %} {% endfor %}{% endunless %}{% endfor %}