<commit_before>import { pluralize } from '../utils/inflector';
import extend from '../utils/extend';
import Association from './associations/association';

/*
  The Model class. Notes:

  - We need to pass in type, because models are created with
    .extend and anonymous functions, so you cannot use
    reflection to find the name of the constructor.
*/

/*
  Constructor
*/
var Model = function(schema, type, attrs, fks) {
  if (!schema) { throw 'Mirage: A model requires a schema'; }
  if (!type) { throw 'Mirage: A model requires a type'; }

  this.toString = function() {
    return 'model:' + type;
  };

  this._schema = schema;
  this.type = type;
  this.fks = fks || [];
  attrs = attrs || {};

  this._setupAttrs(attrs);
  this._setupRelationships(attrs);

  return this;
};

/*
  Create or save the model
*/
Model.prototype.save = function() {
  var collection = pluralize(this.type);

  if (this.isNew()) {
    // Update the attrs with the db response
    this.attrs = this._schema.db[collection].insert(this.attrs);

    // Ensure the id getter/setter is set
    this._definePlainAttribute('id');

  } else {
    this._schema.db[collection].update(this.attrs.id, this.attrs);
  }

  // Update associated children
  this._saveAssociations();

  return this;
};

/*
  Update the db record.
*/
Model.prototype.update = function(key, val) {
  var _this = this;
  var attrs;
  if (key == null) {return this;}

  if (typeof key === 'object') {
    attrs = key;
  } else {
    (attrs = {})[key] = val;
  }

  Object.keys(attrs).forEach(function(attr) {
    _this[attr] = attrs[attr];
  });

  this.save();

  return this;
};

/*
  Destroy the db record.
*/
Model.prototype.destroy = function() {
  var collection = pluralize(this.type);
  this._schema.db[collection].remove(this.attrs.id);
};

/*
  Is the model new?
*/
Model.prototype.isNew = function() {
  return this.attrs.id === undefined || this.attrs.id === null;
};

Model.prototype.isSaved = function() {
  return this.attrs.id !== undefined && this.attrs.id !== null;
};

/*
  Reload data from the db
*/
Model.prototype.reload = function() {
  var _this = this;
  var collection = pluralize(this.type);
  var attrs = this._schema.db[collection].find(this.id);

  Object.keys(attrs)
    .filter(function(attr) { return attr !== 'id'; })
    .forEach(function(attr) {
      _this[attr] = attrs[attr];
    });
};

Model.prototype.addAssociationMethods = function(schema) {
  var _this = this;

  this.hasManyAssociations = {};       // a registry of the model's hasMany associations. Key is key from model definition, value is association instance itself
  this.belongsToAssociations = {};     // a registry of the model's belongsTo associations. Key is key from model definition, value is association instance itself
  this.associationKeys = [];    // ex: address.user, user.addresses
  this.associationIdKeys = [];  // ex: address.user_id, user.address_ids. may or may not be a fk.

  Object.keys(this.constructor).forEach(function(attr) {
    if (_this.constructor[attr] instanceof Association) {
      var association = _this.constructor[attr];
      association.addMethodsToModel(_this, attr, schema);
    }
  });
};

// Private
/*
  model.attrs represents the persistable attributes, i.e. your db
  table fields.
*/
Model.prototype._setupAttrs = function(attrs) {
  var _this = this;

  // Filter out association keys
  var hash = Object.keys(attrs).reduce(function(memo, attr) {
    if (_this.associationKeys.indexOf(attr) === -1 && _this.associationIdKeys.indexOf(attr) === -1) {
      memo[attr] = attrs[attr];
    }

    return memo;
  }, {});

  // Ensure fks are there
  this.fks.map(function(fk) {
    hash[fk] = attrs[fk] || null;
  });

  this.attrs = hash;

  // define plain getter/setters for non-association keys
  Object.keys(hash).forEach(function(attr) {
    if (_this.associationKeys.indexOf(attr) === -1 && _this.associationIdKeys.indexOf(attr) === -1) {
      _this._definePlainAttribute(attr);
    }
  });
};

/*
  Define getter/setter for a plain attribute
*/
Model.prototype._definePlainAttribute = function(attr) {
  if (this[attr] !== undefined) { return; }

  // Ensure the attribute is on the attrs hash
  if (!this.attrs.hasOwnProperty(attr)) {
    this.attrs[attr] = null;
  }

  // Define the getter/setter
  Object.defineProperty(this, attr, {
    get: function () { return this.attrs[attr]; },
    set: function (val) { this.attrs[attr] = val; return this; },
  });
};

Model.prototype._setupRelationships = function(attrs) {
  var _this = this;

  // Only want association keys and fks
  var hash = Object.keys(attrs).reduce(function(memo, attr) {
    if (_this.associationKeys.indexOf(attr) > -1 || _this.associationIdKeys.indexOf(attr) > -1 || _this.fks.indexOf(attr) > -1) {
      memo[attr] = attrs[attr];
    }

    return memo;
  }, {});

  Object.keys(hash).forEach(function(attr) {
    _this[attr] = hash[attr];
  });
};

Model.prototype._saveAssociations = function() {
  Object.keys(this.belongsToAssociations).forEach(key => {
    var association = this.belongsToAssociations[key];
    var parent = this[key];
    if (parent.isNew()) {
      var fk = association.getForeignKey();
      parent.save();
      this.update(fk, parent.id);
    }
  });

  Object.keys(this.hasManyAssociations).forEach(key => {
    var association = this.hasManyAssociations[key];
    var children = this[key];
    children.update(association.getForeignKey(), this.id);
  });
};

Model.extend = extend.bind(Model, null);

Model.toString = function() {
  return 'model';
};

export default Model;
<commit_msg>ES6ify Model<commit_after>import { pluralize } from '../utils/inflector';
import extend from '../utils/extend';
import Association from './associations/association';

/*
  The Model class. Notes:

  - We need to pass in type, because models are created with
    .extend and anonymous functions, so you cannot use
    reflection to find the name of the constructor.
*/

/*
  Constructor
*/
class Model {

  constructor(schema, type, attrs, fks) {
    if (!schema) { throw 'Mirage: A model requires a schema'; }
    if (!type) { throw 'Mirage: A model requires a type'; }

    this.toString = function() {
      return 'model:' + type;
    };

    this._schema = schema;
    this.type = type;
    this.fks = fks || [];
    attrs = attrs || {};

    this._setupAttrs(attrs);
    this._setupRelationships(attrs);

    return this;
  }

  /*
    Create or save the model
  */
  save() {
    var collection = pluralize(this.type);

    if (this.isNew()) {
      // Update the attrs with the db response
      this.attrs = this._schema.db[collection].insert(this.attrs);

      // Ensure the id getter/setter is set
      this._definePlainAttribute('id');

    } else {
      this._schema.db[collection].update(this.attrs.id, this.attrs);
    }

    // Update associated children
    this._saveAssociations();

    return this;
  }

  /*
    Update the db record
  */
  update(key, val) {
    var _this = this;
    var attrs;
    if (key == null) {return this;}

    if (typeof key === 'object') {
      attrs = key;
    } else {
      (attrs = {})[key] = val;
    }

    Object.keys(attrs).forEach(function(attr) {
      _this[attr] = attrs[attr];
    });

    this.save();

    return this;
  }

  /*
    Destroy the db record
  */
  destroy() {
    var collection = pluralize(this.type);
    this._schema.db[collection].remove(this.attrs.id);
  }

  isNew() {
    return this.attrs.id === undefined || this.attrs.id === null;
  }

  isSaved() {
    return this.attrs.id !== undefined && this.attrs.id !== null;
  }

  /*
    Reload data from the db
  */
  reload() {
    var _this = this;
    var collection = pluralize(this.type);
    var attrs = this._schema.db[collection].find(this.id);

    Object.keys(attrs)
      .filter(function(attr) { return attr !== 'id'; })
      .forEach(function(attr) {
        _this[attr] = attrs[attr];
      });
  }

  // TODO: this is really model constructor logic...I think?
  addAssociationMethods(schema) {
    var _this = this;

    this.hasManyAssociations = {};       // a registry of the model's hasMany associations. Key is key from model definition, value is association instance itself
    this.belongsToAssociations = {};     // a registry of the model's belongsTo associations. Key is key from model definition, value is association instance itself
    this.associationKeys = [];    // ex: address.user, user.addresses
    this.associationIdKeys = [];  // ex: address.user_id, user.address_ids. may or may not be a fk.

    Object.keys(this.constructor).forEach(function(attr) {
      if (_this.constructor[attr] instanceof Association) {
        var association = _this.constructor[attr];
        association.addMethodsToModel(_this, attr, schema);
      }
    });
  }

  // Private
  /*
    model.attrs represents the persistable attributes, i.e. your db
    table fields.
  */
  _setupAttrs(attrs) {
    var _this = this;

    // Filter out association keys
    var hash = Object.keys(attrs).reduce(function(memo, attr) {
      if (_this.associationKeys.indexOf(attr) === -1 && _this.associationIdKeys.indexOf(attr) === -1) {
        memo[attr] = attrs[attr];
      }

      return memo;
    }, {});

    // Ensure fks are there
    this.fks.map(function(fk) {
      hash[fk] = attrs[fk] || null;
    });

    this.attrs = hash;

    // define plain getter/setters for non-association keys
    Object.keys(hash).forEach(function(attr) {
      if (_this.associationKeys.indexOf(attr) === -1 && _this.associationIdKeys.indexOf(attr) === -1) {
        _this._definePlainAttribute(attr);
      }
    });
  }

  /*
    Define getter/setter for a plain attribute
  */
  _definePlainAttribute(attr) {
    if (this[attr] !== undefined) { return; }

    // Ensure the attribute is on the attrs hash
    if (!this.attrs.hasOwnProperty(attr)) {
      this.attrs[attr] = null;
    }

    // Define the getter/setter
    Object.defineProperty(this, attr, {
      get: function () { return this.attrs[attr]; },
      set: function (val) { this.attrs[attr] = val; return this; },
    });
  }

  _setupRelationships(attrs) {
    var _this = this;

    // Only want association keys and fks
    var hash = Object.keys(attrs).reduce(function(memo, attr) {
      if (_this.associationKeys.indexOf(attr) > -1 || _this.associationIdKeys.indexOf(attr) > -1 || _this.fks.indexOf(attr) > -1) {
        memo[attr] = attrs[attr];
      }

      return memo;
    }, {});

    Object.keys(hash).forEach(function(attr) {
      _this[attr] = hash[attr];
    });
  }

  _saveAssociations() {
    Object.keys(this.belongsToAssociations).forEach(key => {
      var association = this.belongsToAssociations[key];
      var parent = this[key];
      if (parent.isNew()) {
        var fk = association.getForeignKey();
        parent.save();
        this.update(fk, parent.id);
      }
    });

    Object.keys(this.hasManyAssociations).forEach(key => {
      var association = this.hasManyAssociations[key];
      var children = this[key];
      children.update(association.getForeignKey(), this.id);
    });
  }

  toString() {
    return 'model';
  }
}

Model.extend = extend.bind(Model, null);

export default Model;
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import uniq from 'lodash/uniq';
import flatten from 'lodash/flatten';
import isEqual from 'lodash/isEqual';

