text:
<repo_name>congxc/AlipayAndWeiXinClientDemo<file_sep>/app/src/main/java/pay/com/paydemo/model/WebResult.java
package pay.com.paydemo.model;

import android.text.TextUtils;

/*
 * 和服务端的通用返回对象
 */
public class WebResult {
    private static final long serialVersionUID = 1L;
    public final static String SUCCESS = "1";
    public final static String FAIL = "0";
    private String code;//错误代码
    private String msg; //"错误消息的描述"
    private Object result;//返回的结果对象

    public WebResult(Object result, String code, String msg) {
        this.result = result;
        this.code = code;
        this.msg = msg;
    }

    public WebResult() {

    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }

    public boolean isSuccess(){
        if(!TextUtils.isEmpty(code) && code.equals(SUCCESS))
            return true;
        return false;
    }
}
<file_sep>/app/src/main/java/pay/com/paydemo/utils/HttpUtils.java
package pay.com.paydemo.utils;

import android.text.TextUtils;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtils {
    public final static String APP_CODE = "kjb_android";
    public final static String APP_CODE_OFFLINE = "kjb_android_offline";

    public static String httpPost(String url, String entity) {
        if (url == null || url.length() == 0) {
            return null;
        }
        try {
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, entity);

            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            Response response = OkHttpUtil.execute(request);
            if (response.isSuccessful()) {
                String data = response.body().string();
                if(!TextUtils.isEmpty(data))
                    return data;
                else
                    return null;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
<file_sep>/app/src/main/java/pay/com/paydemo/Constants.java
package pay.com.paydemo;

/**
 * Created by xc on 2016/10/12.
 */

public class Constants {
    //    public final static String BASE_CHARGE_URL = "http://10.10.10.98:8080";
    public final static String BASE_CHARGE_URL = "http://160c729k13.51mypc.cn";
    public final static String ALIPAY_CHARGE_ORDER = BASE_CHARGE_URL+"/pay/OrderAlipay";
    public final static String ALIPAY_GET_QRCODE = BASE_CHARGE_URL+"/pay/ScanAlipay";
    public final static String ALIPAY_TRADE_QUERY = BASE_CHARGE_URL+"/pay/QueryAlipayOrder";

    public final static String WEIXIN_CHARGE_ORDER = BASE_CHARGE_URL+"/pay/OrderWeiXin";
    public final static String WEIXIN_GET_QRCODE = BASE_CHARGE_URL+"/pay/ScanWeiXin";
    public final static String WEIXIN_TRADE_QUERY = BASE_CHARGE_URL+"/pay/QueryWeiXinOrder";

    public final static String TOTAL_AMOUNT = "total_amount";
    public final static String SUBJECT = "subject";
    public final static String BODY = "body";

    public final static String FPAYTYPE = "fpaytype";
    public final static String FCONTRACT_NO = "fcontractno";

    public final static String FCONTROLUNITID = "FControlUnitID";
    public final static String FEFFECTDATE = "feffectdate";
    public final static String FACCOUNTNO = "FAccountNo";

    public final static String PAYMENT_TYPE = "payment_type";
    public final static String ERR_CODE = "errCode";

    public static final String PAY_RESULT_ACTION = "pay_result_action";

    public final static int PAY_SUCCESS = 0;

    public final static String TRADE_NO = "order_no";
}
<file_sep>/app/src/main/java/pay/com/paydemo/PaymentSelectActivity.java
package pay.com.paydemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import java.util.UUID;

import pay.com.paydemo.alipay.AliPay;
import pay.com.paydemo.model.ClientOrder;
import pay.com.paydemo.model.PayType;
import pay.com.paydemo.wxapi.WXPay;

public class PaymentSelectActivity extends AppCompatActivity implements View.OnClickListener {

    private ClientOrder mClientOrder;
    private String JDid = "jd888888888id";//京东公司ID
    private String KingID = "king9999999id";//金士顿公司id
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment_select);
        Intent intent = getIntent();
        int material = intent.getIntExtra("material", 0);

        inidatas(material);////首先客户端生成订单
        findViewById(R.id.login_alipay_pay).setOnClickListener(this);
        findViewById(R.id.login_weixin_pay).setOnClickListener(this);
        findViewById(R.id.scan_code_alipay).setOnClickListener(this);
        findViewById(R.id.scan_code_weixin).setOnClickListener(this);

    }

    private void inidatas(int material) {
        mClientOrder = new ClientOrder();
        mClientOrder.setFID(UUID.randomUUID().toString().replace("-",""));
        mClientOrder.setFcontrolUnitID(KingID);
        mClientOrder.setFnumber("S00123456");
        mClientOrder.setFUserID("888888");
        mClientOrder.setFUserName("zhangsan");
        if(material == 1){
            mClientOrder.setMaterailID("000001");
            mClientOrder.setMaterailName("屠龙刀");
        }else{
            mClientOrder.setMaterailID("000002");
            mClientOrder.setMaterailName("倚天剑");
        }
        mClientOrder.setFstatus(1);
        mClientOrder.setAddress("天安门");
        mClientOrder.setFmobil("155123456");
        mClientOrder.setFAmount(0.01);
        mClientOrder.setCount(1);
        mClientOrder.setFToalAmount(mClientOrder.getCount()*mClientOrder.getFAmount());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login_weixin_pay:
                WXPay wxPay = new WXPay(this);
                mClientOrder.setFpaymentType(PayType.WeiXIn.getValue());
                wxPay.pay(mClientOrder);
                break;
            case R.id.scan_code_weixin:
                Bundle data = new Bundle();
                mClientOrder.setFpaymentType(PayType.WeiXIn.getValue());
                data.putSerializable(ClientOrder.class.getName(),mClientOrder);
                Intent intent = new Intent(this,ScanCodePayActivity.class);
                intent.putExtras(data);
                startActivity(intent);
                break;
            case R.id.login_alipay_pay:
                IPay iPay = new AliPay(this);
                mClientOrder.setFpaymentType(PayType.Alipay.getValue());
                iPay.pay(mClientOrder);
                break;
            case R.id.scan_code_alipay:
                data = new Bundle();
                mClientOrder.setFpaymentType(PayType.Alipay.getValue());
                data.putSerializable(ClientOrder.class.getName(),mClientOrder);
                intent = new Intent(this,ScanCodePayActivity.class);
                intent.putExtras(data);
                startActivity(intent);
                break;
        }
    }
}
<file_sep>/app/src/main/java/pay/com/paydemo/utils/OkHttpUtil.java
package pay.com.paydemo.utils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/3/8.
 */
public class OkHttpUtil {
    //下载用的httpclient
    private static final OkHttpClient mDownloadOkHttpClient = new OkHttpClient.Builder().
            connectTimeout(600, TimeUnit.SECONDS).readTimeout(600, TimeUnit.SECONDS).build();

    private static final OkHttpClient mOkHttpClient = new OkHttpClient.Builder().connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS).build();

    /**
     * 开启异步线程访问网络
     *
     * @param request
     * @param responseCallback
     */
    public static void enqueue(Request request, Callback responseCallback) {
        mOkHttpClient.newCall(request).enqueue(responseCallback);
    }

    /**
     * 该不会开启异步线程。
     *
     * @param request
     * @return
     */
    public static Response execute(Request request) throws Exception {
        return mOkHttpClient.newCall(request).execute();
    }

    /**
     * 该不会开启异步线程。
     *
     * @param request
     * @return
     */
    public static Response downloadExecute(Request request) throws Exception {
        return mDownloadOkHttpClient.newCall(request).execute();
    }

    /**
     * 开启异步线程访问网络
     *
     * @param request
     * @param responseCallback
     */
    public static void downloadEnqueue(Request request, Callback responseCallback) {
        mDownloadOkHttpClient.newCall(request).enqueue(responseCallback);
    }

    /**
     * 开启异步线程访问网络, 且不在意返回结果（实现空callback）
     *
     * @param request
     */
    public static void enqueue(Request request) {
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {

            }
        });
    }

    public static String getStringFromServer(String url) throws Exception {
        Request request = new Request.Builder().url(url).build();
        Response response = execute(request);
        if (response.isSuccessful()) {
            String responseUrl = response.body().string();
            return responseUrl;
        } else {
            throw new Exception("Unexpected code " + response);
        }
    }

    private static final String CHARSET_NAME = "UTF-8";

    /**
     * 为HttpGet 的 url 方便的添加1个name value 参数。
     *
     * @param url
     * @param name
     * @param value
     * @return
     */
    public static String attachHttpGetParam(String url, String name, String value) {
        return url + "?" + name + "=" + value;
    }

}
<file_sep>/app/src/main/java/pay/com/paydemo/model/QrTradeOrder.java
package pay.com.paydemo.model;

