text:
"""
Steady-State Memetic Algorithm
"""

# Author: Dayvid Victor <victor.dvro@gmail.com>
#
# License: BSD 3 clause

import random
import numpy as np

from sklearn.utils.validation import check_X_y
from sklearn.neighbors.classification import KNeighborsClassifier

from ..base import InstanceReductionMixin

class SSMA(InstanceReductionMixin):
    """Steady State Memetic Algorithm

    The Steady-State Memetic Algorithm is an evolutionary prototype
    selection algorithm. It uses a memetic algorithm in order to
    perform a local search in the code.

    Parameters
    ----------
    n_neighbors : int, optional (default = 3)
        Number of neighbors to use by default for :meth:`k_neighbors` queries.

    alpha   : float (default = 0.6)
        Parameter that ponderates the fitness function.

    max_loop    : int (default = 1000)
        Number of maximum loops performed by the algorithm.

    threshold   : int (default = 0)
        Threshold that regulates the substitution condition;

    chromosomes_count: int (default = 10)
        number of chromosomes used to find the optimal solution.

    Attributes
    ----------
    `X_` : array-like, shape = [indeterminated, n_features]
        Selected prototypes.

    `y_` : array-like, shape = [indeterminated]
        Labels of the selected prototypes.

    `reduction_` : float, percentual of reduction.

    Examples
    --------
    >>> from protopy.selection.ssma import SSMA
    >>> import numpy as np
    >>> X = np.array([[i] for i in range(100)])
    >>> y = np.asarray(50 * [0] + 50 * [1])
    >>> ssma = SSMA()
    >>> ssma.fit(X, y)
    SSMA(alpha=0.6, chromosomes_count=10, max_loop=1000, threshold=0)
    >>> print ssma.predict([[40],[60]])
    [0 1]
    >>> print ssma.reduction_
    0.98

    See also
    --------
    sklearn.neighbors.KNeighborsClassifier: nearest neighbors classifier

    References
    ----------
    Joaquín Derrac, Salvador García, and Francisco Herrera. Stratified prototype
    selection based on a steady-state memetic algorithm: a study of scalability.
    Memetic Computing, 2(3):183–199, 2010.

    """
    def __init__(self, n_neighbors=1, alpha=0.6, max_loop=1000, threshold=0, chromosomes_count=10):
        self.n_neighbors = n_neighbors
        self.alpha = alpha
        self.max_loop = max_loop
        self.threshold = threshold
        self.chromosomes_count = chromosomes_count

        self.evaluations = None
        self.chromosomes = None

        self.best_chromosome_ac = -1
        self.best_chromosome_rd = -1

        self.classifier = KNeighborsClassifier(n_neighbors = n_neighbors)

    def accuracy(self, chromosome, X, y):
        mask = np.asarray(chromosome, dtype=bool)
        cX, cy = X[mask], y[mask]
        #print len(cX), len(cy), sum(chromosome)

        self.classifier.fit(cX, cy)
        labels = self.classifier.predict(X)
        accuracy = (labels == y).sum()

        return float(accuracy)/len(y)

    def fitness(self, chromosome, X, y):
        #TODO add the possibility of use AUC for factor1
        ac = self.accuracy(chromosome, X, y)
        rd = 1.0 - (float(sum(chromosome))/len(chromosome))

        return self.alpha * ac + (1.0 - self.alpha) * rd

    def fitness_gain(self, gain, n):
        return self.alpha * (float(gain)/n) + (1 - self.alpha) * (1.0 / n)

    def update_threshold(self, X, y):
        best_index = np.argmax(self.evaluations)
        chromosome = self.chromosomes[best_index]

        best_ac = self.accuracy(chromosome, X, y)
        best_rd = 1.0 - float(sum(chromosome))/len(y)

        if best_ac <= self.best_chromosome_ac:
            self.threshold = self.threshold + 1
        if best_rd <= self.best_chromosome_rd:
            self.threshold = self.threshold - 1

        self.best_chromosome_ac = best_ac
        self.best_chromosome_rd = best_rd

    def index_nearest_neighbor(self, S, X, y):
        classifier = KNeighborsClassifier(n_neighbors=1)

        U = []
        S_mask = np.array(S, dtype=bool, copy=True)
        indexs = np.asarray(range(len(y)))[S_mask]
        X_tra, y_tra = X[S_mask], y[S_mask]

        for i in range(len(y)):
            real_indexes = np.asarray(range(len(y)))[S_mask]
            X_tra, y_tra = X[S_mask], y[S_mask]
            #print len(X_tra), len(y_tra)
            classifier.fit(X_tra, y_tra)
            [[index]] = classifier.kneighbors(X[i], return_distance=False)
            U = U + [real_indexes[index]]

        return U

    def memetic_looper(self, S, R):
        c = 0
        for i in range(len(S)):
            if S[i] == 1 and i not in R:
                c = c + 1
                if c == 2:
                    return True

        return False

    def memetic_select_j(self, S, R):
        indexs = []
        for i in range(len(S)):
            if i not in R and S[i] == 1:
                indexs.append(i)
        # if list is empty wlil return error
        return np.random.choice(indexs)

    def generate_population(self, X, y):
        self.chromosomes = [[np.random.choice([0,1]) for i in range(len(y))]
                            for c in range(self.chromosomes_count)]
        self.evaluations = [self.fitness(c, X, y) for c in self.chromosomes]

        self.update_threshold(X, y)

    def select_parents(self, X, y):
        parents = []
        for i in range(2):
            samples = random.sample(self.chromosomes, 2)
            parents = parents + [samples[0] if self.fitness(samples[0], X, y) >
                                    self.fitness(samples[1], X, y) else samples[1]]
        return np.array(parents, copy=True)

    def crossover(self, parent_1, parent_2):
        size = len(parent_1)
        mask = [0] * (size/2) + [1] * (size - size/2)
        mask = np.asarray(mask, dtype=bool)
        np.random.shuffle(mask)

        off_1 = parent_1 * mask + parent_2 * ~mask
        off_2 = parent_2 * mask + parent_1 * ~mask

        return np.asarray([off_1, off_2])

    def mutation(self, offspring):
        for i in range(len(offspring)):
            if np.random.uniform(0,1) < 1.0/len(offspring):
                offspring[i] = not offspring[i]

        return offspring

    def memetic_search(self, chromosome, X, y, chromosome_fitness = None):
        S = np.array(chromosome, copy=True)
        if S.sum() == 0:
            return S, 0

        if chromosome_fitness == None:
            chromosome_fitness = self.fitness(chromosome, X, y)
        fitness_s = chromosome_fitness

        # List of visited genes in S
        R = []
        # let U = {u0, u1, ..., un} list where ui = classifier(si,S)/i
        U = self.index_nearest_neighbor(S, X, y)

        while self.memetic_looper(S, R):
            j = self.memetic_select_j(S, R)
            S[j] = 0
            gain = 0.0
            U_copy = list(U)
            mask = np.asarray(S, dtype=bool)
            X_tra, y_tra = X[mask], y[mask]
            real_idx = np.asarray(range(len(y)))[mask]

            if len(y_tra) > 0:
                for i in range(len(U)):
                    if U[i] == j:
                        self.classifier.fit(X_tra, y_tra)
                        [[idx]] = self.classifier.kneighbors(X[i], n_neighbors=1,
                                return_distance=False)
                        U[i] = real_idx[idx]

                        if y[i] == y[U_copy[i]] and y[i] != y[U[i]]:
                            gain = gain - 1.0
                        if y[i] != y[U_copy[i]] and y[i] == y[U[i]]:
                            gain = gain + 1.0

            if gain >= self.threshold:
                n = S.sum()
                g = self.fitness_gain(gain, n)
                fitness_s = fitness_s + g
                R = []
            else:
                U = U_copy
                S[j] = 1
                R.append(j)

        return list(S), fitness_s

    def main_loop(self, X, y):
        self.generate_population(X, y)
        n, worse_fit_index = 0, -1
        while (n < self.max_loop):
            parents = self.select_parents(X, y)
            offspring = self.crossover(parents[0], parents[1])
            offspring[0] = self.mutation(offspring[0])
            offspring[1] = self.mutation(offspring[1])

            fit_offs = [self.fitness(off, X, y) if sum(off) > 0 else -1 for off in offspring]

            if worse_fit_index == -1:
                worse_fit_index = np.argmin(self.evaluations)

            for i in range(len(offspring)):
                p_ls = 1.0

                if fit_offs[i] == -1:
                    p_ls = -1

                if fit_offs[i] <= self.evaluations[worse_fit_index]:
                    p_ls = 0.0625

                if np.random.uniform(0,1) < p_ls:

                    offspring[i], fit_offs[i] = self.memetic_search(offspring[i], X, y, chromosome_fitness = fit_offs[i])

            for i in range(len(offspring)):
                if fit_offs[i] > self.evaluations[worse_fit_index]:
                    self.chromosomes[worse_fit_index] = offspring[i]
                    self.evaluations[worse_fit_index] = fit_offs[i]

                    worse_fit_index = np.argmin(self.evaluations)

            n = n + 1
            if n % 10 == 0:
                self.update_threshold(X, y)

    def reduce_data(self, X, y):
        X, y = check_X_y(X, y, accept_sparse="csr")

        classes = np.unique(y)
        self.classes_ = classes

        self.main_loop(X, y)

        best_index = np.argmax(self.evaluations)
        mask = np.asarray(self.chromosomes[best_index], dtype=bool)
        self.X_ = X[mask]
        self.y_ = y[mask]
        self.reduction_ = 1.0 - float(len(self.y_))/len(y)

        return self.X_, self.y_


text:
const memoize = (func, resolver = (a) => a) => {
  const cache = new Map();
  return (...args) => {
    const key = resolver(...args);
    if (cache.has(key)) {
      return cache.get(key);
    }
    const value = func(...args);
    cache.set(key, value);
    return value;
  };
};

export default memoize;

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace application\library;
use application\library\Log as LOG;
use \PDO as PDO;

class DBQuery extends CustomDataModel {

    private $conn;

    protected function initialise($args=null) {

        $this->conn = $this->Connect($this->controller->config['DataBase']['Conn'],
                                     $this->controller->config['DataBase']['Username'],
                                     $this->controller->config['DataBase']['Password']);

    }

    public function queryFromFile($file, $params = null, $mode = PDO::FETCH_ASSOC) {
        return parent::queryFromFile($this->conn, $file, $params, $mode);
    }

    public function executeFromFile($file, $params = null) {
        return parent::executeFromFile($this->conn, $file, $params);
    }

    public function query($sql, $params = null, $mode = PDO::FETCH_ASSOC) {
        return parent::query($this->conn, $sql, $params, $mode);
    }

