text:
package de.craften.craftenlauncher.gui.panel;

import de.craften.craftenlauncher.exception.CraftenAuthenticationException;
import de.craften.craftenlauncher.exception.CraftenException;
import de.craften.craftenlauncher.exception.CraftenLogicException;
import de.craften.craftenlauncher.gui.MainController;
import de.craften.craftenlauncher.logic.Facade;
import de.craften.craftenlauncher.logic.manager.TranslationManager;
import de.craften.ui.swingmaterial.*;
import de.craften.ui.swingmaterial.toast.TextToast;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

@SuppressWarnings("serial")
public class LoginPanel extends JPanel {
    private static final Logger LOGGER = LogManager.getLogger(LoginPanel.class);
    private MaterialTextField usernameField;
    private MaterialPasswordField passwordField;
    private MaterialButton loginButton;
    private MaterialButton loginFreeButton;

    public LoginPanel() {
        setBackground(Color.WHITE);
        setLayout(null);

        buildUI();
        addHelpLabels();

        try {
            if (Facade.getInstance().getUser() != null && Facade.getInstance().getUser().getEmail() != null) {
                usernameField.setText(Facade.getInstance().getUser().getEmail());
                passwordField.grabFocus();
            }
        } catch (CraftenLogicException e) {
            LOGGER.error(e);
        }
    }

    private void doLogin() {
        try {
            MainController.getInstance().performLogin(usernameField.getText(), passwordField.getPassword());
        } catch (CraftenAuthenticationException e) {
            switch (e.getReason()) {
                case DID_NOT_BUY_MINECRAFT:
                    MainController.getInstance().displayToast(new TextToast(TranslationManager.getString("loginFailedBuyMinecraft")));
                    break;
                case USER_CREDENTIALS_ARE_WRONG:
                    MainController.getInstance().displayToast(new TextToast(TranslationManager.getString("loginFailedCredentials")));
                    break;
                default:
                    MainController.getInstance().displayToast(new TextToast(TranslationManager.getString("loginFailed")));
                    break;
            }
            LOGGER.error("Auth failure", e);
        } catch (CraftenException e) {
            LOGGER.error("Unexpected error while authenticating", e);
        }
    }

    private void doWithoutLogin(){
        MainController.getInstance().performWithoutLogin();
    }

    private void buildUI() {
        usernameField = new MaterialTextField();
        usernameField.setLabel(TranslationManager.getString("emailLabel"));
        usernameField.setHint(TranslationManager.getString("emailHint"));
        usernameField.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    doLogin();
                } else {
                    loginButton.setEnabled(!usernameField.getText().isEmpty() && passwordField.getPassword().length > 0);
                }
            }
        });
        usernameField.setBounds(0, 0, 240, 72);
        usernameField.setLocation(68, -18);
        add(usernameField);

        passwordField = new MaterialPasswordField();
        passwordField.setLabel(TranslationManager.getString("passwordLabel"));
        passwordField.enableInputMethods(true);
        passwordField.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    doLogin();
                } else {
                    loginButton.setEnabled(!usernameField.getText().isEmpty() && passwordField.getPassword().length > 0);
                }
            }
        });
        passwordField.setBounds(0, 0, 240, 64);
        passwordField.setLocation(68, 57);
        add(passwordField);

        loginButton = new MaterialButton();
        loginButton.setBackground(MaterialColor.CYAN_500);
        loginButton.setForeground(Color.WHITE);
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                doLogin();
            }
        });
        loginButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        loginButton.setText(TranslationManager.getString("loginBtn"));
        loginButton.setBounds(0, 0, 240 + MaterialShadow.OFFSET_LEFT + MaterialShadow.OFFSET_RIGHT,
                36 + MaterialShadow.OFFSET_TOP + MaterialShadow.OFFSET_BOTTOM);
        loginButton.setLocation(68 - MaterialShadow.OFFSET_LEFT, 155 - MaterialShadow.OFFSET_TOP);
        loginButton.setEnabled(!usernameField.getText().isEmpty() && passwordField.getPassword().length > 0);
        add(loginButton);

        loginFreeButton = new MaterialButton();
        loginFreeButton.setForeground(MaterialColor.CYAN_500);
        loginFreeButton.setRippleColor(MaterialColor.CYAN_500);
        loginFreeButton.setBackground(MaterialColor.TRANSPARENT);
        loginFreeButton.setType(MaterialButton.Type.FLAT);
        loginFreeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                doWithoutLogin();
            }
        });
        loginFreeButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        loginFreeButton.setText(TranslationManager.getString("loginFreeBtn"));
        loginFreeButton.setBounds(0, 0, 240 + MaterialShadow.OFFSET_LEFT + MaterialShadow.OFFSET_RIGHT,
                36 + MaterialShadow.OFFSET_TOP + MaterialShadow.OFFSET_BOTTOM);
        loginFreeButton.setLocation(68 - MaterialShadow.OFFSET_LEFT, 199 - MaterialShadow.OFFSET_TOP);
        add(loginFreeButton);
    }

    private void addHelpLabels() {
        final JLabel forgotPasswordLink = new JLabel(TranslationManager.getString("forgotPassword"));
        forgotPasswordLink.setFont(Roboto.REGULAR.deriveFont(12f));
        forgotPasswordLink.setForeground(MaterialColor.MIN_BLACK);
        forgotPasswordLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        forgotPasswordLink.setHorizontalAlignment(JLabel.RIGHT);
        forgotPasswordLink.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent env) {
                openLink("https://help.mojang.com/customer/portal/articles/329524-change-or-forgot-password");
            }

            @Override
            public void mouseEntered(MouseEvent mouseEvent) {
                forgotPasswordLink.setForeground(MaterialColor.CYAN_500);
            }

            @Override
            public void mouseExited(MouseEvent mouseEvent) {
                forgotPasswordLink.setForeground(MaterialColor.MIN_BLACK);
            }
        });
        forgotPasswordLink.setLocation(68, passwordField.getY() + passwordField.getHeight());
        forgotPasswordLink.setSize(240, 15);
        add(forgotPasswordLink);
        setComponentZOrder(forgotPasswordLink, 0);
    }

    private static void openLink(String url) {
        try {
            Desktop.getDesktop().browse(new URI(url));
        } catch (IOException | URISyntaxException e) {
            LOGGER.warn("Could not open link", e);
        }
    }
}


text:
package org.csap.agent ;

import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder ;

import java.io.File ;
import java.io.IOException ;
import java.io.OutputStream ;
import java.lang.management.ManagementFactory ;
import java.lang.management.MemoryMXBean ;
import java.lang.management.OperatingSystemMXBean ;
import java.net.InetAddress ;
import java.net.NetworkInterface ;
import java.net.URI ;
import java.nio.ByteBuffer ;
import java.nio.charset.Charset ;
import java.nio.file.Files ;
import java.nio.file.Path ;
import java.nio.file.Paths ;
import java.nio.file.StandardCopyOption ;
import java.text.DecimalFormat ;
import java.time.Duration ;
import java.time.LocalDate ;
import java.time.LocalDateTime ;
import java.time.OffsetDateTime ;
import java.time.ZoneId ;
import java.time.format.DateTimeFormatter ;
import java.util.ArrayList ;
import java.util.Arrays ;
import java.util.Collections ;
import java.util.List ;
import java.util.Spliterator ;
import java.util.Spliterators ;
import java.util.concurrent.TimeUnit ;
import java.util.regex.Matcher ;
import java.util.regex.Pattern ;
import java.util.stream.Collectors ;
import java.util.stream.LongStream ;
import java.util.stream.Stream ;
import java.util.stream.StreamSupport ;

import org.apache.commons.io.FileUtils ;
import org.apache.commons.io.FilenameUtils ;
import org.csap.agent.model.ProjectLoader ;
import org.csap.agent.project.loader.Rest_Service_Tests ;
import org.csap.helpers.CSAP ;
import org.csap.helpers.CsapApplication ;
import org.csap.helpers.CsapRestTemplateFactory ;
import org.ehcache.Cache ;
import org.ehcache.CacheManager ;
import org.ehcache.config.CacheConfiguration ;
import org.ehcache.config.builders.CacheConfigurationBuilder ;
import org.ehcache.config.builders.ExpiryPolicyBuilder ;
import org.ehcache.config.builders.ResourcePoolsBuilder ;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor ;
import org.junit.jupiter.api.Disabled ;
import org.junit.jupiter.api.Test ;
import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;
import org.springframework.core.io.DefaultResourceLoader ;
import org.springframework.http.HttpEntity ;
import org.springframework.http.HttpHeaders ;
import org.springframework.http.HttpMethod ;
import org.springframework.http.HttpStatus ;
import org.springframework.http.MediaType ;
import org.springframework.http.ResponseEntity ;
import org.springframework.http.converter.FormHttpMessageConverter ;
import org.springframework.util.LinkedMultiValueMap ;
import org.springframework.util.MultiValueMap ;
import org.springframework.web.client.RestTemplate ;

import com.fasterxml.jackson.core.SerializableString ;
import com.fasterxml.jackson.core.io.CharacterEscapes ;
import com.fasterxml.jackson.core.type.TypeReference ;
import com.fasterxml.jackson.databind.ObjectMapper ;
import com.fasterxml.jackson.databind.node.ArrayNode ;
import com.fasterxml.jackson.databind.node.MissingNode ;
import com.fasterxml.jackson.databind.node.ObjectNode ;

import io.micrometer.core.instrument.Counter ;
import io.micrometer.core.instrument.Metrics ;
import io.micrometer.core.instrument.Timer ;
import io.micrometer.core.instrument.distribution.HistogramSnapshot ;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry ;

/**
 *
 * Simple tests to validate specific configuration of Spring LDAP Template.
 *
 * Similar to sql - LDAP has a DSL for interacting with provider, which in turn
 * is abstracted somewhat by Java nameing apis. Spring Ldap makes this much more
 * developer friendly.
 *
 * Prior to jumping to code, it is highly recommended to make use of a desktop
 * LDAP browser to browse LDAP tree to familiarize your self with syntax and
 * available attributes.
 *
 * Softerra ldap browser is nice way to approach
 *
 *
 * @author someDeveloper
 *
 *
 * @see <a href=
 *      "http://docs.spring.io/spring-ldap/docs/1.3.2.RELEASE/reference/htmlsingle/#introduction-overview">
 *      Spring LDAP lookup </a>
 *
 */

// TO RUN - update UID and password
//@Disabled
public class NonCsapTests {

	final static private Logger logger = LoggerFactory.getLogger( NonCsapTests.class ) ;

	static {

		CsapApplication.initialize( "Test Setup Complete" ) ;

	}

	ObjectMapper jsonMapper = new ObjectMapper( ) ;

