text:
<file_sep>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.util.ArrayList;

/**
 *
 * @author Dima
 */
public class Improvement {

    ArrayList<MODELImprovementBalance> balance = new ArrayList<>();
    ArrayList<MODELImprovementEnterprise> enterpriseCount = new ArrayList<>();
    ArrayList<MODELImprovementIncasation> incasationTime = new ArrayList<>();

    public Improvement() {
    }

    public ArrayList<MODELImprovementBalance> getBalance() {
        return balance;
    }

    public void setBalance(ArrayList<MODELImprovementBalance> balance) {
        this.balance = balance;
    }

    public ArrayList<MODELImprovementEnterprise> getEnterpriseCount() {
        return enterpriseCount;
    }

    public void setEnterpriseCount(ArrayList<MODELImprovementEnterprise> enterpriseCount) {
        this.enterpriseCount = enterpriseCount;
    }

    public ArrayList<MODELImprovementIncasation> getIncasationTime() {
        return incasationTime;
    }

    public void setIncasationTime(ArrayList<MODELImprovementIncasation> incasationTime) {
        this.incasationTime = incasationTime;
    }

}
<file_sep>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import Errors.MyErrors;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Type;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Constants;
import model.Constants.ReqestLink;
import model.response.ErrorResponse;
import util.HTTPStatuses;

/**
 *
 * @author Dima
 */
@Stateless
public class ValidateRequest {

    @EJB
    private ValidatorRequestHeader validatorRequestHeader;
    Gson gson = new Gson();

    public void validateHaveIMEI(HttpServletRequest request, HttpServletResponse response) throws IOException {
        validatorRequestHeader.validateAccountEnter(request, response);
    }

    public boolean validateRequestBody(HttpServletRequest request, HttpServletResponse response, Class classType) {

        try {
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = request.getReader().readLine()) != null) {
                sb.append(s);
            }
            new Gson().fromJson(sb.toString(), classType);
            System.out.println(request.getPathInfo());
            System.out.println(sb.toString());
            return true;
        } catch (IOException ex) {
            response.setStatus(HTTPStatuses.ERROR_RESPONSE_CODE);
            return false;
        }
    }

    public boolean validateRequestBody(HttpServletRequest request, HttpServletResponse response, Type type) {

        try {
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = request.getReader().readLine()) != null) {
                sb.append(s);
            }
            System.out.println(request.getPathInfo());
            System.out.println("Body1: " + sb.toString());
            return true;
        } catch (IOException ex) {
            response.setStatus(HTTPStatuses.ERROR_RESPONSE_CODE);
            return false;
        }
    }

    public String readBody(HttpServletRequest request) {
        try {
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = request.getReader().readLine()) != null) {
                sb.append(s);
            }
            System.out.println("Body2: " + sb.toString());
            return sb.toString();
        } catch (IOException ex) {
            return "";
        }
    }

    public Object parser(String string, Class T) {
        return gson.fromJson(string, T);
    }

    public void validateRequestParameters(HttpServletRequest request, HttpServletResponse response, ReqestLink reqestLink) throws IOException {
        ErrorResponse mErrorResponse = null;// = new ErrorResponse();

        switch (reqestLink) {
            case ACCOUNT_EDIT_USERNAME: {
                if (request.getParameter(Constants.ParameterRequestConstant.USER_NAME) == null) {
                    mErrorResponse = new ErrorResponse(MyErrors.ParametrError.AccountError.PARAMETR_USER_NAME_IS_NULL);
                }
            }
        }

        if (mErrorResponse != null) {
            response.getWriter().println(new Gson().toJson(mErrorResponse));
            throw new IOException();
        }

    }

}
<file_sep>j2ee.platform.classpath=C:/Program Files/NetBeans 8.2/enterprise/modules/ext/javaee-api-7.0.jar
j2ee.server.instance=jelastic:j.layershift.co.uk-env-4310121.j.layershift.co.uk
javac.debug=true
javadoc.preview=true
selected.browser=default
user.properties.file=C:\\Users\\Dima\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
<file_sep>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.validation.constraints.NotNull;
import model.ProfileDB;
import util.SQLStatements;

/**
 *
 * @author Dima
 */
@Stateless
public class ProfileEJB {

    public ProfileDB create( ProfileDB profile, String IMEI){
        Connection conn = null;
        Statement stmt = null;
        PreparedStatement mPreparedStatement = null;
        ResultSet rs = null;
        try {
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup("jndi/bizz");
            conn = ds.getConnection();
            mPreparedStatement = conn.prepareStatement(SQLStatements.CREATE_PROFILE, Statement.RETURN_GENERATED_KEYS);
            mPreparedStatement.setString(1, IMEI);
            mPreparedStatement.setString(2, profile.getFacebookLink());
            mPreparedStatement.setString(3, profile.getUserFirstName());
            mPreparedStatement.setString(4, profile.getUserLastName());
            mPreparedStatement.executeUpdate();
            rs = mPreparedStatement.getGeneratedKeys();
                if(rs.next())
                {
                    int last_inserted_id = rs.getInt(1);
                    System.out.println("last_inserted_id : " + String.valueOf(last_inserted_id));
                }
            return null;
        } catch (SQLException ex) {
            System.out.println("OGO: " + ex.getMessage());
            return null;
        } catch (NamingException ex) {
            Logger.getLogger(EJBAccount.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                System.out.println("ppz");
            }
        }
        return null;
    }
}
<file_sep>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Errors;

import model.Constants;

/**
 *
 * @author Dima
 */
public class MyErrors {

    public class RequestError {

        /**
         *
         */
        public static final String IMEI_NOT_FOUNT = Constants.ServletConstant.IMEI + " not found";
    }

    public class ParametrError {

        public class AccountError{
            public static final String PARAMETR_USER_NAME_IS_NULL = "parameter " + Constants.ParameterRequestConstant.USER_NAME + " cannot be null";
        }

    }
}
<file_sep>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dbmodels;

/**
 *
 * @author Dima
 */
public class Enterprise {

    private String id;
    private Location location = new Location();
    private String name;
    private long bought;
    private String holder;
    private long createdAt;
    private long incasation;

    public Enterprise() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHolder() {
        return holder;
    }

    public void setHolder(String holder) {
        this.holder = holder;
    }

    @Override
    public String toString() {
        return "Enterprise{" + "id=" + id + ", location=" + location + ", name=" + name + ", bought=" + bought + ", holder=" + holder + ", createdAt=" + createdAt + ", incasation=" + incasation + '}';
    }

    public long getBought() {
        return bought;
    }

    public void setBought(long bought) {
        this.bought = bought;
    }

    public long getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(long createdAt) {
        this.createdAt = createdAt;
    }

    public long getIncasation() {
        return incasation;
    }

    public void setIncasation(long incasation) {
        this.incasation = incasation;
    }
}
<file_sep>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import DAO.DAOAccount;
import DAO.DAOEnterprise;
import DAO.DAOProfile;
import com.google.gson.Gson;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.AccountDB;
import model.AccountGeneral;
import model.Constants;
import model.Constants.ServletConstant;
import model.ProfileDB;

/**
 *
 * @author Dima
 */
@Stateless
public class EJBAccount {

    private static final int START_BALANCE = 50_000;

    @EJB
    private DAOProfile daoProfile;
    @EJB
    private DAOAccount daoAccount;
    @EJB
    private ValidateRequest validator;
    @EJB
    private DAOEnterprise daoEnterprise;

    public String enter(HttpServletRequest request, HttpServletResponse response) {

        AccountDB data = daoAccount.getAccountByIMEI(request.getHeader(ServletConstant.IMEI));
        if (data == null) {
            String body = validator.readBody(request);
            AccountDB accountDB = new AccountDB();
            accountDB.setIMEI(request.getHeader(ServletConstant.IMEI));
            accountDB.setBalance(START_BALANCE);
            daoAccount.create(accountDB);
            ProfileDB profileDB = new ProfileDB();
            profileDB.setIMEI(accountDB.getIMEI());

            if (!body.isEmpty()) {
                ProfileDB incomeProfile = new Gson().fromJson(body, ProfileDB.class);
                profileDB.setFacebookLink(incomeProfile.getFacebookLink());
                profileDB.setUserFirstName(incomeProfile.getUserFirstName());
                profileDB.setUserLastName(incomeProfile.getUserLastName());
            } else {

            }
            daoProfile.create(profileDB);
        } else {
            System.out.println(new Gson().toJson(data));
        }
        return new Gson().toJson(getAccountWithProfile(request.getHeader(ServletConstant.IMEI)));

    }

    public String editUserName(String IMEI, String userName) {
        AccountDB data = daoAccount.getAccountByIMEI(IMEI);
        if (data != null) {
            daoAccount.editUserName(IMEI, userName);
            return new Gson().toJson(getAccountWithProfile(IMEI));
        } else {
            return Constants.ParameterRequestConstant.GLOBAL;
        }
    }