/*
 * 扫描订单对象
 */
public class QrTradeOrder {
    private String orderNo;
    private String twoDimCode;
    private String ownerId;
    private Double totalFee;

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

    public Double getTotalFee() {
        return totalFee;
    }

    public void setTotalFee(Double totalFee) {
        this.totalFee = totalFee;
    }

    public String getOwnerId() {
        return ownerId;
    }

    public void setOwnerId(String ownerId) {
        this.ownerId = ownerId;
    }

    public String getTwoDimCode() {
        return twoDimCode;
    }

    public void setTwoDimCode(String twoDimCode) {
        twoDimCode = twoDimCode;
    }
}
<file_sep>/app/src/main/java/pay/com/paydemo/model/OrderQuery.java
package pay.com.paydemo.model;

public class OrderQuery {
    private int paymentType;
    private String out_trade_no;
    //外部订单号
    public String trade_no;

    public OrderQuery() {

    }

    public OrderQuery(int paymentType,String out_trade_no,String trade_no) {
        this.out_trade_no = out_trade_no;
        this.paymentType = paymentType;
        this.trade_no = trade_no;
    }

    public String getOutOrderNo() {
        return out_trade_no;
    }
    public void setOutOrderNo(String out_trade_no) {
        this.out_trade_no = out_trade_no;
    }
    public int getPaymentType() {
        return paymentType;
    }
    public void setPaymentType(int paymentType) {
        this.paymentType = paymentType;
    }

    public String getTrade_no() {
        return trade_no;
    }

    public void setTrade_no(String trade_no) {
        this.trade_no = trade_no;
    }
}
<file_sep>/app/src/main/java/pay/com/paydemo/utils/ZxingUtils.java
package pay.com.paydemo.utils;

import android.graphics.Bitmap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.Hashtable;

/**
 * 使用了google zxing作为二维码生成工具
 */
public class ZxingUtils {
//	private static Log log = LogFactory.getLog(ZxingUtils.class);

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    /** 将内容contents生成长为width，宽为width的图片，图片路径由imgPath指定
     */
	public static Bitmap getQRCodeImge(String contents, int width, int height, String imgPath) {
		try {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF8");

			BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);

            return BitMatrixToBitmap(bitMatrix);

		} catch (Exception e) {
            return null;
		}
	}

    private static Bitmap BitMatrixToBitmap(BitMatrix matrix) {
        final int WHITE = 0xFFFFFFFF;
        final int BLACK = 0xFF000000;

        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = matrix.get(x, y) ? BLACK : WHITE;
            }
        }
        return createBitmap(width, height, pixels);
    }

    /**
     * 生成Bitmap
     * @param width
     * @param height
     * @param pixels
     * @return
     */
    private static Bitmap createBitmap(int width, int height, int[] pixels) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
}
<file_sep>/app/src/main/java/pay/com/paydemo/model/OrderRequest.java
package pay.com.paydemo.model;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import pay.com.paydemo.utils.GsonFactory;

/**
 * 下单请求
 */
public class OrderRequest {

    private String FControlUnitID;//公司
    private String FEquipmentNo;
    private String FUserId;
    private String Fcontractno;//合同号
    private String subject;
    private double total_fee;
    private String body;
    private int paymentType;
    private String create_ip;
    public String getFControlUnitID() {
        return FControlUnitID;
    }

    public void setFControlUnitID(String fControlUnitID) {
        FControlUnitID = fControlUnitID;
    }

    public String getFEquipmentNo() {
        return FEquipmentNo;
    }

    public void setFEquipmentNo(String fEquipmentNo) {
        FEquipmentNo = fEquipmentNo;
    }

    public String getFUserId() {
        return FUserId;
    }

    public void setFUserId(String fUserId) {
        FUserId = fUserId;
    }

    public String getFcontractno() {
        return Fcontractno;
    }

