text:
package ameba.container.server;

import ameba.exception.ConfigErrorException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;

import static ameba.util.IOUtils.readByteArrayFromResource;

/**
 *
Connector class.

 *
 * @author icode
 * @since 0.1.6e
 */
public class Connector {
    /**
     * Constant CONNECTOR_CONF_PREFIX="connector."
     */
    public static final String CONNECTOR_CONF_PREFIX = "connector.";
    public static final String DEFAULT_NETWORK_HOST = "0.0.0.0";
    private static final Logger logger = LoggerFactory.getLogger(Connector.class);
    protected URI httpServerBaseUri;
    protected String host;
    protected String name;
    protected boolean ajpEnabled;
    protected boolean secureEnabled;
    protected Integer port;
    protected String sslProtocol;
    protected boolean sslClientMode;
    protected boolean sslNeedClientAuth;
    protected boolean sslWantClientAuth;
    protected String sslKeyPassword;
    protected byte[] sslKeyStoreFile;
    protected String sslKeyStoreType;
    protected String sslKeyStorePassword;
    protected String sslKeyStoreProvider;
    protected String sslKeyManagerFactoryAlgorithm;
    protected String sslTrustPassword;
    protected byte[] sslTrustStoreFile;
    protected String sslTrustStorePassword;
    protected String sslTrustStoreType;
    protected String sslTrustStoreProvider;
    protected String sslTrustManagerFactoryAlgorithm;
    protected boolean sslConfigReady;
    protected Map<String, String> rawProperties;

    /**
     *
Constructor for Connector.

     */
    protected Connector() {
    }

    /**
     *
createDefault.

     *
     * @param properties a {@link java.util.Map} object.
     * @return a {@link ameba.container.server.Connector} object.
     */
    public static Connector createDefault(Map<String, String> properties) {
        Connector.Builder builder = Connector.Builder.create()
                .rawProperties(properties)
                .secureEnabled(Boolean.parseBoolean(properties.get("ssl.enabled")))
                .sslProtocol(properties.get("ssl.protocol"))
                .sslClientMode(Boolean.parseBoolean(properties.get("ssl.clientMode")))
                .sslNeedClientAuth(Boolean.parseBoolean(properties.get("ssl.needClientAuth")))
                .sslWantClientAuth(Boolean.parseBoolean(properties.get("ssl.wantClientAuth")))
                .sslKeyManagerFactoryAlgorithm(properties.get("ssl.key.manager.factory.algorithm"))
                .sslKeyPassword(properties.get("ssl.key.password"))
                .sslKeyStoreProvider(properties.get("ssl.key.store.provider"))
                .sslKeyStoreType(properties.get("ssl.key.store.type"))
                .sslKeyStorePassword(properties.get("ssl.key.store.password"))
                .sslTrustManagerFactoryAlgorithm(properties.get("ssl.Trust.manager.factory.algorithm"))
                .sslTrustPassword(properties.get("ssl.trust.password"))
                .sslTrustStoreProvider(properties.get("ssl.trust.store.provider"))
                .sslTrustStoreType(properties.get("ssl.trust.store.type"))
                .sslTrustStorePassword(properties.get("ssl.trust.store.password"))
                .ajpEnabled(Boolean.parseBoolean(properties.get("ajp.enabled")))
                .host(StringUtils.defaultIfBlank(properties.get("host"), "0.0.0.0"))
                .port(Integer.valueOf(StringUtils.defaultIfBlank(properties.get("port"), "80")))
                .name(properties.get("name"));

        String keyStoreFile = properties.get("ssl.key.store.file");
        if (StringUtils.isNotBlank(keyStoreFile))
            try {
                builder.sslKeyStoreFile(readByteArrayFromResource(keyStoreFile));
            } catch (IOException e) {
                logger.error("读取sslKeyStoreFile出错", e);
            }

        String trustStoreFile = properties.get("ssl.trust.store.file");
        if (StringUtils.isNotBlank(trustStoreFile))
            try {
                builder.sslTrustStoreFile(readByteArrayFromResource(trustStoreFile));
            } catch (IOException e) {
                logger.error("读取sslTrustStoreFile出错", e);
            }

        return builder.build();
    }

    /**
     *
createDefaultConnectors.

     *
     * @param properties a {@link java.util.Map} object.
     * @return a {@link java.util.List} object.
     */
    public static List<Connector> createDefaultConnectors(Map<String, Object> properties) {
        List<Connector> connectors = Lists.newArrayList();
        Map<String, Map<String, String>> propertiesMap = Maps.newLinkedHashMap();
        for (String key : properties.keySet()) {
            if (key.startsWith(Connector.CONNECTOR_CONF_PREFIX)) {
                String oKey = key;
                key = key.substring(Connector.CONNECTOR_CONF_PREFIX.length());
                int index = key.indexOf(".");
                if (index == -1) {
                    throw new ConfigErrorException("connector configure error, format connector.{connectorName}.{property}");
                }
                String name = key.substring(0, index);
                Map<String, String> pr = propertiesMap.get(name);
                if (pr == null) {
                    pr = Maps.newLinkedHashMap();
                    propertiesMap.put(name, pr);
                    pr.put("name", name);
                }
                pr.put(key.substring(index + 1), String.valueOf(properties.get(oKey)));
            }
        }

        for (Map<String, String> prop : propertiesMap.values()) {
            connectors.add(createDefault(prop));
        }
        return connectors;
    }

    /**
     *
Getter for the field host.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getHost() {
        return host;
    }

    /**
     *
Getter for the field port.

     *
     * @return a {@link java.lang.Integer} object.
     */
    public Integer getPort() {
        return port;
    }

    /**
     *
Getter for the field httpServerBaseUri.

     *
     * @return a {@link java.net.URI} object.
     */
    public URI getHttpServerBaseUri() {
        return httpServerBaseUri;
    }

    /**
     *
isSecureEnabled.

     *
     * @return a boolean.
     */
    public boolean isSecureEnabled() {
        return secureEnabled;
    }

    /**
     *
isSslClientMode.

     *
     * @return a boolean.
     */
    public boolean isSslClientMode() {
        return sslClientMode;
    }

    /**
     *
isSslNeedClientAuth.

     *
     * @return a boolean.
     */
    public boolean isSslNeedClientAuth() {
        return sslNeedClientAuth;
    }

    /**
     *
isSslWantClientAuth.

     *
     * @return a boolean.
     */
    public boolean isSslWantClientAuth() {
        return sslWantClientAuth;
    }

    /**
     *
Getter for the field sslKeyPassword.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslKeyPassword() {
        return sslKeyPassword;
    }

    /**
     *
Getter for the field sslKeyStoreFile.

     *
     * @return an array of byte.
     */
    public byte[] getSslKeyStoreFile() {
        return sslKeyStoreFile;
    }

    /**
     *
Getter for the field sslKeyStoreType.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslKeyStoreType() {
        return sslKeyStoreType;
    }

    /**
     *
Getter for the field sslKeyStorePassword.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslKeyStorePassword() {
        return sslKeyStorePassword;
    }

    /**
     *
Getter for the field sslTrustPassword.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslTrustPassword() {
        return sslTrustPassword;
    }

    /**
     *
Getter for the field sslTrustStoreFile.

     *
     * @return an array of byte.
     */
    public byte[] getSslTrustStoreFile() {
        return sslTrustStoreFile;
    }

    /**
     *
Getter for the field sslTrustStorePassword.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslTrustStorePassword() {
        return sslTrustStorePassword;
    }

    /**
     *
Getter for the field sslTrustStoreType.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslTrustStoreType() {
        return sslTrustStoreType;
    }

    /**
     *
isSslConfigReady.

     *
     * @return a boolean.
     */
    public boolean isSslConfigReady() {
        return sslConfigReady;
    }

    /**
     *
Getter for the field sslProtocol.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslProtocol() {
        return sslProtocol;
    }

    /**
     *
Getter for the field sslKeyStoreProvider.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslKeyStoreProvider() {
        return sslKeyStoreProvider;
    }

    /**
     *
Getter for the field sslTrustStoreProvider.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslTrustStoreProvider() {
        return sslTrustStoreProvider;
    }

    /**
     *
Getter for the field sslKeyManagerFactoryAlgorithm.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslKeyManagerFactoryAlgorithm() {
        return sslKeyManagerFactoryAlgorithm;
    }

    /**
     *
Getter for the field sslTrustManagerFactoryAlgorithm.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getSslTrustManagerFactoryAlgorithm() {
        return sslTrustManagerFactoryAlgorithm;
    }

    /**
     *
isAjpEnabled.

     *
     * @return a boolean.
     */
    public boolean isAjpEnabled() {
        return ajpEnabled;
    }

    /**
     *
Getter for the field name.

     *
     * @return a {@link java.lang.String} object.
     */
    public String getName() {
        return name;
    }

    /**
     *
Getter for the field rawProperties.

     *
     * @return a {@link java.util.Map} object.
     */
    public Map<String, String> getRawProperties() {
        return rawProperties;
    }

    public static class Builder {
        Connector connector;

        private Builder(Connector connector) {
            this.connector = connector;
        }

        private Builder() {
            this(new Connector());
        }

        public static Builder from(Connector connector) {
            return new Builder(connector);
        }

        public static Builder create() {
            return new Builder();
        }

        public String getHost() {
            return connector.getHost();
        }

        public URI getHttpServerBaseUri() {
            return connector.getHttpServerBaseUri();
        }

        public boolean isSslWantClientAuth() {
            return connector.isSslWantClientAuth();
        }

        public String getSslTrustStoreProvider() {
            return connector.getSslTrustStoreProvider();
        }

        public String getSslKeyStoreProvider() {
            return connector.getSslKeyStoreProvider();
        }

        public String getSslTrustManagerFactoryAlgorithm() {
            return connector.getSslTrustManagerFactoryAlgorithm();
        }

        public String getSslProtocol() {
            return connector.getSslProtocol();
        }

        public boolean isAjpEnabled() {
            return connector.isAjpEnabled();
        }

        public Integer getPort() {
            return connector.getPort();
        }

        public boolean isSslClientMode() {
            return connector.isSslClientMode();
        }

        public byte[] getSslTrustStoreFile() {
            return connector.getSslTrustStoreFile();
        }

        public String getSslTrustStorePassword() {
            return connector.getSslTrustStorePassword();
        }

        public String getSslTrustPassword() {
            return connector.getSslTrustPassword();
        }

        public String getSslKeyStoreType() {
            return connector.getSslKeyStoreType();
        }

        public boolean isSslConfigReady() {
            return connector.isSslConfigReady();
        }

        public String getSslTrustStoreType() {
            return connector.getSslTrustStoreType();
        }

        public byte[] getSslKeyStoreFile() {
            return connector.getSslKeyStoreFile();
        }

        public String getSslKeyStorePassword() {
            return connector.getSslKeyStorePassword();
        }

        public String getSslKeyManagerFactoryAlgorithm() {
            return connector.getSslKeyManagerFactoryAlgorithm();
        }

