text:
/* Copyright 2004 - 2007 Kasper Nielsen <kasper@codehaus.org> Licensed under
 * the Apache 2.0 License, see http://coconut.codehaus.org/license.
 */
package org.coconut.operations;

import java.io.Serializable;

import org.coconut.operations.Ops.Predicate;

/**
 * Various String based {@link Predicate} methods and utility classes.
 *

 * This class is normally best used via <tt>import static</tt>.
 *
 * @author Kasper Nielsen
 * @version $Id: StringPredicates.java 472 2007-11-19 09:34:26Z kasper $
 */
public final class StringPredicates {

    // /CLOVER:OFF
    /** Cannot instantiate. */
    private StringPredicates() {}

    // /CLOVER:ON

    /**
     * Creates a Predicate that will accept any String that contains the specified
     * CharSequence. The returned predicate is serializable.
     *
     * @param contains
     *            the CharSequence the predicate will check for
     * @return the newly created Predicate
     * @throws NullPointerException
     *             if the specified charSequence is null
     * @see String#contains(CharSequence)
     */
    public static Predicate<String> contains(CharSequence contains) {
        return new ContainsPredicate(contains);
    }

    /**
     * Creates a Predicate that will accept any String that ends with the specified
     * String. The returned predicate is serializable.
     *
     * @param endsWith
     *            the String the predicate will check against
     * @return the newly created Predicate
     * @throws NullPointerException
     *             if the specified String is null
     * @see String#endsWith(String)
     */
    public static Predicate<String> endsWith(String endsWith) {
        return new EndsWithPredicate(endsWith);
    }

    /**
     * Creates a Predicate that will accept any String that is equal to the specified
     * String ignoring case considerations. The returned predicate is serializable.
     *
     * @param equalsToIgnoreCase
     *            the String the predicate will check against
     * @return the newly created Predicate
     * @throws NullPointerException
     *             if the specified String is null
     * @see String#equalsIgnoreCase(String)
     */
    public static Predicate<String> equalsToIgnoreCase(String equalsToIgnoreCase) {
        return new EqualsIgnoreCasePredicate(equalsToIgnoreCase);
    }

    /**
     * Creates a Predicate that will accept any String that starts with the specified
     * String. The returned predicate is serializable.
     *
     * @param startsWith
     *            the String the predicate will check against
     * @return the newly created Predicate
     * @throws NullPointerException
     *             if the specified String is null
     * @see String#startsWith(String)
     */
    public static Predicate<String> startsWith(String startsWith) {
        return new StartsWithPredicate(startsWith);
    }

    /**
     * A Predicate that will accept any String that contains the specified CharSequence.
     *
     * @see String#contains(CharSequence)
     */
    static final class ContainsPredicate implements Predicate<String>, Serializable {
        /** serialVersionUID. */
        private static final long serialVersionUID = -5349595721464596428L;

        /** The CharSequence the string must contain to be accepted. */
        private final CharSequence contains;

        /**
         * Creates a new ContainsPredicate.
         *
         * @param contains
         *            the CharSequence the predicate will check for
         * @throws NullPointerException
         *             if the specified charSequence is null
         */
        ContainsPredicate(CharSequence contains) {
            if (contains == null) {
                throw new NullPointerException("contains is null");
            }
            this.contains = contains;
        }

        /** {@inheritDoc} */
        @Override
        public boolean equals(Object obj) {
            return obj instanceof ContainsPredicate
                    && ((ContainsPredicate) obj).contains.equals(contains);
        }

        /** {@inheritDoc} */
        public boolean evaluate(String element) {
            return element.contains(contains);
        }

        /** {@inheritDoc} */
        @Override
        public int hashCode() {
            return contains.hashCode();
        }

        /** {@inheritDoc} */
        @Override
        public String toString() {
            return "String contains '" + contains + "'";
        }
    }

    /**
     * A Predicate that will accept any String that ends with the specified String.
     */
    static final class EndsWithPredicate implements Predicate<String>, Serializable {

        /** serialVersionUID. */
        private static final long serialVersionUID = 8903408398832899327L;

        /** The String the string must end with to be accepted. */
        private final String endsWith;

        /**
         * Creates a new EndsWithPredicate.
         *
         * @param endsWith
         *            the String the predicate will check against
         * @throws NullPointerException
         *             if the specified String is null
         */
        EndsWithPredicate(String endsWith) {
            if (endsWith == null) {
                throw new NullPointerException("endsWith is null");
            }
            this.endsWith = endsWith;
        }

        /** {@inheritDoc} */
        @Override
        public boolean equals(Object obj) {
            return obj instanceof EndsWithPredicate
                    && ((EndsWithPredicate) obj).endsWith.equals(endsWith);
        }

        /** {@inheritDoc} */
        public boolean evaluate(String element) {
            return element.endsWith(endsWith);
        }

        /** {@inheritDoc} */
        @Override
        public int hashCode() {
            return endsWith.hashCode();
        }

        /** {@inheritDoc} */
        @Override
        public String toString() {
            return "String ends with '" + endsWith + "'";
        }
    }

    /**
     * A Predicate that will accept any String that is equal to the specified String
     * ignoring case considerations.
     *
     * @see String#equalsIgnoreCase(String)
     */
    static final class EqualsIgnoreCasePredicate implements Predicate<String>, Serializable {

        /** serialVersionUID. */
        private static final long serialVersionUID = 8903408398832899327L;

        /** The String the string must be equal to (ignoring case considerations). */
        private final String equalsIgnoreCase;

        /**
         * Creates a new EqualsIgnoreCasePredicate.
         *
         * @param equalsIgnoreCase
         *            the String the predicate will check against
         * @throws NullPointerException
         *             if the specified String is null
         */
        EqualsIgnoreCasePredicate(String equalsIgnoreCase) {
            if (equalsIgnoreCase == null) {
                throw new NullPointerException("equalsIgnoreCase is null");
            }
            this.equalsIgnoreCase = equalsIgnoreCase;
        }

        /** {@inheritDoc} */
        @Override
        public boolean equals(Object obj) {
            return obj instanceof EqualsIgnoreCasePredicate
                    && ((EqualsIgnoreCasePredicate) obj).equalsIgnoreCase.equals(equalsIgnoreCase);
        }

        /** {@inheritDoc} */
        public boolean evaluate(String element) {
            return element.equalsIgnoreCase(equalsIgnoreCase);
        }

        /** {@inheritDoc} */
        @Override
        public int hashCode() {
            return equalsIgnoreCase.hashCode();
        }

        /** {@inheritDoc} */
        @Override
        public String toString() {
            return "String equals ignore case '" + equalsIgnoreCase + "'";
        }
    }

    /**
     * A Predicate that will accept any String that starts with the specified String.
     */
    static final class StartsWithPredicate implements Predicate<String>, Serializable {

        /** serialVersionUID. */
        private static final long serialVersionUID = 8903408398832899327L;

        /** The String the string must start with to be accepted. */
        private final String startsWith;

        /**
         * Creates a new StartsWithPredicate.
         *
         * @param startsWith
         *            the String the predicate will check against
         * @throws NullPointerException
         *             if the specified String is null
         */
        StartsWithPredicate(String startsWith) {
            if (startsWith == null) {
                throw new NullPointerException("startsWith is null");
            }
            this.startsWith = startsWith;
        }

        /** {@inheritDoc} */
        @Override
        public boolean equals(Object obj) {
            return obj instanceof StartsWithPredicate
                    && ((StartsWithPredicate) obj).startsWith.equals(startsWith);
        }