    public AccountDB getAccountWithProfile(String IMEI) {
        AccountDB accountDB = daoAccount.getAccountByIMEI(IMEI);
        ProfileDB DB = daoProfile.getProfileByIMEI(IMEI);
        if (DB != null) {
            accountDB.setProfile(DB);
        } else {
            System.out.println("PROFILE IS NULL");
        }
        return accountDB;
    }

    public AccountGeneral getGeneralAccount(String IMEI) {
        AccountGeneral accountGeneral = new AccountGeneral();
        accountGeneral.setAccount(getAccountWithProfile(IMEI));
        accountGeneral.setEnterprises(daoEnterprise.getEnterpriseList(accountGeneral.getAccount().getIMEI()));
        System.out.println("accountGeneral: " + accountGeneral.toString());
        return accountGeneral;
    }

}
<file_sep>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package model.enterprise;

import java.util.ArrayList;
import java.util.List;
import model.LatLong;

/**
 *
 * @author Dima
 */
public class EnterpriseIncome {

    private String id;
    private String forsqareId;
    private LatLong location;
    private String name;
    private enterpriseCategory categories;
    private Likes likes = new Likes();
    private double rating;
    private long createdAt;
    private int accountId; // holder;
    private long incasationAt;
    private int bought;

    public EnterpriseIncome() {
    }