    public function execute($sql, $params = null) {
        return parent::execute($this->conn, $sql, $params);
    }

    public function lastPDOError() {
        return parent::lastPDOError();
    }

    /**
     *
     * A sample function docblock
     * @global string document the use $_myvar
     * @param string $table database table name
     * @param string $columns
     * @param array $args
     * @return array
     * @tutorial
     *

     *
test

     *

     * @example
     *
     *       $output = array(
     *           'sEcho' => (int) $args['sEcho'],
     *           'iTotalRecords' => $unfilteredTotal,
     *           'iTotalDisplayRecords' => $filteredTotal,
     *           'aaData' => $result->fetchAll()
     *      );
     *
     *
     *********************************************/
    public function serveDataTables($table, $columns, $args) {

        /*
         * Paging
         */

        $limit = '';
        if (isset($args['iDisplayStart']) && $args['iDisplayLength'] != '-1') {
            $limit = 'LIMIT '. (int) $args['iDisplayStart']. ', '. (int) $args['iDisplayLength'];
        }

        /*
         * Ordering
         */
        $order = '';
        if (isset($args['iSortCol_0'])) {
            $order = 'ORDER BY  ';
            for ($i = 0; $i < (int) $args['iSortingCols']; $i++) {
                if ($args[ 'bSortable_'.(int)$args['iSortCol_'.$i] ] == 'true') {
                    $order .= $columns[ (int) $args['iSortCol_'.$i] ]." ".$args['sSortDir_'.$i].", ";
                }
            }

            $order = substr_replace($order, "", -2);
            if ($order == 'ORDER BY') {
                $order = '';
            }
        }

        /*
         * Filtering
         * NOTE this does not match the built-in DataTables filtering which does it
         * word by word on any field. It's possible to do here, but concerned about efficiency
         * on very large tables, and MySQL's regex functionality is very limited
         */

        $numberColumns = count($columns);

        $where = '';
        if (isset($args['sSearch']) && $args['sSearch'] != '') {
            $where = 'WHERE (';
            for ($i = 0; $i < $numberColumns; $i++) {
                $where .= $columns[$i].' LIKE '.$this->conn->quote('%'.$args['sSearch'].'%').' OR ';
            }
            $where = substr_replace($where, "", -3);
            $where .= ')';
        }

        /* Individual column filtering */
        for ($i = 0; $i < $numberColumns; $i++) {
            if (isset($args['bSearchable_'.$i]) && $args['bSearchable_'.$i] == 'true' && $args['sSearch_'.$i] != '') {
                if ($where == '') {
                    $where = 'WHERE ';
                } else {
                    $where .= ' AND ';
                }
                if (is_array($columns[$i])) {
                    $col = $columns[$i][0];
                } else {
                    $col = $columns[$i];
                }
                $search = $args['sSearch_'.$i];
                if (strtoupper($search) == 'NULL') {
                    $where .= $col.' IS NULL ';
                } else {
                    $where .= $col.' LIKE '.$this->conn->quote('%'.$search.'%').' ';
                }
            }
        }

        /*
         * SQL queries
         * Get data to display
         *
         * NOTE: There is a performance issue with SQL_CALC_FOUND_ROWS on large datasets
         *       see http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/
         *       experience here confirms SQL_CALC_FOUND_ROWS on a very large table is dire!!!!
         */

        /*$query = 'SELECT SQL_CALC_FOUND_ROWS '
               . str_replace(' , ', ' ', implode(', ', $columns))
               . " FROM $table $where $order $limit";
        $this->controller->log($query);
        $result = $this->conn->query($query);*/

        /* Data set length after filtering */
        /*$query = 'SELECT FOUND_ROWS()';
        $this->controller->log($query);
        $filteredTotal = $this->conn->query($query)->fetchColumn();*/

        //This is variable value is used for to decide whether we need to fetch rows count or not on each page loaded.
        $cacheRowsCount = 100;

        /* Data set length after filtering */
        if (!isset($args['iTotalDisplayRecords']) || (isset($args['iTotalDisplayRecords']) && isset($args['iTotalDisplayRecords']) < $cacheRowsCount)) {
            $query = "SELECT COUNT(*) FROM $table $where $order";
            $args['iTotalDisplayRecords'] = $this->conn->query($query)->fetchColumn();
        }

        /* Result set after filtering */
        $query = 'SELECT '
        . str_replace(' , ', ' ', implode(', ', $columns))
        . " FROM $table $where $order $limit";

        $this->log(LOG::DEBUG, 'ServeDataTables: '.$query);

        // 26/06/2012
        // return only indexed result set to client
        $result = $this->conn->query($query, PDO::FETCH_NUM);

        /* Total data set length */
        if (!isset($args['iTotalRecords'])  || (isset($args['iTotalRecords']) && isset($args['iTotalRecords']) < $cacheRowsCount)) {
            $query = "SELECT COUNT(*) FROM $table $where";
            $args['iTotalRecords'] = $this->conn->query($query)->fetchColumn();
        }
        /*
         * Output
         */
        if (!isset($args['sEcho'])) {
            $args['sEcho'] = '';
        }

        $output = array(
                'sEcho' => (int) $args['sEcho'],
                'iTotalRecords' => $args['iTotalRecords'],
                'iTotalDisplayRecords' => $args['iTotalDisplayRecords'],
                'aaData' => $result->fetchAll()
        );

        return $output;
    }

}