        /** {@inheritDoc} */
        public boolean evaluate(String element) {
            return element.startsWith(startsWith);
        }

        /** {@inheritDoc} */
        @Override
        public int hashCode() {
            return startsWith.hashCode();
        }

        /** {@inheritDoc} */
        @Override
        public String toString() {
            return "String starts with '" + startsWith + "'";
        }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.myapp.struts.election_manager;

import com.myapp.struts.hbm.Candidate1;
import com.myapp.struts.hbm.ElectionDAO;
import com.myapp.struts.hbm.Electionrule;
import com.myapp.struts.hbm.Position1;
import com.myapp.struts.hbm.PositionDAO;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Iqubal Ahmad
 */
public class deletePositionsBallotAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
         String positions="";
        PositionDAO emailDAO = new PositionDAO();
        HttpSession session = request.getSession();
        String electionid = (String)request.getParameter("getElectionId");
        String instituteId = (String)session.getAttribute("institute_id");
        String positionId = (String)request.getParameter("positionId");
        System.out.println("11111111electionid"+electionid+"positionid="+positionId);
        Position1 position = emailDAO.searchPosition1(Integer.parseInt(positionId), electionid, instituteId);

        if(position!=null)
        {
            PositionDAO pos=new PositionDAO();
            List<Candidate1> obj=(List<Candidate1>)pos.getCandidate(position.getId().getPositionId(),position.getId().getElectionId(),instituteId);

            if(obj.isEmpty()){

            emailDAO.deletePosition(position);
             List<Electionrule> rule = (List<Electionrule>)emailDAO.searchCriteria(Integer.parseInt(positionId), electionid, instituteId);
            if(rule.isEmpty()==false && rule!=null)
            emailDAO.deleteRule(rule);

            positions+="<email_ids><message>Position Deleted Successfully</message></email_ids>";
            response.setContentType("application/xml");
            response.getWriter().write(positions);
            return null;
            }else{
            positions+="<email_ids><message>Sorry Position Cannot be Deleted because Candidature request is sent against this position </message></email_ids>";
            response.setContentType("application/xml");
            response.getWriter().write(positions);
            return null;

            }
        }
        else
        {
            positions+="<email_ids><message>Position Not Exist!</message></email_ids>";
            response.setContentType("application/xml");
            response.getWriter().write(positions);
            return null;
        }
        //return mapping.findForward(SUCCESS);
    }
}

domain: java


text:
/*
 * Copyright 2015 Jameson Williams
 *
 * 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.
 */

package org.nosemaj.pixphony;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

import org.nosemaj.pixphony.R;

/*
 * See https://stackoverflow.com/questions/5486789/how-do-i-make-a-splash-screen
 */
public class SplashActivity extends Activity {
    private final int SPLASH_DISPLAY_LENGTH = 2000;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.splash);

        /* New Handler to start the Menu-Activity
         * and close this Splash-Screen after some seconds.*/
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                /* Create an Intent that will start the Menu-Activity. */
                Intent mainIntent = new Intent(SplashActivity.this, PianoActivity.class);
                SplashActivity.this.startActivity(mainIntent);
                SplashActivity.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }
}


text:
package com.xqoo.email.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.xqoo.email.bo.EmailTemplateBO;
import com.xqoo.email.entity.EmailTemplateEntity;
import com.xqoo.common.core.entity.CurrentUser;
import com.xqoo.common.entity.ResultEntity;
import com.xqoo.common.page.PageResponseBean;
import com.xqoo.email.vo.EmailTemplateVO;

import java.util.List;

/**
 * 数据源表(email_template)表服务接口
 *
 * @author xqoo-code-gen
 * @date 2021-01-11 17:06:49
 */

public interface EmailTemplateService extends IService<EmailTemplateEntity> {

    ResultEntity<PageResponseBean<EmailTemplateEntity>> pageGetList(EmailTemplateBO page);

    ResultEntity insertList(List<EmailTemplateEntity> list, CurrentUser currentUser);

    EmailTemplateEntity getOneEmailTemplateEntityByPrimaryKey(Integer id);

    ResultEntity updateDelFlag(Integer id);

    ResultEntity<String> updateEmailTemplate(EmailTemplateVO vo);

    ResultEntity<String> addEmailTemplate(EmailTemplateVO vo);
}


text:
package org.pipservices3.components.log;

/**
 * Dummy implementation of logger that doesn't do anything.
 * <p>
 * It can be used in testing or in situations when logger is required
 * but shall be disabled.
 *
 * @see ILogger
 */
public class NullLogger implements ILogger {

	/**
	 * Creates a new instance of the logger.
	 */
	public NullLogger() {
	}

	/**
	 * Gets the maximum log level. Messages with higher log level are filtered out.
	 *
	 * @return the maximum log level.
	 */
	public LogLevel getLevel() {
		return LogLevel.None;
	}

	/**
	 * Set the maximum log level.
	 *
	 * @param value a new maximum log level.
	 */
	public void setLevel(LogLevel value) {
	}

	/**
	 * Logs a message at specified log level.
	 *
	 * @param level         a log level.
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param error         an error object associated with this message.
	 * @param message       a human-readable message to log.
	 * @param args          arguments to parameterize the message.
	 */
	public void log(LogLevel level, String correlationId, Exception error, String message, Object... args) {
	}

	/**
	 * Logs fatal (unrecoverable) message that caused the process to crash.
	 *
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param message       a human-readable message to log.
	 * @param args          arguments to parameterize the message.
	 */
	public void fatal(String correlationId, String message, Object... args) {
	}

	/**
	 * Logs fatal (unrecoverable) message that caused the process to crash.
	 *
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param error         an error object associated with this message.
	 */
	public void fatal(String correlationId, Exception error) {
	}

	/**
	 * Logs fatal (unrecoverable) message that caused the process to crash.
	 *
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param error         an error object associated with this message.
	 * @param message       a human-readable message to log.
	 * @param args          arguments to parameterize the message.
	 */
	public void fatal(String correlationId, Exception error, String message, Object... args) {
	}

	/**
	 * Logs recoverable application error.
	 *
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param message       a human-readable message to log.
	 * @param args          arguments to parameterize the message.
	 */
	public void error(String correlationId, String message, Object... args) {
	}

	/**
	 * Logs recoverable application error.
	 *
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param error         an error object associated with this message.
	 */
	public void error(String correlationId, Exception error) {
	}

	/**
	 * Logs recoverable application error.
	 *
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param error         an error object associated with this message.
	 * @param message       a human-readable message to log.
	 * @param args          arguments to parameterize the message.
	 */
	public void error(String correlationId, Exception error, String message, Object... args) {
	}

	/**
	 * Logs a warning that may or may not have a negative impact.
	 *
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param message       a human-readable message to log.
	 * @param args          arguments to parameterize the message.
	 */
	public void warn(String correlationId, String message, Object... args) {
	}

	/**
	 * Logs an important information message
	 *
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param message       a human-readable message to log.
	 * @param args          arguments to parameterize the message.
	 */
	public void info(String correlationId, String message, Object... args) {
	}

	/**
	 * Logs a high-level debug information for troubleshooting.
	 *
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param message       a human-readable message to log.
	 * @param args          arguments to parameterize the message.
	 */
	public void debug(String correlationId, String message, Object... args) {
	}

	/**
	 * Logs a low-level debug information for troubleshooting.
	 *
	 * @param correlationId (optional) transaction id to trace execution through
	 *                      call chain.
	 * @param message       a human-readable message to log.
	 * @param args          arguments to parameterize the message.
	 */
	public void trace(String correlationId, String message, Object... args) {
	}
}