	@Disabled
	@Test
	void writeResource ( ) throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		// var cp = new ClassPathResource("/info.png" ) ;
		var resourceLoader = new DefaultResourceLoader( ) ;
		var cp = resourceLoader.getResource( "/info.png" ) ;

		var src = cp.getInputStream( ) ;

//		try ( var reader = new BufferedReader(
//				new InputStreamReader( resource ) ) ) {
//
//
//			String springContent = reader.lines( )
//					.collect( Collectors.joining( "\n" ) ) ;
//
//
//			logger.info( "springContent: {}", springContent ) ;
//
//		}

		// InputStream src = c.getResourceAsStream(res);
		Files.copy( src, Paths.get( "/dev/peter.png" ), StandardCopyOption.REPLACE_EXISTING ) ;

		// logger.info( "MissingNode.getInstance int value: {}", misValue );

	}

	@Test
	void missingNodeToInt ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		int misValue = MissingNode.getInstance( ).asInt( ) ;

		logger.info( "MissingNode.getInstance int value: {}", misValue ) ;

	}

	@Test
	void java_regex_keyword_value ( ) throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		var jobYamlFile = new File(
				Rest_Service_Tests.class.getResource(
						"create-rni-job.yaml" )
						.getPath( ) ) ;
		var jobYamlContent = FileUtils.readFileToString( jobYamlFile ) ;

		// https://www.oreilly.com/library/view/java-cookbook-3rd/9781449338794/ch04.html#javacook-regex-SECT-10
		// non whitespace characters