    public EnterpriseIncome(String id, String forsqareId, LatLong location, String name, enterpriseCategory categories, double rating, long createdAt, int accountId, long incasationAt, int bought) {
        this.id = id;
        this.forsqareId = forsqareId;
        this.location = location;
        this.name = name;
        this.categories = categories;
        this.rating = rating;
        this.createdAt = createdAt;
        this.accountId = accountId;
        this.incasationAt = incasationAt;
        this.bought = bought;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getForsqareId() {
        return forsqareId;
    }

    public void setForsqareId(String forsqareId) {
        this.forsqareId = forsqareId;
    }

    public LatLong getLocation() {
        return location;
    }

    public void setLocation(LatLong location) {
        this.location = location;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public enterpriseCategory getCategories() {
        return categories;
    }

    public void setCategories(enterpriseCategory categories) {
        this.categories = categories;
    }

    public Likes getLikes() {
        return likes;
    }

    public void setLikes(Likes likes) {
        this.likes = likes;
    }

    public double getRating() {
        return rating;
    }

    public void setRating(double rating) {
        this.rating = rating;
    }

    public long getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(long createdAt) {
        this.createdAt = createdAt;
    }

    public int getAccountId() {
        return accountId;
    }

    public void setAccountId(int accountId) {
        this.accountId = accountId;
    }

    public long getIncasationAt() {
        return incasationAt;
    }

    public void setIncasationAt(long incasationAt) {
        this.incasationAt = incasationAt;
    }

    public int getBought() {
        return bought;
    }

    public void setBought(int bought) {
        this.bought = bought;
    }

    @Override
    public String toString() {
        return "EnterpriseIncome{" + "id=" + id + ", forsqareId=" + forsqareId + ", location=" + location + ", name=" + name + ", categories=" + categories + ", likes=" + likes + ", rating=" + rating + ", createdAt=" + createdAt + ", accountId=" + accountId + ", incasationAt=" + incasationAt + ", bought=" + bought + '}';
    }

}
<file_sep>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

/**
 *
 * @author Dima
 */
public class SQLStatements {

    // Account
    public static final String CREATE_ACCOUNT = "INSERT INTO `account`( `IMEI`, `level`, `balance`, `enterprise_count`, `created_at`, `last_enter`, `user_name`, `in_flight`, `coordinates_latitude`, `coordinates_longitude`, `investment_in_business` ) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
    public static final String GET_ACCOUNT_BY_ID = "SELECT * FROM `account` WHERE `idAccount`= ?";
    public static final String GET_ACCOUNT_BY_IMEI = "SELECT * FROM `account` WHERE `IMEI`= ?";
    public static final String EDIT_NICK_NAME = "UPDATE `account` SET `user_name`=? WHERE `IMEI`=?";
    public static final String EDIT_ENTERPRISE_COUNT = "UPDATE `account` SET `enterprise_count` = ? WHERE `IMEI` = ?";
    public static final String EDIT_BALANCE = "UPDATE `account` SET `balance` = ? WHERE `IMEI` = ?";
    //Profile
    public static final String GET_PROFILE_BY_ID = "SELECT * FROM `profile` WHERE `id_profile`= ?";
    public static final String GET_PROFILE_BY_IMEI = "SELECT * FROM `profile` WHERE `IMEI`= ?";
    public static final String CREATE_PROFILE = "INSERT INTO `profile`( `IMEI`, `id_facebook`, `first_name`, `last_name`) VALUES (?,?,?,?)";
    //Enterprise
    public static final String CREATE_ENTERPRISE = "INSERT INTO `enterprise`( `forsquareId`, `locationX`, `locationY`, `name`, `categoryId`, `likes`, `rating`, `createdAt`, `IMEI`, `incasation`, `bought`) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
    public static final String GET_ENTERPRISE_BY_ID = "SELECT * FROM `enterprise` WHERE `id` =?";
    public static final String GET_ENTERPRISE_BY_SQUARE_ID = "SELECT * FROM `enterprise` WHERE `forsquareId` =?";
    public static final String GET_ENTERPRISE_BY_HOLDER = "select * from enterprise where IMEI = ?";
    public static final String UPDATE_INCASATION = "SET `incasation` = ? WHERE `forsquareId` = ?;";
    //improvements
    public static final String GET_IMPROVEMENTS_BALANCE = "SELECT * FROM `improvement_balance` WHERE `sub_level` = ? and `level` = ?;";
    public static final String GET_ALL_IMPROVEMENTS_BALANCE = "SELECT * FROM `improvement_balance`";

    public static final String GET_IMPROVEMENTS_ENTERPRISE = "SELECT * FROM `improvement_enterprise` WHERE `sub_level` = ? and `level` = ?;";
    public static final String GET_ALL_IMPROVEMENTS_ENTERPRISE = "SELECT * FROM `improvement_enterprise`";

    public static final String GET_IMPROVEMENTS_INCASATION = "SELECT * FROM `improvement_time_incasation` WHERE `sub_level` = ? and `level` = ?;";
    public static final String GET_ALL_IMPROVEMENTS_INCASATION = "SELECT * FROM `improvement_time_incasation`";

}
<file_sep>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import DAO.DAOImprovementBalance;
import DAO.DAOImprovementEnterprise;
import DAO.DAOImprovementIncasation;
import com.google.gson.Gson;
import java.util.HashSet;
import java.util.Set;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import model.Improvement;

/**
 *
 * @author Dima
 */
@Stateless
public class EJBGeneralUtil {

    @EJB
    private DAOImprovementIncasation dAOImprovementIncasation;
    @EJB
    private DAOImprovementEnterprise dAOImprovementEnterprise;
    @EJB
    private DAOImprovementBalance dAOImprovementBalance;

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    public String getMapImprovements() {
        Improvement improvement = new Improvement();
        improvement.setBalance(dAOImprovementBalance.getImprovmentBalanceAll());
        improvement.setEnterpriseCount(dAOImprovementEnterprise.getImprovmentEnterpriseAll());
        improvement.setIncasationTime(dAOImprovementIncasation.getImprovmentEnterpriseAll());
        return new Gson().toJson(improvement);
    }
}

branch_name: refs/heads/master

languages: Java INI

repo_language: Java

repo_name: dimaulko/BIZZ


text:
<repo_name>wissenschaft89/Museums-in-Korea<file_sep>/README.md
# Museums-in-Korea
한국의 미술관

#1. 국립현대미술관
#2. 인사동갤러리
#3.

repo_language: Markdown


text:
<file_sep>import click
import logging as log

from config import CONF_PARAMS
from mhrw.utils import start_session
from mhrw import MHRWSampler

@click.command()
@click.argument('edges_path')
@click.argument('sample_save_path')
@click.option('--seed_ratio', default=0.001, help="The fraction of seed nodes in the graph for which random walk will be started.")
@click.option('--budget_ratio', default=0.1, help="The fraction of the nodes that need to be sampled. reaching it, the random walk will stop.")
@click.option('--method', default="MHRW", help="""The method by which the samples will be sampled. It determines with what probability the node will be accepted or rejected on each iteration. Two methods are available:
                                                - Metropolis-Hastings Random Walk (MHRW)
                                                - Rejection-Controlled Metropolis-Hastings Algorithm (RCMH).""")
@click.option('--alpha', default=0.5, help="Only for RCMH. Alpha ∈ [0, 1] which parameterizes the acceptance function of node acceptance or rejection on each iteration. When alpha = 1 the algorithm is reduced to the original MHRW, when alpha = 0 to the simply random walk.")
def main(edges_path: str, sample_save_path: str, seed_ratio: float,
         budget_ratio: float, method: str, alpha: float):
    """
    The MHRW algorithm is an application of the Metropolis-Hastings algorithm
    for unbiased graph sampling. It makes use of a modified random walk to
    draw nodes from the graph. In particular, it modifies the transition
    probabilities of a random walk so that the walk converges into a uniform
    distribution.

    First, node seed node u is sampled. When MH draws a node v from N(u) with
    probability 1/d_u, MH accepts v as a sample with probability min{1, d_u/d_v},
    and reject it with probability 1 − min{1, d_u/d_v}, where N(u) is set of u neighbors
    and d_i degree of i's node.

    Above is a description of how the algorithm works in relation to one
    node. In this implementation, a certain percentage of seed nodes is
    selected first, and then random walk begins for each one. Due to the
    fact that all this is done for each node independently, the
    parallelism and distributedness of the algorithm is achieved with
    the help of PySpark. All unique nodes on every iteration are added to the
    pool.
    """
    spark, sc = start_session("mhrwGraphSample", **CONF_PARAMS)
    edge_list = spark.read.parquet(edges_path)

    log.info(f"edges in full graph: {edge_list.count()}")

    sampler = MHRWSampler(spark, "tmp", seed_ratio, budget_ratio, method, alpha).fit(edge_list)
    sampled_graph = sampler.transform(edge_list)

    log.info(f"edges in sampled graph: {sampled_graph.count()}")
    sampled_graph.write.parquet(sample_save_path, mode="overwrite")
    sampler.clear_ids()

if __name__ == "__main__":
    main()<file_sep>appnope==0.1.0
attrs==19.1.0
backcall==0.1.0
bleach==3.1.0
Click==7.0
cycler==0.10.0
decorator==4.4.0
defusedxml==0.6.0
entrypoints==0.3
fastparquet==0.3.2
flake8==3.7.8
ipykernel==5.1.2
ipython==7.8.0
ipython-genutils==0.2.0
ipywidgets==7.5.1
jedi==0.15.1
Jinja2==2.10.1
jsonschema==3.0.2
jupyter==1.0.0
jupyter-client==5.3.2
jupyter-console==6.0.0
jupyter-core==4.5.0
kiwisolver==1.1.0
llvmlite==0.29.0
MarkupSafe==1.1.1
matplotlib==3.1.1
mccabe==0.6.1
mistune==0.8.4
mypy==0.720
mypy-extensions==0.4.1
nbconvert==5.6.0
nbformat==4.4.0
notebook==6.0.1
numba==0.45.1
numpy==1.17.2
pandas==0.25.1
pandocfilters==1.4.2
parso==0.5.1
pexpect==4.7.0
pickleshare==0.7.5
prometheus-client==0.7.1
prompt-toolkit==2.0.9
ptyprocess==0.6.0
py4j==0.10.7
pycodestyle==2.5.0
pyflakes==2.1.1
Pygments==2.4.2
PyMySQL==0.9.3
pyparsing==2.4.2
pyrsistent==0.15.4
pyspark==2.4.4
python-dateutil==2.8.0
pytz==2019.2
pyzmq==18.1.0
qtconsole==4.5.5
scipy==1.3.1
Send2Trash==1.5.0
six==1.12.0
terminado==0.8.2
testpath==0.4.2
thrift==0.11.0
toolz==0.10.0
tornado==6.0.3
tqdm==4.35.0
traitlets==4.3.2
typed-ast==1.4.0
typing-extensions==3.7.4
wcwidth==0.1.7
webencodings==0.5.1
widgetsnbextension==3.5.1
xlrd==1.2.0
xlwt==1.3.0
<file_sep>import shutil

import pyspark.sql.functions as F

from .mhrw_base import MHRW
from .utils import graph_filter_ids

from pyspark.sql import SparkSession, DataFrame

class MHRWSampler:
    def __init__(self, spark: SparkSession, ids_path: str, seed_ratio: float=0.001,
                 budget_ratio: float=0.1, method: str="MHRW", alpha: float=0.5):
        self.spark = spark
        self.ids_path = ids_path

        self.seed_ratio = seed_ratio
        self.budget_ratio = budget_ratio

        self.method = method
        self.alpha = alpha

        self._ids = None

    @property
    def sampled_ids(self) -> DataFrame:
        # return lazy dataframe
        if self._ids is None:
            try:
                sample_ids = self.spark.read.parquet(self.ids_path)
            except Exception:
                raise ValueError("Sample does not exists. First, fit the model")

            sample_ids = sample_ids.distinct().withColumnRenamed("user", "id")
            self._ids = sample_ids

            return self._ids
        else:
            return self._ids

    def fit(self, edge_list: DataFrame, cache: bool=True) -> 'MHRWSampler':
        self._ids = None
        graph = (edge_list
                    .toDF("user", "item")
                    .groupBy("user")
                    .agg(F.collect_list("item").alias("neigh")))

        if cache:
            graph.persist()

        MHRW(graph, self.ids_path, seed_ratio=self.seed_ratio,
            budget_ratio=self.budget_ratio, accept_func=self.method, alpha=self.alpha)

        if cache:
            graph.unpersist()

        return self

    def transform(self, edge_list: DataFrame) -> DataFrame:
        sampled_graph = graph_filter_ids(edge_list, self.sampled_ids)

        return sampled_graph

    def clear_ids(self) -> str:
        shutil.rmtree(self.ids_path)

        return self.ids_path
<file_sep>from .mhrw_sampler import MHRWSampler
<file_sep>import numpy as np

import pyspark.sql.functions as F

from pyspark import SparkContext
from pyspark.sql import DataFrame, SparkSession
from pyspark.sql.types import IntegerType, LongType

from typing import Dict, Tuple

arr_len = F.udf(lambda arr: len(arr), IntegerType())
arr_choice = F.udf(lambda arr: int(np.random.choice(arr)), LongType())

def start_session(task_name: str, **kwargs) -> Tuple[SparkSession, SparkContext]:
    from pyspark import SparkConf
    from pyspark.sql import SparkSession

    conf = SparkConf()
    for param in kwargs:
        assert isinstance(param, str), "conf param should be string"
        try:
            conf.set(param, kwargs[param])
        except KeyError:
            raise KeyError(f"Unknown configuration parameter: {param}")

    spark = (SparkSession
                .builder
                .config(conf=conf)
                .appName(task_name)
                .getOrCreate())
    sc = spark.sparkContext

    return spark, sc

def graph_filter_ids(edge_list: DataFrame, filter_ids: DataFrame) -> DataFrame:
    edge_list_filt = (edge_list
            .join(filter_ids, edge_list["user"] == filter_ids["id"])
            .drop("id")
            .join(filter_ids, edge_list["item"] == filter_ids["id"])
            .select("user", "item"))

    return edge_list_filt

def rename_columns(df: DataFrame, columns: Dict[str, str]) -> DataFrame:
    if isinstance(columns, dict):
        for old_name, new_name in columns.items():
            df = df.withColumnRenamed(old_name, new_name)
        return df
    else:
        raise ValueError("'columns' should be a dict, like {'old_name_1':'new_name_1', 'old_name_2':'new_name_2'}")

if __name__ == "__main__":
    spark, sc = start_session("test_session")
    print(spark)

    print(sc.getConf().getAll())
<file_sep># spark context configuration
CONF_PARAMS = {
    "spark.master": "local[*]",
}
<file_sep>import shutil

import logging as log
import numpy as np

import pyspark.sql.functions as F

from itertools import count
from typing import Tuple

from pyspark.sql.types import IntegerType
from pyspark.sql import SparkSession
from pyspark.sql import DataFrame

from .utils import arr_choice, arr_len, rename_columns

log.basicConfig(level=log.INFO,
                format='%(levelname)s - %(asctime)s: %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S')

def MHRW(graph: DataFrame, ids_path: str, seed_ratio: float=0.001,
        budget_ratio: float=0.1, accept_func: str="MHRW", alpha: float=0.5):

    if not 0 <= seed_ratio <= 1:
        raise ValueError("seed ratio should be in range (0, 1)")

    if not 0 <= budget_ratio <= 1:
        raise ValueError("budget ratio should be in range (0, 1)")

    sample_seed = np.random.random()
    budget = int(graph.count() * budget_ratio)

    seed_nodes = graph.sample(False, seed_ratio, seed=sample_seed).persist()
    seed_nodes.select("user").write.parquet(ids_path, mode="overwrite")

    nodes_sampled_count = seed_nodes.count()
    log.info(f"sampled {nodes_sampled_count} seed nodes, budget: {budget}")

    progress_total = 0.0
    cache = [seed_nodes]

    for iter_ in count():
        if nodes_sampled_count < budget:
            new_nodes, nodes_count = _iter_MHRW(graph, cache[iter_],
                                                accept_func=accept_func, alpha=alpha)

            cache.append(new_nodes.persist())
            cache[iter_].unpersist()

            # use accumulator?
            nodes_sampled_count += nodes_count

            new_nodes.select("user").write.parquet(ids_path, mode="append")

            progress_iter = round((nodes_sampled_count / budget)*100, 2)

            if abs(progress_total - progress_iter) < 0.5:
                log.warn(f"gain lower than 0.5%, stop sampling!")
                break
            else:
                log.info(f"iteration {iter_ + 1}, sampled {nodes_sampled_count} nodes, progress: {progress_iter}%")
                progress_total = progress_iter
        else:
            log.info(f"the budget has been spent! stop sampling")
            break

    seed_nodes.unpersist()

def _iter_MHRW(user_neigh: DataFrame, seed_nodes: DataFrame, accept_func: str="MHRW", alpha: float=0.5) -> Tuple[DataFrame, int]:

    if accept_func == "MHRW":
        if_select = F.udf(lambda q_ratio: 1 if np.random.uniform(0, 1) <= min(1, q_ratio) else 0, IntegerType())
    elif accept_func == "RCMH":
        if_select = F.udf(lambda q_ratio: 1 if np.random.uniform(0, 1) <= q_ratio**alpha else 0, IntegerType())
    else:
        raise ValueError("wrong accept_func option, only: MHRW, RCMH (with alpha correction)")

    seed_nodes = seed_nodes.withColumn("cand", arr_choice("neigh"))
    cand_nodes = rename_columns(user_neigh, {"user": "cand_user", "neigh": "cand_neigh"})

    seed_nodes = (seed_nodes
                    .join(cand_nodes, seed_nodes["cand"] == cand_nodes["cand_user"])
                    .drop("cand_user")
                 )

    seed_nodes = seed_nodes.withColumn("q_ratio", arr_len(seed_nodes["neigh"]) / arr_len(seed_nodes["cand_neigh"]))
    seed_nodes = seed_nodes.withColumn("if_selected", if_select("q_ratio"))

    new_nodes_count = seed_nodes.filter(F.col("if_selected") == 1).count()

    new_nodes = (seed_nodes
                         .withColumn("user",
                                     F.when(F.col("if_selected") == 1, F.col("cand")).otherwise(F.col("user")))
                          .withColumn("neigh",
                                     F.when(F.col("if_selected") == 1, F.col("cand_neigh")).otherwise(F.col("neigh")))

                    ).select("user", "neigh")

    return new_nodes, new_nodes_count
<file_sep># MHRW

Metropolis hastings random walk implementation with pyspark.

`example.ipynb` - sampling fb friends network code example.

# How to use

```console
Usage: mhrw_sample.py [OPTIONS] EDGES_PATH SAMPLE_SAVE_PATH

  The MHRW algorithm is an application of the Metropolis-Hastings algorithm
  for unbiased graph sampling. It makes use of a modified random walk to
  draw nodes from the graph. In particular, it modifies the transition
  probabilities of a random walk so that the walk converges into a uniform
  distribution.

  First, node seed node u is sampled. When MH draws a node v from N(u) with
  probability 1/d_u, MH accepts v as a sample with probability min{1,
  d_u/d_v}, and reject it with probability 1 − min{1, d_u/d_v}, where N(u)
  is set of u neighbors and d_i degree of i's node.

  Above is a description of how the algorithm works in relation to one
  node. In this implementation, a certain percentage of seed nodes is
  selected first, and then random walk begins for each one. Due to the  fact
  that all this is done for each node independently, the  parallelism and
  distributedness of the algorithm is achieved with  the help of PySpark.
  All unique nodes on every iteration are added to the  pool.

Options:
  --seed_ratio FLOAT    The fraction of seed nodes in the graph for which
                        random walk will be started.
  --budget_ratio FLOAT  The fraction of the nodes that need to be sampled.
                        reaching it, the random walk will stop.
  --method TEXT         The method by which the samples will be sampled. It
                        determines with what probability the node will be
                        accepted or rejected on each iteration. Two methods
                        are available:
                        - Metropolis-Hastings Random Walk
                        (MHRW)
                        - Rejection-Controlled Metropolis-Hastings
                        Algorithm (RCMH).
  --alpha FLOAT         Only for RCMH. Alpha ∈ [0, 1] which parameterizes the
                        acceptance function of node acceptance or rejection on
                        each iteration. When alpha = 1 the algorithm is
                        reduced to the original MHRW, when alpha = 0 to the
                        simply random walk.
  --help                Show this message and exit.
```

# Theory

![code](https://i.imgur.com/lCK1sW5.png)

# References

- <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., … <NAME>. (2011). Understanding Graph Sampling Algorithms for Social Network Analysis.
  2011 31st International Conference on Distributed Computing Systems Workshops, 123–128.
  https://doi.org/10.1109/ICDCSW.2011.34https://doi.org/10.1109/ICDE.2015.7113345

- <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2015). On random walk based graph sampling.
  2015 IEEE 31st International Conference on Data Engineering, 927–938.
  https://doi.org/10.1109/ICDE.2015.7113345

languages: Markdown Text Python

repo_name: Howuhh/MHRW


text:
<file_sep><?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = [
        'slug',
        'title',
        'excerpt',
        'content',
        'published',
        'published_at'
    ];

    public function getPublishedPosts()
    {
        return self::latest( 'published_at' )
            ->published()
            ->get();
    }

    public function getUnPublishedPosts()
    {
        return self::latest( 'published_at' )
            ->unPublished()
            ->get();
    }

    public function scopePublished( $query )
    {
        $query
            ->where( 'published_at', '>=', Carbon::now() )
            ->where( 'published', '=', true );
    }

    public function scopeUnPublished( $query )
    {
        $query
            ->where( 'published', '=', false );
    }
}
<file_sep>@extends( 'app' )

@section( 'content' )