text:
package ru.wobot.uri.impl;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

public class ParsedUri {
    private final Collection<String> segments;
    private final String scheme;
    private final Map<String, String> query;

    private ParsedUri(String scheme, Collection<String> segments, Map<String, String> query) {
        this.segments = segments;
        this.scheme = scheme;
        this.query = query;
    }

    public static ParsedUri parse(final String uri) {
        return parse(URI.create(uri));
    }

    public static ParsedUri parse(final URI uri) {
        final Collection<String> segments = new ArrayList<String>() {{
            String host = uri.getHost();
            if (host == null)
                throw new NullPointerException("Host is null for URI [" + uri + "]");
            add(host);
        }};
        if (uri.getPath() != null && uri.getPath().contains("/")) {
            Collections.addAll(segments, uri.getPath().substring(1).split("/"));
        }
        return new ParsedUri(uri.getScheme(), segments, splitQuery(uri));
    }

    private static Map<String, String> splitQuery(final URI uri) {
        Map<String, String> queryPairs = new LinkedHashMap<>();
        if (uri.getQuery() == null)
            return queryPairs;

        try {
            for (String pair : uri.getQuery().split("&")) {
                int idx = pair.indexOf("=");
                if (idx < 0)
                    queryPairs.put(URLDecoder.decode(pair, "UTF-8"), "");
                else
                    queryPairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
            }
        } catch (UnsupportedEncodingException shouldNotHappens) {
            throw new RuntimeException("Broken VM doesn't support UTF-8.");
        }
        return queryPairs;
    }

    public Collection<String> getSegments() {
        return segments;
    }

    public String getScheme() {
        return scheme;
    }

    public Map<String, String> getQuery() {
        return query;
    }
}


text:
/*
 Copyright (c) Petr Panteleyev. All rights reserved.
 Licensed under the BSD license. See LICENSE file in the project root for full license information.
 */
package org.panteleyev.fx;

import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import java.util.ResourceBundle;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * This class provides convenience methods to create and configure various JavaFX controls in one method call.
 * Most of the methods take resource bundle and text key as parameters for I18N purposes.
 */
public final class FxFactory {
    /**
     * Creates new search text field.
     *
     * @param fieldSupplier text field supplier
     * @param valueCallback value callback
     * @return text field
     */
    public static TextField newSearchField(Supplier<TextField> fieldSupplier, Consumer<String> valueCallback) {
        var searchField = fieldSupplier.get();
        searchField.setPrefColumnCount(20);
        searchField.textProperty().addListener((x, y, newValue) -> valueCallback.accept(newValue));
        searchField.setOnKeyPressed(keyEvent -> {
            if (keyEvent.getCode() == KeyCode.ESCAPE) {
                searchField.clear();
            }
        });
        return searchField;
    }

    /**
     * Creates new text field.
     * @param prefColumnCount the preferred number of text columns
     * @return text field
     */
    public static TextField textField(int prefColumnCount) {
        return textField("", prefColumnCount);
    }

    /**
     * Creates new text field.
     * @param initialValue initial value
     * @param prefColumnCount the preferred number of text columns
     * @return text field
     */
    public static TextField textField(String initialValue, int prefColumnCount) {
        var textField = new TextField(initialValue);
        textField.setPrefColumnCount(prefColumnCount);
        return textField;
    }

    /**
     * Creates new check box.
     *
     * @param rb  resource bundle
     * @param key text key
     * @return check box
     */
    public static CheckBox newCheckBox(ResourceBundle rb, String key) {
        return new CheckBox(rb.getString(key));
    }

    /**
     * Creates new tab.
     *
     * @param rb        resource bundle
     * @param key       text key
     * @param closeable closeable flag
     * @return tab
     */
    public static Tab newTab(ResourceBundle rb, String key, boolean closeable) {
        var tab = new Tab(rb.getString(key));
        tab.setClosable(closeable);
        return tab;
    }

    /**
     * Creates new tab.
     *
     * @param rb        resource bundle
     * @param key       text key
     * @param closeable closeable flag
     * @param node      tab content
     * @return tab
     */
    public static Tab newTab(ResourceBundle rb, String key, boolean closeable, Node node) {
        var tab = new Tab(rb.getString(key), node);
        tab.setClosable(closeable);
        return tab;
    }
}


text:
/*
 * Copyright 2013 the original author or authors.
 *
 * 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.
 */

package org.gradle.language.nativeplatform.internal.incremental.sourceparser;

import java.io.File;
import java.util.List;

/**
 * A parser to extract information from C-compatible source files.
 */
public interface CSourceParser {

    SourceDetails parseSource(File sourceFile);

    interface SourceDetails {
        List<String> getIncludes();
        List<String> getImports();
    }
}


text:
/*
 * Copyright (c) 2018 Couchbase, 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.
 */

package com.couchbase.client.core.env;

public interface PropertyLoader<B extends CoreEnvironment.Builder> {

  void load(B builder);

}


text:
package net.core.tutorial.proficient._01_ConcurrencyAdvanced.exampleThreadLocal;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SharedMapWithUserContext implements Runnable {

    public static Map<Integer, Context> userContextPerUserId = new ConcurrentHashMap<>();
    private Integer userId;
    private UserRepository userRepository = UserRepository.getInstance();

    public SharedMapWithUserContext(Integer userId) {
        this.userId = userId;
    }

    @Override
    public void run() {
        String userName = userRepository.getUserNameForUserId(userId);
        userContextPerUserId.put(userId, new Context(userName));
    }

}


text:
package com.microsoft.azure.cosmos.sample.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.NonNull;

import com.microsoft.azure.cosmos.sample.model.TodoItem;

public class MockDao implements TodoDao {
    private final Map<String, TodoItem> todoItemMap;

    public MockDao() {
        todoItemMap = new HashMap<String, TodoItem>();
    }

    @Override
    public TodoItem createTodoItem(@NonNull TodoItem todoItem) {
        if (todoItem.getId() == null || todoItem.getId().isEmpty()) {
            todoItem.setId(generateId());
        }
        todoItemMap.put(todoItem.getId(), todoItem);
        return todoItem;
    }

    @Override
    public TodoItem readTodoItem(@NonNull String id) {
        return todoItemMap.get(id);
    }

    @Override
    public List<TodoItem> readTodoItems() {
        return new ArrayList<TodoItem>(todoItemMap.values());
    }

    @Override
    public TodoItem updateTodoItem(String id, boolean isComplete) {
        todoItemMap.get(id).setComplete(isComplete);
        return todoItemMap.get(id);
    }

    @Override
    public boolean deleteTodoItem(@NonNull String id) {
        todoItemMap.remove(id);
        return true;
    }

    private String generateId() {
        return new Integer(todoItemMap.size()).toString();
    }
}


text:
package devilrx.smartpacket;

import java.io.*;
import java.net.*;
import java.util.*;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//import org.apache.http.conn.util.InetAddressUtils;

public class Utils {

    /**
     * Convert byte array to hex string
     * @param bytes toConvert
     * @return hexValue
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sbuf = new StringBuilder();
        for(int idx=0; idx < bytes.length; idx++) {
            int intVal = bytes[idx] & 0xff;
            if (intVal < 0x10) sbuf.append("0");
            sbuf.append(Integer.toHexString(intVal).toUpperCase());
        }
        return sbuf.toString();
    }

    /**
     * Get utf8 byte array.
     * @param str which to be converted
     * @return  array of NULL if error was found
     */
    public static byte[] getUTF8Bytes(String str) {
        try { return str.getBytes("UTF-8"); } catch (Exception ex) { return null; }
    }