    public void setFcontractno(String fcontractno) {
        Fcontractno = fcontractno;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public double getTotal_fee() {
        return total_fee;
    }

    public void setTotal_fee(double total_fee) {
        this.total_fee = total_fee;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public int getPaymentType() {
        return paymentType;
    }

    public void setPaymentType(int paymentType) {
        this.paymentType = paymentType;
    }

    public static OrderRequest build(PaymentType paymentType,ClientOrder clientOrder,Context context){
        OrderRequest orderRequest = new OrderRequest();
        orderRequest.setPaymentType(paymentType.getValue());
        orderRequest.setSubject(clientOrder.getSubject());
        orderRequest.setTotal_fee(clientOrder.getFToalAmount());
        orderRequest.setFUserId(clientOrder.getFUserID());
        orderRequest.setFControlUnitID(clientOrder.getFcontrolUnitID());
        orderRequest.create_ip = getDeviceIp(context);
        orderRequest.setBody(GsonFactory.getGson().toJson(clientOrder));
        return orderRequest;
    }
    /**
     * 获取设备ip
     *
     * @return
     */
    public static String getDeviceIp(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        return ((ipAddress >> 24) & 0xFF) + "." +
                ((ipAddress >> 16) & 0xFF) + "." +
                ((ipAddress >> 8) & 0xFF) + "." +
                (ipAddress & 0xFF);
    }
}

branch_name: refs/heads/master

repo_language: Java

repo_name: congxc/AlipayAndWeiXinClientDemo


text:
<repo_name>diego12o/proyecto_freelancer<file_sep>/css/style.css
/*
    (*) selector {propiedad: valor;}
    (*) en vez de usar px o en, se utiliza rem ya que se adapta a distintos tamaños de las tecnologías

    (*) el configurar el html y body como se muestra genera que la conversión de rem a px
    sea de 1 rem = 10px haciendo más fácil el manejo de la unidad de medida

    (*) Selectores:
        - de elemento -> según etiqueta
        - de clase (inicia con punto)
        - de ID (inicia con #)-> id no puede repetirse
        - de atributo -> según un atributo que tenga algún elemento
    (*) Combinación de descendentes -> selecciona los elementos hijos cuyo padre sea una clase o id en específico
    (*) todos los hijos -> aplica la regla a todos los elementos hijos
        ej: .cliente > p{
            color: blue;
        }
        aplica color azul a todos los parrafos de los elementos pertenecientes a la clase cliente
    (*) especificidad -> es el cómo el navegador mostrará el css respecto a qué tan específico es el selector creado. Con ello, se puede modificar un selector y se tendrá preferencia la especificidad antes que la cascada

    (*)color en css:
        -> por nombre
        -> valor hexadecimal
        -> rgb(): red, green and blue
        -> hsl()

    (*) página font de google para ver distintas fuentes
        -> se utiliza en font-family la fuente de google
        -> se ajusta al tamaño elegido en la página

    (*)display: block -> los elementos se colocarán unos
                        debajo de los otros
                        ej: parrafos, div, etc
    (*)display inline -> los elementos se posicionarán a la
                        derecha una vez que hayan tomado el
                        espacio que requieren
                        ej: los enlaces del nav
    - no es necesario modificar el display a no ser que
    se requiera

    (*)Cómo elegir entre flexbox y css grid
        -> flexbox : para alineación o distribución de los elementos dentro de contenedores
        -> css grid : para definir Layouts (como columnas o contenedores de elementos)

        (*) lo de flexbox lo puede hacer grid, pero a veces es más sencillo con flexbox y otras con grid

    (*) NUNCA USAR FLOAT -> internet explorer

    (*) en CSS se pueden usar como atributos los type
        ej:
            .campo input[type="text"],
            .campo input[type="tel"]{
                background-color: red;
            }
*/

/*
    paleta de colores (root)
    = custom properties
*/
:root{
    --blanco: #ffffff;
    --oscuro: #212121;
    --primario: #E6B61E;
    --secundario: #05B6A9;
    --gris: #757575;
    --grisClaro: #DFE9F3;
}
html {
    font-size: 62.5%;
    box-sizing: border-box;
}

/*
    * : selecciona todos los elementos de html
    , : ayuda para ahorrar líneas de código en caso de que algunos selectores coincidan en propiedades
    before|after : define algo antes o después del selector y que no es posible de seleccionar
*/
*, *:before, *:after {
    /*esto es para css box model (tambien lo de box-sizing)*/
    box-sizing: inherit;
}

body {
    font-size: 16px;
    font-family: 'Oswald', sans-serif;
    background-image: linear-gradient(to top, var(--grisClaro) 0%, var(--blanco) 100%);
}

h1 {
    font-size: 3.8rem;
}

h2{
    font-size: 2.8rem;
}

h3{
    font-size: 1.8rem;
}

h1, h2, h3 {
    text-align: center;
}

.titulo span {
    font-size: 2rem;
}

/*magin left y right al definirlos automaticos, se ponen
centrados
margin: w x y z -> w top, x right, y bot, z left
si w=y y x=z, entonces margin: w x*/
.contenedor{
    max-width: 120rem;
    margin: 0 auto;
}

.sombra{
    -webkit-box-shadow: -9px 9px 21px -5px rgba(120,104,120,1);
    -moz-box-shadow: -9px 9px 21px -5px rgba(120,104,120,1);
    box-shadow: -9px 9px 21px -5px rgba(120,104,120,1);
    background-color: var(--blanco);
    padding: 2rem;
    border-radius: 1rem;
}

.boton{
    background-color: var(--secundario);
    color: var(--blanco);
    padding: 1rem 3rem;
    margin-top: 1rem;
    font-size: 2rem;
    text-decoration: none; /*quita la linea del enlace*/
    text-transform: uppercase; /*transforma en mayuscula*/
    font-weight: bold;
    border-radius: .5rem; /*darle esquinas circulares al boton*/
    width: 90%;
    text-align: center;
    border: none;
}

@media (min-width: 768px) {
    .boton{
        width: auto;
    }
}

.boton:hover{
    cursor: pointer;
}

.nav-bg{
    background-color: var(--secundario);
}

/*padding: 1rem -> padding: 1rem 1rem 1rem 1rem
display: flex -> habilita flex box
    flexbox es unidireccional (fila o columna)
        -> row o row-reverse los elementos hijos se colocarán
        de izquierda a derecha uno junto al otro
        ->column o column-reverse los elementos se colocarán
        de arriba hacia abajo
        FLEXBOX sirve para alinear los elementos, no para animación ni textos*/

.nav-principal{
    display: flex;
    flex-direction: column;
}

@media (min-width: 768px) {
    .nav-principal{
        flex-direction: row;
        justify-content: space-around;
    }

    .servicios{
        display: grid; /*agrega las funciones de css grid*/
        /*contenido se agrega dentro de un área definida con posibilidad de 1 o 2 dimensiones con grid, a diferencia de flexbox que
        se agrega automaticamente en 1 dimensión
        --se pueden usar en un mismo diseño*/

        /*grid-template-columns: 1fr 1fr 1fr; 1fr = 1 fraccion*/
        /*grid-template-rows: 20rem 80rem;*/

        /*para reemplazar columns y rows se puede usar grid: 20rem 80rem / 30 rem 30 rem 30 rem; */

        /*se simplifica usando repeat:*/
        grid-template-columns: repeat(3, 1fr); /*repite 3 veces 1 fr*/
        column-gap: 1rem;

    }
}

.servicio{
    align-content: center;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.servicio p{
    line-height: 2;
    font-weight: normal;
}

.servicio .iconos{
    height: 15rem;
    width: 15rem;
    background-color: var(--primario);
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.nav-principal a{
    text-align: center;
    color: var(--blanco);
    text-decoration: none;
    font-size: 2rem;
    font-weight: 700;
    padding: 1rem;
}

/*para definir un evento en el enlace*/
.nav-principal a:hover{
    background-color: var(--primario);
    color: var(--oscuro);
}

/*
    Para hacer al sitio web adaptable a todos los tamaños de pantalla se utiliza responsive web design
    -> esto se logra con media queries
        sintaxis: @media (min-width: 768 px){
            body{
                background-color: blue;
            }
        }

        -> esto define que a partir de los 768 px en adelante, el color del fondo del sitio será azul

        media queries estándar:
            -> celulares: min-width: 480px
            -> tablets: min-width: 768px
            -> laptops o pc de escritorio: min-width: 1140px
*/

/*
    CSS box model -> lo que se muestra en pantalla está delimitado por 4 cosas:
                    (*)tamaño contenido
                    (*)padding
                    (*)tamaño borde
                    (*)margen
*/
.hero {
    background-image: url(../img/imagen0.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    height: 450px;
    position: relative;

    margin-bottom: 2rem;
}

.contenido-hero {
    position: absolute;
    background-color: rgb( 0,0,0, .1); /* Anterior */
    background-color: rgb( 0 0 0 / 70%); /* Nueva */
    width: 100%;
    height: 100%;

    display: flex; /* iniciar flex box */
    flex-direction: column;
    align-items: center; /* alinear horizontalmente */
    justify-content: center; /* alinear verticalmente */
}

.contenido-hero h2,
.contenido-hero p{
    color: var(--blanco);
}

.formulario{
    background-color: var(--gris);
    width: min(70rem, 100%); /** utiliza valor más pequeño **/
    margin: 0 auto;
    padding: 2rem;
    border-radius: 1rem;
}

.formulario fieldset{
    border: none;
}

.formulario legend{
    text-align: center;
    font-size: 2rem;
    text-transform: uppercase;
    font-weight: 700;
    margin-bottom: 2rem;
}

.campo{
    margin-bottom: 1rem;
}

.campo label{
     color: var(--blanco);
     font-weight: bold;
     margin-bottom: .5rem;
     display: block;
}

.campo textarea{
    height: 15rem;
}

.input-text{
    width: 100%;
    border: none;
    padding: 1.2rem;
    border-radius: .5rem;
}

.w-sm-100{
    width: 100%;
}

.flex{
    display:flex;
}
.alinear-derecha{
    justify-content: flex-end;
}

@media (min-width: 768px) {
    .w-sm-100{
        width:auto;
    }

    .contenedor-campos{
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-template-rows: auto auto 20rem;
        column-gap: 1rem;
    }

    .campo:nth-child(3),
    .campo:nth-child(4){
        grid-column: 1 / 3;
    }
}

.footer{
    text-align: center;
}

/*
.ubicacion{
    display: flex;
    align-items: flex-end;
}*/

/*
    diferentes modos de escribir código css:
        (1) BEM
        (2) utility first
        (3) módulo

    estas las más comunes

    1. BEM -> bloques, elementos, modificadores
            ej:
                .card{}           -> bloque
                .card__titulo{}   -> elementos
                .card__imagen{}   -> elementos
                .card__boton{}    -> elementos
                .card__boton--activo{} -> modificadores

    2. Utility first -> se crean clases con una sola propiedad
        ej:
            .text-center{}
            .color-red-100 {}
            etc

    3. Modulo -> se define contenido principal y luego se
                seleccionan los elementos
                ej:
                    .card{}
                    .card h2{}
                    .card img{}
                    etc

*/

branch_name: refs/heads/main

repo_language: CSS


text:
<repo_name>rafaelhueb92/appSecurityExpress<file_sep>/server/src/routes.js
const app = require("express").Router();
const proxy = require("express-http-proxy");

app.get("/:msg", (req, res) => {
  try {
    const { msg } = req.params;
    const html = `
      <html>
      <body>
      <h1>${msg}</h1>
      </body>
      </html>
      `;
    setTimeout(() => {
      res.send(html);
    }, 1000);
  } catch (ex) {
    res.sendStatus(500);
  }
});

module.exports = app;<file_sep>/ddosApp/Styles.js
import { StyleSheet } from "react-native";

export default StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  title: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  searchForm: {
    position: "absolute",
    top: 20,
    left: 20,
    right: 20,
    zIndex: 5,
    flexDirection: "row"
  },
  loadButton: {
    width: 50,
    height: 50,
    backgroundColor: "#8E4Dff",
    borderRadius: 25,
    justifyContent: "center",
    alignItems: "center",
    marginLeft: 15
  },
  StopButton: {
    width: 50,
    height: 50,
    backgroundColor: "#8E4Dff",
    borderRadius: 25,
    justifyContent: "center",
    alignItems: "center",
    marginLeft: 15
  }
});
<file_sep>/ddosApp/App.js
import React, { useState, useEffect } from "react";
import {
  TouchableOpacity,
  Text,
  View,
  TextInput
} from "react-native";
import { MaterialIcons } from "@expo/vector-icons";

import styles from "./Styles";
import ddos from "./services/ddos";

export default function App() {
  const [continueAtk, setcontinueAtk] = useState(false);
  const [results, setresults] = useState([]);
  const [host, sethost] = useState("");

  useEffect(() => {
    async function makeAttack() {
      const Ddos = ddos(host);
      console.log("Is ready to attack?", continueAtk ? "Yes" : "No");
      for (i = 1; continueAtk; i++) {
        console.log("attack atempt", i);
        const { status } = await Ddos.attack();
        console.log(i, "status attack:", status);
        setresults([...results, { i, status }]);
      }
    }
    makeAttack();
  }, [continueAtk]);

  async function attack() {
    try {
      console.log("Begin Attack!");
      setcontinueAtk(true);
    } catch (ex) {
      throw ex;
    }
  }

  function StopAttack() {
    console.log("Stop Attack!");
    setcontinueAtk(false);
    sethost("");
  }

  return (
    <View style={styles.container}>
      {continueAtk === false ? (
        <>
          <Text style={styles.title}>Put the host to attack!</Text>
          <TextInput
            style={styles.searchInput}
            placeholder="ex.: http://localhost:9000"
            placeholderTextColor="#999"
            autoCorrect={false}
            value={host}
            onChangeText={sethost}
          />
          <TouchableOpacity
            style={styles.loadButton}
            onPress={() => {
              attack();
            }}
          >
            <MaterialIcons name="flight-land" size={20} color="#FFF" />
          </TouchableOpacity>
        </>
      ) : (
        <>
          <TouchableOpacity
            style={styles.loadButton}
            onPress={() => {
              StopAttack();
            }}
          >
            <MaterialIcons name="stop" size={20} color="#FFF" />
            <Text style={styles.title}>Resultados</Text>
          </TouchableOpacity>

          {results.forEach(({ i, status }) => {
            <Text style={styles.title}>{`Req:${i} status:${status}`}</Text>;
          })}
        </>
      )}
    </View>
  );
}
<file_sep>/server/src/index.js
const  PORT = process.env.PORT || 8000;
const http = require("http");
const express = require("express");

const app = express();

app.use("api/", require("./routes"));
app.use(require("./middlewares"));
http
  .createServer(app)
  .listen(PORT, () =>
    console.log(`Server running on http://localhost:${PORT}`)
  );
<file_sep>/ddosApp/utils/axios.js
import axios from "axios";

export default (baseURL) => axios.create({baseURL});<file_sep>/server/src/middleware/nodeCache.middleware.js
const app = require("express").Router();
const cache = require("../utils/nodeCache.utils");

app.use((req, res, next) => {
  try {
    const ip = req.socket.remoteAddress || req.headers["X-Forwarded-For"];
    console.log("remote Adress", ip);
    const addr = cache.get("ip");
    if (!addr) {
      cache.set("ip", ip);
      next();
    } else return res.sendStatus(403);
  } catch (ex) {
    res.sendStatus(501);
  }
});

module.exports = app;

repo_language: JavaScript


text:
<file_sep>class DropDownList {
    /**
     * Constructor
     * Put your required dependencies in the constructor parameters list
     */
    constructor(session) {
        this.session = session; // for storing items from ajax requests
        // user options
        this.searchable = true;
        this.multiple = false;
        this.value = null;
        this.items = null;
        this.placeholder = null;
        this.heading = null;
        this.closeOnSelect = null;
        this.limit = 0;
        this.maxSelections = null;
        this.defaultTheme = 'white';
        this.lazyLoading = false;
        this.isLoadingItems = false;

        // available events
        this.eventsList = [
            'onselect', // triggered when user selects item
        ];

        // internal options
        this.errorClasses = 'error-msg';
        this.error = null;
        this.originalItems = [];
        this.stopSelecting = false;
        this.id = Random.string(5);
        this.checkedItems = {};
        this._formHandler = null;
        this.searchInput = null;
        this.closeAfter = 200;
        this._closed = true;
        this.currentImage = null;

        this.availableThemes = ['white', 'white-transparent', 'dark', 'dark-transparent', 'custom'];
    }

    /**
     * Initialize the component
     * This method is triggered before rendering the component
     */
    init() {
        // input options
        this.selectedItems = [];
        this.addtionalClasses = this.prop('class', '');
        this.label = this.prop('label');
        this.name = this.prop('name', '');
        this.isRequired = !Is.null(this.inputs.getAttr('required')) || this.inputs.getProp('required');
        let value = this.inputs.getProp('value');
        this.placeholder = this.prop('placeholder');

        this.heading = this.prop('heading');

        this.onSelectEvent = this.inputs.getEvent('select');
        this.limit = this.inputs.getProp('limit', Config.get('form.dropdown.limit', 0));
        this.theme = this.prop('theme', Config.get('form.dropdown.theme', this.defaultTheme));

        this.imageable = this.inputs.getProp('imageable', false);
        this.except = this.inputs.getProp('except');

        this.icon = this.prop('icon');

        this.position = this.prop('position', 'bottom'); // dropdown list position

        if (this.multiple) {
            this.currentValue = Is.array(value) ? value.map(item => {
                return String(Is.object(item) ? item.id || item.value : item);
            }) : [];
        } else {
            this.currentValue = value ? String(value) : null;
        }

        this.getItemsList();

        if (!this.availableThemes.includes(this.theme)) {
            throw new Error(`flk-dropdownlist: Invalid theme '${this.theme}', available themes are: ${this.availableThemes.join(', ')}. `);
        }

        let closeOnSelect = this.prop('closeOnSelect');

        this.closeOnSelect = Is.boolean(closeOnSelect) ? closeOnSelect : this.multiple === false;
    }

    /**
     * Check if the dropdown items will be loaded from a service, endpoint or an http request
     */
    getItemsList() {
        this.lazyLoading = this.inputs.getProp('lazyLoading');

        this.mapRecordings = this.inputs.getEvent('map', item => {
            let text = Is.scalar(item) ? item : (item.text || item.name || item.title),
                value = Is.scalar(item) ? item : (item.id || item.value),
                image = null;

            if (this.imageable) {
                image = item.image || item.icon;
            }

            value = String(value);

            return { text, value, image };
        });

        if (!this.lazyLoading) {
            let items = this.inputs.getProp('items');
            return this.updateItems(items);
        }

        let request;
        this.service = this.inputs.getProp('service');
        this.callMethod = this.inputs.getProp('call');

        this.responseKey = this.prop('responseKey', Config.get('form.dropdown.responseKey', 'records'));

        if (this.service) {
            this.serviceMethod = this.prop('serviceMethod', Config.get('form.dropdown.serviceMethod', 'list'));
            request = this.service[this.serviceMethod].bind(this.service);
        } else if (this.callMethod) {
            request = this.callMethod;
        }

        request().then(response => {
            this.originalItems = Array.clone(response[this.responseKey]).map(this.mapRecordings);
            this.session.set(this.cacheKey, this.originalItems);
            this.prepareItems(this.originalItems);

            this.isLoadingItems = false;
        });

        // TODO: // endpoint, http requests
    }

    /**
     * Prepare items list
     *
     * @param Array items
     */
    prepareItems(items) {
        this.itemsList = Array.clone(items).map(this.mapRecordings);

        this.itemsList.forEach(item => {
            this.checkedItems[String(item.value)] = this.multiple ? this.currentValue.includes(item.value) : this.currentValue == item.value;
        });

        this.prepareItemsList(this.itemsList);
    }

    /**
     * Update items list
     *
     * @param {any} items
     */
    updateItems(items) {
        this.items = items;

        if (Is.empty(this.items) && !Is.array(this.items)) {
            let type = Is.null(this.items) ? 'null' : typeof this.items;
            throw new Error(`Invalid "${type}" type for passed [items] value, make sure to pass a valid array of items.`);
        }

        // if the passed items are key/value pairs of object
        // then we will convert it to array.
        if (!Is.array(this.items) && Is.plainObject(this.items)) {
            let arrayedItems = [];

            let reverseKeys = this.inputs.getProp('reverseKeys', false);

            for (let key in this.items) {
                let text = reverseKeys ? this.items[key] : key,
                    value = reverseKeys ? key : this.items[key];

                arrayedItems.push({
                    text,
                    value,
                });
            }

            this.items = arrayedItems;
        }
        this.originalItems = Array.clone(this.items).map(this.mapRecordings);
        this.prepareItems(this.originalItems);
    }

    /**
     * Get checked items list
     *
     * @returns Array
     */
    getCheckedItems() {
        return Is.array(this.currentValue) ? this.currentValue : [this.currentValue];
    }

    /**
     * Attach the form
     */
    attachForm(form) {
        this._formHandler = form ? form.formHandler : null;
    }

    /**
     * Validate input
     */
    validate(input) {
        if (!this.isRequired || input.value && input.checked) return;

        if (Is.empty(this.currentValue)) {
            this._formHandler.addError(this.name, 'required', trans('validation.required'));
            this.error = trans('validation.required');
        }
    }

    /**
     * Search for the given value
     *
     * @param  string keywords
     */
    searchFor(keywords) {
        let itemsList = this.originalItems.filter(item => item.text.match(new RegExp(keywords, 'i')));

        this.prepareItemsList(itemsList);
    }

    /**
     * Prepare items list in sorting and max displayed items
     *
     * @param   array itemsList
     * @returns void
     */
    prepareItemsList(itemsList) {
        if (this.except) {
            let except = (Is.array(this.except) ? this.except : [this.except]).map(value => String(value));
            itemsList = itemsList.filter(item => !except.includes(item.value));
        }

        itemsList = this.orderItems(itemsList);

        if (this.limit > 0) {
            itemsList = itemsList.slice(0, this.limit);
        }

        this.itemsList = itemsList;
    }

    /**
     * Order the given itemsList based on selected items to be displayed first
     *
     * @param   array items
     * @returns array
     */
    orderItems(items) {
        return items.sort((itemA, itemB) => {
            let checkedItemA = this.isCheckedItem(itemA),
                checkedItemB = this.isCheckedItem(itemB);

            return checkedItemA === checkedItemB ? 0 : checkedItemA ? -1 : 0;
        });
    }

    /**
     * Get input place holder
     *
     * @returns string
     */
    getPlaceholder() {
        return this.placeholder || trans('search');
    }

    /**
     * Remove the error
     */
    removeError() {
        this.error = null;
        this._formHandler.removeError(this.name);
    }

    /**
     * Toggle the list items
     */
    toggle() {
        if (this.isLoadingItems) return;
        this._closed = !this._closed;

        if (!this._closed && this.searchInput) {
            setTimeout(() => {
                this.searchInput.focused = true;
                this.searchInput.focus();
            }, 100);
        }
    }

    /**
     * Close the dropdown list
     */
    close() {
        this._closed = true;
    }

    /**
     * Get input type based on the multiple option
     */
    getInputType() {
        return this.multiple ? 'checkbox' : 'radio';
    }

    /**
     * Check if the given item is checked
     *
     * @param  object item
     * returns bool
     */
    isCheckedItem(item) {
        return this.checkedItems[item.value] === true;
    }

    /**
     * Get select list heading
     *
     * @returns string
     */
    getHeading() {
        if (this.isLoadingItems) return 'Loading...';
        let heading = this.heading || this.placeholder || this.label;

        if (this.multiple) {
            let totalCheckedItems = this.getTotalCheckedItems();
            if (totalCheckedItems > 0) {
                heading = pluralize(heading, totalCheckedItems, true);
            }
        } else if (this.currentValue) {
            return this.getTextOf(this.currentValue) || heading;
        }

        if (!heading) return trans('please-select');;

        return heading;
    }

    /**
     * Get the text of the given value
     *
     * @param string value
     * @returns string
     */
    getTextOf(value) {
        if (Is.empty(this.itemsList)) return this.heading || this.placeholder;

        let currentItem = Array.get(this.itemsList, item => item.value == value);

        return currentItem.text;
    }

    /**
     * Change the state of the given input in the checked items list
     *
     * @param  HTMLElement input
     * @returns void
     */
    changeStateOf(input, item) {
        this.checkedItems[input.value] = input.checked;
        if (!this.multiple && input.checked) {
            for (let value in this.checkedItems) {
                if (value == input.value) continue;
                this.checkedItems[value] = false;
            }
        }

        if (this.multiple === false) {
            this.currentValue = input.value;
            if (this.imageable) {
                this.setCurrentImage();
            }
        } else {
            if (input.checked) {
                this.appendSelected(input.value, false);
            } else {
                this.removeSelected(input.value, false);
            }
        }

        if (this.error) {
            this.removeError();
        }

        if (this.multiple) {
            this.itemsList = this.orderItems(this.itemsList);

            this.stopSelecting = this.maxSelections == this.currentValue.length;
        }

        if (this.onSelectEvent) {
            if (! this.multiple) {
                this.selectedItems = item;
            } else {
                this.selectedItems.push(item);
            }

            this.onSelectEvent(this.selectedItems);
        }

        if (this.closeOnSelect) {
            setTimeout(() => {
                this.close();
            }, this.closeAfter);
        }

        this.detectChanges(); // because this.checkedItems is not in the html file
    }

    /**
     * Append selected value
     * Works only with `[multiple]` with true
     *
     * @param {any} value
     */
    appendSelected(value, detectChanges = true) {
        value = String(value);
        this.currentValue = Array.pushOnce(this.currentValue, value);

        if (detectChanges) {
            this.checkedItems[value] = true;

            this.detectChanges();
        }
    }

    /**
     * Remove selected value
     * Works only with `[multiple]` with true
     *
     * @param {any} value
     */
    removeSelected(value, detectChanges = true) {
        value = String(value);
        this.currentValue = Array.remove(this.currentValue, value);

        if (detectChanges) {
            this.checkedItems[value] = false;

            this.detectChanges();
        }
    }

    /**
     * Set current image
     */
    setCurrentImage() {
        let currentItem = this.itemsList.filter(item => item.value == this.currentValue);

        this.currentImage = currentItem[0].image;
    }

    /**
     * Get total checked items
     *
     * @returns int
     */
    getTotalCheckedItems() {
        let totalCheckedItems = 0;

        for (let value in this.checkedItems) {
            if (this.checkedItems[value]) {
                totalCheckedItems++;
            }
        }

        return totalCheckedItems;
    }
}

repo_name: dvmhmdsd/flk-dropdown-list


text:
<file_sep>package com.example.vaishnavirachapudi.savefavplacesapp;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.support.multidex.MultiDex;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import android.widget.EditText;
import android.widget.Toast;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener ,GoogleMap.OnInfoWindowLongClickListener {

    private GoogleMap mMap;
    private List<Marker> markerList = new ArrayList<>();
    Firebase myFirebaseRef;
    String address = null;
    String location=null;

    Location myLocation = null;
    Marker markers;
    String url = "https://androidhomework09.firebaseio.com/";
    Boolean Flag = false;
    Boolean ClearFavFlag=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        Firebase.setAndroidContext(this);

        myFirebaseRef = new Firebase("https://androidhomework09.firebaseio.com/");
        MultiDex.install(this);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        final EditText input = new EditText(MapsActivity.this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(input);
        builder.setMessage("Enter Address")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        address = input.getText().toString();
                        if (address == null || address.equals("")) {
                            Toast.makeText(getApplicationContext(), "Please enter address", Toast.LENGTH_LONG).show();
                        } else {
                            if (Geocoder.isPresent()) {

                                new GeoTask(MapsActivity.this).execute(address);

                            }

                        }
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        final ArrayList<Location> list = new ArrayList<Location>();

        if (myLocation == null) {
            LatLng location = new LatLng(40.73581, -73.99155);

            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 5));
        } else {

            if(ClearFavFlag==false) {
                myFirebaseRef.child("myFavPlaces").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot snapshot) {

                        HashMap<String, Object> myPlaces = (HashMap<String, Object>) snapshot.getValue();

                        int i = 1;
                        if (myPlaces != null) {
                            if (myPlaces.size() > 0) {
                                for (String key : myPlaces.keySet()) {
                                    Object value = myPlaces.get(key);

                                    if (value instanceof Object) {
                                        HashMap<String, String> map = (HashMap<String, String>) value;

                                        Location place = new Location(map.get("place"), map.get("latitude"), map.get("longitude")
                                        );
                                        System.out.println("user: " + place.toString());

                                        list.add(place);

                                    }
                                    i++;
                                }

                                if (list.size() > 0) {
                                    for (int j = 0; j < list.size(); j++) {
                                        String lat = (String) list.get(j).getLatitude();
                                        String lon = (String) list.get(j).getLongitude();
                                        String location = (String) list.get(j).getLocation();

                                        LatLng loc = new LatLng(Double.parseDouble((String) list.get(j).getLatitude()), Double.parseDouble((String) list.get(j).getLongitude()));
                                        markers = mMap.addMarker(new MarkerOptions().position(loc).title((String) list.get(j).getLocation()).snippet((String) list.get(j).getLocation()).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));

                                        markerList.add(markers);
                                        mMap.setOnInfoWindowClickListener(MapsActivity.this);
                                        mMap.setOnInfoWindowLongClickListener(MapsActivity.this);

                                    }
                                }

                            }

                        }
                    }

                    @Override
                    public void onCancelled(FirebaseError firebaseError) {

                    }
                });

            }

            LatLng pointer = new LatLng(Double.parseDouble(myLocation.getLatitude()), Double.parseDouble(myLocation.getLongitude()));
            mMap.addMarker(new MarkerOptions().position(pointer).title(myLocation.getLocation()).snippet(myLocation.getLocation()));

            if (Flag == true && markers!=null) {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();
                markerList.add(markers);
                for (Marker marker : markerList) {
                    builder.include(marker.getPosition());
                }
                LatLngBounds bounds = builder.build();
                int padding = 0; // offset from edges of the map in pixels
                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
                mMap.moveCamera(cu);
            } else if(Flag==true && markers==null && ClearFavFlag==false)
            {
                Toast.makeText(getApplicationContext(),"No Saved Places to zoom",Toast.LENGTH_LONG).show();
            }
            else if(markers==null && ClearFavFlag==true)
            {
                Toast.makeText(getApplicationContext(),"No Saved Places to be Cleared",Toast.LENGTH_LONG).show();
            }

            else if (Flag == false) {
                mMap.moveCamera(CameraUpdateFactory.newLatLng(pointer));
            }

            mMap.setOnInfoWindowClickListener(MapsActivity.this);
            mMap.setOnInfoWindowLongClickListener(MapsActivity.this);

        }

    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    @Override
    public void onInfoWindowLongClick(Marker marker) {

        marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
        Firebase locationsRef = myFirebaseRef.child("myFavPlaces");
        HashMap locations = new HashMap();
        locations.put("latitude", myLocation.getLatitude());
        locations.put("longitude", myLocation.getLongitude());
        locations.put("place", location);

        locationsRef.push().setValue(locations);

    }

    class GeoTask extends AsyncTask<String, Void, java.util.List<Address>> {
        Context mContext;

        public GeoTask(Context context) {
            this.mContext = context;
        }

        @Override
        protected List<Address> doInBackground(String... params) {
            List<Address> addressList = null;

            Geocoder geocoder = new Geocoder(mContext);

            try {
                addressList = geocoder.getFromLocationName(params[0], 10);
                if (addressList == null) {
                    Toast.makeText(MapsActivity.this, "wrong address", Toast.LENGTH_LONG).show();

                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            return addressList;
        }

        @Override
        protected void onPostExecute(List<Address> addresses) {
            if (addresses != null &&  !addresses.isEmpty()) {

                Address first = addresses.get(0);
                double lat = first.getLatitude();
                double lon = first.getLongitude();
                String lattitude = String.valueOf(lat);
                String longitude = String.valueOf(lon);

                String address = addresses.get(0).getAddressLine(0);
                String city = addresses.get(0).getAddressLine(1);
                String country = addresses.get(0).getAddressLine(3);
                String zipcode = addresses.get(0).getAddressLine(2);
                if (country == null) {
                    country = "";

                }
                if (zipcode == null) {
                    zipcode = "";
                }

                location = address + "," + city + "," + country + "," + zipcode;
                myLocation = new Location(location, lattitude, longitude);

                SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map);
                mapFragment.getMapAsync(MapsActivity.this);

            } else {

                Toast.makeText(getApplicationContext(),"Invalid Address Entered",Toast.LENGTH_LONG).show();
            }

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_bar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.action_add:

                Intent intent = new Intent(MapsActivity.this, MapsActivity.class);
                startActivity(intent);
                finish();

                return true;
            case R.id.action_clear:
                url = url + "myFavPlaces";

                myFirebaseRef = new Firebase(url);
                myFirebaseRef.removeValue();
                ClearFavFlag=true;

                mMap.clear();

                SupportMapFragment mapFragment1 = (SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map);
                mapFragment1.getMapAsync(this);

                return true;
            case R.id.action_zoom:
                Flag = true;
                SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map);
                mapFragment.getMapAsync(this);

                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}


text:
<file_sep>/* -- custom css for file timeline.html -- */

/* -- lead fw-100 -- */
#obj-19098 {
	font-size: 12px;
}