        {!! link_to_route( 'post', 'published' ) !!}
        {!! link_to_route( 'post.unpublished', 'unpublished' ) !!}
        {!! link_to_route( 'post.create', 'create' ) !!}

    @foreach( $posts as $post )

{{ $post->title }}

{!! $post->{ 'content' . lang() } !!}

{{ $post->published_at }}

    @endforeach
@stop<file_sep>

    {!! Form::label( 'slug' ) !!}
    {!! Form::text( 'slug', null, [ 'class' => 'form-control' ] ) !!}

    {!! Form::label( 'title' ) !!}
    {!! Form::text( 'title', null, [ 'class' => 'form-control' ] ) !!}

    {!! Form::label( 'excerpt' ) !!}
    {!! Form::textarea( 'excerpt', null, [ 'class' => 'form-control' ] ) !!}

    {!! Form::label( 'content' ) !!}
    {!! Form::textarea( 'content', null, [ 'class' => 'form-control' ] ) !!}

    {!! Form::label( 'published' ) !!}
    {!! Form::checkbox( 'published', null, false ) !!}

    {!! Form::label( 'published_at' ) !!}
    {!! Form::input( 'date', 'published_at', date( 'Y-m-d' ), [ 'class' => 'form-control' ] ) !!}

    {!! Form::submit( 'Create', [ 'class' => 'btn btn-primary' ] ) !!}

<file_sep>@extends( 'app' )

@section( 'content' )

        {!! link_to_route( 'post', 'published' ) !!}
        {!! link_to_route( 'post.unpublished', 'unpublished' ) !!}
        {!! link_to_route( 'post.create', 'create' ) !!}

Create

    {!! Form::open([ 'route' => 'post.store' ]) !!}
        @include( 'post._form' )
    {!! Form::close() !!}
@stop<file_sep><?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        config( [
            'laravellocalization.supportedLocales' => [
                'kaz' => array(
                    'name'   => 'Kazakh',
                    'script' => 'Cyrl',
                    'native' => 'қазақ тілі'
                ),

                'en'  => array(
                    'name'   => 'English',
                    'script' => 'Latn',
                    'native' => 'English'
                ),
                'ru'  => array(
                    'name'   => 'Russian',
                    'script' => 'Cyrl',
                    'native' => 'русский'
                ),
            ],

            'laravellocalization.useAcceptLanguageHeader' => true,

            'laravellocalization.hideDefaultLocaleInURL' => true
        ] );
    }
}
<file_sep><?php

use Illuminate\Database\Seeder;
use App\Models\Post;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);

        $this->call( PostsSeeder::class );
    }
}

class PostsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table( 'Posts' )->delete();
        Post::create([
            'title' => 'First Post',
            'slug' => 'first-post',
            'excerpt' => 'First Post body',
            'content' => 'Content First Post body',
            'published' => true
        ]);

        Post::create([
            'title' => 'Second Post',
            'slug' => 'second-post',
            'excerpt' => 'Second Post body',
            'content' => 'Content Second Post body',
            'published' => false
        ]);

        Post::create([
            'title' => 'Third Post',
            'slug' => 'third-post',
            'excerpt' => 'Third Post body',
            'content' => 'Content Third Post body',
            'published' => false
        ]);
    }
}<file_sep><?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::group( [
    'prefix'     => LaravelLocalization::setLocale(),
    'middleware' => [
        'localeSessionRedirect',
        'localizationRedirect'
    ]
], function(){
    Route::get( '/', [ 'as' => 'post', 'uses' => 'PostController@index' ] );
    Route::get( 'unpublished', [ 'as' => 'post.unpublished', 'uses' => 'PostController@unpublished' ] );

    Route::get( 'post/create', [ 'as' => 'post.create', 'uses' => 'PostController@create' ] );
    Route::post( 'post', [ 'as' => 'post.store', 'uses' => 'PostController@store' ] );
    Route::get ( 'post/{post}', [ 'as' => 'post.show', 'uses' => 'PostController@show' ] );
    Route::get ( 'post/{post}/edit', [ 'as' => 'post.edit', 'uses' => 'PostController@edit' ] );
    Route::post( 'post/{post}', [ 'as' => 'post.update', 'uses' => 'PostController@update' ] );
} );