text:
package com.amazonaws.services.frauddetector.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The details of the model version.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ModelVersionDetail implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The model ID.
     *

     */
    private String modelId;
    /**
     *

     * The model type.
     *

     */
    private String modelType;
    /**
     *

     * The model version number.
     *

     */
    private String modelVersionNumber;
    /**
     *

     * The status of the model version.
     *

     */
    private String status;
    /**
     *

     * The model version training data source.
     *

     */
    private String trainingDataSource;
    /**
     *

     * The training data schema.
     *

     */
    private TrainingDataSchema trainingDataSchema;
    /**
     *

     * The external events data details. This will be populated if the trainingDataSource for the model
     * version is specified as EXTERNAL_EVENTS.
     *

     */
    private ExternalEventsDetail externalEventsDetail;
    /**
     *

     * The ingested events data details. This will be populated if the trainingDataSource for the model
     * version is specified as INGESTED_EVENTS.
     *

     */
    private IngestedEventsDetail ingestedEventsDetail;
    /**
     *

     * The training results.
     *

     */
    private TrainingResult trainingResult;
    /**
     *

     * The timestamp when the model was last updated.
     *

     */
    private String lastUpdatedTime;
    /**
     *

     * The timestamp when the model was created.
     *

     */
    private String createdTime;
    /**
     *

     * The model version ARN.
     *

     */
    private String arn;
    /**
     *

     * The training result details. The details include the relative importance of the variables.
     *

     */
    private TrainingResultV2 trainingResultV2;

    /**
     *

     * The model ID.
     *

     *
     * @param modelId
     *        The model ID.
     */

    public void setModelId(String modelId) {
        this.modelId = modelId;
    }

    /**
     *

     * The model ID.
     *

     *
     * @return The model ID.
     */

    public String getModelId() {
        return this.modelId;
    }

    /**
     *

     * The model ID.
     *

     *
     * @param modelId
     *        The model ID.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withModelId(String modelId) {
        setModelId(modelId);
        return this;
    }

    /**
     *

     * The model type.
     *

     *
     * @param modelType
     *        The model type.
     * @see ModelTypeEnum
     */

    public void setModelType(String modelType) {
        this.modelType = modelType;
    }

    /**
     *

     * The model type.
     *

     *
     * @return The model type.
     * @see ModelTypeEnum
     */

    public String getModelType() {
        return this.modelType;
    }

    /**
     *

     * The model type.
     *

     *
     * @param modelType
     *        The model type.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ModelTypeEnum
     */

    public ModelVersionDetail withModelType(String modelType) {
        setModelType(modelType);
        return this;
    }

    /**
     *

     * The model type.
     *

     *
     * @param modelType
     *        The model type.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ModelTypeEnum
     */

    public ModelVersionDetail withModelType(ModelTypeEnum modelType) {
        this.modelType = modelType.toString();
        return this;
    }

    /**
     *

     * The model version number.
     *

     *
     * @param modelVersionNumber
     *        The model version number.
     */

    public void setModelVersionNumber(String modelVersionNumber) {
        this.modelVersionNumber = modelVersionNumber;
    }

    /**
     *

     * The model version number.
     *

     *
     * @return The model version number.
     */

    public String getModelVersionNumber() {
        return this.modelVersionNumber;
    }

    /**
     *

     * The model version number.
     *

     *
     * @param modelVersionNumber
     *        The model version number.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withModelVersionNumber(String modelVersionNumber) {
        setModelVersionNumber(modelVersionNumber);
        return this;
    }

    /**
     *

     * The status of the model version.
     *

     *
     * @param status
     *        The status of the model version.
     */

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     *

     * The status of the model version.
     *

     *
     * @return The status of the model version.
     */

    public String getStatus() {
        return this.status;
    }

    /**
     *

     * The status of the model version.
     *

     *
     * @param status
     *        The status of the model version.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withStatus(String status) {
        setStatus(status);
        return this;
    }

    /**
     *

     * The model version training data source.
     *

     *
     * @param trainingDataSource
     *        The model version training data source.
     * @see TrainingDataSourceEnum
     */

    public void setTrainingDataSource(String trainingDataSource) {
        this.trainingDataSource = trainingDataSource;
    }

    /**
     *

     * The model version training data source.
     *

     *
     * @return The model version training data source.
     * @see TrainingDataSourceEnum
     */

    public String getTrainingDataSource() {
        return this.trainingDataSource;
    }

    /**
     *

     * The model version training data source.
     *

     *
     * @param trainingDataSource
     *        The model version training data source.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see TrainingDataSourceEnum
     */

    public ModelVersionDetail withTrainingDataSource(String trainingDataSource) {
        setTrainingDataSource(trainingDataSource);
        return this;
    }

    /**
     *

     * The model version training data source.
     *

     *
     * @param trainingDataSource
     *        The model version training data source.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see TrainingDataSourceEnum
     */

    public ModelVersionDetail withTrainingDataSource(TrainingDataSourceEnum trainingDataSource) {
        this.trainingDataSource = trainingDataSource.toString();
        return this;
    }

    /**
     *

     * The training data schema.
     *

     *
     * @param trainingDataSchema
     *        The training data schema.
     */

    public void setTrainingDataSchema(TrainingDataSchema trainingDataSchema) {
        this.trainingDataSchema = trainingDataSchema;
    }

    /**
     *

     * The training data schema.
     *

     *
     * @return The training data schema.
     */

    public TrainingDataSchema getTrainingDataSchema() {
        return this.trainingDataSchema;
    }

    /**
     *

     * The training data schema.
     *

     *
     * @param trainingDataSchema
     *        The training data schema.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withTrainingDataSchema(TrainingDataSchema trainingDataSchema) {
        setTrainingDataSchema(trainingDataSchema);
        return this;
    }

    /**
     *

     * The external events data details. This will be populated if the trainingDataSource for the model
     * version is specified as EXTERNAL_EVENTS.
     *

     *
     * @param externalEventsDetail
     *        The external events data details. This will be populated if the trainingDataSource for the
     *        model version is specified as EXTERNAL_EVENTS.
     */

    public void setExternalEventsDetail(ExternalEventsDetail externalEventsDetail) {
        this.externalEventsDetail = externalEventsDetail;
    }

    /**
     *

     * The external events data details. This will be populated if the trainingDataSource for the model
     * version is specified as EXTERNAL_EVENTS.
     *

     *
     * @return The external events data details. This will be populated if the trainingDataSource for the
     *         model version is specified as EXTERNAL_EVENTS.
     */

    public ExternalEventsDetail getExternalEventsDetail() {
        return this.externalEventsDetail;
    }

    /**
     *

     * The external events data details. This will be populated if the trainingDataSource for the model
     * version is specified as EXTERNAL_EVENTS.
     *

     *
     * @param externalEventsDetail
     *        The external events data details. This will be populated if the trainingDataSource for the
     *        model version is specified as EXTERNAL_EVENTS.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withExternalEventsDetail(ExternalEventsDetail externalEventsDetail) {
        setExternalEventsDetail(externalEventsDetail);
        return this;
    }

    /**
     *

     * The ingested events data details. This will be populated if the trainingDataSource for the model
     * version is specified as INGESTED_EVENTS.
     *

     *
     * @param ingestedEventsDetail
     *        The ingested events data details. This will be populated if the trainingDataSource for the
     *        model version is specified as INGESTED_EVENTS.
     */

    public void setIngestedEventsDetail(IngestedEventsDetail ingestedEventsDetail) {
        this.ingestedEventsDetail = ingestedEventsDetail;
    }

    /**
     *

     * The ingested events data details. This will be populated if the trainingDataSource for the model
     * version is specified as INGESTED_EVENTS.
     *

     *
     * @return The ingested events data details. This will be populated if the trainingDataSource for the
     *         model version is specified as INGESTED_EVENTS.
     */

    public IngestedEventsDetail getIngestedEventsDetail() {
        return this.ingestedEventsDetail;
    }

    /**
     *

     * The ingested events data details. This will be populated if the trainingDataSource for the model
     * version is specified as INGESTED_EVENTS.
     *

     *
     * @param ingestedEventsDetail
     *        The ingested events data details. This will be populated if the trainingDataSource for the
     *        model version is specified as INGESTED_EVENTS.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withIngestedEventsDetail(IngestedEventsDetail ingestedEventsDetail) {
        setIngestedEventsDetail(ingestedEventsDetail);
        return this;
    }

    /**
     *

     * The training results.
     *

     *
     * @param trainingResult
     *        The training results.
     */

    public void setTrainingResult(TrainingResult trainingResult) {
        this.trainingResult = trainingResult;
    }

    /**
     *

     * The training results.
     *

     *
     * @return The training results.
     */

    public TrainingResult getTrainingResult() {
        return this.trainingResult;
    }

    /**
     *

     * The training results.
     *

     *
     * @param trainingResult
     *        The training results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withTrainingResult(TrainingResult trainingResult) {
        setTrainingResult(trainingResult);
        return this;
    }

    /**
     *

     * The timestamp when the model was last updated.
     *

     *
     * @param lastUpdatedTime
     *        The timestamp when the model was last updated.
     */

    public void setLastUpdatedTime(String lastUpdatedTime) {
        this.lastUpdatedTime = lastUpdatedTime;
    }

    /**
     *

     * The timestamp when the model was last updated.
     *

     *
     * @return The timestamp when the model was last updated.
     */

    public String getLastUpdatedTime() {
        return this.lastUpdatedTime;
    }

    /**
     *

     * The timestamp when the model was last updated.
     *

     *
     * @param lastUpdatedTime
     *        The timestamp when the model was last updated.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withLastUpdatedTime(String lastUpdatedTime) {
        setLastUpdatedTime(lastUpdatedTime);
        return this;
    }

    /**
     *

     * The timestamp when the model was created.
     *

     *
     * @param createdTime
     *        The timestamp when the model was created.
     */

    public void setCreatedTime(String createdTime) {
        this.createdTime = createdTime;
    }

    /**
     *

     * The timestamp when the model was created.
     *

     *
     * @return The timestamp when the model was created.
     */

    public String getCreatedTime() {
        return this.createdTime;
    }

    /**
     *

     * The timestamp when the model was created.
     *

     *
     * @param createdTime
     *        The timestamp when the model was created.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withCreatedTime(String createdTime) {
        setCreatedTime(createdTime);
        return this;
    }

    /**
     *

     * The model version ARN.
     *

     *
     * @param arn
     *        The model version ARN.
     */

    public void setArn(String arn) {
        this.arn = arn;
    }

    /**
     *

     * The model version ARN.
     *

     *
     * @return The model version ARN.
     */

    public String getArn() {
        return this.arn;
    }

    /**
     *

     * The model version ARN.
     *

     *
     * @param arn
     *        The model version ARN.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withArn(String arn) {
        setArn(arn);
        return this;
    }

    /**
     *

     * The training result details. The details include the relative importance of the variables.
     *

     *
     * @param trainingResultV2
     *        The training result details. The details include the relative importance of the variables.
     */

    public void setTrainingResultV2(TrainingResultV2 trainingResultV2) {
        this.trainingResultV2 = trainingResultV2;
    }

    /**
     *

     * The training result details. The details include the relative importance of the variables.
     *

     *
     * @return The training result details. The details include the relative importance of the variables.
     */

    public TrainingResultV2 getTrainingResultV2() {
        return this.trainingResultV2;
    }

    /**
     *

     * The training result details. The details include the relative importance of the variables.
     *

     *
     * @param trainingResultV2
     *        The training result details. The details include the relative importance of the variables.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ModelVersionDetail withTrainingResultV2(TrainingResultV2 trainingResultV2) {
        setTrainingResultV2(trainingResultV2);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getModelId() != null)
            sb.append("ModelId: ").append(getModelId()).append(",");
        if (getModelType() != null)
            sb.append("ModelType: ").append(getModelType()).append(",");
        if (getModelVersionNumber() != null)
            sb.append("ModelVersionNumber: ").append(getModelVersionNumber()).append(",");
        if (getStatus() != null)
            sb.append("Status: ").append(getStatus()).append(",");
        if (getTrainingDataSource() != null)
            sb.append("TrainingDataSource: ").append(getTrainingDataSource()).append(",");
        if (getTrainingDataSchema() != null)
            sb.append("TrainingDataSchema: ").append(getTrainingDataSchema()).append(",");
        if (getExternalEventsDetail() != null)
            sb.append("ExternalEventsDetail: ").append(getExternalEventsDetail()).append(",");
        if (getIngestedEventsDetail() != null)
            sb.append("IngestedEventsDetail: ").append(getIngestedEventsDetail()).append(",");
        if (getTrainingResult() != null)
            sb.append("TrainingResult: ").append(getTrainingResult()).append(",");
        if (getLastUpdatedTime() != null)
            sb.append("LastUpdatedTime: ").append(getLastUpdatedTime()).append(",");
        if (getCreatedTime() != null)
            sb.append("CreatedTime: ").append(getCreatedTime()).append(",");
        if (getArn() != null)
            sb.append("Arn: ").append(getArn()).append(",");
        if (getTrainingResultV2() != null)
            sb.append("TrainingResultV2: ").append(getTrainingResultV2());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof ModelVersionDetail == false)
            return false;
        ModelVersionDetail other = (ModelVersionDetail) obj;
        if (other.getModelId() == null ^ this.getModelId() == null)
            return false;
        if (other.getModelId() != null && other.getModelId().equals(this.getModelId()) == false)
            return false;
        if (other.getModelType() == null ^ this.getModelType() == null)
            return false;
        if (other.getModelType() != null && other.getModelType().equals(this.getModelType()) == false)
            return false;
        if (other.getModelVersionNumber() == null ^ this.getModelVersionNumber() == null)
            return false;
        if (other.getModelVersionNumber() != null && other.getModelVersionNumber().equals(this.getModelVersionNumber()) == false)
            return false;
        if (other.getStatus() == null ^ this.getStatus() == null)
            return false;
        if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
            return false;
        if (other.getTrainingDataSource() == null ^ this.getTrainingDataSource() == null)
            return false;
        if (other.getTrainingDataSource() != null && other.getTrainingDataSource().equals(this.getTrainingDataSource()) == false)
            return false;
        if (other.getTrainingDataSchema() == null ^ this.getTrainingDataSchema() == null)
            return false;
        if (other.getTrainingDataSchema() != null && other.getTrainingDataSchema().equals(this.getTrainingDataSchema()) == false)
            return false;
        if (other.getExternalEventsDetail() == null ^ this.getExternalEventsDetail() == null)
            return false;
        if (other.getExternalEventsDetail() != null && other.getExternalEventsDetail().equals(this.getExternalEventsDetail()) == false)
            return false;
        if (other.getIngestedEventsDetail() == null ^ this.getIngestedEventsDetail() == null)
            return false;
        if (other.getIngestedEventsDetail() != null && other.getIngestedEventsDetail().equals(this.getIngestedEventsDetail()) == false)
            return false;
        if (other.getTrainingResult() == null ^ this.getTrainingResult() == null)
            return false;
        if (other.getTrainingResult() != null && other.getTrainingResult().equals(this.getTrainingResult()) == false)
            return false;
        if (other.getLastUpdatedTime() == null ^ this.getLastUpdatedTime() == null)
            return false;
        if (other.getLastUpdatedTime() != null && other.getLastUpdatedTime().equals(this.getLastUpdatedTime()) == false)
            return false;
        if (other.getCreatedTime() == null ^ this.getCreatedTime() == null)
            return false;
        if (other.getCreatedTime() != null && other.getCreatedTime().equals(this.getCreatedTime()) == false)
            return false;
        if (other.getArn() == null ^ this.getArn() == null)
            return false;
        if (other.getArn() != null && other.getArn().equals(this.getArn()) == false)
            return false;
        if (other.getTrainingResultV2() == null ^ this.getTrainingResultV2() == null)
            return false;
        if (other.getTrainingResultV2() != null && other.getTrainingResultV2().equals(this.getTrainingResultV2()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getModelId() == null) ? 0 : getModelId().hashCode());
        hashCode = prime * hashCode + ((getModelType() == null) ? 0 : getModelType().hashCode());
        hashCode = prime * hashCode + ((getModelVersionNumber() == null) ? 0 : getModelVersionNumber().hashCode());
        hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
        hashCode = prime * hashCode + ((getTrainingDataSource() == null) ? 0 : getTrainingDataSource().hashCode());
        hashCode = prime * hashCode + ((getTrainingDataSchema() == null) ? 0 : getTrainingDataSchema().hashCode());
        hashCode = prime * hashCode + ((getExternalEventsDetail() == null) ? 0 : getExternalEventsDetail().hashCode());
        hashCode = prime * hashCode + ((getIngestedEventsDetail() == null) ? 0 : getIngestedEventsDetail().hashCode());
        hashCode = prime * hashCode + ((getTrainingResult() == null) ? 0 : getTrainingResult().hashCode());
        hashCode = prime * hashCode + ((getLastUpdatedTime() == null) ? 0 : getLastUpdatedTime().hashCode());
        hashCode = prime * hashCode + ((getCreatedTime() == null) ? 0 : getCreatedTime().hashCode());
        hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode());
        hashCode = prime * hashCode + ((getTrainingResultV2() == null) ? 0 : getTrainingResultV2().hashCode());
        return hashCode;
    }

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

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.frauddetector.model.transform.ModelVersionDetailMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
<!DOCTYPE html
  PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>fn_propcontrol</title><meta name="generator" content="MATLAB 8.5"><link rel="schema.DC" href="http://purl.org/dc/elements/1.1/"><meta name="DC.date" content="2017-01-07"><meta name="DC.source" content="help_fn_propcontrol.m">

fn_propcontrol

Contents

Syntax

Description

Source

Syntax

fn_propcontrol(obj,prop,spec,graphic object options...)
fn_propcontrol(obj,prop,spec,{graphic object options...})
hu = fn_propcontrol.createcontrol(...)

Description

Create a control that will be synchronized to an object property value.
Use the static method fn_propcontrol.createcontrol (3rd syntax above) to
return the graphic handle of the control rather than the fn_propcontrol
object.

Input:
- obj     the object whose property is observed
- prop    the name of the observed property THIS PROPERTY MUST BE SET AS
          OBSERVABLE, AND ITS SET ACCESS MUST BE PUBLIC
- spec    specification of both the value type and the control style:
          . for logical values: 'checkbox', 'radiobutton' or 'menu'
          . for numerical and char values: 'char', 'double', 'uint8', etc
          . for list of values: {spec value1 value2 ...}
            or {spec {values...} {labels...} [{shortlabels...}]} where
            spec is any of 'listbox', 'checkbox', 'pushbutton', 'menu'
            (one entry with sub-entries), 'menuval' (same, and value is
            indicated on the top-level entry), 'menugroup' (multiple
            entries at the first level) Under these two options, two
            special behaviors are available:
            * if 'labels' has one value less than 'values', the last
              element of 'values' is considered as a default value that
              is set when unchecking the current value (such value would
              typically be '', [] or 0).
            * if on the contrary 'labels' has one more value than
              'values' (typically, 'others...'), this label is checked
              whenever the property value is not in the list, and when
              this label is pressed, a small input window lets the user
              select the desired value
- options options for the graphic object that will be created
          - If spec is 'menu', 'menuval' or 'menugroup', it is mandatory
          that options will contain the pair ('parent',parentmenu).
          - Labels should be set with property 'string' for 'checkbox',
          'char', 'double', etc., and with property 'label' for
          'menu', etc. If not specified, the name of the observed
          property is used.
          For better readability, options can be nested inside a cell
          array.

See also: fn_menugroup, fn_control

Source

Thomas Deneux

Copyright 2015-2017

Published with MATLAB® R2015a


text:
package org.geometerplus.fbreader.library;

import org.fbreader.util.Pair;

import org.geometerplus.zlibrary.core.resources.ZLResource;

import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.Filter;

public class SyncLabelTree extends FilteredTree {
	public final String Label;
	private final ZLResource myResource;

	SyncLabelTree(SyncTree parent, String label, Filter filter, ZLResource resource) {
		super(parent, filter, -1);
		Label = label;
		myResource = resource;
	}

	@Override
	public String getName() {
		return myResource.getValue();
	}

	@Override
	public Pair<String,String> getTreeTitle() {
		return new Pair(getSummary(), null);
	}

	@Override
	public String getSummary() {
		return myResource.getResource("summary").getValue();
	}

	@Override
	protected String getStringId() {
		return "@SyncLabelTree " + Label;
	}

	@Override
	public boolean isSelectable() {
		return false;
	}

	@Override
	public Status getOpeningStatus() {
		return Status.ALWAYS_RELOAD_BEFORE_OPENING;
	}

	@Override
	protected boolean createSubtree(Book book) {
		return createBookWithAuthorsSubtree(book);
	}
}


text:
// [[[[INFO>
// Copyright 2015 Epicycle (http://epicycle.org, https://github.com/open-epicycle)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information check https://github.com/open-epicycle/Epicycle.Math-cs
// ]]]]

using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra;
using System.Linq;

namespace Epicycle.Math.LinearAlgebra
{
    public abstract class BaseMatrix : IMatrix
    {
        // creates zero matrix
        protected BaseMatrix(int rowCount, int colCount)
        {
            _data = new DenseMatrix(rowCount, colCount);
        }

        protected BaseMatrix(Matrix<double> data)
        {
            _data = data;
        }

        protected readonly Matrix<double> _data;

        public static implicit operator OMatrix(BaseMatrix matrix)
        {
            return new OMatrix(matrix);
        }

        internal Matrix<double> Data
        {
            get { return _data; }
        }

        public int RowCount
        {
            get { return _data.RowCount; }
        }

        public int ColumnCount
        {
            get { return _data.ColumnCount; }
        }

        public double this[int row, int col]
        {
            get { return _data[row, col]; }
        }

        public IMatrix Add(IMatrix matrix)
        {
            var that = (BaseMatrix)matrix; // Liskov violated because Add is morally a multi-method

            return new Matrix(this._data + that._data);
        }

        public IMatrix Subtract(IMatrix matrix)
        {
            var that = (BaseMatrix)matrix; // Liskov violated because Multiply is morally a multi-method

            return new Matrix(this._data - that._data);
        }

        public IMatrix Multiply(IMatrix matrix)
        {
            var that = (BaseMatrix)matrix; // Liskov violated because Multiply is morally a multi-method

            return new Matrix(this._data * that._data);
        }

        public IVector Multiply(IVector vector)
        {
            var that = (Vector)vector; // Liskov violated because... Oops, no good excuse

            return new Vector(this._data * that.Data);
        }

        public IMatrix Multiply(double scalar)
        {
            return new Matrix(scalar * _data);
        }

        public IMatrix Divide(double scalar)
        {
            return new Matrix((1 / scalar) * _data);
        }

        public IVector GetRow(int i)
        {
            return new Vector(_data.Row(i));
        }

        public IVector GetColumn(int j)
        {
            return new Vector(_data.Column(j));
        }

        public double FrobeniusNorm()
        {
            return _data.FrobeniusNorm();
        }

        public abstract ISquareMatrix AsSquare();

        public abstract IMatrix Transposed();
        public abstract IVector ApplyTransposed(IVector vector);

        public static OMatrix operator +(BaseMatrix m1, BaseMatrix m2)
        {
            return new OMatrix(m1.Add(m2));
        }

        public static OMatrix operator -(BaseMatrix m1, BaseMatrix m2)
        {
            return new OMatrix(m1.Subtract(m2));
        }

        public static OMatrix operator *(BaseMatrix m1, BaseMatrix m2)
        {
            return new OMatrix(m1.Multiply(m2));
        }

        public static OVector operator *(BaseMatrix m, Vector v)
        {
            return new OVector(m.Multiply(v));
        }

        public static OMatrix operator *(double x, BaseMatrix m)
        {
            return new OMatrix(m.Multiply(x));
        }

        public static OMatrix operator *(BaseMatrix m, double x)
        {
            return new OMatrix(m.Multiply(x));
        }

        public static OMatrix operator /(BaseMatrix m, double x)
        {
            return new OMatrix(m.Divide(x));
        }

        public override string ToString()
        {
            if (RowCount > 4 || ColumnCount > 4)
            {
                return base.ToString();
            }
            else
            {
                return "(" + string.Join(", ", _data.EnumerateRows().Select(x => x.ToString()).ToArray()) + ")";
            }
        }
    }
}


text:
using System;
using Microsoft.Z3;

namespace JetBrains.ReSharper.Plugin.AgentZero
{
  public class Program
  {
    static void Main(string[] args)
    {
      var other = new Other();
      other.M();
    }
  }

  public class Other
  {
    public Status M()
    {
      using (var context = new Context())
      {
        var variable = (BitVecExpr) context.MkConst("x", context.MkBitVecSort(32));

        var solver = context.MkSolver();

        var num42 = context.MkBV(v: 42, size: 32);
        var num43 = context.MkBV(v: 43, size: 32);

        solver.Assert(context.MkBVSGT(variable, num42));
        solver.Assert(context.MkBVSLT(variable, num43));

        //context.MkReal();

        return solver.Check();

        //Console.WriteLine(status);
      }
    }
  }
}


text:
using namespace std;
namespace po = boost::program_options;

int main(int argc, char** argv)
{
	// SP_CNN defaults
	unsigned int numCNNunits = 1;
	std::string memInstanceFile = "ini/DDR3_micron_16M_8B_x8_sg15.ini";
	std::string systemIniFile = "system.ini";
	std::string rel_dir = ".";
	unsigned mem_size = 2048;
	uint32_t num_mshr = 64;
	uint32_t max_num_out_mem_req = 1;
	uint32_t bytes_per_mem_request = 64;
	uint32_t bytes_per_cnn_elem = 1;
	uint64_t cnnClkFreqHz = 200 * 1000 * 1000;
	uint32_t num_alus = 1;
	uint32_t cell_to_pe_ratio = 40;
	uint32_t max_num_assigned_partitions = 1;

	std::string geneName;
	std::string inputFile;
	unsigned int cnnM, cnnN;
	unsigned int interval;
	std::string part_trav_order;
	std::string run_type;
	std::string correctOutFile;

	po::options_description desc("Allowed options");

	std::string program(argv[0]);

	desc.add_options()
					("help,h", "produce help message")
					// Required positional parameters
					("gene_name", po::value<std::string>(&geneName)->required(), "cnn gene")
					("input_file", po::value<std::string>(&inputFile)->required(), "input file")
					("run_type", po::value<std::string>(&run_type)->required(), "cnn_p run-type either (fixed-interval or early-finish)")
					("cnnM", po::value<unsigned int>(&cnnM)->required(), "cnn_p number of rows")
					("cnnN", po::value<unsigned int>(&cnnN)->required(), "cnn_p number of columns")
					("interval_length", po::value<unsigned int>(&interval)->required(), "interval length")
					("part_trav_order", po::value<std::string>(&part_trav_order)->required(), "partition traversal order")
					("correct_output", po::value<std::string>(&correctOutFile)->required(), "correct output file")
					// Optional parameters
					("num_cnnP", po::value<unsigned int>(&numCNNunits), "number of CNN_P units")
					("dram_mem_file", po::value<std::string>(&memInstanceFile), "DRAM SIM 2 memory specification file")
					("dram_sys_file", po::value<std::string>(&systemIniFile), "DRAM SIM 2 system specification file")
					("dram_rel_dir", po::value<std::string>(&rel_dir), "DRAM SIM 2 relative directory of filenames")
					("mem_size", po::value<unsigned>(&mem_size), "memory size (in MB)")
					("cnn_freq", po::value<uint64_t>(&cnnClkFreqHz), "CNN_P frequency (in MHz)")
					("mshr_size", po::value<uint32_t>(&num_mshr), "number of mshr entries for CNN_P")
					("max_num_mem_req", po::value<uint32_t>(&max_num_out_mem_req), "max number of mem requests per cycle for CNN_P")
					("bytes_per_mem_req", po::value<uint32_t>(&bytes_per_mem_request), "bytes per memory request")
					("bytes_per_cnn_elem", po::value<uint32_t>(&bytes_per_cnn_elem), "bytes per single cnn element value")
					("num_alus", po::value<uint32_t>(&num_alus), "number of alus used by CNN_P (must be 1 or 2 currently)")
					("cell_to_pe_ratio", po::value<uint32_t>(&cell_to_pe_ratio), "the cell to pe ratio for CNN_P")
					("max_num_assigned_part", po::value<uint32_t>(&max_num_assigned_partitions), "maximum number of assigned partitions for CNN_P")
					;

	po::positional_options_description positionalOptions;
	positionalOptions.add("gene_name", 1);
	positionalOptions.add("input_file", 1);
	positionalOptions.add("run_type", 1);
	positionalOptions.add("cnnM", 1);
	positionalOptions.add("cnnN", 1);
	positionalOptions.add("interval_length", 1);
	positionalOptions.add("part_trav_order", 1);
	positionalOptions.add("correct_output", 1);

	po::variables_map vm;
	po::store(po::command_line_parser(argc, argv).options(desc)
			.positional(positionalOptions).run(), vm);

	if (vm.count("help")) {
		rad::OptionPrinter::printStandardAppDesc(program, std::cout, desc, &positionalOptions);
		return 0;
	}

	po::notify(vm);

	if (vm.count("cnn_freq"))
		cnnClkFreqHz *= 1000 * 1000;

	CNNGene* gene = CNNGeneFactory::createCNNGene(geneName);

	BWImage testIn, correctOutput;
	testIn.dlmread(inputFile, " ");
	correctOutput.dlmread(correctOutFile, " ");
	CNNInput* input = gene->getInput(testIn.getImage(), testIn.R(), testIn.C());

	SP_CNN sp_cnn(testIn.R(), testIn.C(),  gene->r(), cnnM, cnnN, numCNNunits,
			memInstanceFile, systemIniFile, rel_dir,
			mem_size, num_mshr, max_num_out_mem_req, bytes_per_mem_request, bytes_per_cnn_elem,
			cnnClkFreqHz, num_alus, cell_to_pe_ratio, max_num_assigned_partitions);

	SP_CNN::RunData runData = sp_cnn.run(gene, input, interval, part_trav_order, run_type);

	BWImage sp_cnnOut(testIn.R(), testIn.C());
	sp_cnn.copyOutput(sp_cnnOut.getImage());

	cout << geneName << "(" << inputFile << "," << numCNNunits << "," << interval << ")";
	cout << ": (" << runData.virtualConvTime << "," << runData.cycle_count << "," << runData.actualTimeMs;
	unsigned int numPixelsDiff = correctOutput.numPixelsDiff(&sp_cnnOut);
	double percentDiff = ((double)numPixelsDiff) / ((double)(testIn.R() * testIn.C()));
	cout << "," << numPixelsDiff << "," << percentDiff << ")" << endl;

	cout << std::endl;
	cout << std::endl;

	ofstream file;
	file.open("sim_config.cfg");
	file << "GENE: " << geneName << std::endl;
	file << "INPUT_FILE: " << inputFile << std::endl;
	file << "RUN_TYPE: " << run_type << std::endl;
	file << "CNN_M: " << cnnM << std::endl;
	file << "CNN_N: " << cnnN << std::endl;
	file << "INTERVAL: " << interval << std::endl;
	file << "PART_TRAV_ORDER: " << part_trav_order << std::endl;
	file << "CORRECT_OUTPUT: " << correctOutFile << std::endl;
	file << "NUM_CNNP: " << numCNNunits << std::endl;
	file << "DRAM_MEM_FILE: " << memInstanceFile << std::endl;
	file << "DRAM_SYS_FILE: " << systemIniFile << std::endl;
	file << "DRAM_REL_DIR: " << rel_dir << std::endl;
	file << "MEM_SIZE: " << mem_size << std::endl;
	file << "CNN_FREQ: " << cnnClkFreqHz << std::endl;
	file << "MSHR_SIZE: " << num_mshr << std::endl;
	file << "MAX_NUM_MEM_REQ: " << max_num_out_mem_req << std::endl;
	file << "BYTES_PER_MEM_REQ: " << bytes_per_mem_request << std::endl;
	file << "BYTES_PER_CNN_ELEM: " << bytes_per_cnn_elem << std::endl;
	file << "NUM_ALUS: " << num_alus << std::endl;
	file << "CELL_TO_PE_RATIO: " << cell_to_pe_ratio << std::endl;
	file << "MAX_NUM_ASSIGNED_PART: " << max_num_assigned_partitions << std::endl;
	file.close();

	for (std::vector<std::vector<PartitionExecutionStats*>>::iterator it = runData.execution_stats.begin();
			it != runData.execution_stats.end(); it++) {
		for (std::vector<PartitionExecutionStats*>::iterator jt = it->begin(); jt != it->end(); jt++) {
			PartitionExecutionStats* partExec = *jt;;
			partExec->computeTimes();
		}
	}

	for (int i = 0; i < runData.numPartitions; i++) {
		for (std::vector<std::vector<PartitionExecutionStats*>>::iterator it = runData.execution_stats.begin();
				it != runData.execution_stats.end(); it++) {
			int count = 0;
			for (std::vector<PartitionExecutionStats*>::iterator jt = it->begin(); jt != it->end(); jt++) {
				PartitionExecutionStats* partExec = *jt;;
				if (partExec->partitionId == i) {
					count++;
				}
			}
			assert(count == 1);
		}
	}

	file.open("virt_conv_time.csv");
	file << "Virtual Convergence Time";
	for (int i = 1; i <= runData.numIters; i++) {
		file << "," << i;
	}
	file << std::endl;

	for (int i = 0; i < runData.numPartitions; i++) {
		file << i;
		for (std::vector<std::vector<PartitionExecutionStats*>>::iterator it = runData.execution_stats.begin();
				it != runData.execution_stats.end(); it++) {
			for (std::vector<PartitionExecutionStats*>::iterator jt = it->begin(); jt != it->end(); jt++) {
				PartitionExecutionStats* partExec = *jt;;
				if (partExec->partitionId == i) {
					file << "," << partExec->virt_conv_time;
				}
			}
		}
		file << std::endl;
	}
	file.close();

	file.open("core_time.csv");
	file << "Core Time";
	for (int i = 1; i <= runData.numIters; i++) {
		file << "," << i;
	}
	file << std::endl;

	for (int i = 0; i < runData.numPartitions; i++) {
		file << i;
		for (std::vector<std::vector<PartitionExecutionStats*>>::iterator it = runData.execution_stats.begin();
				it != runData.execution_stats.end(); it++) {
			for (std::vector<PartitionExecutionStats*>::iterator jt = it->begin(); jt != it->end(); jt++) {
				PartitionExecutionStats* partExec = *jt;;
				if (partExec->partitionId == i) {
					file << "," << partExec->coreTime;
				}
			}
		}
		file << std::endl;
	}
	file.close();

	file.open("exec_time.csv");
	file << "Exec Time";
	for (int i = 1; i <= runData.numIters; i++) {
		file << "," << i;
	}
	file << std::endl;

	for (int i = 0; i < runData.numPartitions; i++) {
		file << i;
		for (std::vector<std::vector<PartitionExecutionStats*>>::iterator it = runData.execution_stats.begin();
				it != runData.execution_stats.end(); it++) {
			for (std::vector<PartitionExecutionStats*>::iterator jt = it->begin(); jt != it->end(); jt++) {
				PartitionExecutionStats* partExec = *jt;;
				if (partExec->partitionId == i) {
					file << "," << partExec->execTime;
				}
			}
		}
		file << std::endl;
	}
	file.close();

	file.open("exec_time_diff.csv");
	file << "Exec Time Diff";
	for (int i = 1; i <= runData.numIters; i++) {
		file << "," << i;
	}
	file << std::endl;

	for (int i = 0; i < runData.numPartitions; i++) {
		file << i;
		for (std::vector<std::vector<PartitionExecutionStats*>>::iterator it = runData.execution_stats.begin();
				it != runData.execution_stats.end(); it++) {
			for (std::vector<PartitionExecutionStats*>::iterator jt = it->begin(); jt != it->end(); jt++) {
				PartitionExecutionStats* partExec = *jt;;
				if (partExec->partitionId == i) {
					file << "," << partExec->execTimeDiff;
				}
			}
		}
		file << std::endl;
	}
	file.close();

	file.open("read_time.csv");
	file << "Read Time";
	for (int i = 1; i <= runData.numIters; i++) {
		file << "," << i;
	}
	file << std::endl;

	for (int i = 0; i < runData.numPartitions; i++) {
		file << i;
		for (std::vector<std::vector<PartitionExecutionStats*>>::iterator it = runData.execution_stats.begin();
				it != runData.execution_stats.end(); it++) {
			for (std::vector<PartitionExecutionStats*>::iterator jt = it->begin(); jt != it->end(); jt++) {
				PartitionExecutionStats* partExec = *jt;;
				if (partExec->partitionId == i) {
					file << "," << partExec->readTime;
				}
			}
		}
		file << std::endl;
	}
	file.close();

	file.open("write_time.csv");
	file << "Write Time";
	for (int i = 1; i <= runData.numIters; i++) {
		file << "," << i;
	}
	file << std::endl;

	for (int i = 0; i < runData.numPartitions; i++) {
		file << i;
		for (std::vector<std::vector<PartitionExecutionStats*>>::iterator it = runData.execution_stats.begin();
				it != runData.execution_stats.end(); it++) {
			for (std::vector<PartitionExecutionStats*>::iterator jt = it->begin(); jt != it->end(); jt++) {
				PartitionExecutionStats* partExec = *jt;;
				if (partExec->partitionId == i) {
					file << "," << partExec->writeTime;
				}
			}
		}
		file << std::endl;
	}
	file.close();

	file.open("wait_time.csv");
	file << "Wait Time";
	for (int i = 1; i <= runData.numIters; i++) {
		file << "," << i;
	}
	file << std::endl;

	for (int i = 0; i < runData.numPartitions; i++) {
		file << i;
		for (std::vector<std::vector<PartitionExecutionStats*>>::iterator it = runData.execution_stats.begin();
				it != runData.execution_stats.end(); it++) {
			for (std::vector<PartitionExecutionStats*>::iterator jt = it->begin(); jt != it->end(); jt++) {
				PartitionExecutionStats* partExec = *jt;;
				if (partExec->partitionId == i) {
					file << "," << partExec->waitTime;
				}
			}
		}
		file << std::endl;
	}
	file.close();

	return 0;
}


text:
import random
import time
import math

class MonteCarloTreeSearch(object):
	def __init__(self, game, simulationPlayerClass, turnTime = 30):
		self.game = game
		self.state = str(game)
		self.child_states = self.game.get_child_states()
		self.children = None
		self.isLeaf = True
		self.turnTime = turnTime
		self.points = 0.0
		self.playouts = 0
		self.simulationClass = simulationPlayerClass

	def _enumerateChildren(self):
		self.children = {}
		for childState in self.child_states:
			child = self.game.make_new_instance()
			child.load_state_from_string(childState)
			self.children[childState] = MonteCarloTreeSearch(child, self.simulationClass, self.turnTime)

	def getPoints(self):
		return self.points

	def getVisits(self):
		return self.playouts

	def _selectChildState(self):
		bestScore = 0.0
		bestStates = []
		scalar = 1 #math.sqrt(2.0)
		for childState in self.child_states:
			child = self.children[childState]
			exploit = 0
			explore = 0
			if child.getVisits() > 0:
				exploit = child.getPoints()/child.getVisits()
				explore = math.sqrt(2.0 * math.log(self.playouts)/float(child.getVisits()))
			else:
				return childState
			score = exploit + scalar * explore
			if score == bestScore:
				bestStates.append(childState)
			elif score > bestScore:
				bestStates = [childState]
				bestScore = score
		return random.choice(bestStates)

	def _simulation(self, numGames = 1):
		outcomes = [0,0,0]
		for i in range(numGames):
			randomGame = self.game.make_new_instance()
			randomGame.force_quiet()
			randomGame.set_players([None, self.simulationClass(), self.simulationClass()])
			winner = randomGame.play()
			outcomes[winner] += 1
		return outcomes

	def _updateScores(self, result):
		self.playouts += sum(result)
		self.points += 50*result[0] # should this be 100/numPlayers instead of 100/2 ?
		self.points += 100*result[self.game.get_player_num()]

	def search(self):
		searchStartTime = time.time()
		while (time.time() - searchStartTime < self.turnTime):
			self._selection() #calling _selection on self, no need to update scores

	def _selection(self):
		if self.isLeaf:
			if self.game.is_game_over():
				winner = self.game.winner
				outcome = [0,0,0]
				outcome[winner] = 1
				self._updateScores(outcome)
				return outcome
			else:
				self._enumerateChildren()
				chosenChildState = self._selectChildState()
				result = self.children[chosenChildState]._simulation()
				self.children[chosenChildState]._updateScores(result)
				self._updateScores(result)
				self.isLeaf = False
				return result
		else:
			chosenChildState = self._selectChildState()
			result = self.children[chosenChildState]._selection()
			self._updateScores(result)
			return result

	def childByState(self, childState):
		if self.children is not None:
			if childState in self.children:
				return self.children[childState]
		#something probably went wrong...
		raise ValueError("in MonteCarloTreeSearch.childByState, childState did not exist!")

	def bestMove(self):
		bestState = None
		maxPoints = -1
		for childState in self.child_states:
			childPoints = self.children[childState].getPoints()
			if childPoints > maxPoints:
				bestState = childState
				maxPoints = childPoints
		bestMove = self.game.get_child_state2move_dict()[bestState]
		return (bestState, bestMove)


text:
<?php
namespace Admin\System\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class TaskController extends AbstractActionController
{
	public function indexAction()
	{
		echo 'Task';exit();
		return new ViewModel();
	}
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.StrictMode;

import com.google.android.gms.gcm.GcmNetworkManager;
import com.google.android.gms.gcm.OneoffTask;
import com.google.android.gms.gcm.Task;

import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.chrome.browser.externalauth.ExternalAuthUtils;
import org.chromium.chrome.browser.externalauth.UserRecoverableErrorHandler;

/**
 * The {@link BackgroundSyncLauncher} singleton is created and owned by the C++ browser. It
 * registers interest in waking up the browser the next time the device goes online after the
 * browser closes via the {@link #setLaunchWhenNextOnline} method.
 *
 * Thread model: This class is to be run on the UI thread only.
 */