//		var yamlPattern= Pattern.compile( "(?<=(command|name): )(\\S+)" ) ;
		var yamlPattern = Pattern.compile( "(?<=(command|name): )(.*)" ) ;

		var matches = new ArrayList<String>( ) ;
		Matcher yamlKeywordMatcher = yamlPattern.matcher( jobYamlContent ) ;

		while ( yamlKeywordMatcher.find( ) ) {

			matches.add( CSAP.padNoLine( yamlKeywordMatcher.group( 1 ) ) + yamlKeywordMatcher.group( 2 ) ) ;

		}

		var matchesDesc = matches.stream( )
				.collect( Collectors.joining( "\n" ) ) ;

		logger.info( "matches: \n{}", matchesDesc ) ;

	}

	@Test
	void listHashes ( ) {

		var empty = List.of( ) ;

		var apples = List.of( "a" ) ;

		var ab = List.of( "ab" ) ;

		var a_b = List.of( "a", "b" ) ;

		var z = List.of( "z" ) ;

		logger.info( CSAP.buildDescription(
				"hashes",
				empty, empty.hashCode( ),
				ab, ab.hashCode( ),
				a_b, a_b.hashCode( ),
				apples, apples.hashCode( ),
				z, z.hashCode( ) ) ) ;

	}

	@Test
	void offsetTimes ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		var gmtTime = OffsetDateTime.now( ZoneId.of( "Z" ) ) ;

		var localTime = gmtTime.toZonedDateTime( ).withZoneSameInstant( ZoneId.systemDefault( ) ) ;

		logger.info( "nowOffset: {},\n local: {},\n formatted: {}", gmtTime,
				localTime,
				localTime.format( DateTimeFormatter.ofPattern( "MM/dd/yyyy - HH:mm:ss z" ) ) ) ;

	}

	@Test
	void valueSet ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		var source = jsonMapper.createObjectNode( ) ;
		source.put( "hi", "there" ) ;

		var dest = jsonMapper.createObjectNode( ) ;
		dest.set( "hey", source.path( "hi" ) ) ;

		logger.info( "source: {}, dest: {}", source, dest ) ;

	}

	@Test
	void pathTest ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		var myPath = Paths.get( "/some/linux/path" ) ;

		logger.info( "source: {}, dest: {}", myPath, FilenameUtils.separatorsToUnix( myPath.getParent( )
				.toString( ) ) ) ;

	}

	@Test
	void filePath ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		var currentFolder = new File( "." ) ;

		var winpath = new File( "C:\\Users\\peter.nightingale" ) ;

		logger.info( CSAP.buildDescription(
				"Conversions",
				"winpath", winpath,
				"exists", winpath.exists( ),
				"currentFolder", currentFolder,
				".getAbsolutePath( )", currentFolder.getAbsolutePath( ),
				".toURI( )", currentFolder.toURI( ),
				".toURI().getPath()", currentFolder.toURI( ).getPath( ) ) ) ;

		var convertedBackString = new URI( currentFolder.toURI( ).toString( ) ) ;
		var convertedBackFolder = new File( convertedBackString ) ;

		logger.info( CSAP.buildDescription(
				"convertedBackString",
				"convertedBackString", convertedBackString,
				".getAbsolutePath( )", convertedBackFolder.getAbsolutePath( ) ) ) ;

	}

	@Test
	void streamTest ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		var testObject = jsonMapper.createObjectNode( ) ;
		var hiPath = testObject.remove( "hi" ) ;

		CSAP.asStreamHandleNulls( hiPath ).forEach( item -> {

			logger.info( "got: '{}'", item ) ;

		} ) ;

	}

	@Test
	void timeCheck ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		LocalDateTime now = LocalDateTime.now( ) ;

		LocalDateTime anotherTime = LocalDateTime.now( ).minusSeconds( 10 ) ;

		logger.info( "now: '{}' oneSecondPast: {} , difference: {}",
				now,
				anotherTime,
				Duration.between( anotherTime, now ).getSeconds( ) ) ;

	}

	@Test
	void jsonPath ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		var testObject = jsonMapper.createObjectNode( ) ;
		var hiPath = testObject.path( "hi" ) ;
		var hiTherePath = testObject.path( ProjectLoader.SERVICE_TEMPLATES ) ;

		logger.info( "hiPath: '{}' \t\t hiTherePath: '{}'", hiPath.getClass( ), hiTherePath.getClass( ) ) ;

	}

	@Test
	void millisCheck ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		var millisInAMinute = TimeUnit.MINUTES.toMillis( 2 ) ;
		logger.info( "Millis in a 2 minute: {} current millis: {}", millisInAMinute, System.currentTimeMillis( ) ) ;

	}

	@Test
	void processHandle ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		var processListing = ProcessHandle.allProcesses( )
				.map( process -> {

					var info = process.info( ) ;

					var args = info.arguments( ).orElse( new String[] {} ) ;

					return CSAP.pad( "" + process.pid( ) )
							+ CSAP.pad( "" + info.totalCpuDuration( ).orElse( Duration.ofMillis( 0 ) ).toMinutes( ) )
							+ CSAP.pad( info.command( ).orElse( "-" ) )
							+ Arrays.asList( args ) ;

				} )
				.collect( Collectors.joining( "\n" ) ) ;

		logger.info( CsapApplication.header( "\n" + processListing ) ) ;

		// ProcessHandle.allProcesses().filter(p - >
		// p.info().command().isPresent()).limit(4).forEach((process) - > {
		//
		// System.out.println("Process id : " + process.pid());
		//
		// ProcessHandle.Info info = process.info();
		//
		// System.out.println("Command: " + info.command().orElse(""));
		//
		// String[] arguments = info.arguments().orElse(new String[] {});
		//
		// System.out.println("Arguments:");
		//
		// for (String arg: arguments)
		//
		// System.out.println(" arguement :" + arg);
		//
		// System.out.println("Command line: " + info.commandLine().orElse(""));
		//
		// System.out.println("Start time: " +
		// info.startInstant().orElse(Instant.now()).toString());
		//
		// System.out.println("Run time duration: " +
		// info.totalCpuDuration().orElse(Duration.ofMillis(0)).toMillis());
		//
		// System.out.println("User :" + info.user().orElse(""));
		//
		// System.out.println("===================");
		//
		// });
	}

	@Test
	public void verify_ehcache_pojo ( )
		throws InterruptedException {

		logger.info( CsapApplication.testHeader( ) ) ;

		CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder
				.newCacheConfigurationBuilder( Long.class, String.class,
						ResourcePoolsBuilder.heap( 3 ) )
				.withExpiry( ExpiryPolicyBuilder.timeToLiveExpiration( Duration.ofSeconds( 2 ) ) )
				.build( ) ;

		try ( CacheManager cacheManager = newCacheManagerBuilder( )
				.withCache( "basicCache",
						cacheConfiguration )
				.build( true ) ) {

			Cache<Long, String> basicCache = cacheManager.getCache( "basicCache", Long.class, String.class ) ;

			logger.info( "Putting to cache" ) ;
			basicCache.put( 1L, "da one!" ) ;
			basicCache.put( 2L, "da 2!" ) ;
			basicCache.put( 3L, "da 3!" ) ;
			basicCache.put( 4L, "da 4!" ) ;

			var val1 = basicCache.get( 1L ) ;
			logger.info( "Retrieved '{}'", val1 ) ;

			var val2 = basicCache.get( 2L ) ;
			logger.info( "Retrieved '{}'", val2 ) ;

			TimeUnit.SECONDS.sleep( 3 ) ;
			val2 = basicCache.get( 2L ) ;
			logger.info( "Retrieved '{}'", val2 ) ;
			logger.info( "Closing cache manager" ) ;

		}

	}

	@Test
	public void jasypt_encode_example ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor( ) ;
		encryptor.setAlgorithm( "PBEWITHMD5ANDTRIPLEDES" ) ;
		encryptor.setPassword( "willBeOverwritten" ) ;

		var testVal = encryptor.decrypt( "k16ljSCT5UnF8o1fCyshcD3+VZtrWm2c" ) ;

		logger.info( "Decoded: {}", testVal ) ;

	}

	@Test
	public void simpleReplace ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		var string = "peter $was+1 here" ;

		logger.info( "original: {}, replaced: {}",
				string,
				string.replaceAll( Pattern.quote( "$was+1" ), "is" ) ) ;

		var test = ".csap.com" ;

		logger.info( "found * : '{}'", test.contains( "*" ) ) ;

	}

	@Test
	public void verifyStreamObject ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		var s = jsonMapper.createObjectNode( ) ;

		s.put( "a", "1" ) ;
		s.put( "b", "2" ) ;

		CSAP.jsonStream( s ).forEach( System.out::println ) ;
		;

	}

	@Test
	public void verifyArrayAdd ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		List<String> list = new ArrayList<String>( Arrays.asList( "item 1", "item 2" ) ) ;

		list.remove( "item 1" ) ;
		list.add( "peter" ) ;

		logger.info( "list: {}", list ) ;

	}

	//

	@Test
	public void microMeterCounter ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		Metrics.addRegistry( new SimpleMeterRegistry( ) ) ;
		Metrics.counter( "junit-counter" ).increment( ) ;

		Counter testCounter = Metrics.globalRegistry.find( "junit-counter" ).counter( ) ;

		logger.info( "testCounter: {}", testCounter.count( ) ) ;

	}

	@Test
	public void microMeterTimer ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		Metrics.addRegistry( new SimpleMeterRegistry( ) ) ;
		Timer testTimer = Metrics.timer( "junit-timer" ) ;

		testTimer.record( ( ) -> {

			try {

				TimeUnit.MILLISECONDS.sleep( 55 ) ;

			} catch ( InterruptedException ignored ) {

			}

		} ) ;

		Timer searchTimer = Metrics.globalRegistry.find( "junit-timer" ).timer( ) ;

		HistogramSnapshot snap = searchTimer.takeSnapshot( ) ;

		logger.info( "testCounter: {} ms,   {} seconds, snap: {} ms",
				searchTimer.mean( TimeUnit.MILLISECONDS ),
				searchTimer.mean( TimeUnit.SECONDS ),
				snap.mean( TimeUnit.MILLISECONDS ) ) ;

	}

	@Test
	public void verifyDiskParsing ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		String disk = "7942M" ;

		logger.info( "disk: {}, parsed: {}", disk, Integer.parseInt( disk.replaceAll( "[\\D]", "" ) ) ) ;

		double memUsed = 1.21790464E8 ;
		logger.info( "memUsed: {}, in mb: {}", memUsed, memUsed / CSAP.MB_FROM_BYTES ) ;

		double cpu = 5.771106343341624E-1 ;
		logger.info( "cpu: {}, in cpu rounded: {}", cpu, Math.round( cpu * 100 ) ) ;

	}

	@Test
	public void endsWith ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		String name = "perter.gz" ;

		logger.info( "name: '{}', endsWith .gz{}", name, name.endsWith( ".gz" ) ) ;

	}

	@Test
	public void json_default ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		ObjectNode testObject = jsonMapper.createObjectNode( ) ;

		int testInt = testObject.path( "doesNotExist" ).asInt( -1 ) ;

		logger.info( "testInt: {}, parsed: {}", testInt, Math.round( Double.parseDouble( "03.5" ) ) ) ;

		logger.info( "list: {}", Arrays.asList( " a    b c d ".trim( ).split( "\\s+ ", 9 ) ) ) ; // 8th field is the
																									// args

		testObject.put( "testDouble", 1 ) ;
		logger.info( "testDouble: {}", testObject.path( "testDouble" ).asDouble( -0.01 ) ) ;

	}

	@Test
	public void verifyJsonClone ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		ArrayNode testArray = jsonMapper.createArrayNode( ) ;

		testArray.add( "a" ) ;
		testArray.add( "b" ) ;
		testArray.add( "c" ) ;

		ArrayNode cloneArray = testArray.deepCopy( ) ;

		cloneArray.remove( 1 ) ;

		logger.info( "testArray: {}, cloneArray{}", testArray, cloneArray ) ;

		// logger.info( "Missing item: {}",
		// jacksonMapper.createObjectNode().get( "missing" ).asText("") );
	}

	@Test
	public void linuxFile ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		File f = new File( System.getProperty( "user.dir" ) ) ;
		logger.info( "file: {}, {}", f.getPath( ) ) ;

	}

	@Test
	public void verifyJsonFileName ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		ObjectNode fileNode = jsonMapper.createObjectNode( ) ;

		Files.newDirectoryStream(

				Paths.get(
						System.getProperty( "user.dir" ) + "/src/main/resources" ),

				path -> path.toString( )
						.endsWith( ".yml" ) )

				.forEach( path -> {

					logger.info( "path: {}", path ) ;
					String content ;

					try {

						content = new String(
								Files.readAllBytes( path ),
								Charset.forName( "UTF-8" ) ) ;
						fileNode.put( path.toFile( ).getName( ), content ) ;

					} catch ( IOException e ) {

						// TODO Auto-generated catch block
						e.printStackTrace( ) ;

					}

				} ) ;

		logger.info( "fileNode: {}", CsapConstants.jsonPrint( jsonMapper, fileNode ) ) ;

		// logger.info( "Missing item: {}",
		// jacksonMapper.createObjectNode().get( "missing" ).asText("") );
	}

	// @Test
	// public void verify_metric_parsing ()
	// throws Exception {
	//
	// RestTemplate restTemplate = new RestTemplate();
	//
	// String url =
	// "http://csap-dev04:8014/api/v1/namespaces/default/services/csap-test-k8s-service-6090-service/proxy/csap-test-k8s-service/csap/metrics/micrometers"
	// ;
	//
	// ObjectNode apiResponse = restTemplate.getForObject( url, ObjectNode.class ) ;
	//
	// logger.info( "url: {} \n\t response: {}", url, CSAP.jsonPrint( apiResponse ))
	// ;
	//
	// String path="/http.server.requests[~1**~1*.css]/COUNT" ;
	// logger.info( "path: {} \n\t value: {}", path, apiResponse.at( path
	// ).toString()) ;
	//
	//
	// }

	// @Test
	public void verify_pod_status ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		RestTemplate restTemplate = new RestTemplate( ) ;

		String url = "http://saasrni-csap01.lab.sensus.net:8011/CsAgent/api/agent/kubernetes/pods?namespace=all" ;

		ArrayNode status_of_all_pods = restTemplate.getForObject( url, ArrayNode.class ) ;

		logger.debug( "url: {} \n\t response: {}", url, CSAP.jsonPrint( status_of_all_pods ) ) ;

		String status_text = CSAP.jsonStream( status_of_all_pods )

				.map( pod_status -> {

					var name = pod_status.at( "/metadata/name" ).asText( "name-not-found" ) ;
					var statusNode = pod_status.at( "/status/containerStatuses/0/state" ) ;
					var status = "not-found" ;

					if ( ! statusNode.isMissingNode( ) ) {

						status = statusNode.toString( ) ;

					}

					return "Name: " + name + " 1st container: " + status ;

				} )

				.collect( Collectors.joining( "\n\t" ) ) ;

		logger.info( "Results from {} {}", url, status_text ) ;

	}

	public static String NAMESPACE_YAML = "apiVersion: v1\n" +
			"kind: Namespace\n" +
			"metadata:\n" +
			"  name: demo-dummy-namespace\n" +
			"  labels:\n" +
			"    name: test" ;

	@Disabled
	@Test
	public void verify_kubernetes_post ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		RestTemplate restTemplate = new RestTemplate( ) ;

		String url = "http://csap-dev04.lab.sensus.net:8011/api/agent/kubernetes/specification" ;
		// url =
		// "http://saasrni-csap01.lab.sensus.net:8011/CsAgent/api/agent/kubernetes/specification"
		// ;
		// url =
		// "http://localhost.lab.sensus.net:8011/CsAgent/api/agent/kubernetes/specification"
		// ;

		//
		// Create Namespace
		//

		MultiValueMap<String, String> urlVariables = new LinkedMultiValueMap<String, String>( ) ;
		urlVariables.add( "userid", "csap-unit-test" ) ;
		urlVariables.add( "pass", "RqayZbbIpHdVVkdkbpsY3gu8t1ozIN/+cAfW3lAGaKk=" ) ;
		urlVariables.add( "yaml", NAMESPACE_YAML ) ;

		ResponseEntity<ObjectNode> postResponse = restTemplate.postForEntity( url, urlVariables,
				ObjectNode.class ) ;

		logger.info( "postResponse: {}", postResponse ) ;

		logger.info( "Passed: {}          post url: {} \n\t create response: {}",
				postResponse.getStatusCode( ).equals( HttpStatus.OK ),
				url,
				postResponse.getBody( ).at( "/response-sh" ).asText( "no-response-found" ) ) ;

		//
		// Common configuration for restTemplate PUT and DELETE support
		//

		HttpHeaders headers = new HttpHeaders( ) ;
		headers.setContentType( MediaType.APPLICATION_FORM_URLENCODED ) ;
		restTemplate.getMessageConverters( ).add( new FormHttpMessageConverter( ) ) ;

		//
		// Update Namespace
		//
		// urlVariables.replace( "pass", List.of( "broken password") ) ;

		HttpEntity<MultiValueMap<String, String>> putRequestSettings = new HttpEntity<>( urlVariables, headers ) ;

		ResponseEntity<ObjectNode> putResponse = //
				restTemplate.exchange( url, HttpMethod.PUT, putRequestSettings, ObjectNode.class ) ;

		logger.info( "Passed: {}          put url: {} \n\t update response: {}",
				putResponse.getStatusCode( ).equals( HttpStatus.OK ),
				url,
				putResponse.getBody( ).at( "/response-sh" ).asText( "no-response-found" ) ) ;

		//
		// Delete Namespace
		//

		HttpEntity<MultiValueMap<String, String>> deleteRequestSettings = new HttpEntity<>( urlVariables, headers ) ;
		ResponseEntity<ObjectNode> deleteResponse = //
				restTemplate.exchange( url, HttpMethod.DELETE, deleteRequestSettings, ObjectNode.class ) ;

		logger.info( "Passed: {}          delete url: {} \n\t delete response: {}",
				deleteResponse.getStatusCode( ).equals( HttpStatus.OK ),
				url,
				deleteResponse.getBody( ).at( "/response-sh" ).asText( "no-response-found" ) ) ;

	}

	@Disabled
	@Test
	public void verifyInsecureRest ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		CsapRestTemplateFactory factory = new CsapRestTemplateFactory( null, null ) ;

		RestTemplate sslTestTemplate = factory.buildDefaultTemplate( "junit", false, 10, 10, 5, 60, 300 ) ;

		String sslUrl = "https://csap-secure.yourcompany.com/admin/api/application/health" ;

		String sslResponse = sslTestTemplate.getForObject( sslUrl, String.class ) ;

		logger.info( "url: {} \n\t response: {}", sslUrl, sslResponse ) ;

		// RestTemplate restTemplate = factory.buildDefaultTemplate( "junit",
		// false, 10, 10, 5, 60, 300 );
		//
		// String url =
		// "http://testhost.yourcompany.com:8011/CsAgent/api/agent/health" ;
		// String response = restTemplate.getForObject( url , String.class ) ;
		//
		// logger.info( "url: {} \n\t response: {}", url,response );

		// RestTemplate sslErrorsIgnoreTemplate = new RestTemplate(
		// factory.buildFactoryDisabledSslChecks( "junit", 10, 10 )) ;
		// url = "https://10.127.41.116:8011/CsAgent/api/agent/health" ;
		// response = sslErrorsIgnoreTemplate.getForObject( url , String.class )
		// ;
		//
		// logger.info( "url: {} \n\t response: {}", url,response );

	}

	@Test
	public void nio_filesystem_traversal ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		try (
				Stream<Path> filesystemPaths = Files.list( new File( "/" ).toPath( ) ) ) {

			var folderListing = filesystemPaths
					.map( Path::getFileName )
					.map( Path::toString )
					.collect( Collectors.joining( "\n\t" ) ) ;

			logger.info( "folderListing: {}", folderListing ) ;

		} catch ( Exception e ) {

			logger.info( "failed getting listing: {}", CSAP.buildCsapStack( e ) ) ;

		}

		try (
				Stream<Path> filesystemPaths = Files.list( new File( "/" ).toPath( ) ) ) {

			var folderListing = filesystemPaths
					.map( Path::getFileName )
					.map( Path::toString )
					.sorted( )
					.collect( Collectors.joining( "\n\t" ) ) ;

			logger.info( "folderListing sorted: {}", folderListing ) ;

		} catch ( Exception e ) {

			logger.info( "failed getting listing: {}", CSAP.buildCsapStack( e ) ) ;

		}

		// try (
		// Stream<Path> filesystemPaths = Files.list( new File( "/" ).toPath() )) {
		//
		// var folderListing = filesystemPaths
		// .filter( Files::isRegularFile )
		// .map( Path::getFileName )
		// .map( Path::toString )
		// .collect( Collectors.joining( "\n\t" ) ) ;
		//
		// logger.info( "regular files: {}", folderListing ) ;
		//
		// } catch ( Exception e) {
		// logger.info( "failed getting listing: {}", CSAP.buildCsapStack( e ) );
		// }
		//
		// try (
		// Stream<Path> filesystemPaths = Files.list( new File( "/ss" ).toPath() )) {
		//
		// var folderListing = filesystemPaths
		// .filter( Files::isRegularFile )
		// .filter( path -> path.getFileName().toString().endsWith( ".zip" ) )
		// .map( Path::getFileName )
		// .map( Path::toString )
		// .collect( Collectors.joining( "\n\t" ) ) ;
		//
		// logger.info( "regular files ending in txt:\n {}", folderListing ) ;
		//
		// } catch ( Exception e) {
		// logger.info( "failed getting listing: {}", CSAP.buildCsapStack( e ) );
		// }

	}

	Double byteToMb = 1024 * 1024D ;
	DecimalFormat gbFormat = new DecimalFormat( "#.#Gb" ) ;

	String getMb ( long num ) {

		logger.info( "num: {}", num ) ;
		return gbFormat.format( num / byteToMb ) ;

	}

	DecimalFormat percentFormat = new DecimalFormat( "#.#%" ) ;

	String getPercent ( double num ) {

		logger.info( "num: {}", num ) ;
		return percentFormat.format( num ) ;

	}

	@Test
	public void verifyGB ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		OperatingSystemMXBean s = ManagementFactory.getOperatingSystemMXBean( ) ;
		var osStats = (com.sun.management.OperatingSystemMXBean) s ;

		logger.info( "com.sun.management.OperatingSystemMXBean memory: {} , sys: {}, process: {}",
				getMb( osStats.getTotalPhysicalMemorySize( ) ),
				getPercent( osStats.getSystemCpuLoad( ) ),
				getPercent( osStats.getProcessCpuLoad( ) ) ) ;

		MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean( ) ;
		logger.info( "memoryMXBean heap committed: {} , heap used: {}, non-heap commited: {}",
				getMb( memoryMXBean.getHeapMemoryUsage( ).getCommitted( ) ),
				getMb( memoryMXBean.getHeapMemoryUsage( ).getUsed( ) ),
				getMb( memoryMXBean.getNonHeapMemoryUsage( ).getCommitted( ) ) ) ;

	}

	@Test
	public void verifyDoubleParse ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		ObjectNode test = jsonMapper.createObjectNode( ) ;
		ObjectNode nested = test.putObject( "test" ) ;

		nested.put( "$numberLong", "17" ) ;

		logger.info( "object: {} : value: {}", test.toString( ), test.asDouble( ) ) ;

		double d = 5500 / 1000d ;

		logger.info( "d: {} ", d ) ;

	}

	@Test
	public void verifyJsonParsing ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		ObjectNode test = jsonMapper.createObjectNode( ) ;
		test.put( "hi-there", "from me" ) ;

		logger.info( "object: {} : value: {}", test.toString( ), test.at( "/hi-there" ).asText( ) ) ;

	}

	@Test
	public void verifyStringRegex ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		String params = "serviceName=[ServletSample_8091], javaOpts=[-DcsapJava8 -Xms128M -Xmx128M ], runtime=[tomcat8.x], scmUserid=[someDeveloper],"
				+ " scmPass=[ws0zIy4CVuhWgkjKwebi0/y69yQMiJTr], scmBranch=[trunk], hotDeploy=[null], targetScpHosts=[], scmCommand=[-X -Dmaven.test.skip=true clean package, "
				+ "-X -Dmaven.test.skip=true clean package], mavenDeployArtifact=[null]" ;

		logger.info( "params: \n{}\n\n{}", params, params.replaceAll( "\\bscmPass[^\\s]*", "scmPass[*MASKED*]," ) ) ;

		logger.info( "alphanumeric only: \n{}\n\n{}", params, params.replaceAll( "[^A-Za-z0-9]", "_" ) ) ;

	}

	@Test
	public void lifeReplace ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		String params = "JAVA_OPTS=$life -Djava.rmi.server.hostname=localhost -Dcom.sun.management.jmxremote.port=8046 -Dcom.sun.management.jmxremote.rmi.port=8046 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false  -DcsapProcessId=ServletSample_8041  -Djava.security.egd=file:/dev/./urandom -DcsapDockerJava" ;

		logger.info( "params: \n{}\n\n{}\n{}", params,
				params.replaceAll( Matcher.quoteReplacement( "$life" ), Matcher.quoteReplacement( "$peter" ) ) ) ;

		// String result = params.trim().replaceAll( "\\" +
		// CSAP.SERVICE_PARAMETERS, "-D test.life=$dev".replaceAll( "$", "\\$" )
		// );
		//
		// logger.info( "CSAP.SERVICE_PARAMETERS: {}", result);

	}

	@Test
	public void simpleJson ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		ObjectMapper jsonMapper = new ObjectMapper( ) ;

		ObjectNode full = jsonMapper.createObjectNode( ) ;

		ArrayNode hostsDef = full.putArray( "hosts" ) ;
		hostsDef.add( "csap-dev01" ) ;
		hostsDef.add( "csap-dev02" ) ;

		List<String> hosts = jsonMapper.readValue( full.path( "hosts" ).traverse( ),
				new TypeReference<List<String>>( ) {
				} ) ;

		logger.info( "hosts: {}", hosts ) ;

	}

	@Test
	public void verifyStringExtract ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		String descLine = "users:((\"nginx\",pid=17497,fd=39),(\"nginx\",pid=17493,fd=39)," ;
		var users = descLine.split( "\"", 3 ) ;

		if ( users.length == 3 ) {

			descLine = users[1] ;

		}

		logger.info( "descLine: {}", descLine ) ;
		var testSplit = "::1:6443" ;// "::ffff:127.0.0.1:7016" ; //kube-apiserver: ::1:6443,::1:9885

		logger.info( "testSplit: size: {} , {}", testSplit.split( ":" ).length, Arrays.asList( testSplit.split(
				":" ) ) ) ;

	}

	@Test
	public void verifyMatches ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		String prod = "prod" ;

		logger.info( "Matched: {}", prod.matches( "prod" ) ) ;
		logger.info( "Matched: {}", prod.matches( "p(?!rod)" ) ) ;

		String dev = "dev" ;

		logger.info( "Matched: {}", dev.matches( "p(?!rod)" ) ) ;
		logger.info( "Matched: {}", dev.matches( "p(?!rod)" ) ) ;
		logger.info( "^d.* Matched: {}", dev.matches( "^sd.*" ) ) ;

		String buildResponse = "peter \nDiffEntry[MODIFY Services/testFileForGitJunits.txt]" ;

		Pattern searchWithNewLinesPattern = Pattern.compile(
				".*" + Pattern.quote( "DiffEntry[MODIFY" ) + ".*testFileForGitJunits.txt.*", Pattern.DOTALL ) ;

		logger.info( "buildResponse: {} contains",
				searchWithNewLinesPattern.matcher( buildResponse ).find( ) ) ;
		// buildResponse.matches(
		// ".*" + Pattern.quote( "DiffEntry[MODIFY" ) +
		// ".*testFileForGitJunits.txt.*") );

		var orMatch = "(calico-etcd|csap-test-k8s-service-container|nginx-container|heapster|grafana)" ;
		var source = "csap-test-k8s-service-container" ;
		logger.info( "source {} pattern:{} matches: {}", source, orMatch, source.matches( orMatch ) ) ;

		// logger.info( "source {} pattern:{} matches: {}", "peter", "peter123",
		// "peter".matches( "peter123") ) ;
	}

	public class SlashEscapes extends CharacterEscapes {

		/**
		 *
		 */
		private static final long serialVersionUID = 1L ;
		private final int[] asciiEscapes ;

		public SlashEscapes ( ) {

			// start with set of characters known to require escaping
			// (double-quote, backslash etc)
			int[] esc = CharacterEscapes.standardAsciiEscapesForJSON( ) ;
			// esc['/'] = CharacterEscapes.ESCAPE_STANDARD ;
			esc['/'] = CharacterEscapes.ESCAPE_CUSTOM ;
			asciiEscapes = esc ;

		}

		// this method gets called for character codes 0 - 127
		@Override
		public int[] getEscapeCodesForAscii ( ) {

			return asciiEscapes ;

		}

		// and this for others; we don't need anything special here
		@Override
		public SerializableString getEscapeSequence ( int i ) {

			if ( i == '/' ) {

				return new SerializableString( ) {

					@Override
					public String getValue ( ) {

						return "\\/" ;

					}

					@Override
					public int charLength ( ) {

						return 2 ;

					}

					@Override
					public char[] asQuotedChars ( ) {

						return new char[] {
								'\\', '/'
						} ;

					}

					@Override
					public byte[] asUnquotedUTF8 ( ) {

						return new byte[] {
								'\\', '/'
						} ;

					}

					@Override
					public byte[] asQuotedUTF8 ( ) {

						return new byte[] {
								'\\', '/'
						} ;

					}

					@Override
					public int writeUnquotedUTF8 ( OutputStream out )
						throws IOException {

						return 0 ;

					}

					@Override
					public int writeQuotedUTF8 ( OutputStream out )
						throws IOException {

						return 0 ;

					}

					@Override
					public int putUnquotedUTF8 ( ByteBuffer out )
						throws IOException {

						return 0 ;

					}

					@Override
					public int putQuotedUTF8 ( ByteBuffer buffer )
						throws IOException {

						return 0 ;

					}

					@Override
					public int appendUnquotedUTF8 ( byte[] buffer , int offset ) {

						return 0 ;

					}

					@Override
					public int appendUnquoted ( char[] buffer , int offset ) {

						return 0 ;

					}

					@Override
					public int appendQuotedUTF8 ( byte[] buffer , int offset ) {

						return 0 ;

					}

					@Override
					public int appendQuoted ( char[] buffer , int offset ) {

						return 0 ;

					}
				} ;

			} else {

				return null ;

			}

		}
	}

	@Test
	public void verify_big_decimal_rounding ( )
		throws IOException {

		logger.info( CsapApplication.testHeader( ) ) ;

		double memory = 0.15732585356684092 ;
		logger.info( "Simple : {}, full: {}", CSAP.roundIt( 1.23456, 2 ), CSAP.roundIt( memory, 2 ) ) ;

		ObjectMapper mapper = new ObjectMapper( ) ;
		mapper.getFactory( ).setCharacterEscapes( new SlashEscapes( ) ) ;
		ObjectNode o = mapper.createObjectNode( ) ;
		o.put( "/demo/here", "/some/location" ) ;
		String encodedValue = mapper.writeValueAsString( o ) ;
		logger.info( "object: {}, encodedValue: {}", o.toString( ), encodedValue ) ;

		logger.info( "encodedValue read: {}", mapper.readTree( encodedValue ).toString( ) ) ;

	}

	@Test
	public void verifyFileRegex ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		File f = new File( "/aTemp/alertify.js" ) ;

		logger.info( "Absolute: {}, cannonical: {}", f.getAbsolutePath( ), f.getCanonicalPath( ) ) ;

		Pattern p = Pattern.compile( ".*aTemp.*ale.*" ) ;
		Matcher m = p.matcher( Pattern.quote( f.getCanonicalPath( ) ) ) ;

		logger.info( "Pattern quoted: {} Matches: {}", p.toString( ), m.matches( ) ) ;

		p = Pattern.compile( ".*aTemp.*ale.*" ) ;
		m = p.matcher( f.getCanonicalPath( ) ) ;

		logger.info( "Pattern raw: {} Matches: {}", p.toString( ), m.matches( ) ) ;

		p = Pattern.compile( ".*\\\\aTemp.*ale.*" ) ;
		m = p.matcher( Pattern.quote( f.getCanonicalPath( ) ) ) ;
		logger.info( "Pattern: {} Matches: {}", p.toString( ), m.matches( ) ) ;

		p = Pattern.compile( ".*\\\\aTemp.*ale.*" ) ;
		m = p.matcher( f.getCanonicalPath( ) ) ;
		logger.info( "Pattern Raw: {} Matches: {}", p.toString( ), m.matches( ) ) ;

		String ctl = "├─puppet.service" ;

		p = Pattern.compile( "[^\\-].*\\.service" ) ;
		m = p.matcher( ctl ) ;
		logger.info( "Pattern Raw: {} Matches: {}, then {}", p.toString( ), m.matches( ), m.group( ) ) ;

	}

	@Test
	public void verifyStringList ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		List<String> list = Arrays.asList( "Bob", "Steve", "Jim", "Arbby" ) ;

		List<String> upperCaseList = list.stream( )
				.map( String::toUpperCase )
				.collect( Collectors.toList( ) ) ;

		Collections.reverse( list ) ;
		List<String> upperCaseListReverse = list.stream( )
				.map( String::toUpperCase )
				.collect( Collectors.toList( ) ) ;

		logger.info( "list: {} \n upper: {} \n upperCaseListReverse: {} ", list, upperCaseList, upperCaseListReverse ) ;

		for ( int i = 0; i < list.size( ); i++ ) {

			list.set( i, list.get( i ).toUpperCase( ) ) ;

		}

		logger.info( "list: {}", list ) ;

	}

	@Test
	public void buildDateList ( ) {

		logger.info( CsapApplication.testHeader( ) ) ;

		LocalDate today = LocalDate.now( ) ;
		logger.info( "now: {} ", today.format( DateTimeFormatter.ofPattern( "yyyy-MM-dd" ) ) ) ;

		List<String> past10days = LongStream
				.rangeClosed( 1, 10 )
				.mapToObj( day -> today.minusDays( day ) )
				.map( offsetDate -> offsetDate.format( DateTimeFormatter.ofPattern( "yyyy-MM-dd" ) ) )
				.collect( Collectors.toList( ) ) ;

		List<String> past10daysReverse = LongStream.iterate( 10, e -> e - 1 )
				.limit( 10 )
				.mapToObj( day -> today.minusDays( day ) )
				.map( offsetDate -> offsetDate.format( DateTimeFormatter.ofPattern( "yyyy-MM-dd" ) ) )
				.collect( Collectors.toList( ) ) ;

		logger.info( "past10days: {} \n reverse: {}", past10days, past10daysReverse ) ;

	}

	@Disabled
	@Test
	public void ip ( )
		throws Exception {

		logger.info( CsapApplication.testHeader( ) ) ;

		System.out.println( "localhost: " + InetAddress.getLocalHost( ).getHostAddress( ) ) ;

		System.out.println( "dev1 lookup: " + InetAddress.getByName( "10.22.14.153" ).getCanonicalHostName( ) ) ;
		System.out.println( "dev2 lookup: " + InetAddress.getByName( "10.22.13.240" ).getCanonicalHostName( ) ) ;

		NetworkInterface
				.getNetworkInterfaces( ).asIterator( ).forEachRemaining( ni -> {

					String niAddresses = ni.inetAddresses( )
							.map( address -> {

								return address.getHostName( ) + " - " + address.getHostAddress( ) ;

							} )
							.filter( interfaceLine -> interfaceLine.contains( "10.22.14.153" ) )
							.collect( Collectors.joining( "\n\t" ) ) ;
					System.out.println( "addresses: " + niAddresses ) ;

				} ) ;

		Stream<NetworkInterface> niStream = StreamSupport.stream(
				Spliterators.spliteratorUnknownSize( NetworkInterface
						.getNetworkInterfaces( ).asIterator( ), Spliterator.ORDERED ),
				false ) ;

		String niAddresses = niStream.flatMap( ni -> ni.getInterfaceAddresses( ).stream( ) )
				.map( address -> address.getAddress( ).getCanonicalHostName( ) )
				.collect( Collectors.joining( "\n\t" ) ) ;

		System.out.println( "niAddresses: " + niAddresses ) ;

	}

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.resourceconnector.models;