// Components
import TableHeader from './header/TableHeader';
import TableContent from './content/TableContent';
import TableFooter from './footer/TableFooter';
import { timingSafeEqual } from 'crypto';

export default class CustomTable extends React.Component {
  /* Property typing */
  static propTypes = {
    actions: PropTypes.object,
    columns: PropTypes.array,
    data: PropTypes.array,
    pagination: PropTypes.object,
    filters: PropTypes.bool,
    sort: PropTypes.object,
    onToggleSelectedRow: PropTypes.func,
    onRowDelete: PropTypes.func
  };

  /* Property default values */
  static defaultProps = {
    data: [],
    columns: [],
    pagination: {
      enabled: true,
      pageSize: 20,
      page: 1,
      total: null
    },
    sort: {},
    actions: {
      show: true,
      list: [
        { name: 'Edit', path: '#' },
        { name: 'Remove', path: '#' }
      ]
    },
    filters: true,
    onToggleSelectedRow: null,
    onRowDelete: null
  };

  /**
   * STATIC METHODS
   * - getColumnKeys
   * - getColumnValues
   * - setTableData
  */
  static getColumnKeys(data) {
    return uniq(flatten(data.map(d => Object.keys(d))));
  }

  static getColumnValues(data) {
    const columnsKeys = CustomTable.getColumnKeys(data);
    const columns = {};
    columnsKeys.forEach((key) => {
      const values = uniq(data.map(d => d[key]))
        .sort((a, b) => a - b)
        .map(d => d && d.toString());
      columns[key] = values;
    });
    return columns;
  }

  static setTableData(props) {
    const { data } = props;
    return {
      data,
      columnValues: CustomTable.getColumnValues(data)
    };
  }

  constructor(props) {
    super(props);

    this.state = {
      pagination: props.pagination,
      sort: props.sort,
      initialSort: props.sort,
      search: {},
      columnQueries: {},
      rowSelection: []
    };

    // Bindings
    this.onChangePage = this.onChangePage.bind(this);
    this.onFilter = this.onFilter.bind(this);
    this.onSort = this.onSort.bind(this);
    this.onSearch = this.onSearch.bind(this);
    this.onRowDelete = this.onRowDelete.bind(this);
    this.onToggleSelectedRow = this.onToggleSelectedRow.bind(this);
  }

  componentWillMount() {
    this.setState(CustomTable.setTableData(this.props), () => {
      this.filter();
    });
  }

  componentWillReceiveProps(nextProps) {
    const currentColumnsKeys = CustomTable.getColumnKeys(this.state.data).sort();
    const nextColumnsKeys = CustomTable.getColumnKeys(nextProps.data).sort();
    this.setState(CustomTable.setTableData(nextProps), () => {
      this.filter();
    });

    if (!isEqual(currentColumnsKeys, nextColumnsKeys)) {
      this.setState({
        ...CustomTable.setTableData(nextProps),
        sort: nextProps.sort,
        search: {},
        columnQueries: {},
        rowSelection: []
      });
    }
  }

  /**
   * UI EVENTS
   * - onToggleSelectedRow
   * - onRowDelete
   * - onFilter
   * - onSort
   * - onChangePage
  */
  onToggleSelectedRow(id) {
    const rowSelection = this.state.rowSelection.slice();
    const index = rowSelection.indexOf(id);

    // Toggle the active dataset
    if (index !== -1) {
      rowSelection.splice(index, 1);
    } else {
      rowSelection.push(id);
    }

    this.setState({ rowSelection }, () => {
      if (this.props.onToggleSelectedRow) {
        this.props.onToggleSelectedRow(this.state.rowSelection);
      }
    });
  }

  onRowDelete(id) {
    const data = this.state.data.slice();
    const index = data.findIndex(row => row.id === id);
    data.splice(index, 1);

    this.setState({
      // Data
      data,
      // Columns
      columnValues: CustomTable.getColumnValues(data)
    }, () => {
      this.filter();
      if (this.props.onRowDelete) {
        this.props.onRowDelete(id);
      }
    });
  }

  onFilter(q) {
    let { columnQueries } = this.state;

    // Let's use null when you select all the values, so whenever you add more points to
    // the map they will be selected because you will remove the filter from the columnQueries
    if (q.value) {
      columnQueries = {
        ...this.state.columnQueries,
        [q.field]: q.value
      };
    } else if (columnQueries[q.field]) {
      delete columnQueries[q.field];
    }

    this.setState({ columnQueries }, () => {
      this.filter();
      // this.onChangePage(0);
    });
  }

  onSort(s) {
    const { sort, initialSort } = this.state;

    // check if we are trying to sort on the same as before, then return to initial sorting
    if (isEqual(s, sort)) {
      this.setState({ sort: initialSort },
        // () => this.onChangePage(0)
      );
    } else {
      const newSortingRule = {
        field: s.field,
        value: s.value
      };
      this.setState({ sort: newSortingRule },
        // () => this.onChangePage(0)
      );
    }
  }

  onSearch(s) {
    const search = {
      field: s.field,
      value: s.value
    };
    this.setState({ search }, () => {
      this.filter();
      this.onChangePage(0);
    });
  }

  onChangePage(page) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        page: page + 1
      }
    });
    this.props.onChangePage(page);
  }

  /**
   * FILTER
   * - filter
  */
  filter() {
    const { columnQueries, search } = this.state;

    const filteredData = this.state.data.filter((row) => {
      let filteredBySearch = true;

      if (search.value) {
        filteredBySearch = row[search.field].toString().toLowerCase()
          .includes(search.value.toString().toLowerCase());
      }

      const filteredByQuery = Object.keys(columnQueries).map(field => columnQueries[field]
        .map(val => row[field].toString().toLowerCase() === val.toString()
          .toLowerCase()).some(match => match)).every(match => match);

      return filteredByQuery && filteredBySearch;
    });

    this.setState({ filteredData });
  }

  render() {
    const { pagination } = this.props;

    return (

        {/* Table */}

          {/* Table header */}
          <TableHeader
            actions={this.props.actions}
            columns={this.props.columns}
            columnValues={this.state.columnValues}
            columnQueries={this.state.columnQueries}
            filteredData={this.state.filteredData}
            filters={this.props.filters}
            sort={this.state.sort}
            onFilter={this.onFilter}
            onSearch={this.onSearch}
            onSort={this.onSort}
          />

          {/* Table content */}

          <TableContent
            {...this.props}
            {...this.state}
            onToggleSelectedRow={this.onToggleSelectedRow}
            onRowDelete={this.onRowDelete}
          />

        {/* Table footer */}
        <TableFooter
          pagination={pagination}
          onChangePage={this.onChangePage}
          showTotalPages
        />

    );
  }
}
<commit_msg>WIP - pages<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import uniq from 'lodash/uniq';
import flatten from 'lodash/flatten';
import isEqual from 'lodash/isEqual';

// Components
import TableHeader from './header/TableHeader';
import TableContent from './content/TableContent';
import TableFooter from './footer/TableFooter';
import { timingSafeEqual } from 'crypto';

export default class CustomTable extends React.Component {
  /* Property typing */
  static propTypes = {
    actions: PropTypes.object,
    columns: PropTypes.array,
    data: PropTypes.array,
    pagination: PropTypes.object,
    filters: PropTypes.bool,
    sort: PropTypes.object,
    onToggleSelectedRow: PropTypes.func,
    onRowDelete: PropTypes.func
  };

  /* Property default values */
  static defaultProps = {
    data: [],
    columns: [],
    pagination: {
      enabled: true,
      pageSize: 20,
      page: 1,
      total: null
    },
    sort: {},
    actions: {
      show: true,
      list: [
        { name: 'Edit', path: '#' },
        { name: 'Remove', path: '#' }
      ]
    },
    filters: true,
    onToggleSelectedRow: null,
    onRowDelete: null
  };

  /**
   * STATIC METHODS
   * - getColumnKeys
   * - getColumnValues
   * - setTableData
  */
  static getColumnKeys(data) {
    return uniq(flatten(data.map(d => Object.keys(d))));
  }

  static getColumnValues(data) {
    const columnsKeys = CustomTable.getColumnKeys(data);
    const columns = {};
    columnsKeys.forEach((key) => {
      const values = uniq(data.map(d => d[key]))
        .sort((a, b) => a - b)
        .map(d => d && d.toString());
      columns[key] = values;
    });
    return columns;
  }

  static setTableData(props) {
    const { data } = props;
    return {
      data,
      columnValues: CustomTable.getColumnValues(data)
    };
  }

  constructor(props) {
    super(props);

    this.state = {
      pagination: props.pagination,
      sort: props.sort,
      initialSort: props.sort,
      search: {},
      columnQueries: {},
      rowSelection: []
    };

    // Bindings
    this.onChangePage = this.onChangePage.bind(this);
    this.onFilter = this.onFilter.bind(this);
    this.onSort = this.onSort.bind(this);
    this.onSearch = this.onSearch.bind(this);
    this.onRowDelete = this.onRowDelete.bind(this);
    this.onToggleSelectedRow = this.onToggleSelectedRow.bind(this);
  }

  componentWillMount() {
    this.setState(CustomTable.setTableData(this.props), () => {
      this.filter();
    });
  }

  componentWillReceiveProps(nextProps) {
    const currentColumnsKeys = CustomTable.getColumnKeys(this.state.data).sort();
    const nextColumnsKeys = CustomTable.getColumnKeys(nextProps.data).sort();
    this.setState(CustomTable.setTableData(nextProps), () => {
      this.filter();
    });

    if (!isEqual(currentColumnsKeys, nextColumnsKeys)) {
      this.setState({
        ...CustomTable.setTableData(nextProps),
        sort: nextProps.sort,
        search: {},
        columnQueries: {},
        rowSelection: []
      });
    }
  }

  /**
   * UI EVENTS
   * - onToggleSelectedRow
   * - onRowDelete
   * - onFilter
   * - onSort
   * - onChangePage
  */
  onToggleSelectedRow(id) {
    const rowSelection = this.state.rowSelection.slice();
    const index = rowSelection.indexOf(id);

    // Toggle the active dataset
    if (index !== -1) {
      rowSelection.splice(index, 1);
    } else {
      rowSelection.push(id);
    }

    this.setState({ rowSelection }, () => {
      if (this.props.onToggleSelectedRow) {
        this.props.onToggleSelectedRow(this.state.rowSelection);
      }
    });
  }

  onRowDelete(id) {
    const data = this.state.data.slice();
    const index = data.findIndex(row => row.id === id);
    data.splice(index, 1);

    this.setState({
      // Data
      data,
      // Columns
      columnValues: CustomTable.getColumnValues(data)
    }, () => {
      this.filter();
      if (this.props.onRowDelete) {
        this.props.onRowDelete(id);
      }
    });
  }

  onFilter(q) {
    let { columnQueries } = this.state;

    // Let's use null when you select all the values, so whenever you add more points to
    // the map they will be selected because you will remove the filter from the columnQueries
    if (q.value) {
      columnQueries = {
        ...this.state.columnQueries,
        [q.field]: q.value
      };
    } else if (columnQueries[q.field]) {
      delete columnQueries[q.field];
    }

    this.setState({ columnQueries }, () => {
      this.filter();
      // this.onChangePage(0);
    });
  }