//Route::get( '/', [ 'as' => 'post', 'uses' => 'PostController@index' ] );
//Route::get( 'unpublished', [ 'as' => 'post.unpublished', 'uses' => 'PostController@unpublished' ] );

/*Route::get( 'post/create', [ 'as' => 'post.create', 'uses' => 'PostController@create' ] );
Route::post( 'post', [ 'as' => 'post.store', 'uses' => 'PostController@store' ] );
Route::get ( 'post/{post}', [ 'as' => 'post.show', 'uses' => 'PostController@show' ] );
Route::get ( 'post/{post}/edit', [ 'as' => 'post.edit', 'uses' => 'PostController@edit' ] );
Route::post( 'post/{post}', [ 'as' => 'post.update', 'uses' => 'PostController@update' ] );*/

//$router->resource( 'post', 'PostController' );
Route::auth();

Route::get('/home', 'HomeController@index');
<file_sep><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Models\Post;

class PostController extends Controller
{
    public function index( Post $postModel )
    {
        $posts = $postModel->getPublishedPosts();

        return view( 'post.index', [ 'posts' => $posts ] );
    }

    public function unpublished( Post $postModel )
    {
        $posts = $postModel->getUnPublishedPosts();

        return view( 'post.index', [ 'posts' => $posts ] );
    }

    public function create()
    {
        return view( 'post.create' );
    }

    public function store( Post $postModel, Request $request )
    {
        $post = $postModel->create( $request->all() );

        if( $post->published == "on" ){
            $post->published = 1;
        }
        else{
            $post->published = 0;
        }

        $post->save();

        return redirect()->route( 'post' );
    }

    public function show( $id )
    {

    }

    public function edit( $id )
    {

    }

    public function update( $id )
    {

    }

    public function destroy( $id )
    {

    }
}

languages: Blade PHP

repo_language: Blade

repo_name: LaravelFramework/learn


text:
<repo_name>Kai9026/spring-microservices<file_sep>/README.md
# spring-microservices
Microservices with Spring technology
<file_sep>/src/main/resources/data.sql
insert into user values(1, sysdate(), 'AB');
insert into user values(2, sysdate(), 'Jill');
insert into user values(3, sysdate(), 'Jam');

insert into post values(111, 'My first post', 1);
insert into post values(112, 'My second post', 1);

languages: Markdown SQL


text:
<file_sep>
//THIS CODE IS MY OWN WORK, IT WAS WRITTEN WITHOUT CONSULTING A TUTOR OR CODE WRITTEN BY OTHER STUDENTS - <NAME>
package sort.comparison;

import java.util.Collections;
import java.util.Comparator;

public class ShellSortPratt<T extends Comparable<T>> extends ShellSort<T> {

    public int p;
    public int q;
    public ShellSortPratt()
    {
        this(Comparator.naturalOrder());
    }
    public ShellSortPratt(Comparator<T> comparator)
    {
        this(comparator, 1000);
    }

    public ShellSortPratt(Comparator<T> comparator, int n)
    {
        super(comparator, n);
        p=0;
        q=0;
    }

    @Override
    protected void populateSequence(int n) {

        n /=3;
        if (sequence.size()==0){
            sequence.add(1);
           // p=0;
            //q=0;
        }
        /*else{
            if(p==0&&q==0) {
                p = getP(n);
                q = getP(n);
            }
        }*/

        while(true){
            int i =sequence.get(p);
            int j =sequence.get(q);
            if(i*2<j*3){
                if(i*2 <= n){
                sequence.add(i*2);
                p++;
                }else{

                    break;
                }
            }else if (i*2>j*3){
                if(j*3 <=n){
                    sequence.add(j*3);
                    q++;
                }else
                {
                    break;
                }

            }else{
                if(j*3 <=n){
                    sequence.add(j*3);
                    q++;
                    p++;
                }else
                {break;
                }
            }

        }
       System.out.println(sequence);

    }

    @Override
    protected int getSequenceStartIndex(int n) {
        int index = Collections.binarySearch(sequence, n/3);
        if (index < 0) index = -(index+1);
        if (index == sequence.size()) index--;
        return index;
    }
    private int getP(int n){
        for (int i = sequence.size()-1;i>0;i--){
         if((sequence.get(i)*2 <= sequence.get(sequence.size()-1)&& sequence.get(i-1)*3>=sequence.get(sequence.size()-1))||((sequence.get(i)*2 >= sequence.get(sequence.size()-1)&& sequence.get(i-1)*3<=sequence.get(sequence.size()-1)))){
         return i;
         }
        }
        return sequence.get(sequence.size()-1);
        }

}
<file_sep>package graph.span;

import graph.Graph;

public class InterestingGraph {
    Graph house()
    {
        Graph graph = new Graph(5);

        graph.setUndirectedEdge(0, 1, 2);
        graph.setUndirectedEdge(0, 4, 2);
        graph.setUndirectedEdge(1, 4, 2);
        graph.setUndirectedEdge(3, 2, 2);
        graph.setUndirectedEdge(1, 2, 1.0);
        graph.setUndirectedEdge(4, 3, 1.0);

        return graph;

    }
    public static void main(String[] agrs){
        MSTAll system = new MSTJiangPrim();
        System.out.println(system.getMinimumSpanningTrees(new InterestingGraph().house()));

    }
}
<file_sep>/**
 * Copyright 2014, Emory University
 *
 * 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.
 *
 *
 *
 *
 * THIS CODE IS MY OWN WORK, IT WAS WRITTEN WITHOUT CONSULTING

 A TUTOR OR CODE WRITTEN BY OTHER STUDENTS - Xinyi Jiang*/
package trie.autocomplete;

import trie.Trie;
import trie.TrieNode;

import java.util.*;

/**
 * @author <NAME> ({@code <EMAIL>})
 */
public class JiangAutocomplete extends Trie<List<String>> implements IAutocomplete<List<String>>
{
    @Override
    public List<String> getCandidates(String prefix)
    {
        // TODO must be modified
        prefix = prefix.trim();
        List<String> list = new ArrayList<>();
        TrieNode noderoot = super.find(prefix);
        if(prefix.isEmpty()){
            noderoot = super.getRoot();
        }
        if(noderoot==null){return list;}
        if(noderoot.getValue()!=null) {
            list.addAll((ArrayList) noderoot.getValue());
        }
        if(list.size()>= 20){
            return list;
        }
        Queue<TrieNode> queuelist= new LinkedList<>();
        queuelist.add(noderoot);
        while(!queuelist.isEmpty()) {
            TrieNode p=queuelist.remove();

            if(p.isEndState()) {
                TrieNode b = p;
                String word = "";
                while (b != super.getRoot()) {
                    word = b.getKey() + word;
                    b = b.getParent();
                }
                if (!list.contains(word)) {
                    list.add(word);
                }
                if (list.size() >= 20) {
                    return list;
                }
            }

                List<Map.Entry<Character,TrieNode>> unsortedList = new ArrayList<Map.Entry<Character,TrieNode>>(p.getChildrenMap().entrySet());
                Collections.sort(unsortedList, new Comparator<Map.Entry<Character, TrieNode>>() {
                    @Override
                    public int compare(Map.Entry<Character, TrieNode> o1, Map.Entry<Character, TrieNode> o2) {
                        return o1.getKey().compareTo(o2.getKey());
                    }
                });
                for(Map.Entry<Character, TrieNode> entry: unsortedList){
                    queuelist.add(entry.getValue());
                }

        }

        return list;
    }

    @Override
    public void pickCandidate(String prefix, String candidate)
    {
        prefix=prefix.trim();
        candidate = candidate.trim();
        TrieNode node = super.find(prefix);
        if(node == null){
            super.put(prefix, new ArrayList<>());
            node = super.find(prefix);
            node.setEndState(false);
        }
        if(super.find(candidate)==null){
            super.put(candidate,null);
        }
        List<String> list =(List<String>) node.getValue();
        if(list == null){
            list = new ArrayList<>();
        }

        if(list.contains(candidate)) {
            list.remove(candidate);
        }
        if(list.size()==20){
            list.remove(19);
        }
        list.add(0,candidate);

        node.setValue(list);

        // TODO must be filled
    }
}


text:
<file_sep>A simple portfolio kind of page.
Still under developnent.


