text:
Core Committer Guide
====================

Vision and Scope
-----------------

Core committers, use this section to:

* Guide your instinct and decisions as a core committer
* Limit the codebase from growing infinitely

Command-Line Accessible
~~~~~~~~~~~~~~~~~~~~~~~

* Provides a command-line utility that creates projects from cookiecutters
* Extremely easy to use without having to think too hard
* Flexible for more complex use via optional arguments

API Accessible
~~~~~~~~~~~~~~

* Entirely function-based and stateless (Class-free by intentional design)
* Usable in pieces for developers of template generation tools

Being Jinja2-specific
~~~~~~~~~~~~~~~~~~~~~

* Sets a standard baseline for project template creators, facilitating reuse
* Minimizes the learning curve for those who already use Flask or Django
* Minimizes scope of Cookiecutter codebase

Extensible
~~~~~~~~~~

Being extendable by people with different ideas for Jinja2-based project template tools.

* Entirely function-based
* Aim for statelessness
* Lets anyone write more opinionated tools

Freedom for Cookiecutter users to build and extend.

* No officially-maintained cookiecutter templates, only ones by individuals
* Commercial project-friendly licensing, allowing for private cookiecutters and private Cookiecutter-based tools

Fast and Focused
~~~~~~~~~~~~~~~~

Cookiecutter is designed to do one thing, and do that one thing very well.

* Cover the use cases that @audreyr needs, and as little as possible beyond that :)
* Generates project templates from the command-line or API, nothing more
* Minimize internal line of code (LOC) count
* Ultra-fast project generation for high performance downstream tools

Inclusive
~~~~~~~~~

* Cross-platform and cross-version support are more important than features/functionality
* Fixing Windows bugs even if it's a pain, to allow for use by more beginner coders

Stable
~~~~~~

* Aim for 100% test coverage and covering corner cases
* No pull requests will be accepted that drop test coverage on any platform, including Windows
* Conservative decisions patterned after CPython's conservative decisions with stability in mind
* Stable APIs that tool builders can rely on
* New features require a +1 from @audreyr

VCS-Hosted Templates
~~~~~~~~~~~~~~~~~~~~~

Cookiecutter project templates are intentionally hosted VCS repos as-is.

* They are easily forkable
* It's easy for users to browse forks and files
* They are searchable via standard Github/Bitbucket/other search interface
* Minimizes the need for packaging-related cruft files
* Easy to create a public project template and host it for free
* Easy to collaborate

Process: Pull Requests
------------------------

If a pull request is untriaged:

* Look at the roadmap
* Set it for the milestone where it makes the most sense
* Add it to the roadmap

How to prioritize pull requests, from most to least important:

#. Fixes for broken tests. Broken means broken on any supported platform or Python version.
#. Extra tests to cover corner cases.
#. Minor edits to docs.
#. Bug fixes.
#. Major edits to docs.
#. Features.

Ensure that each pull request meets all requirements in this checklist:
https://gist.github.com/audreyr/4feef90445b9680475f2

Process: Issues
----------------

If an issue is a bug that needs an urgent fix, mark it for the next patch release.
Then either fix it or mark as please-help.

For other issues: encourage friendly discussion, moderate debate, offer your thoughts.

New features require a +1 from @audreyr.

Process: Roadmap
-----------------

The roadmap is https://github.com/audreyr/cookiecutter/milestones?direction=desc&sort=due_date&state=open

Due dates are flexible. Core committers can change them as needed. Note that GitHub sort on them is buggy.

How to number milestones:

* Follow semantic versioning. See http://semver.org

Milestone size:

* If a milestone contains too much, move some to the next milestone.
* Err on the side of more frequent patch releases.

Process: Generating CONTRIBUTING.rst
-------------------------------------

From the `cookiecutter` project root::

    $ make contributing

This will generate the following message::

    rm CONTRIBUTING.rst
    touch CONTRIBUTING.rst
    cat docs/contributing.rst >> CONTRIBUTING.rst
    echo "\r\r" >> CONTRIBUTING.rst
    cat docs/types_of_contributions.rst >> CONTRIBUTING.rst
    echo "\r\r" >> CONTRIBUTING.rst
    cat docs/contributor_setup.rst >> CONTRIBUTING.rst
    echo "\r\r" >> CONTRIBUTING.rst
    cat docs/contributor_guidelines.rst >> CONTRIBUTING.rst
    echo "\r\r" >> CONTRIBUTING.rst
    cat docs/contributor_tips.rst >> CONTRIBUTING.rst
    echo "\r\r" >> CONTRIBUTING.rst
    cat docs/core_committer_guide.rst >> CONTRIBUTING.rst
    echo "\r\rAutogenerated from the docs via \`make contributing\`" >> CONTRIBUTING.rst
    echo "WARNING: Don't forget to replace any :ref: statements with literal names"
    WARNING: Don't forget to replace any :ref: statements with literal names

Responsibilities
-----------------

#. Give priority to bug fixes over new features. This includes fixes for the Windows tests that broke at some point.
#. Ensure cross-platform compatibility for every change that's accepted. Windows, Mac, Debian & Ubuntu Linux.
#. Ensure that code that goes into core meets all requirements in this checklist: https://gist.github.com/audreyr/4feef90445b9680475f2
#. Create issues for any major changes and enhancements that you wish to make. Discuss things transparently and get community feedback.
#. Don't add any classes to the codebase unless absolutely needed. Err on the side of using functions.
#. Be welcoming to newcomers and encourage diverse new contributors from all backgrounds. See the Python Community Code of Conduct (https://www.python.org/psf/codeofconduct/).

Becoming a Core Committer
--------------------------

Contributors may be given core commit privileges. Preference will be given to those with:

A. Past contributions to Cookiecutter and other open-source projects. Contributions to Cookiecutter include both code (both accepted and pending) and friendly participation in the issue tracker. Quantity and quality are considered.
B. A coding style that @audreyr finds simple, minimal, and clean.
C. Access to resources for cross-platform development and testing.
D. Time to devote to the project regularly.


text:
package org.iq80.leveldb.impl;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import org.iq80.leveldb.WriteBatch;
import org.iq80.leveldb.util.Slice;
import org.iq80.leveldb.util.Slices;

import java.util.List;
import java.util.Map.Entry;

import static com.google.common.collect.Lists.newArrayList;

public class WriteBatchImpl implements WriteBatch
{
    private List<Entry<Slice, Slice>> batch = newArrayList();
    private int approximateSize;

    public int getApproximateSize()
    {
        return approximateSize;
    }

    public int size()
    {
        return batch.size();
    }

    @Override
    public WriteBatchImpl put(byte[] key, byte[] value)
    {
        Preconditions.checkNotNull(key, "key is null");
        Preconditions.checkNotNull(value, "value is null");
        batch.add(Maps.immutableEntry(Slices.wrappedBuffer(key), Slices.wrappedBuffer(value)));
        approximateSize += 12 + key.length + value.length;
        return this;
    }

    public WriteBatchImpl put(Slice key, Slice value)
    {
        Preconditions.checkNotNull(key, "key is null");
        Preconditions.checkNotNull(value, "value is null");
        batch.add(Maps.immutableEntry(key, value));
        approximateSize += 12 + key.length() + value.length();
        return this;
    }

    @Override
    public WriteBatchImpl delete(byte[] key)
    {
        Preconditions.checkNotNull(key, "key is null");
        batch.add(Maps.immutableEntry(Slices.wrappedBuffer(key), (Slice) null));
        approximateSize += 6 + key.length;
        return this;
    }

    public WriteBatchImpl delete(Slice key)
    {
        Preconditions.checkNotNull(key, "key is null");
        batch.add(Maps.immutableEntry(key, (Slice) null));
        approximateSize += 6 + key.length();
        return this;
    }

    @Override
    public void close()
    {
    }

    public void forEach(Handler handler)
    {
        for (Entry<Slice, Slice> entry : batch) {
            Slice key = entry.getKey();
            Slice value = entry.getValue();
            if (value != null) {
                handler.put(key, value);
            }
            else {
                handler.delete(key);
            }
        }
    }

    public static interface Handler
    {
        void put(Slice key, Slice value);

        void delete(Slice key);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package foo.bar.example.foreadapters.ui.playlist;

import androidx.fragment.app.FragmentActivity;

import foo.bar.example.foreadapters.R;

public class PlaylistsActivity extends FragmentActivity {
    public PlaylistsActivity() {
        super(R.layout.activity_playlists);
    }
}


text:
define(function (require, exports, module) {
    "use strict";

    var derive = require("base/derive");
    var slice = require("base/slice");
    var EventTarget = require("boost/EventTarget");
    var tagMap = require("boost/tagMap");
    var bridge = require("boost/bridge");

    var NativeObject = derive(EventTarget, function (tag) {
        var origObj;

        //this._super();
        EventTarget.call(this);
        if (tag === undefined) {
            tag = tagMap.genTag();
        }

        origObj = tagMap.get(tag);
        if (origObj !== null && origObj instanceof NativeObject) {
            origObj.destroy();
        }

        tagMap.set(tag, this);
        this.__tag__ = tag;
    }, {
        "get tag": function () {
            return this.__tag__;
        },

        __callNative: function (method, args) {
            bridge.call(this.__tag__, method, args);
        },

        __onEvent: function (type, event) {
            //do nothing
        },

        destroy: function () {
            nativeGlobal.destroyObject(this.__tag__);
        }
    });

    NativeObject.bindNative = function (method) {
        return function () {
            this.__callNative(method, slice(arguments));
        };
    };

    var GLOBAL_TAG = null;
    var NativeGlobalObject = derive(NativeObject, function () {
        //this._super(GLOBAL_TAG);
        NativeObject.call(this, GLOBAL_TAG);
    }, {
        createView: NativeObject.bindNative("createView"),
        updateView: NativeObject.bindNative("updateView"),
        addView: NativeObject.bindNative("addView"),
        removeView: NativeObject.bindNative("removeView"),
        removeAllViews: NativeObject.bindNative("removeAllViews"),
        createAnimation: NativeObject.bindNative("createAnimation"),
        startAnimation: NativeObject.bindNative("startAnimation"),
        cancelAnimation: NativeObject.bindNative("cancelAnimation"),
        //FOR TEST
        test: NativeObject.bindNative("test"),

        //__destroy: NativeObject.bindNative("destroy"),
        destroyObject: function (tag) {
            this.__destroy(tag);
        }
    });

    var nativeGlobal = new NativeGlobalObject();
    NativeObject.global = nativeGlobal;

    NativeObject.getByTag = function (tag) {
        var obj = tagMap.get(tag);
        if (obj !== null && obj instanceof NativeObject) {
            return obj;
        }
        return null;
    };

    // 监听统一的 boost 事件
    document.addEventListener("boost", function (e) {
        var origin = e.origin;
        var target = NativeObject.getByTag(origin);
        var type = e.boostEventType.toLowerCase();
        //console.log("origin:" + origin, "type:" + type, e);
        if (target) {
            // 这里为了提高效率,就不用 dispatchEvent 那一套了。
            target.__onEvent(type, e);
        } else if (type === "boosterror") {
            console.error(e.stack);
            //TODO 构建错误显示界面
            //throw new NativeError(e.stack);
        }
    }, false);

    // 页面卸载时,删除所有的 NativeView
    window.addEventListener("unload", function (e) {
        nativeGlobal.removeAllViews();
        bridge.flush();
    });

    // 页面加载时,先尝试删除所有 NativeView
    nativeGlobal.removeAllViews();

    module.exports = NativeObject;
});


text:
import { Component, OnInit } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { DecimalPipe, SlicePipe } from '@angular/common';

import { MdDialog } from '@angular/material';
import { Ng2SmartTableModule, LocalDataSource } from 'ng2-smart-table';

import { ConfirmDialogComponent } from '../../components/confirm-dialog/confirm-dialog.component';

import { ValidateService } from '../../services/validate.service';
import { FormatterService } from '../../services/formatter.service';
import { MessageGrowlService } from '../../services/message-growl.service';
import { KardexService } from '../../services/kardex.service';
import { CiudadService } from '../../services/ciudad.service';
import { ComprasService } from '../../services/compras.service';
import { ProveedorService } from '../../services/proveedor.service';
import { ProductoService } from '../../services/producto.service';
import { TipoProductoService } from '../../services/tipo-producto.service';

import { Proveedor } from '../../models/proveedor';
import { Producto } from '../../models/producto';

import { IconRenderComponent } from '../image-render/icon-render.component';
import { PipeRenderComponent } from '../pipe-render/pipe-render.component';
import { ImageRenderComponent } from '../image-render/image-render.component';

import { UM } from '../globals';

@Component({
  selector: 'app-compras',
  templateUrl: './compras.component.html',
  styleUrls: ['./compras.component.css']
})
export class ComprasComponent implements OnInit {