        public boolean isSslNeedClientAuth() {
            return connector.isSslNeedClientAuth();
        }

        public boolean isSecureEnabled() {
            return connector.isSecureEnabled();
        }

        public String getSslKeyPassword() {
            return connector.getSslKeyPassword();
        }

        public Builder host(String host) {
            this.connector.host = host;
            return this;
        }

        public Builder ajpEnabled(boolean ajpEnabled) {
            connector.ajpEnabled = ajpEnabled;
            return this;
        }

        public Builder secureEnabled(boolean secureEnabled) {
            connector.secureEnabled = secureEnabled;
            return this;
        }

        public Builder port(Integer port) {
            connector.port = port;
            return this;
        }

        public Builder sslProtocol(String sslProtocol) {
            connector.sslProtocol = sslProtocol;
            return this;
        }

        public Builder sslClientMode(boolean sslClientMode) {
            connector.sslClientMode = sslClientMode;
            return this;
        }

        public Builder sslNeedClientAuth(boolean sslNeedClientAuth) {
            connector.sslNeedClientAuth = sslNeedClientAuth;
            return this;
        }

        public Builder sslWantClientAuth(boolean sslWantClientAuth) {
            connector.sslWantClientAuth = sslWantClientAuth;
            return this;
        }

        public Builder sslKeyPassword(String sslKeyPassword) {
            connector.sslKeyPassword = sslKeyPassword;
            return this;
        }

        public Builder sslKeyStoreFile(byte[] sslKeyStoreFile) {
            connector.sslKeyStoreFile = sslKeyStoreFile;
            return this;
        }

        public Builder sslKeyStoreType(String sslKeyStoreType) {
            connector.sslKeyStoreType = sslKeyStoreType;
            return this;
        }

        public Builder sslKeyStorePassword(String sslKeyStorePassword) {
            connector.sslKeyStorePassword = sslKeyStorePassword;
            return this;
        }

        public Builder sslKeyStoreProvider(String sslKeyStoreProvider) {
            connector.sslKeyStoreProvider = sslKeyStoreProvider;
            return this;
        }

        public Builder sslKeyManagerFactoryAlgorithm(String sslKeyManagerFactoryAlgorithm) {
            connector.sslKeyManagerFactoryAlgorithm = sslKeyManagerFactoryAlgorithm;
            return this;
        }

        public Builder sslTrustPassword(String sslTrustPassword) {
            connector.sslTrustPassword = sslTrustPassword;
            return this;
        }

        public void sslTrustStoreFile(byte[] sslTrustStoreFile) {
            connector.sslTrustStoreFile = sslTrustStoreFile;
        }

        public Builder sslTrustStorePassword(String sslTrustStorePassword) {
            connector.sslTrustStorePassword = sslTrustStorePassword;
            return this;
        }

        public Builder sslTrustStoreType(String sslTrustStoreType) {
            connector.sslTrustStoreType = sslTrustStoreType;
            return this;
        }

        public Builder sslTrustStoreProvider(String sslTrustStoreProvider) {
            connector.sslTrustStoreProvider = sslTrustStoreProvider;
            return this;
        }

        public Builder sslTrustManagerFactoryAlgorithm(String sslTrustManagerFactoryAlgorithm) {
            connector.sslTrustManagerFactoryAlgorithm = sslTrustManagerFactoryAlgorithm;
            return this;
        }

        public Builder name(String name) {
            connector.name = name;
            return this;
        }

        public Builder rawProperties(Map<String, String> properties) {
            connector.rawProperties = ImmutableMap.copyOf(properties);
            return this;
        }

        public Connector build() {
            if (connector.httpServerBaseUri == null) {
                //config server base uri
                connector.httpServerBaseUri = URI.create(
                        "http" + (isSecureEnabled() ? "s" : "") + "://"
                                + connector.getHost()
                                + ":" + connector.port + "/");
            }
            if (connector.secureEnabled && connector.sslKeyStoreFile != null &&
                    StringUtils.isNotBlank(connector.sslKeyPassword) &&
                    StringUtils.isNotBlank(connector.sslKeyStorePassword)) {
                connector.sslConfigReady = true;
            }
            return connector;
        }
    }
}


text:
<?php

abstract class PhabricatorFeedController extends PhabricatorController {

  public function buildStandardPageResponse($view, array $data) {
    $page = $this->buildStandardPageView();

    $page->setApplicationName(pht('Feed'));
    $page->setBaseURI('/feed/');
    $page->setTitle(idx($data, 'title'));
    $page->setGlyph("\xE2\x88\x9E");
    $page->appendChild($view);

    $response = new AphrontWebpageResponse();

    if (!empty($data['public'])) {
      $page->setFrameable(true);
      $page->setShowChrome(false);
      $response->setFrameable(true);
    }

    return $response->setContent($page->render());
  }

  protected function buildSideNavView() {
    $user = $this->getRequest()->getUser();

    $nav = new AphrontSideNavFilterView();
    $nav->setBaseURI(new PhutilURI($this->getApplicationURI()));

    id(new PhabricatorFeedSearchEngine())
      ->setViewer($user)
      ->addNavigationItems($nav->getMenu());

    $nav->selectFilter(null);

    return $nav;
  }

  public function buildApplicationMenu() {
    return $this->buildSideNavView()->getMenu();
  }

}

redpajama_set_name: RedPajamaGithub


text:
const test = require('ava');
const valuationApi = require('./../api/valuation');
const fundSquareInvestmentParser = require('./fundSquareInvestmentDetails');

test('Should return total assets value given a fund square site', t => valuationApi.getJuneOpportunityPriceSite()
    .then((site) => {
      const valuation = fundSquareInvestmentParser.parseFundSquareInvestmentDetailsSite(site);
      t.not(valuation.value, undefined, 'expected valuation to have total assets property');
    })
);


text:
package journal

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"sync"
	"time"

	sorting "sort"
	"strings"

	"github.com/SpectoLabs/hoverfly/core/handlers/v2"
	"github.com/SpectoLabs/hoverfly/core/matching"
	"github.com/SpectoLabs/hoverfly/core/models"
	"github.com/SpectoLabs/hoverfly/core/util"
	log "github.com/sirupsen/logrus"
)

const RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"

type JournalEntry struct {
	Request     *models.RequestDetails
	Response    *models.ResponseDetails
	Mode        string
	TimeStarted time.Time
	Latency     time.Duration
}

type Journal struct {
	entries    []JournalEntry
	EntryLimit int
	mutex      sync.Mutex
}

func NewJournal() *Journal {
	return &Journal{
		entries:    []JournalEntry{},
		EntryLimit: 1000,
	}
}

func (this *Journal) NewEntry(request *http.Request, response *http.Response, mode string, started time.Time) error {
	if this.EntryLimit == 0 {
		return fmt.Errorf("Journal disabled")
	}

	payloadRequest, _ := models.NewRequestDetailsFromHttpRequest(request)

	respBody, _ := util.GetResponseBody(response)

	payloadResponse := &models.ResponseDetails{
		Status:  response.StatusCode,
		Body:    respBody,
		Headers: response.Header,
	}

	this.mutex.Lock()
	if len(this.entries) >= this.EntryLimit {
		this.entries = append(this.entries[:0], this.entries[1:]...)
	}

	entry := JournalEntry{
		Request:     &payloadRequest,
		Response:    payloadResponse,
		Mode:        mode,
		TimeStarted: started,
		Latency:     time.Since(started),
	}

	this.entries = append(this.entries, entry)

	if log.IsLevelEnabled(log.DebugLevel) {
		buf := new(bytes.Buffer)
		enc := json.NewEncoder(buf)
		// do not escape characters in HTML like < and >
		enc.SetEscapeHTML(false)
		err := enc.Encode(convertJournalEntry(entry))
		if err != nil {
			log.WithFields(log.Fields{
				"error": err.Error(),
			}).Error("invalid journal entry")
		} else {
			log.WithFields(log.Fields{
				"json": buf.String(),
			}).Debug("journal entry")
		}
	}

	this.mutex.Unlock()

	return nil
}

func (this *Journal) GetEntries(offset int, limit int, from *time.Time, to *time.Time, sort string) (v2.JournalView, error) {

	journalView := v2.JournalView{
		Journal: []v2.JournalEntryView{},
		Offset:  offset,
		Limit:   limit,
		Total:   0,
	}

	if this.EntryLimit == 0 {
		return journalView, fmt.Errorf("Journal disabled")
	}

	sortKey, sortOrder, err := getSortParameters(sort)

	if err != nil {
		return journalView, err
	}

	var selectedEntries []JournalEntry

	// Filtering
	if from != nil || to != nil {
		for _, entry := range this.entries {
			if from != nil && entry.TimeStarted.Before(*from) {
				continue
			}
			if to != nil && entry.TimeStarted.After(*to) {
				continue
			}
			selectedEntries = append(selectedEntries, entry)
		}
	} else {
		selectedEntries = append(selectedEntries, this.entries...)
	}

	// Sorting
	if sortKey == "timestarted" && sortOrder == "desc" {
		sorting.Slice(selectedEntries, func(i, j int) bool {
			return selectedEntries[i].TimeStarted.After(selectedEntries[j].TimeStarted)
		})
	} else if sortKey == "latency" {
		sorting.Slice(selectedEntries, func(i, j int) bool {
			if sortOrder == "desc" {
				return selectedEntries[i].Latency > selectedEntries[j].Latency
			} else {
				return selectedEntries[i].Latency < selectedEntries[j].Latency
			}
		})
	}

	totalElements := len(selectedEntries)

	if offset >= totalElements {
		return journalView, nil
	}

	endIndex := offset + limit
	if endIndex > totalElements {
		endIndex = totalElements
	}

	journalView.Journal = convertJournalEntries(selectedEntries[offset:endIndex])
	journalView.Total = totalElements
	return journalView, nil
}