import com.azure.core.http.rest.Response;
import com.azure.core.management.Region;
import com.azure.core.management.SystemData;
import com.azure.core.util.Context;
import com.azure.resourcemanager.resourceconnector.fluent.models.ApplianceInner;
import java.util.Map;

/** An immutable client-side representation of Appliance. */
public interface Appliance {
    /**
     * Gets the id property: Fully qualified resource Id for the resource.
     *
     * @return the id value.
     */
    String id();

    /**
     * Gets the name property: The name of the resource.
     *
     * @return the name value.
     */
    String name();

    /**
     * Gets the type property: The type of the resource.
     *
     * @return the type value.
     */
    String type();

    /**
     * Gets the location property: The geo-location where the resource lives.
     *
     * @return the location value.
     */
    String location();

    /**
     * Gets the tags property: Resource tags.
     *
     * @return the tags value.
     */
    Map<String, String> tags();

    /**
     * Gets the identity property: Identity for the resource.
     *
     * @return the identity value.
     */
    Identity identity();

    /**
     * Gets the systemData property: Metadata pertaining to creation and last modification of the resource.
     *
     * @return the systemData value.
     */
    SystemData systemData();

    /**
     * Gets the distro property: Represents a supported Fabric/Infra. (AKSEdge etc...).
     *
     * @return the distro value.
     */
    Distro distro();