/* -- lead fw-100 -- */
#obj-48689 {
	font-size: 12px;
}

<file_sep>/* -- custom css for file chipstags.html -- */

/* -- chip -- */
#obj-57269 {
	min-height: 30px;
}

<file_sep>/* --- A place where you can add your own code -- */
<file_sep># widget-app
<file_sep>/* -- custom css for file containers.html -- */

/* -- block custom-block -- */
#obj-87469 {
	border-left-width: 1px;
	 border-left-style: solid;
	 border-left-color: rgb(179, 0, 0);
	 border-right-width: 1px;
	 border-right-style: solid;
	 border-right-color: rgb(179, 0, 0);
	 border-top-width: 1px !important;
	 border-top-style: dashed !important;
	 border-top-color: transparent !important;
	 border-bottom-width: 1px !important;
	 border-bottom-style: dashed !important;
	 border-bottom-color: transparent !important;
}

/* -- block custom-block block-strong inset -- */
#obj-89458 {
	border-top-width: 1px !important;
	 border-top-style: dashed !important;
	 border-top-color: transparent !important;
	 border-bottom-width: 1px !important;
	 border-bottom-style: dashed !important;
	 border-bottom-color: transparent !important;
}

languages: Markdown JavaScript CSS

repo_language: Markdown


text:
<repo_name>evonloch/animate<file_sep>/src/components/Box1/Box1.jsx
import React from 'react'
import { motion } from 'framer-motion'
import { useState } from 'react'