    /**
     * Load UTF8withBOM or any ansi text file.
     * @param filename which to be converted to string
     * @return String value of File
     * @throws java.io.IOException if error occurs
     */
    public static String loadFileAsString(String filename) throws java.io.IOException {
        final int BUFLEN=1024;
        BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
            byte[] bytes = new byte[BUFLEN];
            boolean isUTF8=false;
            int read,count=0;
            while((read=is.read(bytes)) != -1) {
                if (count==0 && bytes[0]==(byte)0xEF && bytes[1]==(byte)0xBB && bytes[2]==(byte)0xBF ) {
                    isUTF8=true;
                    baos.write(bytes, 3, read-3); // drop UTF8 bom marker
                } else {
                    baos.write(bytes, 0, read);
                }
                count+=read;
            }
            return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
        } finally {
            try{ is.close(); } catch(Exception ignored){}
        }
    }

    /**
     * Returns MAC address of the given interface name.
     * @param interfaceName eth0, wlan0 or NULL=use first interface
     * @return  mac address or empty string
     */
    public static String getMACAddress(String interfaceName) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                if (interfaceName != null) {
                    if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
                }
                byte[] mac = intf.getHardwareAddress();
                if (mac==null) return "";
                StringBuilder buf = new StringBuilder();
                for (byte aMac : mac) buf.append(String.format("%02X:",aMac));
                if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
                return buf.toString();
            }
        } catch (Exception ignored) { } // for now eat exceptions
        return "";
        /*try {
            // this is so Linux hack
            return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
        } catch (IOException ex) {
            return null;
        }*/
    }

    /**
     * Get IP address from first non-localhost interface
     * @param useIPv4   true=return ipv4, false=return ipv6
     * @return  address or empty string
     */
    public static InetAddress getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress();
                        //boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                        boolean isIPv4 = sAddr.indexOf(':')<0;

                        if (useIPv4) {
                            if (isIPv4)
                                return addr;
                        } else {
                            if (!isIPv4) {
                                int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
                                return addr;
//                                return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                            }
                        }
                    }
                }
            }
        } catch (Exception ignored) { } // for now eat exceptions
        return null;
//        return "";

    }

    public static String assetFilePath(Context context, String assetName) {
        File file = new File(context.getFilesDir(), assetName);

        try (InputStream is = context.getAssets().open(assetName)) {
            try (OutputStream os = new FileOutputStream(file)) {
                byte[] buffer = new byte[4 * 1024];
                int read;
                while ((read = is.read(buffer)) != -1) {
                    os.write(buffer, 0, read);
                }
                os.flush();
            }
            return file.getAbsolutePath();
        } catch (IOException e) {
            Log.e("pytorchandroid", "Error process asset " + assetName + " to file path");
        }
        return null;
    }
}


text:
package com.github.nirmalc.es;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import java.io.IOException;

public class TermStat implements Streamable, ToXContent {

    private long termFrequency = 0;
    private long docFrequency = 0;
    private String term;

    public TermStat() {
    }

    public TermStat(String term, long termFrequency, long docFrequency) {
        this.term = term;
        this.termFrequency = termFrequency;
        this.docFrequency = docFrequency;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        termFrequency = in.readLong();
        docFrequency = in.readLong();
    }

    public void add(TermStat termStat) {
        this.termFrequency += termStat.termFrequency;
        this.docFrequency += termStat.docFrequency;
    }

    public long getTermFrequency() {
        return termFrequency;
    }

    public long getDocFrequency() {
        return docFrequency;
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeLong(termFrequency);
        out.writeLong(docFrequency);
    }

    public String toString() {
        try {
            XContentBuilder builder = XContentFactory.jsonBuilder();
            builder.startObject();
            toXContent(builder, EMPTY_PARAMS);
            builder.endObject();
            return builder.toString();
        } catch (IOException e) {
            return "{ \"error\" : \"" + e.getMessage() + "\"}";
        }
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.field("termFrequency", termFrequency);
        builder.field("docFrequency", docFrequency);
        return builder;
    }
}


text:
package org.vertexium.cypher.executor;

import com.google.common.collect.Lists;
import org.vertexium.Element;
import org.vertexium.Vertex;
import org.vertexium.VertexiumException;
import org.vertexium.cypher.VertexiumCypherQueryContext;
import org.vertexium.cypher.VertexiumCypherScope;
import org.vertexium.cypher.ast.model.*;
import org.vertexium.cypher.exceptions.VertexiumCypherNotImplemented;
import org.vertexium.cypher.exceptions.VertexiumCypherTypeErrorException;
import org.vertexium.cypher.functions.CypherFunction;
import org.vertexium.cypher.utils.MapUtils;
import org.vertexium.cypher.utils.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.vertexium.util.StreamUtils.stream;

public class ExpressionExecutor {
    public Object executeExpression(VertexiumCypherQueryContext ctx, CypherAstBase expression, ExpressionScope scope) {
        if (expression == null) {
            return null;
        }

        if (expression instanceof CypherExpression) {
            if (expression instanceof CypherBinaryExpression) {
                return executeBinaryExpression(ctx, (CypherBinaryExpression) expression, scope);
            } else if (expression instanceof CypherComparisonExpression) {
                return executeComparisonExpression(ctx, (CypherComparisonExpression) expression, scope);
            } else if (expression instanceof CypherUnaryExpression) {
                return executeUnaryExpression(ctx, (CypherUnaryExpression) expression, scope);
            } else if (expression instanceof CypherTrueExpression) {
                return true;
            } else if (expression instanceof CypherNegateExpression) {
                return executeNegateExpression(ctx, (CypherNegateExpression) expression, scope);
            }
            throw new VertexiumCypherNotImplemented("" + expression);
        }

        if (expression instanceof CypherListLiteral) {
            //noinspection unchecked
            CypherListLiteral<? extends CypherAstBase> list = (CypherListLiteral<? extends CypherAstBase>) expression;
            return executeList(ctx, list, scope);
        }

        if (expression instanceof CypherLiteral) {
            CypherLiteral literal = (CypherLiteral) expression;
            return literal.getValue();
        }

        if (expression instanceof CypherVariable) {
            CypherVariable variable = (CypherVariable) expression;
            return executeObject(ctx, executeVariable(ctx, variable, scope), scope);
        }

        if (expression instanceof CypherLookup) {
            CypherLookup lookup = (CypherLookup) expression;
            return executeLookup(ctx, lookup, scope);
        }

        if (expression instanceof CypherFunctionInvocation) {
            CypherFunctionInvocation functionInvocation = (CypherFunctionInvocation) expression;
            return executeFunctionInvocation(ctx, functionInvocation, scope);
        }

        if (expression instanceof CypherIn) {
            CypherIn in = (CypherIn) expression;
            return executeIn(ctx, in, scope);
        }

        if (expression instanceof CypherArrayAccess) {
            CypherArrayAccess arrayAccess = (CypherArrayAccess) expression;
            return executeArrayAccess(ctx, arrayAccess, scope);
        }

        if (expression instanceof CypherArraySlice) {
            CypherArraySlice arraySlice = (CypherArraySlice) expression;
            return executeArraySlice(ctx, arraySlice, scope);
        }

        if (expression instanceof CypherParameter) {
            CypherParameter parameter = (CypherParameter) expression;
            return executeParameter(ctx, parameter);
        }

        if (expression instanceof CypherIsNull) {
            CypherIsNull isNull = (CypherIsNull) expression;
            return executeIsNull(ctx, isNull, scope);
        }

        if (expression instanceof CypherIsNotNull) {
            CypherIsNotNull isNotNull = (CypherIsNotNull) expression;
            return executeIsNotNull(ctx, isNotNull, scope);
        }

        if (expression instanceof CypherListComprehension) {
            CypherListComprehension listComprehension = (CypherListComprehension) expression;
            return executeListComprehension(ctx, listComprehension, scope);
        }

        if (expression instanceof CypherStringMatch) {
            CypherStringMatch startWith = (CypherStringMatch) expression;
            return executeStringMatch(ctx, startWith, scope);
        }

        if (expression instanceof CypherPatternComprehension) {
            CypherPatternComprehension patternComprehension = (CypherPatternComprehension) expression;
            VertexiumCypherScope matchScope = scope instanceof VertexiumCypherScope
                    ? (VertexiumCypherScope) scope
                    : VertexiumCypherScope.newSingleItemScope((VertexiumCypherScope.Item) scope);
            VertexiumCypherScope results = ctx.getMatchClauseExecutor().execute(
                    ctx,
                    Lists.newArrayList(patternComprehension.getMatchClause()),
                    matchScope
            );
            return results.stream()
                    .map(item -> executeExpression(ctx, patternComprehension.getExpression(), item));
        }

        throw new VertexiumException("not implemented \"" + expression.getClass().getName() + "\": " + expression);
    }