public class BackgroundSyncLauncher {
    private static final String TAG = "BgSyncLauncher";

    public static final String TASK_TAG = "BackgroundSync Event";

    static final String PREF_BACKGROUND_SYNC_LAUNCH_NEXT_ONLINE = "bgsync_launch_next_online";
    // The instance of BackgroundSyncLauncher currently owned by a C++
    // BackgroundSyncLauncherAndroid, if any. If it is non-null then the browser is running.
    private static BackgroundSyncLauncher sInstance;

    private GcmNetworkManager mScheduler;

    /**
     * Disables the automatic use of the GCMNetworkManager. When disabled, the methods which
     * interact with GCM can still be used, but will not be called automatically on creation, or by
     * {@link #launchBrowserIfStopped}.
     *
     * Automatic GCM use is disabled by tests, and also by this class if it is determined on
     * creation that the installed Play Services library is out of date.
     */
    private static boolean sGCMEnabled = true;

    /**
     * Create a BackgroundSyncLauncher object, which is owned by C++.
     * @param context The app context.
     */
    @VisibleForTesting
    @CalledByNative
    protected static BackgroundSyncLauncher create(Context context) {
        if (sInstance != null) {
            throw new IllegalStateException("Already instantiated");
        }

        sInstance = new BackgroundSyncLauncher(context);
        return sInstance;
    }