export default function Box1() {
    const [isAnimating, setIsAnimating] = useState(false)
    return (

             <motion.div
                className="box"
                style={{
                    opacity: 0.2
                }}
                drag
                whileHover={{
                    scale: 1.1
                }}
                whileTap={{
                    scale: 0.9
                }}
                animate={{
                    y: isAnimating? 300: 0,
                    opacity: isAnimating? 1 : .5,
                    rotate: isAnimating? 360 : 0

                }}
                initial={{
                    opacity: 0.1
                }}
                transition ={{
                    type: "spring",
                    stiffness: 200,
                    damping: 75
                }}

                onClick={() => setIsAnimating(!isAnimating)}
             >

             </motion.div>

    )
}<file_sep>/src/App.js
import logo from './logo.svg';
import './App.css';
import Box1 from './components/Box1/Box1';
import Box2 from './components/Box1/Box2/Box2'
function App() {
  return (

      <Box1/>
      <Box1/>

  );
}

export default App;
<file_sep>/src/components/Box1/Box2/Box2.jsx
import React from 'react'
import { motion } from 'framer-motion'
import { useState } from 'react'

export default function Box2() {

    return (

             <motion.div

             >

             </motion.div>

    )
}

repo_name: evonloch/animate


text:
<repo_name>hannahackk/hannahackk.github.io<file_sep>/README.md
# hannahackk.github.io