  es: any;
  selectedUmMat: any;
  selectedUmMat1: any;
  selected_tipo_producto: any;
  lstUnidadMedida: any = [];
  lstUnidadMedida1: any = [];

  constructor(
    private validateService: ValidateService,
    private http: Http,
    private messageGrowlService: MessageGrowlService,
    private fs: FormatterService,
    private decimalPipe: DecimalPipe,
    private slicePipe: SlicePipe,
    private kardexService: KardexService,
    private ciudadService: CiudadService,
    private comprasService: ComprasService,
    private proveedorService: ProveedorService,
    private productoService: ProductoService,
    private dialog: MdDialog,
    private tipoProductoService: TipoProductoService) {
    this.es = {
      firstDayOfWeek: 1,
      dayNames: ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"],
      dayNamesShort: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],
      dayNamesMin: ["D", "L", "M", "X", "J", "V", "S"],
      monthNames: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
      monthNamesShort: ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"],
      today: 'Hoy',
      clear: 'Borrar'
    }
    this.lstUnidadMedida = [];
    this.lstUnidadMedida.push({ label: 'Masa', value: 0 });
    this.lstUnidadMedida.push({ label: 'Volumen', value: 1 });
    this.lstUnidadMedida.push({ label: 'Unidades', value: 2 });
    this.selectedUmMat = this.lstUnidadMedida[0];
    this.lstUnidadMedida1 = [];
    this.lstUnidadMedida1.push({ label: 'Gramos', value: 0 });
    this.lstUnidadMedida1.push({ label: 'Onza', value: 1 });
    this.lstUnidadMedida1.push({ label: 'Libras', value: 2 });
    this.lstUnidadMedida1.push({ label: 'Kilogramos', value: 3 });
    this.selectedUmMat1 = this.lstUnidadMedida1[0];
  }

  ngOnInit() {
    this.ngOnInitProve();
    this.ngOnInitCompras();
    //this.notifyMe();
  }

  notifyMe() {
    Notification.requestPermission(function (permission) {
      // Si el usuario acepta, lanzamos la notificación
      if (permission === "granted") {
        var notification = new Notification("Bienvenido..!!")
      }
    });
  }

  onChangeUmMat($event) {
    if (this.selectedUmMat.value === 0) {
      this.flagUnits = true;
      this.lstUnidadMedida1 = [];
      this.lstUnidadMedida1.push({ label: 'Gramos', value: 0 });
      this.lstUnidadMedida1.push({ label: 'Onza', value: 1 });
      this.lstUnidadMedida1.push({ label: 'Libras', value: 2 });
      this.lstUnidadMedida1.push({ label: 'Kilogramos', value: 3 });
      this.selectedUmMat1 = this.lstUnidadMedida1[0];
    }
    if (this.selectedUmMat.value === 1) {
      this.flagUnits = true;
      this.lstUnidadMedida1 = [];
      this.lstUnidadMedida1.push({ label: 'Mililitros', value: 0 });
      this.lstUnidadMedida1.push({ label: 'Onza Liquida', value: 1 });
      this.lstUnidadMedida1.push({ label: 'Litros', value: 2 });
      this.selectedUmMat1 = this.lstUnidadMedida1[0];
    }
    if (this.selectedUmMat.value === 2) {
      this.flagUnits = false;
      this.lstUnidadMedida1 = [];
    }
  }

  /*GESTION PROVEEDOR*/
  settingsProve = {};
  sourceProve: LocalDataSource = new LocalDataSource();
  showDialogProve = true;
  showDialogProveU = false;
  objProve: Proveedor;
  showRepresentante = false;
  representante = {
    nombre: '',
    telefono: '',
    correo: '',
    descripcion: '',
    value: ''
  }
  filteredCiudades: any[];
  citiesEcu: any[];
  ciudad: string;
  lstProveedores: any[];
  showProveDialog;
  showComprasDetail = false;

  filterCiudad(event) {
    let query = event.query;
    this.filteredCiudades = this.filterCiudadS(query, this.citiesEcu);
  }

  filterCiudadS(query, countries: any[]): any[] {
    let filtered: any[] = [];
    for (let i = 0; i < countries.length; i++) {
      let country = countries[i];
      if (country.nombre.toLowerCase().indexOf(query.toLowerCase()) == 0) {
        filtered.push(country);
      }
    }
    return filtered;
  }

  onChangeNombreProve($event) {
    this.objProve.nombre_proveedor = this.fs.toTitleCase(this.objProve.nombre_proveedor);
  }

  validCorreo = true;
  onChangeEmail($event) {
    this.objProve.correo = this.objProve.correo.toLocaleLowerCase();
    if (this.validateService.validateEmail(this.objProve.correo)) {
      this.messageGrowlService.notify('success', 'Éxito', 'Correo válido!');
      document.getElementById("correo").style.borderLeft = "5px solid #42A948"; /* green */
      this.validCorreo = false;
    }
    else {
      document.getElementById("correo").style.borderLeft = "5px solid #a94442"; /* red */
      this.validCorreo = true;
    }
  }

  onChangeEmailU($event) {
    this.objProve.correo = this.objProve.correo.toLocaleLowerCase();
    if (this.validateService.validateEmail(this.objProve.correo)) {
      this.messageGrowlService.notify('success', 'Éxito', 'Correo válido!');
      document.getElementById("correoU").style.borderLeft = "5px solid #42A948"; /* green */
      this.validCorreo = false;
    }
    else {
      document.getElementById("correoU").style.borderLeft = "5px solid #a94442"; /* red */
      this.validCorreo = true;
    }
  }

  validRuc = true;
  onChangeRuc() {
    if (this.objProve.ruc.length != 13) {
      document.getElementById("rucProve").style.borderLeft = "5px solid #a94442"; /* red */
      this.validRuc = true;
    } else {
      if (!this.validateService.validarRucCedula(this.objProve.ruc)) {
        this.messageGrowlService.notify('error', 'Error', 'Ruc inválido!');
        document.getElementById("rucProve").style.borderLeft = "5px solid #a94442"; /* red */
        this.validRuc = true;
      } else {
        this.messageGrowlService.notify('success', 'Éxito', 'Ruc válido!');
        document.getElementById("rucProve").style.borderLeft = "5px solid #42A948"; /* green */
        this.validRuc = false;
      }
    }
  }

  onChangeRucU() {
    if (this.objProve.ruc.length != 13) {
      document.getElementById("rucProveU").style.borderLeft = "5px solid #a94442"; /* red */
      this.validRuc = true;
    } else {
      if (!this.validateService.validarRucCedula(this.objProve.ruc)) {
        this.messageGrowlService.notify('error', 'Error', 'Cedula Inválida!');
        document.getElementById("rucProveU").style.borderLeft = "5px solid #a94442"; /* red */
        this.validRuc = true;
      } else {
        this.messageGrowlService.notify('success', 'Éxito', 'Ruc válido!');
        document.getElementById("rucProveU").style.borderLeft = "5px solid #42A948"; /* green */
        this.validRuc = false;
      }
    }
  }

  onChangeCiudad($event) {
    this.objProve.ciudad = this.fs.toTitleCase(this.objProve.ciudad);
  }

  setCursorAddProve() {
    setTimeout(function () {
      document.getElementById('nombreProve').focus();
      setOriginalColorsProve();
      //document.getElementById('telProve').autocomplete = "off";
    }, 0);
    this.setDefaultProve(1);
  }

  check() {
    console.log(JSON.parse(localStorage.getItem('lstProveedor')));
    console.log(this.lstProveedores);
  }

  saveProveedor() {
    this.proveedorService.register(this.objProve).subscribe(data => {
      this.lstProveedores.push(data);
      this.sourceProve.refresh();
      this.setDefaultProve(1);
      this.showDialogProve = false;
      localStorage.setItem('lstProveedor', JSON.stringify(this.lstProveedores));
      this.messageGrowlService.notify('success', 'Existo', 'Ingreso Existoso!');
    }, err => {
      console.log(err);
      this.messageGrowlService.notify('warn', 'Advertencia', 'Algo salió mal!');
    });
  }

  showProveedor(event: any) {
    this.showProveDialog = event.data.nombre_proveedor;
    this.showComprasDetail = true;
  }

  setCursorUpdateProve(event: any) {
    setTimeout(function () {
      document.getElementById('nombreProveU').focus();
      document.getElementById("rucProveU").style.borderLeft = "5px solid #42A948"; /* green */
      document.getElementById("correoU").style.borderLeft = "5px solid #42A948"; /* green */
    }, 0);
    let lst = JSON.parse(localStorage.getItem('lstProveedor'));
    let prov = lst.filter(function (obj) {
      return obj._id.localeCompare(event.data._id) === 0;
    });
    this.objProve = prov[0];
    this.validCorreo = false;
    this.validRuc = false;
  }
  provUpdt: Proveedor;
  searchOldProve(id) {
    let lst = JSON.parse(localStorage.getItem('lstProveedor'));
    this.provUpdt = lst.filter(function (obj) {
      return obj._id.localeCompare(id) === 0;
    });
  }

  updateProveedor() {
    this.proveedorService.update(this.objProve).subscribe(data => {
      this.searchOldProve(data._id);
      this.updateFromLocalStorage(this.objProve);
      this.sourceProve.refresh();
      this.setDefaultProve(2);
      this.showDialogProveU = false;
      this.messageGrowlService.notify('info', 'Información', 'Modificación Existosa!');
    }, err => {
      console.log(err);
      this.messageGrowlService.notify('warn', 'Advertencia', 'Algo salió mal!');
    });
  }

  onDeleteProve(event): void {
    this.openDialogProve(event.data);
  }

  openDialogProve(data) {
    const dialogRef = this.dialog.open(ConfirmDialogComponent);
    dialogRef.afterClosed().subscribe(result => {
      if (result !== undefined) {
        if (result.localeCompare('Aceptar') === 0) {
          this.sourceProve.remove(data);
          this.deleteFromLocalStorage(data);
          // remove from database
          this.proveedorService.delete(data._id).subscribe(dataD => {
            this.messageGrowlService.notify('warn', 'Advertencia', 'Registro eliminado!');
          }, err => {
            console.log(err);
            this.messageGrowlService.notify('error', 'Error', 'Algo salió mal!!');
          });
        }
      }
    });
  }

  setDefaultProve(op) {
    this.objProve = {
      nombre_proveedor: '',
      ruc: '',
      direccion: '',
      ciudad: undefined,
      telefono: '',
      correo: '',
      comprasV: [],
      representanteV: []
    };
    this.validRuc = true;
    this.validCorreo = true;
    if (op = 1) {
      setOriginalColorsProve();
    } else {
      setOriginalColorsProveU();
    }

  }

  deleteFromLocalStorage(element) {
    this.lstProveedores = this.lstProveedores.filter(function (el) {
      return el._id !== element._id
    });
    localStorage.setItem('lstProveedor', JSON.stringify(this.lstProveedores));
  }

  updateFromLocalStorage(data) {
    for (var i in this.lstProveedores) {
      if (this.lstProveedores[i]._id == data._id) {
        this.lstProveedores[i] = data;
        break;
      }
    }
    localStorage.setItem('lstProveedor', JSON.stringify(this.lstProveedores));
  }

  //Representante Proveedor
  showRepre() {
    this.showRepresentante = true;
    setTimeout(function () {
      document.getElementById('nombreRepre').focus();
      setOriginalColorsRepre();
    }, 0);
    this.setDefaultRepre();
  }

  onChangeNombreRepre($event) {
    this.representante.nombre = this.representante.nombre.trim();
    this.representante.nombre = this.fs.toTitleCase(this.representante.nombre);
  }

  flagEmailRepre = true;
  onChangeEmailRepre($event) {
    this.representante.correo = this.representante.correo.toLocaleLowerCase();
    if (this.validateService.validateEmail(this.representante.correo)) {
      this.messageGrowlService.notify('success', 'Éxito', 'Correo válido!');
      document.getElementById("correoRepre").style.borderLeft = "5px solid #42A948"; /* green */
      this.flagEmailRepre = false;
    }
    else {
      document.getElementById("correoRepre").style.borderLeft = "5px solid #a94442"; /* red */
      this.flagEmailRepre = true;
    }
  }