  onSort(s) {
    const { sort, initialSort } = this.state;

    // check if we are trying to sort on the same as before, then return to initial sorting
    if (isEqual(s, sort)) {
      this.setState({ sort: initialSort },
        // () => this.onChangePage(0)
      );
    } else {
      const newSortingRule = {
        field: s.field,
        value: s.value
      };
      this.setState({ sort: newSortingRule },
        // () => this.onChangePage(0)
      );
    }
  }

  onSearch(s) {
    const search = {
      field: s.field,
      value: s.value
    };
    this.setState({ search }, () => {
      this.filter();
      this.onChangePage(0);
    });
  }

  onChangePage(page) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        page
      }
    });
    this.props.onChangePage(page);
  }

  /**
   * FILTER
   * - filter
  */
  filter() {
    const { columnQueries, search } = this.state;

    const filteredData = this.state.data.filter((row) => {
      let filteredBySearch = true;

      if (search.value) {
        filteredBySearch = row[search.field].toString().toLowerCase()
          .includes(search.value.toString().toLowerCase());
      }

      const filteredByQuery = Object.keys(columnQueries).map(field => columnQueries[field]
        .map(val => row[field].toString().toLowerCase() === val.toString()
          .toLowerCase()).some(match => match)).every(match => match);

      return filteredByQuery && filteredBySearch;
    });

    this.setState({ filteredData });
  }

  render() {
    const { pagination } = this.props;

    return (

        {/* Table */}

          {/* Table header */}
          <TableHeader
            actions={this.props.actions}
            columns={this.props.columns}
            columnValues={this.state.columnValues}
            columnQueries={this.state.columnQueries}
            filteredData={this.state.filteredData}
            filters={this.props.filters}
            sort={this.state.sort}
            onFilter={this.onFilter}
            onSearch={this.onSearch}
            onSort={this.onSort}
          />

          {/* Table content */}

          <TableContent
            {...this.props}
            {...this.state}
            onToggleSelectedRow={this.onToggleSelectedRow}
            onRowDelete={this.onRowDelete}
          />

        {/* Table footer */}
        <TableFooter
          pagination={pagination}
          onChangePage={this.onChangePage}
          showTotalPages
        />

    );
  }
}
<|endoftext|>