text:
<file_sep># 项目采用vue-cli 2.x 搭建的，以下对项目的目录作下说明：
```
# build：项目构建（webpack）相关代码

# config：项目开发、生产环境配置，包括端口号等

# node_modules：依赖的node工具包目录

# src：源码目录，基本要做的业务都在这个目录里处理
    --assets：资源目录
    --components：组件目录
    --router：路由
    --views：编写页面的地方（页面也是vue文件）
    --App.vue：页面入口文件
    --main.js：程序入口文件，加载各种公共组件（核心文件）

# static：静态文件目录（图片、json数据之类）

# babelrc：ES6语法编译配置，用来将ES6代码转换成浏览器可以识别的js代码

# editorconfig：编辑器的配置文件

# eslintignore：eslint检测代码忽略的文件（夹）

# eslintrc：定义eslint的plugins,extends,rules

# gitignore：git上传需要忽略的文件格式

# postcssrc：postcss配置文件

# index.html：首页入口页面（可以加上合适的meta头或者统计代码之类的），经过编译之后的代码将插入到这来

# package-lock.json：锁定安装时的包的版本号，并且需要上传到git，以保证其他人在npm install时大家的依赖能保证一致

# package.json：项目配置文件

```

<file_sep>// https://github.com/michael-ciniawsky/postcss-load-config
// .postcssrc.js文件其实是postcss-loader包的一个配置，在webpack的旧版本可以直接在webpack.config.js中配置
// 现版本中postcss的文档示例独立出.postcssrc.js，里面写进去需要使用到的插件

module.exports = {
  "plugins": {
    "postcss-import": {}, // https://www.npmjs.com/package/postcss-import
    "postcss-url": {}, // https://www.npmjs.com/package/postcss-url
    "autoprefixer": {} // https://www.npmjs.com/package/autoprefixer
  }
}
<file_sep>//vue-cli脚手架中webpack配置基础文件详解,原文地址：https://segmentfault.com/a/1190000014804826#articleHeader18
//https://blog.csdn.net/xiaoyangerbani/article/details/80735310

//对package.json的详细说明
description = {
  //从name到private都是package的配置信息，也就是我们在脚手架搭建中输入的项目描述
  "name": "shop", //项目名称：不能以.(点)或者_（下划线）开头，不能包含大写字母，具有明确的的含义与现有项目名字不重复
  "version": "1.0.0", //项目版本号：遵循“大版本.次要版本.小版本”
  "description": "A Vue.js project", //项目描述
  "author": "xxx", //作者名字
  "private": true, //是否私有
  //scripts中的子项即是我们在控制台运行的脚本的缩写
  "scripts": {
    //webpack-dev-server:启动了http服务器，实现实时编译;
    //inline模式会在webpack.config.js入口配置中新增webpack-dev-server/client?http://localhost:8080/的入口,使得我们访问路径为localhost:8080/index.html（相应的还有另外一种模式Iframe）;
    //progress:显示打包的进度
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev", //与npm run dev相同，直接运行开发环境
    "build": "node build/build.js" //使用node运行build文件
  },
  //dependencies(项目依赖库):在安装时使用--save则写入到dependencies
  "dependencies": {
    "vue": "^2.5.2", //vue.js
    "vue-router": "^3.0.1" //vue的路由插件
  },
  //和devDependencies（开发依赖库）：在安装时使用--save-dev将写入到devDependencies
  "devDependencies": {
    "autoprefixer": "^7.1.2", //autoprefixer作为postcss插件用来解析CSS补充前缀，例如 display: flex会补充为display:-webkit-box;display: -webkit-flex;display: -ms-flexbox;display: flex。
    //babel:以下几个babel开头的都是针对es6解析的插件。用最新标准编写的 JavaScript 代码向下编译成可以在今天随处可用的版本
    "babel-core": "^6.22.1", //babel的核心，把 js 代码分析成 ast ，方便各个插件分析语法进行相应的处理。
    "babel-helper-vue-jsx-merge-props": "^2.0.3", //预制babel-template函数，提供给vue,jsx等使用
    "babel-loader": "^7.1.1", //使项目运行使用Babel和webpack来传输js文件，使用babel-core提供的api进行转译
    "babel-plugin-syntax-jsx": "^6.18.0", //支持jsx
    "babel-plugin-transform-runtime": "^6.22.0", //避免编译输出中的重复，直接编译到build环境中
    "babel-plugin-transform-vue-jsx": "^3.5.0", //babel转译过程中使用到的插件，避免重复
    "babel-preset-env": "^1.3.2", //转为es5，transform阶段使用到的插件之一
    "babel-preset-stage-2": "^6.22.0", //ECMAScript第二阶段的规范
    "chalk": "^2.0.1", //用来在命令行输出不同颜色文字
    "copy-webpack-plugin": "^4.0.1", //拷贝资源和文件
    "css-loader": "^0.28.0", //webpack先用css-loader加载器去解析后缀为css的文件，再使用style-loader生成一个内容为最终解析完的css代码的style标签，放到head标签里
    "extract-text-webpack-plugin": "^3.0.0", //将一个以上的包里面的文本提取到单独文件中
    "file-loader": "^1.1.4", //打包压缩文件，与url-loader用法类似
    "friendly-errors-webpack-plugin": "^1.6.1", //识别某些类别的WebPACK错误和清理，聚合和优先排序，以提供更好的开发经验
    "html-webpack-plugin": "^2.30.1", //简化了HTML文件的创建，引入了外部资源，创建html的入口文件，可通过此项进行多页面的配置
    "node-notifier": "^5.1.2", //支持使用node发送跨平台的本地通知
    "optimize-css-assets-webpack-plugin": "^3.2.0", //压缩提取出的css，并解决ExtractTextPlugin分离出的js重复问题(多个文件引入同一css文件)
    "ora": "^1.2.0", //加载（loading）的插件
    "portfinder": "^1.0.13", //查看进程端口
    "postcss-import": "^11.0.0", //可以消耗本地文件、节点模块或web_modules
    "postcss-loader": "^2.0.8", //用来兼容css的插件
    "postcss-url": "^7.2.1", //URL上重新定位、内联或复制
    "rimraf": "^2.6.0", //节点的UNIX命令RM—RF,强制删除文件或者目录的命令
    "semver": "^5.3.0", //用来对特定的版本号做判断的
    "shelljs": "^0.7.6", //使用它来消除shell脚本在UNIX上的依赖性，同时仍然保留其熟悉和强大的命令，即可执行Unix系统命令
    "uglifyjs-webpack-plugin": "^1.1.1", //压缩js文件
    "url-loader": "^0.5.8", //压缩文件，可将图片转化为base64
    "vue-loader": "^13.3.0", //VUE单文件组件的WebPACK加载器
    "vue-style-loader": "^3.0.1", //类似于样式加载程序，您可以在CSS加载器之后将其链接，以将CSS动态地注入到文档中作为样式标签
    "vue-template-compiler": "^2.5.2", //这个包可以用来预编译VUE模板到渲染函数，以避免运行时编译开销和CSP限制
    "webpack": "^3.6.0", //打包工具
    "webpack-bundle-analyzer": "^2.9.0", //可视化webpack输出文件的大小
    "webpack-dev-server": ">=3.1.11", //提供一个提供实时重载的开发服务器
    "webpack-merge": "^4.1.0" //它将数组和合并对象创建一个新对象。如果遇到函数，它将执行它们，通过算法运行结果，然后再次将返回的值封装在函数中
  },
  //engines是引擎，指定node和npm版本
  "engines": {
    "node": ">= 6.0.0",
    "npm": ">= 3.0.0"
  },
  //限制了浏览器或者客户端需要什么版本才可运行
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}

/**
 * devDependencies和dependencies的区别：devDependencies里面的插件只用于开发环境，不用于生产环境，即辅助作用，打包的时候需要，打包完成就不需要了
 * 而dependencies是需要发布到生产环境的，自始至终都在
 * 比如wepack等只是在开发中使用的包就写入到devDependencies
 * 而像vue这种项目全程依赖的包要写入到dependencies
 */

 /**
  * file-loader和url-loader的区别：以图片为例，file-loader可对图片进行压缩，但是还是通过文件路径进行引入，当http请求增多时会降低页面性能
  * 而url-loader通过设定limit参数，小于limit字节的图片会被转成base64的文件，大于limit字节的将进行图片压缩的操作
  * 总而言之，url-loader是file-loader的上层封装
  * https://www.npmjs.com/package/file-loader
  * https://www.npmjs.com/package/url-loader
  * https://blog.csdn.net/qq_38652603/article/details/73835153 二者的区别详解
  */

  /**
   * "webpack-dev-server": ">=3.1.11"
   * 在3.1.11之前，webpack-dev-server中的lib/Server.js中发现了一个问题。
   * 攻击者能够窃取开发人员的代码，是因为WebSocket服务器不检查请求的来源，而WebSocket服务器用于HMR(热模块替换)。
   * 任何人都可以通过ws://127.0.0.1:8080/连接接收WebSocket服务器发送的HMR消息。
   */

   /**
    * "webpack-bundle-analyzer": ">=3.3.2"
    * 3.3.2之前的webpack-bundle-analyzer版本容易受到跨站点脚本的攻击。
    * 该包使用JSON.stringify()，而没有正确转义可能导致跨站点脚本编写的输入。
    */

    /**
     * "js-yaml": ">=3.13.1"
     * 3.13.0之前的版本js-yaml很容易被拒绝服务。通过解析精心设计的YAML文件，节点进程会停止，并可能耗尽系统资源，导致拒绝服务。
     * 3.13.1之前的Js-yaml容易受到代码注入的影响。load()函数可以执行通过恶意YAML文件注入的任意代码。
     */