  onChangeDescRepre($event) {
    this.representante.descripcion = this.representante.descripcion.trim();
  }

  addRepre() {
    this.representante.value = this.representante.nombre;
    this.objProve.representanteV = [...this.objProve.representanteV, this.representante];

    this.showRepresentante = false;
    this.representante = {
      nombre: '',
      telefono: '',
      correo: '',
      descripcion: '',
      value: ''
    }
    document.getElementById("correoRepre").style.borderLeft = "5px solid #a94442"; /* red */
    this.flagEmailRepre = true;
  }

  selectedRepre: any;
  deleteRepre(i) {
    this.objProve.representanteV.splice(i, 1);
  }

  setDefaultRepre() {
    this.representante = {
      nombre: '',
      telefono: '',
      correo: '',
      descripcion: '',
      value: ''
    };
    this.flagEmailRepre = true;
    setOriginalColorsRepre();
  }

  ngOnInitProve() {
    this.objProve = {
      nombre_proveedor: '',
      ruc: '',
      direccion: '',
      ciudad: undefined,
      telefono: '',
      correo: '',
      comprasV: [],
      representanteV: []
    };
    this.validRuc = true;
    this.showDialogProve = false;
    this.showDialogProveU = false;
    /* Get Ciudades */
    this.ciudadService.getAll().subscribe(countries => {
      this.citiesEcu = countries;
    });
    /* Get Proveedores*/
    /*this.proveedorService.getAll().subscribe(data => {

      if (this.lstProveedoresK.length > 0) {
        this.kardex.proveedor = this.lstProveedoresK[0];
      }

      this.kardexService.getAll().subscribe(data => {
        this.lstKardex = data
        let i = 0;
        for (const x of data) {
          const desc = this.searchDescProve(x.proveedor, this.lstProveedoresK);
          this.lstKardex[i].proveedor = desc;
          const desc1 = this.searchDescProd(x.desc_producto, this.productos);
          this.lstKardex[i].desc_producto = desc1;
          i++;
        }
        localStorage.setItem('lstKardex', JSON.stringify(this.lstKardex));
        this.sourceK = new LocalDataSource();
        this.sourceK.load(this.lstKardex);
        this.settingsK = {
          mode: 'external',
          noDataMessage: 'No existen registros',
          columns: {
            num_factura: {
              title: 'Número Factura',
              width: '14%'
            },
            fecha: {
              title: 'Fecha',
              width: '15%'
            },
            desc_producto: {
              title: 'Descripción Producto',
              width: '22%'
            },
            proveedor: {
              title: 'Proveedor',
              width: '22%'
            },
            cantidad: {
              title: 'Unidades',
              width: '9%'
            },
            total: {
              title: 'Total',
              width: '9%'
            },
            unidades_vendidas: {
              title: 'Unidades Vendidas',
              width: '9%',
              filter: false,
              type: 'custom',
              renderComponent: IconRenderKComponent
            }
          },
          actions: {
            // columnTitle: '',
            add: true,
            edit: true,
            delete: true
          },
          attr: {
            class: 'table-bordered table-hover table-responsive'
          }
        }
      }, err => {
        console.log(err);
      })
    }, err => {
      console.log(err);
    })*/
  }

  /*GESTION COMPRAS*/
  settingsC = {};
  sourceC: LocalDataSource = new LocalDataSource();
  showDialogC = true;
  showDialogCU = false;
  selectedIeProd = 'Existente';
  flagProdC = false;
  typesProd: any[];
  objProdCompras: {
    producto: Producto,
    cantidad: 0,
    pcUnitario: 0,
    //unidadMedida: string,
    //contenido: 0,
    //pcAnterior: number,
    fecha: string,
    total: number,
    impuestos: any[]
  }
  selectedProdCompras: any;
  objCompras: {
    num_factura: '',
    fecha: Date,
    proveedor: Proveedor,
    vendedor: '',
    productosV: any[],
    desglose: any,
    formaPago: {
      fpEfectivo: 0,
      fpTarjeta: 0,
      fpPorCobrar: 0,
      fpCheque: 0
    },
    total: number
  }
  lstProveedoresR: any[] = [];
  checkedC = false;
  selectedTipoProd = 'Existente';
  subTotalPagarC = 0;
  flagErrorFP = false;
  campoFP;
  maximoFP;
  lstComprasProve: any[];
  showDialogProdC = false;
  objDesgloce = {
    subtotal: 0,
    iva: 0,
    ice: 0,
    otro: 0,
    descuento: 0,
    propina: 0,
    total: 0
  }
  prodCompra: Producto;
  lstProductos: Producto[];
  flagUnits = true;
  newProd: any;

  setCursorAddC() {
    setTimeout(function () {
      document.getElementById('num_facturaC').focus();
    }, 50);
  }
  validNumFact = true;
  mask = [/\d/, /\d/, /[1-9]/, '-', /\d/, /\d/, /[1-9]/, '-', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /[1-9]/];
  onChangeNumFact() {
    if (!this.validateService.validarNumFact(this.objCompras.num_factura)) {
      this.messageGrowlService.notify('success', 'Éxito', 'Número de factura válido!');
      document.getElementById("num_facturaC").style.borderLeft = "5px solid #42A948";
      this.validNumFact = false;
    } else {
      document.getElementById("num_facturaC").style.borderLeft = "5px solid #a94442";
      this.validNumFact = true;
    }
  }

  onClickSelectButton(event) {
    if (this.selectedIeProd.localeCompare('Existente') == 0) {
      this.flagProdC = false;
    } else {
      this.flagProdC = true;
      this.setCursorAddProdCompras();
    }
  }

  changeTipoProd(event) {
    if (this.selectedTipoProd.localeCompare('Existente') == 0) {
      this.flagProdC = false;
      this.setDvProdCompra();
    } else {
      this.flagProdC = true;
      this.setCursorAddProdCompras();
      this.setDvProdCompra();
    }
  }

  setCursorAddProdCompras() {
    setTimeout(function () {
      document.getElementById('desc_productoC').focus();
    }, 0);
  }

  prodAnterior: any;
  onChangeProdCompra() {
    let name: any = this.prodAnterior;
    let prod = this.lstProductos.filter(function (obj) {
      return obj.nombre.localeCompare(name) === 0;
    });
    prod[0].cant_existente = parseFloat(prod[0].cant_existente.toString());
    this.objProdCompras.producto = prod[0];
  }

  addProdCompra() {
    this.subTotalPagarC = 0;
    let um = this.selectedUmMat.label + '-' + this.selectedUmMat1.label;
    const gain = this.fs.add((this.fs.div(30, 100)), 1);
    let pvp = this.fs.times(this.objProdCompras.pcUnitario, gain)
    if (this.selectedTipoProd.localeCompare('Nuevo') === 0) {
      //Ingresar nuevo producto en tabla producto
      this.prodCompra = {
        nombre: this.objProdCompras.producto.nombre,
        precio_costo: this.objProdCompras.pcUnitario,
        precio_venta: pvp,
        utilidad: 30,
        cant_existente: this.objProdCompras.cantidad,
        cant_minima: 5,
        subproductoV: [],
        id_tipo_producto: this.selected_tipo_producto._id,
        path: this.selected_tipo_producto.path,
        contenido: this.objProdCompras.producto.contenido,
        promocion: [],
        unidad_medida: um,
        impuestosCompraV: this.objImpC,
        impuestosVentaV: [],
        recentIncome: true
      };
      console.log(this.prodCompra);
      /*this.productoService.registerProducto(this.prodCompra).subscribe(data => {
        this.ngOnInitProducto();
        this.ngOnInit();
        this.ngOnInitImp();
        this.messageGrowlService.notify('success', 'Éxito', 'Ingreso Exitoso!');
      }, err => {
        console.log(err);
        this.messageGrowlService.notify('warn', 'Advertencia', 'Algo salió mal!');
      });*/
    } else {
      //Actualizar producto en tabla producto
      this.prodCompra = {
        nombre: this.objProdCompras.producto.nombre,
        precio_costo: this.objProdCompras.pcUnitario,
        precio_venta: pvp,
        utilidad: 30,
        cant_existente: this.objProdCompras.producto.cant_existente + this.objProdCompras.cantidad,
        cant_minima: this.objProdCompras.producto.cant_minima,
        subproductoV: this.objProdCompras.producto.subproductoV,
        id_tipo_producto: this.objProdCompras.producto.id_tipo_producto,
        path: this.objProdCompras.producto.path,
        contenido: this.objProdCompras.producto.contenido,
        promocion: this.objProdCompras.producto.promocion,
        unidad_medida: this.objProdCompras.producto.unidad_medida,
        impuestosCompraV: this.objProdCompras.impuestos,
        impuestosVentaV: [],
        recentIncome: true
      };
      /*this.productoService.updateProducto(this.prodCompra).subscribe(data => {
        this.ngOnInitProducto();
        this.ngOnInit();
        this.ngOnInitImp();
        this.messageGrowlService.notify('info', 'Éxito', 'Modificación Exitosa!');
      }, err => {
        console.log(err);
        this.messageGrowlService.notify('warn', 'Advertencia', 'Algo salió mal!');
      });*/
    }
    //Add tabla compras
    this.addLstCompras();
    this.calcSubTotal();
    this.calcIva();
    this.calcIce();
    this.calcOtros();
    //Lista de impuestas de la factura
    /*this.objDesgloce = {
      subtotal: this.subTotalPagarC,
      iva: this.fs.sub(this.fs.times(this.subTotalPagarC, 1.12), this.subTotalPagarC),
      ice: 0,
      otro: 0,
      descuento: 0,
      propina: 0,
      total: this.fs.times(this.subTotalPagarC, 1.12)
    }*/
    this.showDialogProdC = false;
    this.setDvProdCompra();
  }

  addLstCompras() {
    let aux: any = [];
    aux = {
      cantidad: this.objProdCompras.cantidad,
      fecha: this.validateService.getDateTimeStamp(),
      impuestos: this.objProdCompras.impuestos,
      pcUnitario: this.objProdCompras.pcUnitario,
      producto: this.prodCompra,
      total: this.fs.times(this.objProdCompras.pcUnitario, this.objProdCompras.cantidad),
      crud: ''
    }
    //For insert or update
    if (!this.flagProdC) {
      aux.crud = 'u';
    } else {
      aux.crud = 'c';
    }
    this.lstComprasProve = [...this.lstComprasProve, aux];
  }

  calcSubTotal() {
    this.objDesgloce.subtotal = this.lstComprasProve.reduce(function (prev, cur) {
      return prev + cur.total;
    }, 0);
  }

  calcIva() {
    let acum = 0;
    for (let entry of this.lstComprasProve) {
      acum = this.fs.add(acum, this.fs.times(entry.cantidad, entry.impuestos[0].valor));
    }
    this.objDesgloce.iva = Number(acum.toFixed(2));
  }

  calcIce() {
    let acum = 0;
    for (let entry of this.lstComprasProve) {
      acum = this.fs.add(acum, this.fs.times(entry.cantidad, entry.impuestos[1].valor));
    }
    this.objDesgloce.ice = Number(acum.toFixed(2));
  }

  calcOtros() {
    let acum = 0;
    for (let entry of this.lstComprasProve) {
      let n = entry.impuestos.length;
      for (let i = 2; i < n; i++) {
        acum = this.fs.add(acum, this.fs.times(entry.cantidad, entry.impuestos[i].valor));
      }
    }
    this.objDesgloce.otro = Number(acum.toFixed(2));
  }

  calcTotal() {
    this.objDesgloce.total = this.objDesgloce.subtotal + this.objDesgloce.iva + this.objDesgloce.ice + this.objDesgloce.otro - this.objDesgloce.descuento + this.objDesgloce.propina;
  }

  deleteRowCompras(index) {
    this.lstComprasProve.splice(index, 1);
    this.lstComprasProve = [...this.lstComprasProve];
    this.subTotalPagarC = this.calcTotalCompras();
    this.objDesgloce = {
      subtotal: this.subTotalPagarC,
      iva: this.fs.sub(this.fs.times(this.subTotalPagarC, 1.12), this.subTotalPagarC),
      ice: 0,
      otro: 0,
      descuento: 0,
      propina: 0,
      total: this.fs.times(this.subTotalPagarC, 1.12)
    }
  }