    /**
     * Called when the C++ counterpart is deleted.
     */
    @VisibleForTesting
    @CalledByNative
    protected void destroy() {
        assert sInstance == this;
        sInstance = null;
    }

    /**
     * Callback for {@link #shouldLaunchBrowserIfStopped}. The run method is invoked on the UI
     * thread.
     */
    public static interface ShouldLaunchCallback { public void run(Boolean shouldLaunch); }

    /**
     * Returns whether the browser should be launched when the device next goes online.
     * This is set by C++ and reset to false each time {@link BackgroundSyncLauncher}'s singleton is
     * created (the native browser is started). This call is asynchronous and will run the callback
     * on the UI thread when complete.
     * @param context The application context.
     * @param sharedPreferences The shared preferences.
     */
    protected static void shouldLaunchBrowserIfStopped(
            final Context context, final ShouldLaunchCallback callback) {
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
                return prefs.getBoolean(PREF_BACKGROUND_SYNC_LAUNCH_NEXT_ONLINE, false);
            }
            @Override
            protected void onPostExecute(Boolean shouldLaunch) {
                callback.run(shouldLaunch);
            }
        }.execute();
    }

    /**
     * Manages the scheduled tasks which re-launch the browser when the device next goes online
     * after at least {@code minDelayMs} milliseconds.
     * This method is called by C++ as background sync registrations are added and removed. When the
     * {@link BackgroundSyncLauncher} singleton is created (on browser start), this is called to
     * remove any pre-existing scheduled tasks.
     * @param context The application context.
     * @param shouldLaunch Whether or not to launch the browser in the background.
     * @param minDelayMs The minimum time to wait before checking on the browser process.
     */
    @VisibleForTesting
    @CalledByNative
    protected void launchBrowserIfStopped(
            final Context context, final boolean shouldLaunch, final long minDelayMs) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
                prefs.edit()
                        .putBoolean(PREF_BACKGROUND_SYNC_LAUNCH_NEXT_ONLINE, shouldLaunch)
                        .apply();
                return null;
            }
            @Override
            protected void onPostExecute(Void params) {
                if (sGCMEnabled) {
                    if (shouldLaunch) {
                        RecordHistogram.recordBooleanHistogram(
                                "BackgroundSync.LaunchTask.ScheduleSuccess",
                                scheduleLaunchTask(context, mScheduler, minDelayMs));
                    } else {
                        RecordHistogram.recordBooleanHistogram(
                                "BackgroundSync.LaunchTask.CancelSuccess",
                                removeScheduledTasks(mScheduler));
                    }
                }
            }
        }.execute();
    }

    /**
     * Returns true if the native browser has started and created an instance of {@link
     * BackgroundSyncLauncher}.
     */
    protected static boolean hasInstance() {
        return sInstance != null;
    }

    protected BackgroundSyncLauncher(Context context) {
        mScheduler = GcmNetworkManager.getInstance(context);
        launchBrowserIfStopped(context, false, 0);
    }

    private static boolean canUseGooglePlayServices(Context context) {
        return ExternalAuthUtils.getInstance().canUseGooglePlayServices(
                context, new UserRecoverableErrorHandler.Silent());
    }

    /**
     * Returns true if the Background Sync Manager should be automatically disabled on startup.
     * This is currently only the case if Play Services is not up to date, since any sync attempts
     * which fail cannot be reregistered. Better to wait until Play Services is updated before
     * attempting them.
     *
     * @param context The application context.
     */
    @CalledByNative
    private static boolean shouldDisableBackgroundSync(Context context) {
        // Check to see if Play Services is up to date, and disable GCM if not.
        // This will not automatically set {@link sGCMEnabled} to true, in case it has been
        // disabled in tests.
        if (sGCMEnabled) {
            boolean isAvailable = true;
            if (!canUseGooglePlayServices(context)) {
                setGCMEnabled(false);
                Log.i(TAG, "Disabling Background Sync because Play Services is not up to date.");
                isAvailable = false;
            }
            RecordHistogram.recordBooleanHistogram(
                    "BackgroundSync.LaunchTask.PlayServicesAvailable", isAvailable);
        }
        return !sGCMEnabled;
    }

    private static boolean scheduleLaunchTask(
            Context context, GcmNetworkManager scheduler, long minDelayMs) {
        // Google Play Services may not be up to date, if the application was not installed through
        // the Play Store. In this case, scheduling the task will fail silently.
        final long minDelaySecs = minDelayMs / 1000;
        OneoffTask oneoff = new OneoffTask.Builder()
                                    .setService(ChromeBackgroundService.class)
                                    .setTag(TASK_TAG)
                                    // We have to set a non-zero execution window here
                                    .setExecutionWindow(minDelaySecs, minDelaySecs + 1)
                                    .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
                                    .setPersisted(true)
                                    .setUpdateCurrent(true)
                                    .build();
        try {
            scheduler.schedule(oneoff);
        } catch (IllegalArgumentException e) {
            // Disable GCM for the remainder of this session.
            setGCMEnabled(false);
            // Return false so that the failure will be logged.
            return false;
        }
        return true;
    }

    private static boolean removeScheduledTasks(GcmNetworkManager scheduler) {
        // Third-party code causes broadcast to touch disk. http://crbug.com/614679
        StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
        try {
            scheduler.cancelTask(TASK_TAG, ChromeBackgroundService.class);
        } catch (IllegalArgumentException e) {
            // This occurs when BackgroundSyncLauncherService is not found in the application
            // manifest. This should not happen in code that reaches here, but has been seen in
            // the past. See https://crbug.com/548314
            // Disable GCM for the remainder of this session.
            setGCMEnabled(false);
            // Return false so that the failure will be logged.
            return false;
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
        return true;
    }

    /**
     * Reschedule any required background sync tasks, if they have been removed due to an
     * application upgrade.
     *
     * This method checks the saved preferences, and reschedules the sync tasks as appropriate
     * to match the preferences.
     * This method is static so that it can be run without actually instantiating a
     * BackgroundSyncLauncher.
     */
    protected static void rescheduleTasksOnUpgrade(final Context context) {
        final GcmNetworkManager scheduler = GcmNetworkManager.getInstance(context);
        BackgroundSyncLauncher.ShouldLaunchCallback callback =
                new BackgroundSyncLauncher.ShouldLaunchCallback() {
                    @Override
                    public void run(Boolean shouldLaunch) {
                        if (shouldLaunch) {
                            // It's unclear what time the sync event was supposed to fire, so fire
                            // without delay and let the browser reschedule if necessary.
                            // TODO(iclelland): If this fails, report the failure via UMA (not now,
                            // since the browser is not running, but on next startup.)
                            scheduleLaunchTask(context, scheduler, 0);
                        }
                    }
                };
        BackgroundSyncLauncher.shouldLaunchBrowserIfStopped(context, callback);
    }

    @VisibleForTesting
    static void setGCMEnabled(boolean enabled) {
        sGCMEnabled = enabled;
    }
}