func (this *Journal) GetFilteredEntries(journalEntryFilterView v2.JournalEntryFilterView) ([]v2.JournalEntryView, error) {
	// init an empty slice to prevent serializing to a null value
	filteredEntries := []v2.JournalEntryView{}
	if this.EntryLimit == 0 {

		return filteredEntries, fmt.Errorf("Journal disabled")
	}

	requestMatcher := models.RequestMatcher{
		Path:            models.NewRequestFieldMatchersFromView(journalEntryFilterView.Request.Path),
		Method:          models.NewRequestFieldMatchersFromView(journalEntryFilterView.Request.Method),
		Destination:     models.NewRequestFieldMatchersFromView(journalEntryFilterView.Request.Destination),
		Scheme:          models.NewRequestFieldMatchersFromView(journalEntryFilterView.Request.Scheme),
		DeprecatedQuery: models.NewRequestFieldMatchersFromView(journalEntryFilterView.Request.DeprecatedQuery),
		Body:            models.NewRequestFieldMatchersFromView(journalEntryFilterView.Request.Body),
		Query:           models.NewQueryRequestFieldMatchersFromMapView(journalEntryFilterView.Request.Query),
		Headers:         models.NewRequestFieldMatchersFromMapView(journalEntryFilterView.Request.Headers),
	}

	allEntries := convertJournalEntries(this.entries)

	for _, entry := range allEntries {
		if requestMatcher.Body == nil && requestMatcher.Destination == nil &&
			requestMatcher.Headers == nil && requestMatcher.Method == nil &&
			requestMatcher.Path == nil && requestMatcher.DeprecatedQuery == nil &&
			requestMatcher.Scheme == nil && requestMatcher.Query == nil {
			continue
		}
		if !matching.FieldMatcher(requestMatcher.Body, *entry.Request.Body).Matched {
			continue
		}
		if !matching.FieldMatcher(requestMatcher.Destination, *entry.Request.Destination).Matched {
			continue
		}
		if !matching.FieldMatcher(requestMatcher.Method, *entry.Request.Method).Matched {
			continue
		}
		if !matching.FieldMatcher(requestMatcher.Path, *entry.Request.Path).Matched {
			continue
		}
		if !matching.FieldMatcher(requestMatcher.DeprecatedQuery, *entry.Request.Query).Matched {
			continue
		}
		if !matching.FieldMatcher(requestMatcher.Scheme, *entry.Request.Scheme).Matched {
			continue
		}
		if !matching.QueryMatching(requestMatcher, entry.Request.QueryMap).Matched {
			continue
		}
		if !matching.HeaderMatching(requestMatcher, entry.Request.Headers).Matched {
			continue
		}
		filteredEntries = append(filteredEntries, entry)
	}

	return filteredEntries, nil
}

func (this *Journal) DeleteEntries() error {
	if this.EntryLimit == 0 {
		return fmt.Errorf("Journal disabled")
	}

	this.entries = []JournalEntry{}

	return nil
}

func convertJournalEntries(entries []JournalEntry) []v2.JournalEntryView {

	var journalEntryViews []v2.JournalEntryView

	for _, journalEntry := range entries {
		journalEntryViews = append(journalEntryViews, v2.JournalEntryView{
			Request:     journalEntry.Request.ConvertToRequestDetailsView(),
			Response:    journalEntry.Response.ConvertToResponseDetailsView(),
			Mode:        journalEntry.Mode,
			TimeStarted: journalEntry.TimeStarted.Format(RFC3339Milli),
			Latency:     journalEntry.Latency.Seconds() * 1e3,
		})
	}

	return journalEntryViews
}

func convertJournalEntry(entry JournalEntry) v2.JournalEntryView {

	return v2.JournalEntryView{
		Request:     entry.Request.ConvertToRequestDetailsView(),
		Response:    entry.Response.ConvertToResponseDetailsView(),
		Mode:        entry.Mode,
		TimeStarted: entry.TimeStarted.Format(RFC3339Milli),
		Latency:     entry.Latency.Seconds() * 1e3,
	}
}

func getSortParameters(sort string) (string, string, error) {
	sortParams := strings.Split(sort, ":")

	sortKey := strings.ToLower(sortParams[0])
	if sortKey == "" {
		sortKey = "timestarted"
	}
	sortOrder := "asc"

	if sortKey != "timestarted" && sortKey != "latency" {
		return sortKey, sortOrder, fmt.Errorf("'%s' is not a valid sort key, use timeStarted or latency", sortKey)
	}

	if len(sortParams) > 1 {
		sortOrder = strings.ToLower(sortParams[1])

		if sortOrder != "asc" && sortOrder != "desc" {
			return sortKey, sortOrder, fmt.Errorf("'%s' is not a valid sort order. use asc or desc", sortOrder)
		}
	}

	return sortKey, sortOrder, nil
}


text:
@class AEPreset;

@interface AEPresetView : UIView

@property (nonatomic, strong) AEPreset *preset;

@end


text:
from fabric.api import local, lcd
from fabric import colors
from fabric.utils import indent
from fabric.state import env

import netaddr
import os
import time
import itertools

DEFAULT_TEST_PREFIX = ''
DEFAULT_TEST_BASE_DIR = '/tmp/gobgp'
TEST_PREFIX = DEFAULT_TEST_PREFIX
TEST_BASE_DIR = DEFAULT_TEST_BASE_DIR

BGP_FSM_IDLE = 'BGP_FSM_IDLE'
BGP_FSM_ACTIVE = 'BGP_FSM_ACTIVE'
BGP_FSM_ESTABLISHED = 'BGP_FSM_ESTABLISHED'

BGP_ATTR_TYPE_ORIGIN = 1
BGP_ATTR_TYPE_AS_PATH = 2
BGP_ATTR_TYPE_NEXT_HOP = 3
BGP_ATTR_TYPE_MULTI_EXIT_DISC = 4
BGP_ATTR_TYPE_LOCAL_PREF = 5
BGP_ATTR_TYPE_COMMUNITIES = 8
BGP_ATTR_TYPE_MP_REACH_NLRI = 14
BGP_ATTR_TYPE_EXTENDED_COMMUNITIES = 16

env.abort_exception = RuntimeError

def try_several_times(f, t=3, s=1):
    e = None
    for i in range(t):
        try:
            r = f()
        except RuntimeError as e:
            time.sleep(s)
        else:
            return r
    raise e

def get_bridges():
    return try_several_times(lambda : local("brctl show | awk 'NR > 1{print $1}'", capture=True)).split('\n')

def get_containers():
    return try_several_times(lambda : local("docker ps -a | awk 'NR > 1 {print $NF}'", capture=True)).split('\n')

class CmdBuffer(list):
    def __init__(self, delim='\n'):
        super(CmdBuffer, self).__init__()
        self.delim = delim

    def __lshift__(self, value):
        self.append(value)

    def __str__(self):
        return self.delim.join(self)

def make_gobgp_ctn(tag='gobgp', local_gobgp_path='', from_image='osrg/quagga'):
    if local_gobgp_path == '':
        local_gobgp_path = os.getcwd()

    c = CmdBuffer()
    c << 'FROM {0}'.format(from_image)
    c << 'ADD gobgp /go/src/github.com/osrg/gobgp/'
    c << 'RUN go get github.com/osrg/gobgp/gobgpd'
    c << 'RUN go install github.com/osrg/gobgp/gobgpd'
    c << 'RUN go get github.com/osrg/gobgp/gobgp'
    c << 'RUN go install github.com/osrg/gobgp/gobgp'

    rindex = local_gobgp_path.rindex('gobgp')
    if rindex < 0:
        raise Exception('{0} seems not gobgp dir'.format(local_gobgp_path))

    workdir = local_gobgp_path[:rindex]
    with lcd(workdir):
        local('echo \'{0}\' > Dockerfile'.format(str(c)))
        local('docker build -t {0} .'.format(tag))
        local('rm Dockerfile')

class Bridge(object):
    def __init__(self, name, subnet='', with_ip=True, self_ip=False):
        self.name = '{0}_{1}'.format(TEST_PREFIX, name)
        self.with_ip = with_ip
        if with_ip:
            self.subnet = netaddr.IPNetwork(subnet)

            def f():
                for host in self.subnet:
                    yield host
            self._ip_generator = f()
            # throw away first network address
            self.next_ip_address()

        def f():
            if self.name in get_bridges():
                self.delete()
            local("ip link add {0} type bridge".format(self.name))
        try_several_times(f)
        try_several_times(lambda : local("ip link set up dev {0}".format(self.name)))

        self.self_ip = self_ip
        if self_ip:
            self.ip_addr = self.next_ip_address()
            try_several_times(lambda :local("ip addr add {0} dev {1}".format(self.ip_addr, self.name)))
        self.ctns = []

    def next_ip_address(self):
        return "{0}/{1}".format(self._ip_generator.next(),
                                self.subnet.prefixlen)

    def addif(self, ctn):
        name = ctn.next_if_name()
        self.ctns.append(ctn)
        if self.with_ip:

            ctn.pipework(self, self.next_ip_address(), name)
        else:
            ctn.pipework(self, '0/0', name)

    def delete(self):
        try_several_times(lambda : local("ip link set down dev {0}".format(self.name)))
        try_several_times(lambda : local("ip link delete {0} type bridge".format(self.name)))

class Container(object):
    def __init__(self, name, image):
        self.name = name
        self.image = image
        self.shared_volumes = []
        self.ip_addrs = []
        self.is_running = False
        self.eths = []

        if self.docker_name() in get_containers():
            self.remove()

    def docker_name(self):
        if TEST_PREFIX == DEFAULT_TEST_PREFIX:
            return self.name
        return '{0}_{1}'.format(TEST_PREFIX, self.name)

    def next_if_name(self):
        name = 'eth{0}'.format(len(self.eths)+1)
        self.eths.append(name)
        return name

    def run(self):
        c = CmdBuffer(' ')
        c << "docker run --privileged=true"
        for sv in self.shared_volumes:
            c << "-v {0}:{1}".format(sv[0], sv[1])
        c << "--name {0} -id {1}".format(self.docker_name(), self.image)
        self.id = try_several_times(lambda : local(str(c), capture=True))
        self.is_running = True
        self.local("ip li set up dev lo")
        return 0

    def stop(self):
        ret = try_several_times(lambda : local("docker stop -t 0 " + self.docker_name(), capture=True))
        self.is_running = False
        return ret

    def remove(self):
        ret = try_several_times(lambda : local("docker rm -f " + self.docker_name(), capture=True))
        self.is_running = False
        return ret

    def pipework(self, bridge, ip_addr, intf_name=""):
        if not self.is_running:
            print colors.yellow('call run() before pipeworking')
            return
        c = CmdBuffer(' ')
        c << "pipework {0}".format(bridge.name)

        if intf_name != "":
            c << "-i {0}".format(intf_name)
        else:
            intf_name = "eth1"
        c << "{0} {1}".format(self.docker_name(), ip_addr)
        self.ip_addrs.append((intf_name, ip_addr, bridge))
        try_several_times(lambda :local(str(c)))

    def local(self, cmd, capture=False, flag=''):
        return local("docker exec {0} {1} {2}".format(flag,
                                                      self.docker_name(),
                                                      cmd), capture)

    def get_pid(self):
        if self.is_running:
            cmd = "docker inspect -f '{{.State.Pid}}' " + self.docker_name()
            return int(local(cmd, capture=True))
        return -1

