text:
package internal.org.springframework.content.rest.contentservice;

import static java.lang.String.format;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.content.commons.io.RangeableResource;
import org.springframework.content.commons.mappingcontext.ContentProperty;
import org.springframework.content.commons.mappingcontext.MappingContext;
import org.springframework.content.commons.property.PropertyPath;
import org.springframework.content.commons.repository.ContentStore;
import org.springframework.content.commons.storeservice.StoreInfo;
import org.springframework.content.rest.RestResource;
import org.springframework.content.rest.config.RestConfiguration;
import org.springframework.content.rest.config.RestConfiguration.Resolver;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.data.repository.support.RepositoryInvoker;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ResponseStatusException;

import internal.org.springframework.content.rest.controllers.MethodNotAllowedException;
import internal.org.springframework.content.rest.io.AssociatedStoreResource;
import internal.org.springframework.content.rest.io.RenderedResource;
import internal.org.springframework.content.rest.io.StoreResource;
import internal.org.springframework.content.rest.mappings.StoreByteRangeHttpRequestHandler;

public class ContentStoreContentService implements ContentService {

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

    private static final Map<String, StoreExportedMethodsMap> storeExportedMethods = new HashMap<>();

    private final RestConfiguration config;
    private final RepositoryInvoker repoInvoker;
    private final MappingContext mappingContext;
    private final StoreByteRangeHttpRequestHandler byteRangeRestRequestHandler;

    public ContentStoreContentService(RestConfiguration config, StoreInfo store, RepositoryInvoker repoInvoker, MappingContext mappingContext, StoreByteRangeHttpRequestHandler byteRangeRestRequestHandler) {
        this.config = config;
        this.repoInvoker = repoInvoker;
        this.mappingContext = mappingContext;
        this.byteRangeRestRequestHandler = byteRangeRestRequestHandler;
    }

    @Override
    public void getContent(HttpServletRequest request, HttpServletResponse response, HttpHeaders headers, Resource resource, MediaType resourceType)
            throws ResponseStatusException, MethodNotAllowedException {

        AssociatedStoreResource storeResource = (AssociatedStoreResource)resource;
        ContentProperty property = storeResource.getContentProperty();

        Method[] methodsToUse = getExportedMethodsFor(storeResource.getStoreInfo().getInterface(), storeResource.getPropertyPath()).getContentMethods();

        if (methodsToUse.length > 1) {
            throw new IllegalStateException("Too many getContent methods");
        }

        if (methodsToUse.length == 0) {
            throw new MethodNotAllowedException();
        }

        try {
            MediaType producedResourceType = null;
            Resource storedRenditionResource = null;
            List<MediaType> acceptedMimeTypes = headers.getAccept();
            if (acceptedMimeTypes.size() > 0) {

                MediaType.sortBySpecificityAndQuality(acceptedMimeTypes);
                for (MediaType acceptedMimeType : acceptedMimeTypes) {

                    if (acceptedMimeType.includes(resourceType) && matchParameters(acceptedMimeType, resourceType)) {

                        producedResourceType = resourceType;
                        break;
                    } else if ((storedRenditionResource = findStoredRendition(storeResource, acceptedMimeType)) != null) {

                         resource = storedRenditionResource;
                         producedResourceType = acceptedMimeType;
                         break;
                    } else if (((StoreResource) resource).isRenderableAs(acceptedMimeType)) {

                        resource = new RenderedResource(((StoreResource) resource).renderAs(acceptedMimeType), resource);
                        producedResourceType = acceptedMimeType;
                        break;
                    }
                }

                if (producedResourceType == null) {
                    response.setStatus(HttpStatus.NOT_FOUND.value());
                    return;
                }
            }

            if (resource instanceof RangeableResource) {
                this.configureResourceForByteRangeRequest((RangeableResource)resource, headers);
            }

            request.setAttribute("SPRING_CONTENT_RESOURCE", resource);
            request.setAttribute("SPRING_CONTENT_CONTENTTYPE", producedResourceType);
        } catch (Exception e) {

            logger.error("Unable to retrieve content", e);

            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, format("Failed to handle request for %s", resource.getDescription()), e);
        }