text:
class UserController < ApplicationController
  def login
  end

  def admin_login
    session[:login] = 1
    flash[:notice] = "Admin user successfully logged in."
    redirect_to :controller => :admin
  end

  def logout
    session[:login] = nil
    flash[:notice] = "User logged out."
    redirect_to :controller => :home
  end

end


text:
<!doctype html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Novas funcionalidades no Magento 2.0 | Rafael Corrêa Gomes</title>
<meta name="generator" content="Jekyll v3.7.4" />
<meta property="og:title" content="Novas funcionalidades no Magento 2.0" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="Conheças novas funcionalidades do Magento na sua nova versão, magento 2 veio com tudo, saiba também se vale a pena pra você fazer essa mudança agora." />
<meta property="og:description" content="Conheças novas funcionalidades do Magento na sua nova versão, magento 2 veio com tudo, saiba também se vale a pena pra você fazer essa mudança agora." />
<link rel="canonical" href="https://rafaelstz.github.io/blog/magento/novas-funcionalidades-no-magento2.html" />
<meta property="og:url" content="https://rafaelstz.github.io/blog/magento/novas-funcionalidades-no-magento2.html" />
<meta property="og:site_name" content="Rafael Corrêa Gomes" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2016-03-12T22:30:10-05:00" />

<link type="application/atom+xml" rel="alternate" href="https://rafaelstz.github.io/feed.xml" title="Rafael Corrêa Gomes" />
<link rel="amphtml" href="https://rafaelstz.github.io//amp/blog/magento/novas-funcionalidades-no-magento2.html">