text:
<repo_name>frankw2/frank-website<file_sep>/_includes/bio.md
I am currently the lead security engineer at [Headway](https://headway.co/). Before this, I
was the first security engineer at [dbt Labs](https://www.getdbt.com/). In the past, I dabbled in venture capital at
[Dell Technologies Capital](https://www.delltechnologies.com/en-us/capital/ventures.htm) and academia.

I regularly write about my thoughts on security in [my Substack newsletter, Frankly Speaking](https://franklyspeaking.substack.com).

This website is from an old life where I did academia for a living.
However, I still write about cool technical ideas and occasionally publish
papers. To keep up with what's happening in my life,
you can also follow me on [Twitter](https://twitter.com/ffwang2).

I received my PhD from MIT focused on security and cryptography. I was in the
[PDOS](https://pdos.csail.mit.edu/) group,
advised by [<NAME>](https://people.csail.mit.edu/nickolai/)
and [<NAME>](https://mickens.seas.harvard.edu).
Some of my other close collaborators were
[<NAME>](https://people.csail.mit.edu/vinodv/),
[<NAME>](http://people.csail.mit.edu/shafi/),
and [<NAME>](https://cs.stanford.edu/~matei/).
Before MIT, I received my B.S. in computer science from Stanford,
advised by [<NAME>](http://crypto.stanford.edu/~dabo/).

During my PhD, to bridge the gap between academia and industry,
I co-founded [Cybersecurity Factory](https://cybersecurityfactory.com) with
[<NAME>](http://jeanyang.com), a summer program for early stage cybersecurity
startups. I also hung out with people from [Rough Draft Ventures](http://roughdraft.vc).
<file_sep>/_includes/misc.md
#### Teaching
* [6.858: Computer Systems Security](https://css.csail.mit.edu/6.858/2018/)
TA, Spring 2018

* [6.829: Computer Networks](http://web.mit.edu/6.829/www/2016/)
TA, Fall 2016

* [6.858: Computer Systems Security](http://css.csail.mit.edu/6.858/2012/)
TA, Fall 2012

* [CS 255: Introduction to Cryptography](http://crypto.stanford.edu/~dabo/courses/cs255_winter12/)
TA, Winter 2012

#### Some Fun Links

* [security too expensive?](http://www.commitstrip.com/en/2017/06/19/security-too-expensive-try-a-hack/)
* [cute dog](http://www.sanger.dk/)
* [Paris Review boring sleep reads](https://www.theparisreview.org/blog/tag/sleepy/)
* [SEC Fort Worth Twitter](https://twitter.com/FortWorth_SEC)
* [My Undergradate Research Experience](./files/papers/article.pdf)
* [alpacas](https://twitter.com/BarnacreAlpacas)
* [One Mile at a Time](http://onemileatatime.boardingarea.com/)
* [Ron Swanson by the Fire](https://www.youtube.com/watch?v=LS-ErOKpO4E)
* [The Points Guy](http://thepointsguy.com/)
* [watermelon](https://www.youtube.com/watch?v=4dAy9u0_9nM)
* [The Wirecutter](http://thewirecutter.com/)
<file_sep>/_includes/info.md
#### Info

[<EMAIL>](mailto:<EMAIL>)
[Old Academic CV](./files/cv/cv.pdf)
<!--[32-G978B, 32 Vassar Street](http://whereis.mit.edu/?go=32)  -->

LinkedIn: [frankw1](https://www.linkedin.com/in/frankw1/)
Twitter: [@ffwang2](https://twitter.com/ffwang2)
Keybase: [frankw2](https://keybase.io/frankw2)
<!-- Github: [ffwang2](https://github.com/frankw2) -->

<file_sep>/index.md
---
layout: index
---

* Our paper, Riverbed:Enforcing User-defined Privacy Constraints in Distributed Web Services, has been accepted to [NSDI 2019](https://www.usenix.org/conference/nsdi19)!
* I have finished my PhD, and I am joining [Dell Technologies Capital](https://medium.com/@ffwang2/im-joining-dell-technologies-capital-68a2c9738086) as an investor!
* Cybersecurity Factory 2018 is [underway](https://medium.com/cybersecurity-factory/announcing-teams-for-cybersecurity-factory-2018-34eed918e0d8)!
* Check out my [interview](https://www.acscenter.org/resources/cyberbytes/201711_Frank_Wang.html) with the Advanced
Cyber Security Center on security research, academia, and startups in Boston.
* My paper, [Veil: Private Browsing Semantics Without Browser-side Assistance](./files/papers/wang-veil.pdf), has been
accepted at [NDSS 2018](https://www.ndss-symposium.org/ndss2018/).
* My paper, [Cobweb: Practical Remote Attestation using Contextual Graphs](./files/papers/wang-cobweb.pdf), has been accepted
at [SysTEX 2017](https://systex17.ibr.cs.tu-bs.de/).
* My [podcast](http://pgbovine.net/PG-Podcast-30-Frank-Wang.htm) with the one and only [Phil Guo](http://pgbovine.net/) about the vital role of people in technology is online!
* Function secret sharing [library](https://github.com/frankw2/libfss) (Go and C++ versions)
from the Splinter [paper](./files/papers/wang-splinter.pdf) released!
* Check out the [video](https://www.ustream.tv/recorded/102858670) of my
talk about building cryptographically secure systems at [CRAFT](https://craft-conf.com/).
* [MIT Security Seminar](http://css.csail.mit.edu/security-seminar) has concluded
for the 2016-2017 academic year!
A summary of the talks can be found on this [blog](https://medium.com/mit-security-seminar).
* Check out the [video](https://www.usenix.org/conference/nsdi17/technical-sessions/presentation/wang-frank)
of my talk at NSDI on my paper, [Splinter: Practical Private Queries on Public Data](./files/papers/wang-splinter.pdf).
* I am talking about research, cybersecurity startups, etc. on [Startup Security Weekly](https://securityweekly.com/2017/03/14/frank-wang-cybersecurity-factory-startup-security-weekly-29/)!
<file_sep>/deploy_site.sh
bundle exec jekyll build
rsync -rzh _site/* <EMAIL>:/usr/share/nginx/html
git commit -a -m "site updated"
git push
<file_sep>/files/cv/cv.tex
\documentclass[a4paper,10pt]{article}
\usepackage{hyperref,fancyhdr,enumitem,color}
\usepackage[a4paper,text={7in,10in}]{geometry}
\usepackage{pslatex}
\usepackage{longtable}

\begin{document}

\setlength\LTleft{0.2in}
\setlength\LTright{1in plus \fill}

\begin{center}
\textbf{\large{<NAME>}}
\end{center}

\begin{tabular*}{0.95 \textwidth} { l l @{\extracolsep{\fill}} r}
<EMAIL> & & https://frankwang.org\\
(408) 893-1709 & & \\ \\
\textbf{Education} & Massachusetts Institute of Technology & Sept 2012 - July 2018\\
 & Ph.D. in Computer Science & \\
 & Advised by Prof. <NAME> and Prof. <NAME> & \\
 & Thesis Title: Preventing Data Leakage in Web Services \\
 \\
 & Stanford University & Sept 2008 - June 2012 \\
 & B.S. in Computer Science with Honors and Minor in Mathematics & \\
 & Advised by Prof. <NAME> & \\
 & Thesis Title: Offloading Critical Security Operations to the GPU &\\ \\
\end{tabular*}

\begin{longtable}{ p{0.9in} l }
%\textbf{Interests} & Computer Security and Privacy, Systems, and Applied Cryptography \\ \\
%\textbf{Research Projects} & \begin{minipage}[t]{0.78 \columnwidth}
%\textbf{Cryptographically Enforced Access Control for User Data in
%Untrusted Clouds}. \\ Sieve is a new platform which
%selectively (and securely) exposes user data to web services.
%Sieve has a user-centric storage model: each user
%uploads encrypted data to a single cloud store, and by
%default, only the user knows the decryption keys. Given
%this storage model, Sieve defines an infrastructure to support
%rich, legacy web applications. Using attribute-based
%encryption, Sieve allows users to define intuitively understandable
%access policies that are cryptographically
%enforceable. Using key homomorphism, Sieve can re-encrypt
%user data on storage providers in situ, revoking
%decryption keys from web services without revealing new
%keys to the storage provider. Using secret sharing and
%two-factor authentication, Sieve protects cryptographic
%secrets against the loss of user devices like smartphones
%and laptops. The result is that users can enjoy rich, legacy
%web applications, while benefiting from cryptographically
%strong controls over which data a web service can access. \\
%\end{minipage} \tabularnewline

\textbf{Publications} & \begin{minipage}[t]{0.78 \textwidth}
\begin{enumerate}[leftmargin=*]
\setlength{\itemsep}{7pt}
                \setlength{\parskip}{0pt}
                \setlength{\parsep}{0pt}

\item{\textbf{<NAME>}, <NAME>, and <NAME>. ``Riverbed: Enforcing User-defined Privacy Constraints in Distributed Web Services." In \textit{Proceedings of Networked Systems Design and Implementation (NSDI)} 2019.}

\item{\textbf{<NAME>}, <NAME>, and <NAME>. ``Veil: Private Browsing Semantics Without Browser-side Assistance." In \textit{Proceedings of Network and Distributed System Security Symposium (NDSS)} 2018.}

\item{\textbf{<NAME>}, <NAME>, and <NAME>. ``Cobweb: Practical Remote Attestation using Contextual Graphs." In \textit{Proceedings of Workshop on System Software for Trusted Execution (SysTEX)} 2017.}

\item{\textbf{<NAME>}, <NAME>, <NAME>, <NAME>, and <NAME>. ``Splinter: Practical Private Queries on Public Data." In \textit{Proceedings of Networked Systems Design and Implementation (NSDI)} 2017.}

\item{\textbf{<NAME>}, <NAME>, <NAME>, and  <NAME>. ``Sieve: Cryptographically Enforced Access Control for User Data in Untrusted Clouds." In \textit{Proceedings of Networked Systems Design and Implementation (NSDI)} 2016.}

\item{<NAME>, <NAME>, <NAME>, \textbf{<NAME>}, and <NAME>. ``Private database queries using Somewhat Homomorphic Encryption." \textit{In Proceedings of Applied Cryptography and Network Security (ACNS)} 2013.}

\item{<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, \textbf{<NAME>}, and <NAME>. ``StegoTorus: a camouflage proxy for the Tor anonymity system." In \textit{Proceedings of ACM Conference on Computer and Communications Security (CCS)} 2012.}

\item{<NAME>, <NAME>, <NAME>, <NAME>, and \textbf{<NAME>}. ``Declarative privacy policy: Finite models and Attribute-Based Encryption." In \textit{Proceedings of 2nd ACM International Health Informatics Symposium} 2012.}

\item{<NAME> and \textbf{<NAME>}. ``Theoretical analysis of the effect of particle size and support on the kinetics of oxygen reduction reaction on platinum nanoparticles." Nanoscale, 2012, 4(16), 5110-5117.}

\item{<NAME>, \textbf{<NAME>}, and <NAME>. ``Dynamic Monte-Carlo based approach for simulating nanostructured catalytic and electrocatalytic systems." Computing in Science and Engineering, 2012, 14(2), 60-68.}

\end{enumerate}
\end{minipage} \tabularnewline

\end{longtable}

\begin{longtable}{ p{0.9in} l @{\extracolsep{\fill}} r}

\textbf{Invited Talks} & CRAFT Conf & Apr 2017 \\
& \begin{minipage}[t]{0.6 \textwidth}
\textit{Building Cryptographically Secure Web Application Systems} \end{minipage} & \\ \\
& University of Pennsylvania Security Seminar & Mar 2017 \\
& \begin{minipage}[t]{0.6 \textwidth}
\textit{Splinter: Practical Private Queries on Public Data} \end{minipage} & \\ \\
& University of Waterloo CrySP Seminar & Jan 2017 \\
& \begin{minipage}[t]{0.6 \textwidth}
\textit{Sieve: Cryptographically Enforced Access Control for User Data in Untrusted Clouds} \end{minipage} & \\ \\
& Georgia Institute of Technology Cybersecurity Lecture Series & Sept 2016 \\
& \begin{minipage}[t]{0.6 \textwidth}
\textit{Sieve: Cryptographically Enforced Access Control for User Data in Untrusted Clouds} \end{minipage} & \\ \\
& University of Washington Computer Science Seminar& Aug 2016 \\
& \begin{minipage}[t]{0.6 \textwidth}
\textit{Sieve: Cryptographically Enforced Access Control for User Data in Untrusted Clouds} \end{minipage} & \\ \\
& Curry-On 2016 & July 2016 \\
& \begin{minipage}[t]{0.6 \textwidth}
\textit{Sieve: Cryptographically Enforced Access Control for User Data in Untrusted Clouds} \end{minipage} & \\ \\

\textbf{External} & 2016 IEEE S\&P, 2016 ACM CCS & \\
\textbf{Reviewer} & & \\ \\

\textbf{Teaching}
& Teaching Assistant for MIT Computer Networks (6.829) & Fall 2016 \\
& Teaching Assistant for MIT Computer Systems Security (6.858) & Fall 2012 \\
& Teaching Assistant for Stanford Introduction to Cryptography (CS 255) & Winter 2012 \\ \\

\textbf{Other} & \textbf{Recurse Center}, Resident & May 2016, June 2015 \\
\textbf{Teaching} & \begin{minipage}[t]{0.5 \textwidth}
Held security and cryptography seminars. Mentored programmers
in security, cryptography, and systems.
\end{minipage} \\ \\

 & \textbf{CMU Coursera Class}, Online Course Assistant & 2014 - Current\\
 & Statistical Thermodynamics: Molecules to Machines & \\ \\

\textbf{Awards} & \textbf{NSF Graduate Research Fellowship} & Sept 2013 - Sept 2016\\
& \textbf{Jacobs Presidential Fellowship} & Sept 2012 - June 2013\\
& Massachusetts Institute of Technology \\
\\

\textbf{Industry}  & \textbf{Facebook}, Security Engineer Research Intern & June - Aug 2013 \\
\textbf{Experience} & \begin{minipage}[t]{0.5 \textwidth}
Designing and building infrastructure for intrusion detection.
\end{minipage}
& \\ \\
& \textbf{Google}, Software Engineering Intern & June - Aug 2012 \\
& \begin{minipage}[t]{0.5 \textwidth}
Chrome security research project for Security Research Team under mentorship of <NAME> and <NAME>.
\end{minipage}
& \\ \\

\textbf{Other}   & \textbf{Cybersecurity Factory}, Co-founder & 2015 - Current \\
\textbf{Experience}
  & \begin{minipage}[t]{0.5 \textwidth}
  Summer program that provides mentorship and capital to early stage
  cybersecurity companies.
  \end{minipage} & \\ \\
  & \textbf{Sidney Pacific}, Board of Trustees & May 2015 - Current \\
    & \begin{minipage}[t]{0.5 \textwidth}
  Advise new officers, administer elections, and deal with major issues.
  \end{minipage} & \\ \\
  & \textbf{Rough Draft Ventures}, Venture Fellow & 2014 - 2017 \\
  & \begin{minipage}[t]{0.5 \textwidth}
  Investment fund that invests in Boston early student startups.
  \end{minipage} & \\ \\
  & \textbf{<NAME>}, Web Chair & Sept 2012 - May 2015 \\
 & \begin{minipage}[t]{0.5 \textwidth}
Maintain website and create new features.
\end{minipage}
& \\ \\
\end{longtable}

\end{document}
<file_sep>/_includes/profact.md
#### Professional Activities

I enjoy collaborating closely and interacting frequently
with industry.

To bridge the gap between industry and academia,
I co-founded [Cybersecurity Factory](https://cybersecurityfactory.com)
with [<NAME>](http://jeanyang.com/), a summer program for early
stage cybersecurity startups where I help startups with business
and product development. Through this program, I regularly interact
with security executives at both early-stage and established
companies to identify and address future security needs.

If you are an early stage enterprise startup, I would love to chat!

I am also a member of
[Rough Draft Ventures](http://roughdraft.vc) that funds student founders.
In the past, I've also worked on the security teams at Google and Facebook.

languages: Markdown TeX Shell