class BGPContainer(Container):

    WAIT_FOR_BOOT = 0
    RETRY_INTERVAL = 5

    def __init__(self, name, asn, router_id, ctn_image_name):
        self.config_dir = '/'.join((TEST_BASE_DIR, TEST_PREFIX, name))
        local('if [ -e {0} ]; then rm -r {0}; fi'.format(self.config_dir))
        local('mkdir -p {0}'.format(self.config_dir))
        local('chmod 777 {0}'.format(self.config_dir))
        self.asn = asn
        self.router_id = router_id
        self.peers = {}
        self.routes = {}
        self.policies = {}
        super(BGPContainer, self).__init__(name, ctn_image_name)

    def __repr__(self):
        return str({'name':self.name, 'asn':self.asn, 'router_id':self.router_id})

    def run(self):
        self.create_config()
        super(BGPContainer, self).run()
        return self.WAIT_FOR_BOOT

    def add_peer(self, peer, passwd=None, evpn=False, is_rs_client=False,
                 policies=None, passive=False,
                 is_rr_client=False, cluster_id=None,
                 flowspec=False):
        neigh_addr = ''
        local_addr = ''
        for me, you in itertools.product(self.ip_addrs, peer.ip_addrs):
            if me[2] == you[2]:
                neigh_addr = you[1]
                local_addr = me[1]

        if neigh_addr == '':
            raise Exception('peer {0} seems not ip reachable'.format(peer))

        if not policies:
            policies = {}

        self.peers[peer] = {'neigh_addr': neigh_addr,
                            'passwd': passwd,
                            'evpn': evpn,
                            'flowspec': flowspec,
                            'is_rs_client': is_rs_client,
                            'is_rr_client': is_rr_client,
                            'cluster_id': cluster_id,
                            'policies': policies,
                            'passive': passive,
                            'local_addr': local_addr}
        if self.is_running:
            self.create_config()
            self.reload_config()

    def del_peer(self, peer):
        del self.peers[peer]
        if self.is_running:
            self.create_config()
            self.reload_config()

    def disable_peer(self, peer):
        raise Exception('implement disable_peer() method')

    def enable_peer(self, peer):
        raise Exception('implement enable_peer() method')

    def log(self):
        return local('cat {0}/*.log'.format(self.config_dir), capture=True)

    def add_route(self, route, rf='ipv4', attribute=None, aspath=None,
                  community=None, med=None, extendedcommunity=None,
                  nexthop=None, matchs=None, thens=None):
        self.routes[route] = {'prefix': route,
                              'rf': rf,
                              'attr': attribute,
                              'next-hop': nexthop,
                              'as-path': aspath,
                              'community': community,
                              'med': med,
                              'extended-community': extendedcommunity,
                              'matchs': matchs,
                              'thens' : thens}
        if self.is_running:
            self.create_config()
            self.reload_config()

    def add_policy(self, policy, peer=None):
        self.policies[policy['name']] = policy
        if peer in self.peers:
            self.peers[peer]['policies'][policy['name']] = policy
        if self.is_running:
            self.create_config()
            self.reload_config()

    def get_local_rib(self, peer, rf):
        raise Exception('implement get_local_rib() method')

    def get_global_rib(self, rf):
        raise Exception('implement get_global_rib() method')

    def get_neighbor_state(self, peer_id):
        raise Exception('implement get_neighbor() method')

    def get_reachablily(self, prefix, timeout=20):
            version = netaddr.IPNetwork(prefix).version
            addr = prefix.split('/')[0]
            if version == 4:
                ping_cmd = 'ping'
            elif version == 6:
                ping_cmd = 'ping6'
            else:
                raise Exception('unsupported route family: {0}'.format(version))
            cmd = '/bin/bash -c "/bin/{0} -c 1 -w 1 {1} | xargs echo"'.format(ping_cmd, addr)
            interval = 1
            count = 0
            while True:
                res = self.local(cmd, capture=True)
                print colors.yellow(res)
                if '1 packets received' in res and '0% packet loss':
                    break
                time.sleep(interval)
                count += interval
                if count >= timeout:
                    raise Exception('timeout')
            return True

    def wait_for(self, expected_state, peer, timeout=120):
        interval = 1
        count = 0
        while True:
            state = self.get_neighbor_state(peer)
            y = colors.yellow
            print y("{0}'s peer {1} state: {2}".format(self.router_id,
                                                       peer.router_id,
                                                       state))
            if state == expected_state:
                return

            time.sleep(interval)
            count += interval
            if count >= timeout:
                raise Exception('timeout')

    def add_static_route(self, network, next_hop):
        cmd = '/sbin/ip route add {0} via {1}'.format(network, next_hop)
        self.local(cmd)

    def set_ipv6_forward(self):
        cmd = 'sysctl -w net.ipv6.conf.all.forwarding=1'
        self.local(cmd)

    def create_config(self):
        raise Exception('implement create_config() method')

    def reload_config(self):
        raise Exception('implement reload_config() method')


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phyllosticta sordidissima Speg.

### Remarks
null