    private Object executeNegateExpression(VertexiumCypherQueryContext ctx, CypherNegateExpression expression, ExpressionScope scope) {
        Object value = executeExpression(ctx, expression.getValue(), scope);
        if (value instanceof Number) {
            if (value instanceof Double) {
                return -(Double) value;
            }
            if (value instanceof Integer) {
                return -(Integer) value;
            }
            if (value instanceof Long) {
                return -(Long) value;
            }
            return -((Number) value).doubleValue();
        }
        throw new VertexiumException("not implemented");
    }

    private Object executeStringMatch(VertexiumCypherQueryContext ctx, CypherStringMatch stringMatch, ExpressionScope scope) {
        Object value = executeExpression(ctx, stringMatch.getValueExpression(), scope);
        Object stringObj = executeExpression(ctx, stringMatch.getStringExpression(), scope);
        if (stringObj == null) {
            return null;
        }
        if (!(stringObj instanceof String)) {
            return null;
        }
        String string = (String) stringObj;
        if (value == null) {
            return null;
        }
        switch (stringMatch.getOp()) {
            case STARTS_WITH:
                return value.toString().startsWith(string);
            case ENDS_WITH:
                return value.toString().endsWith(string);
            case CONTAINS:
                return value.toString().contains(string);
            default:
                throw new VertexiumException("unhandled string match: " + stringMatch.getOp());
        }
    }

    private Object executeListComprehension(VertexiumCypherQueryContext ctx, CypherListComprehension listComprehension, ExpressionScope scope) {
        Stream<ExpressionScope> itemScopes = executeFilterExpression(ctx, listComprehension.getFilterExpression(), scope);
        if (listComprehension.getExpression() == null) {
            return itemScopes;
        }
        return itemScopes
                .map(itemScope -> executeExpression(ctx, listComprehension.getExpression(), itemScope));
    }

    private Stream<ExpressionScope> executeFilterExpression(
            VertexiumCypherQueryContext ctx,
            CypherFilterExpression filterExpression,
            ExpressionScope scope
    ) {
        String name = filterExpression.getIdInCol().getVariable().getName();
        Object values = executeExpression(ctx, filterExpression.getIdInCol().getExpression(), scope);
        Stream<ExpressionScope> results = toStream(values)
                .map(value -> VertexiumCypherScope.newMapItem(name, value, scope));

        if (filterExpression.getWhere() != null) {
            throw new VertexiumCypherNotImplemented("where");
        }

        return results;
    }

    private Object executeObject(VertexiumCypherQueryContext ctx, Object o, ExpressionScope scope) {
        if (o instanceof CypherAstBase) {
            return executeExpression(ctx, (CypherAstBase) o, scope);
        }
        return o;
    }

    private Object executeIsNotNull(VertexiumCypherQueryContext ctx, CypherIsNotNull isNotNull, ExpressionScope clauseResult) {
        Object value = ctx.getExpressionExecutor().executeExpression(ctx, isNotNull.getValueExpression(), clauseResult);
        return value != null;
    }

    private Object executeIsNull(VertexiumCypherQueryContext ctx, CypherIsNull isNull, ExpressionScope scope) {
        Object value = ctx.getExpressionExecutor().executeExpression(ctx, isNull.getValueExpression(), scope);
        return value == null;
    }

    private Object executeParameter(VertexiumCypherQueryContext ctx, CypherParameter parameter) {
        if (parameter instanceof CypherNameParameter) {
            CypherNameParameter nameParameter = (CypherNameParameter) parameter;
            return ctx.getParameters().get(nameParameter.getParameterName());
        } else if (parameter instanceof CypherIndexedParameter) {
            CypherIndexedParameter indexedParameter = (CypherIndexedParameter) parameter;
            return ctx.getParameters().get(Integer.toString(indexedParameter.getIndex()));
        }
        throw new VertexiumException("not implemented");
    }

    private Object executeArraySlice(VertexiumCypherQueryContext ctx, CypherArraySlice arraySlice, ExpressionScope scope) {
        Object array = ctx.getExpressionExecutor().executeExpression(ctx, arraySlice.getArrayExpression(), scope);
        Object sliceFromObj = ctx.getExpressionExecutor().executeExpression(ctx, arraySlice.getSliceFrom(), scope);
        Object sliceToObj = ctx.getExpressionExecutor().executeExpression(ctx, arraySlice.getSliceTo(), scope);

        if (!(sliceFromObj instanceof Number)) {
            throw new VertexiumException("expected integer from, found " + sliceFromObj.getClass().getName());
        }
        int sliceFrom = ((Number) sliceFromObj).intValue();

        if (!(sliceToObj instanceof Number)) {
            throw new VertexiumException("expected integer to, found " + sliceToObj.getClass().getName());
        }
        int sliceTo = ((Number) sliceToObj).intValue();

        Iterable<?> it = toIterable(array);
        return stream(it)
                .skip(sliceFrom)
                .limit(sliceTo - sliceFrom);
    }

