<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
    /**
     * Test when value is not assigned.
     */
    testUnassigned: {
    	attributes : {testCmpName : "UnsetNumber"},
        test : function(component) {
            var attr = component.get("v.value");
            $A.test.assertEquals(undefined, attr);
        }
    },

	/**
	 * Test max value.
	 */
    testMax: {
        attributes : {max : 9876.54321},
        test : function(component){
            $A.test.assertEquals(9876.54321, component.get("v.max"), "max does not equal expected");
        }
    },

    /**
     * Test min value.
     */
    testMin: {
        attributes : {min : 0.0003},
        test : function(component){
            $A.test.assertEquals(0.0003, component.get("v.min"), "min does not equal expected");
        }
    },

    /**
     * Test step.
     */
    testStep: {
        attributes : {step : 1.23},
        test : function(component){
            $A.test.assertEquals(1.23, component.get("v.step"), "step does not equal expected");
        }
    },

    /**
     * Test disabled.
     */
    testDisabled: {
        attributes : {disabled : true},
        test : function(component){
            $A.test.assertTrue(component.get("v.disabled"), "disable should be true");
        }
    },

    /**
     * Test value.
     */
    testValue: {
        attributes : {value : 567},
        test : function(component){
            $A.test.assertEquals(567, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test decimal value.
     */
    testDecimalValue: {
        attributes : {value : 10.3249},
        test : function(component){
            $A.test.assertEquals(10.3249, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test integer value
     */
    testIntValue: {
        attributes : {value : 100},
        test : function(component){
            $A.test.assertEquals(100, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test negative value.
     */
    testNegativeValue: {
        attributes : {value : -5},
        test : function(component){
            $A.test.assertEquals(-5, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Assign Negative value for attribute 'value' and special negative format
     */
    testNegativeValueWithNegativeFormat:{
        attributes: {value : -123.936, format:"#.0#;(#.0#)"},
        test: function(component){
        	var value = component.getElement().value;
            $A.test.assertEquals(-123.936, component.get("v.value"), "Cmp value: Negative values not displayed correctly.");
            $A.test.assertEquals('(123.94)', value, "Element value: Negative values not displayed correctly.");
        }
    },

    /**
     * Test small decimal value.
     */
    testSmallValue: {
        attributes : {value : 0.000005},
        test : function(component){
            $A.test.assertEquals(0.000005, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test large number
     */
    testLargeValue: {
        attributes : {value : 99999999999999},
        test : function(component){
            $A.test.assertEquals(99999999999999, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test zero value.
     */
    testZeroValue: {
        attributes : {value : 0},
        test : function(component){
            $A.test.assertEquals(0, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test when value is empty string
     */
    testEmptyValue: {
        attributes : {value : ""},
        test : function(component){
            $A.test.assertEquals(undefined, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test number formated correctly.
     */
    testNumberFormat: {
    	attributes : {value : 123, format : "#,#"},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("1,2,3", value, "Element value does not equal expected");
    	}
    },

    /**
     * Test number formated correctly when format is empty.
     */
    testNumberFormatEmptyString: {
    	attributes : {value : 123, format : ""},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("123", value, "Element value does not equal expected");
    	}
    },

    /**
     * Test number formated correctly when format is invalid.
     */
    testNumberFormatInvalidFormat: {
    	attributes : {value : 123, format : "#.#,0"},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("123", value, "Element value does not equal expected");
    	}
    },

    /**
     * Test number formated correctly when format is not of a recognizable type.
     */
    testNumberFormatUnrecognizedFormat: {
    	attributes : {value : 123, format : "xyz"},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("123", value, "Element value does not equal expected");
    	}
    },

    /**
    * Positive test case: Assign nothing to format value and verify default precision used to display decimal.
    */
   testDefaultDecimalPrecision: {
       attributes : {value : 123.450},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(123.45, component.get("v.value"), "Cmp value not displayed as expected when format is not specified.");
           $A.test.assertEquals("123.45", value, " Element value not displayed as expected when format is not specified.");
       }
   },

   /**
    * Verify Rounding up of lots of 9s
    */
   testRoundingLotsOfNines: {
       attributes : {value : 999999.9, format : '#,##0'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(999999.9, component.get("v.value"), "Cmp value: Nines were not rounded up correctly");
           $A.test.assertEquals('1,000,000', value, "Element value: Nines were not rounded up correctly");
       }
   },
   /**
    * Verify Rounding up of lots of 9s with extra zero padding
    */
   testRoundingLotsOfNinesAndZeroPadding: {
       attributes : {value : 999999.9, format : '00000000'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(999999.9, component.get("v.value"), "Cmp value: Nines were not round up correctly");
           $A.test.assertEquals('01000000', value, "Element value: Nines were not round up correctly");
       }
   },
   /**
    * Verify Rounding up of decimal part of value.
    */
   testFormat2DecimalPlaces_RoundUp: {
       attributes : {value : 3.1459, format : '.00'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(3.1459, component.get("v.value"), "Cmp value: Decimal part of value was not rounded up based on format.");
           $A.test.assertEquals('3.15', value, "Element value: Decimal part of value was not rounded up based on format.");
       }
   },
   /**
    * Verify Rounding down of decimal part of value.
    */
   testFormat2DecimalPlaces_RoundDown: {
       attributes : {value : 3.14159, format : '.00'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(3.14159, component.get("v.value"), "Cmp value: Decimal part of value was not rounded down based on format.");
           $A.test.assertEquals('3.14', value, "Element value: Decimal part of value was not rounded down based on format.");
       }
   },
   /**
    * Verify Rounding functionality when length of integer part is restricted by format.
    */
   testFormatDoesNotRestrictIntegerValue: {
       attributes : {value : 22.7, format : '0.0'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(22.7, component.get("v.value"), "Cmp value: Should have displayed full value but was probably truncated.");
           $A.test.assertEquals('22.7', value, "Element value: Should have displayed full value but was probably truncated.");
       }
   },
   /**
    * Verify that zeros are appended to decimal value to match format.
    */
   testAppendingZeroToMatchFormat: {
       attributes : {value : 22.7, format : '.000'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(22.7, component.get("v.value"), "Cmp value: Should have appended two zeros to match format.");
           $A.test.assertEquals('22.700', value, "Element value: Should have appended two zeros to match format.");
       }
   },

    /**
     * Test big value that is too large for a js number and is represented instead by a string
     *
     * Disabled for now due to new changes to inputNumber
     * TODO: wait for this W-2947804 and re-enable the test
     */
    _testBigDecimal: {
        attributes: {value: '1234567890123456789012345678901234567890.12', format: '.00'},
        test: function(component){
            var value = component.getElement().value;
            $A.test.assertEquals('1234567890123456789012345678901234567890.12', component.get("v.value"), "Cmp value: Unexpected value.");
            $A.test.assertEquals('1234567890123456789012345678901234567890.12', value, "Element value: Unexpected value.");
        }
    },

   /**
    * Verify that when the value changes it is rerendered with the unformated new value
    */
   testUpdateValue: {
       attributes : {value : 22.7, format : '##,#0,00.00#####'},
       test: [function(component){
    	   var value = component.getElement().value;
    	   $A.test.assertEquals(22.7, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('0,22.70', value, "Element: Value not formatted correctly.");
           component.set("v.value", 49322);
       }, function(component){
    	   var value = component.getElement().value;
    	   $A.test.assertEquals(49322, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('4,93,22.00', value, "Element: Value not formatted correctly.");
       }]
   },

   /**
    * Verify that when the format changes it is not rerendered with the new format
    */
   testUpdateFormat: {
       attributes : {value : 22.7, format : '##,#0,00.00#####'},
       test: [function(component){
    	   var value = component.getElement().value;
    	   $A.test.assertEquals(22.7, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('0,22.70', value, "Element: Value not formatted correctly.");
           component.set("v.format", '.000');
       }, function(component){
           var value = component.getElement().value;
    	   $A.test.assertEquals(22.7, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('0,22.70', value, "Element: Value not formatted correctly.");
       }]
   },

    /*
     * Verify that when value is set to an invalid value,
     * internal v.value should be undefined
     * displayed value should be empty
     */
    EMPTY_STRING : '',
    testSetInvalidValue: {
        attributes: {value: 12},
        test: [function (cmp) {
            cmp.set('v.value', 'abc');
        }, function(cmp){
            var inputValue = cmp.getElement().value;
            $A.test.assertEquals(this.EMPTY_STRING, inputValue, "Cmp: input value should be empty string");
            $A.test.assertEquals(undefined, cmp.get("v.value"), "Cmp: value should be undefined.");
        }]
    }
})// eslint-disable-line semi
<commit_msg>Update test to assert for null instead of undefined when input is changed. @rev reinier.guerra@ @bug W-2989147@<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
    EMPTY_STRING : '',
    /**
     * Test when value is not assigned.
     */
    testUnassigned: {
    	attributes : {testCmpName : "UnsetNumber"},
        test : function(component) {
            var attr = component.get("v.value");
            $A.test.assertEquals(undefined, attr);
        }
    },

	/**
	 * Test max value.
	 */
    testMax: {
        attributes : {max : 9876.54321},
        test : function(component){
            $A.test.assertEquals(9876.54321, component.get("v.max"), "max does not equal expected");
        }
    },

    /**
     * Test min value.
     */
    testMin: {
        attributes : {min : 0.0003},
        test : function(component){
            $A.test.assertEquals(0.0003, component.get("v.min"), "min does not equal expected");
        }
    },

    /**
     * Test step.
     */
    testStep: {
        attributes : {step : 1.23},
        test : function(component){
            $A.test.assertEquals(1.23, component.get("v.step"), "step does not equal expected");
        }
    },

    /**
     * Test disabled.
     */
    testDisabled: {
        attributes : {disabled : true},
        test : function(component){
            $A.test.assertTrue(component.get("v.disabled"), "disable should be true");
        }
    },

    /**
     * Test value.
     */
    testValue: {
        attributes : {value : 567},
        test : function(component){
            $A.test.assertEquals(567, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test decimal value.
     */
    testDecimalValue: {
        attributes : {value : 10.3249},
        test : function(component){
            $A.test.assertEquals(10.3249, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test integer value
     */
    testIntValue: {
        attributes : {value : 100},
        test : function(component){
            $A.test.assertEquals(100, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test negative value.
     */
    testNegativeValue: {
        attributes : {value : -5},
        test : function(component){
            $A.test.assertEquals(-5, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Assign Negative value for attribute 'value' and special negative format
     */
    testNegativeValueWithNegativeFormat:{
        attributes: {value : -123.936, format:"#.0#;(#.0#)"},
        test: function(component){
        	var value = component.getElement().value;
            $A.test.assertEquals(-123.936, component.get("v.value"), "Cmp value: Negative values not displayed correctly.");
            $A.test.assertEquals('(123.94)', value, "Element value: Negative values not displayed correctly.");
        }
    },

    /**
     * Test small decimal value.
     */
    testSmallValue: {
        attributes : {value : 0.000005},
        test : function(component){
            $A.test.assertEquals(0.000005, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test large number
     */
    testLargeValue: {
        attributes : {value : 99999999999999},
        test : function(component){
            $A.test.assertEquals(99999999999999, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test zero value.
     */
    testZeroValue: {
        attributes : {value : 0},
        test : function(component){
            $A.test.assertEquals(0, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test when value is empty string
     */
    testEmptyValue: {
        attributes : {value : ""},
        test : function(component){
            $A.test.assertEquals(undefined, component.get("v.value"), "value does not equal expected");
        }
    },

    /**
     * Test number formated correctly.
     */
    testNumberFormat: {
    	attributes : {value : 123, format : "#,#"},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("1,2,3", value, "Element value does not equal expected");
    	}
    },

    /**
     * Test number formated correctly when format is empty.
     */
    testNumberFormatEmptyString: {
    	attributes : {value : 123, format : ""},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("123", value, "Element value does not equal expected");
    	}
    },

    /**
     * Test number formated correctly when format is invalid.
     */
    testNumberFormatInvalidFormat: {
    	attributes : {value : 123, format : "#.#,0"},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("123", value, "Element value does not equal expected");
    	}
    },

    /**
     * Test number formated correctly when format is not of a recognizable type.
     */
    testNumberFormatUnrecognizedFormat: {
    	attributes : {value : 123, format : "xyz"},
    	test : function(component){
    		var value = component.getElement().value;
    		$A.test.assertEquals(123, component.get("v.value"), "Cmp value does not equal expected");
    		$A.test.assertEquals("123", value, "Element value does not equal expected");
    	}
    },

    /**
    * Positive test case: Assign nothing to format value and verify default precision used to display decimal.
    */
   testDefaultDecimalPrecision: {
       attributes : {value : 123.450},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(123.45, component.get("v.value"), "Cmp value not displayed as expected when format is not specified.");
           $A.test.assertEquals("123.45", value, " Element value not displayed as expected when format is not specified.");
       }
   },

   /**
    * Verify Rounding up of lots of 9s
    */
   testRoundingLotsOfNines: {
       attributes : {value : 999999.9, format : '#,##0'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(999999.9, component.get("v.value"), "Cmp value: Nines were not rounded up correctly");
           $A.test.assertEquals('1,000,000', value, "Element value: Nines were not rounded up correctly");
       }
   },
   /**
    * Verify Rounding up of lots of 9s with extra zero padding
    */
   testRoundingLotsOfNinesAndZeroPadding: {
       attributes : {value : 999999.9, format : '00000000'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(999999.9, component.get("v.value"), "Cmp value: Nines were not round up correctly");
           $A.test.assertEquals('01000000', value, "Element value: Nines were not round up correctly");
       }
   },
   /**
    * Verify Rounding up of decimal part of value.
    */
   testFormat2DecimalPlaces_RoundUp: {
       attributes : {value : 3.1459, format : '.00'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(3.1459, component.get("v.value"), "Cmp value: Decimal part of value was not rounded up based on format.");
           $A.test.assertEquals('3.15', value, "Element value: Decimal part of value was not rounded up based on format.");
       }
   },
   /**
    * Verify Rounding down of decimal part of value.
    */
   testFormat2DecimalPlaces_RoundDown: {
       attributes : {value : 3.14159, format : '.00'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(3.14159, component.get("v.value"), "Cmp value: Decimal part of value was not rounded down based on format.");
           $A.test.assertEquals('3.14', value, "Element value: Decimal part of value was not rounded down based on format.");
       }
   },
   /**
    * Verify Rounding functionality when length of integer part is restricted by format.
    */
   testFormatDoesNotRestrictIntegerValue: {
       attributes : {value : 22.7, format : '0.0'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(22.7, component.get("v.value"), "Cmp value: Should have displayed full value but was probably truncated.");
           $A.test.assertEquals('22.7', value, "Element value: Should have displayed full value but was probably truncated.");
       }
   },
   /**
    * Verify that zeros are appended to decimal value to match format.
    */
   testAppendingZeroToMatchFormat: {
       attributes : {value : 22.7, format : '.000'},
       test: function(component){
    	   var value = component.getElement().value;
           $A.test.assertEquals(22.7, component.get("v.value"), "Cmp value: Should have appended two zeros to match format.");
           $A.test.assertEquals('22.700', value, "Element value: Should have appended two zeros to match format.");
       }
   },

    /**
     * Test big value that is too large for a js number and is represented instead by a string
     *
     * Disabled for now due to new changes to inputNumber
     * TODO: wait for this W-2947804 and re-enable the test
     */
    _testBigDecimal: {
        attributes: {value: '1234567890123456789012345678901234567890.12', format: '.00'},
        test: function(component){
            var value = component.getElement().value;
            $A.test.assertEquals('1234567890123456789012345678901234567890.12', component.get("v.value"), "Cmp value: Unexpected value.");
            $A.test.assertEquals('1234567890123456789012345678901234567890.12', value, "Element value: Unexpected value.");
        }
    },

   /**
    * Verify that when the value changes it is rerendered with the unformated new value
    */
   testUpdateValue: {
       attributes : {value : 22.7, format : '##,#0,00.00#####'},
       test: [function(component){
    	   var value = component.getElement().value;
    	   $A.test.assertEquals(22.7, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('0,22.70', value, "Element: Value not formatted correctly.");
           component.set("v.value", 49322);
       }, function(component){
    	   var value = component.getElement().value;
    	   $A.test.assertEquals(49322, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('4,93,22.00', value, "Element: Value not formatted correctly.");
       }]
   },

   /**
    * Verify that when the format changes it is not rerendered with the new format
    */
   testUpdateFormat: {
       attributes : {value : 22.7, format : '##,#0,00.00#####'},
       test: [function(component){
    	   var value = component.getElement().value;
    	   $A.test.assertEquals(22.7, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('0,22.70', value, "Element: Value not formatted correctly.");
           component.set("v.format", '.000');
       }, function(component){
           var value = component.getElement().value;
    	   $A.test.assertEquals(22.7, component.get("v.value"), "Cmp: Value not formatted correctly.");
           $A.test.assertEquals('0,22.70', value, "Element: Value not formatted correctly.");
       }]
   },

    /*
     * Verify that when value is set to an invalid value,
     * internal v.value should be undefined
     * displayed value should be empty
     */
    testSetInvalidValue: {
        attributes: {value: 12},
        test: [function (cmp) {
            cmp.set('v.value', 'abc');
        }, function(cmp){
            var inputValue = cmp.getElement().value;
            $A.test.assertEquals(this.EMPTY_STRING, inputValue, "Cmp: input value should be empty string");
            $A.test.assertEquals(null, cmp.get("v.value"), "Cmp: value should be undefined.");
        }]
    }
})// eslint-disable-line semi
<|endoftext|>


<commit_before>var Buffer = require('buffer').Buffer,
    crypto = require('crypto');

function _parseArgs(arg_array) {
    if (arg_array.length === 0) { throw new Error('Atleast a callback argument is required'); }
    var is_range = arg_array.length > 2;

    return {
        cb:  arg_array[arg_array.length-1],
        min: is_range ? arg_array[0] : undefined,
        max: is_range ? arg_array[1] : undefined
    };
}

/*** Returns a random unsigned Int ***
 Returns the random int returned by nodes crypto library
*/
exports.getRandomInt = function(min, max, callback) {
    var args = _parseArgs(arguments);

    crypto.randomBytes(8, function(err, bytes_slow_buf) {
        if (err) { return cb(err); }

        var unsigned_int = Buffer(bytes_slow_buf).readUInt32LE(0);

        if (args.min !== undefined) {
            unsigned_int = unsigned_int % Math.abs(args.max - args.min) + args.min;
        }

        args.cb(null, unsigned_int);
    });
};
<commit_msg>Use better method for calculating random int to return.  This should provide a more even distrobution.<commit_after>var Buffer  = require('buffer').Buffer,
    crypto  = require('crypto'),
    assert  = require('assert'),
    MaxUInt = 4294967295;

function _parseArgs(arg_array) {
   if (arg_array.length === 0) { throw new Error('Atleast a callback argument is required'); }
   var is_range = arg_array.length > 2;

   return {
      cb:  arg_array[arg_array.length-1],
      min: is_range ? arg_array[0] : undefined,
      max: is_range ? arg_array[1] : undefined
   };
}

/** Map random int to the range so that an even distrobution of results is possible
 *
 * Using this method ensures an even distrobution of as opposed to the modulo
 * technique is is biased.
 *
 * @see http://mathoverflow.net/questions/35556/skewing-the-distribution-of-random-values-over-a-range
 * for an explaination of the modulo issue.
 */
function _mapToRange(min, max, randUInt) {
   var result_range = max - min,
       factor = result_range / MaxUInt;

   return Math.round((randUInt * factor) + min); // Math.round may cause some slight issues.
}

/*** Returns a random unsigned Int ***
     Returns the random int returned by nodes crypto library
*/
exports.getRandomInt = function(min, max, callback) {
   var args = _parseArgs(arguments), unsigned_int, rand_int;

   crypto.randomBytes(8, function(err, bytes_slow_buf) {
      if (err) { return cb(err); }

      unsigned_int = Buffer(bytes_slow_buf).readUInt32LE(0);

      if (args.min !== undefined) {
         assert(args.max !== undefined && args.min < args.max);
         rand_int = _mapToRange(args.min, args.max, unsigned_int);
      }
      else {
         rand_int = unsigned_int;
      }

      args.cb(null, rand_int);
   });
};
<|endoftext|>


<commit_before>const glob = require('glob');
const fs = require('fs-extra');
const path = require('path');
const marked = require('marked');
const renderer = require('./utils/renderer');
const formatDate = require('date-fns/format');
const camelCase = require('camel-case');
const titleCase = require('title-case');
const shell = require('shelljs');
const getFileNameFromPath = require('@lukeboyle/get-filename-from-path');

function getMarkupFromMarkdown(markdownString) {
	return marked(markdownString, {renderer: renderer, gfm: true});
}

renderer.heading = function(code, level) {
	if (level === 1) {
		return `

${code}

		`;
	} else {
		return `<h${level}>${code}</h${level}>`;
	}
};

function generateComponent(acc, curr, index) {
	const fileName = getFileNameFromPath(curr.path).replace('.md', '');
	const camelCaseName = camelCase(fileName);
	let imports = `
import React from 'react';
import portfolioData from '../../data/portfolio-items';
import Helmet from 'react-helmet';
import {PORTFOLIO_ITEM_NAMES} from "../../constants";`;

	renderer.image = function(href, title, text) {
		const rawFilename = getFileNameFromPath(href);
		const imageName = `${camelCase(rawFilename.slice(0, rawFilename.indexOf('.')))}Src`;

		imports = `${imports}\nimport ${imageName} from '.${href}'`;

		return `<img src={${imageName}} alt="${text}"/>`;
	};

	const bodyMarkup = getMarkupFromMarkdown(curr.contents);

	acc.push({
		path: curr.path,
		fileName,
		componentName: camelCaseName[0].toUpperCase() + camelCaseName.slice(1),
		component: `
			${imports}

			export default class ${camelCaseName} extends React.Component {
				render() {
					const portfolioContent = portfolioData.find(data => data.name === PORTFOLIO_ITEM_NAMES.${fileName.toUpperCase().split('-').join('_')});

					return (

							<Helmet>
								<title>{portfolioContent.name} | Project Case Study</title>
								<meta name="description" content={portfolioContent.snippet}/>
							</Helmet>

									${bodyMarkup}

					);
				}
			}
		`
	});

	return acc;
}

(() => {
	glob('portfolio-items/**/*.md', {}, (err, files) => {
		const blogPosts = files.reduce((acc, curr) => {
			acc.push({
				path: curr,
				contents: fs.readFileSync(curr, {encoding: 'utf-8'})
			});

			return acc;
		}, []);

		const reversedComponents = blogPosts.reduce(generateComponent, []);

		fs.copySync(`${__dirname}/../portfolio-items/images`, `${__dirname}/../src/pages/portfolio/images`);

		reversedComponents.forEach(component => {
			fs.writeFileSync(path.resolve(`${__dirname}/../src/pages/portfolio/${component.fileName}.jsx`), component.component);
		});
	});
})();<commit_msg>chore: add button links<commit_after>const glob = require('glob');
const fs = require('fs-extra');
const path = require('path');
const marked = require('marked');
const renderer = require('./utils/renderer');
const formatDate = require('date-fns/format');
const camelCase = require('camel-case');
const titleCase = require('title-case');
const shell = require('shelljs');
const getFileNameFromPath = require('@lukeboyle/get-filename-from-path');

function getMarkupFromMarkdown(markdownString) {
	return marked(markdownString, {renderer: renderer, gfm: true});
}

renderer.heading = function(code, level) {
	if (level === 1) {
		return `

${code}

		`;
	} else {
		return `<h${level}>${code}</h${level}>`;
	}
};

function generateComponent(acc, curr, index) {
	const fileName = getFileNameFromPath(curr.path).replace('.md', '');
	const camelCaseName = camelCase(fileName);
	let imports = `
import React from 'react';
import portfolioData from '../../data/portfolio-items';
import Helmet from 'react-helmet';
import {PORTFOLIO_ITEM_NAMES} from "../../constants";`;

	renderer.image = function(href, title, text) {
		const rawFilename = getFileNameFromPath(href);
		const imageName = `${camelCase(rawFilename.slice(0, rawFilename.indexOf('.')))}Src`;

		imports = `${imports}\nimport ${imageName} from '.${href}'`;

		return `<img src={${imageName}} alt="${text}"/>`;
	};

	const bodyMarkup = getMarkupFromMarkdown(curr.contents);

	acc.push({
		path: curr.path,
		fileName,
		componentName: camelCaseName[0].toUpperCase() + camelCaseName.slice(1),
		component: `
			${imports}

			export default class ${camelCaseName} extends React.Component {
				render() {
					const portfolioContent = portfolioData.find(data => data.name === PORTFOLIO_ITEM_NAMES.${fileName.toUpperCase().split('-').join('_')});

					return (

							<Helmet>
								<title>{portfolioContent.name} | Project Case Study</title>
								<meta name="description" content={portfolioContent.snippet}/>
							</Helmet>

									${bodyMarkup}

										{portfolioContent.links.map(link => {
											return (

													{link.label}

											);
										})}

					);
				}
			}
		`
	});

	return acc;
}

(() => {
	glob('portfolio-items/**/*.md', {}, (err, files) => {
		const blogPosts = files.reduce((acc, curr) => {
			acc.push({
				path: curr,
				contents: fs.readFileSync(curr, {encoding: 'utf-8'})
			});

			return acc;
		}, []);

		const reversedComponents = blogPosts.reduce(generateComponent, []);

		fs.copySync(`${__dirname}/../portfolio-items/images`, `${__dirname}/../src/pages/portfolio/images`);
		reversedComponents.forEach(component => {
			fs.writeFileSync(path.resolve(`${__dirname}/../src/pages/portfolio/${component.fileName}.jsx`), component.component);
		});
	});
})();<|endoftext|>


<commit_before>$.Model.extend('ApiType',
/* @Static */
{

	init: function() {
		this.types = [];
		this.url_param_reg = /\{.*?\}/g;

		this.interpolations = {lists: {}};
		//console.log("initting apitype");
	},

	find_type: function(uri) {
	//		console.log("finding type " + uri)
		var r = $.grep(this.types, function(t){return (t.type == uri);});
		return r[0];
	},

	find_all_types_and_calls: function() {
		SMART.ONTOLOGY_get(function(r) {
            var ont = r.graph;
			this.ontology = ont;

			// Get all types
			var types = ont.where("?cls rdf:type owl:Class")
			               .where("?cls rdfs:label ?class_name")
		   		       .optional("?cls api:example ?class_example");

			for (var i = 0; i < types.length; i++) {
				ApiType.create(types[i]);
			}

			// Get all calls
			var calls = ont.where("?call rdf:type api:call")
			   .where("?call api:path ?call_path")
			   .where("?call api:target ?call_target")
			   .where("?call api:category ?call_category")
			   .where("?call api:method ?call_method")
			   .where("?call api:by_internal_id ?call_by_internal_id")
			   .optional("?call api:above ?call_above")
			   .optional("?call api:example ?call_example");

			for (var i = 0; i < calls.length; i++) {
			    if (calls[i].call_category.value.match(/^record/))
				ApiCall.create(calls[i]);
			}

			ApiCallGroup.make_groups();
		    OpenAjax.hub.publish("ontology_parsed");
		});
	},

	addInterpolationValue: function(field, value) {
		if (this.interpolations.lists[field] === undefined)
			this.interpolations.lists[field] = [];

		if ($.inArray(value, this.interpolations.lists[field]) === -1)
			this.interpolations.lists[field].push(value);

	},
	interpolationVars: function(url) {
		var fields = url.match(ApiType.url_param_reg);
		if (fields === null)
		    return [];

		return fields;
	},

	interpolatedPath: function(url) {
		var url = url.replace("http://smartplatforms.org", "");
		var fields = this.interpolationVars(url);

		for (var i = 0; i < fields.length; i++) {
			var f = fields[i];
			var fsans = f.substring(1, f.length-1);

			url = url.replace(f, this.interpolations[fsans]);
		}
		return url;
	},

	create: function(t) {
		var ret = new ApiType({
			type: t.cls.value._string,
			name: t.class_name.value,
			example: t.class_example && t.class_example.value  || ""
		});
		this.types.push(ret);
		return ret;
	},

	pathRegex: function(path) {
		var b = path;
		var fields = b.match(ApiType.url_param_reg);
  	        if (fields == null) fields = [];

		var b = b.replace("http://smartplatforms.org", "");
		for (var i = 0; i < fields.length; i++) {
			var f = fields[i];
			var fsans = f.substring(1, f.length-1);

			b = b.replace(fields[i], "([^/]*)");
		}

		var re = RegExp(b);
		var ret = function(s) {
			var matches = {};
			var m = s.match(re);
			if (m === null) return matches;
			if (m.length != fields.length+1){
				throw "Expected match size = fields size+1"  +
							 m.join(", ")+ " vs. " + fields.join(", ");
			}
			for (var i = 0; i < fields.length; i++) {
				var f = fields[i];
				var fsans = f.substring(1, f.length-1);
				matches[fsans] = m[i+1];
			}

			return matches;
		};

		//console.log("regex " + b);
		return ret;
	}

},
/* @Prototype */
{

  init: function()
  {
	this.calls = [];
  },

  fetchParameters: function() {
   		var c = this.fetchParametersCall();
   		var base_regexes = [];

		$.each(ApiCall.calls, function(path, call) {
			if (call.method == "GET")
				base_regexes.push(ApiType.pathRegex(call.path));
		});

		var args = c.buildCallArgs("", function(contentType, data) {

            if (contentType === "application/rdf+xml") {
                var rdf = SMART.process_rdf(contentType, data);
                var typed_entities = rdf.where("?s rdf:type ?p");
                //console.log("Typed entities available: " + typed_entities.length);

                $.each(typed_entities, function() {
                    var entity_url = ""+this.s.value;
                    $.each(base_regexes, function() {
                        var matched = this(entity_url);
                        $.each(matched, function(fieldname, value) {
                            ApiType.addInterpolationValue(fieldname, value);
                        });

                    });

                });
            }
            ApiType.addInterpolationValue("user_id",SMART.user.id);
            ApiType.addInterpolationValue("smart_app_id",SMART.manifest.id);

   		});

   		SMART.api_call(args[0], args[1]);
   },

   fetchParametersCall: function() {
	   var uri = this.type;
  	   var c = $.grep(ApiCall.calls, function(c) {return c.method=="GET" && c.target === uri && c.category==="record_items";})[0];
  	   return this.oldest_ancestor_call(c);
   },

   oldest_ancestor_call: function(c) {
	//	   console.log("finding oldest ancestor for " + c)
		var c = [c];  // prevent inner scope from creating a global variable.

 		$.each(ApiCall.calls, function(i, possible_parent) {
			if (possible_parent.path == "/records/") return;
 			if (possible_parent.path.length >= c[0].path.length) return;
 			if (c[0].path.match(possible_parent.path)) c[0] = possible_parent;
 		});
 		return c[0];
   }

});

$.Model.extend('ApiCall',
/* @Static */
{

	init: function() {
		this.calls = [];
		this.payload_methods = ['PUT', 'POST'];
		},

	create: function(t) {

		ret = new ApiCall({path: t.call_path.value,
						   target: t.call_target.value._string,
                  				   example: t.call_example?t.call_example.value : undefined,
						   category: t.call_category.value,
						   method: t.call_method.value,
						   by_internal_id: !!(t.call_by_internal_id.value ==="true"),
                                                   above:  t.call_above && t.call_above.value._string || ""});

		this.calls.push(ret);
		return ret;
	}

},
/* @Prototype */
{
	init: function()
	{

	},

	contentType: function() {
		if ($.inArray(this.method, this.Class.payload_methods) !== -1) {
            var path = this.path
            var suffix = "/preferences";
            if (path.indexOf(suffix, path.length - suffix.length) !== -1) {
                // Preferences API call
                return "text/plain";
            } else {
                // All other calls
                return "application/rdf+xml";
            }
		}
		return "application/x-www-form-urlencoded";
	},

	callAPI: function(data, callback) {
		var args = this.buildCallArgs(data, callback);
		SMART.api_call(args[0], args[1]);
	},

	buildCallArgs: function(data, callback) {

		var call_args = [{
			method: this.method,
			url: ApiType.interpolatedPath(this.path),
			contentType: this.contentType(),
			data: data || {}
		}, callback];

		return call_args;
	}
});

$.Model.extend('ApiCallGroup',
/* @Static */
{

	init: function() {
		this.groups= [];
	},

	get_top_groups: function() {
		var g = $.grep(this.groups, function(g) {return (g.group_parent === null);});
		g.sort(function(a,b) {if (a.group_name === b.group_name) return 0; if (a.group_name < b.group_name) return -1; return 1;});
		return g;
	},

	make_groups: function() {
		this.make_record_item_groups();
	},

	make_record_item_groups: function() {
		this.record_item_groups_by_path();
		this.record_item_groups_by_target();

	},

	record_item_groups_by_path: function() {
		var by_path = {};

		$.each(ApiCall.calls, function(i, call) {
			if (by_path[call.path] === undefined )
				by_path[call.path] = [];
			by_path[call.path].push(call);
		});

		var category_names = {"record_item": "Single Item ",
							  "record_items": "All Items "};

		$.each(by_path, function(path, calls) {
			var gn = category_names[calls[0].category];
                        if (calls[0].above !== "") gn += " via " + calls[0].above.split("#")[1]+", "

			if (calls[0].category === "record_item") {
				if (calls[0].by_internal_id === false)
					gn += "by external key";
				else gn += "by id";
			}

			var p = {
					   group_name: gn,
					   group_members: calls,
					   group_parent: null,
					   group_indentation_hint: null,
					   group_type: ApiType.find_type(calls[0].target)
					 };

			var g = new ApiCallGroup({p: p})
			ApiCallGroup.groups.push(g);
		});
	},

	record_item_groups_by_target: function() {
		var by_target = {};
		$.each(ApiCallGroup.groups, function(i, group) {
			var t = group.group_members[0].target;
			if (by_target[t] === undefined )
				by_target[t] = [];
			by_target[t].push(group);
		});

		$.each(by_target, function(target, groups) {
			groups.sort(function(a,b) {if (a.group_name === b.group_name) return 0; if (a.group_name > b.group_name) return -1; return 1;});

			var t= ApiType.find_type(target);

			var p = {
					   group_name: t.name,
					   group_members: groups,
					   group_parent: null,
					   group_indentation_hint: null,
					   group_type: groups[0].group_type
					 };
			var parent = new ApiCallGroup({p: p});
			ApiCallGroup.groups.push(parent);
			$.each(groups, function(i,g) {g.group_parent = parent});
		});
	}

},
/* @Prototype */
{
	init: function()
	{
		this.group_name = this.p.group_name;
		this.group_members = this.p.group_members;

		// the group to which this belongs, if any
		this.group_parent = this.p.group_parent;

		// e.g. fills should be indented below meds
		this.group_indentation_hint = this.p.group_indentation_hint;
		this.group_type = this.p.group_type;
    }
});
<commit_msg>Fixing api playground autocomplete capability<commit_after>$.Model.extend('ApiType',
/* @Static */
{

	init: function() {
		this.types = [];
		this.url_param_reg = /\{.*?\}/g;

		this.interpolations = {lists: {}};
		//console.log("initting apitype");
	},

	find_type: function(uri) {
	//		console.log("finding type " + uri)
		var r = $.grep(this.types, function(t){return (t.type == uri);});
		return r[0];
	},

	find_all_types_and_calls: function() {
		SMART.ONTOLOGY_get(function(r) {
            var ont = r.graph;
			this.ontology = ont;

			// Get all types
			var types = ont.where("?cls rdf:type owl:Class")
			               .where("?cls rdfs:label ?class_name")
		   		       .optional("?cls api:example ?class_example");

			for (var i = 0; i < types.length; i++) {
				ApiType.create(types[i]);
			}

			// Get all calls
			var calls = ont.where("?call rdf:type api:call")
			   .where("?call api:path ?call_path")
			   .where("?call api:target ?call_target")
			   .where("?call api:category ?call_category")
			   .where("?call api:method ?call_method")
			   .where("?call api:by_internal_id ?call_by_internal_id")
			   .optional("?call api:above ?call_above")
			   .optional("?call api:example ?call_example");

			for (var i = 0; i < calls.length; i++) {
			    if (calls[i].call_category.value.match(/^record/))
				ApiCall.create(calls[i]);
			}

			ApiCallGroup.make_groups();
		    OpenAjax.hub.publish("ontology_parsed");
		});
	},

	addInterpolationValue: function(field, value) {
        //console.log ("adding interpolation " + field + " " + value);
		if (this.interpolations.lists[field] === undefined)
			this.interpolations.lists[field] = [];

		if ($.inArray(value, this.interpolations.lists[field]) === -1)
			this.interpolations.lists[field].push(value);

	},
	interpolationVars: function(url) {
		var fields = url.match(ApiType.url_param_reg);
		if (fields === null)
		    return [];

		return fields;
	},

	interpolatedPath: function(url) {
		var url = url.replace("http://smartplatforms.org", "");
		var fields = this.interpolationVars(url);

		for (var i = 0; i < fields.length; i++) {
			var f = fields[i];
			var fsans = f.substring(1, f.length-1);

			url = url.replace(f, this.interpolations[fsans]);
		}
		return url;
	},

	create: function(t) {
		var ret = new ApiType({
			type: t.cls.value._string,
			name: t.class_name.value,
			example: t.class_example && t.class_example.value  || ""
		});
		this.types.push(ret);
		return ret;
	},

	pathRegex: function(path) {
		var b = path;
		var fields = b.match(ApiType.url_param_reg);
  	        if (fields == null) fields = [];

		var b = b.replace("http://smartplatforms.org", "");
		for (var i = 0; i < fields.length; i++) {
			var f = fields[i];
			var fsans = f.substring(1, f.length-1);

			b = b.replace(fields[i], "([^/]*)");
		}

		var re = RegExp(b);
		var ret = function(s) {
			var matches = {};
			var m = s.match(re);
			if (m === null) return matches;
			if (m.length != fields.length+1){
				throw "Expected match size = fields size+1"  +
							 m.join(", ")+ " vs. " + fields.join(", ");
			}
			for (var i = 0; i < fields.length; i++) {
				var f = fields[i];
				var fsans = f.substring(1, f.length-1);
				matches[fsans] = m[i+1];
			}

			return matches;
		};

		//console.log("regex " + b);
		return ret;
	}

},
/* @Prototype */
{

  init: function()
  {
	this.calls = [];
  },

  fetchParameters: function() {
   		var c = this.fetchParametersCall();
   		var base_regexes = [];

		$.each(ApiCall.calls, function(path, call) {
			if (call.method == "GET")
				base_regexes.push(ApiType.pathRegex(call.path));
		});

		var args = c.buildCallArgs("", function(r) {

            if (r.contentType === "application/rdf+xml") {
                var rdf = SMART.process_rdf(r.contentType, r.body);
                var typed_entities = rdf.where("?s rdf:type ?p");
                //console.log("Typed entities available: " + typed_entities.length);

                $.each(typed_entities, function() {
                    var entity_url = ""+this.s.value;
                    $.each(base_regexes, function() {
                        var matched = this(entity_url);
                        $.each(matched, function(fieldname, value) {
                            ApiType.addInterpolationValue(fieldname, value);
                        });

                    });

                });
            }
            ApiType.addInterpolationValue("user_id",SMART.user.id);
            ApiType.addInterpolationValue("smart_app_id",SMART.manifest.id);

   		});

   		SMART.api_call(args[0], args[1]);
   },

   fetchParametersCall: function() {
	   var uri = this.type;
  	   var c = $.grep(ApiCall.calls, function(c) {return c.method=="GET" && c.target === uri && c.category==="record_items";})[0];
  	   return this.oldest_ancestor_call(c);
   },

   oldest_ancestor_call: function(c) {
	//	   console.log("finding oldest ancestor for " + c)
		var c = [c];  // prevent inner scope from creating a global variable.

 		$.each(ApiCall.calls, function(i, possible_parent) {
			if (possible_parent.path == "/records/") return;
 			if (possible_parent.path.length >= c[0].path.length) return;
 			if (c[0].path.match(possible_parent.path)) c[0] = possible_parent;
 		});
 		return c[0];
   }

});

$.Model.extend('ApiCall',
/* @Static */
{

	init: function() {
		this.calls = [];
		this.payload_methods = ['PUT', 'POST'];
		},

	create: function(t) {

		ret = new ApiCall({path: t.call_path.value,
						   target: t.call_target.value._string,
                  				   example: t.call_example?t.call_example.value : undefined,
						   category: t.call_category.value,
						   method: t.call_method.value,
						   by_internal_id: !!(t.call_by_internal_id.value ==="true"),
                                                   above:  t.call_above && t.call_above.value._string || ""});

		this.calls.push(ret);
		return ret;
	}

},
/* @Prototype */
{
	init: function()
	{

	},

	contentType: function() {
		if ($.inArray(this.method, this.Class.payload_methods) !== -1) {
            var path = this.path
            var suffix = "/preferences";
            if (path.indexOf(suffix, path.length - suffix.length) !== -1) {
                // Preferences API call
                return "text/plain";
            } else {
                // All other calls
                return "application/rdf+xml";
            }
		}
		return "application/x-www-form-urlencoded";
	},

	callAPI: function(data, callback) {
		var args = this.buildCallArgs(data, callback);
		SMART.api_call(args[0], args[1]);
	},

	buildCallArgs: function(data, callback) {

		var call_args = [{
			method: this.method,
			url: ApiType.interpolatedPath(this.path),
			contentType: this.contentType(),
			data: data || {}
		}, callback];

		return call_args;
	}
});

$.Model.extend('ApiCallGroup',
/* @Static */
{

	init: function() {
		this.groups= [];
	},

	get_top_groups: function() {
		var g = $.grep(this.groups, function(g) {return (g.group_parent === null);});
		g.sort(function(a,b) {if (a.group_name === b.group_name) return 0; if (a.group_name < b.group_name) return -1; return 1;});
		return g;
	},

	make_groups: function() {
		this.make_record_item_groups();
	},

	make_record_item_groups: function() {
		this.record_item_groups_by_path();
		this.record_item_groups_by_target();

	},

	record_item_groups_by_path: function() {
		var by_path = {};

		$.each(ApiCall.calls, function(i, call) {
			if (by_path[call.path] === undefined )
				by_path[call.path] = [];
			by_path[call.path].push(call);
		});

		var category_names = {"record_item": "Single Item ",
							  "record_items": "All Items "};

		$.each(by_path, function(path, calls) {
			var gn = category_names[calls[0].category];
                        if (calls[0].above !== "") gn += " via " + calls[0].above.split("#")[1]+", "

			if (calls[0].category === "record_item") {
				if (calls[0].by_internal_id === false)
					gn += "by external key";
				else gn += "by id";
			}

			var p = {
					   group_name: gn,
					   group_members: calls,
					   group_parent: null,
					   group_indentation_hint: null,
					   group_type: ApiType.find_type(calls[0].target)
					 };

			var g = new ApiCallGroup({p: p})
			ApiCallGroup.groups.push(g);
		});
	},

	record_item_groups_by_target: function() {
		var by_target = {};
		$.each(ApiCallGroup.groups, function(i, group) {
			var t = group.group_members[0].target;
			if (by_target[t] === undefined )
				by_target[t] = [];
			by_target[t].push(group);
		});

		$.each(by_target, function(target, groups) {
			groups.sort(function(a,b) {if (a.group_name === b.group_name) return 0; if (a.group_name > b.group_name) return -1; return 1;});

			var t= ApiType.find_type(target);

			var p = {
					   group_name: t.name,
					   group_members: groups,
					   group_parent: null,
					   group_indentation_hint: null,
					   group_type: groups[0].group_type
					 };
			var parent = new ApiCallGroup({p: p});
			ApiCallGroup.groups.push(parent);
			$.each(groups, function(i,g) {g.group_parent = parent});
		});
	}

},
/* @Prototype */
{
	init: function()
	{
		this.group_name = this.p.group_name;
		this.group_members = this.p.group_members;

		// the group to which this belongs, if any
		this.group_parent = this.p.group_parent;

		// e.g. fills should be indented below meds
		this.group_indentation_hint = this.p.group_indentation_hint;
		this.group_type = this.p.group_type;
    }
});
<|endoftext|>


<commit_before>importScripts('serviceworker-cache-polyfill.js');

this.addEventListener("install", function (event) {
      event.waitUntil(
        caches.open('v3').then(function (cache) {
         return cache.addAll(['/html/',
          '/html/js/911.js',
          '/html/img/trapped_lady.jpg',
          '/html/img/screaming.jpg',
          '/html/img/location4.jpg',
          '/html/img/embrace3.jpg'
          ]);
        })
        );
    });

this.addEventListener('activate', function(event) {
  var cacheWhitelist = ['v2'];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});

this.addEventListener('fetch', function (event) {
	event.respondWith(
    caches.match(event.request)
    );
});<commit_msg>remove polyfills<commit_after>this.addEventListener("install", function (event) {
      event.waitUntil(
        caches.open('v3').then(function (cache) {
         return cache.addAll(['/html/',
          '/html/js/911.js',
          '/html/img/trapped_lady.jpg',
          '/html/img/screaming.jpg',
          '/html/img/location4.jpg',
          '/html/img/embrace3.jpg'
          ]);
        })
        );
    });

this.addEventListener('activate', function(event) {
  var cacheWhitelist = ['v2'];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});

this.addEventListener('fetch', function (event) {
	event.respondWith(
    caches.match(event.request)
    );
});<|endoftext|>


<commit_before>/*!
  backbone.fetch-cache v0.1.2
  by Andy Appleton - https://github.com/mrappleton/backbone-fetch-cache.git
 */

// AMD wrapper from https://github.com/umdjs/umd/blob/master/amdWebGlobal.js

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module and set browser global
    define(['underscore', 'backbone'], function (_, Backbone) {
      return (root.Backbone = factory(_, Backbone));
    });
  } else {
    // Browser globals
    root.Backbone = factory(root._, root.Backbone);
  }
}(this, function (_, Backbone) {

  // Setup
  var modelFetch = Backbone.Model.prototype.fetch,
      collectionFetch = Backbone.Collection.prototype.fetch,
      supportLocalStorage = typeof window.localStorage !== 'undefined';

  Backbone.fetchCache = (Backbone.fetchCache || {});
  Backbone.fetchCache._cache = (Backbone.fetchCache._cache || {});

  Backbone.fetchCache.priorityFn = function(a, b) {
    if (!a || !a.expires || !b || !b.expires) {
      return a;
    }

    return a.expires - b.expires;
  };

  Backbone.fetchCache._prioritize = function() {
    var sorted = _.values(this._cache).sort(this.priorityFn);
    var index = _.indexOf(_.values(this._cache), sorted[0]);
    return _.keys(this._cache)[index];
  };

  Backbone.fetchCache._deleteCacheWithPriority = function() {
    Backbone.fetchCache._cache[this._prioritize()] = null;
    delete Backbone.fetchCache._cache[this._prioritize()];

    localStorage.setItem('backboneCache', JSON.stringify(Backbone.fetchCache._cache));
  };

  if (typeof Backbone.fetchCache.localStorage === 'undefined') {
    Backbone.fetchCache.localStorage = true;
  }

  // Shared methods
  function setCache(instance, opts, attrs) {
    opts = (opts || {});
    var url = _.isFunction(instance.url) ? instance.url() : instance.url,
        expires = false;

    // need url to use as cache key so return if we can't get it
    if (!url) { return; }

    if (opts.expires !== false) {
      expires = (new Date()).getTime() + ((opts.expires || 5 * 60) * 1000);
    }

    Backbone.fetchCache._cache[url] = {
      expires: expires,
      value: attrs
    };

    Backbone.fetchCache.setLocalStorage();
  }

  function setLocalStorage() {
    if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
    try {
      localStorage.setItem('backboneCache', JSON.stringify(Backbone.fetchCache._cache));
    } catch (err) {
      if (err.name === 'QUOTA_EXCEEDED_ERR') {
        this.deleteCacheWithPriority();
      }
    }
  }

  function getLocalStorage() {
    if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
    Backbone.fetchCache._cache = JSON.parse(localStorage.getItem('backboneCache')) || {};
  }

  // Instance methods
  Backbone.Model.prototype.fetch = function(opts) {
    opts = (opts || {});
    var url = _.isFunction(this.url) ? this.url() : this.url,
        data = Backbone.fetchCache._cache[url],
        expired = false,
        attributes = false,
        promise = new $.Deferred();

    if (data) {
      expired = data.expires;
      expired = expired && data.expires < (new Date()).getTime();
      attributes = data.value;
    }

    if (!expired && (opts.cache || opts.prefill) && attributes) {
      this.set(attributes, opts);
      if (_.isFunction(opts.prefillSuccess)) { opts.prefillSuccess(this); }

      // Notify progress if we're still waiting for an AJAX call to happen...
      if (opts.prefill) { promise.notify(this); }
      // ...finish and return if we're not
      else {
        if (_.isFunction(opts.success)) { opts.success(this); }
        // Mimic actual fetch behaviour buy returning a fulfilled promise
        return promise.resolve(this);
      }
    }

    // Delegate to the actual fetch method and store the attributes in the cache
    modelFetch.apply(this, arguments)
      // resolve the returned promise when the AJAX call completes
      .done( _.bind(promise.resolve, this, this) )
      // Set the new data in the cache
      .done( _.bind(Backbone.fetchCache.setCache, null, this, opts) );

    // return a promise which provides the same methods as a jqXHR object
    return promise;
  };

  Backbone.Collection.prototype.fetch = function(opts) {
    opts = (opts || {});
    var url = _.isFunction(this.url) ? this.url() : this.url,
        data = Backbone.fetchCache._cache[url],
        expired = false,
        attributes = false,
        promise = new $.Deferred();

    if (data) {
      expired = data.expires;
      expired = expired && data.expires < (new Date()).getTime();
      attributes = data.value;
    }

    if (!expired && (opts.cache || opts.prefill) && attributes) {
      this[opts.add ? 'add' : 'reset'](this.parse(attributes), opts);
      if (_.isFunction(opts.prefillSuccess)) { opts.prefillSuccess(this); }

      // Notify progress if we're still waiting for an AJAX call to happen...
      if (opts.prefill) { promise.notify(this); }
      // ...finish and return if we're not
      else {
        if (_.isFunction(opts.success)) { opts.success(this); }
        // Mimic actual fetch behaviour buy returning a fulfilled promise
        return promise.resolve(this);
      }
    }

    // Delegate to the actual fetch method and store the attributes in the cache
    collectionFetch.apply(this, arguments)
      // resolve the returned promise when the AJAX call completes
      .done( _.bind(promise.resolve, this, this) )
      // Set the new data in the cache
      .done( _.bind(Backbone.fetchCache.setCache, null, this, opts) );

    // return a promise which provides the same methods as a jqXHR object
    return promise;
  };

  // Prime the cache from localStorage on initialization
  getLocalStorage();

  // Exports
  Backbone.fetchCache.setCache = setCache;
  Backbone.fetchCache.setLocalStorage = setLocalStorage;
  Backbone.fetchCache.getLocalStorage = getLocalStorage;

  return Backbone;
}));
<commit_msg>Recursively tries to free cache when full<commit_after>/*!
  backbone.fetch-cache v0.1.2
  by Andy Appleton - https://github.com/mrappleton/backbone-fetch-cache.git
 */

// AMD wrapper from https://github.com/umdjs/umd/blob/master/amdWebGlobal.js

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module and set browser global
    define(['underscore', 'backbone'], function (_, Backbone) {
      return (root.Backbone = factory(_, Backbone));
    });
  } else {
    // Browser globals
    root.Backbone = factory(root._, root.Backbone);
  }
}(this, function (_, Backbone) {

  // Setup
  var modelFetch = Backbone.Model.prototype.fetch,
      collectionFetch = Backbone.Collection.prototype.fetch,
      supportLocalStorage = typeof window.localStorage !== 'undefined';

  Backbone.fetchCache = (Backbone.fetchCache || {});
  Backbone.fetchCache._cache = (Backbone.fetchCache._cache || {});

  Backbone.fetchCache.priorityFn = function(a, b) {
    if (!a || !a.expires || !b || !b.expires) {
      return a;
    }

    return a.expires - b.expires;
  };

  Backbone.fetchCache._prioritize = function() {
    var sorted = _.values(this._cache).sort(this.priorityFn);
    var index = _.indexOf(_.values(this._cache), sorted[0]);
    return _.keys(this._cache)[index];
  };

  Backbone.fetchCache._deleteCacheWithPriority = function() {
    Backbone.fetchCache._cache[this._prioritize()] = null;
    delete Backbone.fetchCache._cache[this._prioritize()];

    try {
      localStorage.setItem('backboneCache', JSON.stringify(Backbone.fetchCache._cache));
    } catch (err) {
      if (err.name.toUpperCase() === 'QUOTA_EXCEEDED_ERR') {
        this._deleteCacheWithPriority();
      } else {
        throw(err);
      }
    }
  };

  if (typeof Backbone.fetchCache.localStorage === 'undefined') {
    Backbone.fetchCache.localStorage = true;
  }

  // Shared methods
  function setCache(instance, opts, attrs) {
    opts = (opts || {});
    var url = _.isFunction(instance.url) ? instance.url() : instance.url,
        expires = false;

    // need url to use as cache key so return if we can't get it
    if (!url) { return; }

    if (opts.expires !== false) {
      expires = (new Date()).getTime() + ((opts.expires || 5 * 60) * 1000);
    }

    Backbone.fetchCache._cache[url] = {
      expires: expires,
      value: attrs
    };

    Backbone.fetchCache.setLocalStorage();
  }

  function setLocalStorage() {
    if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
    try {
      localStorage.setItem('backboneCache', JSON.stringify(Backbone.fetchCache._cache));
    } catch (err) {
      if (err.name.toUpperCase() === 'QUOTA_EXCEEDED_ERR') {
        this._deleteCacheWithPriority();
      } else {
        throw(err);
      }
    }
  }

  function getLocalStorage() {
    if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
    Backbone.fetchCache._cache = JSON.parse(localStorage.getItem('backboneCache')) || {};
  }

  // Instance methods
  Backbone.Model.prototype.fetch = function(opts) {
    opts = (opts || {});
    var url = _.isFunction(this.url) ? this.url() : this.url,
        data = Backbone.fetchCache._cache[url],
        expired = false,
        attributes = false,
        promise = new $.Deferred();

    if (data) {
      expired = data.expires;
      expired = expired && data.expires < (new Date()).getTime();
      attributes = data.value;
    }

    if (!expired && (opts.cache || opts.prefill) && attributes) {
      this.set(attributes, opts);
      if (_.isFunction(opts.prefillSuccess)) { opts.prefillSuccess(this); }

      // Notify progress if we're still waiting for an AJAX call to happen...
      if (opts.prefill) { promise.notify(this); }
      // ...finish and return if we're not
      else {
        if (_.isFunction(opts.success)) { opts.success(this); }
        // Mimic actual fetch behaviour buy returning a fulfilled promise
        return promise.resolve(this);
      }
    }

    // Delegate to the actual fetch method and store the attributes in the cache
    modelFetch.apply(this, arguments)
      // resolve the returned promise when the AJAX call completes
      .done( _.bind(promise.resolve, this, this) )
      // Set the new data in the cache
      .done( _.bind(Backbone.fetchCache.setCache, null, this, opts) );

    // return a promise which provides the same methods as a jqXHR object
    return promise;
  };

  Backbone.Collection.prototype.fetch = function(opts) {
    opts = (opts || {});
    var url = _.isFunction(this.url) ? this.url() : this.url,
        data = Backbone.fetchCache._cache[url],
        expired = false,
        attributes = false,
        promise = new $.Deferred();

    if (data) {
      expired = data.expires;
      expired = expired && data.expires < (new Date()).getTime();
      attributes = data.value;
    }

    if (!expired && (opts.cache || opts.prefill) && attributes) {
      this[opts.add ? 'add' : 'reset'](this.parse(attributes), opts);
      if (_.isFunction(opts.prefillSuccess)) { opts.prefillSuccess(this); }

      // Notify progress if we're still waiting for an AJAX call to happen...
      if (opts.prefill) { promise.notify(this); }
      // ...finish and return if we're not
      else {
        if (_.isFunction(opts.success)) { opts.success(this); }
        // Mimic actual fetch behaviour buy returning a fulfilled promise
        return promise.resolve(this);
      }
    }

    // Delegate to the actual fetch method and store the attributes in the cache
    collectionFetch.apply(this, arguments)
      // resolve the returned promise when the AJAX call completes
      .done( _.bind(promise.resolve, this, this) )
      // Set the new data in the cache
      .done( _.bind(Backbone.fetchCache.setCache, null, this, opts) );

    // return a promise which provides the same methods as a jqXHR object
    return promise;
  };

  // Prime the cache from localStorage on initialization
  getLocalStorage();

  // Exports
  Backbone.fetchCache.setCache = setCache;
  Backbone.fetchCache.setLocalStorage = setLocalStorage;
  Backbone.fetchCache.getLocalStorage = getLocalStorage;

  return Backbone;
}));
<|endoftext|>


<commit_before>//imports
const Gpio = require('pigpio').Gpio
const {writeFileSync, readFileSync} = require('fs')

// constants
const SENSITIVITY = 625

//initialize
const led = new Gpio(47, {mode: Gpio.OUTPUT})
const sideA = new Gpio(10, {
  mode: Gpio.INPUT,
  pullUpDown: Gpio.PUD_DOWN,
  edge: Gpio.EITHER_EDGE
})
const sideB = new Gpio(9, {
  mode: Gpio.INPUT,
  pullUpDown: Gpio.PUD_DOWN,
  edge: Gpio.EITHER_EDGE
})

// get initial state
writeFileSync( 'stateA',sideA.digitalRead(), 'utf8' )
writeFileSync( 'stateB',sideB.digitalRead(), 'utf8' )

// helper
const debounce = (func, wait, immediate) => {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

// side A listener
sideA.on('interrupt', debounce( (level) =>{

  writeFileSync( 'stateA',level, 'utf8' )
  stateA = readFileSync('stateA', 'utf8')
  stateB = readFileSync('stateB', 'utf8')
  sendMessage(stateA, stateB)

},SENSITIVITY))

//sideB listener
sideB.on('interrupt', debounce( (level) => {
  writeFileSync( 'stateB',level, 'utf8' )
  stateA = readFileSync('stateA', 'utf8')
  stateB = readFileSync('stateB', 'utf8')
  sendMessage(stateA, stateB)

}, SENSITIVITY))

// TODO: sends state to cloud
const sendMessage = ( stateA, stateB) => console.log(stateA, stateB)
<commit_msg>hardware done<commit_after>//imports
const Gpio = require('pigpio').Gpio
const {writeFileSync, readFileSync} = require('fs')

// constants
const SENSITIVITY = 625

//initialize
const led = new Gpio(47, {mode: Gpio.OUTPUT})
const sideA = new Gpio(10, {
  mode: Gpio.INPUT,
  pullUpDown: Gpio.PUD_DOWN,
  edge: Gpio.EITHER_EDGE
})
const sideB = new Gpio(9, {
  mode: Gpio.INPUT,
  pullUpDown: Gpio.PUD_DOWN,
  edge: Gpio.EITHER_EDGE
})

// get initial state
writeFileSync( 'stateA',sideA.digitalRead(), 'utf8' )
writeFileSync( 'stateB',sideB.digitalRead(), 'utf8' )

// helper
const debounce = (func, wait, immediate) => {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};

// helper
const debounce = (func, wait, immediate) => {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

// side A listener
sideA.on('interrupt', debounce( (level) =>{

  writeFileSync( 'stateA',level, 'utf8' )
  stateA = readFileSync('stateA', 'utf8')
  stateB = readFileSync('stateB', 'utf8')
  sendMessage(stateA, stateB)

},SENSITIVITY))

//sideB listener
sideB.on('interrupt', debounce( (level) => {
  writeFileSync( 'stateB',level, 'utf8' )
  stateA = readFileSync('stateA', 'utf8')
  stateB = readFileSync('stateB', 'utf8')
  sendMessage(stateA, stateB)

}, SENSITIVITY))

// TODO: sends state to cloud
const sendMessage = ( stateA, stateB) => console.log(stateA, stateB)
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var pkg = require('../package.json')
require('update-notifier')({pkg: pkg}).notify()

var <%= appname %> = require('./')
var cli = require('meow')({
  pkg: pkg
  help: require('fs').readFileSync(__dirname + '/help.txt', 'utf8')
})

if (cli.input.length === 0) cli.showHelp()
<commit_msg>improve cli<commit_after>#!/usr/bin/env node
'use strict';

var path = require('path')
var pkg = require('../package.json')

require('update-notifier')({pkg: pkg}).notify()

var <%= appname %> = require('./')

var cli = require('meow')({
  pkg: pkg,
  help: require('fs').readFileSync(path.join(__dirname, 'help.txt'), 'utf8')
})

if (cli.input.length === 0) cli.showHelp()
<|endoftext|>


<commit_before>function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

function replaceAll(find, replace, str) {
    // http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript#answer-1144788
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

function chevron_toggle(show, $toggling, $chevron, $holds_toggle_state, after_fn) {
    var chev = "icon-double-angle-",
        chevB3 = "fa-angle-double-";
    if (show) {
        $toggling.hide();
        $chevron
            .removeClass(chev + "down")
            .addClass(chev + "right")
            .removeClass(chevB3 + "down")
            .addClass(chevB3 + "right");
        $holds_toggle_state.data("show", false);
    } else {
        $toggling.show();
        $toggling.removeClass('hide');
        $chevron
            .removeClass(chev + "right")
            .addClass(chev + "down")
            .removeClass(chevB3 + "right")
            .addClass(chevB3 + "down");
        $holds_toggle_state.data("show", true);
    }
    if (after_fn) {
        after_fn();
    }
}

$(function () {
    $(".more-sortable-button").click(function() {
        var $this = $(this);
        var sortable = $this.data('sortable').replace(new RegExp("\\.", "g"), "\\.");
        $('.sortable-' + sortable).removeClass('hide');
        $this.hide();
        return false;
    });

    $(".facet-group-btn").click(function(){
        var $this = $(this);
        var group_name = $this.data('name');
        var $facet_group = $(".facet-group[data-group-name='" + group_name + "']");

        chevron_toggle($facet_group.data('show'), $facet_group, $this.children('.facet-group-chevron'), $facet_group);
        return false;
    });

    $(".facet-btn").click(function(){
        var $this = $(this);
        var sortable = replaceAll(".", "\\.", $this.data('sortable'));

        var fn = function() {
            $(".more-sortable-button[data-sortable='" + sortable + "']").hide();
        };

        chevron_toggle($this.data('show'), $(".sortable-" + sortable), $this.find('.facet-chevron'), $this, fn);
        return false;
    });

    var $update_btn = $("#update-facets");
    var $facet_search_form = $("#facet-search");
    var $facet_search_bar = $facet_search_form.find('input');
    $update_btn.click(function() {
        var $this = $(this);
        var url = "?";
        if ($this.data('params')) {
            url += $(this).data('params') + "&";
        }
        var prefix = "";
        if ($this.data('prefix')) {
            prefix += $(this).data('prefix')
        }

        $(".sortable").each(function(){
            var sortable_name = $(this).data("name");
            $(this).find('.facet-checkbox').each(function(){
                $facet = $(this);
                if ($facet.is(":checked") && $facet.attr("name")) {
                    url += prefix + sortable_name + "=" + $facet.attr("name") + "&";
                }
            })
        });

        if ($facet_search_bar.val()) {
            var name = $facet_search_bar.attr("name") || "search";
            url += name + "=" + $facet_search_bar.val()
        }
        window.location = encodeURI(url);
    });

    $facet_search_form.submit(function(e) {
        e.preventDefault();
        $update_btn.click();
    });
});
<commit_msg>facet_sidebar.js<commit_after>hqDefine("appstore/js/facet_sidebar", function() {
    var escapeRegExp = function(str) {
        return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }

    var replaceAll = function(find, replace, str) {
        // http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript#answer-1144788
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }

    var chevron_toggle = function(show, $toggling, $chevron, $holds_toggle_state, after_fn) {
        var chev = "icon-double-angle-",
            chevB3 = "fa-angle-double-";
        if (show) {
            $toggling.hide();
            $chevron
                .removeClass(chev + "down")
                .addClass(chev + "right")
                .removeClass(chevB3 + "down")
                .addClass(chevB3 + "right");
            $holds_toggle_state.data("show", false);
        } else {
            $toggling.show();
            $toggling.removeClass('hide');
            $chevron
                .removeClass(chev + "right")
                .addClass(chev + "down")
                .removeClass(chevB3 + "right")
                .addClass(chevB3 + "down");
            $holds_toggle_state.data("show", true);
        }
        if (after_fn) {
            after_fn();
        }
    }

    $(function () {
        $(".more-sortable-button").click(function() {
            var $this = $(this);
            var sortable = $this.data('sortable').replace(new RegExp("\\.", "g"), "\\.");
            $('.sortable-' + sortable).removeClass('hide');
            $this.hide();
            return false;
        });

        $(".facet-group-btn").click(function(){
            var $this = $(this);
            var group_name = $this.data('name');
            var $facet_group = $(".facet-group[data-group-name='" + group_name + "']");

            chevron_toggle($facet_group.data('show'), $facet_group, $this.children('.facet-group-chevron'), $facet_group);
            return false;
        });

        $(".facet-btn").click(function(){
            var $this = $(this);
            var sortable = replaceAll(".", "\\.", $this.data('sortable'));

            var fn = function() {
                $(".more-sortable-button[data-sortable='" + sortable + "']").hide();
            };

            chevron_toggle($this.data('show'), $(".sortable-" + sortable), $this.find('.facet-chevron'), $this, fn);
            return false;
        });

        var $update_btn = $("#update-facets");
        var $facet_search_form = $("#facet-search");
        var $facet_search_bar = $facet_search_form.find('input');
        $update_btn.click(function() {
            var $this = $(this);
            var url = "?";
            if ($this.data('params')) {
                url += $(this).data('params') + "&";
            }
            var prefix = "";
            if ($this.data('prefix')) {
                prefix += $(this).data('prefix')
            }

            $(".sortable").each(function(){
                var sortable_name = $(this).data("name");
                $(this).find('.facet-checkbox').each(function(){
                    $facet = $(this);
                    if ($facet.is(":checked") && $facet.attr("name")) {
                        url += prefix + sortable_name + "=" + $facet.attr("name") + "&";
                    }
                })
            });

            if ($facet_search_bar.val()) {
                var name = $facet_search_bar.attr("name") || "search";
                url += name + "=" + $facet_search_bar.val()
            }
            window.location = encodeURI(url);
        });

        $facet_search_form.submit(function(e) {
            e.preventDefault();
            $update_btn.click();
        });
    });
});
<|endoftext|>


<commit_before>define
([
    'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
    'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
<<<<<<< HEAD
    var AuthLogin = function(username, password, logintoken){
=======
    var AuthDetails = function(username){
		var authDetails = new $.rest('Superdesk/User');
		authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){
			var user = users.UserList[0];
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.Name);
			localStorage.setItem('superdesk.login.email', user.EMail);
		});
		return $(authDetails);
	},
	AuthLogin = function(username, password, logintoken){
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
		var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
			authLogin = new $.rest('Authentication');
			authLogin.resetData().insert({
			UserName: username,
			LoginToken: logintoken,
			HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
		}).done(function(user){
			localStorage.setItem('superdesk.login.session', user.Session);
<<<<<<< HEAD
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.UserName);
			localStorage.setItem('superdesk.login.email', user.EMail);
			$(authLogin).trigger('success');
=======
			//localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.UserName);
			localStorage.setItem('superdesk.login.email', user.EMail);
			$(authLogin).trigger('success');
/*			authDetails = AuthDetails(username);
			$(authDetails).on('failed', function(){
				$(authLogin).trigger('failed', 'authDetails');
			});
*/
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
		});
		return $(authLogin);
	},
	AuthToken = function(username, password) {
		var authToken = new $.rest('Authentication');
		authToken.resetData().select({ userName: username }).done(
			function(data){
				authLogin = AuthLogin(username, password, data.Token);
				authLogin.on('failed', function(){
					$(authToken).trigger('failed', 'authToken');
				}).on('success', function(){
					$(authToken).trigger('success');
				});
			}
		);
		return $(authToken);
	},
	AuthApp =
    {
        success: $.noop,
        require: function()
        {
			if(this.showed) return;
            var self = this; // rest
			self.showed = true;
            $.tmpl('auth', null, function(e, o)
            {
                var dialog = $(o).eq(0).dialog
                ({
                    draggable: false,
                    resizable: false,
                    modal: true,
                    width: "40.1709%",
                    buttons:
                    [
                         { text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
                         { text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
                    ]
                }),
                    form = dialog.find('form');
                form.off('submit.superdesk')//
                .on('submit.superdesk', function(event)
                {
                    var username = $(this).find('#username'), password=$(this).find('#password');
					AuthToken(username.val(), password.val()).on('failed',function(evt, type){
						username.val('');
						password.val('')
					}).on('success', function(){
                        AuthApp.success && AuthApp.success.apply();
						$(dialog).dialog('close');
						self.showed = false;
					});
                    event.preventDefault();

                });
            });
        }
    };
    return AuthApp;
});<commit_msg>NR-226: Create login functionality in Ally framework<commit_after>define
([
    'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
    'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
<<<<<<< HEAD
    var AuthLogin = function(username, password, logintoken){
=======
    var AuthDetails = function(username){
		var authDetails = new $.rest('Superdesk/User');
		authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){
			var user = users.UserList[0];
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.Name);
			localStorage.setItem('superdesk.login.email', user.EMail);
		});
		return $(authDetails);
	},
	AuthLogin = function(username, password, logintoken){
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
		var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
			authLogin = new $.rest('Authentication');
			authLogin.resetData().insert({
			UserName: username,
			LoginToken: logintoken,
			HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
		}).done(function(user){
			localStorage.setItem('superdesk.login.session', user.Session);
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.UserName);
			localStorage.setItem('superdesk.login.email', user.EMail);
			$(authLogin).trigger('success');
		});
		return $(authLogin);
	},
	AuthToken = function(username, password) {
		var authToken = new $.rest('Authentication');
		authToken.resetData().select({ userName: username }).done(
			function(data){
				authLogin = AuthLogin(username, password, data.Token);
				authLogin.on('failed', function(){
					$(authToken).trigger('failed', 'authToken');
				}).on('success', function(){
					$(authToken).trigger('success');
				});
			}
		);
		return $(authToken);
	},
	AuthApp =
    {
        success: $.noop,
        require: function()
        {
			if(this.showed) return;
            var self = this; // rest
			self.showed = true;
            $.tmpl('auth', null, function(e, o)
            {
                var dialog = $(o).eq(0).dialog
                ({
                    draggable: false,
                    resizable: false,
                    modal: true,
                    width: "40.1709%",
                    buttons:
                    [
                         { text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
                         { text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
                    ]
                }),
                    form = dialog.find('form');
                form.off('submit.superdesk')//
                .on('submit.superdesk', function(event)
                {
                    var username = $(this).find('#username'), password=$(this).find('#password');
					AuthToken(username.val(), password.val()).on('failed',function(evt, type){
						username.val('');
						password.val('')
					}).on('success', function(){
                        AuthApp.success && AuthApp.success.apply();
						$(dialog).dialog('close');
						self.showed = false;
					});
                    event.preventDefault();

                });
            });
        }
    };
    return AuthApp;
});<|endoftext|>


<commit_before>//SIDEBAR VARIABLES
var af_sidebar_loader	= false;
var af_sidebar_open		= {};
var af_sidebar_path		= '';

//PROCESS SIDEBAR LOADING OF PAGE
var af_sidebar_ajax = function(event, url, auto, nopush) {

	//IF THIS IS AN EMPTY URL, DO NOTHING
	if (url == null) return false;
	url = String(url).trim();
	if (!url  ||  url == '#') return false;

	//PREVENT DEFAULT ACTIONS ON ANCHORS
	if (event) {
		if (event.which != 1) return false;
		if (af_sidebar_loader) af_sidebar_loader.abort();
		event.preventDefault();
		event.stopPropagation();
	}

	//REMOVE OLD HIGHLIGHT FROM SIDEBAR
	$('.af-sidebar-selected').removeClass('af-sidebar-selected');

	//ADD NEW HIGHLIGHT TO SIDEBAR
	$('#af-sidebar-parent a[href="' + url.replace(af_sidebar_path, '') + '"]')
		.addClass('af-sidebar-selected');

	//IF THIS IS PAGE LOAD INSTEAD OF CONTENT LOAD, DON'T DO ANYTHING ELSE
	if (auto) return af_sidebar_load();

	//SCROLL TO TOP/LEFT OF DIV
	 $('#af-sidebar-page').html('').scrollTop(0).scrollLeft(0);

	//PREVENT RECURSION
	if (!nopush) history_block = true;

	//PUSH URL TO HISTORY STATE
	History.pushState(null, document.title, url);

	//AJAX REQUEST TO LOAD NEW PAGE
	af_sidebar_loader = $.ajax({
		url:		url,
		data:		{jq:1, sidebar:1},

		success:	function(data) {
			$('#af-sidebar-page').html(data);
			af_sidebar_load();
		},

		error:		function(xhr) {
			$('#af-sidebar-page').html(xhr.responseText);
			af_sidebar_load();
		},
	});

	//PREVENT RECURSION
	history_block = false;

	return true;
};

//OVERWRITE ANCHOR CLICK HANDLER
var af_sidebar_load = function() {
	$('#af-sidebar-page a').each(function(id, item) {
		if ($(item).hasClass('af-sidebar-link')) return;

		$(item).addClass('af-sidebar-link').click(function(event) {
			if ($(this).prop('target')) return;
			af_sidebar_ajax(event, $(this).attr('href'));
		});
	});

	return true;
};

//INITIALIZE SIDEBAR - CALLED FROM PAGE'S TEMPLATE
var af_sidebar_init = function(path) {
	if (af_sidebar_path != '') return;

	//INITIALIZE VARIABLES
	af_sidebar_path = path;
	af_sidebar_open = af_storage_read('af_sidebar_open');

	//OVERWRITE DEFAULT REFRESH RULE
	refresh = function() {
		af_sidebar_ajax(false, document.location, false);
	};

	//OVERWRITE DEFAULT REDIRECT RULE
	redirect = function(url) {
		af_sidebar_ajax(false, url, false);
	};

	//OVERWRITE ANCHOR CLICK HANDLER
	$('#af-sidebar-list a').click(function(event){
		if ($(this).attr('target')) return;
		if (!af_sidebar_ajax(event, $(this).attr('href'))) return;
		$('#af-sidebar-page').html('').scrollTop(0).scrollLeft(0);
	});

	//OPEN/CLOSE MENUS ON CLICKING
	$('#af-sidebar-list div span').click(function() {
		var parent = $(this).parent();

		if (parent.children('div,a,hr').is(':animated')) return;

		parent.addClass('af-sidebar-open');

		var visible = !parent.children('div,a,hr').is(':visible');

		af_sidebar_open['menu-'+parent.data('af-sidebar-menu')] = visible ? 1 : 0;
		af_storage_write('af_sidebar_open', af_sidebar_open);

		$(this).children('i').css('transform', visible ? 'rotate(90deg)' : '');

		parent.children('div,a,hr').slideToggle(function() {
			if (visible) {
				$(this).css('display','block');
			} else {
				parent.removeClass('af-sidebar-open');
			}
		});
	});

	//HIDE ALL SUBMENUS BY DEFAULT
	$('#af-sidebar-list div').children('div,a,hr').hide();

	//OPEN EACH MENU FROM LOCAL STORAGE INFORMATION
	for (var prop in af_sidebar_open) {
		if (!af_sidebar_open[prop]) continue;
		prop = prop.replace('menu-', '');
		var parent = $('#af-sidebar-parent div[data-af-sidebar-menu='+afEscape(prop)+']');
		parent.addClass('af-sidebar-open');
		parent.children('span').children('i').css('transform', 'rotate(90deg)');
		parent.children('div,a,hr').css('display','block');
	}

	//SHOW THE SIDEBAR
	$('#af-sidebar-list').show();

	//PROCESS INITIAL URL
	af_sidebar_ajax(false, document.location.pathname, true, true);
};
<commit_msg>Inverted the meaning of 'Auto', and made it a variable inside of af_sidebar_init<commit_after>//SIDEBAR VARIABLES
var af_sidebar_loader	= false;
var af_sidebar_open		= {};
var af_sidebar_path		= '';

//PROCESS SIDEBAR LOADING OF PAGE
var af_sidebar_ajax = function(event, url, auto, nopush) {
	//IF THIS IS AN EMPTY URL, DO NOTHING
	if (url == null) return false;
	url = String(url).trim();
	if (!url  ||  url == '#') return false;

	//PREVENT DEFAULT ACTIONS ON ANCHORS
	if (event) {
		if (event.which != 1) return false;
		if (af_sidebar_loader) af_sidebar_loader.abort();
		event.preventDefault();
		event.stopPropagation();
	}

	//REMOVE OLD HIGHLIGHT FROM SIDEBAR
	$('.af-sidebar-selected').removeClass('af-sidebar-selected');

	//ADD NEW HIGHLIGHT TO SIDEBAR
	$('#af-sidebar-parent a[href="' + url.replace(af_sidebar_path, '') + '"]')
		.addClass('af-sidebar-selected');

	//SHOULD WE AUTO-LOAD CONTENT, OR JUST PROCESS THE CONTENT WE ALREADY HAVE
	if (!auto) return af_sidebar_load();

	//SCROLL TO TOP/LEFT OF DIV
	 $('#af-sidebar-page').html('').scrollTop(0).scrollLeft(0);

	//PREVENT RECURSION
	if (!nopush) history_block = true;

	//PUSH URL TO HISTORY STATE
	History.pushState(null, document.title, url);

	//AJAX REQUEST TO LOAD NEW PAGE
	af_sidebar_loader = $.ajax({
		url:		url,
		data:		{jq:1, sidebar:1},

		success:	function(data) {
			$('#af-sidebar-page').html(data);
			af_sidebar_load();
		},

		error:		function(xhr) {
			$('#af-sidebar-page').html(xhr.responseText);
			af_sidebar_load();
		},
	});

	//PREVENT RECURSION
	history_block = false;

	return true;
};

//OVERWRITE ANCHOR CLICK HANDLER
var af_sidebar_load = function() {
	$('#af-sidebar-page a').each(function(id, item) {
		if ($(item).hasClass('af-sidebar-link')) return;

		$(item).addClass('af-sidebar-link').click(function(event) {
			if ($(this).prop('target')) return;
			af_sidebar_ajax(event, $(this).attr('href'));
		});
	});

	return true;
};

//INITIALIZE SIDEBAR - CALLED FROM PAGE'S TEMPLATE
var af_sidebar_init = function(path, auto) {
	if (af_sidebar_path != '') return;

	//INITIALIZE VARIABLES
	af_sidebar_path = path;
	af_sidebar_open = af_storage_read('af_sidebar_open');

	//OVERWRITE DEFAULT REFRESH RULE
	refresh = function() {
		af_sidebar_ajax(false, document.location);
	};

	//OVERWRITE DEFAULT REDIRECT RULE
	redirect = function(url) {
		af_sidebar_ajax(false, url);
	};

	//OVERWRITE ANCHOR CLICK HANDLER
	$('#af-sidebar-list a').click(function(event){
		if ($(this).attr('target')) return;
		if (!af_sidebar_ajax(event, $(this).attr('href'))) return;
		$('#af-sidebar-page').html('').scrollTop(0).scrollLeft(0);
	});

	//OPEN/CLOSE MENUS ON CLICKING
	$('#af-sidebar-list div span').click(function() {
		var parent = $(this).parent();

		if (parent.children('div,a,hr').is(':animated')) return;

		parent.addClass('af-sidebar-open');

		var visible = !parent.children('div,a,hr').is(':visible');

		af_sidebar_open['menu-'+parent.data('af-sidebar-menu')] = visible ? 1 : 0;
		af_storage_write('af_sidebar_open', af_sidebar_open);

		$(this).children('i').css('transform', visible ? 'rotate(90deg)' : '');

		parent.children('div,a,hr').slideToggle(function() {
			if (visible) {
				$(this).css('display','block');
			} else {
				parent.removeClass('af-sidebar-open');
			}
		});
	});

	//HIDE ALL SUBMENUS BY DEFAULT
	$('#af-sidebar-list div').children('div,a,hr').hide();

	//OPEN EACH MENU FROM LOCAL STORAGE INFORMATION
	for (var prop in af_sidebar_open) {
		if (!af_sidebar_open[prop]) continue;
		prop = prop.replace('menu-', '');
		var parent = $('#af-sidebar-parent div[data-af-sidebar-menu='+afEscape(prop)+']');
		parent.addClass('af-sidebar-open');
		parent.children('span').children('i').css('transform', 'rotate(90deg)');
		parent.children('div,a,hr').css('display','block');
	}

	//SHOW THE SIDEBAR
	$('#af-sidebar-list').show();

	//PROCESS INITIAL URL
	af_sidebar_ajax(false, document.location.pathname, auto, true);
};
<|endoftext|>