text:
package com.amazonaws.services.lightsail.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.lightsail.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * RelationalDatabaseBundleMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RelationalDatabaseBundleMarshaller {

    private static final MarshallingInfo<String> BUNDLEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("bundleId").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("name").build();
    private static final MarshallingInfo<Float> PRICE_BINDING = MarshallingInfo.builder(MarshallingType.FLOAT).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("price").build();
    private static final MarshallingInfo<Float> RAMSIZEINGB_BINDING = MarshallingInfo.builder(MarshallingType.FLOAT).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ramSizeInGb").build();
    private static final MarshallingInfo<Integer> DISKSIZEINGB_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("diskSizeInGb").build();
    private static final MarshallingInfo<Integer> TRANSFERPERMONTHINGB_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("transferPerMonthInGb").build();
    private static final MarshallingInfo<Integer> CPUCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("cpuCount").build();
    private static final MarshallingInfo<Boolean> ISENCRYPTED_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("isEncrypted").build();
    private static final MarshallingInfo<Boolean> ISACTIVE_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("isActive").build();

    private static final RelationalDatabaseBundleMarshaller instance = new RelationalDatabaseBundleMarshaller();

    public static RelationalDatabaseBundleMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(RelationalDatabaseBundle relationalDatabaseBundle, ProtocolMarshaller protocolMarshaller) {

        if (relationalDatabaseBundle == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(relationalDatabaseBundle.getBundleId(), BUNDLEID_BINDING);
            protocolMarshaller.marshall(relationalDatabaseBundle.getName(), NAME_BINDING);
            protocolMarshaller.marshall(relationalDatabaseBundle.getPrice(), PRICE_BINDING);
            protocolMarshaller.marshall(relationalDatabaseBundle.getRamSizeInGb(), RAMSIZEINGB_BINDING);
            protocolMarshaller.marshall(relationalDatabaseBundle.getDiskSizeInGb(), DISKSIZEINGB_BINDING);
            protocolMarshaller.marshall(relationalDatabaseBundle.getTransferPerMonthInGb(), TRANSFERPERMONTHINGB_BINDING);
            protocolMarshaller.marshall(relationalDatabaseBundle.getCpuCount(), CPUCOUNT_BINDING);
            protocolMarshaller.marshall(relationalDatabaseBundle.getIsEncrypted(), ISENCRYPTED_BINDING);
            protocolMarshaller.marshall(relationalDatabaseBundle.getIsActive(), ISACTIVE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?php
namespace test\n\l;
class m { }


text:
package io.flashreport.cfspring.integration;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

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

/**
 * Simple client to send report generation requests to flashreport.io, as well as getting information
 * about a report request.
 *

 * The flashreport api key is extracted from the VCAP_SERVICES environment variable, which is set by Cloud Foundry.
 *

 * Created by Nicolas Lejeune on 18/06/15.
 */

public class FlashreportClient {

    private static final String CREATE_URL = "https://gateway.flashreport.io/api/v1/report/new";
    private static final String BASE_URL = "https://gateway.flashreport.io/api/v1/report/";

    private String API_KEY;

    /**
     * Request the generation of a report with the specified content.
     *
     * @param content json or xml data
     * @return the URI representing the report
     */
    public URI generateReport(String content) {
        return generateReport(content, null, null);
    }

    /**
     * Request the generation of a report with the specified content and title.
     *
     * @param content json or xml data
     * @param title   a title for your report
     * @return the URI representing the report
     */
    public URI generateReport(String content, String title) {
        return generateReport(content, title, null);
    }

    /**
     * Request the generation of a report with the specified content, title and template.
     * The template must have been previously registered in the dashboard.
     *
     * @param content json or xml data
     * @param title   a title for your report
     * @return the URI representing the report
     */
    public URI generateReport(String content, String title, String template) {
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity entityWithBody = new HttpEntity<>(content, getHeaders());

        String url = CREATE_URL;
        if (title != null) url += "?title=" + title;
        if (title != null && template != null) url += "&template=" + template;
        if (title == null && template != null) url += "?template=" + template;

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entityWithBody, String.class);

        if (response.getStatusCode().equals(HttpStatus.CREATED)) {
            return response.getHeaders().getLocation();
        } else {
            throw new RuntimeException("Received unexpected response code : " + response.getStatusCode());
        }
    }

    public String getStorageUrl(String uuid) {
        HttpEntity entity = new HttpEntity<>(getHeaders());
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(BASE_URL + uuid + "/storage", HttpMethod.GET, entity, String.class);
        if (response.getStatusCode().equals(HttpStatus.OK)) {
            return response.getBody();
        } else {
            throw new RuntimeException("Received unexpected response code : " + response.getStatusCode());
        }
    }

    public ReportStatus getReportStatus(String uuid) {
        try {
            return getReportStatus(new URI(BASE_URL + uuid));
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Unable to construct a uri with report uuid [" + uuid + "]");
        }
    }

    public ReportStatus getReportStatus(URI reportUri) {
        HttpEntity entity = new HttpEntity<>(getHeaders());
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(reportUri, HttpMethod.GET, entity, String.class);

        if (response.getStatusCode().equals(HttpStatus.OK)) {
            ObjectMapper mapper = new ObjectMapper();
            ReportStatus status;
            try {
                status = mapper.readValue(response.getBody(), ReportStatus.class);
            } catch (IOException e) {
                throw new RuntimeException("Could not parse response body : " + response.getBody());
            }
            return status;
        } else {
            throw new RuntimeException("Received unexpected response code : " + response.getStatusCode());
        }
    }

    private String extractApiKey() throws IllegalStateException {

        if (API_KEY != null) return API_KEY;

        String vcap_services = System.getenv("VCAP_SERVICES");
        if (vcap_services == null) {
            throw new IllegalStateException("Unable to get VCAP_SERVICES from environment.");
        }

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readValue(vcap_services, JsonNode.class);
            API_KEY = jsonNode.get("flashreport").get(0).get("credentials").get("apiKey").asText();
        } catch (IOException | NullPointerException e) {
            throw new IllegalStateException(
                    "Unable to extract api key from VCAP_SERVICES. Did you bind a flashreport service to your app?");
        }

        return API_KEY;
    }

    private HttpHeaders getHeaders() {
        HttpHeaders httpHeaders = new HttpHeaders();
        String basicHeader = "Basic " + Base64.getEncoder().encodeToString((extractApiKey() + ":").getBytes());
        httpHeaders.add("Authorization", basicHeader);
        return httpHeaders;
    }

}


text:
<?php
namespace CminorFramework\UtilityBelt\General;

use CminorFramework\UtilityBelt\General\Components\Providers\GeneralUtilityBeltServiceProvider;
use CminorFramework\UtilityBelt\General\Contracts\Providers\IGeneralUtilityBeltServiceProvider;
use CminorFramework\UtilityBelt\General\Components\Containers\UtilityBeltHelpers;

/**
 * The General Utility Belt
 *
 * @package CminorFramework/UtilityBelt
 * @subpackage General
 * @version 0.5
 *
 * @author Dimitrios Psarrou <dpsarrou@gmail.com> d(^_^)b
 * @link http://soundcloud.com/cminor, https://github.com/dpsarrou
 *
 */
class GeneralUtilityBelt
{

    /**
     * Holds the utility belt service provider instance
     * @var \CminorFramework\UtilityBelt\General\Contracts\Providers\IGeneralUtilityBeltServiceProvider
     */
    protected $service_provider;

    /**
     * Holds the general utility belt helpers container instance
     * @var \CminorFramework\UtilityBelt\General\Components\Containers\UtilityBeltHelpers
     */
    protected $utility_belt_helpers;

    /**
     * Binds a general utility belt service provider to resolve the utility belt components
     *
     * @param \CminorFramework\UtilityBelt\General\Contracts\Providers\IGeneralUtilityBeltServiceProvider $service_provider
     */
    public function _bindServiceProvider(IGeneralUtilityBeltServiceProvider $service_provider)
    {

        $this->service_provider = $service_provider;

    }

    /**
     * Returns the utility belt service provider
     * @return \CminorFramework\UtilityBelt\General\Contracts\Providers\IGeneralUtilityBeltServiceProvider
     */
    public function getServiceProvider()
    {

        /*
         * Initialize the service provider with the utility belt's default provider
         * if a custom one has not been set before
         */
        if(!isset($this->service_provider)){

            $this->service_provider = new GeneralUtilityBeltServiceProvider();

        }

        return $this->service_provider;
    }

    /**
     * Returns the general utility belt helpers contaniner singleton instance
     *
     * @return \CminorFramework\UtilityBelt\General\Components\Containers\UtilityBeltHelpers
     */
    public function getHelpers()
    {

        if( !isset($this->utility_belt_helpers) ){

            $utility_belt_helpers = new UtilityBeltHelpers();
            $utility_belt_helpers->setServiceProvider($this->getServiceProvider());

            $this->utility_belt_helpers = $utility_belt_helpers;
        }

        return $this->utility_belt_helpers;

    }

}


text:
<?php

namespace Cygnite\Common\Input\CookieManager;

use Closure;
use Cygnite\Common\Security;
use Cygnite\Common\Singleton;
use Cygnite\Proxy\StaticResolver;

class Cookie extends StaticResolver implements CookieInterface
{
    /**
     * Cookie attributes
     */
    private $name;

    private $value;

    private $expire;

    private $path;

    private $domain;

    private $secure = false;

    private $httpOnly = false;

    public static $cookies = [];

    /*
     * Did cookie has been set already ?
     */
    private $setCookie = false;

    //Property to hold security instance.
    private $security;

    /*
     * Constructor of the Cookie.
     * @access private
     * You can not create instance directly.
     * Use Cookie::instance(); to get the object
     *
     * @return void
     */
    protected function __construct()
    {
        //Get the security instance and provide security to cookies
        $this->security = Security::instance(
            function ($instance) {
                return $instance;
            }
        );
    }

    /**
     * @param callable $callback
     * @param array    $request
     * @return object
     */
    protected function create(Closure $callback = null, $request = [])
    {
        if (!empty($request)) {
            static::$cookies = $request['cookie'];
        } else {
            static::$cookies = $_COOKIE;
        }

        $crypt = null;

        if (is_object($crypt)) {
            self::$encrypt = $crypt;
        }

        return (is_callable($callback)) ? $callback(new self) : new self;
    }

    /**
     * Set cookie name
     *
     * @access public
     * @param string $name cookie name
     * @throws \InvalidCookieException
     * @return mixed obj or bool false
     */
    public function setName($name)
    {
        if (is_null($name)) {
            throw new \InvalidCookieException("Cookie name cannot be null");

            return false;
        }

        $this->name = (string) $this->security->sanitize($name);

        return $this;
    }

    /**
     * Set cookie value
     *
     * @access   public
     * @param string $value cookie value
     * @throws \InvalidCookieException
     * @internal param bool $encrypt
     * @return bool whether the string was a string
     */
    public function setValue($value = null)
    {
        if (is_null($value)) {
            throw new \InvalidCookieException("Cookie value cannot be null.");
            return false;
        }

        if (is_array($value)) {
            $value = json_encode($this->security->sanitize($value));
        }

        //$data = $this->encrypt->encode($value);
        $data = $value;

        $length = null;

        $length = (function_exists('mb_strlen')?
            mb_strlen($data) :
            strlen($data));

        if ($length > 4096) {
            throw new \InvalidCookieException('Cookie maximum size exceeds 4kb');
            return false;
        }

        $this->value = $this->security->sanitize($data);
        unset($data);

        return $this;
    }

    /**
     * Set cookie expire time
     *
     * @access   public
     * @param int $expire
     * @throws \InvalidCookieException
     * @internal param string $time +1 day, etc.
     * @return bool whether the string was a string
     */
    public function setExpire($expire = 0)
    {
        $var = null;
        $var = substr($expire, 0, 1);

        if (in_array($var, ['+', '-'])) {
            $this->expire = strtotime($expire);

            if ($this->expire === false) {
                throw new \InvalidCookieException(
                    'Cookie->setExpire was passed a string it could not parse - "'.$expire.'"'
                );
            }

            return $this;
        }

        $this->expire = 0;

        return $this;
    }

    /**
     * Set cookie path
     * @param string $path The cookie path
     * @return $this
     */
    public function setPath($path = '/')
    {
        $this->path = (string) $path;

        return $this;
    }

    /**
     * Set the cookie domain
     * @access public
     * @param string $domain The cookie path
     * @return $this
     */

    public function setDomain($domain = null)
    {
        if ($domain !== null) {
            $this->domain = (string) $domain;
        }

        return $this;
    }

    /*
     * Set the cookie status to be secure or not
     *
     * @param bool $bool true/false if secure
     * @return $this
     */

    public function setSecure($bool = false)
    {
        $this->secure = (bool)$bool;

        return $this;
    }

    /*

     * Set the cookie type http only, or not
     * @param bool $bool true/false if http only
     * @return $this
     */
    public function setHttpOnly($bool = false)
    {
        $this->httpOnly = (bool)$bool;

        return $this;
    }

    /*
     * Get a cookie's value
     *
     * @param string $name The cookie name
     * @return mixed string /bool - The value of the cookie name
     */
    public function get($name = null)
    {
        if (is_null($name)) {
            $name = $this->security->sanitize($this->name);
        }

        $name = $this->security->sanitize($name);

        $value = null;

        if (isset(static::$cookies[$name]) && is_array(static::$cookies[$name])) {
            $value = json_decode(static::$cookies[$name]);
        }

        if (isset(static::$cookies[$name])) {
            $value = $this->security->sanitize(static::$cookies[$name]);

            return  $value;
            //json_decode($this->encrypt->decode(static::$cookies[$name])) :
        }

        if (!isset(static::$cookies[$name])) {
            throw new InvalidCookieException($name.' not found');
            return false;
        }
    }

    /*
     * Set the cookie
     *
     * @return bool
     * @throws \Exceptions  Cookies already set
     */
    public function save()
    {
        if ($this->name && $this->setCookie == true) {
            throw new InvalidCookieException(
                'Cookie->setCookie has already been called. Cookies can only set once.'
            );
        }

        $bool = setcookie(
            $this->name,
            $this->value,
            $this->expire,
            $this->path,
            $this->domain,
            $this->secure,
            $this->httpOnly
        );

        if ($bool == true) {
            $this->setCookie = true;
        }

        return $bool;
    }

    /**
     * @param $cookie
     * @return bool|mixed
     */
    public function has($cookie)
    {
        if (isset(static::$cookies[$cookie]) || $cookie == $this->name) {
            return true;
        }

        return false;
    }

    /**
     * destroy the cookie
     *
     * @access   public
     * @param null $name
     * @internal param string $cookieName to kill
     * @return bool true/false
     */
    public function destroy($name = null)
    {
        if (is_null($name)) {
            $name = $this->name;
        }

        return setcookie(
            $name,
            null,
            (time()-1),
            $this->path,
            $this->domain
        );
    }

    public function __destruct()
    {
        $this->setCookie = false;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>Spillern, Austria</formatted_address>
  <address_component>
   <long_name>Spillern</long_name>
   <short_name>Spillern</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Spillern</long_name>
   <short_name>Gemeinde Spillern</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Korneuburg District</long_name>
   <short_name>Korneuburg District</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Lower Austria</long_name>
   <short_name>Lower Austria</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <geometry>
   <location>
    <lat>48.3775373</lat>
    <lng>16.2638958</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>48.3540101</lat>
     <lng>16.2343699</lng>
    </southwest>
    <northeast>
     <lat>48.3977700</lat>
     <lng>16.2931901</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>48.3540101</lat>
     <lng>16.2343699</lng>
    </southwest>
    <northeast>
     <lat>48.3977700</lat>
     <lng>16.2931901</lng>
    </northeast>
   </bounds>
  </geometry>
  <place_id>ChIJibvM6HASbUcR8CvmLVeXAAQ</place_id>
 </result>
</GeocodeResponse>


text:
@interface ToastView ()
@property (strong, nonatomic, readonly) UILabel *textLabel;
@end
@implementation ToastView
@synthesize textLabel = _textLabel;

float const ToastHeight = 40.0f;
float const ToastGap = 7.0f;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(UILabel *)textLabel
{
    if (!_textLabel) {
        _textLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 5.0, self.frame.size.width - 10.0, self.frame.size.height - 10.0)];
        _textLabel.backgroundColor = [UIColor clearColor];
        _textLabel.textAlignment = NSTextAlignmentCenter;
        _textLabel.textColor = [UIColor whiteColor];
        _textLabel.numberOfLines = 2;
        _textLabel.font = [UIFont systemFontOfSize:11.0];
        _textLabel.lineBreakMode = NSLineBreakByCharWrapping;
        [self addSubview:_textLabel];

    }
    return _textLabel;
}

- (void)setText:(NSString *)text
{
    _text = text;
    self.textLabel.text = text;
}

+ (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration;
{

    //Count toast views are already showing on parent. Made to show several toasts one above another
    int toastsAlreadyInParent = 0;
    for (UIView *subView in [parentView subviews]) {
        if ([subView isKindOfClass:[ToastView class]])
        {
            toastsAlreadyInParent++;
        }
    }

    CGRect parentFrame = parentView.frame;

    float yOrigin = parentFrame.size.height - (70.0 + ToastHeight * toastsAlreadyInParent + ToastGap * toastsAlreadyInParent);

    CGRect selfFrame = CGRectMake(parentFrame.origin.x + 20.0, yOrigin, parentFrame.size.width - 40.0, ToastHeight);
    ToastView *toast = [[ToastView alloc] initWithFrame:selfFrame];

    toast.backgroundColor = [UIColor darkGrayColor];
    toast.alpha = 0.0f;
    toast.layer.cornerRadius = 4.0;
    toast.text = text;

    [parentView addSubview:toast];

    [UIView animateWithDuration:0.4 animations:^{
        toast.alpha = 0.9f;
        toast.textLabel.alpha = 0.9f;
    }completion:^(BOOL finished) {
        if(finished){

        }
    }];

    [toast performSelector:@selector(hideSelf) withObject:nil afterDelay:duration];

}

- (void)hideSelf
{

    [UIView animateWithDuration:0.4 animations:^{
        self.alpha = 0.0;
        self.textLabel.alpha = 0.0;
    }completion:^(BOOL finished) {
        if(finished){
            [self removeFromSuperview];
        }
    }];
}

@end


text:
role :app, "production.host.com"
set :whenever_environment, 'production'
after "deploy:update_code" do
  bundler.bundle_new_release
  config.populate_dirs
  whenever.update_crontab
  resque.restart_resque_web
end


text:
"""
:class:`Property` objects can be defined on subclasses of
:class:`~pydispatch.dispatch.Dispatcher` to create instance attributes that act
as events when their values change

.. doctest:: properties_module

    >>> from pydispatch import Dispatcher, Property

    >>> class Foo(Dispatcher):
    ...     name = Property()
    ...     value = Property()
    ...     def __str__(self):
    ...         return self.__class__.__name__

    >>> class Listener(object):
    ...     def on_foo_name(self, instance, value, **kwargs):
    ...         print("{}'s name is {}".format(instance, value))
    ...     def on_foo_value(self, instance, value, **kwargs):
    ...         print('{} = {}'.format(instance, value))

    >>> foo_obj = Foo()
    >>> listener_obj = Listener()
    >>> foo_obj.bind(name=listener_obj.on_foo_name, value=listener_obj.on_foo_value)

    >>> foo_obj.name = 'bar'
    Foo's name is bar
    >>> foo_obj.value = 42
    Foo = 42

Type checking is not enforced, so values can be any valid python type.
Values are however checked for equality to avoid dispatching events for no
reason. If custom objects are used as values, they must be able to support
equality checking. In most cases, this will be handled automatically.
"""

import weakref

from pydispatch.utils import InformativeWVDict

__all__ = ['Property', 'ListProperty', 'DictProperty']

class Property(object):
    """Defined on the class level to create an observable attribute

    Args:
        default (Optional): If supplied, this will be the default value of the
            Property for all instances of the class. Otherwise :obj:`None`

    Attributes:
        name (str): The name of the Property as defined in the class definition.
            This will match the attribute name for the
            :class:`~pydispatch.dispatch.Dispatcher` instance.

    """
    def __init__(self, default=None):
        self._name = ''
        self.default = default
        self.__storage = {}
        self.__weakrefs = InformativeWVDict(del_callback=self._on_weakref_fin)
    @property
    def name(self):
        return self._name
    def __set_name__(self, owner, name):
        self._name = name
    def _add_instance(self, obj, default=None):
        if default is None:
            default = self.default
        self.__storage[id(obj)] = self.default
        self.__weakrefs[id(obj)] = obj
    def _del_instance(self, obj):
        del self.__storage[id(obj)]
    def _on_weakref_fin(self, obj_id):
        if obj_id in self.__storage:
            del self.__storage[obj_id]
    def __get__(self, obj, objcls=None):
        if obj is None:
            return self
        obj_id = id(obj)
        if obj_id not in self.__storage:
            self._add_instance(obj)
        return self.__storage[obj_id]
    def __set__(self, obj, value):
        obj_id = id(obj)
        if obj_id not in self.__storage:
            self._add_instance(obj)
        current = self.__storage[obj_id]
        if current == value:
            return
        self.__storage[obj_id] = value
        self._on_change(obj, current, value)
    def _on_change(self, obj, old, value, **kwargs):
        """Called internally to emit changes from the instance object

        The keyword arguments here will be passed to callbacks through the
        instance object's :meth:`~pydispatch.dispatch.Dispatcher.emit` method.

        Keyword Args:
            property: The :class:`Property` instance. This is useful if multiple
                properties are bound to the same callback. The attribute name
            keys (optional): If the :class:`Property` is a container type
                (:class:`ListProperty` or :class:`DictProperty`), the changes
                may be found here.
                This is not implemented for nested containers and will only be
                available for operations that do not alter the size of the
                container.

        """
        kwargs['property'] = self
        obj.emit(self.name, obj, value, old=old, **kwargs)
    def __repr__(self):
        return '<{}: {}>'.format(self.__class__, self)
    def __str__(self):
        return self.name

class ListProperty(Property):
    """Property with a :class:`list` type value

    Args:
        default (Optional): If supplied, this will be the default value of the
            Property for all instances of the class. Otherwise :obj:`None`
        copy_on_change (bool, optional): If :obj:`True`, the list will be copied
            when contents are modified. This can be useful for observing the
            original state of the list from within callbacks. The copied
            (original) state will be available from the keyword argument 'old'.
            The default is :obj:`False` (for performance and memory reasons).

    Changes to the contents of the list are able to be observed through
    :class:`ObservableList`.
    """
    def __init__(self, default=None, copy_on_change=False):
        if default is None:
            default = []
        self.copy_on_change = copy_on_change
        super(ListProperty, self).__init__(default)
    def _add_instance(self, obj):
        default = self.default[:]
        default = ObservableList(default, obj=obj, property=self)
        super(ListProperty, self)._add_instance(obj, default)
    def __set__(self, obj, value):
        value = ObservableList(value, obj=obj, property=self)
        super(ListProperty, self).__set__(obj, value)
    def __get__(self, obj, objcls=None):
        if obj is None:
            return self
        value = super(ListProperty, self).__get__(obj, objcls)
        if not isinstance(value, ObservableList):
            value = ObservableList(value, obj=obj, property=self)
            self._Property__storage[id(obj)] = value
        return value

class DictProperty(Property):
    """Property with a :class:`dict` type value

    Args:
        default (Optional): If supplied, this will be the default value of the
            Property for all instances of the class. Otherwise :obj:`None`
        copy_on_change (bool, optional): If :obj:`True`, the dict will be copied
            when contents are modified. This can be useful for observing the
            original state of the dict from within callbacks. The copied
            (original) state will be available from the keyword argument 'old'.
            The default is :obj:`False` (for performance and memory reasons).

    Changes to the contents of the dict are able to be observed through
    :class:`ObservableDict`.
    """
    def __init__(self, default=None, copy_on_change=False):
        if default is None:
            default = {}
        self.copy_on_change = copy_on_change
        super(DictProperty, self).__init__(default)
    def _add_instance(self, obj):
        default = self.default.copy()
        default = ObservableDict(default, obj=obj, property=self)
        super(DictProperty, self)._add_instance(obj, default)
    def __set__(self, obj, value):
        value = ObservableDict(value, obj=obj, property=self)
        super(DictProperty, self).__set__(obj, value)
    def __get__(self, obj, objcls=None):
        if obj is None:
            return self
        value = super(DictProperty, self).__get__(obj, objcls)
        if not isinstance(value, ObservableDict):
            value = ObservableDict(value, obj=obj, property=self)
            self._Property__storage[id(obj)] = value
        return value

class Observable(object):
    """Mixin used by :class:`ObservableList` and :class:`ObservableDict`
    to emit changes and build other observables

    When an item is added to an observable container (a subclass of Observable)
    it is type-checked and, if possible replaced by an observable version of it.

    In other words, if a dict is added to a :class:`ObservableDict`, it is
    copied and replaced by another :class:`ObservableDict`. This allows nested
    containers to be observed and their changes to be tracked.
    """
    def _build_observable(self, item):
        if isinstance(item, list):
            item = ObservableList(item, parent=self)
        elif isinstance(item, dict):
            item = ObservableDict(item, parent=self)
        return item
    def _get_copy_or_none(self):
        p = self.parent_observable
        if p is not None:
            return p._get_copy_or_none()
        if not self.copy_on_change:
            return None
        return self._deepcopy()
    def _deepcopy(self):
        o = self.copy()
        if isinstance(self, list):
            item_iter = enumerate(self)
        elif isinstance(self, dict):
            item_iter = self.items()
        for key, item in item_iter:
            if isinstance(item, Observable):
                o[key] = item._deepcopy()
        return o
    def _emit_change(self, **kwargs):
        if not self._init_complete:
            return
        old = kwargs.pop('old')
        p = self.parent_observable
        if p is not None:
            p._emit_change(old=old)
            return
        self.property._on_change(self.obj, old, self, **kwargs)

class ObservableList(list, Observable):
    """A :class:`list` subclass that tracks changes to its contents

    Note:
        This class is for internal use and not intended to be used directly
    """
    def __init__(self, initlist=None, **kwargs):
        self._init_complete = False
        super(ObservableList, self).__init__()
        self.property = kwargs.get('property')
        self.obj = kwargs.get('obj')
        self.parent_observable = kwargs.get('parent')
        if self.property is not None:
            self.copy_on_change = self.property.copy_on_change
        else:
            self.copy_on_change = False
        if initlist is not None:
            self.extend(initlist)
        self._init_complete = True
    def __setitem__(self, key, item):
        old = self._get_copy_or_none()
        item = self._build_observable(item)
        super(ObservableList, self).__setitem__(key, item)
        self._emit_change(keys=[key], old=old)
    def __delitem__(self, key):
        old = self._get_copy_or_none()
        super(ObservableList, self).__delitem__(key)
        self._emit_change(old=old)
    def clear(self):
        old = self._get_copy_or_none()
        super(ObservableList, self).clear()
        self._emit_change(old=old)
    def __iadd__(self, other):
        other = self._build_observable(other)
        self.extend(other)
        return self
    def append(self, item):
        old = self._get_copy_or_none()
        item = self._build_observable(item)
        super(ObservableList, self).append(item)
        self._emit_change(old=old)
    def extend(self, other):
        old = self._get_copy_or_none()
        init = self._init_complete
        self._init_complete = False
        for item in other:
            self.append(item)
        if init:
            self._init_complete = True
        self._emit_change(old=old)
    def remove(self, *args):
        old = self._get_copy_or_none()
        super(ObservableList, self).remove(*args)
        self._emit_change(old=old)

class ObservableDict(dict, Observable):
    """A :class:`dict` subclass that tracks changes to its contents

    Note:
        This class is for internal use and not intended to be used directly
    """
    def __init__(self, initdict=None, **kwargs):
        self._init_complete = False
        super(ObservableDict, self).__init__()
        self.property = kwargs.get('property')
        self.obj = kwargs.get('obj')
        self.parent_observable = kwargs.get('parent')
        if self.property is not None:
            self.copy_on_change = self.property.copy_on_change
        else:
            self.copy_on_change = False
        if initdict is not None:
            self.update(initdict)
        self._init_complete = True
    def __setitem__(self, key, item):
        old = self._get_copy_or_none()
        item = self._build_observable(item)
        super(ObservableDict, self).__setitem__(key, item)
        self._emit_change(keys=[key], old=old)
    def __delitem__(self, key):
        old = self._get_copy_or_none()
        super(ObservableDict, self).__delitem__(key)
        self._emit_change(old=old)
    def update(self, other):
        old = self._get_copy_or_none()
        init = self._init_complete
        self._init_complete = False
        keys = set(other.keys()) - set(self.keys())
        for key, val in other.items():
            if key not in keys and self[key] == val:
                continue
            self[key] = val
            keys.add(key)
        if init:
            self._init_complete = True
        self._emit_change(keys=list(keys), old=old)
    def clear(self):
        old = self._get_copy_or_none()
        super(ObservableDict, self).clear()
        self._emit_change(old=old)
    def pop(self, *args):
        old = self._get_copy_or_none()
        super(ObservableDict, self).pop(*args)
        self._emit_change(old=old)
    def setdefault(self, *args):
        old = self._get_copy_or_none()
        super(ObservableDict, self).setdefault(*args)
        self._emit_change(old=old)


text:
[[warning | Deprecation Notice]]
| The `history_plugin` that the `history_api_plugin` depends upon is deprecated and will no longer be maintained. Please use the [`state_history_plugin`](../state_history_plugin/index.md) or the [`trace_api_plugin`](../trace_api_plugin/index.md) instead.

## Description

The `history_api_plugin` exposes functionality from the [`history_plugin`](../history_plugin/index.md) to the RPC API interface managed by the [`http_plugin`](../http_plugin/index.md), providing read-only access to blockchain data.

It provides four RPC API endpoints:

* get_actions
* get_transaction
* get_key_accounts
* get_controlled_accounts

[[info | More Info]]
| See HISTORY section of [RPC API](https://developers.eos.io/eosio-nodeos/reference).

The four actions listed above are used by the following `cleos` commands (matching order):

* get actions
* get transaction
* get accounts
* get servants

## Usage

```console
# config.ini
plugin = eosio::history_api_plugin
```
```sh
# command-line
nodeos ... --plugin eosio::history_api_plugin
```

## Options

None

## Dependencies

* [`history_plugin`](../history_plugin/index.md)
* [`chain_plugin`](../chain_plugin/index.md)
* [`http_plugin`](../http_plugin/index.md)

### Load Dependency Examples

```console
# config.ini
plugin = eosio::history_plugin
[options]
plugin = eosio::chain_plugin
[options]
plugin = eosio::http_plugin
[options]
```
```sh
# command-line
nodeos ... --plugin eosio::history_plugin [options]  \
           --plugin eosio::chain_plugin [operations] [options]  \
           --plugin eosio::http_plugin [options]
```


text:
package com.streamsets.datacollector.client.cli.command.system;

import com.streamsets.datacollector.client.api.SystemApi;
import com.streamsets.datacollector.client.cli.command.BaseCommand;
import io.airlift.airline.Command;

@Command(name = "disableDPM", description = "Disable DPM")
public class DisableDPMCommand extends BaseCommand {
  @Override
  public void run() {
    try {
      SystemApi systemApi = new SystemApi(getApiClient());
      systemApi.disableDPM();
      System.out.println("Successfully disabled DPM by updating file'etc/dpm.properties'. " +
          "Restart the Data Collector for the changes to take effect. ");
    } catch (Exception ex) {
      if(printStackTrace) {
        ex.printStackTrace();
      } else {
        System.out.println(ex.getMessage());
      }
    }
  }
}


text:
**1. Written For Full Stack Development**

> Your app has a cleanly designed `Express`-based API back-end **and** a well-organized client

**2. Designed to Promote Modular Development**

> MVC patterns from the get go using `BackboneJS`
> Client-side files integrated using AMD via `RequireJS`

**3. Client libraries are already set up for you**

> No need for copying a pasting a bunch of libraries from node_modules.
> RExpress does that for you, right out of the box!

**4. API Authentication Out of the Box**

> `Passport.js` can be enabled with the `--auth` flag when generating a new app

**5. CORS-enabled Out of the Box**

> `CORS` can be enabled with the `-C` option when generating a new app

**6. MongoDB Support Out of the Box**

> Your choice of `Mongoose` or `Monk`. Just use the `-M` or `-m` flags, respectively to enable the one you want.

> Plus, the required `data/db` directory is created for you

**7. Bootstrap + JQuery = OMG!**

> Comes pre-installed with Bootstrap and JQuery

**8. Better Naming Conventions for Public Directories**

> `javascript` --> `js`
> `stylesheets` --> `css`

> Let's get with the program, folks!

**9. Common Client-side Matters Already Dealt With**

> `client/img` Images directory
> `client/fonts` Fonts directory
> `client/templates` Handlebars templates
>
> No app should be without these!

**10. Procfile Generated To Manage Your Deploy**

> `Foreman` is your friend

**11. Prevent Accidental Override of Your App**

> Yup, the `-f` option was removed. No need to put your masterpiece at risk unnecessarily.

**12. All Necessary Modules Are Downloaded By Default**

> You're welcome...


text:
'use strict';

/**
 * @ngdoc function
 * @name 343LandingPageApp.controller:AccountDashboardCtrl
 * @description
 * # AccountDashboardCtrl
 * Controller of the 343LandingPageApp
 */
angular.module('343LandingPageApp')
    .controller('AccountDashboardCtrl', ['$scope', '$http', 'authFact', '$location', function ($scope, $http, authFact, $location) {
        var test = 'test';
        var token = JSON.parse(authFact.getToken()).token;
        var url = 'http://neadcom.wwwss24.a2hosted.com/343TruckingAPI/api/v1/account/dashboard';

        $scope.loadData = function () {

            $http.get(url + '?token=' + token).then(function (response) {

                // success
                if(response.data.status !== 'fail'){
                    $scope.posts = response.data;
                }

            }, function (response) {
                $location.path('/logout');
            });
        }

        /**
        * @description
        * Removes the post from the users profile
        */
        $scope.removePost = function (postId) {

            if (window.confirm("Are you sure you want to delete this?")) {
                var data = {
                    'token': token
                };

                $http.delete('http://neadcom.wwwss24.a2hosted.com/343TruckingAPI/api/v1/trucking/job/' + postId + '?token=' + token, {token:token}).then(function (response) {

                    // success: load data again to refresh the page
                    $scope.loadData();

                }, function (error) {
                    // error
                    console.log(error.data);
                });
            }
        };

        /**
         * @name editJob
         * @description
         * Edits the job details for this job
         * @param {Integer} id
         */
        $scope.loadForm = function (mypost) {
            $scope.jobObject = {
                id: mypost.id,
               title : mypost.title,
               description: mypost.description,
               requirements: mypost.requirements,
               location: mypost.location,
               compensation: mypost.compensation,
               benefits: mypost.benefits,
               howToApply: mypost.howToApply,
               datePosted: mypost.datePosted
            };
        }

        $scope.update = function(mypost){
            $scope.jobObject = {
               id: mypost.id,
               title : mypost.title,
               description: mypost.description,
               requirements: mypost.requirements,
               location: mypost.location,
               compensation: mypost.compensation,
               benefits: mypost.benefits,
               howToApply: mypost.howToApply,
               datePosted: mypost.datePosted
            };

            var urlRequest = 'http://neadcom.wwwss24.a2hosted.com/343TruckingAPI/api/v1/trucking/job/update?token=' + token;

            var req = {
			    method: 'POST',
			    url: urlRequest,
			    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
			    data: $scope.jobObject
		    };

            // send the request to post
            $http(req).then(function(response){
                alert('Succes');
                $scope.loadData();
            }, function(error){
                alert('Failure')
            });
        }

        if (authFact.isUserAuthenticated()) {
            $scope.loadData();
        }
}]);


text:
namespace ompu { namespace midi {

std::ostream& operator<<(std::ostream& os, Message const& v)
{
    boost::ignore_unused(v);
    return os << "TODO: implement (<<) midi::Message";
}

#if 0
std::ostream& operator<<(std::ostream& os, Sysex const& v)
{
    boost::ignore_unused(v);
    return os << "TODO: implement (<<) midi::Sysex";
}
#endif

std::ostream& operator<<(std::ostream& os, Track const& v)
{
    boost::ignore_unused(v);
    return os << "TODO: implement (<<) midi::Track";
}

}} // ompu


text:
var c = Object.create;
var obj4 = c(null, { f4: { value: function() { return 4; }, writable: true }});
var obj3 = c(obj4, { f3: { value: function() { return 3; }, writable: true }});
var obj2 = c(obj3, { f2: { value: function() { return 2; }, writable: true }});
var obj1 = c(obj2, { f1: { value: function() { return 1; }, writable: true }});
var obj0 = c(obj1, { f0: { value: function() { return 0; }, writable: true }});

function get4(obj) { return obj.f4; }

assertEquals(4, get4(obj0)());
assertEquals(4, get4(obj0)());
%OptimizeFunctionOnNextCall(get4);
assertEquals(4, get4(obj0)());
obj4.f4 = function() { return 5; };
assertEquals(5, get4(obj0)());

function get3(obj) { return obj.f3; }

assertEquals(3, get3(obj0)());
assertEquals(3, get3(obj0)());
%OptimizeFunctionOnNextCall(get3);
assertEquals(3, get3(obj0)());
obj2.f3 = function() { return 6; };
assertEquals(6, get3(obj0)());


text:
import { WatsonHealth3DPrintMesh24 } from "../../../";

export = WatsonHealth3DPrintMesh24;


text:
<archimate:Product
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="Soba"
    id="834d5d88-d6b5-4a21-8e9e-253a26d0ebf1"
    documentation="Soba: a JavaScript visualization toolkit released under the MIT license. Soba is a 2D plotting library integrated with Sushi written in JavaScript.
Limited interest for graphs"/>


text:
import * as os from 'os';
import { join } from 'path';
import { writeFile, deleteFile } from '../../utils/fs';
import { ng } from '../../utils/process';
import { expectToFail } from '../../utils/utils';

export default function() {
  const homedir = os.homedir();
  const globalConfigPath = join(homedir, '.angular-config.json');
  return Promise.resolve()
    .then(() => writeFile(globalConfigPath, '{"version":1}'))
    .then(() => process.chdir(homedir))
    .then(() => ng('new', 'proj-name', '--dry-run'))
    .then(() => deleteFile(globalConfigPath))
    // Test that we cannot create a project inside another project.
    .then(() => writeFile(join(homedir, '.angular.json'), '{"version":1}'))
    .then(() => expectToFail(() => ng('new', 'proj-name', '--dry-run')))
    .then(() => deleteFile(join(homedir, '.angular.json')));
}


text:
FROM gcr.io/oss-fuzz-base/base-builder
MAINTAINER flim@google.com
RUN apt-get install -y make autoconf automake libtool wget

RUN git clone https://git.xiph.org/opus.git
RUN wget https://opus-codec.org/static/testvectors/opus_testvectors.tar.gz
WORKDIR opus
COPY build.sh $SRC/


text:
(function(window, document, $) {
    $(document).on('init.dt', function(e, dtSettings) {
        if ( e.namespace !== 'dt' ) {
            return;
        }

        var options = dtSettings.oInit.conditionalPaging;

        if ($.isPlainObject(options) || options === true) {
            var config = $.isPlainObject(options) ? options : {},
                api = new $.fn.dataTable.Api(dtSettings),
                speed = 'slow',
                conditionalPaging = function(e) {
                    var $paging = $(api.table().container()).find('div.dataTables_paginate'),
                        pages = api.page.info().pages;

                    if (e instanceof $.Event) {
                        if (pages <= 1) {
                            if (config.style === 'fade') {
                                $paging.stop().fadeTo(speed, 0);
                            }
                            else {
                                $paging.css('visibility', 'hidden');
                            }
                        }
                        else {
                            if (config.style === 'fade') {
                                $paging.stop().fadeTo(speed, 1);
                            }
                            else {
                                $paging.css('visibility', '');
                            }
                        }
                    }
                    else if (pages <= 1) {
                        if (config.style === 'fade') {
                            $paging.css('opacity', 0);
                        }
                        else {
                            $paging.css('visibility', 'hidden');
                        }
                    }
                };

            if ($.isNumeric(config.speed) || $.type(config.speed) === 'string') {
                speed = config.speed;
            }

            conditionalPaging();

            api.on('draw.dt', conditionalPaging);
        }
    });
})(window, document, jQuery);


text:
extern crate rl_sys;
extern crate nix;
extern crate term;

extern crate flang_common as common;
extern crate flang_compiler as compiler;
extern crate flang_errors as errors;
extern crate parser;

use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::CString;
use std::io::{self, Write};
use std::sync::mpsc::channel;
use std::panic::catch_unwind;
use std::rc::Rc;
use std::str;
use std::sync::{Arc, Mutex};
use std::thread;

use nix::libc;
use rl_sys::readline;

mod directive;
use InputType::*;
use ErrorKind::*;

pub use common::driver::{DriverEnv, ErrorDestination};
use compiler::{IncrCompilerAction, IncrCompiler};
use errors::{DiagnosticBuilder, Handler};
use errors::emitter::{ColorConfig, Emitter, EmitterWriter};
use parser::ast::Stmt;
use parser::ast::StmtKind::*;
use parser::codemap::CodeMap;
use parser::lexer::{Reader, StringReader};
use parser::parser::{filemap_to_parser, parse_tts_from_source_str, ParseSess, Parser, PResult};
use parser::tokenstream::TokenTree;

static WELCOME_MSG: &'static str =
  "Welcome to Flang version 0.1. (Type :help for assistance.)\n";
static DEFAULT_PROMPT: &'static str = "\x1b[33mflang> \x1b[0m";
static CONTINUE_PROMPT: &'static str = "\x1b[33m> \x1b[0m";
static REPL_DUMMY_FILENAME: &'static str = "console.fl";

pub enum InputType<'a> {
  Directive(&'a str, Vec<&'a str>),
  ExternalComamnd(&'a str),
  ExecuteSource(&'a str),
  Empty,
}

pub struct Repl {
  unexecuted_src: SourceFile,
  executed_src: SourceFile,
  compiler: IncrCompiler,
  env: DriverEnv,
}

impl Repl {
  pub fn new(env: DriverEnv) -> Repl {
    Repl {
      unexecuted_src: SourceFile::new(),
      executed_src: SourceFile::new(),
      compiler: IncrCompiler::new(
        REPL_DUMMY_FILENAME.to_owned(),
        env.errdst.clone()),
      env: env,
    }
  }

  fn println(&self, msg: &str) {
    self.env.errdst.borrow_mut().write(msg.as_bytes()).ok();
  }

  pub fn run(&mut self) {
    self.println(WELCOME_MSG);

    let mut prompt: String = DEFAULT_PROMPT.to_string();

    loop {
      match readline::readline(&prompt) {
        Ok(Some(line)) => {
          match self.handle_line(&line) {
            IncrCompilerAction::Done | IncrCompilerAction::Error => {
              prompt = DEFAULT_PROMPT.to_string();
            }
            IncrCompilerAction::Continue => prompt = CONTINUE_PROMPT.to_string(),
            IncrCompilerAction::Quit => break
          }
        }
        Ok(None) => break, // eof
        Err(msg) => {
          self.println(&format!("ERROR: {}", msg));
        }
      }
    }
  }

  fn handle_line(&mut self, line: &str) -> IncrCompilerAction {
    match self.parse_input(line) {
      Directive(d, args) => self.exec_directive(d, args),
      ExecuteSource(line) => self.exec_line(line),
      ExternalComamnd(command) => self.exec_external_program(command),
      Empty => IncrCompilerAction::Done // just enter without any type
    }
  }

  fn parse_input<'a>(&self, line: &'a str) -> InputType<'a> {
    let mut tokens = line.split_whitespace();
    let first_token = tokens.next();

    match first_token {
      Some(first) => match first {
        x if x.starts_with(':') => {
          Directive(&first[1..], tokens.collect::<Vec<_>>())
        }
        x if x.starts_with('!') => ExternalComamnd(&line[1..]),
        _ => ExecuteSource(line)
      },
      None => Empty
    }
  }

  pub fn exec_directive(&self, directive: &str, args: Vec<&str>)
      -> IncrCompilerAction {
    match directive {
      "dump" => {
        self.println(self.executed_src.as_str());
        IncrCompilerAction::Done
      }
      "quit" => IncrCompilerAction::Quit,
      _ => IncrCompilerAction::Done
    }
  }

  fn new_emitter(errdst: ErrorDestination, cm: Rc<CodeMap>)
      -> (Box<Emitter>, Rc<RefCell<Vec<ErrorKind>>>) {
    let ew = match errdst {
      ErrorDestination::Stderr => {
        EmitterWriter::stderr(ColorConfig::Auto, Some(cm))
      }
      ErrorDestination::Raw(ref buf) => {
        let delegator = WriteDelegator {write: buf.clone()};
        EmitterWriter::new(Box::new(delegator), Some(cm))
      }
    };

    let (emitter, errkinds) = EmitterDelegator::new(ew);
    (Box::new(emitter), errkinds)
  }

  pub fn exec_line(&mut self, line: &str) -> IncrCompilerAction {
    self.unexecuted_src.add_line(line);
    let to_be_executed = self.unexecuted_src.as_str().to_owned();

    let action = self.compiler.eval(&to_be_executed);

    match action {
      IncrCompilerAction::Error => {
        self.unexecuted_src.clear();
      }

      IncrCompilerAction::Done => {
        self.unexecuted_src.clear();
        self.executed_src.add_line(&to_be_executed);
      }

      _ => {}
    };

    action
  }

  pub fn exec_external_program(&self, command: &str) -> IncrCompilerAction {
    let c_to_print = CString::new(command).unwrap();
    unsafe { libc::system(c_to_print.as_ptr()); }
    IncrCompilerAction::Done
  }
}

fn parse_flang<'a>(parsess: &'a ParseSess, line: &str) -> Parser<'a> {
  let filemap = parsess
    .codemap()
    .new_filemap_and_lines(REPL_DUMMY_FILENAME, None, line);
  filemap_to_parser(&parsess, filemap)
}

pub struct WriteDelegator {
  write: Rc<RefCell<Box<io::Write + Send>>>
}

unsafe impl Send for WriteDelegator {}

impl io::Write for WriteDelegator {
  fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
    self.write.borrow_mut().write(buf)
  }

  fn flush(&mut self) -> io::Result<()> {
    self.write.borrow_mut().flush()
  }
}