    /**
     * Gets the infrastructureConfig property: Contains infrastructure information about the Appliance.
     *
     * @return the infrastructureConfig value.
     */
    AppliancePropertiesInfrastructureConfig infrastructureConfig();

    /**
     * Gets the provisioningState property: The current deployment or provisioning state, which only appears in the
     * response.
     *
     * @return the provisioningState value.
     */
    String provisioningState();

    /**
     * Gets the publicKey property: Certificates pair used to download MSI certificate from HIS.
     *
     * @return the publicKey value.
     */
    String publicKey();

    /**
     * Gets the status property: Appliance's health and state of connection to on-prem.
     *
     * @return the status value.
     */
    Status status();

    /**
     * Gets the version property: Version of the Appliance.
     *
     * @return the version value.
     */
    String version();

    /**
     * Gets the region of the resource.
     *
     * @return the region of the resource.
     */
    Region region();

    /**
     * Gets the name of the resource region.
     *
     * @return the name of the resource region.
     */
    String regionName();

    /**
     * Gets the name of the resource group.
     *
     * @return the name of the resource group.
     */
    String resourceGroupName();

    /**
     * Gets the inner com.azure.resourcemanager.resourceconnector.fluent.models.ApplianceInner object.
     *
     * @return the inner object.
     */
    ApplianceInner innerModel();

    /** The entirety of the Appliance definition. */
    interface Definition
        extends DefinitionStages.Blank,
            DefinitionStages.WithLocation,
            DefinitionStages.WithResourceGroup,
            DefinitionStages.WithCreate {
    }
    /** The Appliance definition stages. */
    interface DefinitionStages {
        /** The first stage of the Appliance definition. */
        interface Blank extends WithLocation {
        }
        /** The stage of the Appliance definition allowing to specify location. */
        interface WithLocation {
            /**
             * Specifies the region for the resource.
             *
             * @param location The geo-location where the resource lives.
             * @return the next definition stage.
             */
            WithResourceGroup withRegion(Region location);