    private Object executeArrayAccess(VertexiumCypherQueryContext ctx, CypherArrayAccess arrayAccess, ExpressionScope scope) {
        Object array = ctx.getExpressionExecutor().executeExpression(ctx, arrayAccess.getArrayExpression(), scope);
        if (array == null) {
            return null;
        }
        Object indexObj = ctx.getExpressionExecutor().executeExpression(ctx, arrayAccess.getIndexExpression(), scope);

        if (array instanceof Element) {
            Element element = (Element) array;
            if (indexObj instanceof String) {
                String propertyName = (String) indexObj;
                return element.getPropertyValue(propertyName);
            }

            throw new VertexiumCypherTypeErrorException("expected string property name, found " + indexObj.getClass().getName());
        }

        if (array instanceof Map) {
            Map map = (Map) array;
            if (indexObj instanceof String) {
                String propertyName = (String) indexObj;
                return map.get(propertyName);
            }

            throw new VertexiumCypherTypeErrorException("MapElementAccessByNonString: expected string, found " + indexObj.getClass().getName());
        }

        if (array instanceof List || array instanceof CypherListLiteral) {
            if (indexObj instanceof Long) {
                indexObj = ((Long) indexObj).intValue();
            }

            if (indexObj instanceof Integer) {
                int index = (int) indexObj;
                if (array instanceof CypherListLiteral) {
                    return ((CypherListLiteral) array).get(index);
                } else if (array instanceof List) {
                    return ((List) array).get(index);
                }
            }

            throw new VertexiumCypherTypeErrorException("ListElementAccessByNonInteger: expected integer, found " + indexObj.getClass().getName());
        }

        if (array instanceof Stream) {
            if (indexObj instanceof Long) {
                indexObj = ((Long) indexObj).intValue();
            }

            if (indexObj instanceof Integer) {
                int index = (int) indexObj;
                return ((Stream<?>) array).skip(index).findFirst().get();
            }

            throw new VertexiumCypherTypeErrorException("ListElementAccessByNonInteger: expected integer, found " + indexObj.getClass().getName());
        }

        throw new VertexiumCypherTypeErrorException("InvalidElementAccess: unexpected object access, found object " + array.getClass().getName() + ": " + array + ", index " + indexObj.getClass().getName() + ": " + indexObj);
    }

    private Object executeIn(VertexiumCypherQueryContext ctx, CypherIn in, ExpressionScope scope) {
        Object value = ctx.getExpressionExecutor().executeExpression(ctx, in.getValueExpression(), scope);
        Object array = ctx.getExpressionExecutor().executeExpression(ctx, in.getArrayExpression(), scope);
        if (value == null) {
            if (array == null) {
                return null;
            }
            Iterable<?> it = toIterable(array);
            if (!it.iterator().hasNext()) {
                return false;
            }
            return null;
        }
        Iterable<?> it = toIterable(array);

        boolean hasNullValue = false;
        for (Object o : it) {
            if (o == null) {
                hasNullValue = true;
                continue;
            }
            if (o instanceof CypherLiteral) {
                o = ((CypherLiteral) o).getValue();
            }
            if (o.equals(value)) {
                return true;
            }
        }
        if (hasNullValue) {
            return null;
        }
        return false;
    }

    private Iterable<?> toIterable(Object obj) {
        Iterable<?> it;
        if (obj instanceof Stream) {
            return ((Stream<?>) obj).collect(Collectors.toList());
        } else if (obj instanceof CypherListLiteral || obj instanceof List || obj instanceof Set) {
            it = (Iterable) obj;
        } else {
            throw new VertexiumCypherNotImplemented("expected iterable, found " + obj == null ? null : obj.getClass().getName());
        }
        return it;
    }

    private Stream<?> toStream(Object obj) {
        if (obj instanceof Stream) {
            return (Stream<?>) obj;
        } else {
            return stream(toIterable(obj));
        }
    }

    private Object executeUnaryExpression(
            VertexiumCypherQueryContext ctx,
            CypherUnaryExpression expression,
            ExpressionScope scope
    ) {
        Object value = ctx.getExpressionExecutor().executeExpression(ctx, expression.getExpression(), scope);
        switch (expression.getOp()) {
            case NOT:
                return executeNOT(value);
            default:
                throw new VertexiumCypherNotImplemented("" + expression.getOp());
        }
    }