<link type="application/json" rel="alternate" title="Rafael Corrêa Gomes" href="https://rafaelstz.github.io/feed.json">
<meta name="google-site-verification" content="L9c-obQotAu449hc8pH_AeHVeyOcPZVg0gDFdOPcl_o" />
<meta name="robots" content="index,follow">

<link rel="apple-touch-icon" sizes="57x57" href="https://rafaelstz.github.io/assets/favicon/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="https://rafaelstz.github.io/assets/favicon/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="https://rafaelstz.github.io/assets/favicon/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="https://rafaelstz.github.io/assets/favicon/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="https://rafaelstz.github.io/assets/favicon/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="https://rafaelstz.github.io/assets/favicon/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="https://rafaelstz.github.io/assets/favicon/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="https://rafaelstz.github.io/assets/favicon/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="https://rafaelstz.github.io/assets/favicon/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="https://rafaelstz.github.io/assets/favicon/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="https://rafaelstz.github.io/assets/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="https://rafaelstz.github.io/assets/favicon/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="https://rafaelstz.github.io/assets/favicon/favicon-16x16.png">
<link rel="manifest" href="https://rafaelstz.github.io/manifest.json">
<meta name="msapplication-TileColor" content="#000000">
<meta name="msapplication-TileImage" content="https://rafaelstz.github.io/assets/favicon/ms-icon-144x144.png">
<meta name="theme-color" content="#000000">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

<link rel="manifest" href="https://rafaelstz.github.io/manifest.json"/>

<link rel="stylesheet" href="https://rafaelstz.github.io/assets/css/normalize.css">
<link rel="stylesheet" href="https://rafaelstz.github.io/assets/css/zeit.css">
<link rel="stylesheet" href="https://rafaelstz.github.io/assets/css/base.css">

    Rafael Corrêa Gomes

    Articles
    Talks
    Projects

Novas funcionalidades no Magento 2.0

Home

blog

magento

Magento 2.0 foi oficialmente anunciado em 2010, quando Yoav Kutner, co-fundador e CTO Magento, disse que 'finalmente, a plataforma Magento é madura suficiente para se exigir uma nova versão'.

Entusiastas Magento em todo o mundo esperava por esta nova versão desde então, mas levou cinco longos anos para Magento lançar esta versão do Magento, e finalmente em 17 de novembro de 2015 a nova versão estava disponível para download no site do Magento.

O lançamento da nova versão atrasou-se em parte porque a empresa foi adquirida pelo eBay em 2011, e eBay tinha algumas expectativas diferentes da versão nova do que o originais co-fundadores. Aparentemente, isto resultou em Yoav deixando a empresa dentro de um ano de aquisição.

Fonte da imagem

Como fãs Magento esperaram tempo suficiente para ver esta nova versão do Magento, naturalmente têm grandes expectativas sobre ela também. É esperado dizer que o Magento mudou muito com a nova versão da versão 2.0. Magento 2.0 oferece escalabilidade e desempenho melhorado, muitas novas funcionalidades são adicionadas para simplificar o processo de compras e checkout para aumentar a taxa de conversão, e com o cache de página inteira, a velocidade de recarga da página é significativamente melhorada.

Em suma, com a nova plataforma esperamos ajudar empresas em todo o globo entregar um envolvente omnichannel, compras, experiências para seus clientes de forma simples e econômica.

Neste artigo, vou resumir brevemente alguns pontos-chave desta nova versão do Magento.

Full-Page Cache baseado em Varnish

Magento é um sistema de gerenciamento de conteúdo enorme. Este volume vem ao custo de tempo de carregamento de página lento. Tinha sido a principal preocupação dos desenvolvedores Magento, melhorar o tempo de carregamento de página do Magento para melhorar a experiência do usuário e aumentar a taxa de conversão do site. Varnish foi amplamente utilizado para implementar o full-page cache no Magento para melhorar o tempo de carregamento da página.

Tendo percebido essa necessidade, Magento 2.0 vem com Varnish pre-integrado ao conteúdo da página de cache, e isto fez a página carregar em cerca de 50% mais rápido que as versões anteriores. Para mim, essa melhoria é bastante significativa.

Reforçar a experiência de compras

Magento 2.0 não só melhorou o tempo de carregamento da página, mas também melhorou em muitos outros aspectos de experiências de compras dos usuários. Muitos temas responsivos podem ser adicionados, com seu local de fácil acesso às diferentes plataformas e dispositivos.

O processo de checkout tornou-se muito mais simples. No passado, quase todos os sites de Magento usavam extensões de terceiros como OnePageCheckout para melhorar o processo de checkout.

Com Magento 2.0, o processo de checkout foi feito simples por padrão. Presume-se o checkout como convidado, e não há nenhuma necessidade de selecionar o tipo de cartão, automaticamente é determinado pelo tipo de número de cartão de crédito, então muitos campos de check-out desnecessários são eliminados, tornando-se muito mais fácil para os usuários a verificação. Tabelas de dados relacionadas com checkout também são separadas, e agora os usuários não vão sentir a velocidade de consulta de banco de dados.

Base de código mais enxuta e limpa

Todas as versões anteriores do Magento versões vieram na mesma base de código. Com anos de desenvolvimento, a base de código tornou-se monstruosa, com um monte de código legado ruim. Magento 2.0 é um novo começo, então com uma base de código mais limpa, é mais fácil de manter e editar, e como há menos arquivos, é mais rápido também. Espero que a equipe do Magento continue mantendo esse código base limpo em todas as versões futuras.

Problema de bloqueio de tabela melhorada

Um gargalo significativo para o Magento foram os atrasos causados pelo problema de travamento de tabela. O problema que costumava ocorrer quando um processo tinha que escrever em alguma tabela ele bloqueava antes de escrever para que nenhum outro processo pudesse escrever nela enquanto ele estava escrevendo.