            /**
             * Specifies the region for the resource.
             *
             * @param location The geo-location where the resource lives.
             * @return the next definition stage.
             */
            WithResourceGroup withRegion(String location);
        }
        /** The stage of the Appliance definition allowing to specify parent resource. */
        interface WithResourceGroup {
            /**
             * Specifies resourceGroupName.
             *
             * @param resourceGroupName The name of the resource group. The name is case insensitive.
             * @return the next definition stage.
             */
            WithCreate withExistingResourceGroup(String resourceGroupName);
        }
        /**
         * The stage of the Appliance definition which contains all the minimum required properties for the resource to
         * be created, but also allows for any other optional properties to be specified.
         */
        interface WithCreate
            extends DefinitionStages.WithTags,
                DefinitionStages.WithIdentity,
                DefinitionStages.WithDistro,
                DefinitionStages.WithInfrastructureConfig,
                DefinitionStages.WithPublicKey,
                DefinitionStages.WithVersion {
            /**
             * Executes the create request.
             *
             * @return the created resource.
             */
            Appliance create();

            /**
             * Executes the create request.
             *
             * @param context The context to associate with this operation.
             * @return the created resource.
             */
            Appliance create(Context context);
        }
        /** The stage of the Appliance definition allowing to specify tags. */
        interface WithTags {
            /**
             * Specifies the tags property: Resource tags..
             *
             * @param tags Resource tags.
             * @return the next definition stage.
             */
            WithCreate withTags(Map<String, String> tags);
        }
        /** The stage of the Appliance definition allowing to specify identity. */
        interface WithIdentity {
            /**
             * Specifies the identity property: Identity for the resource..
             *
             * @param identity Identity for the resource.
             * @return the next definition stage.
             */
            WithCreate withIdentity(Identity identity);
        }
        /** The stage of the Appliance definition allowing to specify distro. */
        interface WithDistro {
            /**
             * Specifies the distro property: Represents a supported Fabric/Infra. (AKSEdge etc...)..
             *
             * @param distro Represents a supported Fabric/Infra. (AKSEdge etc...).
             * @return the next definition stage.
             */
            WithCreate withDistro(Distro distro);
        }
        /** The stage of the Appliance definition allowing to specify infrastructureConfig. */
        interface WithInfrastructureConfig {
            /**
             * Specifies the infrastructureConfig property: Contains infrastructure information about the Appliance.
             *
             * @param infrastructureConfig Contains infrastructure information about the Appliance.
             * @return the next definition stage.
             */
            WithCreate withInfrastructureConfig(AppliancePropertiesInfrastructureConfig infrastructureConfig);
        }
        /** The stage of the Appliance definition allowing to specify publicKey. */
        interface WithPublicKey {
            /**
             * Specifies the publicKey property: Certificates pair used to download MSI certificate from HIS.
             *
             * @param publicKey Certificates pair used to download MSI certificate from HIS.
             * @return the next definition stage.
             */
            WithCreate withPublicKey(String publicKey);
        }
        /** The stage of the Appliance definition allowing to specify version. */
        interface WithVersion {
            /**
             * Specifies the version property: Version of the Appliance.
             *
             * @param version Version of the Appliance.
             * @return the next definition stage.
             */
            WithCreate withVersion(String version);
        }
    }
    /**
     * Begins update for the Appliance resource.
     *
     * @return the stage of resource update.
     */
    Appliance.Update update();

    /** The template for Appliance update. */
    interface Update extends UpdateStages.WithTags {
        /**
         * Executes the update request.
         *
         * @return the updated resource.
         */
        Appliance apply();

        /**
         * Executes the update request.
         *
         * @param context The context to associate with this operation.
         * @return the updated resource.
         */
        Appliance apply(Context context);
    }
    /** The Appliance update stages. */
    interface UpdateStages {
        /** The stage of the Appliance update allowing to specify tags. */
        interface WithTags {
            /**
             * Specifies the tags property: Resource tags.
             *
             * @param tags Resource tags.
             * @return the next definition stage.
             */
            Update withTags(Map<String, String> tags);
        }
    }
    /**
     * Refreshes the resource to sync with Azure.
     *
     * @return the refreshed resource.
     */
    Appliance refresh();

    /**
     * Refreshes the resource to sync with Azure.
     *
     * @param context The context to associate with this operation.
     * @return the refreshed resource.
     */
    Appliance refresh(Context context);

    /**
     * Returns the cluster customer user credentials for the dedicated appliance.
     *
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the List Cluster Customer User Credential Results appliance.
     */
    ApplianceListClusterCustomerUserCredentialResults listClusterCustomerUserCredential();

    /**
     * Returns the cluster customer user credentials for the dedicated appliance.
     *
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the List Cluster Customer User Credential Results appliance along with {@link Response}.
     */
    Response<ApplianceListClusterCustomerUserCredentialResults> listClusterCustomerUserCredentialWithResponse(
        Context context);

    /**
     * Returns the cluster user credentials for the dedicated appliance.
     *
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the List Cluster User Credential appliance.
     */
    ApplianceListCredentialResults listClusterUserCredential();

    /**
     * Returns the cluster user credentials for the dedicated appliance.
     *
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the List Cluster User Credential appliance along with {@link Response}.
     */
    Response<ApplianceListCredentialResults> listClusterUserCredentialWithResponse(Context context);
}


text:
package org.carlspring.strongbox.cron.quartz;

import org.carlspring.strongbox.cron.exceptions.CronTaskNotFoundException;
import org.carlspring.strongbox.cron.domain.CronTaskConfiguration;

import java.util.*;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

/**
 * @author Yougeshwar
 */
@Service
public class CronJobSchedulerService
{

    private final Logger logger =
            LoggerFactory.getLogger(CronJobSchedulerService.class);

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    private Map<String, CronTask> jobsMap = new HashMap<>();

    public void scheduleJob(CronTaskConfiguration cronTaskConfiguration)
            throws ClassNotFoundException, SchedulerException
    {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        if (jobsMap.containsKey(cronTaskConfiguration.getName()))
        {
            CronTask cronTask = jobsMap.get(cronTaskConfiguration.getName());
            JobDetail jobDetail = cronTask.getJobDetail();
            org.quartz.Trigger oldTrigger = cronTask.getTrigger();

            org.quartz.Trigger newTrigger = TriggerBuilder.newTrigger().withIdentity(
                    cronTaskConfiguration.getName()).withSchedule(
                    CronScheduleBuilder.cronSchedule(
                            cronTaskConfiguration.getProperty("cronExpression").toString())).build();

            scheduler.addJob(jobDetail, true, true);
            scheduler.rescheduleJob(oldTrigger.getKey(), newTrigger);

            cronTask.setTrigger(newTrigger);
            cronTask.setScriptName(cronTaskConfiguration.getProperty("fileName"));
        }
        else
        {
            CronTask cronTask = new CronTask();

            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("config", cronTaskConfiguration);
            jobDataMap.put("schedulerFactoryBean", schedulerFactoryBean);
            jobDataMap.put("cronTask", cronTask);

            JobDetail jobDetail = JobBuilder.newJob(
                    (Class<? extends Job>) Class.forName(
                            cronTaskConfiguration.getProperty("jobClass"))).withIdentity(
                    cronTaskConfiguration.getName()).setJobData(jobDataMap).build();

            org.quartz.Trigger trigger;
            trigger = TriggerBuilder.newTrigger().withIdentity(
                    cronTaskConfiguration.getName()).withSchedule(
                    CronScheduleBuilder.cronSchedule(
                            cronTaskConfiguration.getProperty("cronExpression"))).build();

            scheduler.scheduleJob(jobDetail, trigger);

            cronTask.setJobDetail(jobDetail);
            cronTask.setTrigger(trigger);
            cronTask.setScriptName(cronTaskConfiguration.getProperty("fileName"));
            jobsMap.put(cronTaskConfiguration.getName(), cronTask);
        }

        if (!scheduler.isStarted())
        {
            logger.debug("Scheduler started");
            scheduler.start();
        }

        logger.debug("Job scheduled successfully");
    }

    public void deleteJob(CronTaskConfiguration cronTaskConfiguration)
            throws ClassNotFoundException, SchedulerException, CronTaskNotFoundException
    {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        if (!jobsMap.containsKey(cronTaskConfiguration.getName()))
        {
            throw new CronTaskNotFoundException("Cron Task not found on given name");
        }

        CronTask cronTask = jobsMap.get(cronTaskConfiguration.getName());
        JobDetail jobDetail = cronTask.getJobDetail();
        org.quartz.Trigger trigger = cronTask.getTrigger();

        scheduler.unscheduleJob(trigger.getKey());
        scheduler.deleteJob(jobDetail.getKey());

        jobsMap.remove(cronTaskConfiguration.getName());

        logger.debug("Job un-scheduled successfully");
    }

    public GroovyScriptNames getGroovyScriptsName()
    {
        GroovyScriptNames groovyScriptNames = new GroovyScriptNames();
        for (CronTask struct : jobsMap.values())
        {
            if (struct.getScriptName() != null && !struct.getScriptName().isEmpty() &&
                struct.getScriptName().endsWith(".groovy"))
            {
                groovyScriptNames.addName(struct.getScriptName());
            }
        }

        return groovyScriptNames;
    }
}


text:
ACCEPTED

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

#### Published in
Lilloa 9: 218 (1943)

#### Original name
Cystidiodendron Rick

### Remarks
null


text:
FFI bindings to bthprops.