languages: Markdown JavaScript


text:
<repo_name>vaisurohini/guvi<file_sep>/registration.php
<form name="frmRegistration" method="post" action="">

		<?php if(!empty($success_message)) { ?>

<?php if(isset($success_message)) echo $success_message; ?>

		<?php } ?>
		<?php if(!empty($error_message)) { ?>

<?php if(isset($error_message)) echo $error_message; ?>

		<?php } ?>

			User Name
			<input type="text" class="demoInputBox" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>">

			First Name
			<input type="text" class="demoInputBox" name="firstName" value="<?php if(isset($_POST['firstName'])) echo $_POST['firstName']; ?>">

			Last Name
			<input type="text" class="demoInputBox" name="lastName" value="<?php if(isset($_POST['lastName'])) echo $_POST['lastName']; ?>">

			Password
			<input type="password" class="demoInputBox" name="password" value="">

			Confirm Password
			<input type="<PASSWORD>" class="demoInputBox" name="confirm_password" value="">

			Email
			<input type="text" class="dem.
oInputBox" name="userEmail" value="<?php if(isset($_POST['userEmail'])) echo $_POST['userEmail']; ?>">

			Gender
			<input type="radio" name="gender" value="Male" <?php if(isset($_POST['gender']) && $_POST['gender']=="Male") { ?>checked<?php  } ?>> Male
			<input type="radio" name="gender" value="Female" <?php if(isset($_POST['gender']) && $_POST['gender']=="Female") { ?>checked<?php  } ?>> Female

			<input type="checkbox" name="terms"> I accept Terms and Conditions <input type="submit" name="register-user" value="Register" class="btnRegister">

</form>

repo_language: PHP

repo_name: vaisurohini/guvi


text:
<repo_name>casher0009/lab-canvas-race-car<file_sep>/starter_code/script.js
//canvas height="800px" width="1200px"
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

// //PRUEBAS Y DIMENSIONES DEL CANVAS
// ctx.fillRect(0,0,50,50)
// ctx.fillRect(canvas.width-50,0,50,50)
// ctx.fillRect(canvas.width-50,canvas.height-50,50,50)
// ctx.fillRect(0,canvas.height-50,50,50)

//constants
var interval;
var frames = 0;
var images = {
    bg:"./images/pista.jpg",
    car:"./images/car.png"
}
var obs = [];

//class
class Board{
  constructor(){
      this.x = 0;
      this.y = 0;
      this.width = canvas.width;
      this.height = canvas.height;
      this.image = new Image();
      this.image.src = images.bg;
      this.image.onload = function(){
          this.draw();
      }.bind(this)
  }
  draw(){
    ctx.drawImage(this.image, this.x,this.y,this.width,this.height);

    // VELOCIDAD <NAME>
    this.y+=5
    if (this.y === this.height) this.y = 0;
    ctx.drawImage(this.image, this.x,this.y,this.width,this.height);
    ctx.drawImage(this.image, this.x, this.y-this.height,this.width,this.height)
    ctx.fillStyle = "peru";
ctx.font = '70px Courier New';
ctx.fillText(Math.floor(frames / 60), this.width -100, 50 )

}
gameOver(){
    ctx.font = "65px Courier New";
    ctx.fillText("Game Over", 50,200);
    ctx.font = "24px Courier New";
    ctx.fillText("PRESS 'SPACE' TO RESTART", 55,270);

}

}

class Car{
    constructor(){
        this.width = 50;
        this.height = 80;
        this.x = 50;
        this.y = canvas.height-this.height -20;
        this.image = new Image();
        this.image.src = images.car;
        this.image.onload = function(){
            this.draw();
        }.bind(this)
    }
    draw(){
        ctx.drawImage(this.image, this.x,this.y,this.width,this.height);
}

isTouching(item){
    return  (this.x < item.x + item.width) &&
            (this.x + this.width > item.x) &&
            (this.y < item.y + item.height) &&
            (this.y + this.height > item.y);
  }
}

class Obstacle{
    constructor(x, width){
        this.x = x
        this.y = 0;
        this.width = width;
        this.height = 30;
    }
    draw(){
        this.y+=10;
        ctx.fillStyle="#A01E8E";
        ctx.fillRect(this.x,this.y, this.width,this.height)
    }
}

//instances
var board = new Board();
var car = new Car();

//mainFunctions
function update(){
    frames++;
    ctx.clearRect(0,0,canvas.width,canvas.height);
    board.draw();
    car.draw();
    generate()
    drawObs()

}

function start(){
    if(interval) return;
    interval = setInterval(update, 1000/60);
};

//aux functions

function generate(){
    // OBSTACULOS PRO
    if(!(frames%50===0) ) return;

    // OBSTACULOS KARY Y LEO
    //  if(!(frames%80===0) ) return;

    var width = Math.floor((Math.random() * 200)+60);
    var x = Math.floor(Math.random() * 400);
    var obstaculo = new Obstacle(x,width);
    obs.push(obstaculo);
}

function drawObs(){
    obs.forEach(function(obstaculo){
        obstaculo.draw();
        if(car.isTouching(obstaculo)){
            finish();
        }
    });
}

    function finish(){
        clearInterval(interval);
        interval = undefined;
        board.gameOver();
    }
    function restart(){
        if(interval) return;
        obs = [];
        frames = 0;
        start();
    }

//listeners
addEventListener("keydown", function(e){
    console.log(e.keyCode)
    switch(e.keyCode){
      case 37:
      if(car.x === 50)return;
      car.x-=50;
      break;
      case 39:
      if(car.x === canvas.width - car.width*2)return;
      car.x+=50;
      break;
      case 32:
      restart()
    }
  })

var inicio = document.getElementById("start-button")
inicio.addEventListener('click', start())

//INTENTO ANTERIOR
// //canvas
// var canvas = document.getElementById('canvas');
// var ctx = canvas.getContext('2d');

// var img = new Image();
// img.src = "./images/pista.jpg";
// // var img = new Image();
// // img.src = 'images/pista.jpg';

// ctx.fillRect(0,0,50,50)

// //constantes
// var interval;

// //clases EL FONDO DE LAS COSAS, COMO SE CREAN MUEVEN Y DIBUJAN
// //   draw: function() {

// //     ctx.drawImage(this.img, this.x, 0);
// //     if (this.speed < 0)
// //      {
// //       ctx.drawImage(this.img, this.x + canvas.width, 0);
// //   } else
// //   {
// //       ctx.drawImage(this.img, this.x - this.img.width, 0);
// //     }
// //   },
// // };

// class Fondo{
//   constructor(){
//     this.x = 0;
//     this.y = 0;
//     this.width = canvas.width;
//     this.height = canvas.height;
//     this.image = new Image();
//     this.image.src = '../images/pista.jpg';
//     this.image.onload = function(){
//       this.draw()
//     }.bind(this)
//   }
//     draw(){
//     ctx.drawImage()
//   }
//   }

// // start calling updateCanvas once the image is loaded
// //img.onload = updateCanvas;

// //instancias LAS PARTES QUE EXISTEN

// var fondo = new Fondo()

// //main functions EL DIBUJAR LAS COSAS... AQUI EXISTE LA MAGIA
// function updateCanvas() {
//   fondo.draw()}
//   // backgroundImage.move();

//   // ctx.clearRect(0, 0, canvas.width, canvas.height);
//   // backgroundImage.draw();

//   // requestAnimationFrame(updateCanvas)}

// //listeners ES LA INTERFACE DEL USUARIO

// // window.onload = function() {
// //   document.getElementById("start-button").onclick = function() {
// //     startGame();
// //   }
// // }
// console.log(fondo)

repo_language: JavaScript


text:
<file_sep>package uk.ac.belfastmet.rhi.repositories;

import org.springframework.data.repository.CrudRepository;

import uk.ac.belfastmet.rhi.domain.Beneficiary;

public interface RHIRepository extends CrudRepository<Beneficiary, Integer>
{

}
<file_sep>package uk.ac.belfastmet.buildings.service;

import java.util.ArrayList;

import org.springframework.stereotype.Service;

import uk.ac.belfastmet.buildings.domain.Building;

@Service
public class BuildingService
{