  calcTotalCompras() {
    let sum = 0;
    return sum = this.lstComprasProve.reduce(function (prev, cur) {
      return prev + cur.total;
    }, 0);
  }

  onAddCompra() {
    this.calcTotal();
    this.objCompras.productosV = this.lstComprasProve;
    this.objCompras.desglose = this.objDesgloce;
    this.objCompras.total = this.objDesgloce.subtotal + this.objDesgloce.iva + this.objDesgloce.ice + this.objDesgloce.otro + this.objDesgloce.propina - this.valorReal1
    console.log(this.objCompras);
    this.comprasService.register(this.objCompras).subscribe(data => {
      this.messageGrowlService.notify('success', 'Éxito', 'Ingreso Exitoso!');
    }, err => {
      console.log(err);
      this.messageGrowlService.notify('warn', 'Advertencia', 'Algo salió mal!');
    });
  }

  onChangeNombreProdCompra($event) {
    this.objProdCompras.producto = this.fs.toTitleCase(this.objProdCompras.producto);
  }

  flagCantPC = false;
  onChangeCantProdCompra($event) {
    if (this.objProdCompras.cantidad > 0) {
      this.flagCantPC = true;
    } else {
      this.flagCantPC = false;
    }
  }

  flagPrecioCostoPC = false;
  onChangePCUProdCompra($event) {
    if (this.objProdCompras.pcUnitario > 0) {
      this.flagPrecioCostoPC = true;
    } else {
      this.flagPrecioCostoPC = false;
    }
  }

  setDvProdCompra() {
    this.flagCantPC = false;
    this.flagPrecioCostoPC = false;
    this.objProdCompras = {
      producto: new Producto,
      cantidad: 0,
      pcUnitario: 0,
      fecha: '',
      total: 0,
      impuestos: []
    }
    this.ngOnInitImpC();
  }

  flagRepresentante = false;
  loadSailers($event) {
    let a: any = this.objCompras.proveedor;
    this.lstProveedoresR = a.representanteV;
    this.flagRepresentante = true;

    //console.log(this.objCompras.proveedor)
  }

  onChangeFPE($event) {
    let total = this.objDesgloce.subtotal + this.objDesgloce.iva + this.objDesgloce.ice + this.objDesgloce.otro + this.objDesgloce.propina - this.valorReal1
    if (this.objCompras.formaPago.fpEfectivo + this.objCompras.formaPago.fpTarjeta + this.objCompras.formaPago.fpPorCobrar + this.objCompras.formaPago.fpCheque > total) {
      this.objCompras.formaPago.fpEfectivo = 0;
      setTimeout(function () {
        let v = document.getElementById('fpEfectivo');
        if (v != null) {
          v.click();
        }
      }, 0);
      this.campoFP = 'Efectivo';
      this.maximoFP = total - (this.objCompras.formaPago.fpEfectivo + this.objCompras.formaPago.fpTarjeta + this.objCompras.formaPago.fpPorCobrar + this.objCompras.formaPago.fpCheque);
      this.flagErrorFP = true;
    } else {
      this.flagErrorFP = false;
    }
  }

  onChangeFPT($event) {
    let total = this.objDesgloce.subtotal + this.objDesgloce.iva + this.objDesgloce.ice + this.objDesgloce.otro + this.objDesgloce.propina - this.valorReal1
    if (this.objCompras.formaPago.fpEfectivo + this.objCompras.formaPago.fpTarjeta + this.objCompras.formaPago.fpPorCobrar + this.objCompras.formaPago.fpCheque > total) {
      this.objCompras.formaPago.fpTarjeta = 0;
      setTimeout(function () {
        let v = document.getElementById('fpTarjeta');
        if (v != null) {
          v.click();
        }
      }, 0);
      this.campoFP = 'Tarjeta de Crédito';
      this.maximoFP = total - (this.objCompras.formaPago.fpEfectivo + this.objCompras.formaPago.fpTarjeta + this.objCompras.formaPago.fpPorCobrar + this.objCompras.formaPago.fpCheque);
      this.flagErrorFP = true;
    } else {
      this.flagErrorFP = false;
    }
  }

  onChangeFPC($event) {
    let total = this.objDesgloce.subtotal + this.objDesgloce.iva + this.objDesgloce.ice + this.objDesgloce.otro + this.objDesgloce.propina - this.valorReal1
    if (this.objCompras.formaPago.fpEfectivo + this.objCompras.formaPago.fpTarjeta + this.objCompras.formaPago.fpPorCobrar + this.objCompras.formaPago.fpCheque > total) {
      this.objCompras.formaPago.fpPorCobrar = 0;
      setTimeout(function () {
        let v = document.getElementById('fpPorCobrar');
        if (v != null) {
          v.click();
        }
      }, 0);
      this.campoFP = 'Crédito Directo';
      this.maximoFP = total - (this.objCompras.formaPago.fpEfectivo + this.objCompras.formaPago.fpTarjeta + this.objCompras.formaPago.fpPorCobrar + this.objCompras.formaPago.fpCheque);
      this.flagErrorFP = true;
    } else {
      this.flagErrorFP = false;
    }
  }

  onChangeFPCH($event) {
    let total = this.objDesgloce.subtotal + this.objDesgloce.iva + this.objDesgloce.ice + this.objDesgloce.otro + this.objDesgloce.propina - this.valorReal1
    if (this.objCompras.formaPago.fpEfectivo + this.objCompras.formaPago.fpTarjeta + this.objCompras.formaPago.fpPorCobrar + this.objCompras.formaPago.fpCheque > total) {
      this.objCompras.formaPago.fpCheque = 0;
      setTimeout(function () {
        let v = document.getElementById('fpCheque');
        if (v != null) {
          v.click();
        }
      }, 0);
      this.campoFP = 'Cheque';
      this.maximoFP = total - (this.objCompras.formaPago.fpEfectivo + this.objCompras.formaPago.fpTarjeta + this.objCompras.formaPago.fpPorCobrar + this.objCompras.formaPago.fpCheque);
      this.flagErrorFP = true;
    } else {
      this.flagErrorFP = false;
    }
  }

  representanteC = {
    nombre: '',
    telefono: '',
    correo: '',
    descripcion: '',
    value: ''
  }
  showRepresentanteC = false;
  onChangeNombreRepreC($event) {
    this.representanteC.nombre = this.representanteC.nombre.trim();
    this.representanteC.nombre = this.fs.toTitleCase(this.representanteC.nombre);
  }

  onChangeEmailRepreC($event) {
    /*this.representanteC.correo = this.representanteC.correo.toLocaleLowerCase();
    if (this.validateService.validateEmail(this.representanteC.correo)) {
      document.getElementById("correoRepreC").style.borderLeft = "5px solid #42A948"; //green
      this.flagEmailRepre = false;
    }
    else {
      document.getElementById("correoRepreC").style.borderLeft = "5px solid #a94442"; //red
      this.flagEmailRepre = true;
    }*/
  }

  onChangeDescRepreC($event) {
    this.representanteC.descripcion = this.representanteC.descripcion.trim();
  }

  addRepreC() {
    /*this.representanteC.value = this.representanteC.nombre;
    this.objCompras.proveedor.representanteV = [...this.objCompras.proveedor.representanteV, this.representanteC];
    let a: any = this.objCompras.proveedor;
    this.lstProveedoresR = a.representanteV;
    let b: any = this.representanteC
    this.objCompras.vendedor = b;

    this.proveedorService.update(this.objCompras.proveedor).subscribe(data => {
      this.messageGrowlService.notify('info', 'Información', 'Ingreso Existoso!');
      document.getElementById("correoRepreC").style.borderLeft = "5px solid #a94442";
    }, err => {
      console.log(err);
    });

    this.showRepresentanteC = false;
    this.representante = {
      nombre: '',
      telefono: '',
      correo: '',
      descripcion: '',
      value: ''
    }
    document.getElementById("correoRepreC").style.borderLeft = "5px solid #a94442";
    this.flagEmailRepre = true;*/
  }

  valorReal1 = 0;
  onChangeDescuento() {
    let total = this.objDesgloce.subtotal + this.objDesgloce.iva + this.objDesgloce.ice + this.objDesgloce.otro + this.objDesgloce.propina;
    this.valorReal1 = this.fs.times(this.fs.div(this.objDesgloce.descuento, 100), total);
  }

  onChangeDescuento1() {
    let total = this.objDesgloce.subtotal + this.objDesgloce.iva + this.objDesgloce.ice + this.objDesgloce.otro + this.objDesgloce.propina;
    this.objDesgloce.descuento = this.fs.div(this.fs.times(this.valorReal1, 100), total);
  }

  searchTipoProdById(id) {
    for (const entry of this.lstTipoProductos) {
      if (entry._id === id) {
        return entry;
      }
    }
  }

  lstTipoProductos: any[];
  lstCompras: any[];
  ngOnInitCompras() {
    this.typesProd = [];
    this.typesProd.push({ label: 'Existente', value: 'Existente' });
    this.typesProd.push({ label: 'Nuevo', value: 'Nuevo' });
    this.lstComprasProve = [];
    this.objCompras = {
      num_factura: '',
      fecha: new Date(),
      proveedor: new Proveedor,
      vendedor: '',
      productosV: [],
      desglose: undefined,
      formaPago: {
        fpEfectivo: 0,
        fpTarjeta: 0,
        fpPorCobrar: 0,
        fpCheque: 0
      },
      total: 0
    };
    this.objProdCompras = {
      producto: new Producto,
      cantidad: 0,
      pcUnitario: 0,
      fecha: '',
      total: 0,
      impuestos: []
    }
    /* Get Proveedores*/
    this.proveedorService.getAll().subscribe(data => {
      this.lstProveedores = data;
      localStorage.setItem('lstProveedor', JSON.stringify(this.lstProveedores));
      this.sourceProve = new LocalDataSource();
      this.sourceProve.load(data);
      this.settingsProve = {
        mode: 'external',
        noDataMessage: 'No existen registros',
        columns: {
          ruc: {
            title: 'Ruc',
            width: '12%'
          },
          nombre_proveedor: {
            title: 'Nombre',
            width: '20%'
          },
          direccion: {
            title: 'Dirección',
            width: '20%'
          },
          ciudad: {
            title: 'Ciudad',
            width: '12%',
            valuePrepareFunction: (ciudad) => {
              let fila = ciudad.nombre + '--' + ciudad.provincia;
              return fila;
            }
          },
          telefono: {
            title: 'Teléfono',
            width: '12%'
          },
          representanteV: {
            title: 'Representante',
            width: '14%',
            valuePrepareFunction: (representanteV) => {
              let fila = '';
              for (let entry of representanteV) {
                fila += entry.nombre + '--' + entry.telefono + ' ';
              }
              return fila;
            }
          },
          compras: {
            title: 'Compras',
            width: '10%',
            filter: false,
            type: 'custom',
            renderComponent: IconRenderComponent
          }
        },
        actions: {
          // columnTitle: '',
          add: true,
          edit: true,
          delete: true
        },
        attr: {
          class: 'table-bordered table-hover table-responsive'
        }
      }
      /* Get Compras */
      this.comprasService.getAll().subscribe(data => {
        this.lstCompras = data;
        localStorage.setItem('lstCompras', JSON.stringify(this.lstCompras));
        this.sourceC = new LocalDataSource();
        this.sourceC.load(data);
        this.settingsC = {
          mode: 'external',
          noDataMessage: 'No existen registros',
          columns: {
            fecha: {
              title: 'Fecha Compra',
              width: '15%'
            },
            num_factura: {
              title: 'Numero Factura',
              width: '15%'
            },
            proveedor: {
              title: 'Proveedor',
              width: '20%',
              valuePrepareFunction: (proveedor) => {
                let name = this.lstProveedores.filter(function (obj) {
                  return obj._id.localeCompare(proveedor) === 0;
                })
                if (name.length > 0) {
                  return name[0].nombre_proveedor;
                } else {
                  return '';
                }
              }
            },
            productosV: {
              title: 'Productos',
              width: '35%',
              valuePrepareFunction: (productosV) => {
                //console.log(productosV);
              }
            },
            total: {
              title: 'Total',
              width: '15%',
              type: 'custom',
              renderComponent: PipeRenderComponent,
              filter: false
            }
          },
          actions: {
            columnTitle: '',
            add: true,
            edit: true,
            delete: true
          },
          attr: {
            class: 'table-bordered table-hover table-responsive'
          }
        };
      }, err => {
        console.log(err);
      })
    }, err => {
      console.log(err);
      return false;
    });
    /* Get Tipo Productos */
    this.tipoProductoService.getAll().subscribe(tp => {
      this.lstTipoProductos = tp;
    }, err => {
      console.log(err);
      return false;
    });
    /* Get Productos*/
    this.lstProductos = [];
    this.productoService.getAll().subscribe(p => {
      localStorage.setItem('lstProductos', JSON.stringify(this.lstProductos));
      for (let entry of p) {
        entry['value'] = entry.nombre;
        entry['label'] = entry.nombre;
        this.lstProductos = [...this.lstProductos, entry];
      }
      //console.log(this.lstProductos);
    }, err => {
      console.log(err);
      return false;
    });

    //console.log(this.fs.dinamicModulo11('010520180117912875410012001011006161585281014691'));
  }