[Documentation](https://retep998.github.io/doc/bthprops-sys/)


text:
package gson_classes;

public class BIUserEvaluation {
    private Attributes attributes;
	public String getAssignedEvidencePair() {
		return attributes.assignedEvidencePair;
	}
	public Integer getAbsTime() {
		return attributes.absTime;
	}
    private class Attributes {
        String assignedEvidencePair;
        Integer absTime;
    }
}


text:
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <sqlite3.h>

#include "database.h"
#include "log.h"

#define count(x) (sizeof((x))/sizeof(*(x)))
#define check(r) if((r) != SQLITE_OK) { goto sqlerror; }

static sqlite3_uint64 gettime(void)
{
    sqlite3_uint64 timestamp;
    struct timespec now;
    if(clock_gettime(CLOCK_MONOTONIC, &now) == -1)
    {
        /* LCOV_EXCL_START : clock_gettime() is unlikely to fail */
        log_critical(0, "getting time failed (clock_gettime): %s",
                     strerror(errno));
        exit(125);
        /* LCOV_EXCL_STOP */
    }
    timestamp = now.tv_sec;
    timestamp *= 1000000000;
    timestamp += now.tv_nsec;
    return timestamp;
}

static sqlite3 *db;
static sqlite3_stmt *stmt_last_rowid;
static sqlite3_stmt *stmt_insert_process;
static sqlite3_stmt *stmt_set_exitcode;
static sqlite3_stmt *stmt_insert_file;
static sqlite3_stmt *stmt_insert_exec;

static int run_id = -1;

int db_init(const char *filename)
{
    int tables_exist;

    check(sqlite3_open(filename, &db));
    log_debug(0, "database file opened: %s", filename);

    check(sqlite3_exec(db, "BEGIN IMMEDIATE;", NULL, NULL, NULL))

    {
        int ret;
        const char *sql = ""
                "SELECT name FROM SQLITE_MASTER "
                "WHERE type='table';";
        sqlite3_stmt *stmt_get_tables;
        unsigned int found = 0x00;
        check(sqlite3_prepare_v2(db, sql, -1, &stmt_get_tables, NULL));
        while((ret = sqlite3_step(stmt_get_tables)) == SQLITE_ROW)
        {
            const char *colname = (const char*)sqlite3_column_text(
                    stmt_get_tables, 0);
            if(strcmp("processes", colname) == 0)
                found |= 0x01;
            else if(strcmp("opened_files", colname) == 0)
                found |= 0x02;
            else if(strcmp("executed_files", colname) == 0)
                found |= 0x04;
            else
                goto wrongschema;
        }
        if(found == 0x00)
            tables_exist = 0;
        else if(found == 0x07)
            tables_exist = 1;
        else
        {
        wrongschema:
            log_critical(0, "database schema is wrong");
            return -1;
        }
        sqlite3_finalize(stmt_get_tables);
        if(ret != SQLITE_DONE)
            goto sqlerror; /* LCOV_EXCL_LINE */
    }

    if(!tables_exist)
    {
        const char *sql[] = {
            "CREATE TABLE processes("
            "    id INTEGER NOT NULL PRIMARY KEY,"
            "    run_id INTEGER NOT NULL,"
            "    parent INTEGER,"
            "    timestamp INTEGER NOT NULL,"
            "    is_thread BOOLEAN NOT NULL,"
            "    exitcode INTEGER"
            "    );",
            "CREATE INDEX proc_parent_idx ON processes(parent);",
            "CREATE TABLE opened_files("
            "    id INTEGER NOT NULL PRIMARY KEY,"
            "    run_id INTEGER NOT NULL,"
            "    name TEXT NOT NULL,"
            "    timestamp INTEGER NOT NULL,"
            "    mode INTEGER NOT NULL,"
            "    is_directory BOOLEAN NOT NULL,"
            "    process INTEGER NOT NULL"
            "    );",
            "CREATE INDEX open_proc_idx ON opened_files(process);",
            "CREATE TABLE executed_files("
            "    id INTEGER NOT NULL PRIMARY KEY,"
            "    name TEXT NOT NULL,"
            "    run_id INTEGER NOT NULL,"
            "    timestamp INTEGER NOT NULL,"
            "    process INTEGER NOT NULL,"
            "    argv TEXT NOT NULL,"
            "    envp TEXT NOT NULL,"
            "    workingdir TEXT NOT NULL"
            "    );",
            "CREATE INDEX exec_proc_idx ON executed_files(process);",
        };
        size_t i;
        for(i = 0; i < count(sql); ++i)
            check(sqlite3_exec(db, sql[i], NULL, NULL, NULL));
    }

    /* Get the first unused run_id */
    {
        sqlite3_stmt *stmt_get_run_id;
        const char *sql = "SELECT max(run_id) + 1 FROM processes;";
        check(sqlite3_prepare_v2(db, sql, -1, &stmt_get_run_id, NULL));
        if(sqlite3_step(stmt_get_run_id) != SQLITE_ROW)
        {
            /* LCOV_EXCL_START */
            sqlite3_finalize(stmt_get_run_id);
            goto sqlerror;
            /* LCOV_EXCL_STOP */
        }
        run_id = sqlite3_column_int(stmt_get_run_id, 0);
        if(sqlite3_step(stmt_get_run_id) != SQLITE_DONE)
        {
            /* LCOV_EXCL_START */
            sqlite3_finalize(stmt_get_run_id);
            goto sqlerror;
            /* LCOV_EXCL_STOP */
        }
        sqlite3_finalize(stmt_get_run_id);
    }
    log_debug(0, "This is run %d", run_id);

    {
        const char *sql = ""
                "SELECT last_insert_rowid()";
        check(sqlite3_prepare_v2(db, sql, -1, &stmt_last_rowid, NULL));
    }

    {
        const char *sql = ""
                "INSERT INTO processes(run_id, parent, timestamp, is_thread)"
                "VALUES(?, ?, ?, ?)";
        check(sqlite3_prepare_v2(db, sql, -1, &stmt_insert_process, NULL));
    }

    {
        const char *sql = ""
                "UPDATE processes SET exitcode=?"
                "WHERE id=?";
        check(sqlite3_prepare_v2(db, sql, -1, &stmt_set_exitcode, NULL));
    }

    {
        const char *sql = ""
                "INSERT INTO opened_files(run_id, name, timestamp, "
                "        mode, is_directory, process)"
                "VALUES(?, ?, ?, ?, ?, ?)";
        check(sqlite3_prepare_v2(db, sql, -1, &stmt_insert_file, NULL));
    }

    {
        const char *sql = ""
                "INSERT INTO executed_files(run_id, name, timestamp, process, "
                "        argv, envp, workingdir)"
                "VALUES(?, ?, ?, ?, ?, ?, ?)";
        check(sqlite3_prepare_v2(db, sql, -1, &stmt_insert_exec, NULL));
    }

    return 0;

    /* LCOV_EXCL_START */
sqlerror:
    log_critical(0, "sqlite3 error creating database: %s", sqlite3_errmsg(db));
    return -1;
    /* LCOV_EXCL_STOP */
}

int db_close(int rollback)
{
    if(rollback)
    {
        check(sqlite3_exec(db, "ROLLBACK;", NULL, NULL, NULL));
    }
    else
    {
        check(sqlite3_exec(db, "COMMIT;", NULL, NULL, NULL));
    }
    log_debug(0, "database file closed%s", rollback?" (rolled back)":"");
    check(sqlite3_finalize(stmt_last_rowid));
    check(sqlite3_finalize(stmt_insert_process));
    check(sqlite3_finalize(stmt_set_exitcode));
    check(sqlite3_finalize(stmt_insert_file));
    check(sqlite3_finalize(stmt_insert_exec));
    check(sqlite3_close(db));
    run_id = -1;
    return 0;

    /* LCOV_EXCL_START */
sqlerror:
    log_critical(0, "sqlite3 error on exit: %s", sqlite3_errmsg(db));
    return -1;
    /* LCOV_EXCL_STOP */
}

#define DB_NO_PARENT ((unsigned int)-2)

int db_add_process(unsigned int *id, unsigned int parent_id,
                   const char *working_dir, int is_thread)
{
    check(sqlite3_bind_int(stmt_insert_process, 1, run_id));
    if(parent_id == DB_NO_PARENT)
    {
        check(sqlite3_bind_null(stmt_insert_process, 2));
    }
    else
    {
        check(sqlite3_bind_int(stmt_insert_process, 2, parent_id));
    }
    /* This assumes that we won't go over 2^32 seconds (~135 years) */
    check(sqlite3_bind_int64(stmt_insert_process, 3, gettime()));
    check(sqlite3_bind_int(stmt_insert_process, 4, is_thread?1:0));

    if(sqlite3_step(stmt_insert_process) != SQLITE_DONE)
        goto sqlerror; /* LCOV_EXCL_LINE */
    sqlite3_reset(stmt_insert_process);

    /* Get id */
    if(sqlite3_step(stmt_last_rowid) != SQLITE_ROW)
        goto sqlerror; /* LCOV_EXCL_LINE */
    *id = sqlite3_column_int(stmt_last_rowid, 0);
    if(sqlite3_step(stmt_last_rowid) != SQLITE_DONE)
        goto sqlerror; /* LCOV_EXCL_LINE */
    sqlite3_reset(stmt_last_rowid);

    return db_add_file_open(*id, working_dir, FILE_WDIR, 1);

    /* LCOV_EXCL_START : Insertions shouldn't fail */
sqlerror:
    log_critical(0, "sqlite3 error inserting process: %s", sqlite3_errmsg(db));
    return -1;
    /* LCOV_EXCL_STOP */
}

int db_add_first_process(unsigned int *id, const char *working_dir)
{
    return db_add_process(id, DB_NO_PARENT, working_dir, 0);
}

int db_add_exit(unsigned int id, int exitcode)
{
    check(sqlite3_bind_int(stmt_set_exitcode, 1, exitcode));
    check(sqlite3_bind_int(stmt_set_exitcode, 2, id));

    if(sqlite3_step(stmt_set_exitcode) != SQLITE_DONE)
        goto sqlerror; /* LCOV_EXCL_LINE */
    sqlite3_reset(stmt_set_exitcode);

    return 0;

    /* LCOV_EXCL_START : Insertions shouldn't fail */
sqlerror:
    log_critical(0, "sqlite3 error setting exitcode: %s", sqlite3_errmsg(db));
    return -1;
    /* LCOV_EXCL_STOP */
}

int db_add_file_open(unsigned int process, const char *name,
                     unsigned int mode, int is_dir)
{
    check(sqlite3_bind_int(stmt_insert_file, 1, run_id));
    check(sqlite3_bind_text(stmt_insert_file, 2, name, -1, SQLITE_TRANSIENT));
    /* This assumes that we won't go over 2^32 seconds (~135 years) */
    check(sqlite3_bind_int64(stmt_insert_file, 3, gettime()));
    check(sqlite3_bind_int(stmt_insert_file, 4, mode));
    check(sqlite3_bind_int(stmt_insert_file, 5, is_dir));
    check(sqlite3_bind_int(stmt_insert_file, 6, process));

    if(sqlite3_step(stmt_insert_file) != SQLITE_DONE)
        goto sqlerror; /* LCOV_EXCL_LINE */
    sqlite3_reset(stmt_insert_file);
    return 0;

    /* LCOV_EXCL_START : Insertions shouldn't fail */
sqlerror:
    log_critical(0, "sqlite3 error inserting file: %s", sqlite3_errmsg(db));
    return -1;
    /* LCOV_EXCL_STOP */
}

static char *strarray2nulsep(const char *const *array, size_t *plen)
{
    char *list;
    size_t len = 0;
    {
        const char *const *a = array;
        while(*a)
        {
            len += strlen(*a) + 1;
            ++a;
        }
    }
    {
        const char *const *a = array;
        char *p;
        p = list = malloc(len);
        while(*a)
        {
            const char *s = *a;
            while(*s)
                *p++ = *s++;
            *p++ = '\0';
            ++a;
        }
    }
    *plen = len;
    return list;
}

int db_add_exec(unsigned int process, const char *binary,
                const char *const *argv, const char *const *envp,
                const char *workingdir)
{
    check(sqlite3_bind_int(stmt_insert_exec, 1, run_id));
    check(sqlite3_bind_text(stmt_insert_exec, 2, binary,
                            -1, SQLITE_TRANSIENT));
    /* This assumes that we won't go over 2^32 seconds (~135 years) */
    check(sqlite3_bind_int64(stmt_insert_exec, 3, gettime()));
    check(sqlite3_bind_int(stmt_insert_exec, 4, process));
    {
        size_t len;
        char *arglist = strarray2nulsep(argv, &len);
        check(sqlite3_bind_text(stmt_insert_exec, 5, arglist, len,
                                SQLITE_TRANSIENT));
        free(arglist);
    }
    {
        size_t len;
        char *envlist = strarray2nulsep(envp, &len);
        check(sqlite3_bind_text(stmt_insert_exec, 6, envlist, len,
                                SQLITE_TRANSIENT));
        free(envlist);
    }
    check(sqlite3_bind_text(stmt_insert_exec, 7, workingdir,
                            -1, SQLITE_TRANSIENT));

    if(sqlite3_step(stmt_insert_exec) != SQLITE_DONE)
        goto sqlerror; /* LCOV_EXCL_LINE */
    sqlite3_reset(stmt_insert_exec);
    return 0;

    /* LCOV_EXCL_START : Insertions shouldn't fail */
sqlerror:
    log_critical(0, "sqlite3 error inserting exec: %s", sqlite3_errmsg(db));
    return -1;
    /* LCOV_EXCL_STOP */
}


text:
#include "config.h"
#include "SVGLocatable.h"

#include "RenderElement.h"
#include "SVGGraphicsElement.h"
#include "SVGImageElement.h"
#include "SVGMatrix.h"
#include "SVGNames.h"

namespace WebCore {

static bool isViewportElement(Node* node)
{
    return (node->hasTagName(SVGNames::svgTag)
        || node->hasTagName(SVGNames::symbolTag)
        || node->hasTagName(SVGNames::foreignObjectTag)
        || is<SVGImageElement>(*node));
}

SVGElement* SVGLocatable::nearestViewportElement(const SVGElement* element)
{
    ASSERT(element);
    for (Element* current = element->parentOrShadowHostElement(); current; current = current->parentOrShadowHostElement()) {
        if (isViewportElement(current))
            return downcast<SVGElement>(current);
    }

    return nullptr;
}

SVGElement* SVGLocatable::farthestViewportElement(const SVGElement* element)
{
    ASSERT(element);
    SVGElement* farthest = nullptr;
    for (Element* current = element->parentOrShadowHostElement(); current; current = current->parentOrShadowHostElement()) {
        if (isViewportElement(current))
            farthest = downcast<SVGElement>(current);
    }
    return farthest;
}

FloatRect SVGLocatable::getBBox(SVGElement* element, StyleUpdateStrategy styleUpdateStrategy)
{
    ASSERT(element);
    if (styleUpdateStrategy == AllowStyleUpdate)
        element->document().updateLayoutIgnorePendingStylesheets();

    // FIXME: Eventually we should support getBBox for detached elements.
    if (!element->renderer())
        return FloatRect();

    return element->renderer()->objectBoundingBox();
}

AffineTransform SVGLocatable::computeCTM(SVGElement* element, CTMScope mode, StyleUpdateStrategy styleUpdateStrategy)
{
    ASSERT(element);
    if (styleUpdateStrategy == AllowStyleUpdate)
        element->document().updateLayoutIgnorePendingStylesheets();

    AffineTransform ctm;

    SVGElement* stopAtElement = mode == NearestViewportScope ? nearestViewportElement(element) : nullptr;
    for (Element* currentElement = element; currentElement; currentElement = currentElement->parentOrShadowHostElement()) {
        if (!currentElement->isSVGElement())
            break;

        ctm = downcast<SVGElement>(*currentElement).localCoordinateSpaceTransform(mode).multiply(ctm);

        // For getCTM() computation, stop at the nearest viewport element
        if (currentElement == stopAtElement)
            break;
    }

    return ctm;
}

ExceptionOr<Ref<SVGMatrix>> SVGLocatable::getTransformToElement(SVGElement* target, StyleUpdateStrategy styleUpdateStrategy)
{
    AffineTransform ctm = getCTM(styleUpdateStrategy);

    if (is<SVGGraphicsElement>(target)) {
        AffineTransform targetCTM = downcast<SVGGraphicsElement>(*target).getCTM(styleUpdateStrategy);
        if (auto inverse = targetCTM.inverse())
            ctm = inverse.value() * ctm;
        else
            return Exception { InvalidStateError, ASCIILiteral("Matrix is not invertible") };
    }

    return SVGMatrix::create(ctm);
}

}


text:
var mongoose = require('mongoose');
var paginate = require('mongoose-paginate');
var schema = new mongoose.Schema({
  title : {
    type: String,
    required: true
  },
  prizes : [{
    name: String,
    photo: [{src: String}],
    amount: Number
  }],
  max_participants : {
    type: Number,
    default: 100
  },
  event : { type: mongoose.Schema.Types.ObjectId, ref: 'event', required: true },
  participants : [{ type: mongoose.Schema.Types.ObjectId, ref: 'user' }],
});

schema.plugin(paginate);

module.exports = mongoose.model('sorteio', schema);


text:
package com.arjuna.wsas.tests.arq;

import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;

public class WarDeployment {
	public static WebArchive getDeployment(Class<?>...args){
		WebArchive archive = ShrinkWrap
		.create(WebArchive.class, "test.war")
		.addClasses(args)
		.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");

		archive.delete(ArchivePaths.create("META-INF/MANIFEST.MF"));

		final String ManifestMF = "Manifest-Version: 1.0\n"
			+ "Dependencies: org.jboss.modules,org.jboss.msc,org.jboss.jts,org.jboss.xts\n";
		archive.setManifest(new StringAsset(ManifestMF));

		return archive;
	}
}


text:
[![Build Status](https://travis-ci.org/alceanicu/ro-num.svg?branch=master)](https://travis-ci.org/alceanicu/ro-num) [![Latest Stable Version](https://poser.pugx.org/alcea/ro-num/v/stable.svg)](https://packagist.org/packages/alcea/ro-num) [![Total Downloads](https://poser.pugx.org/alcea/ro-num/downloads.svg)](https://packagist.org/packages/alcea/ro-num) [![License](https://poser.pugx.org/alcea/ro-num/license.svg)](https://packagist.org/packages/alcea/ro-num)

# Transformare numar in litere
Clasa PHP ce face conversie din numar(cifre) in litere (romana).
Transforma orice numar din intervalul [0-999 999 999 999] in transcriere lui in litere (in limba romana).
Orice numar invalid sau in afara intervalului va fi convertit in '' (empty space);
Optional se poate seta si un separator (implicint este ' ' [empty space]);
EX:
```txt
0 va fi transcris in 'zero'
83 va fi transcris in 'optzeci şi trei'
10002 va fi transcris in 'zece mii doi',
```

# How to install?

### 1. use composer
```php
composer require alcea/ro-num
```

### 2. or, edit require section from composer.json
```
"alcea/ro-num": "^1.1"
```

# How to use?

```php
<?php
# require __DIR__ . '\vendor\autoload.php';
use alcea\romanian\TranslateNumberToTxt;

$number = '22620';
echo new TranslateNumberToTxt($number);      // douăzeci şi două de mii şase sute douăzeci
echo new TranslateNumberToTxt($number, '#'); // douăzeci#şi#două#de#mii#şase#sute#douăzeci
echo new TranslateNumberToTxt($number, '');  // douăzecişidouădemiişasesutedouăzeci

// or

echo TranslateNumberToTxt::convert(255);     // 'două sute cincizeci şi cinci'
echo TranslateNumberToTxt::convert(83, '#'); // 'optzeci#şi#trei'
```

# How to run tests?
```
## Open an terminal and run commands:
git clone https://github.com/alceanicu/ro-num.git
cd ro-num
composer install
./vendor/bin/phpunit --bootstrap ./vendor/autoload.php --testdox
```

## License

This package is licensed under the [MIT](http://opensource.org/licenses/MIT) license.


text:
/**
 * Constructor
 * CodeEditorMenu
 *
 * @see
 * @since: 2015.07.15
 * @author: hw.shim
 */

// @formatter:off
define([
    'dojo/Deferred',
    'webida-lib/util/genetic',
    'webida-lib/util/logger/logger-client',
    'plugins/webida.editor.text-editor/TextEditorMenu'
], function (
    Deferred,
    genetic,
    Logger,
    TextEditorMenu
) {
    'use strict';
// @formatter:on

    /**
     * @typedef {Object} DataSource
     */

    var logger = new Logger();
    //logger.setConfig('level', Logger.LEVELS.log);
    logger.off();

    function CodeEditorMenu(allItems, part) {
        logger.info('new CodeEditorMenu(' + allItems + ', ' + part + ')');
        TextEditorMenu.apply(this, arguments);
    }

    genetic.inherits(CodeEditorMenu, TextEditorMenu, {

        _getAvailableEditItems: function () {
            logger.info('_getAvailableEditItems()');
            var items = TextEditorMenu.prototype._getAvailableEditItems.call(this);
            var deferred = new Deferred();
            var menuItems = this.getAllItems();
            var part = this.getPart();
            var viewer = part.getViewer();
            var editor, selected;
            if (part && viewer) {
                editor = viewer.getWidget();
                selected = editor.getSelection();

                // Toggle Comments
                if (editor._contentAssistDelegator) {
                    if (editor._contentAssistDelegator.execCommand('isLineCommentable', editor) ) {
                        items['&Source']['&Toggle Line Comments'] =
                            menuItems.editMenuItems['&Source']['&Toggle Line Comments'];
                    }
                    if (editor._contentAssistDelegator.execCommand('isBlockCommentable', editor) ) {
                        items['&Source']['Toggle Block Comment'] =
                            menuItems.editMenuItems['&Source']['Toggle Block Comment'];
                    }
                }

                // Code Folding
                items['&Source']['&Fold'] = menuItems.editMenuItems['&Source']['&Fold'];

                // Beautify (All)
                if (editor.getMode().name === 'javascript') {
                    if (selected) {
                        items['&Source']['&Beautify'] = menuItems.editMenuItems['&Source']['&Beautify'];
                    }
                    items['&Source']['B&eautify All'] = menuItems.editMenuItems['&Source']['B&eautify All'];
                }

                // Rename async
                if (editor._contentAssistDelegator) {
                    editor._contentAssistDelegator.execCommand(
                        'request', editor,
                        {type: 'rename', newName: 'someName', fullDocs: true},
                        function (error/*, data*/) {
                            if (!error) {
                                items['&Source']['&Rename Variables'] =
                                    menuItems.editMenuItems['&Source']['&Rename Variables'];
                            }
                            deferred.resolve(items);
                        }
                    );
                } else {
                    deferred.resolve(items);
                }
            }
            return deferred;
        },

        _getAvailableNavigateItems: function () {
            var items = TextEditorMenu.prototype._getAvailableNavigateItems.call(this);
            var menuItems = this.getAllItems();
            var part = this.getPart();
            var viewer = part.getViewer();
            if (viewer) {
                items['&Go to Definition'] = menuItems.navMenuItems['&Go to Definition'];
                if (viewer.execute('isDefaultKeyMap')) {
                    items['G&o to Line'] = menuItems.navMenuItems['G&o to Line'];
                }
                if (viewer.execute('isThereMatchingBracket')) {
                    items['Go to &Matching Brace'] = menuItems.navMenuItems['Go to &Matching Brace'];
                }
            }
            return items;
        }
    });

    return CodeEditorMenu;
});