	public ArrayList<Building> getLargestFloorArea()
	{
		ArrayList<Building> buildings = new ArrayList<Building>();

		Building building1 = new Building("New Century Global Center","China", "Chengdu", "1,760,000", "LFA1.jpg");
		buildings.add(building1);
		Building building2 = new Building("Dubai International Airport Terminal 3","United Arab Emirates", "Dubai", "1,713,000", "LFA2.jpg");
		buildings.add(building2);
		Building building3 = new Building("Abraj Al-Bait Endowment","Saudi Arabia", "Mecca", "1,575,815", "LFA3.jpg");
		buildings.add(building3);
		Building building4 = new Building("Central World", "Thailand", "Bangkok", "1,024,000", "LFA4.jpg");
		buildings.add(building4);
		Building building5 = new Building("Aalsmeer Flower Auction","Netherlands", "Aalsmeer", "990,000", "LFA5.jpg");
		buildings.add(building5);
		Building building6 = new Building("Beijing Capital International Airport Terminal 3", "China", "Beijing", "986,000", "LFA6.jpg");
		buildings.add(building6);
		Building building7 = new Building("The Venetian Macao","Macau", "Macau", "980,000", "LFA7.jpg");
		buildings.add(building7);
		Building building8 = new Building("Sands Cotai Central","Macau", "Macau", "890,000", "LFA8.jpg");
		buildings.add(building8);
		Building building9 = new Building("Ciputra World Surabaya","Indonesia", "Surabaya", "750,000", "LFA9.jpg");
		buildings.add(building9);
		Building building10 = new Building("Berjaya Times Square","Malaysia", "Kuala Lumpur", "700,000", "LFA10.jpg");
		buildings.add(building10);

		return buildings;
	}

	public ArrayList<Building> getLargestFootprint()
	{
		ArrayList<Building> buildings = new ArrayList<Building>();

		Building building1 = new Building("Aalsmeer Flower Auction","Netherlands", "Aalsmeer", "518,000", "LFP1.jpg");
		buildings.add(building1);
		Building building2 = new Building("Tesla Factory","United States", "California", "427,354" , "LFP2.jpg");
		buildings.add(building2);
		Building building3 = new Building("Boeing Everett Factory","United States", "Everett", "398,000", "LFP3.jpg");
		buildings.add(building3);
		Building building4 = new Building("Michelin Distribution Center", "United States", "Spartanburg", "371,612", "LFP4.jpg");
		buildings.add(building4);
		Building building5 = new Building("Great Mosque of Mecca","Saudi Arabia", "Hijaz", "356,000", "LFP5.jpg");
		buildings.add(building5);
		Building building6 = new Building("Nike - North America Logistics Center", "United States", "Memphis", "260,000", "LFP6.jpg");
		buildings.add(building6);
		Building building7 = new Building("John Deere North American Parts Distribution Center","United States", "Illinois", "246,000" , "LFP7.jpg");
		buildings.add(building7);
		Building building8 = new Building("Mall of Dubai","United Arab Emirates", "Dubai", "500,000" , "LFP8.jpg");
		buildings.add(building8);
		Building building9 = new Building("Mitsubishi Motors North America","United States", "Illinois", "220,000", "LFP9.jpg");
		buildings.add(building9);
		Building building10 = new Building("Indonesia Convention Exhibition","Indonesia", "Bumi Serpong Damai", "220,000", "LFP10.jpg");
		buildings.add(building10);

		return buildings;
	}

	public ArrayList<Building> getLargestUsableVolume()
	{
		ArrayList<Building> buildings = new ArrayList<Building>();

		Building building1 = new Building("Boeing Everett Factory","United States", "Everett", "13,300,000", "LUV1.jpg");
		buildings.add(building1);
		Building building2 = new Building("Great Mosque of Mecca","Saudi Arabia", "Hijaz", "8,000,000" , "LUV2.jpg");
		buildings.add(building2);
		Building building3 = new Building("<NAME>","France", "Toulouse", "5,600,000", "LUV3.jpg");
		buildings.add(building3);
		Building building4 = new Building("Boeing Composite Wing Center", "United States", "Everett", "3,700,000", "LUV4.jpg");
		buildings.add(building4);
		Building building5 = new Building("Aerium","Germany", "Brandenburg", "5,200,000" , "LUV5.jpg");
		buildings.add(building5);
		Building building6 = new Building("Meyer Werft Dockhalle 2", "Germany", "Papenburg", "4,720,000", "LUV6.jpg");
		buildings.add(building6);
		Building building7 = new Building("NASA Vehicle Assembly Building","United States", "Brevard County", "3,660,000" , "LUV7.jpg");
		buildings.add(building7);
		Building building8 = new Building("The O2","United Kingdom", "London", "2,790,000" , "LUV8.jpg");
		buildings.add(building8);
		Building building9 = new Building("Tesco Ireland Distribution Centre","Ireland", "Donabate", "1,550,000", "LUV9.jpg");
		buildings.add(building9);
		Building building10 = new Building("Target Import Warehouse","United States", "Savannah", "1,500,000" , "LUV10.jpg");
		buildings.add(building10);

		return buildings;
	}
}
<file_sep>package uk.ac.belfastmet.constituencies.controller;

import java.util.ArrayList;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import uk.ac.belfastmet.constituencies.domain.Member;
import uk.ac.belfastmet.constituencies.domain.Members;

@Controller
@RequestMapping("")
public class ConstituencyController
{

	public ConstituencyController()
	{

	}

	@GetMapping("/")
	public String home(Model model)
	{
		model.addAttribute("pageTitle", "Events");

		return "homePage";
	}

	@GetMapping("/constituency/{constituencyId}")
	public String singleEvent(Model model, @PathVariable("constituencyId") String constituencyId)
	{
		model.addAttribute("pageTitle", "Constituency");

		//using an edited version of the original json because its terrible
		String membersUrl = "https://api.myjson.com/bins/y888n";

		RestTemplate restTemplate = new RestTemplate();
		Members members = restTemplate.getForObject(membersUrl, Members.class);
		ArrayList<Member> requestedMembers = new ArrayList<Member>();

		for(Member member: members.getAllMembers())
		{

			if (member.getConstituencyId().equals(constituencyId))
			{
				requestedMembers.add(member);
			}

		}

		model.addAttribute("constituency", requestedMembers.get(0).getConstituencyName());
		model.addAttribute("members", requestedMembers);
		return "mlaPage";
	}
}
<file_sep>package uk.ac.belfastmet.cereal.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.validator.constraints.NotEmpty;

@Entity
public class BreakfastCereal
{

	@Id
	@GeneratedValue
	private Integer cerealId;
	@NotEmpty
	private String manufacturer;
	@NotEmpty
	private String cerealName;
	private int energy;
	private int calories;
	private double protein;
	private double carbohydrate;
	private double sugars;
	private double fat;
	private double saturates;
	private double fibre;
	private String sodium;
	private String salt;
	private double iron;

	public BreakfastCereal()
	{

	}

	public BreakfastCereal(Integer cerealId, String manufacturer, String cerealName, int energy, int calories,
						   double protein, double carbohydrate, double sugars, double fat, double saturates,
						   double fibre, String sodium, String salt, double iron)
	{
		this.cerealId = cerealId;
		this.manufacturer = manufacturer;
		this.cerealName = cerealName;
		this.energy = energy;
		this.calories = calories;
		this.protein = protein;
		this.carbohydrate = carbohydrate;
		this.sugars = sugars;
		this.fat = fat;
		this.saturates = saturates;
		this.fibre = fibre;
		this.sodium = sodium;
		this.salt = salt;
		this.iron = iron;
	}

	public Integer getCerealId()
	{
		return cerealId;
	}

	public void setCerealId(Integer cerealId)
	{
		this.cerealId=cerealId;
	}

	public String getManufacturer()
	{
		return manufacturer;
	}

	public void setManufacturer(String manufacturer)
	{
		this.manufacturer = manufacturer;
	}

	public String getCerealName()
	{
		return cerealName;
	}

	public void setCerealName(String cerealName)
	{
		this.cerealName = cerealName;
	}

	public int getEnergy()
	{
		return energy;
	}

	public void setEnergy(int energy)
	{
		this.energy = energy;
	}

	public int getCalories()
	{
		return calories;
	}

	public void setCalories(int calories)
	{
		this.calories = calories;
	}

	public double getProtein()
	{
		return protein;
	}

	public void setProtein(double protein)
	{
		this.protein = protein;
	}

	public double getCarbohydrate()
	{
		return carbohydrate;
	}

	public void setCarbohydrate(double carbohydrate)
	{
		this.carbohydrate = carbohydrate;
	}

	public double getSugars()
	{
		return sugars;
	}

	public void setSugars(double sugars)
	{
		this.sugars = sugars;
	}

	public double getFat()
	{
		return fat;
	}

	public void setFat(double fat)
	{
		this.fat = fat;
	}

	public double getSaturates()
	{
		return saturates;
	}

	public void setSaturates(double saturates)
	{
		this.saturates = saturates;
	}

	public double getFibre()
	{
		return fibre;
	}

	public void setFibre(double fibre)
	{
		this.fibre = fibre;
	}

	public String getSodium()
	{
		return sodium;
	}

	public void setSodium(String sodium)
	{
		this.sodium = sodium;
	}

	public String getSalt()
	{
		return salt;
	}

	public void setSalt(String salt)
	{
		this.salt = salt;
	}

	public double getIron()
	{
		return iron;
	}

	public void setIron(double iron)
	{
		this.iron = iron;
	}

}

repo_name: ThomasJamison/Neueda-Springboot