Para grandes lojas quando muitos processos simultâneos tinham que escrever na mesma tabela causava uma fila, e os processos tinham de esperar pela sua vez  para bloquear e escrever na tabela. Com cache melhorado e otimizações de tabelas robusta, Magento 2.0 promete significativamente resolver esse problema.

Design melhorado do painel admin

Com Magento 2.0, o velho design do painel admin desagradável se foi. Ele vem com um painel de administração que está muito mais fácil de usar e intuitivo e com touch habilitado, assim você pode facilmente usá-lo em seus dispositivos móveis também.

Criação de novos produtos e importação de produtos agora é muito mais fácil e até quatro vezes mais rápido com o novo design. Você pode salvar novas exibições no painel de admin, para ter acesso rápido a informação que são vitais para as suas necessidades de negócios. E como é simplificada e mais intuitiva, é fácil aprender para as pessoas que são novas no Magento.

Pagamento seguro e novas integrações

Magento 2.0 tornou muito mais fácil implementar vários gateways de pagamento novos e estabelecidos como PayPal, Authorize.net e BrainTree. Todas estas integrações de pagamento vem com maior segurança e conformidade de PCI. Magento Enterprise Edition também vem com integrações WorldPay e CyberSource.

Fácil manutenção e Upgrades

Aqueles que têm experiência de manter um site Magento sabem como foi difícil atualizar para sua versão mais recente. Com a versão 2.0 do Magento, é para ser uma tarefa muito mais rápida e fácil. Como a base de código é muito mais enxuta e vem com arquitetura moderna e modular, o custo e a complexidade da manutenção do site serão também significativamente reduzidos.

Você está pronto para migrar para o Magento 2.0?

Eu sei, como todos os usuários do Magento, se você tem trabalhado em um projeto Magento, você também ficou animado com esta nova versão. Mas antes de você dar o salto de migrar seu site de versão 1. x para 2.0, há algumas coisas a considerar.

Dê uma olhada em suas extensões. Muitas extensões amplamente utilizadas agora são construídas para a nova versão do Magento, e isto é especialmente verdade para a Enterprise edition. Muitos outros já estão disponíveis para a nova versão ou estarão disponíveis nas próximas semanas. No entanto, ainda há muitas extensões que levará algum tempo para estar disponível para Magento 2.0. Se seu site estiver usando qualquer uma dessas extensões, é melhor esperar até que você tenha todas as suas extensões essenciais disponíveis para esta nova versão.

Se você fez lotes de personalização no seu site Magento e passou um tempo significativo e dinheiro sobre essa personalização, melhor que reconsiderasse sua idéia da migração para a versão 2.0. Como esta nova versão é completamente uma fera diferente, você pode acabar gastando muito mais tempo e recursos para migrar.

Para obter mais informações sobre migração, veja meu tutorial recente sobre a Migração para Magento 2.

Conclusão

Só faz alguns meses desde o lançamento público desta edição do Magento. As pessoas tinham grandes expectativas de encontrarem muitas grandes extensões.

Eu pessoalmente acho que esta nova versão vai dar um impulso para o Magento no longo prazo. Ela vai torná-lo mais robusto e como user- e developer-friendly como qualquer CMS moderno deve ser, que francamente as versões anteriores não foram.

Magento é uma solução de comércio eletrônico poderoso e está ficando cada vez mais forte com cada versão. Você está apenas começando, ou você está começando com a próxima versão, não se esqueça de verificar as extensões disponíveis para você também.

Rafael Corrêa Gomes

I'm Lead Software Engineer at Imagination Media Magento Partner, Magento Master 2018, 3x certified, open source evangelist.

Share

            Twitter

            Facebook

            Google+

    Please enable JavaScript to view the comments powered by Disqus.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>
    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="assets/css/bootstrap.css" rel="stylesheet">

    <link href="assets/css/bootstrap-responsive.css" rel="stylesheet">

    <link rel="shortcut icon" href="assets/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">

      StatApp

           Info

        Help

          Contact

          Main

          Distributions

          Models

          Tests

      Linear

      Click Me


text:
class AddUniversityToCourse < ActiveRecord::Migration
  def change
    add_reference :courses, :university, index: true
  end
end


text:
<?xml version="1.0"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one or more
  ~ contributor license agreements.  See the NOTICE file distributed with
  ~ this work for additional information regarding copyright ownership.
  ~ The ASF licenses this file to You under the Apache License, Version 2.0
  ~ (the "License"); you may not use this file except in compliance with
  ~ the License.  You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
  xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.servicecomb</groupId>
    <artifactId>transport-rest</artifactId>
    <version>2.3.0</version>
  </parent>
  <artifactId>transport-rest-servlet</artifactId>
  <name>Java Chassis::Transports::Rest::Servlet</name>

  <dependencies>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.servicecomb</groupId>
      <artifactId>transport-rest-client</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.servicecomb</groupId>
      <artifactId>registry-service-center</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.servicecomb</groupId>
      <artifactId>foundation-test-scaffolding</artifactId>
    </dependency>
  </dependencies>
</project>


text:
const AccountProfile = require('./model');
const AccountProfileManager = require('./manager');

module.exports = {
    model: AccountProfile,
    manager: AccountProfileManager
};


text:
SimpleSocialVideo PHP Class
===========================

*Develop by Julien HAY*

*Licensed under the MIT license : http://opensource.org/licenses/MIT*

Class PHP to get infos from Youtube or Vimeo video, thumbnail, title, description.

Example
-------

```php
<?php

namespace simple;
use Exception;

require '../src/simple/SimpleSocialVideo.php';

$valid_url_youtube = 'http://www.youtube.com/watch?v=wGvZWPOpZAE';

try {

    $video = new SimpleSocialVideo($valid_url_youtube);

    echo '<p>Provider : '.$video->getProvider().'</p>';
    echo '<p>Video ID : '.$video->getVideoId().'</p>';
    echo '<p>Video title : '.$video->getVideoTitle().'</p>';

    echo '<p>Video : '.$video->iframePlayer(800, 600, true, false, true).'</p>';

    echo '<p>Small Thumb : <img src="'.$video->getThumbnailUrl().'" /></p>';
    echo '<p>Medium Thumb : <img src="'.$video->getThumbnailUrl('medium').'" /></p>';
    echo '<p>Large Thumb : <img src="'.$video->getThumbnailUrl('large').'" /></p>';
    echo '<p>Max Thumb : <img src="'.$video->getThumbnailUrl('max').'" /></p>';

} catch (Exception $e) {
    echo '<strong>'.$e->getMessage().'</strong>';
}

?>
```

Composer Install
----------------

- Create file composer.json with this content :

```json

{
	"require" :
	{
		"simple/simplesocialvideo": "dev-master"
	}
}
```

- Tape ```composer install```
- Create file example.php
```php
<?php

require ('vendor/autoload.php');
$video = new simple\SimpleSocialVideo($URL);

?>
```
- And now you can use Simple Social Video


text:
package org.jgentleframework.configure.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.jgentleframework.configure.AnnotatingRuntimeException;

/**
 * Annotates members of your class (methods, fields, parameters) or Class with
 * which the container should annotate annotations. In all cases, a member can
 * be annotated regardless of its Java access specifier (private, default,
 * protected, public).
 *
 * @author LE QUOC CHUNG - mailto: skydunkpro@yahoo.com
 * @date Apr 21, 2008
 * @see Inject
 */
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.TYPE, ElementType.METHOD, ElementType.FIELD,
		ElementType.CONSTRUCTOR, ElementType.PARAMETER,
		ElementType.ANNOTATION_TYPE })
public @interface Annotate {
	/**
	 * Indicates the set of annotations which are annotated with.
	 */
	String[] value();

	/**
	 * If specified value is true, the annotated annotation must not be
	 * null. If violates, the specified exception of
	 * {@link #throwsException()} will be thrown at run-time.
	 *

	 * The default value is true.
	 */
	boolean required() default true;

	/**
	 * This specified exception shall be thrown if annotating process is not
	 * completed.
	 *

	 * The default value is {@link AnnotatingRuntimeException} class.
	 */
	Class<? extends RuntimeException> throwsException() default AnnotatingRuntimeException.class;
}


text:
<?php

namespace JupyterPHP;

final class ConnectionSettings
{
    /**
     * @return array[string]mixed
     */
    public static function get(): array
    {
        global $argv;
        if (!isset($argv) || empty($argv)) {
            $argv = $_SERVER['argv'];
        }

        if (\is_array($argv) && \count($argv) > 1) {
            $connectionFileContents = \file_get_contents(
                $argv[1],
                null,
                null,
                0,
                2048
            );

            if (false === $connectionFileContents) {
                throw new \RuntimeException('Connection Settings: Unable to open the connection file.');
            }

            $connectionSettings = \json_decode($connectionFileContents, true);

            if (\json_last_error() !== JSON_ERROR_NONE) {
                throw new \RuntimeException('Connection Settings: Corrupted connection file.');
            }

            return $connectionSettings;
        } else {
            throw new \RuntimeException('Connection Settings: Not specified.');
        }
    }

    /**
     * @param null|array $connectionSettings
     * @return array[string]string
     */
    public static function getConnectionUris(array $connectionSettings = null): array
    {
        if (null === $connectionSettings) {
            $connectionSettings = self::get();
        }

        $connectionUri = $connectionSettings['transport'].'://'.$connectionSettings['ip'].':';

        return [
            'stdin'   => $connectionUri.$connectionSettings['stdin_port'],
            'control' => $connectionUri.$connectionSettings['control_port'],
            'hb'      => $connectionUri.$connectionSettings['hb_port'],
            'shell'   => $connectionUri.$connectionSettings['shell_port'],
            'iopub'   => $connectionUri.$connectionSettings['iopub_port']
        ];
    }
}


text:
using Newtonsoft.Json;

namespace ZendeskApi_v2.Models.Targets
{
    public class BasecampTarget : BaseTarget
    {
        [JsonProperty("type")]
        public override string Type
        {
            get
            {
                return "basecamp_target";
            }
        }

        [JsonProperty("target_url")]
        public string TargetUrl { get; set; }

        [JsonProperty("username")]
        public string Username { get; set; }

        [JsonProperty("password")]
        public string Password { get; set; }

        [JsonProperty("token")]
        public string Token { get; set; }

        [JsonProperty("project_id")]
        public string ProjectId { get; set; }

        [JsonProperty("resource")]
        public string Resource { get; set; }

        [JsonProperty("message_id")]
        public string MessageId { get; set; }

        [JsonProperty("todo_list_id")]
        public string TodoListId { get; set; }
    }
}