<commit_before>// Display DataTables from mysql to HTML
$(document).ready(function() {
                var dataTable = $('#show_divisi').DataTable( {
                    "processing": true,
                    "serverSide": true,
                    "columnDefs":[{
                        "targets": 0,
                        "orderable":false,
                        "searchable":false
                    }],
                    "ajax":{
                        url :"ajax/data_divisi.php",
                        type: "post",
                        error: function(){
                            $(".show_divisi-error").html("");
                            $("#show_divisi").append('

Data Tidak Di temukan

');
                            $("#show_divisi_processing").css("display","none");
                        }
                    }

                } );

                $("#bulkDelete").on('click',function() { // bulk checked
                    var status = this.checked;
                    $(".deleteRow").each( function() {
                        $(this).prop("checked",status);
                    });
                });

                $('#deleteTriger').on("click", function(event){ // triggering delete one by one
                    if( $('.deleteRow:checked').length > 0 ){  // at-least one checkbox checked
                        var ids = [];
                        $('.deleteRow').each(function(){
                            if($(this).is(':checked')) {
                                ids.push($(this).val());
                            }
                        // console.log(ids);
                        });
                        var ids_string = ids.toString();  // array to string conversion
                        // console.log(ids_string);
                        $.ajax({
                            type: "POST",
                            url: "ajax/deleteRecord.php",
                            data: {data_ids:ids_string},
                            success: function(result) {
                                dataTable.draw(); // redrawing datatable
                            },
                            async:false
                        });

                    }
                });
            } );

// Add Record from database script
function addRecord() {
    var divisi_name = $("#divisi_name").val();

    $.post("ajax/addRecords.php",{
        divisi_name: divisi_name
    }, function (data, status){
        $("#modalLayout").modal("hide");

        readRecord();

        $("#divisi_name").val("");
    });
}

// Reload DataTables After insert Form
function readRecord() {
    var table = $('#show_divisi').DataTable();

    table.ajax.reload(function (json){
        $('#add').val( json.lastInput );
    });
}

//Get Detail record row datatables
function getDetailDivisi(id_divisi){
   // alert(id_divisi);
   $("#user_id_hidden").val(id_divisi);
   $.post("ajax/readUserDetail.php", {
        id_divisi: id_divisi
   },
    function (data, status){
        // parser JSON data
        var divisi = JSON.parse(data);
        $("#divisi_name_update").val(divisi.divisi_name);
    }
   );
$("#update_user_modal").modal("show");

}

// update Record row datatables
function updateDivisi(){

    // get value to modal
    var divisi_name = $("#divisi_name_update").val();
    // get hidden id value
    var id_divisi = $("#user_id_hidden").val();

    // send to proses update
    $.post("ajax/updateDivisiName.php",{
        id_divisi: id_divisi,
        divisi_name: divisi_name
    },
    function (data, status){
        $("#update_user_modal").modal("hide");
        readRecord();
    }
    );
}

$(document).ready(function () {

    readRecord();
});

// TO script.js and ajax user.html<commit_msg>edit file script.js<commit_after>// Display DataTables from mysql to HTML
$(document).ready(function() {
                var dataTable = $('#show_divisi').DataTable( {
                    "processing": true,
                    "serverSide": true,
                    "columnDefs":[{
                        "targets": 0,
                        "orderable":false,
                        "searchable":false
                    }],
                    "ajax":{
                        url :"ajax/data_divisi.php",
                        type: "post",
                        error: function(){
                            $(".show_divisi-error").html("");
                            $("#show_divisi").append('

Data Tidak Di temukan

');
                            $("#show_divisi_processing").css("display","none");
                        }
                    }

                } );

                $("#bulkDelete").on('click',function() { // bulk checked
                    var status = this.checked;
                    $(".deleteRow").each( function() {
                        $(this).prop("checked",status);
                    });
                });

                $('#deleteTriger').on("click", function(event){ // triggering delete one by one
                    if( $('.deleteRow:checked').length > 0 ){  // at-least one checkbox checked
                        var ids = [];
                        $('.deleteRow').each(function(){
                            if($(this).is(':checked')) {
                                ids.push($(this).val());
                            }
                        // console.log(ids);
                        });
                        var ids_string = ids.toString();  // array to string conversion
                        // console.log(ids_string);
                        $.ajax({
                            type: "POST",
                            url: "ajax/deleteRecord.php",
                            data: {data_ids:ids_string},
                            success: function(result) {
                                dataTable.draw(); // redrawing datatable
                            },
                            async:false
                        });

                    }
                });
            } );

// Add Record from database script
function addRecord() {
    var divisi_name = $("#divisi_name").val();

    $.post("ajax/addRecords.php",{
        divisi_name: divisi_name
    }, function (data, status){
        $("#modalLayout").modal("hide");

        readRecord();

        $("#divisi_name").val("");
    });
}

// Reload DataTables After insert Form
function readRecord() {
    var table = $('#show_divisi').DataTable();

    table.ajax.reload(function (json){
        $('#add').val( json.lastInput );
    });
}

//Get Detail record row datatables
function getDetailDivisi(id_divisi){
   // alert(id_divisi);
   $("#user_id_hidden").val(id_divisi);
   $.post("ajax/readUserDetail.php", {
        id_divisi: id_divisi
   },
    function (data, status){
        // parser JSON data
        var divisi = JSON.parse(data);
        $("#divisi_name_update").val(divisi.divisi_name);
    }
   );
$("#update_user_modal").modal("show");

}

// update Record row datatables
function updateDivisi(){

    // get value to modal
    var divisi_name = $("#divisi_name_update").val();
    // get hidden id value
    var id_divisi = $("#user_id_hidden").val();

    // send to proses update
    $.post("ajax/updateDivisiName.php",{
        id_divisi: id_divisi,
        divisi_name: divisi_name
    },
    function (data, status){
        $("#update_user_modal").modal("hide");
        readRecord();
    }
    );
}

$(document).ready(function () {

    readRecord();
});

// TO script.js and ajax user.html
$(document).ready(function(){
    var table_user = $("#show_user").DataTable({
        "processing": true,
        "serverSide": true,
        "columnDefs": [{
            "targets": 0,
            "orderable": false,
            "searchable": false
        }],
        "ajax": {
            url: "ajax/data_user.php",
            type: "post",
            error: function(){
                $(".show_user-error").html("");
                $("#show_user").append('

Data Tidak ditemukan

')
            }
        }
    })
});<|endoftext|>


<commit_before>// ==UserScript==
// @name         Ads DOM Remover
// @namespace    sagiegurari
// @version      0.89
// @author       Sagie Gur-Ari
// @description  Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @match        http://www.ynet.co.il/home/*
// @match        http://www.ynet.co.il/articles/*
// @match        http://www.mynet.co.il/articles/*
// @match        http://www.calcalist.co.il/*
// @match        http://www.globes.co.il/*
// @match        https://sourceforge.net/projects/*/download*
// @match        http://subscenter.cinemast.com/*
// @match        http://www.subscenter.co/*
// @match        http://www.subscenter.org/*
// @match        https://*.wikipedia.org/*
// @require      https://code.jquery.com/jquery-2.2.2.min.js
// @require      https://greasyfork.org/scripts/18490-ads-dom-remover-runner/code/Ads%20DOM%20Remover%20Runner.js?version=123541
// @grant        none
// @license      MIT License
// ==/UserScript==

(function run($, runner) {
    'use strict';

    var selectorDefinitions = {
        ynet: [
            '#colorbox',
            '#cboxOverlay',
            '#ads.premium',
            '#articleLayoutrightsidtable',
            '#google_image_div',
            'img[src*="dynamicyield"]',
            'div.MSCmainContent',
            '[id*="arketingCarouse"]',
            '[id*="arketingRecommended"]',
            '.mainVerticalArticleSharingLinks',
            '.OUTBRAIN',
            '.topBannerWrap',
            '.block.B3 .B3.ghcite.dyother.dyMonitor div',
            '.bigdealhomepage',
            '#ww6s_Main',
            '.buyandsavedy',
            '.area.footer.ghcite',
            '.hdr_set_homepage',
            '#c1_Hor',
            '#c2_Hor',
            '#c3_Hor',
            '#c4_Hor',
            '#c5_Hor',
            '#c6_Hor',
            '.homepagevideo-x6',
            '.buyandsave',
            '.general-image',
            '.PhotoArticlesTalkbacks',
            '[name="ExternalWebpageIframe"]',
            '#PROCOIL_SearchForm',
            '#magazines1024',
            '[id^="promo_"]',
            '[id^="ads."]',
            '.main_search_radio',
            'tr td [id^="ads."]',
            '.art-action-wrp',
            '.header-user-profile',
            '.left-art-content',
            {
                selector: '.homepagelitevideo',
                fineTuneSelector: function ($element) {
                    return $element.parent().parent();
                }
            },
            {
                selector: 'iframe',
                filter: function ($element) {
                    return !$element.parent().hasClass('news_ticker_iframe');
                }
            },
            {
                selector: 'div.B2b.block div',
                pre: function ($element) {
                    $element.parent().css({
                        height: '1px'
                    });
                }
            }
        ],
        globes: [
            '#chromeWindow',
            {
                selector: 'iframe',
                filter: function ($element) {
                    var id = $element.attr('id');
                    var src = $element.attr('src') || '';

                    return (id !== 'GlobalFinanceData_home') && (src.indexOf('/news/') !== -1);
                }
            }
        ],
        sourceforge: [
            '#content-for-adblock'
        ],
        subscenter: [
            '.weekBottom',
            '.reviewsWindow',
            '#banner_cinemast',
            '.bottomMenu',
            'footer',
            '#paypal',
            '#aboveSite',
            {
                selector: '#subtitles_list a[href="/he/contactus/"]',
                fineTuneSelector: function ($element) {
                    return $element.parent();
                }
            }
        ],
        wikipedia: [
            '#frbanner',
            '#wlm-banner',
            '.frbanner'
        ]
    };

    [
        '#dcPremiumRightImg',
        '.boulevard',
        '#multiarticles-9',
        '#multiarticles-12',
        '#multiarticles-13',
        '#multiarticles-14',
        '#multiarticles-15',
        '#multiarticles-16',
        '.CdaMostViews',
        '.CdaCalcalistToday',
        '.CdaRecomendedMovies',
        '#SpecialBuilder1280',
        '.cdaFooter1280'
    ].forEach(function addSelector(selector) {
        selectorDefinitions.ynet.push({
            selector: selector,
            fineTuneSelector: function ($element) {
                return $element.parent();
            }
        });
    });

    Object.keys(selectorDefinitions).forEach(function (id) {
        selectorDefinitions[id] = {
            id: id,
            selectors: selectorDefinitions[id]
        };
    });

    runner($, {
        getSelectors: function (hostName) {
            var selectors;
            if (hostName.indexOf('globes') !== -1) {
                selectors = selectorDefinitions.globes;
            } else if (hostName.indexOf('sourceforge.net') !== -1) {
                selectors = selectorDefinitions.sourceforge;
            } else if (hostName.indexOf('subscenter') !== -1) {
                selectors = selectorDefinitions.subscenter;
            } else if (hostName.indexOf('wikipedia.org') !== -1) {
                selectors = selectorDefinitions.wikipedia;
            } else { //ynet/calcalist
                selectors = selectorDefinitions.ynet;
            }

            return selectors;
        }
    });
}(window.jQuery.noConflict(true), window.adrRunner));
<commit_msg>more selectors<commit_after>// ==UserScript==
// @name         Ads DOM Remover
// @namespace    sagiegurari
// @version      0.90
// @author       Sagie Gur-Ari
// @description  Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @match        http://www.ynet.co.il/home/*
// @match        http://www.ynet.co.il/articles/*
// @match        http://www.mynet.co.il/articles/*
// @match        http://www.calcalist.co.il/*
// @match        http://www.globes.co.il/*
// @match        https://sourceforge.net/projects/*/download*
// @match        http://subscenter.cinemast.com/*
// @match        http://www.subscenter.co/*
// @match        http://www.subscenter.org/*
// @match        https://*.wikipedia.org/*
// @require      https://code.jquery.com/jquery-2.2.2.min.js
// @require      https://greasyfork.org/scripts/18490-ads-dom-remover-runner/code/Ads%20DOM%20Remover%20Runner.js?version=123541
// @grant        none
// @license      MIT License
// ==/UserScript==

(function run($, runner) {
    'use strict';

    var selectorDefinitions = {
        ynet: [
            '#colorbox',
            '#cboxOverlay',
            '#ads.premium',
            '#articleLayoutrightsidtable',
            '#google_image_div',
            'img[src*="dynamicyield"]',
            'div.MSCmainContent',
            '[id*="arketingCarouse"]',
            '[id*="arketingRecommended"]',
            '.mainVerticalArticleSharingLinks',
            '.OUTBRAIN',
            '.topBannerWrap',
            '.block.B3 .B3.ghcite.dyother.dyMonitor div',
            '.bigdealhomepage',
            '#ww6s_Main',
            '.buyandsavedy',
            '.area.footer.ghcite',
            '.hdr_set_homepage',
            '#c1_Hor',
            '#c2_Hor',
            '#c3_Hor',
            '#c4_Hor',
            '#c5_Hor',
            '#c6_Hor',
            '.homepagevideo-x6',
            '.buyandsave',
            '.general-image',
            '.PhotoArticlesTalkbacks',
            '[name="ExternalWebpageIframe"]',
            '#PROCOIL_SearchForm',
            '#magazines1024',
            '[id^="promo_"]',
            '[id^="ads."]',
            '.main_search_radio',
            'tr td [id^="ads."]',
            '.art-action-wrp',
            '.header-user-profile',
            '.left-art-content',
            {
                selector: '.homepagelitevideo',
                fineTuneSelector: function ($element) {
                    return $element.parent().parent();
                }
            },
            {
                selector: 'iframe',
                filter: function ($element) {
                    return !$element.parent().hasClass('news_ticker_iframe');
                }
            },
            {
                selector: 'div.B2b.block div',
                pre: function ($element) {
                    $element.parent().css({
                        height: '1px'
                    });
                }
            }
        ],
        globes: [
            '#chromeWindow',
            {
                selector: 'iframe',
                filter: function ($element) {
                    var id = $element.attr('id');
                    var src = $element.attr('src') || '';

                    return (id !== 'GlobalFinanceData_home') && (src.indexOf('/news/') !== -1);
                }
            }
        ],
        sourceforge: [
            '#content-for-adblock',
            '#newsletter-floating',
            '#page-body'
        ],
        subscenter: [
            '.weekBottom',
            '.reviewsWindow',
            '#banner_cinemast',
            '.bottomMenu',
            'footer',
            '#paypal',
            '#aboveSite',
            {
                selector: '#subtitles_list a[href="/he/contactus/"]',
                fineTuneSelector: function ($element) {
                    return $element.parent();
                }
            }
        ],
        wikipedia: [
            '#frbanner',
            '#wlm-banner',
            '.frbanner'
        ]
    };

    [
        '#dcPremiumRightImg',
        '.boulevard',
        '#multiarticles-9',
        '#multiarticles-12',
        '#multiarticles-13',
        '#multiarticles-14',
        '#multiarticles-15',
        '#multiarticles-16',
        '.CdaMostViews',
        '.CdaCalcalistToday',
        '.CdaRecomendedMovies',
        '#SpecialBuilder1280',
        '.cdaFooter1280'
    ].forEach(function addSelector(selector) {
        selectorDefinitions.ynet.push({
            selector: selector,
            fineTuneSelector: function ($element) {
                return $element.parent();
            }
        });
    });

    Object.keys(selectorDefinitions).forEach(function (id) {
        selectorDefinitions[id] = {
            id: id,
            selectors: selectorDefinitions[id]
        };
    });

    runner($, {
        getSelectors: function (hostName) {
            var selectors;
            if (hostName.indexOf('globes') !== -1) {
                selectors = selectorDefinitions.globes;
            } else if (hostName.indexOf('sourceforge.net') !== -1) {
                selectors = selectorDefinitions.sourceforge;
            } else if (hostName.indexOf('subscenter') !== -1) {
                selectors = selectorDefinitions.subscenter;
            } else if (hostName.indexOf('wikipedia.org') !== -1) {
                selectors = selectorDefinitions.wikipedia;
            } else { //ynet/calcalist
                selectors = selectorDefinitions.ynet;
            }

            return selectors;
        }
    });
}(window.jQuery.noConflict(true), window.adrRunner));
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Ads DOM Remover
// @namespace    sagiegurari
// @version      1.12
// @author       Sagie Gur-Ari
// @description  Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @match        http://www.ynet.co.il/home/*
// @match        https://www.ynet.co.il/home/*
// @match        http://www.ynet.co.il/articles/*
// @match        https://www.ynet.co.il/articles/*
// @match        http://www.mynet.co.il/articles/*
// @match        https://www.mynet.co.il/articles/*
// @match        http://www.calcalist.co.il/*
// @match        https://www.calcalist.co.il/*
// @match        http://www.globes.co.il/*
// @match        https://www.globes.co.il/*
// @match        https://sourceforge.net/projects/*/download*
// @match        https://sourceforge.net/projects/*/postdownload*
// @match        http://subscenter.cinemast.com/*
// @match        https://subscenter.cinemast.com/*
// @match        http://www.subscenter.co/*
// @match        https://www.subscenter.co/*
// @match        http://www.subscenter.org/*
// @match        https://www.subscenter.org/*
// @match        https://*.wikipedia.org/*
// @match        http://www.opensubtitles.org/*
// @match        https://www.opensubtitles.org/*
// @match        http://*.wikia.com/wiki/*
// @match        https://*.wikia.com/wiki/*
// @require      https://code.jquery.com/jquery-2.2.2.min.js
// @require      https://greasyfork.org/scripts/18490-ads-dom-remover-runner/code/Ads%20DOM%20Remover%20Runner.js?version=189663
// @grant        none
// @license      MIT License
// ==/UserScript==

(function run($, runner) {
    'use strict';

    var selectorDefinitions = {
        ynet: {
            hostNames: ['ynet', 'calcalist'],
            selectors: [
                '#colorbox',
                '#cboxOverlay',
                '#ads.premium',
                '#articleLayoutrightsidtable',
                '#google_image_div',
                'img[src*="dynamicyield"]',
                'div.MSCmainContent',
                '[id*="arketingCarouse"]',
                '[id*="arketingRecommended"]',
                '.mainVerticalArticleSharingLinks',
                '.OUTBRAIN',
                '.topBannerWrap',
                '.block.B3 .B3.ghcite.dyother.dyMonitor div',
                '.bigdealhomepage',
                '#ww6s_Main',
                '.buyandsavedy',
                '.area.footer.ghcite',
                '.hdr_set_homepage',
                '#c1_Hor',
                '#c2_Hor',
                '#c3_Hor',
                '#c4_Hor',
                '#c5_Hor',
                '#c6_Hor',
                '.homepagevideo-x6',
                '.buyandsave',
                '.general-image',
                '.PhotoArticlesTalkbacks',
                '[name="ExternalWebpageIframe"]',
                '#PROCOIL_SearchForm',
                '#magazines1024',
                '[id^="promo_"]',
                '[id^="ads."]',
                '[class*="facebook"]',
                '[class*="WinWin"]',
                '.main_search_radio',
                'tr td [id^="ads."]',
                '.art-action-wrp',
                '.header-user-profile',
                '.left-art-content',
                '[class*="GeneralBanner"]',
                '#vilon',
                '#prime.shook',
                '#articlebottomsharinglinks',
                {
                    selector: '.homepagelitevideo',
                    fineTuneSelector: function ($element) {
                        return $element.parent().parent();
                    }
                },
                {
                    selector: 'iframe',
                    fineTuneSelector: function ($element) {
                        return $element.filter(function () {
                            return !$(this).parent().hasClass('news_ticker_iframe');
                        });
                    }
                },
                {
                    selector: 'div.B2b.block div',
                    pre: function ($element) {
                        $element.parent().css({
                            height: '1px'
                        });
                    }
                }
            ]
        },
        globes: {
            hostNames: 'globes',
            selectors: [
                '#chromeWindow',
                {
                    selector: 'iframe',
                    filter: function ($element) {
                        var id = $element.attr('id');
                        var src = $element.attr('src') || '';

                        return (id !== 'GlobalFinanceData_home') && (src.indexOf('/news/') !== -1);
                    }
                }
            ]
        },
        sourceforge: {
            hostNames: 'sourceforge.net',
            selectors: [
                '#content-for-adblock',
                '#newsletter-floating',
                '#page-body'
            ]
        },
        subscenter: {
            hostNames: 'subscenter',
            selectors: [
                '.weekBottom',
                '.reviewsWindow',
                '#banner_cinemast',
                '.bottomMenu',
                'footer',
                '#paypal',
                '#aboveSite',
                {
                    selector: '#subtitles_list a[href="/he/contactus/"]',
                    fineTuneSelector: function ($element) {
                        return $element.parent();
                    }
                }
            ]
        },
        wikipedia: {
            hostNames: 'wikipedia.org',
            selectors: [
                '#frbanner',
                '#frb-inline',
                '#wlm-banner',
                '#centralNotice',
                '.frbanner',
                '.frm'
            ]
        },
        opensubtitles: {
            hostNames: 'opensubtitles',
            selectors: [
                '.rec_container_right'
            ]
        },
        wikia: {
            hostNames: 'wikia.com',
            selectors: [
                '.WikiaFooter',
                '.WikiaRail',
                '.wds-global-footer'
            ]
        }
    };

    [
        '#dcPremiumRightImg',
        '.boulevard',
        '#multiarticles-9',
        '#multiarticles-12',
        '#multiarticles-13',
        '#multiarticles-14',
        '#multiarticles-15',
        '#multiarticles-16',
        '.CdaMostViews',
        '.CdaCalcalistToday',
        '.CdaRecomendedMovies',
        '#SpecialBuilder1280',
        '.cdaFooter1280'
    ].forEach(function addSelector(selector) {
        selectorDefinitions.ynet.selectors.push({
            selector: selector,
            fineTuneSelector: function ($element) {
                return $element.parent();
            }
        });
    });

    runner($, {
        getSelectorDefinitions: function () {
            return selectorDefinitions;
        }
    });
}(window.jQuery.noConflict(true), window.adrRunner));
<commit_msg>wikipedia selectors<commit_after>// ==UserScript==
// @name         Ads DOM Remover
// @namespace    sagiegurari
// @version      1.13
// @author       Sagie Gur-Ari
// @description  Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @match        http://www.ynet.co.il/home/*
// @match        https://www.ynet.co.il/home/*
// @match        http://www.ynet.co.il/articles/*
// @match        https://www.ynet.co.il/articles/*
// @match        http://www.mynet.co.il/articles/*
// @match        https://www.mynet.co.il/articles/*
// @match        http://www.calcalist.co.il/*
// @match        https://www.calcalist.co.il/*
// @match        http://www.globes.co.il/*
// @match        https://www.globes.co.il/*
// @match        https://sourceforge.net/projects/*/download*
// @match        https://sourceforge.net/projects/*/postdownload*
// @match        http://subscenter.cinemast.com/*
// @match        https://subscenter.cinemast.com/*
// @match        http://www.subscenter.co/*
// @match        https://www.subscenter.co/*
// @match        http://www.subscenter.org/*
// @match        https://www.subscenter.org/*
// @match        https://*.wikipedia.org/*
// @match        http://www.opensubtitles.org/*
// @match        https://www.opensubtitles.org/*
// @match        http://*.wikia.com/wiki/*
// @match        https://*.wikia.com/wiki/*
// @require      https://code.jquery.com/jquery-2.2.2.min.js
// @require      https://greasyfork.org/scripts/18490-ads-dom-remover-runner/code/Ads%20DOM%20Remover%20Runner.js?version=189663
// @grant        none
// @license      MIT License
// ==/UserScript==

(function run($, runner) {
    'use strict';

    var selectorDefinitions = {
        ynet: {
            hostNames: ['ynet', 'calcalist'],
            selectors: [
                '#colorbox',
                '#cboxOverlay',
                '#ads.premium',
                '#articleLayoutrightsidtable',
                '#google_image_div',
                'img[src*="dynamicyield"]',
                'div.MSCmainContent',
                '[id*="arketingCarouse"]',
                '[id*="arketingRecommended"]',
                '.mainVerticalArticleSharingLinks',
                '.OUTBRAIN',
                '.topBannerWrap',
                '.block.B3 .B3.ghcite.dyother.dyMonitor div',
                '.bigdealhomepage',
                '#ww6s_Main',
                '.buyandsavedy',
                '.area.footer.ghcite',
                '.hdr_set_homepage',
                '#c1_Hor',
                '#c2_Hor',
                '#c3_Hor',
                '#c4_Hor',
                '#c5_Hor',
                '#c6_Hor',
                '.homepagevideo-x6',
                '.buyandsave',
                '.general-image',
                '.PhotoArticlesTalkbacks',
                '[name="ExternalWebpageIframe"]',
                '#PROCOIL_SearchForm',
                '#magazines1024',
                '[id^="promo_"]',
                '[id^="ads."]',
                '[class*="facebook"]',
                '[class*="WinWin"]',
                '.main_search_radio',
                'tr td [id^="ads."]',
                '.art-action-wrp',
                '.header-user-profile',
                '.left-art-content',
                '[class*="GeneralBanner"]',
                '#vilon',
                '#prime.shook',
                '#articlebottomsharinglinks',
                {
                    selector: '.homepagelitevideo',
                    fineTuneSelector: function ($element) {
                        return $element.parent().parent();
                    }
                },
                {
                    selector: 'iframe',
                    fineTuneSelector: function ($element) {
                        return $element.filter(function () {
                            return !$(this).parent().hasClass('news_ticker_iframe');
                        });
                    }
                },
                {
                    selector: 'div.B2b.block div',
                    pre: function ($element) {
                        $element.parent().css({
                            height: '1px'
                        });
                    }
                }
            ]
        },
        globes: {
            hostNames: 'globes',
            selectors: [
                '#chromeWindow',
                {
                    selector: 'iframe',
                    filter: function ($element) {
                        var id = $element.attr('id');
                        var src = $element.attr('src') || '';

                        return (id !== 'GlobalFinanceData_home') && (src.indexOf('/news/') !== -1);
                    }
                }
            ]
        },
        sourceforge: {
            hostNames: 'sourceforge.net',
            selectors: [
                '#content-for-adblock',
                '#newsletter-floating',
                '#page-body'
            ]
        },
        subscenter: {
            hostNames: 'subscenter',
            selectors: [
                '.weekBottom',
                '.reviewsWindow',
                '#banner_cinemast',
                '.bottomMenu',
                'footer',
                '#paypal',
                '#aboveSite',
                {
                    selector: '#subtitles_list a[href="/he/contactus/"]',
                    fineTuneSelector: function ($element) {
                        return $element.parent();
                    }
                }
            ]
        },
        wikipedia: {
            hostNames: 'wikipedia.org',
            selectors: [
                '#frbanner',
                '#frb-inline',
                '#wlm-banner',
                '#centralNotice',
                '.frb-main',
                '.frbanner',
                '.frm'
            ]
        },
        opensubtitles: {
            hostNames: 'opensubtitles',
            selectors: [
                '.rec_container_right'
            ]
        },
        wikia: {
            hostNames: 'wikia.com',
            selectors: [
                '.WikiaFooter',
                '.WikiaRail',
                '.wds-global-footer'
            ]
        }
    };

    [
        '#dcPremiumRightImg',
        '.boulevard',
        '#multiarticles-9',
        '#multiarticles-12',
        '#multiarticles-13',
        '#multiarticles-14',
        '#multiarticles-15',
        '#multiarticles-16',
        '.CdaMostViews',
        '.CdaCalcalistToday',
        '.CdaRecomendedMovies',
        '#SpecialBuilder1280',
        '.cdaFooter1280'
    ].forEach(function addSelector(selector) {
        selectorDefinitions.ynet.selectors.push({
            selector: selector,
            fineTuneSelector: function ($element) {
                return $element.parent();
            }
        });
    });

    runner($, {
        getSelectorDefinitions: function () {
            return selectorDefinitions;
        }
    });
}(window.jQuery.noConflict(true), window.adrRunner));
<|endoftext|>


<commit_before>var http       = require('http')
  , AlexaSkill = require('./AlexaSkill')
  , APP_ID     = 'amzn1.echo-sdk-ams.app.901a3f73-22df-4ad2-aa7c-ed49c3a07a6f'
  , MTA_KEY    = 'your-mta-key';

var url = 'http://www.showertexts.com/today';

var getThoughtText = function(callback){
  http.get(url, function(res){
    var body = '';

    res.on('data', function(data){
      body += data;
    });

    res.on('end', function(){
      var result = body;
      callback(result);
    });

  }).on('error', function(e){
    console.log('Error: ' + e);
  });
};

var handleNextRequest = function(intent, session, response){
  getThoughtText(function(data){
    var heading = 'Todays shower thought.';
    response.tellWithCard(data, heading, data);
  });
};

var ShowerText = function(){
  AlexaSkill.call(this, APP_ID);
};

ShowerText.prototype = Object.create(AlexaSkill.prototype);
ShowerText.prototype.constructor = ShowerText;

ShowerText.prototype.eventHandlers.onLaunch = function(launchRequest, session, response){
  getThoughtText(function(data){
    var heading = 'Todays shower thought.';
    response.tellWithCard(data, heading, data);
  });
};

ShowerText.prototype.intentHandlers = {
  GetThoughtIntent: function(intent, session, response){
    handleNextRequest(intent, session, response);
  },

  HelpIntent: function(intent, session, response){
    var speechOutput = 'To get todays shower thought, just say: Alexa, open Shower Thoughts.';
    response.tellWithCard(speechOutput, 'Help', speechOutput);
  }
};

exports.handler = function(event, context) {
    var skill = new ShowerText();
    skill.execute(event, context);
};
<commit_msg>random thought<commit_after>var http       = require('http')
  , AlexaSkill = require('./AlexaSkill')
  , APP_ID     = 'amzn1.echo-sdk-ams.app.901a3f73-22df-4ad2-aa7c-ed49c3a07a6f'
  , MTA_KEY    = 'your-mta-key';

var url = 'http://www.showertexts.com/random';

var getThoughtText = function(callback){
  http.get(url, function(res){
    var body = '';

    res.on('data', function(data){
      body += data;
    });

    res.on('end', function(){
      var result = body;
      callback(result);
    });

  }).on('error', function(e){
    console.log('Error: ' + e);
  });
};

var handleNextRequest = function(intent, session, response){
  getThoughtText(function(data){
    var heading = 'Todays shower thought.';
    response.tellWithCard(data, heading, data);
  });
};

var ShowerText = function(){
  AlexaSkill.call(this, APP_ID);
};

ShowerText.prototype = Object.create(AlexaSkill.prototype);
ShowerText.prototype.constructor = ShowerText;

ShowerText.prototype.eventHandlers.onLaunch = function(launchRequest, session, response){
  getThoughtText(function(data){
    var heading = 'Todays shower thought.';
    response.tellWithCard(data, heading, data);
  });
};

ShowerText.prototype.intentHandlers = {
  GetThoughtIntent: function(intent, session, response){
    handleNextRequest(intent, session, response);
  },

  HelpIntent: function(intent, session, response){
    var speechOutput = 'To get todays shower thought, just say: Alexa, open Shower Thoughts.';
    response.tellWithCard(speechOutput, 'Help', speechOutput);
  }
};

exports.handler = function(event, context) {
    var skill = new ShowerText();
    skill.execute(event, context);
};
<|endoftext|>


<commit_before>angular.module('tw.directives.cropper', ['tw.services.fileReader']);

angular.module('tw.directives.cropper').directive('twCropper', ['$parse', '$window', '$document', 'twFileReader', function($parse, $window, $document, twFileReader) {
  var document = $document[0],
    Math = $window.Math;

  return {
    restrict: 'A',
    controller: ['$scope', '$attrs', '$element', function($scope, $attrs, $element) {
      var canvas = $element[0];

      // If twCropper attribute is provided
      if ($attrs.twCropper) {
        // Publish this controller to the scope via the expression
        $parse($attrs.twCropper).assign($scope, this);
      }

      this.toDataURL = function toDataURL() {
        return canvas.toDataURL();
      };
    }],
    link: function(scope, el, attrs) {
      if (angular.lowercase(el[0].nodeName) !== 'canvas') {
        return;
      }

      var canvas = el[0];
      var ctx = canvas.getContext('2d');
      var img = new Image();
      var x, y, scale, maxScale, minScale;

      var draw = function draw() {
        var sx = x,
          sy = y,
          sWidth = canvas.width * scale,
          sHeight = canvas.height * scale,
          dx = 0,
          dy = 0,
          dWidth = canvas.width,
          dHeight = canvas.height;

        ctx.drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
      };

      var zoom = function zoom(dScale) {
        var s = scale;

        scale += dScale;

        if (scale < minScale) {
          scale = minScale;
        } else if (scale > maxScale) {
          scale = maxScale;
        }

        var newWidth = scale * canvas.width;
        var newHeight = scale * canvas.height;
        var oldWidth = s * canvas.width;
        var oldHeight = s * canvas.height;

        var dWidth = newWidth - oldWidth;
        var dHeight = newHeight - oldHeight;

        x -= dWidth / 2;
        y -= dHeight / 2;

        if (x < 0) {
          x = 0;
        } else {
          if (x + newWidth > img.width) {
            x = img.width - newWidth;
          }
        }

        if (y < 0) {
          y = 0;
        } else {
          if (y + newHeight > img.height) {
            y = img.height - newHeight;
          }
        }
      };

      scope.$watch(attrs.source, function(newVal) {
        if (!newVal) {
          ctx.clearRect(0, 0, canvas.width, canvas.height);

          return;
        }

        twFileReader.readAsDataURL(newVal).then(function(dataURL) {
          img.onload = function() {
            x = 0;
            y = 0;
            scale = minScale = 1;

            if (img.width > img.height) {
              maxScale = img.height / canvas.height;
            } else {
              maxScale = img.width / canvas.width;

            }

            if (img.height < canvas.height) {
              scale = minScale = maxScale;
            }

            if (img.width < canvas.width) {
              scale = minScale = maxScale;
            }

            draw();
          };

          img.src = dataURL;
        });
      });

      var sx, sy;
      var move = function move(newX, newY) {
        x += (sx - newX) * scale;
        y += (sy - newY) * scale;

        if (x < 0) {
          x = 0;
        } else {
          var scaledWidth = canvas.width * scale;

          if (x + scaledWidth > img.width) {
            x = img.width - scaledWidth;
          }
        }

        if (y < 0) {
          y = 0;
        } else {
          var scaledHeight = canvas.height * scale;

          if (y + scaledHeight > img.height) {
            y = img.height - scaledHeight;
          }
        }

        draw();

        sx = newX;
        sy = newY;
      };

      var mousemove = function mousemove(e) {
        move(e.clientX, e.clientY);
      };

      var d = null;
      var pinch = function pinch(touch1, touch2) {
        var x1 = touch1.clientX;
        var y1 = touch1.clientY;
        var x2 = touch2.clientX;
        var y2 = touch2.clientY;

        var newD = Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));

        if (d !== null) {
          var dx = newD - d;

          zoom(dx * -.015);

          draw();
        }

        d = newD;
      };

      var touchmove = function touchmove(e) {
        e = e.originalEvent || e;

        if (e.touches.length === 1) {
          move(e.touches[0].clientX, e.touches[0].clientY);
        } else if (e.touches.length === 2) {
          pinch(e.touches[0], e.touches[1]);
        }
      };

      var start = function(x, y) {
        if (!img.src) {
          return;
        }

        sx = x;
        sy = y;

        $document.on('mousemove', mousemove);
        $document.on('touchmove', touchmove);
      };

      var mousedown = function mousedown(e) {
        start(e.clientX, e.clientY);
      };

      var touchstart = function touchstart(e) {
        e = e.originalEvent || e;

        e.preventDefault();

        if (e.touches.length === 1) {
          start(e.touches[0].clientX, e.touches[0].clientY);
        }
      };

      el.on('mousedown', mousedown);
      el.on('touchstart', touchstart);

      var end = function end() {
        $document.off('mousemove', mousemove);
        $document.off('touchmove', touchmove);

        d = null;
      };

      $document.on('mouseup touchend', end);

      el.on('wheel', function(e) {
        e.preventDefault();

        e = e.originalEvent || e;

        if (!img.src) {
          return;
        }

        if (e.deltaY < 0) {
          zoom(-.15);
        } else {
          zoom(.15);
        }

        draw();
      });
    }
  };
}]);
<commit_msg>Add comment about jQuery and originalEvent<commit_after>angular.module('tw.directives.cropper', ['tw.services.fileReader']);

angular.module('tw.directives.cropper').directive('twCropper', ['$parse', '$window', '$document', 'twFileReader', function($parse, $window, $document, twFileReader) {
  var document = $document[0],
    Math = $window.Math;

  return {
    restrict: 'A',
    controller: ['$scope', '$attrs', '$element', function($scope, $attrs, $element) {
      var canvas = $element[0];

      // If twCropper attribute is provided
      if ($attrs.twCropper) {
        // Publish this controller to the scope via the expression
        $parse($attrs.twCropper).assign($scope, this);
      }

      this.toDataURL = function toDataURL() {
        return canvas.toDataURL();
      };
    }],
    link: function(scope, el, attrs) {
      if (angular.lowercase(el[0].nodeName) !== 'canvas') {
        return;
      }

      var canvas = el[0];
      var ctx = canvas.getContext('2d');
      var img = new Image();
      var x, y, scale, maxScale, minScale;

      var draw = function draw() {
        var sx = x,
          sy = y,
          sWidth = canvas.width * scale,
          sHeight = canvas.height * scale,
          dx = 0,
          dy = 0,
          dWidth = canvas.width,
          dHeight = canvas.height;

        ctx.drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
      };

      var zoom = function zoom(dScale) {
        var s = scale;

        scale += dScale;

        if (scale < minScale) {
          scale = minScale;
        } else if (scale > maxScale) {
          scale = maxScale;
        }

        var newWidth = scale * canvas.width;
        var newHeight = scale * canvas.height;
        var oldWidth = s * canvas.width;
        var oldHeight = s * canvas.height;

        var dWidth = newWidth - oldWidth;
        var dHeight = newHeight - oldHeight;

        x -= dWidth / 2;
        y -= dHeight / 2;

        if (x < 0) {
          x = 0;
        } else {
          if (x + newWidth > img.width) {
            x = img.width - newWidth;
          }
        }

        if (y < 0) {
          y = 0;
        } else {
          if (y + newHeight > img.height) {
            y = img.height - newHeight;
          }
        }
      };

      scope.$watch(attrs.source, function(newVal) {
        if (!newVal) {
          ctx.clearRect(0, 0, canvas.width, canvas.height);

          return;
        }

        twFileReader.readAsDataURL(newVal).then(function(dataURL) {
          img.onload = function() {
            x = 0;
            y = 0;
            scale = minScale = 1;

            if (img.width > img.height) {
              maxScale = img.height / canvas.height;
            } else {
              maxScale = img.width / canvas.width;

            }

            if (img.height < canvas.height) {
              scale = minScale = maxScale;
            }

            if (img.width < canvas.width) {
              scale = minScale = maxScale;
            }

            draw();
          };

          img.src = dataURL;
        });
      });

      var sx, sy;
      var move = function move(newX, newY) {
        x += (sx - newX) * scale;
        y += (sy - newY) * scale;

        if (x < 0) {
          x = 0;
        } else {
          var scaledWidth = canvas.width * scale;

          if (x + scaledWidth > img.width) {
            x = img.width - scaledWidth;
          }
        }

        if (y < 0) {
          y = 0;
        } else {
          var scaledHeight = canvas.height * scale;

          if (y + scaledHeight > img.height) {
            y = img.height - scaledHeight;
          }
        }

        draw();

        sx = newX;
        sy = newY;
      };

      var mousemove = function mousemove(e) {
        move(e.clientX, e.clientY);
      };

      var d = null;
      var pinch = function pinch(touch1, touch2) {
        var x1 = touch1.clientX;
        var y1 = touch1.clientY;
        var x2 = touch2.clientX;
        var y2 = touch2.clientY;

        var newD = Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));

        if (d !== null) {
          var dx = newD - d;

          zoom(dx * -.015);

          draw();
        }

        d = newD;
      };

      var touchmove = function touchmove(e) {
        // jQuery doesn't copy touches over to its event, so we need to go through originalEvent in that case
        e = e.originalEvent || e;

        if (e.touches.length === 1) {
          move(e.touches[0].clientX, e.touches[0].clientY);
        } else if (e.touches.length === 2) {
          pinch(e.touches[0], e.touches[1]);
        }
      };

      var start = function(x, y) {
        if (!img.src) {
          return;
        }

        sx = x;
        sy = y;

        $document.on('mousemove', mousemove);
        $document.on('touchmove', touchmove);
      };

      var mousedown = function mousedown(e) {
        start(e.clientX, e.clientY);
      };

      var touchstart = function touchstart(e) {
        // jQuery doesn't copy touches over to its event, so we need to go through originalEvent in that case
        e = e.originalEvent || e;

        e.preventDefault();

        if (e.touches.length === 1) {
          start(e.touches[0].clientX, e.touches[0].clientY);
        }
      };

      el.on('mousedown', mousedown);
      el.on('touchstart', touchstart);

      var end = function end() {
        $document.off('mousemove', mousemove);
        $document.off('touchmove', touchmove);

        d = null;
      };

      $document.on('mouseup touchend', end);

      el.on('wheel', function(e) {
        e.preventDefault();

        e = e.originalEvent || e;

        if (!img.src) {
          return;
        }

        if (e.deltaY < 0) {
          zoom(-.15);
        } else {
          zoom(.15);
        }

        draw();
      });
    }
  };
}]);
<|endoftext|>