  //Impuestos
  showDlgImpC = false;
  choiceSetC = { nombre: [], porcentaje: [], valor: [] };
  objIvaC = {
    desc: 'IVA',
    porcentaje: 12,
    valor: 0
  }
  objIceC = {
    desc: 'ICE',
    porcentaje: 0,
    valor: 0
  }
  objOtroC = {
    desc: 'OTRO',
    porcentaje: 0,
    valor: 0
  }
  objIvaVC = {
    desc: 'IVA',
    porcentaje: 12,
    valor: 0
  }
  objIceVC = {
    desc: 'ICE',
    porcentaje: 0,
    valor: 0
  }
  objOtroVC = {
    desc: 'OTRO',
    porcentaje: 0,
    valor: 0
  }
  objImpC: any[] = [];

  ngOnInitImpC() {
    this.choiceSetC.nombre = [];
    this.choiceSetC.porcentaje = [];
    this.choiceSetC.valor = [];
    this.objIvaC = {
      desc: 'IVA',
      porcentaje: 12,
      valor: 0
    }
    this.objIceC = {
      desc: 'ICE',
      porcentaje: 0,
      valor: 0
    }
    this.objOtroC = {
      desc: 'OTRO',
      porcentaje: 0,
      valor: 0
    }
    this.objImpC = [...this.objImpC, this.objIvaC];
    this.objImpC = [...this.objImpC, this.objIceC];
    this.objImpC = [...this.objImpC, this.objOtroC];
  }

  addRowImpC = function () {
    this.choiceSetC.nombre.push('');
    this.choiceSetC.porcentaje.push('');
    this.choiceSetC.valor.push('');
  };

  removeChoiceC = function (z) {
    this.choiceSetC.nombre.splice(z, 1);
    this.choiceSetC.porcentaje.splice(z, 1);
    this.choiceSetC.valor.splice(z, 1);
  };

  lstImps: any;
  addImpuestoC() {
    this.objProdCompras.impuestos = [];
    /*this.objProdCompras.impuestos = [...this.objImpC, this.objIvaC];
    this.objProdCompras.impuestos = [...this.objImpC, this.objIceC];
    this.objProdCompras.impuestos = [...this.objImpC, this.objOtroC];*/
    this.objProdCompras.impuestos.push(this.objIvaC);
    this.objProdCompras.impuestos.push(this.objIceC);
    this.objProdCompras.impuestos.push(this.objOtroC);

    let n = this.choiceSetC.nombre.length;
    for (let i = 0; i < n; i++) {
      let aux = { desc: this.choiceSetC.nombre[i], porcentaje: this.choiceSetC.porcentaje[i], valor: this.choiceSetC.valor[i] };
      this.objProdCompras.impuestos = [...this.objImpC, aux];
    }
    this.messageGrowlService.notify('info', 'Información', 'Se guardaron los impuestos!');
    this.showDlgImpC = false;
  }

  valueChangePorIvaC($event) {
    let porcentaje = this.fs.div(this.objIvaC.porcentaje, 100);
    this.objIvaC.valor = this.fs.times(this.objProdCompras.pcUnitario, porcentaje);
  }

  valueChangePorIceC($event) {
    let porcentaje = this.fs.div(this.objIceC.porcentaje, 100);
    this.objIceC.valor = this.fs.times(this.objProdCompras.pcUnitario, porcentaje);
  }

  valueChangePorOtroC($event) {
    let porcentaje = this.fs.div(this.objOtroC.porcentaje, 100);
    this.objOtroC.valor = this.fs.times(this.objProdCompras.pcUnitario, porcentaje);
  }

  calcImpC() {
    let porIva = this.fs.div(this.objIvaC.porcentaje, 100);
    let porIce = this.fs.div(this.objIceC.porcentaje, 100);
    let porOtro = this.fs.div(this.objOtroC.porcentaje, 100);
    this.objIvaC.valor = this.fs.times(this.objProdCompras.pcUnitario, porIva);
    this.objIceC.valor = this.fs.times(this.objProdCompras.pcUnitario, porIce);
    this.objOtroC.valor = this.fs.times(this.objProdCompras.pcUnitario, porOtro);
  }

  valueChangePorGenericC(i) {
    let porcentaje = this.fs.div(this.choiceSetC.porcentaje[i], 100);
    this.choiceSetC.valor[i] = this.fs.times(this.objProdCompras.pcUnitario, porcentaje);
  }

  onChangeDescOtroImpC($event) {
    this.objOtroC.desc = this.objOtroC.desc.toUpperCase();
  }

  onChangeDescVC(i) {
    this.choiceSetC.nombre[i] = this.choiceSetC.nombre[i].toUpperCase();
  }

  //Width detection
  textAlignTitle = 'left';
  onResize(event) {
    let x = event.target.innerWidth;
    //console.log(x)
    if (x < 768) {
      this.textAlignTitle = 'center';
    } else {
      this.textAlignTitle = 'left';
    }
  }

  onRzOnInit(x) {
    if (x < 768) {
      this.textAlignTitle = 'center';
    } else {
      this.textAlignTitle = 'left';
    }
  }
}

function setOriginalColorsProve() {
  document.getElementById("rucProve").style.borderColor = "";
  document.getElementById("correo").style.borderColor = "";
}

function setOriginalColorsProveU() {
  document.getElementById("rucProveU").style.borderColor = "";
  document.getElementById("correoU").style.borderColor = "";
}

function setOriginalColorsRepre() {
  document.getElementById("correoRepre").style.borderColor = "";
}


text:
<?php

namespace Controller\AdminController;

class NewFileController extends LoggedInController {
	private $data;
	private $link;
	private $title;
	public function __construct() {
		parent::__construct ();
		$this->data = new \stdClass();
	}
	public function show() {
		if ($_POST) {
			$this->saveFile();
		} else {
			$this->data->files = \Core\File::getFilesFromDir();
			$this->link = "newFile";
			$this->title = "Hercules";
		}
		parent::output ( $this->link, $this->title, $this->data);
	}
	public function saveFile(){
		// Data? - OK
		$file = new \Core\File ();
		$this->data->error = "";
		$this->data->error.= $file->setVisibleTitle ( $_POST ['fileTitle'] );
		$this->data->error.= $file->setFileName(isset($_POST['fileName']) ? $_POST['fileName'] : null);
		$file->setOwner(\Repository\Factory::getUser()->getID());

		if($this->data->error === ""){
			\Repository\Factory::getRepFile()->save($file);
			$this->data = "Erfolgreich gespeichert";
			$this->link = "newFile_saved";
			$this->title = "Hercules";
		} else {
			$this->data->files = \Core\File::getFilesFromDir();
			$this->link = "newFile";
			$this->title = "Hercules";
		}
	}
}


text:
{% extends ../base.html %}

{% block page_container %} FILL IN PAGE HERE {% end %}


text:
package sample

import (
	"context"
	"net/http"

	"google.golang.org/appengine"
	"google.golang.org/appengine/datastore"
	"google.golang.org/appengine/log"
	"google.golang.org/appengine/memcache"
)

var maxHeight int
var minBirthYear, maxBirthYear int

// [START gae_go_datastore_interface]
type Person struct {
	FirstName string
	LastName  string
	City      string
	BirthYear int
	Height    int
}

func handle(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)

	// The Query type and its methods are used to construct a query.
	q := datastore.NewQuery("Person").
		Filter("LastName =", "Smith").
		Filter("Height <=", maxHeight).
		Order("-Height")

	// To retrieve the results,
	// you must execute the Query using its GetAll or Run methods.
	var people []Person
	if _, err := q.GetAll(ctx, &people); err != nil {
		// Handle error.
	}
	// ...
}

// [END gae_go_datastore_interface]

func example() {
	var lastSeenKey *datastore.Key

	// [START gae_go_datastore_key_filter]
	q := datastore.NewQuery("Person").Filter("__key__ >", lastSeenKey)
	// [END gae_go_datastore_key_filter]
	_ = q
}

func example2() {
	// [START gae_go_datastore_property_filter]
	q := datastore.NewQuery("Person").Filter("Height <=", maxHeight)
	// [END gae_go_datastore_property_filter]
	_ = q
}

func example3() {
	var ancestorKey *datastore.Key

	// [START gae_go_datastore_ancestor_filter]
	q := datastore.NewQuery("Person").Ancestor(ancestorKey)
	// [END gae_go_datastore_ancestor_filter]
	_ = q
}

func example4() {
	// [START gae_go_datastore_sort_order]
	// Order alphabetically by last name:
	q := datastore.NewQuery("Person").Order("LastName")

	// Order by height, tallest to shortest:
	q = datastore.NewQuery("Person").Order("-Height")
	// [END gae_go_datastore_sort_order]
	_ = q
}

func example5() {
	// [START gae_go_datastore_multiple_sort_orders]
	q := datastore.NewQuery("Person").Order("LastName").Order("-Height")
	// [END gae_go_datastore_multiple_sort_orders]
	_ = q
}

func example6() {
	type Photo struct {
		URL string
	}
	var ctx context.Context

	// [START gae_go_datastore_ancestor_query]
	// Create two Photo entities in the datastore with a Person as their ancestor.
	tomKey := datastore.NewKey(ctx, "Person", "Tom", 0, nil)

	wPhoto := Photo{URL: "http://example.com/some/path/to/wedding_photo.jpg"}
	wKey := datastore.NewKey(ctx, "Photo", "", 0, tomKey)
	_, err := datastore.Put(ctx, wKey, wPhoto)
	// check err

	bPhoto := Photo{URL: "http://example.com/some/path/to/baby_photo.jpg"}
	bKey := datastore.NewKey(ctx, "Photo", "", 0, tomKey)
	_, err = datastore.Put(ctx, bKey, bPhoto)
	// check err

	// Now fetch all Photos that have tomKey as an ancestor.
	// This will populate the photos slice with wPhoto and bPhoto.
	q := datastore.NewQuery("Photo").Ancestor(tomKey)
	var photos []Photo
	_, err = q.GetAll(ctx, &photos)
	// check err
	// do something with photos
	// [END gae_go_datastore_ancestor_query]
	_ = err
	_ = photos
}

func example7() {
	// [START gae_go_datastore_keys_only]
	q := datastore.NewQuery("Person").KeysOnly()
	// [END gae_go_datastore_keys_only]
	_ = q
}

func example8() {
	// [START gae_go_datastore_inequality_filters_one_property_valid_1]
	q := datastore.NewQuery("Person").
		Filter("BirthYear >=", minBirthYear).
		Filter("BirthYear <=", maxBirthYear)
	// [END gae_go_datastore_inequality_filters_one_property_valid_1]
	_ = q
}

func example9() {
	// [START gae_go_datastore_inequality_filters_one_property_invalid]
	q := datastore.NewQuery("Person").
		Filter("BirthYear >=", minBirthYear).
		Filter("Height <=", maxHeight) // ERROR
	// [END gae_go_datastore_inequality_filters_one_property_invalid]
	_ = q
}

func example10() {
	var targetLastName, targetCity string

	// [START gae_go_datastore_inequality_filters_one_property_valid_2]
	q := datastore.NewQuery("Person").
		Filter("LastName =", targetLastName).
		Filter("City =", targetCity).
		Filter("BirthYear >=", minBirthYear).
		Filter("BirthYear <=", maxBirthYear)
	// [END gae_go_datastore_inequality_filters_one_property_valid_2]
	_ = q
}

func example11() {
	// [START gae_go_datastore_inequality_filters_sort_orders_valid]
	q := datastore.NewQuery("Person").
		Filter("BirthYear >=", minBirthYear).
		Order("BirthYear").
		Order("LastName")
	// [END gae_go_datastore_inequality_filters_sort_orders_valid]
	_ = q
}