pub struct SourceFile {
  source: String
}

impl SourceFile {
  pub fn new() -> SourceFile {
    SourceFile { source : String::new() }
  }

  pub fn add_line(&mut self, line: &str) {
    self.source.push_str(line);
    self.source.push_str("\n");
  }

  pub fn as_str(&self) -> &str {
    &self.source
  }

  pub fn as_bytes(&self) -> &[u8] {
    self.source.as_bytes()
  }

  pub fn clear(&mut self) {
    self.source.clear();
  }

  pub fn update(&mut self, lines: &str) {
    self.clear();
    self.source.push_str(lines);
  }
}

unsafe impl Sync for SourceFile {}

enum ErrorKind {
  UnclosedDelimiter,
  Unknown
}

struct EmitterDelegator {
  em: EmitterWriter,
  errors: Rc<RefCell<Vec<ErrorKind>>>
}

impl EmitterDelegator {
  pub fn new(em : EmitterWriter)
      -> (EmitterDelegator, Rc<RefCell<Vec<ErrorKind>>>) {
    let errors = Rc::new(RefCell::new(Vec::new()));
    let delegator = EmitterDelegator { em : em, errors: errors.clone() };
    (delegator, errors)
  }
}

impl Emitter for EmitterDelegator {
  fn emit(&mut self, db: &DiagnosticBuilder) {

    let errkind = error_kind(db.message());

    match errkind {
      UnclosedDelimiter => {},
      _ => self.em.emit(db)
    };

    self.errors.borrow_mut().push(errkind);
  }
}