    private Object executeNOT(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Boolean) {
            return !((boolean) value);
        }
        throw new VertexiumException("could not NOT: " + value.getClass().getName());
    }

    private Object executeFunctionInvocation(
            VertexiumCypherQueryContext ctx,
            CypherFunctionInvocation functionInvocation,
            ExpressionScope scope
    ) {
        CypherFunction fn = ctx.getFunction(functionInvocation.getFunctionName());
        return fn.invoke(ctx, functionInvocation.getArguments(), scope);
    }

    private Stream<Object> executeList(VertexiumCypherQueryContext context, CypherListLiteral<? extends CypherAstBase> list, ExpressionScope scope) {
        return list.stream()
                .map(i -> executeExpression(context, i, scope));
    }

    private Object executeLookup(VertexiumCypherQueryContext ctx, CypherLookup expression, ExpressionScope scope) {
        Object item = executeExpression(ctx, expression.getAtom(), scope);
        return executeLookup(ctx, item, expression, scope);
    }

    private Object executeLookup(VertexiumCypherQueryContext ctx, Object item, CypherLookup expression, ExpressionScope scope) {
        if (item == null) {
            return null;
        }

        if (item instanceof Map) {
            if (expression.hasLabels()) {
                throw new VertexiumException("lookup using labels from a map is not supported");
            }
            Object value = MapUtils.getByExpression((Map) item, expression.getProperty());
            if (value == null) {
                return null;
            }
            if (value instanceof Element) {
                return value;
            }
            if (value instanceof CypherAstBase) {
                return executeExpression(ctx, (CypherAstBase) value, scope);
            }
            return value;
        }

        if (item instanceof Element) {
            Element element = (Element) item;

            if (expression.hasLabels()) {
                if (element instanceof Vertex) {
                    if (expression.getProperty() != null) {
                        throw new VertexiumException("cannot have labels and properties");
                    }
                    return expression.getLabels().stream()
                            .anyMatch(l -> ctx.getVertexLabels((Vertex) element)
                                    .contains(ctx.normalizeLabelName(l.getValue()))
                            );
                }
                throw new VertexiumCypherNotImplemented("label lookup");
            }

            if (expression.getProperty() == null) {
                return element;
            }

            return element.getPropertyValue(ctx.normalizePropertyName(expression.getProperty()));
        }

        if (item instanceof Collection) {
            Collection<?> list = (Collection) item;
            return list.stream().map(listItem -> executeLookup(ctx, listItem, expression, scope));
        }

        if (item instanceof Stream) {
            Stream<?> list = (Stream) item;
            return list.map(listItem -> executeLookup(ctx, listItem, expression, scope));
        }

        throw new VertexiumCypherTypeErrorException(item, Element.class, Map.class, Collection.class, null);
    }

    private Object executeComparisonExpression(
            VertexiumCypherQueryContext context,
            CypherComparisonExpression expression,
            ExpressionScope scope
    ) {
        Object left = executeExpression(context, expression.getLeft(), scope);
        Object right = executeExpression(context, expression.getRight(), scope);
        String op = expression.getOp();
        switch (op) {
            case "=":
            case "<":
            case "<=":
            case ">":
            case ">=":
            case "<>":
                if (left == null && right == null) {
                    return null;
                }
                if (left == null) {
                    return false;
                }
                return compare(left, op, right);
            default:
                throw new VertexiumException("comparison not implemented: " + op);


text:
/*
 * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
 * the License. A copy of the License is located at
 *
 * http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file 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.
 */
package com.amazonaws.services.guardduty.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListInvitationsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * A list of invitation descriptions.
     *

     */
    private java.util.List<Invitation> invitations;
    /**
     *

     * The pagination parameter to be used on the next list operation to retrieve more items.
     *

     */
    private String nextToken;

    /**
     *

     * A list of invitation descriptions.
     *

     *
     * @return A list of invitation descriptions.
     */

    public java.util.List<Invitation> getInvitations() {
        return invitations;
    }

    /**
     *

     * A list of invitation descriptions.
     *

     *
     * @param invitations
     *        A list of invitation descriptions.
     */

    public void setInvitations(java.util.Collection<Invitation> invitations) {
        if (invitations == null) {
            this.invitations = null;
            return;
        }

        this.invitations = new java.util.ArrayList<Invitation>(invitations);
    }

    /**
     *

     * A list of invitation descriptions.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setInvitations(java.util.Collection)} or {@link #withInvitations(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param invitations
     *        A list of invitation descriptions.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListInvitationsResult withInvitations(Invitation... invitations) {
        if (this.invitations == null) {
            setInvitations(new java.util.ArrayList<Invitation>(invitations.length));
        }
        for (Invitation ele : invitations) {
            this.invitations.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of invitation descriptions.
     *

     *
     * @param invitations
     *        A list of invitation descriptions.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListInvitationsResult withInvitations(java.util.Collection<Invitation> invitations) {
        setInvitations(invitations);
        return this;
    }

    /**
     *

     * The pagination parameter to be used on the next list operation to retrieve more items.
     *

     *
     * @param nextToken
     *        The pagination parameter to be used on the next list operation to retrieve more items.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The pagination parameter to be used on the next list operation to retrieve more items.
     *

     *
     * @return The pagination parameter to be used on the next list operation to retrieve more items.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The pagination parameter to be used on the next list operation to retrieve more items.
     *

     *
     * @param nextToken
     *        The pagination parameter to be used on the next list operation to retrieve more items.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListInvitationsResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getInvitations() != null)
            sb.append("Invitations: ").append(getInvitations()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListInvitationsResult == false)
            return false;
        ListInvitationsResult other = (ListInvitationsResult) obj;
        if (other.getInvitations() == null ^ this.getInvitations() == null)
            return false;
        if (other.getInvitations() != null && other.getInvitations().equals(this.getInvitations()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getInvitations() == null) ? 0 : getInvitations().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public ListInvitationsResult clone() {
        try {
            return (ListInvitationsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
/*
 * Copyright 2002-2018 the original author or authors.
 *
 * 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
 *
 *      https://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.
 */

package org.springframework.beans.factory.xml;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

/**
 * Default implementation of the {@link BeanDefinitionDocumentReader} interface that
 * reads bean definitions according to the "spring-beans" DTD and XSD format
 * (Spring's default XML bean definition format).
 *
 *
The structure, elements, and attribute names of the required XML document
 * are hard-coded in this class. (Of course a transform could be run if necessary
 * to produce this format). {@code <beans>} does not need to be the root
 * element of the XML document: this class will parse all bean definition elements
 * in the XML file, regardless of the actual root element.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @author Erik Wiersma
 * @since 18.12.2003
 */
public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {

	public static final String BEAN_ELEMENT = BeanDefinitionParserDelegate.BEAN_ELEMENT;

	public static final String NESTED_BEANS_ELEMENT = "beans";

	public static final String ALIAS_ELEMENT = "alias";

	public static final String NAME_ATTRIBUTE = "name";

	public static final String ALIAS_ATTRIBUTE = "alias";

	public static final String IMPORT_ELEMENT = "import";

	public static final String RESOURCE_ATTRIBUTE = "resource";

	public static final String PROFILE_ATTRIBUTE = "profile";

	protected final Log logger = LogFactory.getLog(getClass());

	@Nullable
	private XmlReaderContext readerContext;

	@Nullable
	private BeanDefinitionParserDelegate delegate;

	/**
	 * This implementation parses bean definitions according to the "spring-beans" XSD
	 * (or DTD, historically).
	 *
Opens a DOM Document; then initializes the default settings
	 * specified at the {@code <beans/>} level; then parses the contained bean definitions.
	 */
	@Override
	public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
		logger.debug("Loading bean definitions");
		Element root = doc.getDocumentElement();
		//核心逻辑：真正开始bean的解析
		doRegisterBeanDefinitions(root);
	}

	/**
	 * Return the descriptor for the XML resource that this parser works on.
	 */
	protected final XmlReaderContext getReaderContext() {
		Assert.state(this.readerContext != null, "No XmlReaderContext available");
		return this.readerContext;
	}

	/**
	 * Invoke the {@link org.springframework.beans.factory.parsing.SourceExtractor}
	 * to pull the source metadata from the supplied {@link Element}.
	 */
	@Nullable
	protected Object extractSource(Element ele) {
		return getReaderContext().extractSource(ele);
	}

	/**
	 * Register each bean definition within the given root {@code <beans/>} element.
	 */
	protected void doRegisterBeanDefinitions(Element root) {
		// Any nested <beans> elements will cause recursion in this method. In
		// order to propagate and preserve <beans> default-* attributes correctly,
		// keep track of the current (parent) delegate, which may be null. Create
		// the new (child) delegate with a reference to the parent for fallback purposes,
		// then ultimately reset this.delegate back to its original (parent) reference.
		// this behavior emulates a stack of delegates without actually necessitating one.
		BeanDefinitionParserDelegate parent = this.delegate;
		this.delegate = createDelegate(getReaderContext(), root, parent);

		if (this.delegate.isDefaultNamespace(root)) {
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isInfoEnabled()) {
						logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}
		//处理"profile"（PROFILE_ATTRIBUTE）
		//preProcessXml(root),postProcessXml(root)两个方法是空方法，这里使用模板方法模式，
		//如果继承自 DefaultBeanDefinitionDocumentReader 的子类需要在Bean解析前后做一些处理的话，那么只需要重写这两个方法就可以了。
		preProcessXml(root);
		//开始解析，分：默认命名、自定义命名空间 两种情况
		parseBeanDefinitions(root, this.delegate);
		postProcessXml(root);

		this.delegate = parent;
	}

	protected BeanDefinitionParserDelegate createDelegate(
			XmlReaderContext readerContext, Element root, @Nullable BeanDefinitionParserDelegate parentDelegate) {

		BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
		delegate.initDefaults(root, parentDelegate);
		return delegate;
	}

	/**
	 * Parse the elements at the root level in the document:
	 * "import", "alias", "bean".
	 * @param root the DOM root element of the document
	 */
	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		if (delegate.isDefaultNamespace(root)) { //判断根节点是否是默认命名空间
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				if (node instanceof Element) {
					Element ele = (Element) node;
					if (delegate.isDefaultNamespace(ele)) { //判断子节点是否是默认命名空间
						//默认命名空间的解析
						parseDefaultElement(ele, delegate);
					}
					else {
						//自定义命名空间的解析
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
			//自定义命名空间的解析
			delegate.parseCustomElement(root);
		}
	}

	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
			importBeanDefinitionResource(ele);
		}
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			processAliasRegistration(ele);
		}
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			processBeanDefinition(ele, delegate);
		}
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}

	/**
	 * Parse an "import" element and load the bean definitions
	 * from the given resource into the bean factory.
	 */
	protected void importBeanDefinitionResource(Element ele) {
		String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
		if (!StringUtils.hasText(location)) {
			getReaderContext().error("Resource location must not be empty", ele);
			return;
		}

		// Resolve system properties: e.g. "${user.dir}"
		location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);

		Set<Resource> actualResources = new LinkedHashSet<>(4);

		// Discover whether the location is an absolute or relative URI
		boolean absoluteLocation = false;
		try {
			absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
		}
		catch (URISyntaxException ex) {
			// cannot convert to an URI, considering the location relative
			// unless it is the well-known Spring prefix "classpath*:"
		}

		// Absolute or relative?
		if (absoluteLocation) {
			try {
				int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
				if (logger.isDebugEnabled()) {
					logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
				}
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error(
						"Failed to import bean definitions from URL location [" + location + "]", ele, ex);
			}
		}
		else {
			// No URL -> considering resource location as relative to the current file.
			try {
				int importCount;
				Resource relativeResource = getReaderContext().getResource().createRelative(location);
				if (relativeResource.exists()) {
					importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
					actualResources.add(relativeResource);
				}
				else {
					String baseLocation = getReaderContext().getResource().getURL().toString();
					importCount = getReaderContext().getReader().loadBeanDefinitions(
							StringUtils.applyRelativePath(baseLocation, location), actualResources);
				}
				if (logger.isDebugEnabled()) {
					logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
				}
			}
			catch (IOException ex) {
				getReaderContext().error("Failed to resolve current resource location", ele, ex);
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",
						ele, ex);
			}
		}
		Resource[] actResArray = actualResources.toArray(new Resource[0]);
		getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
	}

	/**
	 * Process the given alias element, registering the alias with the registry.
	 */
	protected void processAliasRegistration(Element ele) {
		String name = ele.getAttribute(NAME_ATTRIBUTE);
		String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
		boolean valid = true;
		if (!StringUtils.hasText(name)) {
			getReaderContext().error("Name must not be empty", ele);
			valid = false;
		}
		if (!StringUtils.hasText(alias)) {
			getReaderContext().error("Alias must not be empty", ele);
			valid = false;
		}
		if (valid) {
			try {
				//注册alias
				getReaderContext().getRegistry().registerAlias(name, alias);
			}
			catch (Exception ex) {
				getReaderContext().error("Failed to register alias '" + alias +
						"' for bean with name '" + name + "'", ele, ex);
			}
			//别名注册后通知监听器做相应处理
			getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
		}
	}

	/**
	 * Process the given bean element, parsing the bean definition
	 * and registering it with the registry.
	 */
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			// Send registration event.
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}

	/**
	 * Allow the XML to be extensible by processing any custom element types first,
	 * before we start to process the bean definitions. This method is a natural
	 * extension point for any other custom pre-processing of the XML.
	 *
The default implementation is empty. Subclasses can override this method to
	 * convert custom elements into standard Spring bean definitions, for example.
	 * Implementors have access to the parser's bean definition reader and the
	 * underlying XML resource, through the corresponding accessors.
	 * @see #getReaderContext()
	 */
	protected void preProcessXml(Element root) {
	}

	/**
	 * Allow the XML to be extensible by processing any custom element types last,
	 * after we finished processing the bean definitions. This method is a natural
	 * extension point for any other custom post-processing of the XML.
	 *
The default implementation is empty. Subclasses can override this method to
	 * convert custom elements into standard Spring bean definitions, for example.
	 * Implementors have access to the parser's bean definition reader and the
	 * underlying XML resource, through the corresponding accessors.
	 * @see #getReaderContext()
	 */
	protected void postProcessXml(Element root) {
	}

}