func example12() {
	// [START gae_go_datastore_inequality_filters_sort_orders_invalid_1]
	q := datastore.NewQuery("Person").
		Filter("BirthYear >=", minBirthYear).
		Order("LastName") // ERROR
	// [END gae_go_datastore_inequality_filters_sort_orders_invalid_1]
	_ = q
}

func example13() {
	// [START gae_go_datastore_inequality_filters_sort_orders_invalid_2]
	q := datastore.NewQuery("Person").
		Filter("BirthYear >=", minBirthYear).
		Order("LastName").
		Order("BirthYear") // ERROR
	// [END gae_go_datastore_inequality_filters_sort_orders_invalid_2]
	_ = q
}

func example14() {
	// [START gae_go_datastore_surprising_behavior_1]
	q := datastore.NewQuery("Widget").
		Filter("x >", 1).
		Filter("x <", 2)
	// [END gae_go_datastore_surprising_behavior_1]
	_ = q
}

func example15() {
	// [START gae_go_datastore_surprising_behavior_2]
	q := datastore.NewQuery("Widget").
		Filter("x =", 1).
		Filter("x =", 2)
	// [END gae_go_datastore_surprising_behavior_2]
	_ = q
}

func doSomething(k *datastore.Key, p Person) {}

func example16() {
	var ctx context.Context
	// [START gae_go_datastore_retrieval]
	q := datastore.NewQuery("Person")
	t := q.Run(ctx)
	for {
		var p Person
		k, err := t.Next(&p)
		if err == datastore.Done {
			break // No further entities match the query.
		}
		if err != nil {
			log.Errorf(ctx, "fetching next Person: %v", err)
			break
		}
		// Do something with Person p and Key k
		doSomething(k, p)
	}
	// [END gae_go_datastore_retrieval]
}

func example17() {
	var ctx context.Context

	// [START gae_go_datastore_all_entities_retrieval]
	q := datastore.NewQuery("Person")
	var people []Person
	keys, err := q.GetAll(ctx, &people)
	if err != nil {
		log.Errorf(ctx, "fetching people: %v", err)
		return
	}
	for i, p := range people {
		k := keys[i]
		// Do something with Person p and Key k
		doSomething(k, p)
	}
	// [END gae_go_datastore_all_entities_retrieval]
}

func example18() {
	var ctx context.Context

	// [START gae_go_datastore_query_limit]
	q := datastore.NewQuery("Person").Order("-Height").Limit(5)
	var people []Person
	_, err := q.GetAll(ctx, &people)
	// check err

	for _, p := range people {
		log.Infof(ctx, "%s %s, %d inches tall", p.FirstName, p.LastName, p.Height)
	}
	// [END gae_go_datastore_query_limit]
	_ = err
}

func example19() {
	q := datastore.NewQuery("Person").Order("-Height").Limit(5).Offset(5)
	_ = q
}

func example20() {
	var ctx context.Context

	// [START gae_go_datastore_cursors]
	// Create a query for all Person entities.
	q := datastore.NewQuery("Person")

	// If the application stored a cursor during a previous request, use it.
	item, err := memcache.Get(ctx, "person_cursor")
	if err == nil {
		cursor, err := datastore.DecodeCursor(string(item.Value))
		if err == nil {
			q = q.Start(cursor)
		}
	}

	// Iterate over the results.
	t := q.Run(ctx)
	for {
		var p Person
		_, err := t.Next(&p)
		if err == datastore.Done {
			break
		}
		if err != nil {
			log.Errorf(ctx, "fetching next Person: %v", err)
			break
		}
		// Do something with the Person p
	}

	// Get updated cursor and store it for next time.
	if cursor, err := t.Cursor(); err == nil {
		memcache.Set(ctx, &memcache.Item{
			Key:   "person_cursor",
			Value: []byte(cursor.String()),
		})
	}
	// [END gae_go_datastore_cursors]
}

func example21() {
	var lastSeenKey *datastore.Key

	// [START gae_go_datastore_kindless_query]
	q := datastore.NewQuery("").Filter("__key__ >", lastSeenKey)
	// [END gae_go_datastore_kindless_query]
	_ = q
}

func example22() {
	var ancestorKey, lastSeenKey *datastore.Key

	// [START gae_go_datastore_kindless_ancestor_key_query]
	q := datastore.NewQuery("").Ancestor(ancestorKey).Filter("__key__ >", lastSeenKey)
	// [END gae_go_datastore_kindless_ancestor_key_query]
	_ = q
}

func example23() {
	type Photo struct {
		URL string
	}
	type Video Photo
	var ctx context.Context
	doSomething := func(x interface{}) {}

	// [START gae_go_datastore_kindless_ancestor_query]
	tomKey := datastore.NewKey(ctx, "Person", "Tom", 0, nil)

	weddingPhoto := &Photo{URL: "http://example.com/some/path/to/wedding_photo.jpg"}
	_, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Photo", tomKey), weddingPhoto)

	weddingVideo := &Video{URL: "http://example.com/some/path/to/wedding_video.avi"}
	_, err = datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Video", tomKey), weddingVideo)

	// The following query returns both weddingPhoto and weddingVideo,
	// even though they are of different entity kinds.
	q := datastore.NewQuery("").Ancestor(tomKey)
	t := q.Run(ctx)
	for {
		var x interface{}
		_, err := t.Next(&x)
		if err == datastore.Done {
			break
		}
		if err != nil {
			log.Errorf(ctx, "fetching next Photo/Video: %v", err)
			break
		}
		// Do something (e.g. switch on types)
		doSomething(x)
	}
	// [END gae_go_datastore_kindless_ancestor_query]
	_ = err
}


text:
<bill session="115" type="h" number="1351" updated="2017-10-06T19:45:12Z">
  <state datetime="2017-05-03">REPORTED</state>
  <status>
    <unknown datetime="2017-05-03"/>
  </status>
  <introduced datetime="2017-03-02"/>
  <titles>
    <title type="short" as="introduced">Strengthening Oversight of TSA Employee Misconduct Act</title>
    <title type="short" as="introduced">Strengthening Oversight of TSA Employee Misconduct Act</title>
    <title type="short" as="reported to house">Strengthening Oversight of TSA Employee Misconduct Act</title>
    <title type="short" as="reported to house">Strengthening Oversight of TSA Employee Misconduct Act</title>
    <title type="official" as="introduced">To amend title 49, United States Code, to direct the Administrator of the Transportation Security Administration (TSA) to make certain improvements in managing TSA's employee misconduct, and for other purposes.</title>
    <title type="display">Strengthening Oversight of TSA Employee Misconduct Act</title>
  </titles>
  <sponsor bioguide_id="P000605"/>
  <cosponsors>
    <cosponsor bioguide_id="M001157" joined="2017-03-02"/>
  </cosponsors>
  <actions>
    <action datetime="2017-03-02">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-03-02" state="REFERRED">
      <text>Referred to the House Committee on Homeland Security.</text>
    </action>
    <action datetime="2017-03-22">
      <text>Referred to the Subcommittee on Transportation and Protective Security.</text>
    </action>
    <action datetime="2017-05-03">
      <text>Subcommittee on Transportation and Protective Security Discharged.</text>
    </action>
    <action datetime="2017-05-03">
      <text>Committee Consideration and Mark-up Session Held.</text>
    </action>
    <calendar datetime="2017-05-03" state="REPORTED">
      <text>Ordered to be Reported by the Yeas and Nays: 14 - 10.</text>
    </calendar>
    <action datetime="2017-07-17">
      <text>Reported (Amended) by the Committee on Homeland Security. H. Rept. 115-226.</text>
    </action>
    <calendar datetime="2017-07-17" calendar="Union" number="161">
      <text>Placed on the Union Calendar, Calendar No. 161.</text>
    </calendar>
  </actions>
  <committees>
    <committee subcommittee="" code="HSHM" name="House Homeland Security" activity="Reporting, Markup, Referral"/>
    <committee subcommittee="Transportation Security" code="HSHM07" name="House Homeland Security" activity="Discharged, Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Transportation and public works"/>
    <term name="Aviation and airports"/>
    <term name="Congressional oversight"/>
    <term name="Department of Homeland Security"/>
    <term name="Employee performance"/>
    <term name="Government employee pay, benefits, personnel management"/>
    <term name="Government ethics and transparency, public corruption"/>
    <term name="Government studies and investigations"/>
    <term name="Transportation safety and security"/>
  </subjects>
  <amendments/>
  <summary date="2017-03-02T05:00:00Z" status="Introduced in House">Strengthening Oversight of TSA Employee Misconduct Act

This bill directs the Transportation Security Administration (TSA) of the Department of Homeland Security (DHS) to designate a senior official:

 implement a plan to oversee unannounced inspections of actions taken in response to allegations of TSA employee misconduct, including corrective actions by airport managers and employee dismissal; certify to the TSA, on a quarterly basis until September 30, 2022, that such unannounced inspections were completed across a sufficient number of airports; review the results of such inspections to identify root causes of any variances in actions taken in response to employee misconduct allegations and to develop corrective actions; implement any recommendations; and provide the results of such inspections to DHS. DHS shall review such results to identify trends and make recommendations to the TSA to address employee misconduct. The TSA shall implement such recommendations.</summary>
  <committee-reports>
    <report>H. Rept. 115-226</report>
  </committee-reports>
</bill>


text:
package com.wesleyware.client;

import com.wesleyware.daowiz.fieldtypes.*;
import com.wesleyware.daowiz.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * contacts for clients
 */
public abstract class ClientContactBase extends Record implements Cloneable
{
   protected final static ClientContactDao DAO =  new ClientContactDao();

   protected final static String DB_TABLE_NAME = "client_contacts";

   /**
    *auto generated id for client contact
    */
   public final static IntField CLIENTCONTACTID = new IntField("client_contact_id",new Constraints(true, true, false, true));
   /**
    *referenced client
    */
   public final static VarCharField CLIENTID = new VarCharField("client_id",10,new Constraints(true, false, true, false));
   /**
    *department
    */
   public final static VarCharField DEPARTMENT = new VarCharField("department",30,new Constraints(true, false, false, false));
   /**
    *first name
    */
   public final static VarCharField FIRSTNAME = new VarCharField("first_name",30,new Constraints(true, false, false, false));
   /**
    *last name
    */
   public final static VarCharField LASTNAME = new VarCharField("last_name",30,new Constraints(true, false, false, false));
   /**
    *email address
    */
   public final static VarCharField EMAIL = new VarCharField("email",60,new Constraints(false, false, false, false));
   /**
    *phone number
    */
   public final static VarCharField PHONE = new VarCharField("phone",12,new Constraints(false, false, false, false));
   /**
    *phone extension
    */
   public final static VarCharField PHONEEXTENSION = new VarCharField("phone_ext",4,new Constraints(false, false, false, false));
   /**
    *date of birth
    */
   public final static DateField BIRTHDATE = new DateField("birth_date",new Constraints(false, false, false, false));
   /**
    *client status (A = Active, I =Inactive, P = Prospective)
    */
   public final static CharField STATUS = new CharField("status",1,new Constraints(true, false, false, false));
   /**
    *creation date of record
    */
   public final static TimeStampField CREATIONDATE = new TimeStampField("creation_date",new Constraints(true, false, false, true));
   /**
    *last modified date of record
    */
   public final static TimeStampField MODIFIEDDATE = new TimeStampField("modified_date",new Constraints(true, false, false, true));

   private final static Field[] ALL_DB_FIELDS =
   {
      CLIENTCONTACTID,CLIENTID,DEPARTMENT,FIRSTNAME,
      LASTNAME,EMAIL,PHONE,PHONEEXTENSION,
      BIRTHDATE,STATUS,CREATIONDATE,MODIFIEDDATE
   };

   private final static Field[] PK_DB_FIELDS =
   {
      CLIENTCONTACTID
   };

   /**
    * No argument constructor
    */
   public ClientContactBase()
   {
   }

   /**
    * PK constructor
    *
    * throws InvalidPkException
    */
   public ClientContactBase(Integer clientContactId) throws InvalidPkException
   {
      if(!setClientContactId(clientContactId) )
         throw new InvalidPkException();
   }