<commit_before>'use strict';

const co = require('co');
const _ = require('lodash');

const api = requireLocal('services/api-proxy');

const sponsoring = {};

/**
 * Sends the occurred error back to the client, and logs it to the bunyan global logger.
 * @param res
 * @param errMsg
 * @param err
 * @returns {*}
 */
const sendErr = (res, errMsg, err) => {

  if (err) logger.error(errMsg, err);
  else logger.error(errMsg);

  res.status(500).send({error: errMsg});
};

/**
 * Creates a sponsoring.
 * @param req
 * @param res
 * @param next
 */

sponsoring.create = (req, res, next) => co(function*() {

  let body = {};
  if (Number(req.body.amountPerKm_range) !== Number(req.body.amountPerKm_text)) {
    return sendErr(res, 'amountPerKm is malformed');
  }

  try {
    let obj = JSON.parse(req.body.team);
    body.team = obj.team;
    body.event = obj.event;
  } catch (ex) {
    return sendErr(res, ex.message, ex);
  }

  body.amountPerKm = req.body.amountPerKm_range;
  if (req.body.limit) body.limit = req.body.limit;
  //TODO add proper limit (BACKEND HACK)
  else body.limit = 1000000000;

  //OFFLINE PART
  if (req.body.street) {
    body.unregisteredSponsor = {};
    body.unregisteredSponsor.address = {
      street: req.body.street,
      housenumber: req.body.housenumber,
      zipcode: req.body.zipcode,
      city: req.body.city,
      country: req.body.country
    };
    body.unregisteredSponsor.firstname = req.body.firstname;
    body.unregisteredSponsor.lastname = req.body.lastname;
    body.unregisteredSponsor.company = req.body.company;
    body.unregisteredSponsor.gender = req.body.gender;

    if (!req.body.url) body.unregisteredSponsor.url = "";
    else body.unregisteredSponsor.url = req.body.url;

    if (req.body.selfChallengeDescription.length !== req.body.selfChallengeAmount.length) {
      return sendErr(res, 'Unequal amount of challenge descriptions and challenge amounts');
    }

    body.challenges = yield req.body.selfChallengeDescription.map(
      (e, i) => {
        let currBody = {
          amount: req.body.selfChallengeAmount[i],
          description: e,
          unregisteredSponsor: body.unregisteredSponsor
        };
        if(currBody.amount > 0) {
          return api.challenge.create(req.user, body.event, body.team, currBody);
        }
        else return null;
      });
  }

  for(var i = 0; i < body.challenges.length; i++) {
    if (body.challenges[i] && req.file) {
      return api.uploadPicture(req.file, body.challenges[i].contract);
    }

  }

  let sponsoring = null;

  if(body.amountPerKm > 0) {
    sponsoring = yield api.sponsoring.create(req.user, body.event, body.team, body);
    if (req.file) {
      yield api.uploadPicture(req.file, sponsoring.contract);
    }
  } else if(req.body.selfChallengeDescription.length === 0) {
    return sendErr(res, 'Missing amountPerKm and challanges, at least one variable has to be present');
  }

  let challengesCreated = body.challenges.reduce((c1, c2) => !!c1 || !!c2);

  if(!challengesCreated && !sponsoring) {
    return sendErr(res, 'Neither sponsorings nor challenges created');
  }

  res.send(sponsoring);

}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.getAllTeams = (req) => co(function*() {
  const events = yield api.event.all();

  let teamsByEvent = yield events.map((e) => api.getModel(`event/${e.id}/team`, req.user));

  let allTeams = teamsByEvent.map((teams, index) => {
    return teams.map(team => {
      team.city = events[index].city;
      team.event = events[index].id;
      return team;
    });
  });

  allTeams = _.flatten(allTeams);
  allTeams = allTeams.filter(t => t.hasFullyPaid);
  return _.sortBy(allTeams,t => t.name);

}).catch(ex => {
  throw ex;
});

sponsoring.getByTeam = (req) => co(function*() {

  let allSponsorings = yield api.sponsoring.getByTeam(
    req.user.me.participant.eventId,
    req.user.me.participant.teamId);

  let callSponsorings = allSponsorings.filter(c => !!c.userId);

  let sponsors = yield callSponsorings.map(s => api.user.get(s.userId));

  return allSponsorings.map(sponsoring => {
    sponsoring.sponsor = sponsors.filter(s => s.id = sponsoring.userId)[0];
    return sponsoring;
  });

}).catch(ex => {
  throw ex;
});

sponsoring.getBySponsor = (req) => co(function*() {

  return yield api.sponsoring.getBySponsor(
    req.user,
    req.user.me.id);

}).catch(ex => {
  throw ex;
});

sponsoring.accept = (req, res, next) => co(function*() {

  yield api.sponsoring.accept(req.user, req.body.eventId, req.body.teamId, req.body.sponsoringId);

  return res.sendStatus(200);
}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.reject = (req, res, next) => co(function*() {

  yield api.sponsoring.reject(req.user, req.body.eventId, req.body.teamId, req.body.sponsoringId);

  return res.sendStatus(200);
}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.delete = (req, res, next) => co(function*() {

  yield api.sponsoring.delete(req.user, req.body.eventId, req.body.teamId, req.body.sponsoringId);

  return res.sendStatus(200);

}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.challenge = {};

sponsoring.challenge.create = (req, res, next) => co(function*() {

  let body = {};

  try {
    let obj = JSON.parse(req.body.addChallengeTeam);
    body.team = obj.team;
    body.event = obj.event;
  } catch (ex) {
    return sendErr(res, ex.message, ex);
  }

  if (req.body.addChallengeDescription.length !== req.body.addChallengeAmount.length) {
    return sendErr(res, 'Unequal amount of challenge descriptions and challenge amounts');
  }

  let test = yield req.body.addChallengeDescription.map(
    (e, i) => {
      let currBody = {
        amount: req.body.addChallengeAmount[i],
        description: e
      };
      return api.challenge.create(req.user, body.event, body.team, currBody)
    });

  res.sendStatus(200);

}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.challenge.getByTeam = (req) => co(function*() {

  let allChallenges = yield api.challenge.getByTeam(
    req.user.me.participant.eventId,
    req.user.me.participant.teamId);

  let callChallenges = allChallenges.filter(c => !!c.userId);

  let sponsors = yield callChallenges.map(c => api.user.get(c.userId));

  return allChallenges.map(challenge => {
    challenge.sponsor = sponsors.filter(s => s.id = challenge.userId)[0];
    return challenge;
  });

}).catch(ex => {
  throw ex;
});

sponsoring.challenge.getBySponsor = (req) => co(function*() {

  return yield api.challenge.getBySponsor(
    req.user,
    req.user.me.id);

}).catch(ex => {
  throw ex;
});

sponsoring.challenge.accept = (req, res, next) => co(function*() {

  yield api.challenge.accept(req.user, req.body.eventId, req.body.teamId, req.body.challengeId);

  return res.sendStatus(200);
}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.challenge.reject = (req, res, next) => co(function*() {

  yield api.challenge.reject(req.user, req.body.eventId, req.body.teamId, req.body.challengeId);

  return res.sendStatus(200);
}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.challenge.delete = (req, res, next) => co(function*() {

  yield api.challenge.delete(req.user, req.body.eventId, req.body.teamId, req.body.challengeId);

  return res.sendStatus(200);
}).catch(ex => {
  sendErr(res, ex.message, ex);
});

module.exports = sponsoring;<commit_msg>fixes 2 major issues<commit_after>'use strict';

const co = require('co');
const _ = require('lodash');

const api = requireLocal('services/api-proxy');

const sponsoring = {};

/**
 * Sends the occurred error back to the client, and logs it to the bunyan global logger.
 * @param res
 * @param errMsg
 * @param err
 * @returns {*}
 */
const sendErr = (res, errMsg, err) => {

  if (err) logger.error(errMsg, err);
  else logger.error(errMsg);

  res.status(500).send({error: errMsg});
};

/**
 * Creates a sponsoring.
 * @param req
 * @param res
 * @param next
 */

sponsoring.create = (req, res, next) => co(function*() {

  let body = {};

  try {
    let obj = JSON.parse(req.body.team);
    body.team = obj.team;
    body.event = obj.event;
  } catch (ex) {
    return sendErr(res, ex.message, ex);
  }

  body.amountPerKm = req.body.amountPerKm_text;
  if (req.body.limit) body.limit = req.body.limit;
  //TODO add proper limit (BACKEND HACK)
  else body.limit = 1000000000;

  //OFFLINE PART
  if (req.body.street) {
    body.unregisteredSponsor = {};
    body.unregisteredSponsor.address = {
      street: req.body.street,
      housenumber: req.body.housenumber,
      zipcode: req.body.zipcode,
      city: req.body.city,
      country: req.body.country
    };
    body.unregisteredSponsor.firstname = req.body.firstname;
    body.unregisteredSponsor.lastname = req.body.lastname;
    body.unregisteredSponsor.company = req.body.company;
    body.unregisteredSponsor.gender = req.body.gender;

    if (!req.body.url) body.unregisteredSponsor.url = "";
    else body.unregisteredSponsor.url = req.body.url;

    if (req.body.selfChallengeDescription) {
      if (req.body.selfChallengeDescription.length !== req.body.selfChallengeAmount.length) {
        return sendErr(res, 'Unequal amount of challenge descriptions and challenge amounts');
      }

      body.challenges = yield req.body.selfChallengeDescription.map(
        (e, i) => {
          let currBody = {
            amount: req.body.selfChallengeAmount[i],
            description: e,
            unregisteredSponsor: body.unregisteredSponsor
          };
          if (currBody.amount > 0) {
            return api.challenge.create(req.user, body.event, body.team, currBody);
          }
          else return null;
        });

      for (var i = 0; i < body.challenges.length; i++) {
        if (body.challenges[i] && req.file) {
          return api.uploadPicture(req.file, body.challenges[i].contract);
        }
      }

    }

  }

  let sponsoring = null;

  if (body.amountPerKm > 0) {
    sponsoring = yield api.sponsoring.create(req.user, body.event, body.team, body);
    if (req.file) {
      yield api.uploadPicture(req.file, sponsoring.contract);
    }
  } else if (!req.body.selfChallengeDescription) {
    return sendErr(res, 'Missing amountPerKm and challanges, at least one variable has to be present');
  }

  res.send(sponsoring);

}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.getAllTeams = (req) => co(function*() {
  const events = yield api.event.all();

  let teamsByEvent = yield events.map((e) => api.getModel(`event/${e.id}/team`, req.user));

  let allTeams = teamsByEvent.map((teams, index) => {
    return teams.map(team => {
      team.city = events[index].city;
      team.event = events[index].id;
      return team;
    });
  });

  allTeams = _.flatten(allTeams);
  allTeams = allTeams.filter(t => t.hasFullyPaid);
  return _.sortBy(allTeams, t => t.name);

}).catch(ex => {
  throw ex;
});

sponsoring.getByTeam = (req) => co(function*() {

  let allSponsorings = yield api.sponsoring.getByTeam(
    req.user.me.participant.eventId,
    req.user.me.participant.teamId);

  let callSponsorings = allSponsorings.filter(c => !!c.userId);

  let sponsors = yield callSponsorings.map(s => api.user.get(s.userId));

  return allSponsorings.map(sponsoring => {
    sponsoring.sponsor = sponsors.filter(s => s.id == sponsoring.userId)[0];
    return sponsoring;
  });

}).catch(ex => {
  throw ex;
});

sponsoring.getBySponsor = (req) => co(function*() {

  return yield api.sponsoring.getBySponsor(
    req.user,
    req.user.me.id);

}).catch(ex => {
  throw ex;
});

sponsoring.accept = (req, res, next) => co(function*() {

  yield api.sponsoring.accept(req.user, req.body.eventId, req.body.teamId, req.body.sponsoringId);

  return res.sendStatus(200);
}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.reject = (req, res, next) => co(function*() {

  yield api.sponsoring.reject(req.user, req.body.eventId, req.body.teamId, req.body.sponsoringId);

  return res.sendStatus(200);
}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.delete = (req, res, next) => co(function*() {

  yield api.sponsoring.delete(req.user, req.body.eventId, req.body.teamId, req.body.sponsoringId);

  return res.sendStatus(200);

}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.challenge = {};

sponsoring.challenge.create = (req, res, next) => co(function*() {

  let body = {};

  try {
    let obj = JSON.parse(req.body.addChallengeTeam);
    body.team = obj.team;
    body.event = obj.event;
  } catch (ex) {
    return sendErr(res, ex.message, ex);
  }

  if (req.body.addChallengeDescription.length !== req.body.addChallengeAmount.length) {
    return sendErr(res, 'Unequal amount of challenge descriptions and challenge amounts');
  }

  let test = yield req.body.addChallengeDescription.map(
    (e, i) => {
      let currBody = {
        amount: req.body.addChallengeAmount[i],
        description: e
      };
      return api.challenge.create(req.user, body.event, body.team, currBody)
    });

  res.sendStatus(200);

}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.challenge.getByTeam = (req) => co(function*() {

  let allChallenges = yield api.challenge.getByTeam(
    req.user.me.participant.eventId,
    req.user.me.participant.teamId);

  let callChallenges = allChallenges.filter(c => !!c.userId);

  let sponsors = yield callChallenges.map(c => api.user.get(c.userId));

  return allChallenges.map(challenge => {
    challenge.sponsor = sponsors.filter(s => s.id = challenge.userId)[0];
    return challenge;
  });

}).catch(ex => {
  throw ex;
});

sponsoring.challenge.getBySponsor = (req) => co(function*() {

  return yield api.challenge.getBySponsor(
    req.user,
    req.user.me.id);

}).catch(ex => {
  throw ex;
});

sponsoring.challenge.accept = (req, res, next) => co(function*() {

  yield api.challenge.accept(req.user, req.body.eventId, req.body.teamId, req.body.challengeId);

  return res.sendStatus(200);
}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.challenge.reject = (req, res, next) => co(function*() {

  yield api.challenge.reject(req.user, req.body.eventId, req.body.teamId, req.body.challengeId);

  return res.sendStatus(200);
}).catch(ex => {
  sendErr(res, ex.message, ex);
});

sponsoring.challenge.delete = (req, res, next) => co(function*() {

  yield api.challenge.delete(req.user, req.body.eventId, req.body.teamId, req.body.challengeId);

  return res.sendStatus(200);
}).catch(ex => {
  sendErr(res, ex.message, ex);
});

module.exports = sponsoring;<|endoftext|>


<commit_before>(function () {
    'use strict';

    var passport        = require('passport'),
        LocalStrategy   = require('passport-local').Strategy,
        provider        = require('../providers').userProvider,
        crypt           = require('bcryptjs');

    module.exports = function () {
        passport.use(
            new LocalStrategy({ usernameField: 'email', passwordField: 'password' },
            function (username, password, done) {
                return provider
                    .findByEmail(username)
                    .then(function (user) {
                        if (!user) {
                            return done(null, false);
                        }

                        return crypt.compare(password, user.password, function (err, res) {
                            if (err) {
                                return done(err);
                            }
                            return (res) ? done(null, user) : done(null, false);
                        });
                    });
            }
        ));

        passport.serializeUser(function(user, done) {
            done(null, user.id);
        });

        passport.deserializeUser(function(id, done) {
            provider.findById(id).then(function (user) {
                done(null, user);
            });
        });
    };

    module.exports.loggedIn = function (req, res, fn) {
        if (req.isAuthenticated()) {
            // refreshing session
            req.session.access = Date.now();
            fn();
        } else {
            res.redirect(302, '/login');
        }
    };

}());<commit_msg>API checks authentication<commit_after>(function () {
    'use strict';

    var passport        = require('passport'),
        LocalStrategy   = require('passport-local').Strategy,
        provider        = require('../providers').userProvider,
        crypt           = require('bcryptjs');

    module.exports = function () {
        passport.use(
            new LocalStrategy({ usernameField: 'email', passwordField: 'password' },
            function (username, password, done) {
                return provider
                    .findByEmail(username)
                    .then(function (user) {
                        if (!user) {
                            return done(null, false);
                        }

                        return crypt.compare(password, user.password, function (err, res) {
                            if (err) {
                                return done(err);
                            }
                            return (res) ? done(null, user) : done(null, false);
                        });
                    });
            }
        ));

        passport.serializeUser(function(user, done) {
            done(null, user.id);
        });

        passport.deserializeUser(function(id, done) {
            provider.findById(id).then(function (user) {
                done(null, user);
            });
        });
    };

    module.exports.adminLoginCheck = function (req, res, fn) {
        if (req.isAuthenticated()) {
            req.session.access = Date.now(); // refreshing session
            fn();
        } else {
            res.redirect(302, '/login');
        }
    };

    module.exports.apiLoginCheck = function (req, res, fn) {
        if (req.isAuthenticated()) {
            fn();
        } else {
            res.send(401);
        }
    };

}());<|endoftext|>


<commit_before>module.exports = {
  skipJsErrors: true,
  hostname: 'localhost',
  retryTestPages: true,
  pageRequestTimeout: 20000,
}
<commit_msg>Update .testcaferc.js<commit_after>module.exports = {
  skipJsErrors: true,
  hostname: 'localhost',
  retryTestPages: true,
  pageRequestTimeout: 50000,
}
<|endoftext|>


<commit_before>angular.module('wmProfile.filters', [])
  .filter('interpolate', ['version',
    function (version) {
      return function (text) {
        return String(text).replace(/\%VERSION\%/mg, version);
      };
    }
  ])
  .filter('noProtocol', [

    function () {
      return function (text) {
        return text.replace(/https?:\/\//, '');
      };
    }
  ])
  .filter('rfc3339', function () {
    return function (timestamp) {
      timestamp = timestamp || '';
      return new Date(timestamp).toISOString();
    };
  })
  .filter('decode', function () {
    return function (tag) {
      tag = tag || '';
      return decodeURIComponent(tag);
    };
  });
<commit_msg>Fix bug 1059901 - Add uriEncode filter<commit_after>angular.module('wmProfile.filters', [])
  .filter('interpolate', ['version',
    function (version) {
      return function (text) {
        return String(text).replace(/\%VERSION\%/mg, version);
      };
    }
  ])
  .filter('noProtocol', [

    function () {
      return function (text) {
        return text.replace(/https?:\/\//, '');
      };
    }
  ])
  .filter('rfc3339', function () {
    return function (timestamp) {
      timestamp = timestamp || '';
      return new Date(timestamp).toISOString();
    };
  })
  .filter('decode', function () {
    return function (tag) {
      tag = tag || '';
      return decodeURIComponent(tag);
    };
  })
  .filter('uriEncode', [ '$window', function ($window) {
    return $window.encodeURIComponent;
  }]);
<|endoftext|>


<commit_before>import {navigate} from '../services/navigation'
import {getDistance, getHeading} from '../helpers/geo'
export const GETTING_LOCATION = 'GETTING_LOCATION'
export const LOCATION_UPDATED = 'LOCATION_UPDATED'
export const GEO_ERROR = 'GEO_ERROR'
export const SET_TRIP = 'SET_TRIP'
export const START_TRIP = 'START_TRIP'

export const getLocation = () => {
  return (dispatch, getState) => {
    dispatch({
      type: GETTING_LOCATION,
    })
    const err = (msg) => {
      console.log("### ERROR")
      console.log(msg)
    }
    const success = (position) => {
      const {latitude, longitude, speed} = position.coords
      let newPosition = {
        type: LOCATION_UPDATED,
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
      }
      let prevLatitude = getState().get('geo').get('latitude')
      let prevLongitude = getState().get('geo').get('longitude')
      if (speed) {
        newPosition.speed = speed
      }
      if (prevLatitude && prevLongitude) {
        newPosition.heading = getHeading(prevLatitude, prevLongitude, latitude, longitude)
      }
      console.log(newPosition)
      dispatch(newPosition)
    }
    const watchPositionOptions = {
      enableHighAccuracy: true,
      timeout: 3000,
    }
    if (navigator.geolocation) {
      navigator.geolocation.watchPosition(success, err, watchPositionOptions)
    } else {
      dispatch({
        type: GEO_ERROR,
        message: 'No Geo Location Permissions',
      })
    }
  }
}

export const setTrip = (distance, duration, tripSteps) => {
  const heading = tripSteps[0].heading
  return (dispatch, getState) => {
    dispatch({
      type: SET_TRIP,
      distance,
      duration,
      tripSteps,
      heading: tripSteps[0].heading,
      destinationLoaded: true,
    })
  }
}

export const startTrip = () => {
  return (dispatch, getState) => {
    dispatch({
      type: START_TRIP,
    })
  }
}
<commit_msg>flip it again<commit_after>import {navigate} from '../services/navigation'
import {getDistance, getHeading} from '../helpers/geo'
export const GETTING_LOCATION = 'GETTING_LOCATION'
export const LOCATION_UPDATED = 'LOCATION_UPDATED'
export const GEO_ERROR = 'GEO_ERROR'
export const SET_TRIP = 'SET_TRIP'
export const START_TRIP = 'START_TRIP'

export const getLocation = () => {
  return (dispatch, getState) => {
    dispatch({
      type: GETTING_LOCATION,
    })
    const err = (msg) => {
      console.log("### ERROR")
      console.log(msg)
    }
    const success = (position) => {
      const {latitude, longitude, speed} = position.coords
      let newPosition = {
        type: LOCATION_UPDATED,
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
      }
      let prevLatitude = getState().get('geo').get('latitude')
      let prevLongitude = getState().get('geo').get('longitude')
      if (speed) {
        newPosition.speed = speed
      }
      if (prevLatitude && prevLongitude) {
        newPosition.heading = getHeading(latitude, longitude, prevLatitude, prevLongitude)
      }
      console.log(newPosition)
      dispatch(newPosition)
    }
    const watchPositionOptions = {
      enableHighAccuracy: true,
      timeout: 3000,
    }
    if (navigator.geolocation) {
      navigator.geolocation.watchPosition(success, err, watchPositionOptions)
    } else {
      dispatch({
        type: GEO_ERROR,
        message: 'No Geo Location Permissions',
      })
    }
  }
}

export const setTrip = (distance, duration, tripSteps) => {
  const heading = tripSteps[0].heading
  return (dispatch, getState) => {
    dispatch({
      type: SET_TRIP,
      distance,
      duration,
      tripSteps,
      heading: tripSteps[0].heading,
      destinationLoaded: true,
    })
  }
}

export const startTrip = () => {
  return (dispatch, getState) => {
    dispatch({
      type: START_TRIP,
    })
  }
}
<|endoftext|>