text:
/**
 *
 */
package gov.noaa.pmel.dashboard.qc;

import java.util.TreeSet;

/**
 * Extension of a TreeSet of Integers whose toString() method prints the contents in a compact form.  A sequence of
 * consecutive integers are printed using the first value, a hyphen, and the last value, such as: "5-35, 67, 88-99"
 *
 * @author Karl Smith
 */
public class RowNumSet extends TreeSet<Integer> {

    private static final long serialVersionUID = 6330118819228802042L;

    /**
     * Creates an empty set.
     */
    public RowNumSet() {
        super();
    }

    /**
     * Prints the contents of this set of integers in a compact form. A sequence of consecutive integers are printed
     * using the first value, a hyphen, and the last value, such as: "5-35,67,68,88-99"
     */
    @Override
    public String toString() {
        if ( this.size() < 1 )
            return "";
        StringBuilder sb = new StringBuilder();
        Integer start = null;
        Integer end = null;
        boolean first = true;
        for (Integer val : this) {
            if ( start == null ) {
                // start of a new sequence
                start = val;
                end = val;
            }
            else if ( val.equals(end + 1) ) {
                // continue the current sequence
                end = val;
            }
            else {
                // gap - print the stored sequence
                if ( first ) {
                    first = false;
                }
                else {
                    sb.append(",");
                }
                if ( start.equals(end) ) {
                    // singleton
                    sb.append(start.toString());
                }
                else if ( start.equals(end - 1) ) {
                    // pair
                    sb.append(start.toString());
                    sb.append(",");
                    sb.append(end.toString());
                }
                else {
                    // range
                    sb.append(start.toString());
                    sb.append("-");
                    sb.append(end.toString());
                }
                // start a new sequence
                start = val;
                end = val;
            }
        }
        // print the final stored sequence
        if ( !first ) {
            sb.append(",");
        }
        if ( start.equals(end) ) {
            // singleton
            sb.append(start.toString());
        }
        else if ( start.equals(end - 1) ) {
            // pair
            sb.append(start.toString());
            sb.append(",");
            sb.append(end.toString());
        }
        else {
            // range
            sb.append(start.toString());
            sb.append("-");
            sb.append(end.toString());
        }

        return sb.toString();
    }
}


text:
package com.zandgall.arvopia.state;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import com.zandgall.arvopia.Handler;
import com.zandgall.arvopia.utils.Button;
import com.zandgall.arvopia.utils.LoaderException;
import com.zandgall.arvopia.utils.Public;

public class Changelog extends State {

	public String[] changelog;

	private Button back;

	private int scroll;

	public Changelog(Handler handler) {
		super(handler);

		scroll = 0;

		back = new Button(handler, handler.getWidth()-60, handler.getHeight()-30, 55, 20, "Brings you back to the main menu", "Back");

		try {
			changelog = LoaderException.streamToString(LoaderException.loadResource("/Changelog.txt"), 14).split("\\r");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			changelog = new String[] {"404 File not found: There was an error trying to load the changelog :( try again later"};
		}
	}

	@Override
	public void tick() {

		back.tick();
		if(back.on)
			State.setState(handler.getGame().menuState);

		if(handler.getKeyManager().up && scroll<10)
			scroll+=5;
		if(handler.getKeyManager().down && scroll > -790)
			scroll-=5;

		if(handler.getMouse().getMouseScroll()>0 && scroll>-790 || (handler.getMouse().getMouseScroll()<0 && scroll<10))
			scroll-=handler.getMouse().getMouseScroll()*10;

		if(scroll > 10)
			scroll = 10;
		if(scroll < -790)
			scroll = -790;
	}

	@Override
	public void render(Graphics g, Graphics2D g2d) {
		g2d.setTransform(handler.getGame().getDefaultTransform());

		g.setColor(new Color(120, 225, 255));

		g.fillRect(0, 0, handler.getWidth(), handler.getHeight());

		back.render(g);

		g2d.translate(0, scroll);

		g.setFont(Public.defaultFont);
		g.setColor(Color.black);
		for(int i = 0; i<changelog.length; i++)
			g.drawString(changelog[i], 15, i*13+10);
	}

	@Override
	public void init() {

	}

}


text:
package learning.webapps;

import javax.servlet.*;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class Filter1 implements Filter {
    private String message;

    @Override
    public void init(FilterConfig filterConfig) {
        message = filterConfig.getInitParameter("message");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        addMessage(request);
        chain.doFilter(request, response);
    }

    private void addMessage(ServletRequest request) {
        List<String> list = (List) request.getAttribute("messageList");
        if (list == null) {
            list = new LinkedList<>();
        }
        list.add(message);
        request.setAttribute("messageList", list);
    }

    @Override
    public void destroy() {

    }
}