   /**
    * This method returns the possiblities for clientId given the current state of the object
    *
    * @param   conn   active db connection
    * @return  possible values for clientId
    * @throws SQLException
    */
   public abstract List clientIdChoices(Connection conn) throws SQLException;

   /**
    * This method returns a list of values possible for a fk field given the state of the object
    * It should use the DAO of the referenced table to generate this list.
    * The fk constraint in each field indicates if anything should be returned by this method
    *
    * @param   conn   active db connection
    * @param field     the field whose possible values will be returned
    * @return list of possible data objects whose values are referenced by this field
    * @throws SQLException
    */
   protected List choices(Connection conn, Field field) throws SQLException
   {
      if(field==CLIENTID) return clientIdChoices(conn);
      return null;
   }

   /**
    * setter for auto generated id for client contact
    *
    * @param   value ofclientContactId
    * @return  true if valid
    */
   public boolean setClientContactId(Integer clientContactId)
   {
      return set(CLIENTCONTACTID,clientContactId);
   }

   /**
    * primitive value setter for auto generated id for client contact
    *
    * @param   value ofclientContactId
    * @return  true if valid
    */
   public boolean setClientContactId(int clientContactId)
   {
      return set(CLIENTCONTACTID,clientContactId);
   }

   /**
    * getter for auto generated id for client contact
    *
    * @return   value ofclientContactId
    */
   public Integer getClientContactIdObject()
   {
      return get(CLIENTCONTACTID);
   }

   /**
    * primitive getter for auto generated id for client contact
    *
    * @return   value ofclientContactId
    */
   public int getClientContactId()
   {
      return getPrimitive(CLIENTCONTACTID);
   }

   /**
    * setter for referenced client
    *
    * @param   value ofclientId
    * @return  true if valid
    */
   public boolean setClientId(String clientId)
   {
      return set(CLIENTID,clientId);
   }

   /**
    * getter for referenced client
    *
    * @return   value ofclientId
    */
   public String getClientId()
   {
      return get(CLIENTID);
   }

   /**
    * setter for department
    *
    * @param   value ofdepartment
    * @return  true if valid
    */
   public boolean setDepartment(String department)
   {
      return set(DEPARTMENT,department);
   }

   /**
    * getter for department
    *
    * @return   value ofdepartment
    */
   public String getDepartment()
   {
      return get(DEPARTMENT);
   }

   /**
    * setter for first name
    *
    * @param   value offirstName
    * @return  true if valid
    */
   public boolean setFirstName(String firstName)
   {
      return set(FIRSTNAME,firstName);
   }

   /**
    * getter for first name
    *
    * @return   value offirstName
    */
   public String getFirstName()
   {
      return get(FIRSTNAME);
   }

   /**
    * setter for last name
    *
    * @param   value oflastName
    * @return  true if valid
    */
   public boolean setLastName(String lastName)
   {
      return set(LASTNAME,lastName);
   }

   /**
    * getter for last name
    *
    * @return   value oflastName
    */
   public String getLastName()
   {
      return get(LASTNAME);
   }

   /**
    * setter for email address
    *
    * @param   value ofemail
    * @return  true if valid
    */
   public boolean setEmail(String email)
   {
      return set(EMAIL,email);
   }

   /**
    * getter for email address
    *
    * @return   value ofemail
    */
   public String getEmail()
   {
      return get(EMAIL);
   }

   /**
    * setter for phone number
    *
    * @param   value ofphone
    * @return  true if valid
    */
   public boolean setPhone(String phone)
   {
      return set(PHONE,phone);
   }

   /**
    * getter for phone number
    *
    * @return   value ofphone
    */
   public String getPhone()
   {
      return get(PHONE);
   }

   /**
    * setter for phone extension
    *
    * @param   value ofphoneExtension
    * @return  true if valid
    */
   public boolean setPhoneExtension(String phoneExtension)
   {
      return set(PHONEEXTENSION,phoneExtension);
   }

   /**
    * getter for phone extension
    *
    * @return   value ofphoneExtension
    */
   public String getPhoneExtension()
   {
      return get(PHONEEXTENSION);
   }

   /**
    * setter for date of birth
    *
    * @param   value ofbirthDate
    * @return  true if valid
    */
   public boolean setBirthDate(java.util.Date birthDate)
   {
      return set(BIRTHDATE,birthDate);
   }

   /**
    * getter for date of birth
    *
    * @return   value ofbirthDate
    */
   public java.sql.Date getBirthDate()
   {
      return get(BIRTHDATE);
   }

   /**
    * setter for client status (A = Active, I =Inactive, P = Prospective)
    *
    * @param   value ofstatus
    * @return  true if valid
    */
   public boolean setStatus(String status)
   {
      return set(STATUS,status);
   }

   /**
    * getter for client status (A = Active, I =Inactive, P = Prospective)
    *
    * @return   value ofstatus
    */
   public String getStatus()
   {
      return get(STATUS);
   }

   /**
    * setter for creation date of record
    *
    * @param   value ofcreationDate
    * @return  true if valid
    */
   public boolean setCreationDate(java.util.Date creationDate)
   {
      return set(CREATIONDATE,creationDate);
   }

   /**
    * getter for creation date of record
    *
    * @return   value ofcreationDate
    */
   public java.sql.Timestamp getCreationDate()
   {
      return get(CREATIONDATE);
   }

   /**
    * setter for last modified date of record
    *
    * @param   value ofmodifiedDate
    * @return  true if valid
    */
   public boolean setModifiedDate(java.util.Date modifiedDate)
   {
      return set(MODIFIEDDATE,modifiedDate);
   }

   /**
    * getter for last modified date of record
    *
    * @return   value ofmodifiedDate
    */
   public java.sql.Timestamp getModifiedDate()
   {
      return get(MODIFIEDDATE);
   }

   /**
    *  Validates the record    *  @return table name
    */
   protected String recordName()
   {
      return DB_TABLE_NAME;
   }

   /**
    * Clones the record
    */
   public Object clone()
   {
      ClientContact clone = new ClientContact();
      copyTo(clone);
      return clone;
   }

   /**
    * Returns all fields for internal use
    * @return all fields
    */
   protected Field[] allFields()
   {
	   return ALL_DB_FIELDS;
   }

   /**
    *  Returns all primary keys fields for internal use
    *  @return primary key fields
    */
   protected Field[] primaryKeyFields()
   {
      return PK_DB_FIELDS;
   }

   /**
    *  Returns all primary keys fields for internal use
    *  @return primary key fields
    */
   protected RecordDao dao()
   {
      return DAO;
   }

   /**
    *  Shortcut to DAO method
    *  @return all records
    */
   public static List loadAll(Connection conn) throws SQLException
   {
      return DAO.loadAll(conn);
   }
}


text:
package UAV::Pilot::Logger;
use v5.14;
use Moose::Role;
use UAV::Pilot;
use Log::Log4perl;

my $LOGGER = undef;

sub _logger
{
    my ($class) = @_;
    return $LOGGER if defined $LOGGER;
    UAV::Pilot->init_log;
    return Log::Log4perl->get_logger( $class->_logger_name );
}

sub _logger_name
{
    my ($self) = @_;
    return ref $self;
}

1;
__END__

=head1 NAME

  UAV::Pilot::Logger

=head1 DESCRIPTION

A Moose role for C<UAV::Pilot> classes that want to log things.

Provides the attribute C<_logger>, which returns a C<Log::Log4perl::Logger> for
your object.

Also provides a method C<_logger_name> for fetching the logger name.  This will
be your class's name by default.  Override as you see fit.

=cut


text:
'use strict'

const webpack = require('webpack')
const path = require('path')

const buildModules = [{
  test: /\.js$/,
  loaders: ['react-hot'],
  include: path.join(__dirname, 'ui')
}, {
  test: /\.styl$/,
  loader: 'style-loader!css-loader!stylus-loader'
}]

module.exports = {

  devtool: 'eval-source-map',
  progress: true,
  entry: [
    'webpack-dev-server/client?http://localhost:9090',
    'webpack/hot/dev-server',
    './ui/universe-dev.js'
  ],
  output: {
    libraryTarget: 'commonjs2',
    path: path.join(__dirname, 'dist/ui'),
    filename: 'universe.js',
    publicPath: 'http://localhost:9090/dist/ui/'
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],

  resolve: {
    extensions: [ '', '.js', '.styl' ]
  },

  module: { loaders: buildModules }

}


text:
from hacking import core
import re

wildcard_injection_os_command_re = re.compile(
      r".*?(?:system|popen|Popen).*?(?:chown|chmod|tar|rsync).*?\*")

promiscous_file_perm_oct_re = re.compile(
    r".*chmod\((.*0o{0,1}[0-7][0-7][2367])\)")

promiscous_file_perm_stat_re = re.compile(
    r".*chmod\(.*(stat.S_IWOTH|stat.S_IRWXO).*\)")

@core.flake8ext
def sec_shell_eq_true(logical_line):
    """Check for shell injection vulnerabilities in subprocess calls

    S001
    """
    line_no_sp = logical_line.replace(' ', '')
    if 'shell=True' in line_no_sp and 'Popen' in line_no_sp:
        yield(0, "S001: Security risk: use of shell=True in Popen call.")

@core.flake8ext
def sec_chmod_perms(logical_line):
    """Check for promiscuous file permissions in chmod calls

    S002
    """
    re_oct_check = promiscous_file_perm_oct_re.match(logical_line)
    re_stat_check = promiscous_file_perm_stat_re.match(logical_line)
    if re_oct_check:
        yield (0, "S002: Chmod with dangerous file permissions: " +
               re_oct_check.group() + ".")
    if re_stat_check:
        yield (0, "S002: Chmod with dangerous file permissions: " +
               re_stat_check.group() + ".")

@core.flake8ext
def hacking_creating_temp_file_or_dir(logical_line):
    """Check for creating temp file or dir

    S004
    """
    if 'mktemp' in logical_line:
        yield (0, "S004: Creating temporary file or directory")

@core.flake8ext
def hacking_using_md5_hash_alg(logical_line):
    """Check for use of md5 hash algorithm

    S005
    """
    if 'md5' in logical_line.lower():
        yield (0, "S005: use of md5 hash algorithm not recommended. Consider using Sha1 or Sha256")

@core.flake8ext
def hacking_no_pickle(logical_line):
    """Check for use of pickle

    S006
    """
    if 'import pickle' in logical_line:
        yield (0, "S006: use of pickle not allowed")

@core.flake8ext
def hacking_no_inline_passwords(logical_line):
    """
    S007
    Check for default passwords, or where not: password='%s'
    """
    blank = re.compile(r".*password\s*=\s*['\"]['\"].*")
    default = re.compile(r".*password\s*=\s*['\"](?!%s)")
    if not blank.match(logical_line) and default.match(logical_line):
        yield(0, "S007: use of default password is not allowed")

@core.flake8ext
def sec_wildcard_injection(logical_line, physical_line):
    """Check for wildcard injection vulnerabilities - OS commands with
    unexpected wildcard expansion behavior.  Please see link:
    http://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt

    S008
    """
    line_no_sp = physical_line.replace(' ', '')
    res = wildcard_injection_os_command_re.match(line_no_sp)
    if res:
        yield (0, "S008: Wildcard injection vulnerability with OS command")

@core.flake8ext
def hacking_service_binding_all_interfaces(logical_line, physical_line):
    """Check for use of pickle

    S009
    """
    #TODO: Check for pecan default bind
    #TODO: Check for eventlet default bind
    if 'eventlet.listen' in logical_line:
        if '0.0.0.0' in physical_line:
            yield (0, "S009: binding to all interfaces")
    if 'host' in logical_line:
        if '0.0.0.0' in physical_line:
            yield (0, "S009: binding to all interfaces")
    if 'bind' in logical_line:
        if '0.0.0.0' in physical_line:
            yield (0, "S009: binding to all interfaces")

@core.flake8ext
def hacking_check_for_bad_ctypes(logical_line, physical_line, lines):
    """Check for use of bad C functions with bad ctypes

    S013
    """
    banned_functions = ['strcpy(', 'strlen(', 'strcmp(', 'strcmp('
                        'strcat(', 'strdup(', 'sprintf(',
                        'wcscpy(', 'wcslen(', ' gets(', '.gets(']

    for func in banned_functions:
        if func in physical_line:
            for line in lines:
                if 'ctypes' in line:
                    yield (0, "S013: Bad C Function: %s" % func)