        try {
            byteRangeRestRequestHandler.handleRequest(request, response);
        }
        catch (Exception e) {
            if (isClientAbortException(e)) {
                // suppress
            } else {
                logger.error("Unable to handle request", e);

                throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, format("Failed to handle request for %s", resource.getDescription()), e);
            }
        }
    }

    @Override
    public void setContent(HttpServletRequest request, HttpServletResponse response, HttpHeaders headers, Resource source, MediaType sourceMimeType, Resource target) throws IOException, MethodNotAllowedException {

        AssociatedStoreResource storeResource = (AssociatedStoreResource)target;
        ContentProperty property = storeResource.getContentProperty();

        // Update mimeType and originalFilename before setContent-method invocation,
        // because this information may be needed during setting of content.
        Object domainObject = storeResource.getAssociation();
        property.setMimeType(domainObject, sourceMimeType.toString());

        String originalFilename = source.getFilename();
        if (source.getFilename() != null && StringUtils.hasText(originalFilename)) {
            property.setOriginalFileName(domainObject, source.getFilename());
        }

        Method[] methodsToUse = getExportedMethodsFor(storeResource.getStoreInfo().getInterface(), storeResource.getPropertyPath()).setContentMethods();

        if (methodsToUse.length > 1) {
            RestConfiguration.DomainTypeConfig dtConfig = config.forDomainType(storeResource.getStoreInfo().getDomainObjectClass());
            methodsToUse = filterMethods(methodsToUse, dtConfig.getSetContentResolver(), headers);
        }

        if (methodsToUse.length > 1) {
            throw new UnsupportedOperationException(format("Too many setContent methods exported.  Expected 1.  Got %s", methodsToUse.length));
        }

        if (methodsToUse.length == 0) {
            throw new MethodNotAllowedException();
        }

        Method methodToUse = methodsToUse[0];
        List<Object> argsList = new ArrayList<>();
        argsList.add(domainObject);
        argsList.add(storeResource.getPropertyPath());
        Object contentArg = convertContentArg(source, methodToUse.getParameterTypes()[indexOfContentArg(methodToUse.getParameterTypes())]);
        argsList.add(contentArg);
        if (methodToUse.getParameters().length > 3 && methodToUse.getParameters()[3].getType().equals(long.class)) {
            long len = -1L;
            // if available use the original content length
            if (headers.containsKey(HttpHeaders.CONTENT_LENGTH)) {
                len = headers.getContentLength();
            }
            argsList.add(len);
        }

        try {
            Object targetObj = storeResource.getStoreInfo().getImplementation(ContentStore.class);
            ReflectionUtils.makeAccessible(methodToUse);
            Object updatedDomainObj = ReflectionUtils.invokeMethod(methodToUse, targetObj, argsList.toArray());

            repoInvoker.invokeSave(updatedDomainObj);
        } finally {
            cleanup(contentArg);
        }
    }

    @Override
    public void unsetContent(Resource resource) throws MethodNotAllowedException {

        AssociatedStoreResource storeResource = (AssociatedStoreResource)resource;
        ContentProperty property = storeResource.getContentProperty();

        Method[] methodsToUse = getExportedMethodsFor(storeResource.getStoreInfo().getInterface(), storeResource.getPropertyPath()).unsetContentMethods();

        if (methodsToUse.length == 0) {
            throw new MethodNotAllowedException();
        }

        if (methodsToUse.length > 1) {
            throw new IllegalStateException("Too many unsetContent methods");
        }

        Object updateObject = storeResource.getAssociation();

        Object targetObj = storeResource.getStoreInfo().getImplementation(ContentStore.class);

        ReflectionUtils.makeAccessible(methodsToUse[0]);

        Object updatedDomainObj = ReflectionUtils.invokeMethod(methodsToUse[0], targetObj, updateObject, storeResource.getPropertyPath());

        updateObject = updatedDomainObj;
        property.setMimeType(updateObject, null);
        property.setOriginalFileName(updateObject, null);

        repoInvoker.invokeSave(updateObject);
    }

    private void cleanup(Object contentArg) {

        if (contentArg == null) {
            return;
        }

        if (FileSystemResource.class.isAssignableFrom(contentArg.getClass())) {
            ((FileSystemResource)contentArg).getFile().delete();
        }
    }

    private Object convertContentArg(Resource resource, Class<?> parameterType) {

        if (InputStream.class.equals(parameterType)) {
            try {
                return resource.getInputStream();
            } catch (IOException e) {
                throw new IllegalArgumentException(format("Unable to get inputstream from resource %s", resource.getFilename()));
            }
        } else if (Resource.class.equals(parameterType)) {
            try {
                File f = Files.createTempFile("", "").toFile();
                FileUtils.copyInputStreamToFile(resource.getInputStream(), f);
                return new FileSystemResource(f);
            } catch (IOException e) {
                throw new IllegalArgumentException(format("Unable to re-purpose resource %s", resource.getFilename()));
            }
        } else {
            throw new IllegalArgumentException(format("Unsupported content type %s", parameterType.getCanonicalName()));
        }
    }

    private Method[] filterMethods(Method[] methods, Resolver<Method, HttpHeaders> resolver, HttpHeaders headers) {

        List<Method> resolved = new ArrayList<>();
        for (Method method : methods) {
            if (resolver.resolve(method, headers)) {
                resolved.add(method);
            }
        }

        return resolved.toArray(new Method[]{});
    }

    private boolean matchParameters(MediaType acceptedMediaType, MediaType producableMediaType) {
        for (String name : producableMediaType.getParameters().keySet()) {
            String s1 = producableMediaType.getParameter(name);
            String s2 = acceptedMediaType.getParameter(name);
            if (StringUtils.hasText(s1) && StringUtils.hasText(s2) && !s1.equalsIgnoreCase(s2)) {
                return false;
            }
        }
        return true;
    }

    private void configureResourceForByteRangeRequest(RangeableResource resource, HttpHeaders headers) {
        if (headers.containsKey(HttpHeaders.RANGE)) {
            resource.setRange(headers.getFirst(HttpHeaders.RANGE));
        }
    }

    private int indexOfContentArg(Class<?>[] paramTypes) {
        for (int i=0; i < paramTypes.length; i++) {
            if (InputStream.class.equals(paramTypes[i]) || Resource.class.equals(paramTypes[i])) {
                return i;
            }
        }

        return 0;
    }

    private Resource findStoredRendition(AssociatedStoreResource storeResource, MediaType acceptedMimeType) {

        Resource storedRenditionResource = null;

        Object entity = storeResource.getAssociation();

        for (ContentProperty contentProperty : this.mappingContext.getContentProperties(entity.getClass())) {
            Object candidateMimeType = contentProperty.getMimeType(entity);
            if (candidateMimeType != null) {
                String strCandidateMimeType = candidateMimeType.toString();
                try {
                    MediaType candidateType = MediaType.parseMediaType(strCandidateMimeType);
                    if (acceptedMimeType.includes(candidateType) && matchParameters(acceptedMimeType, candidateType)) {
                        ContentStore store = storeResource.getStoreInfo().getImplementation(ContentStore.class);
                        storedRenditionResource = new RenderedResource(store.getContent(entity, PropertyPath.from(contentProperty.getContentPropertyPath())), storeResource);
                        break;
                    }
                } catch (InvalidMediaTypeException imte) {}
            }
        }

        return storedRenditionResource;
    }

    public static StoreExportedMethodsMap getExportedMethodsFor(Class<?> storeInterfaceClass, PropertyPath path) {

        StoreExportedMethodsMap exportMap = storeExportedMethods.get(storeInterfaceClass.getCanonicalName()+"#"+path.toString());
        if (exportMap == null) {
            storeExportedMethods.put(storeInterfaceClass.getCanonicalName()+"#"+path.toString(), new StoreExportedMethodsMap(storeInterfaceClass, path));
            exportMap = storeExportedMethods.get(storeInterfaceClass.getCanonicalName()+"#"+path.toString());
        }

        return exportMap;
    }

    public static class StoreExportedMethodsMap {

        private static Method[] SETCONTENT_METHODS = null;
        private static Method[] UNSETCONTENT_METHODS = null;
        private static Method[] GETCONTENT_METHODS = null;

        static {
            SETCONTENT_METHODS = new Method[] {
                ReflectionUtils.findMethod(ContentStore.class, "setContent", Object.class, PropertyPath.class, InputStream.class, long.class),
                ReflectionUtils.findMethod(ContentStore.class, "setContent", Object.class, PropertyPath.class, Resource.class),
            };

            UNSETCONTENT_METHODS = new Method[] {
                ReflectionUtils.findMethod(ContentStore.class, "unsetContent", Object.class, PropertyPath.class),
            };

            GETCONTENT_METHODS = new Method[] {
                ReflectionUtils.findMethod(ContentStore.class, "getContent", Object.class, PropertyPath.class),
            };
        }

        private Class<?> storeInterface;
        private PropertyPath path;
        private Method[] getContentMethods;
        private Method[] setContentMethods;
        private Method[] unsetContentMethods;

        public StoreExportedMethodsMap(Class<?> storeInterface, PropertyPath path) {
            this.storeInterface = storeInterface;
            this.getContentMethods = calculateExports(GETCONTENT_METHODS, path);
            this.setContentMethods = calculateExports(SETCONTENT_METHODS, path);
            this.unsetContentMethods = calculateExports(UNSETCONTENT_METHODS, path);
        }

        public Method[] getContentMethods() {
            return this.getContentMethods;
        }

        public Method[] setContentMethods() {
            return this.setContentMethods;
        }

        public Method[] unsetContentMethods() {
            return this.unsetContentMethods;
        }

        private Method[] calculateExports(Method[] storeMethods, PropertyPath path) {

            List<Method> exportedMethods = new ArrayList<>();
            exportedMethods.addAll(Arrays.asList(storeMethods));

            List<Method> unexportedMethods = new ArrayList<>();

            for (Method m : exportedMethods) {
                for (Method dm : storeInterface.getDeclaredMethods()) {
                    if (!dm.isBridge()) {
                        if (dm.getName().equals(m.getName())) {
                            if (argsMatch(dm, m)) {

                                RestResource r = dm.getAnnotation(RestResource.class);
                                if (r != null && r.exported() == false) {
                                    List<String> paths = Arrays.asList(r.paths());
                                    if (paths.contains("*") || paths.contains(path.getName())) {
                                        unexportedMethods.add(m);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Method unexportedMethod : unexportedMethods) {

                exportedMethods.remove(unexportedMethod);
            }

            return exportedMethods.toArray(new Method[]{});
        }

        private boolean argsMatch(Method dm, Method m) {

            if (m.getParameterTypes().length != dm.getParameterTypes().length) {
                return false;
            }

            for (int i=0; i < m.getParameterTypes().length; i++) {

                if (!m.getParameterTypes()[i].isAssignableFrom(dm.getParameterTypes()[i])) {

                    return false;
                }
            }

            return true;
        }
    }

    public static boolean isClientAbortException(Exception e) {
        if (e.getClass().getSimpleName().equals("ClientAbortException")) {
            return true;
        }
        return false;
    }
}


text:
	<title>Craig Baldwin's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Craig Baldwin's panel show appearances

Craig Baldwin has appeared in 2 episodes between 2008-2008. Note that these appearances may be for more than one person if multiple people have the same name.

2008

2008-09-21 / Gardener's Question Time

2008-09-14 / Gardener's Question Time

redpajama_set_name: RedPajamaGithub


text:
namespace bluez {

// static
const char FakeBluetoothGattServiceClient::kHeartRateServicePathComponent[] =
    "service0000";
const char FakeBluetoothGattServiceClient::kBatteryServicePathComponent[] =
    "service0001";
const char FakeBluetoothGattServiceClient::kGenericAccessServiceUUID[] =
    "00001800-0000-1000-8000-00805f9b34fb";
const char FakeBluetoothGattServiceClient::kHeartRateServiceUUID[] =
    "0000180d-0000-1000-8000-00805f9b34fb";
const char FakeBluetoothGattServiceClient::kBatteryServiceUUID[] =
    "0000180f-0000-1000-8000-00805f9b34fb";

FakeBluetoothGattServiceClient::Properties::Properties(
    const PropertyChangedCallback& callback)
    : BluetoothGattServiceClient::Properties(
          NULL,
          bluetooth_gatt_service::kBluetoothGattServiceInterface,
          callback) {}

FakeBluetoothGattServiceClient::Properties::~Properties() = default;

void FakeBluetoothGattServiceClient::Properties::Get(
    dbus::PropertyBase* property,
    dbus::PropertySet::GetCallback callback) {
  DVLOG(1) << "Get " << property->name();
  std::move(callback).Run(false);
}

void FakeBluetoothGattServiceClient::Properties::GetAll() {
  DVLOG(1) << "GetAll";
}

void FakeBluetoothGattServiceClient::Properties::Set(
    dbus::PropertyBase* property,
    dbus::PropertySet::SetCallback callback) {
  DVLOG(1) << "Set " << property->name();
  std::move(callback).Run(false);
}

FakeBluetoothGattServiceClient::FakeBluetoothGattServiceClient() {}

FakeBluetoothGattServiceClient::~FakeBluetoothGattServiceClient() = default;

void FakeBluetoothGattServiceClient::Init(
    dbus::Bus* bus,
    const std::string& bluetooth_service_name) {}

void FakeBluetoothGattServiceClient::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void FakeBluetoothGattServiceClient::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

std::vector<dbus::ObjectPath> FakeBluetoothGattServiceClient::GetServices() {
  std::vector<dbus::ObjectPath> paths;
  if (heart_rate_service_properties_.get()) {
    DCHECK(!heart_rate_service_path_.empty());
    paths.push_back(dbus::ObjectPath(heart_rate_service_path_));
  }
  if (battery_service_properties_.get()) {
    DCHECK(!battery_service_path_.empty());
    paths.push_back(dbus::ObjectPath(battery_service_path_));
  }
  return paths;
}

FakeBluetoothGattServiceClient::Properties*
FakeBluetoothGattServiceClient::GetProperties(
    const dbus::ObjectPath& object_path) {
  if (object_path.value() == heart_rate_service_path_)
    return heart_rate_service_properties_.get();
  if (object_path.value() == battery_service_path_)
    return battery_service_properties_.get();
  return NULL;
}

void FakeBluetoothGattServiceClient::ExposeHeartRateService(
    const dbus::ObjectPath& device_path) {
  if (IsHeartRateVisible()) {
    DCHECK(!heart_rate_service_path_.empty());
    DVLOG(1) << "Fake Heart Rate Service already exposed.";
    return;
  }
  DVLOG(2) << "Exposing fake Heart Rate Service.";
  heart_rate_service_path_ =
      device_path.value() + "/" + kHeartRateServicePathComponent;
  heart_rate_service_properties_ =
      std::make_unique<Properties>(base::BindRepeating(
          &FakeBluetoothGattServiceClient::OnPropertyChanged,
          base::Unretained(this), dbus::ObjectPath(heart_rate_service_path_)));
  heart_rate_service_properties_->uuid.ReplaceValue(kHeartRateServiceUUID);
  heart_rate_service_properties_->device.ReplaceValue(device_path);
  heart_rate_service_properties_->primary.ReplaceValue(true);

  NotifyServiceAdded(GetHeartRateServicePath());

  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::BindOnce(
          &FakeBluetoothGattServiceClient::ExposeHeartRateCharacteristics,
          weak_ptr_factory_.GetWeakPtr()));
}

void FakeBluetoothGattServiceClient::HideHeartRateService() {
  if (!IsHeartRateVisible()) {
    DCHECK(heart_rate_service_path_.empty());
    DVLOG(1) << "Fake Heart Rate Service already hidden.";
    return;
  }
  DVLOG(2) << "Hiding fake Heart Rate Service.";
  FakeBluetoothGattCharacteristicClient* char_client =
      static_cast<FakeBluetoothGattCharacteristicClient*>(
          bluez::BluezDBusManager::Get()
              ->GetBluetoothGattCharacteristicClient());
  char_client->HideHeartRateCharacteristics();

  // Notify observers before deleting the properties structure so that it
  // can be accessed from the observer method.
  NotifyServiceRemoved(dbus::ObjectPath(heart_rate_service_path_));

  heart_rate_service_properties_.reset();
  heart_rate_service_path_.clear();
}

void FakeBluetoothGattServiceClient::ExposeBatteryService(
    const dbus::ObjectPath& device_path) {
  if (IsBatteryServiceVisible()) {
    DCHECK(!battery_service_path_.empty());
    DVLOG(1) << "Fake Battery Service already exposed.";
    return;
  }

  DVLOG(2) << "Exposing fake Battery Service.";
  battery_service_path_ =
      device_path.value() + "/" + kBatteryServicePathComponent;
  battery_service_properties_ =
      std::make_unique<Properties>(base::BindRepeating(
          &FakeBluetoothGattServiceClient::OnPropertyChanged,
          base::Unretained(this), dbus::ObjectPath(battery_service_path_)));
  battery_service_properties_->uuid.ReplaceValue(kBatteryServiceUUID);
  battery_service_properties_->device.ReplaceValue(device_path);
  battery_service_properties_->primary.ReplaceValue(true);

  NotifyServiceAdded(GetBatteryServicePath());
}

bool FakeBluetoothGattServiceClient::IsHeartRateVisible() const {
  return !!heart_rate_service_properties_.get();
}

bool FakeBluetoothGattServiceClient::IsBatteryServiceVisible() const {
  return !!battery_service_properties_.get();
}

dbus::ObjectPath FakeBluetoothGattServiceClient::GetHeartRateServicePath()
    const {
  return dbus::ObjectPath(heart_rate_service_path_);
}

dbus::ObjectPath FakeBluetoothGattServiceClient::GetBatteryServicePath() const {
  return dbus::ObjectPath(battery_service_path_);
}

void FakeBluetoothGattServiceClient::OnPropertyChanged(
    const dbus::ObjectPath& object_path,
    const std::string& property_name) {
  DVLOG(2) << "Fake GATT Service property changed: " << object_path.value()
           << ": " << property_name;
  for (auto& observer : observers_)
    observer.GattServicePropertyChanged(object_path, property_name);
}

void FakeBluetoothGattServiceClient::NotifyServiceAdded(
    const dbus::ObjectPath& object_path) {
  DVLOG(2) << "GATT service added: " << object_path.value();
  for (auto& observer : observers_)
    observer.GattServiceAdded(object_path);
}

void FakeBluetoothGattServiceClient::NotifyServiceRemoved(
    const dbus::ObjectPath& object_path) {
  DVLOG(2) << "GATT service removed: " << object_path.value();
  for (auto& observer : observers_)
    observer.GattServiceRemoved(object_path);
}

void FakeBluetoothGattServiceClient::ExposeHeartRateCharacteristics() {
  if (!IsHeartRateVisible()) {
    DVLOG(2) << "Heart Rate service not visible. Not exposing characteristics.";
    return;
  }
  FakeBluetoothGattCharacteristicClient* char_client =
      static_cast<FakeBluetoothGattCharacteristicClient*>(
          bluez::BluezDBusManager::Get()
              ->GetBluetoothGattCharacteristicClient());
  char_client->ExposeHeartRateCharacteristics(
      dbus::ObjectPath(heart_rate_service_path_));
}

}  // namespace bluez


text:
namespace Multiply_Evens_by_Odds
{
    using System;

    public class MultiplyEvensByOdds
    {
        static void Main()

        {
            int number = int.Parse(Console.ReadLine());
            int returnedMultipliedSum = MultiplySumAndOddDigits(number);
            Console.WriteLine(returnedMultipliedSum);
        }

        private static int MultiplySumAndOddDigits(int number)
        {
            int sumOfEvenNumbers = 0;
            int sumOfOddNumbers = 0;

            while (Math.Abs(number) > 0)
            {
                int lastDigit = number % 10;
                if (lastDigit % 2 == 0)
                {
                    sumOfEvenNumbers += lastDigit;
                }
                else
                {
                    sumOfOddNumbers += lastDigit;
                }
                number /= 10;
            }

            int multipliedEvenAndOddDigits = sumOfEvenNumbers * sumOfOddNumbers;

            return multipliedEvenAndOddDigits;
        }
    }
}


text:
package com.oracle.xmlns.webservices.jaxws_databinding;

import com.sun.xml.ws.model.RuntimeModelerException;

/**
 * Simple util to handle default values.
 *
 * @author miroslav.kos@oracle.com
 */
class Util {

    static String nullSafe(String value) {
        return value == null ? "" : value;
    }

    static <T> T nullSafe(T value, T defaultValue) {
        return value == null ? defaultValue : value;
    }

    @SuppressWarnings("unchecked")
    static <T extends Enum> T nullSafe(Enum value, T defaultValue) {
        return value == null ? defaultValue : (T) T.valueOf(defaultValue.getClass(), value.toString());
    }

    public static Class<?> findClass(String className) {
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeModelerException("runtime.modeler.external.metadata.generic", e);
        }
    }
}


text:
package io.github.marcelbraghetto.football.framework.providers.network.contracts;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

/**
 * Created by Marcel Braghetto on 2/12/15.
 *
 * Network request contract for calling server resources.
 */
public interface NetworkRequestProvider {
    /**
     * Determine whether the user has any kind of
     * network connection.
     * @return true if there is a network connection.
     */
    boolean hasNetworkConnection();

    /**
     * Start a network request with the given configuration
     * and callback delegate.
     * @param tag to associate with this request.
     * @param url to use in the request.
     * @param delegate to call back to.
     */
    void startGetRequest(@NonNull String tag, @NonNull String url, @NonNull NetworkRequestDelegate delegate);

    /**
     * Start a synchronous GET request which will run on
     * the same thread it is invoked. Do NOT call this
     * method on the main thread. It is intended to be
     * used in async tasks, threads or intent services.
     * @param url to use in the request.
     * @return response text or null if the request failed.
     */
    @Nullable String startSynchronousGetRequest(@NonNull String url);

    /**
     * Attempt to cancel the given request tag.
     * @param tag to cancel the request for.
     */
    void cancelRequest(@Nullable String tag);
}


text:
XmlNode is an helper class to work with xmls.
A XmlNode object has a name, a value, attributes, children nodes and a father.
An XmlNode without a father is a root node.
It's possible to convert product of XmlParser into an XmlNode.
It's also possible to add / remove children and attributes from a node.
--]]

require("Shilke2D/Utils/Config/Externals/XmlParser")

XmlNode = class()

---Constructor.
function XmlNode:init(name,attributes,value,children)
    self.name = name
    self.value = value
    self.attributes = attributes or {}
    self.children = children or {}
	self.parent = nil
end

--[[---
Creates a XmlNode starting from the product of XmlParser.parse.
Attaches the new xmlNode to "parent"
@tparam table xml a xml lua table obtained by XmlParser.parse
@tparam[opt=nil] XmlNode parent if provided the new node is attached to the parent node
@treturn XmlNode node
--]]
function XmlNode.fromLuaXml(xml, parent)
    local node = XmlNode(xml.name, xml.attributes, xml.value)
	if parent then
		parent:addChild(node)
	end
    if xml.children then
        for _,child in pairs(xml.children) do
            childNode = XmlNode.fromLuaXml(child,node)
        end
    end
    return node
end

--[[---
Builds an XmlNode starting from a string.
Uses XmlParser.parseString to easily load the string
@tparam string xml the xml string to use for creating the node structure
@tparam[opt=nil] XmlNode parent if provided the new node is attached to the parent node
@treturn[1] XmlNode node the newly created node
@return[2] nil
@treturn[2] string error message
--]]
function XmlNode.fromString(xml, parent)
	local luaXml, err = XmlParser.parseString(xml)
	if not luaXml then
		return nil, err
	end
	local xmlNode = XmlNode.fromLuaXml(luaXml,parent)
	return xmlNode
end

--[[---
Builds an XmlNode starting from a file.
Uses XmlParser.parseFile to easily load the file
@tparam string fileName the name of the xml file to parse
@tparam[opt=nil] XmlNode parent if provided the new node is attached to the parent node
@treturn[1] XmlNode node
@return[2] nil
@treturn[2] string error message
--]]
function XmlNode.fromFile(fileName, parent)
	local luaXml, err = XmlParser.parseFile(fileName)
	if not luaXml then
		return nil, err
	end
	local xmlNode = XmlNode.fromLuaXml(luaXml, parent)
	return xmlNode
end

--[[---
Adds a child to the current XmlNode
@tparam XmlNode child the XmlNode to attach as a child
@treturn XmlNode return a reference to the added node
--]]
function XmlNode:addChild(child)
    table.insert(self.children,child)
	child.parent = self
	return child
end

--[[---
Removes a child from the current XmlNode
@tparam XmlNode child the XmlNode to remove from children list
@treturn[1] XmlNode the removed child
@return[2] nil if child was not in node children
--]]
function XmlNode:removeChild(child)
	local res = table.removeObj(self.children,child)
	if res then
		res.parent = nil
	end
	return res
end

--[[---
Adds a new attribute
if the attribute was already defined it replaces the attribute value
@tparam string name attribute name
@tparam string value attribute value
--]]
function XmlNode:addAttribute(name,value)
	if self.attributes then
        self.attributes[name] = tostring(value)
    end
end

--[[---
Removes an attribute
@tparam string name the name of the attribute to remove
@treturn[1] string value of the removed attribute
@return[2] nil if name is not a valid node attribute
--]]
function XmlNode:removeAttribute(name)
	if self.attributes then
        local value = self.attributes[name]
		self.attributes[name] = nil
		return value
    end
    return nil
end

--[[---
Returns the value of an attribute
@tparam string name attribute key
@tparam[opt=nil] string default if the attribute doesn't exist returns it.
@treturn[1] string the value of the attribute as a string
@return[2] default
--]]
function XmlNode:getAttribute(name, default)
    if self.attributes and self.attributes[name] then
        return self.attributes[name]
    end
    return default
end

--[[---
Returns an attribute value converted as number.
@tparam string name attribute key
@param[opt=nil] default if the attribute doesn't exist returns it.
@treturn[1] number the value of the attribute as a number
@return[2] default
--]]
function XmlNode:getAttributeAsNumber(name, default)
	local v = self:getAttribute(name)
	if v then
		return tonumber(v)
	else
		return default
	end
end

--[[---
Returns an attribute value converted as boolean.
@tparam string name attribute key
@param[opt=nil] default if the attribute doesn't exist returns it. default value is nil
@treturn[1] bool the value of the attribute as a bool
@return[2] default
--]]
function XmlNode:getAttributeAsBool(name, default)
	local v = self:getAttribute(name)
	if v then
		return v:lower() == "true"
	else
		return default
	end
end

--[[---
Returns the attribute name of attribute number 'idx'
@tparam number idx the index of the attribute
@treturn[1] string the name of the attribute if idx is a valid index
@return[2]	nil
--]]
function XmlNode:getAttributeName(idx)
    local i=1
    for k,_ in pairs(self.attributes) do
        if i == idx then
            return k
        end
        i = i + 1
    end
	return nil
end

--[[---
Returns the number of attributes
@treturn int number of attributes
--]]
function XmlNode:getNumAttributes()
    local i=0
    for _,_ in pairs(self.attributes) do
        i = i + 1
    end
    return i
end

--[[---
Returns a children list of child with a given name
@tparam[opt=nil] string name the name of the children element we want to retrieve.
If not provided the method returns all the children of the node
@treturn {XmlNode} an ordered array of all the children with the given name
--]]
function XmlNode:getChildren(name)
    if not name then
        return self.children
    else
        local tmp = {}
        for _,child in pairs(self.children) do
            if child.name and child.name == name then
                table.insert(tmp,child)
            end
        end
        return tmp
    end
end

--[[---
Returns the parent node
@treturn XmlNode the parent node
--]]
function XmlNode:getParent()
    return self.parent
end

--[[---
Dumps xmlnode content over a StringBuilder
@tparam StringBuilder sb
@tparam number tab the number of '\t' required to format the output
--]]
function XmlNode:dump(sb, tab)

	local tab = tab or 0
	if tab > 0 then
		sb:writeln()
	end
	for i=0,tab-1,1 do
		sb:write('\t')
	end
	sb:write("<" .. self.name)
	for k,v in pairs(self.attributes) do
		sb:write(" " .. k .. '="' .. XmlParser.toXmlString(v) .. '"')
	end
	sb:write(">")
	if self.value then
		sb:write(XmlParser.toXmlString(self.value))
	end
	local bNewLine = false
	for _,v in pairs(self.children) do
		v:dump(sb, tab+1)
		bNewLine = true
	end
	if bNewLine then
		sb:writeln()
		for i=0,tab-1,1 do
			sb:write('\t')
		end
	end
	sb:write("</" .. self.name .. ">")
end

--[[---
Prints the content of an XmlNode
@treturn string
--]]
function XmlNode:strDump()
	local sb = StringBuilder()
	self:dump(sb)
    return sb:toString(true)
end

--[[---
Write the content to a file
@tparam string fileName the name of the file to write
@treturn[1] bool success
@return[2] nil
@treturn[2] string error message
--]]
function XmlNode:write(fileName)
	local file, err = IO.open(fileName,'w')
	if not file then
		return false, err
	end
	file:write('<?xml version="1.0" encoding="UTF-8"?>\n')
	file:write(self:strDump())
	io.close(file)
	return true
end


text:
====================================================================
:mod:`gou07` : unidirection dimerisation and quadratic autocatalator
====================================================================

Overview
~~~~~~~~
The :mod:`cmepy.models.gou07` modules defines two models of systems given as
examples by Goutsias [GOU07]_ .

The first model is a unidirectional dimerisation model, which consists of the
single reaction:

.. math::

   P + Q \xrightarrow{k} PQ

The rate coefficient for this reaction is :math:`k = 0.001`. Initially there
are 10 copies of both species :math:`P` and :math:`Q`.

This model can be used in CmePy as follows::

    from cmepy.models import gou07

    model = gou07.create_model_uni_dim()

The second model defined by this module is called the quadratic autocatalator,
and is a system of six reactions:

.. math::

   S \xrightarrow{k_1} P \\
   D + P \xrightarrow{k_2} D + 2P \\
   P + P \xrightarrow{k_3} P + Q \\
   P + Q \xrightarrow{k_4} 2Q \\
   P \xrightarrow{k_5} \star \\
   Q \xrightarrow{k_6} \star

The rate coefficients of these reactions are
:math:`k_1 = 0.002`,
:math:`k_2 = 0.001`,
:math:`k_3 = 0.005`,
:math:`k_4 = 0.004`,
:math:`k_5 = 0.002` and
:math:`k_6 = 0.050`,
while the initial copy counts are 3 copies of the species :math:`S`
and zero copies of all other species.

This model can be used in CmePy as follows::

    from cmepy.models import gou07

    model = gou07.create_model_quad_autocat()

.. Note::

   Goutsias [GOU07]_ actually assumes that the copy count of the species
   :math:`S` used in the above model is in fact *constant*, so that the first
   reaction :math:`S \xrightarrow{k_1} P` proceeds with a fixed propensity.

   This behaviour can be enabled by passing the keyword argument
   ``fixed_s = True`` when calling the
   :func:`create_model_quad_autocat` function to create the quadratic
   autocatalator model.

Running the model
~~~~~~~~~~~~~~~~~
The source code for these models is listed below.

The function :func:`main` defined in the module :mod:`cmepy.models.gou07`
solves the quadratic autocatalator model.
To run this function, open the Python interpreter and enter:

    >>> from cmepy.models import gou07
    >>> gou07.main()

This will solve the system up to :math:`t = 1000`, over 100 steps,
then display plots of the standard deviation and expected value of the
species counts, as seen below.

Sample results
~~~~~~~~~~~~~~
.. image:: gou07_ev_plot.png
.. image:: gou07_std_dev_plot.png

Source
~~~~~~
.. literalinclude:: ../../cmepy/models/gou07.py

.. rubric:: References
.. [GOU07]
   `Goutsias, J.,
   Classical versus stochastic kinetics modeling of biochemical reaction systems,
   Biophysical Journal (2007),
   Vol 92, pp. 2350--2365.
   <http://scholar.google.com/scholar
   &q=goutsias+2007+classical+versus+stochastic+kinetics+modeling+
   of+biochemical+reaction+systems>`_


text:
package org.apache.drill.exec.physical.rowSet;

import java.util.HashSet;
import java.util.Set;

import org.apache.drill.exec.memory.BufferAllocator;
import org.apache.drill.exec.record.BatchSchema;
import org.apache.drill.exec.record.metadata.MetadataUtils;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.exec.physical.rowSet.RowSet.SingleRowSet;

/**
 * Fluent builder to quickly build up an row set (record batch)
 * programmatically.
 */

public final class RowSetBuilder {

  private final DirectRowSet rowSet;
  private final RowSetWriter writer;
  private boolean withSv2;
  private final Set<Integer> skipIndices = new HashSet<>();

  /**
   * Creates a {@link RowSetBuilder}. Since {@link BatchSchema} does not handle complex types well, this has been deprecated in favor of the other constructors.
   *
   * @param allocator An allocator.
   * @param schema    A {@link BatchSchema}.
   * @deprecated Use {@link #RowSetBuilder(BufferAllocator, TupleMetadata)} instead.
   */
  @Deprecated
  public RowSetBuilder(BufferAllocator allocator, BatchSchema schema) {
    this(allocator, MetadataUtils.fromFields(schema), DirectRowSet.INITIAL_ROW_COUNT);
  }

  public RowSetBuilder(BufferAllocator allocator, TupleMetadata schema) {
    this(allocator, schema, DirectRowSet.INITIAL_ROW_COUNT);
  }

  public RowSetBuilder(BufferAllocator allocator, TupleMetadata schema, int capacity) {
    rowSet = DirectRowSet.fromSchema(allocator, schema);
    writer = rowSet.writer(capacity);
  }

  public static RowSet emptyBatch(BufferAllocator allocator, TupleMetadata schema) {
    return new RowSetBuilder(allocator, schema).build();
  }

  public RowSetWriter writer() { return writer; }

  /**
   * Add a new row using column values passed as variable-length arguments. Expects
   * map values to be flattened. a schema of (a:int, b:map(c:varchar)) would be>
   * set as
<tt>add(10, "foo");</tt>
 Values of arrays can be expressed as a Java
   * array. A schema of (a:int, b:int[]) can be set as

   * <tt>add(10, new int[] {100, 200});</tt>

   *
   * @param values column values in column index order
   * @return this builder
   * @throws IllegalStateException if the batch, or any vector in the batch,
   *                               becomes full. This method is designed to be used in tests where we will
   *                               seldom create a full vector of data.
   */
  public RowSetBuilder addRow(Object... values) {
    writer.addRow(values);
    return this;
  }

  public RowSetBuilder addSelection(boolean selected, Object... values) {
    final int index = writer.rowIndex();
    writer.addRow(values);

    if (!selected) {
      skipIndices.add(index);
    }

    return this;
  }

  /**
   * The {@link #addRow(Object...)} method uses Java variable-length arguments to
   * pass a row of values. But, when the row consists of a single array, Java
   * gets confused: is that an array for variable-arguments or is it the value
   * of the first argument? This method clearly states that the single value
   * (including an array) is meant to be the value of the first (and only)
   * column.
   *

   * Examples:

   *     RowSetBuilder twoColsBuilder = ...
   *     // Fine, second item is an array of strings for a repeated Varchar
   *     // column.
   *     twoColsBuilder.add("First", new String[] {"a", "b", "c"});
   *     ...
   *     RowSetBuilder oneColBuilder = ...
   *     // Ambiguous: is this a varargs array of three items?
   *     // That is how Java will perceive it.
   *     oneColBuilder.add(new String[] {"a", "b", "c"});
   *     // Unambiguous: this is a single column value for the
   *     // repeated Varchar column.
   *     oneColBuilder.addSingleCol(new String[] {"a", "b", "c"});
   *

   *
   * @param value value of the first column, which may be an array for a
   *              repeated column
   * @return this builder
   */

  public RowSetBuilder addSingleCol(Object value) {
    return addRow(value);
  }

  public RowSetBuilder addSingleCol(boolean selected, Object value) {
    return addSelection(selected, value);
  }

  /**
   * Build the row set with a selection vector 2. The SV2 is
   * initialized to have a 1:1 index to the rows: SV2 0 points
   * to row 1, SV2 position 1 points to row 1 and so on.
   *
   * @return this builder
   */

  public RowSetBuilder withSv2() {
    withSv2 = true;
    return this;
  }

  public SingleRowSet build() {
    SingleRowSet result = writer.done();
    if (withSv2) {
      return rowSet.toIndirect(skipIndices);
    }
    return result;
  }
}


text:
package org.docksidestage.compatible10x.dbflute.whitebox.bhv;

import org.dbflute.exception.IllegalConditionBeanOperationException;
import org.docksidestage.compatible10x.dbflute.cbean.PurchaseCB;
import org.docksidestage.compatible10x.dbflute.exbhv.PurchaseBhv;
import org.docksidestage.compatible10x.dbflute.exentity.Purchase;
import org.docksidestage.compatible10x.unit.UnitContainerTestCase;

/**
 * @author jflute
 * @since 1.0.5K (2014/07/29 Tuesday)
 */
public class WxBhvVaryingUpdateDreamCruiseTest extends UnitContainerTestCase {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    private PurchaseBhv purchaseBhv;

    // ===================================================================================
    //                                                                  Option Calculation
    //                                                                  ==================
    public void test_varyingUpdateNonstrict_DreamCruise_OptionCalculation_basic() throws Exception {
        // ## Arrange ##
        Purchase before = purchaseBhv.selectByPKValueWithDeletedCheck(3L);
        Integer purchaseCount = before.getPurchaseCount();
        Purchase purchase = new Purchase();
        purchase.setPurchaseId(3L);
        purchase.setPaymentCompleteFlg_True();
        final PurchaseCB purchaseCB = new PurchaseCB();

        // ## Act ##
        purchaseBhv.varyingUpdateNonstrict(purchase, op -> op.self(colCB -> {
            colCB.specify().columnPurchaseCount();
        }).plus(purchaseCB.dreamCruiseCB().specify().columnPurchasePrice()));

        // ## Assert ##
        Purchase actual = purchaseBhv.selectByPKValueWithDeletedCheck(3L);
        assertEquals(Integer.valueOf(purchaseCount + actual.getPurchasePrice()), actual.getPurchaseCount());
    }

    public void test_varyingUpdateNonstrict_DreamCruise_OptionCalculation_chain() throws Exception {
        // ## Arrange ##
        Purchase before = purchaseBhv.selectByPKValueWithDeletedCheck(3L);
        Integer purchaseCount = before.getPurchaseCount();
        Purchase purchase = new Purchase();
        purchase.setPurchaseId(3L);
        purchase.setPaymentCompleteFlg_True();
        final PurchaseCB purchaseCB = new PurchaseCB();

        // ## Act ##
        purchaseBhv.varyingUpdateNonstrict(purchase, op -> op.self(colCB -> {
            colCB.specify().columnPurchaseCount();
        }).multiply(3).plus(purchaseCB.dreamCruiseCB().specify().columnPurchasePrice()));

        // ## Assert ##
        Purchase actual = purchaseBhv.selectByPKValueWithDeletedCheck(3L);
        assertEquals(Integer.valueOf((purchaseCount * 3) + actual.getPurchasePrice()), actual.getPurchaseCount());
    }

    // ===================================================================================
    //                                                                 Specify Calculation
    //                                                                 ===================
    public void test_varyingUpdateNonstrict_DreamCruise_SpecifyCalculation() throws Exception {
        // ## Arrange ##
        Purchase purchase = new Purchase();
        purchase.setPurchaseId(3L);
        purchase.setPaymentCompleteFlg_True();
        final PurchaseCB purchaseCB = new PurchaseCB();

        // ## Act ##
        try {
            purchaseBhv.varyingUpdateNonstrict(purchase, op -> op.self(colCB -> {
                colCB.specify().columnPurchaseCount().plus(purchaseCB.dreamCruiseCB().specify().columnPurchasePrice());
            }).plus(3));
            // ## Assert ##
            fail();
        } catch (IllegalConditionBeanOperationException e) {
            log(e.getMessage());
        }
    }
}


text:
namespace {

// Toolbar favorites are placed under this special folder name.
const base::char16 kFavoritesBarTitle[] = L"_Favorites_Bar_";
const base::char16 kSpartanDatabaseFile[] = L"spartan.edb";

struct EdgeFavoriteEntry {
  EdgeFavoriteEntry()
      : is_folder(false),
        order_number(0),
        item_id(GUID_NULL),
        parent_id(GUID_NULL) {}

  base::string16 title;
  GURL url;
  base::FilePath favicon_file;
  bool is_folder;
  int64_t order_number;
  base::Time date_updated;
  GUID item_id;
  GUID parent_id;

  std::vector<const EdgeFavoriteEntry*> children;

  ImportedBookmarkEntry ToBookmarkEntry(
      bool in_toolbar,
      const std::vector<base::string16>& path) const {
    ImportedBookmarkEntry entry;
    entry.in_toolbar = in_toolbar;
    entry.is_folder = is_folder;
    entry.url = url;
    entry.path = path;
    entry.title = title;
    entry.creation_time = date_updated;
    return entry;
  }
};

struct EdgeFavoriteEntryComparator {
  bool operator()(const EdgeFavoriteEntry* lhs,
                  const EdgeFavoriteEntry* rhs) const {
    return std::tie(lhs->order_number, lhs->title) <
           std::tie(rhs->order_number, rhs->title);
  }
};

// The name of the database file is spartan.edb, however it isn't clear how
// the intermediate path between the DataStore and the database is generated.
// Therefore we just do a simple recursive search until we find a matching name.
base::FilePath FindSpartanDatabase(const base::FilePath& profile_path) {
  base::FilePath data_path =
      profile_path.empty() ? importer::GetEdgeDataFilePath() : profile_path;
  if (data_path.empty())
    return base::FilePath();

  base::FileEnumerator enumerator(data_path.Append(L"DataStore\\Data"), true,
                                  base::FileEnumerator::FILES);
  base::FilePath path = enumerator.Next();
  while (!path.empty()) {
    if (base::EqualsCaseInsensitiveASCII(path.BaseName().value(),
                                         kSpartanDatabaseFile))
      return path;
    path = enumerator.Next();
  }
  return base::FilePath();
}

struct GuidComparator {
  bool operator()(const GUID& a, const GUID& b) const {
    return memcmp(&a, &b, sizeof(a)) < 0;
  }
};

bool ReadFaviconData(const base::FilePath& file,
                     std::vector<unsigned char>* data) {
  std::string image_data;
  if (!base::ReadFileToString(file, &image_data))
    return false;

  const unsigned char* ptr =
      reinterpret_cast<const unsigned char*>(image_data.c_str());
  return importer::ReencodeFavicon(ptr, image_data.size(), data);
}

void BuildBookmarkEntries(const EdgeFavoriteEntry& current_entry,
                          bool is_toolbar,
                          std::vector<ImportedBookmarkEntry>* bookmarks,
                          favicon_base::FaviconUsageDataList* favicons,
                          std::vector<base::string16>* path) {
  for (const EdgeFavoriteEntry* entry : current_entry.children) {
    if (entry->is_folder) {
      // If the favorites bar then load all children as toolbar items.
      if (base::EqualsCaseInsensitiveASCII(entry->title, kFavoritesBarTitle)) {
        // Replace name with Links similar to IE.
        path->push_back(L"Links");
        BuildBookmarkEntries(*entry, true, bookmarks, favicons, path);
        path->pop_back();
      } else {
        path->push_back(entry->title);
        BuildBookmarkEntries(*entry, is_toolbar, bookmarks, favicons, path);
        path->pop_back();
      }
    } else {
      bookmarks->push_back(entry->ToBookmarkEntry(is_toolbar, *path));
      favicon_base::FaviconUsageData favicon;
      if (entry->url.is_valid() && !entry->favicon_file.empty() &&
          ReadFaviconData(entry->favicon_file, &favicon.png_data)) {
        // As the database doesn't provide us a favicon URL we'll fake one.
        GURL::Replacements path_replace;
        path_replace.SetPathStr("/favicon.ico");
        favicon.favicon_url =
            entry->url.GetWithEmptyPath().ReplaceComponents(path_replace);
        favicon.urls.insert(entry->url);
        favicons->push_back(favicon);
      }
    }
  }
}

}  // namespace

EdgeImporter::EdgeImporter() {}

void EdgeImporter::StartImport(const importer::SourceProfile& source_profile,
                               uint16_t items,
                               ImporterBridge* bridge) {
  bridge_ = bridge;
  bridge_->NotifyStarted();
  source_path_ = source_profile.source_path;

  if ((items & importer::FAVORITES) && !cancelled()) {
    bridge_->NotifyItemStarted(importer::FAVORITES);
    ImportFavorites();
    bridge_->NotifyItemEnded(importer::FAVORITES);
  }
  bridge_->NotifyEnded();
}

EdgeImporter::~EdgeImporter() {}

void EdgeImporter::ImportFavorites() {
  std::vector<ImportedBookmarkEntry> bookmarks;
  favicon_base::FaviconUsageDataList favicons;
  ParseFavoritesDatabase(&bookmarks, &favicons);

  if (!bookmarks.empty() && !cancelled()) {
    const base::string16& first_folder_name =
        l10n_util::GetStringUTF16(IDS_BOOKMARK_GROUP_FROM_EDGE);
    bridge_->AddBookmarks(bookmarks, first_folder_name);
  }
  if (!favicons.empty() && !cancelled())
    bridge_->SetFavicons(favicons);
}

// From Edge 13 (released with Windows 10 TH2), Favorites are stored in a JET
// database within the Edge local storage. The import uses the ESE library to
// open and read the data file. The data is stored in a Favorites table with
// the following schema.
// Column Name          Column Type
// ------------------------------------------
// DateUpdated          LongLong - FILETIME
// FaviconFile          LongText - Relative path
// HashedUrl            ULong
// IsDeleted            Bit
// IsFolder             Bit
// ItemId               Guid
// OrderNumber          LongLong
// ParentId             Guid
// RoamDisabled         Bit
// RowId                Long
// Title                LongText
// URL                  LongText
void EdgeImporter::ParseFavoritesDatabase(
    std::vector<ImportedBookmarkEntry>* bookmarks,
    favicon_base::FaviconUsageDataList* favicons) {
  base::FilePath database_path = FindSpartanDatabase(source_path_);
  if (database_path.empty())
    return;

  EdgeDatabaseReader database;
  if (!database.OpenDatabase(database_path.value())) {
    DVLOG(1) << "Error opening database " << database.GetErrorMessage();
    return;
  }

  scoped_ptr<EdgeDatabaseTableEnumerator> enumerator =
      database.OpenTableEnumerator(L"Favorites");
  if (!enumerator) {
    DVLOG(1) << "Error opening database table " << database.GetErrorMessage();
    return;
  }

  if (!enumerator->Reset())
    return;

  std::map<GUID, EdgeFavoriteEntry, GuidComparator> database_entries;
  base::FilePath favicon_base =
      source_path_.empty() ? importer::GetEdgeDataFilePath() : source_path_;
  favicon_base = favicon_base.Append(L"DataStore");

  do {
    EdgeFavoriteEntry entry;
    bool is_deleted = false;
    if (!enumerator->RetrieveColumn(L"IsDeleted", &is_deleted))
      continue;
    if (is_deleted)
      continue;
    if (!enumerator->RetrieveColumn(L"IsFolder", &entry.is_folder))
      continue;
    base::string16 url;
    if (!enumerator->RetrieveColumn(L"URL", &url))
      continue;
    entry.url = GURL(url);
    if (!entry.is_folder && !entry.url.is_valid())
      continue;
    if (!enumerator->RetrieveColumn(L"Title", &entry.title))
      continue;
    base::string16 favicon_file;
    if (!enumerator->RetrieveColumn(L"FaviconFile", &favicon_file))
      continue;
    if (!favicon_file.empty())
      entry.favicon_file = favicon_base.Append(favicon_file);
    if (!enumerator->RetrieveColumn(L"ParentId", &entry.parent_id))
      continue;
    if (!enumerator->RetrieveColumn(L"ItemId", &entry.item_id))
      continue;
    if (!enumerator->RetrieveColumn(L"OrderNumber", &entry.order_number))
      continue;
    FILETIME data_updated;
    if (!enumerator->RetrieveColumn(L"DateUpdated", &data_updated))
      continue;
    entry.date_updated = base::Time::FromFileTime(data_updated);
    database_entries[entry.item_id] = entry;
  } while (enumerator->Next() && !cancelled());

  // Build simple tree.
  EdgeFavoriteEntry root_entry;
  for (auto& entry : database_entries) {
    auto found_parent = database_entries.find(entry.second.parent_id);
    if (found_parent == database_entries.end() ||
        !found_parent->second.is_folder) {
      root_entry.children.push_back(&entry.second);
    } else {
      found_parent->second.children.push_back(&entry.second);
    }
  }
  // With tree built sort the children of each node including the root.
  std::sort(root_entry.children.begin(), root_entry.children.end(),
            EdgeFavoriteEntryComparator());
  for (auto& entry : database_entries) {
    std::sort(entry.second.children.begin(), entry.second.children.end(),
              EdgeFavoriteEntryComparator());
  }
  std::vector<base::string16> path;
  BuildBookmarkEntries(root_entry, false, bookmarks, favicons, &path);
}


text:
<?php

namespace Terranet\Translator;

interface TranslatorInterface
{
    public function get($key, array $replace = [], $locale = null, $fallback = true);

    public function addNamespace($namespace, $hint);
}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_GRADIENT_VALUE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_GRADIENT_VALUE_H_

#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_image_generator_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"

namespace blink {

class Color;
class Gradient;
class Document;

namespace cssvalue {

enum CSSGradientType {
  kCSSDeprecatedLinearGradient,
  kCSSDeprecatedRadialGradient,
  kCSSPrefixedLinearGradient,
  kCSSPrefixedRadialGradient,
  kCSSLinearGradient,
  kCSSRadialGradient,
  kCSSConicGradient
};
enum CSSGradientRepeat { kNonRepeating, kRepeating };

// This struct is stack allocated and allocated as part of vectors.
// When allocated on the stack its members are found by conservative
// stack scanning. When allocated as part of Vectors in heap-allocated
// objects its members are visited via the containing object's
// (CSSGradientValue) traceAfterDispatch method.
//
// http://www.w3.org/TR/css3-images/#color-stop-syntax
struct CSSGradientColorStop {
  DISALLOW_NEW();

  bool operator==(const CSSGradientColorStop& other) const {
    return base::ValuesEquivalent(color_, other.color_) &&
           base::ValuesEquivalent(offset_, other.offset_);
  }

  bool IsHint() const {
    DCHECK(color_ || offset_);
    return !color_;
  }

  bool IsCacheable() const;

  void Trace(Visitor*) const;

  Member<const CSSPrimitiveValue> offset_;  // percentage | length | angle
  Member<const CSSValue> color_;
};

}  // namespace cssvalue
}  // namespace blink

// We have to declare the VectorTraits specialization before CSSGradientValue
// declares its inline capacity vector below.
WTF_ALLOW_MOVE_AND_INIT_WITH_MEM_FUNCTIONS(
    blink::cssvalue::CSSGradientColorStop)

namespace blink {
namespace cssvalue {

class CSSGradientValue : public CSSImageGeneratorValue {
 public:
  scoped_refptr<Image> GetImage(const ImageResourceObserver&,
                                const Document&,
                                const ComputedStyle&,
                                const gfx::SizeF&) const;

  void AddStop(const CSSGradientColorStop& stop) {
    stops_.push_back(stop);
    is_cacheable_ = is_cacheable_ && stop.IsCacheable();
  }

  size_t StopCount() const { return stops_.size(); }

  bool IsRepeating() const { return repeating_; }

  CSSGradientType GradientType() const { return gradient_type_; }

  bool KnownToBeOpaque(const Document&, const ComputedStyle&) const;
  CSSGradientValue* ComputedCSSValue(const ComputedStyle&,
                                     bool allow_visited_style) const;

  Vector<Color> GetStopColors(const Document&, const ComputedStyle&) const;

  void TraceAfterDispatch(blink::Visitor*) const;

  struct GradientDesc;

 protected:
  CSSGradientValue(ClassType class_type,
                   CSSGradientRepeat repeat,
                   CSSGradientType gradient_type)
      : CSSImageGeneratorValue(class_type),
        gradient_type_(gradient_type),
        repeating_(repeat == kRepeating),
        is_cacheable_(true) {}

  void AddStops(GradientDesc&,
                const CSSToLengthConversionData&,
                const Document&,
                const ComputedStyle&) const;
  void AddDeprecatedStops(GradientDesc&,
                          const Document&,
                          const ComputedStyle&) const;
  void AddComputedStops(const ComputedStyle&,
                        bool allow_visited_style,
                        const HeapVector<CSSGradientColorStop, 2>& stops);

  void AppendCSSTextForColorStops(StringBuilder&,
                                  bool requires_separator) const;
  void AppendCSSTextForDeprecatedColorStops(StringBuilder&) const;

  // Stops
  HeapVector<CSSGradientColorStop, 2> stops_;
  CSSGradientType gradient_type_;
  bool repeating_ : 1;
  bool is_cacheable_ : 1;
};

class CSSLinearGradientValue final : public CSSGradientValue {
 public:
  CSSLinearGradientValue(const CSSValue* first_x,
                         const CSSValue* first_y,
                         const CSSValue* second_x,
                         const CSSValue* second_y,
                         const CSSPrimitiveValue* angle,
                         CSSGradientRepeat repeat,
                         CSSGradientType gradient_type = kCSSLinearGradient)
      : CSSGradientValue(kLinearGradientClass, repeat, gradient_type),
        first_x_(first_x),
        first_y_(first_y),
        second_x_(second_x),
        second_y_(second_y),
        angle_(angle) {}

  String CustomCSSText() const;

  // Create the gradient for a given size.
  scoped_refptr<Gradient> CreateGradient(const CSSToLengthConversionData&,
                                         const gfx::SizeF&,
                                         const Document&,
                                         const ComputedStyle&) const;

  bool Equals(const CSSLinearGradientValue&) const;

  CSSLinearGradientValue* ComputedCSSValue(const ComputedStyle&,
                                           bool allow_visited_style) const;

  bool IsUsingCurrentColor() const;

  void TraceAfterDispatch(blink::Visitor*) const;

 private:
  // Any of these may be null.
  Member<const CSSValue> first_x_;
  Member<const CSSValue> first_y_;
  Member<const CSSValue> second_x_;
  Member<const CSSValue> second_y_;
  Member<const CSSPrimitiveValue> angle_;
};

class CORE_EXPORT CSSRadialGradientValue final : public CSSGradientValue {
 public:
  CSSRadialGradientValue(const CSSValue* first_x,
                         const CSSValue* first_y,
                         const CSSPrimitiveValue* first_radius,
                         const CSSValue* second_x,
                         const CSSValue* second_y,
                         const CSSPrimitiveValue* second_radius,
                         const CSSIdentifierValue* shape,
                         const CSSIdentifierValue* sizing_behavior,
                         const CSSPrimitiveValue* horizontal_size,
                         const CSSPrimitiveValue* vertical_size,
                         CSSGradientRepeat repeat,
                         CSSGradientType gradient_type = kCSSRadialGradient)
      : CSSGradientValue(kRadialGradientClass, repeat, gradient_type),
        first_x_(first_x),
        first_y_(first_y),
        second_x_(second_x),
        second_y_(second_y),
        first_radius_(first_radius),
        second_radius_(second_radius),
        shape_(shape),
        sizing_behavior_(sizing_behavior),
        end_horizontal_size_(horizontal_size),
        end_vertical_size_(vertical_size) {}

  CSSRadialGradientValue(const CSSValue* first_x,
                         const CSSValue* first_y,
                         const CSSPrimitiveValue* first_radius,
                         const CSSValue* second_x,
                         const CSSValue* second_y,
                         const CSSPrimitiveValue* second_radius,
                         CSSGradientRepeat repeat,
                         CSSGradientType gradient_type = kCSSRadialGradient)
      : CSSGradientValue(kRadialGradientClass, repeat, gradient_type),
        first_x_(first_x),
        first_y_(first_y),
        second_x_(second_x),
        second_y_(second_y),
        first_radius_(first_radius),
        second_radius_(second_radius),
        shape_(nullptr),
        sizing_behavior_(nullptr),
        end_horizontal_size_(nullptr),
        end_vertical_size_(nullptr) {}

  CSSRadialGradientValue(const CSSValue* center_x,
                         const CSSValue* center_y,
                         const CSSIdentifierValue* shape,
                         const CSSIdentifierValue* sizing_behavior,
                         const CSSPrimitiveValue* horizontal_size,
                         const CSSPrimitiveValue* vertical_size,
                         CSSGradientRepeat repeat,
                         CSSGradientType gradient_type)
      : CSSGradientValue(kRadialGradientClass, repeat, gradient_type),
        first_x_(center_x),
        first_y_(center_y),
        second_x_(center_x),
        second_y_(center_y),
        first_radius_(nullptr),
        second_radius_(nullptr),
        shape_(shape),
        sizing_behavior_(sizing_behavior),
        end_horizontal_size_(horizontal_size),
        end_vertical_size_(vertical_size) {}

  String CustomCSSText() const;

  void SetShape(CSSIdentifierValue* val) { shape_ = val; }
  void SetSizingBehavior(CSSIdentifierValue* val) { sizing_behavior_ = val; }

  void SetEndHorizontalSize(CSSPrimitiveValue* val) {
    end_horizontal_size_ = val;
  }
  void SetEndVerticalSize(CSSPrimitiveValue* val) { end_vertical_size_ = val; }

  // Create the gradient for a given size.
  scoped_refptr<Gradient> CreateGradient(const CSSToLengthConversionData&,
                                         const gfx::SizeF&,
                                         const Document&,
                                         const ComputedStyle&) const;

  bool Equals(const CSSRadialGradientValue&) const;

  CSSRadialGradientValue* ComputedCSSValue(const ComputedStyle&,
                                           bool allow_visited_style) const;

  bool IsUsingCurrentColor() const;

  void TraceAfterDispatch(blink::Visitor*) const;

 private:
  // Any of these may be null.
  Member<const CSSValue> first_x_;
  Member<const CSSValue> first_y_;
  Member<const CSSValue> second_x_;
  Member<const CSSValue> second_y_;

  // These may be null for non-deprecated gradients.
  Member<const CSSPrimitiveValue> first_radius_;
  Member<const CSSPrimitiveValue> second_radius_;

  // The below are only used for non-deprecated gradients. Any of them may be
  // null.
  Member<const CSSIdentifierValue> shape_;
  Member<const CSSIdentifierValue> sizing_behavior_;

  Member<const CSSPrimitiveValue> end_horizontal_size_;
  Member<const CSSPrimitiveValue> end_vertical_size_;
};

class CSSConicGradientValue final : public CSSGradientValue {
 public:
  CSSConicGradientValue(const CSSValue* x,
                        const CSSValue* y,
                        const CSSPrimitiveValue* from_angle,
                        CSSGradientRepeat repeat)
      : CSSGradientValue(kConicGradientClass, repeat, kCSSConicGradient),
        x_(x),
        y_(y),
        from_angle_(from_angle) {}

  String CustomCSSText() const;

  // Create the gradient for a given size.
  scoped_refptr<Gradient> CreateGradient(const CSSToLengthConversionData&,
                                         const gfx::SizeF&,
                                         const Document&,
                                         const ComputedStyle&) const;

  bool Equals(const CSSConicGradientValue&) const;

  CSSConicGradientValue* ComputedCSSValue(const ComputedStyle&,
                                          bool allow_visited_style) const;

  bool IsUsingCurrentColor() const;

  void TraceAfterDispatch(blink::Visitor*) const;

 private:
  // Any of these may be null.
  Member<const CSSValue> x_;
  Member<const CSSValue> y_;
  Member<const CSSPrimitiveValue> from_angle_;
};

}  // namespace cssvalue

template <>
struct DowncastTraits<cssvalue::CSSGradientValue> {
  static bool AllowFrom(const CSSValue& value) {
    return value.IsGradientValue();
  }
};

template <>
struct DowncastTraits<cssvalue::CSSLinearGradientValue> {
  static bool AllowFrom(const CSSValue& value) {
    return value.IsLinearGradientValue();
  }
};

template <>
struct DowncastTraits<cssvalue::CSSRadialGradientValue> {
  static bool AllowFrom(const CSSValue& value) {
    return value.IsRadialGradientValue();
  }
};

template <>
struct DowncastTraits<cssvalue::CSSConicGradientValue> {
  static bool AllowFrom(const CSSValue& value) {
    return value.IsConicGradientValue();
  }
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_GRADIENT_VALUE_H_


text:
module EXEL
  # Middleware is code configured to run around each processor execution. Custom middleware can be added as follows:
  #
  #   EXEL.configure do |config|
  #     config.middleware.add(MyMiddleware)
  #     config.middleware.add(AnotherMiddleware, 'constructor arg')
  #   end
  #
  # Middleware can be any class that implements a +call+ method that includes a call to +yield+:
  #
  #   class MyMiddleware
  #     def call(processor, context, args)
  #       puts 'before process'
  #       yield
  #       puts 'after process'
  #     end
  #   end
  #
  # The +call+ method will be passed the class of the processor that will be executed, the current context, and any args
  # that were passed to the processor in the job definition.
  module Middleware
    # Chain of middleware to be invoked in sequence around each processor execution.
    class Chain
      attr_reader :entries

      Entry = Struct.new(:klass, :args)

      def initialize
        @entries = []
      end

      # Adds a middleware class to the chain. If it is already in the chain it will be removed and added to the end.
      # Any additional arguments will be passed to +new+ when the middleware is created.
      def add(klass, *args)
        remove(klass)
        @entries << Entry.new(klass, args)
      end

      # Removes a middleware class from the chain.
      def remove(klass)
        @entries.delete_if { |entry| entry.klass == klass }
      end

      # Returns true if the given class is in the chain.
      def include?(klass)
        @entries.any? { |entry| entry.klass == klass }
      end

      # Calls each middleware in the chain.
      def invoke(*args)
        chain = @entries.map { |entry| entry.klass.new(*entry.args) }

        traverse_chain = lambda do
          if chain.empty?
            yield
          else
            chain.shift.call(*args, &traverse_chain)
          end
        end

        traverse_chain.call
      end
    end
  end
end


text:
@protocol SaveCardInfoBarViewDelegate;
@class SaveCardMessageWithLinks;

// An infobar for saving credit cards. It features a header section including
// an optional leading icon, followed by an optional message, followed by an
// optional close button. Below that, there is an optional description. In the
// next section, credit card details appear including the issuer network icon,
// the card's label, and the card's sublabel. In the following section, optional
// legal messages appear. The bottom section is the footer which contains a
// an optional confirm button and an optional cancel button.
@interface SaveCardInfoBarView : UIView

@property(nonatomic, weak) id<SaveCardInfoBarViewDelegate> delegate;

@property(nonatomic, strong) UIImage* icon;

@property(nonatomic, strong) UIImage* googlePayIcon;

@property(nonatomic, strong) SaveCardMessageWithLinks* message;

@property(nonatomic, strong) UIImage* closeButtonImage;

@property(nonatomic, copy) NSString* description;

@property(nonatomic, strong) UIImage* cardIssuerIcon;

@property(nonatomic, copy) NSString* cardLabel;

@property(nonatomic, copy) NSString* cardSublabel;

@property(nonatomic, strong) NSArray<SaveCardMessageWithLinks*>* legalMessages;

@property(nonatomic, copy) NSString* cancelButtonTitle;

@property(nonatomic, copy) NSString* confirmButtonTitle;

@end

#endif  // IOS_CHROME_BROWSER_UI_AUTOFILL_SAVE_CARD_INFOBAR_VIEW_H_


text:
Automatron determines whether a runbook action should be performed based on the results of a health check. There are two types of health checks within Automatron.  **Arbitrary shell commands** and **Plugin executables**. In this guide we will walk through defining two health checks, one of each type.

The below runbook is a sample that this guide will be based on.

```yaml+jinja
name: Check NGINX
schedule: "*/2 * * * *"
checks:
  nginx_is_running:
    execute_from: target
    type: cmd
    cmd: service nginx status
  port_443_is_up:
    execute_from: target
    type: plugin
    plugin: network/tcp_connect.py
    args: --host=localhost --port 443
actions:
  restart_nginx:
    execute_from: target
    trigger: 2
    frequency: 300
    call_on:
      - WARNING
      - CRITICAL
      - UNKNOWN
    type: cmd
    cmd: service nginx restart
  remove_from_dns:
    execute_from: remote
    trigger: 0
    frequency: 0
    call_on:
      - WARNING
      - CRITICAL
      - UNKNOWN
    type: plugin
    plugin: cloudflare/dns.py
    args: remove test@example.com apikey123 example.com --content 10.0.0.1
```

In the above example, there are two health checks defined `nginx_is_running` and `port_443_is_up`. In the below section we will break down each of these health checks to better understand how health checks are defined.

## A command based health check

Command based health checks are one of the simplest concepts in Automatron. This type of health check allows users to define a command that is executed to determine the health status of a target.

This is accomplished by Automatron simply logging into the target system over SSH and executing the defined command. The exit code of the executed command is then used to determine the status of the health check.

The below sample is the `nginx_is_running` command based health check.

```yaml+jinja
  nginx_is_running:
    execute_from: target
    type: cmd
    cmd: service nginx status
```

In this sample we can see that there are 3 values required for command based health checks. Those values are `execute_from`, `type`, and `cmd`. Let's go ahead and break down these values to gain a better understanding of what they mean and tell Automatron to do.

### Execute from

The `execute_from` field is used to specify where to run the health check. Acceptable values for this field are `target` which is used to execute the health check on the monitored node itself and `remote`. The `remote` setting will tell Automatron to execute the health check from the system running Automatron itself.

In our case the command we wish to execute can only be executed from the monitored system itself, as such the value of this field will be `target`.

### Type

The `type` field is used to specify what type of health check this check is. Acceptable values are `cmd` or `plugin`. In this case, since we are defining a command based health check our value is set to `cmd`.

### Command

The `cmd` field is used to specify the shell command to execute. In our example the command is simply `service nginx status`. However, this field can support much more complicated commands such as the below example.

```yaml+jinja
cmd: /usr/bin/curl -Lw "Response %{http_code}\\n" http://10.0.0.1 -o /dev/null | egrep "Response [200|301]"
```

It is not uncommon to use multiple commands connected with output redirection and conditionals within a runbook.

## A plugin based health check

Plugin based health checks are similar to Command Based health checks in that the exit code is used to determine status. Where these checks differ is that Automatron will copy an executable to the target system and then execute that executable with the specified arguments.

Below is an example Plugin health check.

```yaml+jinja
port_443_is_up:
  execute_from: target
  type: plugin
  plugin: network/tcp_connect.py
  args: --host=localhost --port 443
```

Plugin type health checks have 4 configuration items `execute_from`, `type`, `plugin` & `args`. Let's go ahead and break down these values to gain a better understanding of what they mean and tell Automatron to do.

### Execute from & Type

The `execute_from` and `type` fields are common fields for every runbook. The way they are applied for plugin health checks is the same as the way they are applied for command based health checks. As such we will skip repeating these fields in this section.

### Plugin

The `plugin` field is used to specify the location of the plugin executable. This is a relative file path starting from the value of the `plugin_path` parameter located within the `config/config.yml` configuration file.

For example, a plugin located at `/path/to/plugins/checks/mycheck/mycheck.pl` would require the value of `mycheck/mycheck.pl`.

### Plugin Arguments

The `args` field is used to specify the arguments to provide the plugin executable. In the example above the plugin will be executed as follows by Automatron

```sh
$ /path/to/plugins/checks/network/tcp_connect.py --host=localhost --port 443
```

## Using Exit Codes to relay health check status

Automatron follows the **Nagios** model for health check exit codes. When a health check is executed the exit code is used to inform Automatron of the results. The below list is a map of acceptable exit codes and how they relate to Automatron health check status.

  * `OK`: Requires a successful exit code of `0`
  * `WARNING`: Is indicated by an exit code of `1`
  * `CRITICAL`: Is indicated by an exit code of `2`
  * `UNKNOWN`: Is indicated by any other exit code

!!! tip
    Since Automatron supports the **Nagios** exit code strategy most Nagios compliant health checks can also be used with Automatron.


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
* Setting controllers class
 *
 * @package     SYSCMS
 * @subpackage  Controllers
 * @category    Controllers
 * @author      Sistiandy Syahbana nugraha <sistiandy.web.id>
 */

class Setting extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        if ($this->session->userdata('logged') == NULL) {
            header("Location:" . site_url('admin/auth/login') . "?location=" . urlencode($_SERVER['REQUEST_URI']));
        }
    }

    public function index() {
        $this->load->model('Setting_model');
        $this->load->library('form_validation');
        $this->form_validation->set_rules('class_name', 'Class Name', 'trim|required|xss_clean');
        $this->form_validation->set_rules('class_description', 'Class Description', 'trim|required|xss_clean');
        $this->form_validation->set_rules('class_cash', 'Class Cash', 'trim|required|xss_clean');
        $this->form_validation->set_error_delimiters('
', '
');
        if ($_POST AND $this->form_validation->run() == TRUE) {

            $param['class_name'] = $this->input->post('class_name');
            $param['class_description'] = $this->input->post('class_description');
            $param['class_cash'] = $this->input->post('class_cash');
            $this->Setting_model->save($param);
            $this->session->set_flashdata('success', ' Sunting pengaturan berhasil');
            redirect('admin/setting');
        } else {
            $data['title'] = 'Pengaturan';
            $data['class_name'] = $this->Setting_model->get(array('id' => CLASS_NAME));
            $data['class_description'] = $this->Setting_model->get(array('id' => CLASS_DESC));
            $data['class_cash'] = $this->Setting_model->get(array('id' => CLASS_CASH));
            $data['main'] = 'admin/setting/setting_list';
            $this->load->view('admin/layout', $data);
        }
    }

}

/* End of file dashboard.php */
/* Location: ./application/controllers/dashboard.php */


text:
package com.baidubce.services.lss.model;

import com.baidubce.auth.BceCredentials;
import com.baidubce.model.AbstractBceRequest;

/**
 * Created by wuyafei on 16/10/18.
 */
public class GetOneDomainStatisticsRequest extends AbstractBceRequest  {

    private String domain = null;

    private String startTime = null;

    private String endTime = null;

    private String timeInterval = null;

    @Override
    public GetOneDomainStatisticsRequest withRequestCredentials(BceCredentials credentials) {
        this.setRequestCredentials(credentials);
        return this;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public GetOneDomainStatisticsRequest withDomain(String domain) {
        this.domain = domain;
        return this;
    }

    public String getStartTime() {
        return startTime;
    }

    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    public GetOneDomainStatisticsRequest withStartTime(String startTime) {
        this.startTime = startTime;
        return this;
    }

    public String getEndTime() {
        return endTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    public GetOneDomainStatisticsRequest withEndTime(String endTime) {
        this.endTime = endTime;
        return this;
    }

    public String getTimeInterval() {
        return timeInterval;
    }

    public void setTimeInterval(String interval) {
        this.timeInterval = interval;
    }

    public GetOneDomainStatisticsRequest withTimeInterval(String interval) {
        this.timeInterval = interval;
        return this;
    }

    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("class GetOneDomainStatisticsRequest {\n");
        sb.append("    domain: ").append(domain).append("\n");
        sb.append("    startTime: ").append(startTime).append("\n");
        sb.append("    endTime: ").append(endTime).append("\n");
        sb.append("    timeInterval: ").append(timeInterval).append("\n");
        sb.append("}\n");
        return sb.toString();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lichen obliteratus Pers.

### Remarks
null


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Resources;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

// This is the assembly-level GUID, and the GUID for the TypeLib associated with
// this assembly.  We should specify this explicitly, as opposed to letting
// tlbexp just pick whatever it wants.
[assembly: GuidAttribute("E3D4D3B9-944C-407b-A82E-B19719EA7FB3")]

[assembly: InternalsVisibleTo("Microsoft.Build.Tasks.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: InternalsVisibleTo("Microsoft.Build.Tasks.Whidbey.Unittest, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]

// This will enable passing the SafeDirectories flag to any P/Invoke calls/implementations within the assembly,
// so that we don't run into known security issues with loading libraries from unsafe locations
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]

// Needed for the "hub-and-spoke model to locate and retrieve localized resources": https://msdn.microsoft.com/en-us/library/21a15yht(v=vs.110).aspx
// We want "en" to require a satellite assembly for debug builds in order to flush out localization
// issues, but we want release builds to work without it. Also, .net core does not have resource fallbacks
#if (DEBUG && !RUNTIME_TYPE_NETCORE)
[assembly: NeutralResourcesLanguage("en", UltimateResourceFallbackLocation.Satellite)]
#else
[assembly: NeutralResourcesLanguage("en")]
#endif

[assembly: ComVisible(false)]

[assembly: CLSCompliant(true)]


text:
package org.jbehave.core.embedder;

import java.io.File;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;

import org.jbehave.core.failures.BatchFailures;
import org.jbehave.core.model.Meta;
import org.jbehave.core.model.Scenario;
import org.jbehave.core.model.Story;
import org.jbehave.core.model.StoryDuration;
import org.jbehave.core.model.StoryMaps;
import org.jbehave.core.reporters.ReportsCount;

/**
 * Decorator of EmbedderMonitor that delegates to an injected instance and
 * allows classes extending it to override only the methods that are needed.
 */
public class EmbedderMonitorDecorator implements EmbedderMonitor {

    private final EmbedderMonitor delegate;

    public EmbedderMonitorDecorator(EmbedderMonitor delegate) {
        this.delegate = delegate;
    }

    public void runningEmbeddable(String name) {
        delegate.runningEmbeddable(name);
    }

    public void embeddableFailed(String name, Throwable cause) {
        delegate.embeddableFailed(name, cause);
    }

    public void embeddableNotConfigurable(String name) {
        delegate.embeddableNotConfigurable(name);
    }

    public void embeddablesSkipped(List<String> classNames) {
        delegate.embeddablesSkipped(classNames);
    }

    public void metaNotAllowed(Meta meta, MetaFilter filter) {
        delegate.metaNotAllowed(meta, filter);
    }

    public void runningStory(String path) {
        delegate.runningStory(path);
    }

    public void storyFailed(String path, Throwable cause) {
        delegate.storyFailed(path, cause);
    }

    public void storiesSkipped(List<String> storyPaths) {
        delegate.storiesSkipped(storyPaths);
    }

    public void storiesNotAllowed(List<Story> notAllowed, MetaFilter filter) {
        delegate.storiesNotAllowed(notAllowed, filter);
    }

    public void storiesNotAllowed(List<Story> stories, MetaFilter filter, boolean verbose) {
        delegate.storiesNotAllowed(stories, filter, verbose);
     }

	public void scenarioNotAllowed(Scenario scenario, MetaFilter filter) {
		delegate.scenarioNotAllowed(scenario, filter);
	}

    public void batchFailed(BatchFailures failures) {
        delegate.batchFailed(failures);
    }

    public void beforeOrAfterStoriesFailed() {
        delegate.beforeOrAfterStoriesFailed();
    }

    public void generatingReportsView(File outputDirectory, List<String> formats, Properties viewProperties) {
        delegate.generatingReportsView(outputDirectory, formats, viewProperties);
    }

    public void reportsViewGenerationFailed(File outputDirectory, List<String> formats, Properties viewProperties,
            Throwable cause) {
        delegate.reportsViewGenerationFailed(outputDirectory, formats, viewProperties, cause);
    }

    public void reportsViewGenerated(ReportsCount count) {
        delegate.reportsViewGenerated(count);
    }

    public void reportsViewFailures(ReportsCount count) {
        delegate.reportsViewFailures(count);
    }

    public void reportsViewNotGenerated() {
        delegate.reportsViewNotGenerated();
    }

    public void runningWithAnnotatedEmbedderRunner(String className) {
        delegate.runningWithAnnotatedEmbedderRunner(className);
    }

    public void annotatedInstanceNotOfType(Object annotatedInstance, Class<?> type) {
        delegate.annotatedInstanceNotOfType(annotatedInstance, type);
    }

    public void mappingStory(String storyPath, List<String> metaFilters) {
        delegate.mappingStory(storyPath, metaFilters);
    }

    public void generatingMapsView(File outputDirectory, StoryMaps storyMaps, Properties viewProperties) {
        delegate.generatingMapsView(outputDirectory, storyMaps, viewProperties);
    }

    public void mapsViewGenerationFailed(File outputDirectory, StoryMaps storyMaps, Properties viewProperties,
            Throwable cause) {
        delegate.mapsViewGenerationFailed(outputDirectory, storyMaps, viewProperties, cause);
    }

    public void generatingNavigatorView(File outputDirectory, Properties viewResources) {
        delegate.generatingNavigatorView(outputDirectory, viewResources);
    }

    public void navigatorViewGenerationFailed(File outputDirectory, Properties viewResources, Throwable cause) {
        delegate.navigatorViewGenerationFailed(outputDirectory, viewResources, cause);
    }

    public void navigatorViewNotGenerated() {
        delegate.navigatorViewNotGenerated();
    }

    public void processingSystemProperties(Properties properties) {
        delegate.processingSystemProperties(properties);
    }

    public void systemPropertySet(String name, String value) {
        delegate.systemPropertySet(name, value);
    }

    public void storyTimeout(Story story, StoryDuration storyDuration) {
        delegate.storyTimeout(story, storyDuration);
    }

    public void usingThreads(int threads) {
        delegate.usingThreads(threads);
    }

    public void usingExecutorService(ExecutorService executorService) {
        delegate.usingExecutorService(executorService);
    }

    public void usingControls(EmbedderControls embedderControls) {
        delegate.usingControls(embedderControls);
    }

	public void invalidTimeoutFormat(String path) {
		delegate.invalidTimeoutFormat(path);
	}

	public void usingTimeout(String path, long timeout) {
		delegate.usingTimeout(path, timeout);
	}

}


text:
"""module docstring"""

# imports
import sys
import os
import sqlalchemy
import datetime

sys.path.append(os.path.dirname(os.getcwd()))  # Add .. to path
from backend.ldaplogin import (get_member_with_real_name,
        DuplicateNamesException, PersonNotFoundException)
from backend import connect
from backend.orm import *

import common

# constants
# exception classes
# interface functions
# classes
# internal functions & classes

def main():
    SessionMaker = connect.connect('members',
        'members', 'localhost', 'members')
    session= SessionMaker()

    phuxes = common.get_members_with_current_membership_id(session, "Phux")

    departmentdict = {}
    for phux in phuxes:
        try:
            departmentdict.setdefault(phux.department[0].department.name_fld,
                    []).append(phux.contactinfo.email_fld)
        except IndexError: # No phuxes
            continue

    for department, emails in departmentdict.items():
        print(department)
        for email in emails:
            print(email)
        print()

if __name__ == '__main__':
    status = main()
    sys.exit(status)