fn error_kind(msg: &str) -> ErrorKind {
  if is_unclosed_delemiter(msg) {
    ErrorKind::UnclosedDelimiter
  } else {
    Unknown
  }
}

fn is_unclosed_delemiter(msg: &str) -> bool {
  msg == "this file contains an un-closed delimiter"
}


text:
package main

import "testing"

// TEST CONTEXT TO PROVIDE CUSTOM ASSERT METHODS ON THE TEST CLASS

type TestContext struct {
	t *testing.T
}

func NewTestCtx(t *testing.T) *TestContext {
	return &TestContext{t}
}

/** These assert* methods return _false_ if the assertion passed and _true_ if it failed. This
    convention is to support easy early exiting on an assertion failure:

     if assert(okay_condition) {return}
 */

func (ctx *TestContext) assertGotErr(expectedMsg string, err error, desc string) bool {
	if ctx.assert(err != nil, "In %s, expected error message '%s' but got no error", desc, expectedMsg) {
		return true
	}
	actualMessage := err.Error()
	return ctx.assert(actualMessage == expectedMsg, "In %s, expected error messge '%s' but got error message '%s'", desc, expectedMsg, actualMessage)
}

func (ctx *TestContext) assertNoErr(err error, desc string) bool {
	if err != nil {
		return ctx.assert(err == nil, "In %s, expected no error, but got error message '%s'", desc, err.Error())
	}
	return false
}

func (ctx *TestContext) assertStrEqual(expected string, actual string, desc string) bool {
	return ctx.assert(expected == actual, "In %s, expected string '%s' but got '%s'", desc, expected, actual)
}

func (ctx *TestContext) assert(cond bool, fmt string, args ...interface{}) bool {
	if !cond {
		ctx.t.Errorf(fmt, args...)
		return true
	} else {
		return false
	}
}