@core.flake8ext
def hacking_check_vulnerable_ssl(logical_line):
    """
    Check for vulnerable SSL
    """
    vuln_protos = ['PROTOCOL_SSLv2', 'PROTOCOL_SSLv23', 'PROTOCOL_SSLv3']
    for proto in vuln_protos:
        if proto in logical_line:
            yield(0, "S014: Vulnerable SSL Protocol")


text:
public interface Interface
{
	public String getString();
	public Integer getInteger();
	public int getPrimitiveInt();
	public boolean getPrimitiveBool();
	public Object getNull();
}


text:
package fpgatidbits.SimUtils

import Chisel._
import fpgatidbits.dma._

class HighLatencyMemParams(
  val depth: Int,
  val numPorts: Int,
  val dataWidth: Int,
  val addrWidth: Int,
  val idWidth: Int,
  val latency: Int
) {

  override def clone = {
    new HighLatencyMemParams( depth, numPorts, dataWidth, addrWidth,
                              idWidth, latency).asInstanceOf[this.type]
  }

  def toMemReqParams() = {
    new MemReqParams(addrWidth, dataWidth, idWidth, 1)
  }
}

class HighLatencyMem(val p: HighLatencyMemParams) extends Module {
  val pReq = p.toMemReqParams()
  val reqType = new GenericMemoryRequest(pReq)
  val rspType = new GenericMemoryResponse(pReq)

  val io = new Bundle {
    // dedicated port for testbench reads/writes
    val memAddr = UInt(INPUT, p.addrWidth)
    val memWriteEn = Bool(INPUT)
    val memWriteData = UInt(INPUT, p.dataWidth)
    val memReadData = UInt(OUTPUT, p.dataWidth)
    // ports for accelerator accesss
    val memPort = Vec.fill(p.numPorts) {new GenericMemorySlavePort(pReq)}
  }

  // the memory
  val mem = Mem(UInt(width = p.dataWidth),  p.depth)
  val memUnitBytes = UInt(p.dataWidth/8)

  // testbench memory access
  def addrToWord(x: UInt) = {x >> UInt(log2Up(p.dataWidth/8))}
  val memWord = addrToWord(io.memAddr)
  io.memReadData := mem(memWord)

  when (io.memWriteEn) {mem(memWord) := io.memWriteData}

  // add lateny between a producer-consumer pair using 2-deep queues
  def addLatency[T <: Data](n: Int, prod: DecoupledIO[T]): DecoupledIO[T] = {
    if(n == 1) {
      return Queue(prod, 2)
    } else {
      return addLatency(n-1, Queue(prod, 2))
    }
  }

  // accelerator memory access ports
  // one FSM per port, rather simple, but supports bursts
  for(i <- 0 until p.numPorts) {
    // reads
    val sWaitRd :: sRead :: Nil = Enum(UInt(), 2)
    val regStateRead = Reg(init = UInt(sWaitRd))
    val regReadRequest = Reg(init = GenericMemoryRequest(pReq))

    val accmp = io.memPort(i)
    val accRdReq = addLatency(p.latency, accmp.memRdReq)
    val accRdRsp = accmp.memRdRsp

    accRdReq.ready := Bool(false)
    accRdRsp.valid := Bool(false)
    accRdRsp.bits.channelID := regReadRequest.channelID
    accRdRsp.bits.metaData := UInt(0)
    accRdRsp.bits.isWrite := Bool(false)
    accRdRsp.bits.isLast := Bool(false)
    accRdRsp.bits.readData := mem(addrToWord(regReadRequest.addr))

    switch(regStateRead) {
      is(sWaitRd) {
        accRdReq.ready := Bool(true)
        when (accRdReq.valid) {
          regReadRequest := accRdReq.bits
          regStateRead := sRead
        }
      }

      is(sRead) {
        when(regReadRequest.numBytes === UInt(0)) {
          // prefetch the read request if possible to minimize waiting
          accRdReq.ready := Bool(true)
          when (accRdReq.valid) {
            regReadRequest := accRdReq.bits
            // stay in this state and continue processing
          } .otherwise {regStateRead := sWaitRd}
        }
        .otherwise {
          accRdRsp.valid := Bool(true)
          accRdRsp.bits.isLast := (regReadRequest.numBytes === memUnitBytes)
          when (accRdRsp.ready) {
            regReadRequest.numBytes := regReadRequest.numBytes - memUnitBytes
            regReadRequest.addr := regReadRequest.addr + UInt(memUnitBytes)

            // was this the last beat of burst transferred?
            when(regReadRequest.numBytes === memUnitBytes) {
              // prefetch the read request if possible to minimize waiting
              accRdReq.ready := Bool(true)
              when (accRdReq.valid) {
                regReadRequest := accRdReq.bits
                // stay in this state and continue processing
              }
            }
          }
        }
      }
    }

    // writes
    val sWaitWr :: sWrite :: Nil = Enum(UInt(), 2)
    val regStateWrite = Reg(init = UInt(sWaitWr))
    val regWriteRequest = Reg(init = GenericMemoryRequest(pReq))
    // write data queue to avoid deadlocks (state machine expects rspQ and data
    // available simultaneously)
    val wrDatQ = Module(new Queue(UInt(width = p.dataWidth), 16)).io
    wrDatQ.enq <> accmp.memWrDat

    // queue on write response port (to avoid combinational loops)
    val wrRspQ = Module(new Queue(GenericMemoryResponse(pReq), 16)).io
    wrRspQ.deq <> accmp.memWrRsp

    val accWrReq = addLatency(10, accmp.memWrReq)

    accWrReq.ready := Bool(false)
    wrDatQ.deq.ready := Bool(false)
    wrRspQ.enq.valid := Bool(false)
    wrRspQ.enq.bits.driveDefaults()
    wrRspQ.enq.bits.channelID := regWriteRequest.channelID

    switch(regStateWrite) {
      is(sWaitWr) {
        accWrReq.ready := Bool(true)
        when(accWrReq.valid) {
          regWriteRequest := accWrReq.bits
          regStateWrite := sWrite
        }
      }

      is(sWrite) {
        when(regWriteRequest.numBytes === UInt(0)) {regStateWrite := sWaitWr}
        .otherwise {
          when(wrRspQ.enq.ready && wrDatQ.deq.valid) {
            when(regWriteRequest.numBytes === memUnitBytes) {
              wrRspQ.enq.valid := Bool(true)
            }
            wrDatQ.deq.ready := Bool(true)
            mem(addrToWord(regWriteRequest.addr)) := wrDatQ.deq.bits
            regWriteRequest.numBytes := regWriteRequest.numBytes - memUnitBytes
            regWriteRequest.addr := regWriteRequest.addr + UInt(memUnitBytes)
          }
        }
      }
    }
  }
}


text:
package test.IDao;

import test.domain.DynamicList;

public interface DynamicListMapper {
    int insert(DynamicList record);

    int insertSelective(DynamicList record);
}


text:
section  img {

	width: 250px;
	height:  250px;
  margin-left: auto;
  margin-right: auto;
  display: block;
}

#mainname{

	font-size: 40px;

}
.check{
  color:white;
  border:3px solid white;
  border-radius: 20px;
}

/* 탑버튼 */
#toTop { z-index:1030; width: 100px; border: 2px solid #f7f7f7; background: #f7f7f7; text-align: center; position: fixed; bottom: 10px; right: 10px; cursor: pointer; display: none; color: #333; opacity: 0.6; filter: alpha(opacity=60); -webkit-border-radius: 30px; -moz-border-radius: 30px; -o-border-radius: 30px; border-radius: 20px; -webkit-transition: all .25s linear; -moz-transition: all .25s linear; -o-transition: all .25s linear; transition: all .25s linear; padding: 5px; } #toTop:hover { background: #b3b3b3; border: 2px solid #b3b3b3; }


text:
title: Smiley Face Birthday Candle
propCategories: [props]
images: [main.jpg]
purchaseLink: http://www.walmart.com/ip/Smiley-Face-Pick-Birthday-Candles-6pk/35760684
---


text:
// -----------------------------------------------------------------------
// <copyright file="IEntity.cs" company="">
// Copyright 2016 Alexander Soffronow Pagonidis
// </copyright>
// -----------------------------------------------------------------------

namespace QDMS
{
    public interface IEntity
    {
        int ID { get; set; }
    }
}


text:
namespace FBCore.Common.Disk
{
    /// <summary>
    /// Any class that uses a lot of disk space and should implement this interface.
    /// </summary>
    public interface IDiskTrimmable
    {
        /// <summary>
        /// Called when there is very little disk space left.
        /// </summary>
        void TrimToMinimum();

        /// <summary>
        /// Called when there is almost no disk space left and the app is likely to crash soon.
        /// </summary>
        void TrimToNothing();
    }
}


text:
using LucidOcean.MultiChain.Exceptions;
using LucidOcean.MultiChain.Response;
using LucidOcean.MultiChain.Util;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MultiChainTests;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace LucidOcean.MultiChain
{
    [TestClass]
    public class AssetTests
    {
        private MultiChainClient _Client = null;

        [TestInitialize]
        public void Init()
        {
            _Client = new MultiChainClient(TestSettings.Connection);
        }

        [TestMethod]
        public void ListAssetsAsync()
        {
            JsonRpcResponse<List<AssetResponse>> response = null;
            Task.Run(async () =>
            {
                response = await _Client.Asset.ListAssetsAsync();
            }).GetAwaiter().GetResult();

            ResponseLogger<List<AssetResponse>>.Log(response);
        }

        [TestMethod]
        public void ListAssetsFilterAsync()
        {
            JsonRpcResponse<List<AssetResponse>> response = null;
            Task.Run(async () =>
            {
                response = await _Client.Asset.ListAssetsAsync("Asset1",true);
            }).GetAwaiter().GetResult();

            ResponseLogger<List<AssetResponse>>.Log(response);
        }

        [TestMethod]
        public void GetTotalBalancesAsync()
        {
            JsonRpcResponse<List<AssetBalanceResponse>> response = null;
            Task.Run(async () =>
            {
                response = await _Client.Wallet.GetTotalBalancesAsync();
            }).GetAwaiter().GetResult();

            ResponseLogger<List<AssetBalanceResponse>>.Log(response);
        }

        [TestMethod]
        public void IssueAsync()
        {
            MultiChainTests.Mocks.Asset asset = new MultiChainTests.Mocks.Asset();
            asset.Title = "Asset1";
            asset.Description = "An Asset added by a unit test";

            JsonRpcResponse<string> response = null;
            Task.Run(async () =>
            {
                try {
                    response = await _Client.Asset.IssueAsync(TestSettings.FromAddress, new { name = asset.Title, open = true }, 10, 1, asset);
                    await _Client.Asset.SubscribeAsync(response.Result, true);
                }
                catch (JsonRpcException ex){
                    if (ex.Error.Code != -705) { throw ex; }
                }

            }).GetAwaiter().GetResult();

            ResponseLogger<string>.Log(response);
        }

        [TestMethod]
        public void GetAssetTransactionAsync()
        {
            ResponseLogger<string>.Log("This depends on the asset being created by Issue Command. Run Issue first.");

            JsonRpcResponse<ListAssetTransactionsResponse> response = null;
            Task.Run(async () =>
            {
                JsonRpcResponse<List<ListAssetTransactionsResponse>> r = await _Client.Asset.ListAssetTransactions("Asset1", true);
                response = await _Client.Asset.GetAssetTransactionAsync("Asset1", r.Result[0].TxId);
            }).GetAwaiter().GetResult();

            ResponseLogger<ListAssetTransactionsResponse>.Log(response);
        }
    }
}


text:
<?php
/**
 *
 * @package Collinsharper_Canpost
 *
 * @author Maxim Nulman
 */
class Collinsharper_Canpost_Block_Adminhtml_Sales_Order_Shipment_Create_Items extends Mage_Adminhtml_Block_Sales_Order_Shipment_Create_Items
{

    /**
     * Prepare child blocks
     */
    protected function _beforeToHtml()
    {
        $onclick = 'submitShipment(this);console.log("changed");';
        if (version_compare(Mage::getVersion(), '1.6.0.0', '<')) {
            $onclick = 'if(editForm.submit()) disableElements(\'submit-button\');';
        }

        $this->setChild(
            'submit_button',
            $this->getLayout()->createBlock('adminhtml/widget_button')->setData(array(
                'label'     => Mage::helper('chcanpost2module')->__('Approve Shipment'),
                'class'     => 'save submit-button',
                'onclick'   => 'submitShipment(this);',
            ))
        );

    }

}