text:
import sys
import operator
import copy

import csb.test as test
import csb.core as utils

from csb.io import Pickle

@test.unit
class TestDeepCopy(test.Case):

    def runTest(self):

        rec = sys.getrecursionlimit()
        obj = ['X']
        copy = utils.deepcopy(obj, recursion=(rec + 1))

        self.assertEqual(obj, copy)
        self.assertNotEquals(id(obj), id(copy))

@test.unit
class TestIterable(test.Case):

    def runTest(self):

        for i in [ [], tuple(), iter([]) ]:
            self.assertTrue(utils.iterable(i))

        self.assertFalse(utils.iterable(""))

@test.unit
class TestEnum(test.Case):

    def setUp(self):

        class SampleEnum(utils.enum):
            A=0; B=1; C=66

        super(TestEnum, self).setUp()
        self.enum = SampleEnum

    def testConstructor(self):

        def test():
            class FaultyEnum(utils.enum):
                A=1; B=1

        self.assertRaises(utils.EnumValueError, test)
        self.assertEqual(self.enum.__name__, 'SampleEnum')

    def testIterator(self):

        result = list(self.enum)
        members = [self.enum.A, self.enum.B, self.enum.C]
        self.assertEqual(set(result), set(members))

    def testInOperator(self):
        self.assertTrue(self.enum.C in self.enum)

    def testMutability(self):

        def test():
            self.enum.NEW = 1

        self.assertRaises(AttributeError, test)
        self.assertRaises(TypeError, self.enum)

    def testComparison(self):
        self.assertEqual(self.enum.A, 0)
        self.assertEqual(self.enum.C, 66)
        self.assertFalse(self.enum.C is 66)
        self.assertFalse(isinstance(self.enum.A, int))

    def testStr(self):
        self.assertEqual(str(self.enum.A), '0')
        self.assertEqual(int(self.enum.A), 0)
        self.assertEqual(self.enum.A.value, 0)

    def testRepr(self):
        self.assertEqual(repr(self.enum.A), 'A')
        self.assertEqual(self.enum.A.name, 'A')

    def testMembers(self):
        result = utils.Enum.members(self.enum)
        members = [self.enum.A, self.enum.B, self.enum.C]
        self.assertEqual(set(result), set(members))

    def testCreate(self):
        new = utils.Enum.create('NewEnum', A=11, B=22)
        self.assertEqual(new.__name__, 'NewEnum')
        self.assertEqual(new.B, 22)

    def testNames(self):
        result = utils.Enum.names(self.enum)
        names = map(repr, [self.enum.A, self.enum.B, self.enum.C])
        names2 = map(operator.attrgetter('name'), [self.enum.A, self.enum.B, self.enum.C])
        self.assertEqual(set(result), set(names))
        self.assertEqual(set(result), set(names2))

    def testValues(self):
        result = utils.Enum.values(self.enum)
        values = map(int, [self.enum.A, self.enum.B, self.enum.C])
        values2 = map(operator.attrgetter('value'), [self.enum.A, self.enum.B, self.enum.C])
        self.assertEqual(set(result), set(values))
        self.assertEqual(set(result), set(values2))

    def testParseValue(self):
        item = utils.Enum.parse(self.enum, 66)
        self.assertTrue(item is self.enum.C)
        self.assertRaises(utils.EnumValueError, utils.Enum.parse, self.enum, 111)
        self.assertRaises(utils.EnumValueError, utils.Enum.parse, self.enum, '0')

    def testParseName(self):
        item = utils.Enum.parsename(self.enum, 'A')
        self.assertTrue(item is self.enum.A)
        self.assertRaises(utils.EnumMemberError, utils.Enum.parsename, self.enum, 'XXX')

    def testIsMember(self):
        self.assertTrue(utils.Enum.ismember(self.enum.A, self.enum))

    def testSerialization(self):

        from csb.bio.sequence import SequenceTypes

        self.assertTrue(copy.copy(SequenceTypes.Protein) is SequenceTypes.Protein)
        self.assertTrue(copy.deepcopy(SequenceTypes.Protein) is SequenceTypes.Protein)
        self.assertTrue(utils.deepcopy(SequenceTypes.Protein) is SequenceTypes.Protein)
        self.assertTrue(Pickle.loads(Pickle.dumps(SequenceTypes.Protein)) is SequenceTypes.Protein)

        self.assertTrue(copy.deepcopy(SequenceTypes) is SequenceTypes)
        self.assertTrue(copy.deepcopy(SequenceTypes) is SequenceTypes)
        self.assertTrue(Pickle.loads(Pickle.dumps(SequenceTypes)) is SequenceTypes)

@test.unit
class TestDictionaryContainer(test.Case):

    def setUp(self):

        super(TestDictionaryContainer, self).setUp()

        self.dict = utils.OrderedDict([('A', 1), ('B', 2)])
        self.keys = ('A', 'B', 'C', 'D', 'Z')
        self.new = utils.DictionaryContainer
        self.test = utils.DictionaryContainer(items=self.dict, restrict=self.keys)

    def testConstructor(self):
        new = utils.DictionaryContainer(items=self.dict, restrict=self.keys)
        self.assertEqual(dict(new), dict(self.dict))
        self.assertEqual(list(new), list(self.dict))    # True if the dictionary is ordered
        self.assertEqual(new.length, len(self.dict))
        self.assertRaises(utils.InvalidKeyError, self.new, items={'X': 1}, restrict=self.keys)

    def testAppend(self):
        self.test.append('C', 1)
        self.assertTrue('C' in self.test)
        self.assertRaises(utils.DuplicateKeyError, self.test.append, key='C', item=1)
        self.assertRaises(utils.InvalidKeyError, self.test.append, key='X', item=1)

    def testRemove(self):
        self.assertTrue('A' in self.test)
        self.test._remove('A')
        self.assertFalse('A' in self.test)

    def testGetitem(self):
        self.assertEqual(self.test['B'], self.dict['B'])
        self.assertRaises(utils.ItemNotFoundError, lambda k: self.test[k], 66)

    def testLength(self):
        self.assertEqual(self.test.length, len(self.test))
        self.assertEqual(self.test.length, 2)

    def testBool(self):
        self.assertTrue(self.test)
        self.assertFalse(self.new())

    def testSet(self):
        new = utils.DictionaryContainer(items=self.dict, restrict=self.keys)
        new._set({'Z': 6})
        self.assertTrue('Z' in new)
        self.assertFalse('A' in new)

    def testUpdate(self):
        new = utils.DictionaryContainer(items=self.dict, restrict=self.keys)

        new._update({'A': 7})
        self.assertTrue('A' in new)
        self.assertEqual(new['A'], 7)

        self.assertRaises(utils.ItemNotFoundError, new._update, {'Z': 0})

@test.unit
class TestCollectionContainer(test.Case):

    def setUp(self):

        super(TestCollectionContainer, self).setUp()

        self.items = [11, 22, 33]
        self.start = 5
        self.new = utils.CollectionContainer
        self.test = utils.CollectionContainer(items=self.items, type=int, start_index=self.start)

    def testConstructor(self):
        new = utils.CollectionContainer(items=self.items, type=int, start_index=self.start)
        self.assertEqual(list(new), list(self.items))
        self.assertEqual(new.length, len(self.items))
        self.assertRaises(TypeError, self.new, items=['S', 1.2], type=int)

    def testGetitem(self):
        self.assertEqual(self.test[self.start], self.items[0])
        self.assertEqual(self.test[self.test.start_index], self.items[0])
        self.assertEqual(self.test[self.test.last_index], self.items[-1])
        self.assertEqual(self.test[-1], self.items[-1])
        self.assertEqual(self.test[-1 :-2], self.items[-1 :-2])

        self.assertEqual(self.test[: self.start + 2], self.items[:2])
        self.assertEqual(self.test[self.start + 2 :], self.items[2:])
        self.assertEqual(self.test[:], self.items[:])

        def get(i):
            return self.test[i]

        self.assertRaises(utils.CollectionIndexError, get, self.start + len(self.items))  # i = end + 1
        if self.start > 0:
            self.assertRaises(utils.CollectionIndexError, get, self.start - 1)            # i = start - 1, i >= 0

    def testLength(self):
        self.assertEqual(self.test.length, len(self.test))
        self.assertEqual(self.test.length, len(self.items))

    def testBool(self):
        self.assertTrue(self.test)
        self.assertFalse(self.new())

    def testIndices(self):
        new = self.new(items=self.items, type=int, start_index=self.start)
        self.assertEqual(new.start_index, self.start)
        self.assertEqual(new.last_index, self.start + len(self.items) - 1)
        self.assertEqual(new.length, len(self.items))

    def testAppend(self):
        rank = self.test.append(44)
        self.assertTrue(44 in self.test)
        self.assertEqual(rank, self.test.last_index)
        self.assertRaises(TypeError, self.test.append, item='S')

    def testUpdate(self):
        new = self.new(items=self.items, type=int, start_index=self.start)

        new._update([98, 99])
        self.assertTrue(98 in new)
        self.assertEqual(new.length, 2)

        self.assertRaises(TypeError, new._update, ['S'])

@test.unit
class TestAbstractContainer(test.Case):

    def setUp(self):

        super(TestAbstractContainer, self).setUp()

        dictitems = {'A': 1, 'B': 2}
        self.items = dictitems

        listitems = [11, 22]
        start = 5
        self.listitems = listitems
        self.start = start

        class DummyDict(utils.AbstractContainer):
            @property
            def _children(self):
                return utils.DictionaryContainer(dictitems)

        class DummyList(utils.AbstractContainer):
            @property
            def _children(self):
                return utils.CollectionContainer(listitems, start_index=start)

        self.dict = DummyDict()
        self.list = DummyList()

    def testGetitem(self):
        self.assertEqual(self.dict['A'], 1)
        self.assertRaises(utils.ItemNotFoundError, lambda k: self.dict[k], 'X')

        self.assertEqual(self.list[self.start], self.listitems[0])
        if self.start > 0:
            self.assertRaises(utils.CollectionIndexError, lambda i: self.list[i], 0)

    def testIterator(self):
        self.assertEqual(list(self.items), list(self.dict))
        self.assertEqual(list(self.listitems), list(self.list))

@test.unit
class TestAbstractNIContainer(test.Case):

    def setUp(self):

        super(TestAbstractNIContainer, self).setUp()

        items = list(set([11, 22, 33]))
        start = 1

        self.items = items
        self.start = start

        class Dummy(utils.AbstractNIContainer):
            @property
            def _children(self):
                return utils.CollectionContainer(items, start_index=start)

        self.test = Dummy()

    def testGetitem(self):
        assert self.start > 0

        self.assertEqual(self.test[0], self.items[0])
        self.assertEqual(self.test[1:2], self.items[1:2])
        self.assertEqual(self.test[0], self.test._children[self.start])
        self.assertNotEqual(self.test[1], self.test._children[1])

        self.assertRaises(IndexError, lambda i: self.test[i], 9999999)

    def testIterator(self):
        self.assertEqual(list(self.items), list(self.test))

@test.functional
class TestOrderedDict(test.Case):

    def runTest(self):

        items = [('G', 4), ('A', 2), ('C', 8), ('B', 7)]
        odict = utils.OrderedDict(items)

        self.assertEqual(list(odict.items()), items)

        for i, k in enumerate(odict):
            self.assertEqual(k, items[i][0])
            self.assertEqual(odict[k], items[i][1])

if __name__ == '__main__':

    test.Console()


text:
require 'spec_helper'
require 'rush'
require 'rack'

describe Rush::PageMaker do

  let (:test_fixtures_folder_path) { File.expand_path( "../test_fixtures/page_maker_test", __FILE__ ) }

  def get_page_maker_from_folder_path(folder_path)
    app_folder = File.join(test_fixtures_folder_path, folder_path)
    pages_folder = File.join( app_folder, "pages" )
    headers_folder = File.join( app_folder, "headers" )
    partials_folder = File.join( app_folder, "partials" )
    data_folder = File.join( app_folder, "data" )
    layouts_folder = File.join( app_folder, "layouts" )
    pm = Rush::PageMaker.new(
      OpenStruct.new(
        pages_folder: pages_folder,
        headers_folder: headers_folder,
        partials_folder: partials_folder,
        data_folder: data_folder,
        layouts_folder: layouts_folder
      )
    )
    expected_result = Rush::FileFetcher.get_file_contents( File.join(app_folder, "expected_text.txt") )
    result_got = pm.get_page("welcome")
    return { expected: expected_result, got: result_got[:html], page_maker: pm }
  end

  describe "#call" do

    context "the page can be returned properly" do

      it "proper rack respose is returned" do
        pm = get_page_maker_from_folder_path("data_puller_good")[:page_maker]
        mock_request = Rack::MockRequest.new pm
        mock_request.get("/welcome").body.should == "Khoj"
        mock_request.get("/welcome").ok?.should be true
      end

      context "the path is '/', as in root path" do

        it  "defaults to path index" do
          pm = get_page_maker_from_folder_path("data_puller_good")[:page_maker]
          mock_request = Rack::MockRequest.new pm
          mock_request.get("/").body.should == "Yay!"
          mock_request.get("/").ok?.should be true
        end

      end

    end

    context "the page cannot be returned, there is an error" do

      it "proper failed rack response is returned" do
        pm = get_page_maker_from_folder_path("data_puller_error")[:page_maker]
        mock_request = Rack::MockRequest.new pm
        expect(mock_request.get("/welcome").body).to include("Rush Error", Rush::ERROR_TITLE_MALFORMED_JSON, Rush::ERROR_DESC_MALFORMED_JSON)
        mock_request.get("/welcome").server_error?.should be true
      end

    end

  end

  describe "#get_page" do

    context "the data puller error has errors i.e. JSON was malformed" do

      it "shows the data puller errors in a frindly way" do
        ## Error Case
        ## Folder Made
        folder_name = "data_puller_error"
        result_hash = get_page_maker_from_folder_path(folder_name)
        expect(result_hash[:got]).to include("Rush Error", Rush::ERROR_TITLE_MALFORMED_JSON, Rush::ERROR_DESC_MALFORMED_JSON)
      end

    end

    context "the data puller initialization does not raise an error" do

      it "allows views and partials to acess the data from data puller properly" do
        # Folder Made
        folder_name = "data_puller_good"
        result_hash = get_page_maker_from_folder_path(folder_name)
        result_hash[:got].should == result_hash[:expected]
      end

    end

    context "there is a html file with the same name as the page in the headers folder" do

      context "there is a call to 'render_header' at some point in the page" do

        it "renders the header in the correct place" do
          # Folder Made
          folder_name = "render_header"
          result_hash = get_page_maker_from_folder_path(folder_name)
          result_hash[:got].should == result_hash[:expected]
        end

      end

    end

    context "there is no html file with the same name as the page in the headers folder" do

      context "there is a call to 'render_header' at some point in the page" do

        it "it returns a blank string as the header in response to 'render_header'" do
          # Folder Made
          folder_name = "render_header_no_header"
          result_hash = get_page_maker_from_folder_path(folder_name)
          result_hash[:got].should == result_hash[:expected]
        end

      end

    end

    context "the view was not found in the view folder" do

      it "returns a friendly error indicating that no page was found" do
        ## Error Case
        # Folder Made
        folder_name = "no_page"
        result_hash = get_page_maker_from_folder_path(folder_name)
        expect(result_hash[:got]).to include("Rush Error", Rush::ERROR_TITLE_PAGE_NOT_FOUND, Rush::ERROR_DESC_PAGE_NOT_FOUND)
      end

    end

    context "the view was found in the view folder" do

      context "the layout includes partials via a call to render_partial 'partial_file_name'" do

        context "the partial was found in the partials folder" do

          it "renders the partial at the appropriate spot" do
            # Folder Made
            folder_name = "view_calls_for_partial"
            result_hash = get_page_maker_from_folder_path(folder_name)
            result_hash[:got].should == result_hash[:expected]
          end

        context "the partial also passes some locals as a param" do

          it "renders the partial variables in the view" do
            # Folder Made
            folder_name = "view_calls_for_partial_with_locals"
            result_hash = get_page_maker_from_folder_path(folder_name)
            result_hash[:got].should == result_hash[:expected]
          end

        end

        end

        context "the partial was not found in the partial folder" do

          it "raises a friendly error message letting the user know how to solve the issue" do
            ## Error Case
            # Folder Made
            folder_name = "view_calls_for_partial_missing"
            result_hash = get_page_maker_from_folder_path(folder_name)
            expect(result_hash[:got]).to include("Rush Error", Rush::ERROR_TITLE_PARTIAL_NOT_FOUND, Rush::ERROR_DESC_PARTIAL_NOT_FOUND)
          end

        end

      end

      context "the first line of the view is a comment which has set_layout:'<layout_file_name>'" do

        context "the layout file name as specified in the comment was found in the layouts folder" do

          it "uses the layout other than the default layout of 'application.html' as specified in the comment" do
            # Folder Made
            folder_name = "specific_layout"
            result_hash = get_page_maker_from_folder_path(folder_name)
            result_hash[:got].should == result_hash[:expected]
          end

        end

        context "the layout file name as specified in the comment was not found in the layouts folder" do

          it "raises a friendly error letting the user know that there is no file like '<layout_file_name>.html in the layouts folder'" do
            ## Error Case
            # Folder Made
            folder_name = "specific_layout_not_found"
            result_hash = get_page_maker_from_folder_path(folder_name)
            expect(result_hash[:got]).to include("Rush Error", Rush::ERROR_TITLE_LAYOUT_NOT_FOUND, Rush::ERROR_DESC_LAYOUT_NOT_FOUND)
          end

        end

      end

      context "there is no comment in the first line with the text set_layout:'<layout_file_name>'" do

        context "there is no file called 'application.html' in the layouts folder" do

          it 'raises a friendly error to the user letting him know that there needs to be a file called application.html in the layouts folder' do
            ## Error Case
            # Folder Made
            folder_name = "standard_layout_not_found"
            result_hash = get_page_maker_from_folder_path(folder_name)
            expect(result_hash[:got]).to include("Rush Error", Rush::ERROR_TITLE_STANDARD_LAYOUT_NOT_FOUND, Rush::ERROR_DESC_STANDARD_LAYOUT_NOT_FOUND)
          end

        end

        context "there is a file called 'application.html' in the layouts folder" do

          context "the layout does not make any call to the 'render_page' method via ERB" do

            it "raises a friendly error reminding the developer that he/she should make a call to 'render_page' or the view will not show up" do
              ## Error Case
              # Folder Made
              folder_name = "standard_layout_no_render_view"
              result_hash = get_page_maker_from_folder_path(folder_name)
              expect(result_hash[:got]).to include("Rush Error", Rush::ERROR_TITLE_NO_CALL_TO_RENDER_PAGE, Rush::ERROR_DESC_NO_CALL_TO_RENDER_PAGE)
            end

          end

          context "the layout makes a call to the 'render_page' method via ERB" do

            it "renders the layout with the application.html as the layout" do
              # Folder Made
              folder_name = "standard_layout_found"
              result_hash = get_page_maker_from_folder_path(folder_name)
              result_hash[:got].should == result_hash[:expected]
            end

          end

        end

      end

    end

  end

end

redpajama_set_name: RedPajamaGithub


text:
"use strict";
var _ = require("lodash");
var moment = require("moment-timezone");

// helper class to talk to schedule_matcher.py and use it to match up scheduled
// events and dosed events
var ScheduleMatcher = module.exports = function (params) {
    // parameters to send straight to ScheduleMatcher (see documentation in schedule_matcher.py)
    // DEPRECATED
    this.params = params;
    if (typeof this.params === "undefined" || this.params === null) this.params = {};
};

ScheduleMatcher.prototype.match = function (medication, doses, habits, callback) {
    // Setup =================================================================

    // set defaults for habits
    if (!_.has(habits, "wake") || habits.wake === null) {
        habits.wake = "00:00 am"; // changed to match default in models/patient/schedule.js:97
    }
    if (!_.has(habits, "tz") || habits.tz === null) {
        habits.tz = "America/New_York";
    }
    this.habits = habits;
    var tz = habits.tz;

    // parse ISO 8601-formatted dates into Date objects, and sort them
    function parseDose(dose) {
        var newDose = JSON.parse(JSON.stringify(dose)); // copy the object
        var formatted = moment(dose.date.utc).format();
        var newTz = moment.tz(formatted, tz).format();
        newDose.date.utc = newTz;
        return newDose;
    }
    function sortByDate(dose) {
        return moment.tz(dose.date.utc, tz).unix();
    }
    this.doses = _.map(doses, parseDose);
    this.doses = _.sortBy(this.doses, sortByDate);

    // store time separately for quick access in cost function
    this.doseTimes = _.map(this.doses, sortByDate);

    // calculate start of first day
    var ampm = this.habits.wake.split(" ")[1];
    var wake = _.map(this.habits.wake.split(" ")[0].split(":"), Number);

    if (wake[0] === 12) wake[0] = 0;
    if (ampm === "pm") {
        wake[0] = wake[0] + 12;
    }

    var firstWake;
    if (this.doseTimes.length > 0) {
        firstWake = (moment.tz(this.doseTimes[0] * 1000, tz)
            .hour(wake[0]).minute(wake[1]).second(0).millisecond(0)).format();
        if (moment.tz(firstWake, tz).isAfter(moment(this.doseTimes[0] * 1000))) {
            firstWake = (moment.tz(firstWake, tz).subtract(1, "days")).format();
        }
    } else {
        // sensible default (TODO: I don"t think this is sensible *JSS; what about timezone?)
        firstWake = moment().tz(tz).format();
    }

    // helper function for indexing days
    function dayIndex(dose) {
        // calculate start of that day
        var startDay = moment.tz(dose.date.utc, tz).hour(wake[0]).minute(wake[1]).second(0).millisecond(0);
        if (startDay.isAfter(moment.tz(dose.date.utc, tz))) {
            startDay = startDay.subtract(1, "days");
        }
        return startDay.diff(firstWake, "days");
    }

    // Matching ==============================================================

    // match objects to be returned
    var matches = [];

    // transpose of matrix corresponding to the above,
    // used to determine what to do with unmatched dose events
    var reverse_matches = {};

    _.forEach(this.doses, function (dose) {
        var match = {
            "match": {}
        };

        // extract day of dose
        var day = dayIndex(dose);
        match.match.day = day;
        if (!_.has(reverse_matches, day)) {
            reverse_matches[day] = {};
        }

        // store ID of dose
        match.dose = dose._id;
        match.doseF = dose;

        // use scheduled attribute if present (contains ID of index we should match to)
        if (_.has(dose, "scheduled") && dose.scheduled !== null) {
            // just in case the event matched is unspecified, record it so we don"t duplicate it
            reverse_matches[day][dose.scheduled] = true;
            match.match.index = dose.scheduled;
        }

        // otherwise loop through and match up
        matches.push(match);

    });

    _.forEach(matches, function (match, i) {
        var day = match.match.day;

        // skip the match if we"ve already matched it
        if (_.has(match.match, "index")) {
            delete match.doseF;
            matches[i] = match;
            return;
        }

        // otherwise check if there"s still a free "unspecified" schedule event that day to match to
        var unspecified = [];
        var schedule = medication.scheduleFor(match.doseF).prepareForMatching(habits);
        _.forEach(schedule.times, function (event) {
            if (event.type === "unspecified") {
                unspecified.push(event._id);
            }
        });
        unspecified.every(function (event) {
            var event_used = (_.has(reverse_matches[day], event)) && (reverse_matches[day][event] === true);
            if (!event_used) {
                reverse_matches[day][event] = true;
                match.match.index = event;
                return false;
            }
        });

        // if we still haven"t found anything, use null to denote no match was found
        // i.e. it was probably a PRN medication
        if (!_.has(match.match, "index")) {
            match.match = null;
        }

        delete match.doseF;
        matches[i] = match;
    });

    var ret = {
        "matches": matches,
        "start": moment.tz(firstWake, tz).format()
    };
    callback(null, ret);
};


text:
package org.slf4j.migrator;

import java.io.File;
import java.io.IOException;

import junit.framework.TestCase;

import org.slf4j.migrator.InplaceFileConverter;
import org.slf4j.migrator.internal.NopProgressListener;
import org.slf4j.migrator.line.EmptyRuleSet;

public class FileConverterTest extends TestCase {

    public FileConverterTest(String arg0) {
        super(arg0);
    }

    protected void setUp() throws Exception {
        super.setUp();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

    public void test() {
    }

    public void XtestNOP() throws IOException {
        InplaceFileConverter fc = new InplaceFileConverter(new EmptyRuleSet(), new NopProgressListener());
        fc.convert(new File("c:/varargs.txt"));
    }
}


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.touch_to_fill;

import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.CredentialProperties.CREDENTIAL;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.CredentialProperties.FAVICON_OR_FALLBACK;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.CredentialProperties.FORMATTED_ORIGIN;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.CredentialProperties.ON_CLICK_LISTENER;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.CredentialProperties.SHOW_SUBMIT_BUTTON;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.HeaderProperties.FORMATTED_URL;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.HeaderProperties.IMAGE_DRAWABLE_ID;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.HeaderProperties.ORIGIN_SECURE;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.HeaderProperties.PASSWORD_CRED_PRESENT;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.HeaderProperties.SHOW_SUBMIT_SUBTITLE;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.HeaderProperties.SINGLE_CREDENTIAL;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.HeaderProperties.WEBAUTHN_CRED_PRESENT;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.ON_CLICK_MANAGE;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.SHEET_ITEMS;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.VISIBLE;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.WebAuthnCredentialProperties.ON_WEBAUTHN_CLICK_LISTENER;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.WebAuthnCredentialProperties.SHOW_WEBAUTHN_SUBMIT_BUTTON;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.WebAuthnCredentialProperties.WEBAUTHN_CREDENTIAL;
import static org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.WebAuthnCredentialProperties.WEBAUTHN_FAVICON_OR_FALLBACK;

import androidx.annotation.Px;

import org.chromium.base.metrics.RecordHistogram;
import org.chromium.chrome.browser.touch_to_fill.TouchToFillComponent.UserAction;
import org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.CredentialProperties;
import org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.FaviconOrFallback;
import org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.HeaderProperties;
import org.chromium.chrome.browser.touch_to_fill.TouchToFillProperties.WebAuthnCredentialProperties;
import org.chromium.chrome.browser.touch_to_fill.data.Credential;
import org.chromium.chrome.browser.touch_to_fill.data.WebAuthnCredential;
import org.chromium.components.browser_ui.bottomsheet.BottomSheetController;
import org.chromium.components.browser_ui.bottomsheet.BottomSheetController.StateChangeReason;
import org.chromium.components.embedder_support.util.Origin;
import org.chromium.components.favicon.LargeIconBridge;
import org.chromium.components.favicon.LargeIconBridge.LargeIconCallback;
import org.chromium.components.url_formatter.SchemeDisplay;
import org.chromium.components.url_formatter.UrlFormatter;
import org.chromium.ui.modelutil.ListModel;
import org.chromium.ui.modelutil.MVCListAdapter.ListItem;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.url.GURL;

import java.util.List;

/**
 * Contains the logic for the TouchToFill component. It sets the state of the model and reacts to
 * events like clicks.
 */
class TouchToFillMediator {
    static final String UMA_TOUCH_TO_FILL_DISMISSAL_REASON =
            "PasswordManager.TouchToFill.DismissalReason";
    static final String UMA_TOUCH_TO_FILL_CREDENTIAL_INDEX =
            "PasswordManager.TouchToFill.CredentialIndex";
    static final String UMA_TOUCH_TO_FILL_USER_ACTION = "PasswordManager.TouchToFill.UserAction";

    private TouchToFillComponent.Delegate mDelegate;
    private PropertyModel mModel;
    private LargeIconBridge mLargeIconBridge;
    private @Px int mDesiredIconSize;
    private List<Credential> mCredentials;
    private List<WebAuthnCredential> mWebAuthnCredentials;

    void initialize(TouchToFillComponent.Delegate delegate, PropertyModel model,
            LargeIconBridge largeIconBridge, @Px int desiredIconSize) {
        assert delegate != null;
        mDelegate = delegate;
        mModel = model;
        mLargeIconBridge = largeIconBridge;
        mDesiredIconSize = desiredIconSize;
    }

    void showCredentials(GURL url, boolean isOriginSecure, List<Credential> credentials,
            List<WebAuthnCredential> webAuthnCredentials, boolean triggerSubmission) {
        assert credentials != null;
        mModel.set(ON_CLICK_MANAGE, this::onManagePasswordSelected);

        TouchToFillResourceProvider resourceProvider = new TouchToFillResourceProviderImpl();

        ListModel<ListItem> sheetItems = mModel.get(SHEET_ITEMS);
        sheetItems.clear();

        sheetItems.add(new ListItem(TouchToFillProperties.ItemType.HEADER,
                new PropertyModel.Builder(HeaderProperties.ALL_KEYS)
                        .with(SINGLE_CREDENTIAL,
                                credentials.size() + webAuthnCredentials.size() == 1)
                        .with(WEBAUTHN_CRED_PRESENT, webAuthnCredentials.size() > 0)
                        .with(PASSWORD_CRED_PRESENT, credentials.size() > 0)
                        .with(FORMATTED_URL,
                                UrlFormatter.formatUrlForSecurityDisplay(
                                        url, SchemeDisplay.OMIT_HTTP_AND_HTTPS))
                        .with(ORIGIN_SECURE, isOriginSecure)
                        .with(SHOW_SUBMIT_SUBTITLE, triggerSubmission)
                        .with(IMAGE_DRAWABLE_ID, resourceProvider.getHeaderImageDrawableId())
                        .build()));

        mCredentials = credentials;
        for (Credential credential : credentials) {
            final PropertyModel model = createModel(credential, triggerSubmission);
            sheetItems.add(new ListItem(TouchToFillProperties.ItemType.CREDENTIAL, model));
            if (shouldCreateConfirmationButton(credentials, webAuthnCredentials)) {
                sheetItems.add(new ListItem(TouchToFillProperties.ItemType.FILL_BUTTON, model));
            }
            requestIconOrFallbackImage(model, url);
        }

        mWebAuthnCredentials = webAuthnCredentials;
        for (WebAuthnCredential credential : webAuthnCredentials) {
            final PropertyModel model = createWebAuthnModel(credential);
            sheetItems.add(new ListItem(TouchToFillProperties.ItemType.WEBAUTHN_CREDENTIAL, model));
            if (shouldCreateConfirmationButton(credentials, webAuthnCredentials)) {
                sheetItems.add(new ListItem(TouchToFillProperties.ItemType.FILL_BUTTON, model));
            }
            requestWebAuthnIconOrFallbackImage(model, url);
        }

        mModel.set(VISIBLE, true);
    }

    private void requestIconOrFallbackImage(PropertyModel credentialModel, GURL url) {
        Credential credential = credentialModel.get(CREDENTIAL);
        final String iconOrigin = getIconOrigin(credential.getOriginUrl(), url);

        final LargeIconCallback setIcon = (icon, fallbackColor, hasDefaultColor, type) -> {
            credentialModel.set(FAVICON_OR_FALLBACK,
                    new FaviconOrFallback(iconOrigin, icon, fallbackColor, hasDefaultColor, type,
                            mDesiredIconSize));
        };
        final LargeIconCallback setIconOrRetry = (icon, fallbackColor, hasDefaultColor, type) -> {
            if (icon == null && iconOrigin.equals(credential.getOriginUrl())) {
                mLargeIconBridge.getLargeIconForUrl(url, mDesiredIconSize, setIcon);
                return; // Unlikely but retry for exact path if there is no icon for the origin.
            }
            setIcon.onLargeIconAvailable(icon, fallbackColor, hasDefaultColor, type);
        };
        mLargeIconBridge.getLargeIconForStringUrl(iconOrigin, mDesiredIconSize, setIconOrRetry);
    }

    private void requestWebAuthnIconOrFallbackImage(PropertyModel credentialModel, GURL url) {
        WebAuthnCredential credential = credentialModel.get(WEBAUTHN_CREDENTIAL);

        // WebAuthn credentials have already been filtered to match the current site's URL.
        final String iconOrigin = url.getSpec();

        final LargeIconCallback setIcon = (icon, fallbackColor, hasDefaultColor, type) -> {
            credentialModel.set(WEBAUTHN_FAVICON_OR_FALLBACK,
                    new FaviconOrFallback(iconOrigin, icon, fallbackColor, hasDefaultColor, type,
                            mDesiredIconSize));
        };
        final LargeIconCallback setIconOrRetry = (icon, fallbackColor, hasDefaultColor, type) -> {
            if (icon == null) {
                mLargeIconBridge.getLargeIconForUrl(url, mDesiredIconSize, setIcon);
                return; // Unlikely but retry for exact path if there is no icon for the origin.
            }
            setIcon.onLargeIconAvailable(icon, fallbackColor, hasDefaultColor, type);
        };
        mLargeIconBridge.getLargeIconForStringUrl(iconOrigin, mDesiredIconSize, setIconOrRetry);
    }

    private String getIconOrigin(String credentialOrigin, GURL siteUrl) {
        final Origin o = Origin.create(credentialOrigin);
        // TODO(crbug.com/1030230): assert o != null as soon as credential Origin must be valid.
        return o != null && !o.uri().isOpaque() ? credentialOrigin : siteUrl.getSpec();
    }

    private void reportCredentialSelection(int userAction, int index) {
        if (mCredentials.size() + mWebAuthnCredentials.size() > 1) {
            // We only record this histogram in case multiple credentials were shown to the user.
            // Otherwise the single credential case where position should always be 0 will dominate
            // the recording.
            RecordHistogram.recordCount100Histogram(UMA_TOUCH_TO_FILL_CREDENTIAL_INDEX, index);
        }

        RecordHistogram.recordEnumeratedHistogram(
                UMA_TOUCH_TO_FILL_USER_ACTION, userAction, UserAction.MAX_VALUE + 1);
    }

    private void onSelectedCredential(Credential credential) {
        mModel.set(VISIBLE, false);
        reportCredentialSelection(UserAction.SELECT_CREDENTIAL, mCredentials.indexOf(credential));
        mDelegate.onCredentialSelected(credential);
    }

    private void onSelectedWebAuthnCredential(WebAuthnCredential credential) {
        mModel.set(VISIBLE, false);
        // The index assumes WebAuthn credentials are listed after password credentials.
        reportCredentialSelection(UserAction.SELECT_WEBAUTHN_CREDENTIAL,
                mCredentials.size() + mWebAuthnCredentials.indexOf(credential));
        mDelegate.onWebAuthnCredentialSelected(credential);
    }

    public void onDismissed(@StateChangeReason int reason) {
        if (!mModel.get(VISIBLE)) return; // Dismiss only if not dismissed yet.
        mModel.set(VISIBLE, false);
        RecordHistogram.recordEnumeratedHistogram(UMA_TOUCH_TO_FILL_DISMISSAL_REASON, reason,
                BottomSheetController.StateChangeReason.MAX_VALUE + 1);
        RecordHistogram.recordEnumeratedHistogram(
                UMA_TOUCH_TO_FILL_USER_ACTION, UserAction.DISMISS, UserAction.MAX_VALUE + 1);
        mDelegate.onDismissed();
    }

    private void onManagePasswordSelected() {
        mModel.set(VISIBLE, false);
        RecordHistogram.recordEnumeratedHistogram(UMA_TOUCH_TO_FILL_USER_ACTION,
                UserAction.SELECT_MANAGE_PASSWORDS, UserAction.MAX_VALUE + 1);
        mDelegate.onManagePasswordsSelected();
    }

    /**
     * @param credentials The available credentials. Show the confirmation for a lone credential.
     * @return True if a confirmation button should be shown at the end of the bottom sheet.
     */
    private boolean shouldCreateConfirmationButton(
            List<Credential> credentials, List<WebAuthnCredential> webauthnCredentials) {
        return credentials.size() + webauthnCredentials.size() == 1;
    }

    private PropertyModel createModel(Credential credential, boolean triggerSubmission) {
        return new PropertyModel.Builder(CredentialProperties.ALL_KEYS)
                .with(CREDENTIAL, credential)
                .with(ON_CLICK_LISTENER, this::onSelectedCredential)
                .with(FORMATTED_ORIGIN,
                        UrlFormatter.formatUrlForDisplayOmitScheme(credential.getOriginUrl()))
                .with(SHOW_SUBMIT_BUTTON, triggerSubmission)
                .build();
    }

    private PropertyModel createWebAuthnModel(WebAuthnCredential credential) {
        TouchToFillResourceProvider resourceProvider = new TouchToFillResourceProviderImpl();
        return new PropertyModel.Builder(WebAuthnCredentialProperties.ALL_KEYS)
                .with(WEBAUTHN_CREDENTIAL, credential)
                .with(ON_WEBAUTHN_CLICK_LISTENER, this::onSelectedWebAuthnCredential)
                .with(SHOW_WEBAUTHN_SUBMIT_BUTTON, false)
                .build();
    }
}


text:
package com.yougou.h5center.push.impl;

import org.springframework.beans.factory.InitializingBean;

import com.yougou.h5center.push.config.base.BasePushConfig;

/**
 * @author long.yl.
 * @Date 2016/5/31
 */
public interface PushStrategy extends InitializingBean {

	/**
	 * 推送具体实现
	 *
	 * @param pushConfig
	 *            推送配置
	 * */
	boolean push(BasePushConfig pushConfig) throws Exception;
}


text:
Upload de do arquivo

{{status}}

Enviar outra:

          Arraste e solte o arquivo neste retangulo

           Localizar no diretorio local

    <button class="btn btn-primary" ng-disabled="sending" ng-click="save()" >OK</button>
    <button class="btn btn-warning" ng-disabled="sending" ng-click="$dismiss();">Cancel</button>


text:
Orders

        <input placeholder="Search" class="form-control" ng-model="searchText" class="pull-right">

        <input type="checkbox" ng-model="notDeliveredFilter"> Show only not delivered orders

            Client name
            Address
            Delivery Date
            Operations

                    {{order.deliveryDate | date:'dd/MM/yyyy'}}
                    {{order.deliveryDate | date:'HH:mm'}}

                    <button class="btn btn-success" ng-show="!order.cancelled" ng-click="changeStatus(order._id, 1, $event)">{{order.delivered ? 'Mark as Pending': 'Mark as Delivered'}}</button>
                    <button class="btn btn-alert" ng-disabled="{{order.delivered}}" ng-click="changeStatus(order._id, 2, $event)">{{order.cancelled ? 'Undo': 'Cancel'}}</button>
                    <button class="btn btn-danger" ng-show="order.cancelled" ng-click="remove(order)">Delete</button>

        There is no order created. Why don't you create a new one?


text:
window. //+ document, close, closed, ...
window.document. //+ appendChild, close, createAttribute, ...
document.createElement("test"). //+ addEventListener, appendChild, ...
var newElt = document.createElement("div");
newElt.style.bo; //+ border, borderColor, ... @16

var e_which;
window.addEventListener("mousemove", function(e) { e.which. }); //+ toExponential, toString, toFixed @60


text:
package com.github.jeanadrien.evrythng.scala.rest

import com.github.jeanadrien.evrythng.scala.json.Collection
import org.specs2.concurrent.ExecutionEnv
import org.specs2.specification.BeforeAll

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.util.Random

/**
  *
  */
class CollectionsInCollectionSpec(implicit val ee : ExecutionEnv) extends TestOperatorContext with BeforeAll {

    // test data

    var collectionA : Collection = null
    var collectionB : Collection = null
    var collectionC : Collection = null
    var parentCollection : Collection = null

    def randomCollection : Collection = Collection(
        name = Some(Random.nextString(20))
    )

    override def beforeAll() : Unit = {
        super.beforeAll()

        Await.ready(for {
            collectionA <- operator.collections.create(randomCollection).exec
            collectionB <- operator.collections.create(randomCollection).exec
            collectionC <- operator.collections.create(randomCollection).exec
            parentCollection <- operator.collections.create(randomCollection).exec
        } yield {
            this.collectionA = collectionA
            this.collectionB = collectionB
            this.collectionC = collectionC
            this.parentCollection = parentCollection

            logger.debug(s"CollectionA ${collectionA}")
            logger.debug(s"CollectionB ${collectionB}")
            logger.debug(s"CollectionC ${collectionC}")
            logger.debug(s"parentCollection ${parentCollection}")
        }, 10 seconds)
    }

    override def is = sequential ^
        s2""""
            Collections in collection manipulation API allows to
                add a collection to a collection                      ${addSomeCollections(collectionA :: Nil)}
                and see it's there                                    $checkCollectionContent
                add multiple collections to a collection              ${addSomeCollections(collectionA :: collectionB :: collectionC :: Nil)}
                and see they're all there but unique                  $checkCollectionContent
                remove a collection from a collection                 ${removeFromCollection(collectionB)}
                and see it has been removed                           $checkCollectionContent
                remove all collections from a collection              $removeAllFromCollection
                and see it is now empty                               $checkCollectionContent
          """

    private var contentSet = Set[Collection]()

    def addSomeCollections(collections : List[Collection]) =
        operator.collection(parentCollection.id.get).collections.add(collections.map(_.id.get)).exec.map { coll =>
            contentSet = contentSet ++ collections
            coll
        } must beEqualTo(()).await

    def checkCollectionContent = operator.collection(parentCollection.id.get).collections.read.exec.map { page =>
        page.items.map(_.copy(collections = None, updatedAt = None))
    } must containTheSameElementsAs(contentSet.toList.map(_.copy(collections = None, updatedAt = None))).await

    def removeFromCollection(collection : Collection) = operator.collection(parentCollection.id.get).collections
        .remove(collection.id.get).exec.map { _ =>
        contentSet = contentSet - collection
        ()
    } must beEqualTo(()).await

    def removeAllFromCollection = operator.collection(parentCollection.id.get).collections.removeAll.exec.map { _ =>
        contentSet = contentSet.empty
        ()
    } must beEqualTo(()).await
}


text:
Kaiseki
=============

A Parse.com [REST API](https://parse.com/docs/rest) client for Node.js

Installing
-------------

 * Install through npm:

        npm install kaiseki

 * Or in your `package.json`:

        "dependencies": {
          "kaiseki": "*",
          ...
        }
 Then:

        npm install

 * Or you can just download the files and put it in your project.

Usage
-------------

You might want to read about the [REST API](https://parse.com/docs/rest) first before diving in.

### Setup

    // the class
    var Kaiseki = require('kaiseki');

    // instantiate
    var APP_ID = '<your-Parse-application-id>';
    var REST_API_KEY = '<your-Parse-REST-API-key>';
    var kaiseki = new Kaiseki(APP_ID, REST_API_KEY);

    // use it
    kaiseki.getObjects(...);

### Callbacks

All callbacks should follow this format: `function(error, response, body, success) { ... }`. This is because Kaiseki is based on [Request](https://github.com/mikeal/request) and I thought it would be best to pass the same callback parameters. The `error` and `response` parameters are passed as is. On most methods, `body` is changed and parsed from JSON for your convenience.

 * __error__: If there's an error during the request (e.g. no internet connection), this will not be empty. Note that if the API returns a `statusCode` that is not `2xx`, it is not marked as an error.

 * __response__: You can check lots of info about the request in here. For example, the REST API will return a `response.statusCode` value of `4xx` on failures. In these cases, the API will still return a JSON object containing the fields `code` and `error`. You can get this in the `body` parameter.

        { "code": 105,
          "error": "invalid field name: bl!ng" }

 Read more about the Response format [here](https://parse.com/docs/rest#general-responses).

 * __body__: On successful requests, this will be an object or array depending on the method called.

 * __success__: A convenience parameter, this is a boolean indicating if the request was a success.

### Users

#### createUser (data, callback)

This will pass to `body` whatever you passed in `data` plus the returned `createdAt` and `sessionToken` fields.

    var userInfo = {
      // required
      username: 'maricris',
      password: 'whew',

      name: 'Maricris',
      gender: 'female',
      nickname: 'Kit'
    };

    kaiseki.createUser(userInfo, function(err, res, body, success) {
      console.log('user created with session token = ', body.sessionToken);
      console.log('object id = ', body.objectId);
    });

#### getUser (objectId, params, callback)

Gets a user info based on the `objectId` (user id). The `params` is currently unused but is there for a
future use. You can pass in the callback function as the second parameter.

    kaiseki.getUser('<object-id>', function(err, res, body, success) {
      console.log('user info = ', body);
    });

#### loginUser (username, password, callback)

Log in a user. This will give you a user's `sessionToken` that you can use in `updateUser` and `deleteUser`, and other API calls that may need a `sessionToken`.

    kaiseki.loginUser('username', 'my secret password', function(err, res, body, success) {
      console.log('user logged in with session token = ', body.sessionToken);
    });

#### updateUser (objectId, data, callback)

Updates a user object (if that wasn't obvious). This requires a sessionToken received from `loginUser` or `createUser`. If successful, body will contain the `updatedAt` value.

    kaiseki.sessionToken = 'le session token';
    kaiseki.updateUser({name: 'new name'}, function(err, res, body, success) {
      console.log('updated at = ', body.updatedAt);
    });

#### deleteUser (objectId, data, callback)

Deletes a user. Like `updateUser()`, this needs a `sessionToken`.

    kaiseki.sessionToken = '<user-seassion-token>';
    kaiseki.deleteUser('<object-id>', function(err, res, body, success) {
      if (success)
        console.log('deleted!');
      else
        console.log('failed!');
    });

#### getUsers (params, callback)

Returns an array of users. The `params` parameter can be an object containing the query options as described [here](https://parse.com/docs/rest#queries-basic). Note that unlike the Parse API Doc, you do not have to pass in strings for the parameter values. This is all taken care of for you.

If you do not want to pass in some query parameters, you can set the callback as the first parameter.

The `body` in the callback is an array of the returned objects.

    // get all users (no parameters)
    kaiseki.getUsers(function(err, res, body, success) {
      console.log('all users = ', body);
    });

    // query with parameters
    var params = {
      where: { gender: "female" },
      order: '-name'
    };
    kaiseki.getUsers(params, function(err, res, body, success) {
      console.log('female users = ', body);
    });

#### requestPasswordReset (email, callback)

Just provide an email and this function will send the user an email to reset their password

    kaiseki.requestPasswordReset('email@mail.com', function(err, res, body, success) {
      if (success) {
        console.log('Successfully Sent Password Reset');
      } else {
        console.log('Error: ', err, body);
      }
    });

### Objects

Object methods are similar to the User methods except that Object methods require you to specify the Parse class name. Class names are generally passed as the first parameter.

#### createObject (className, data, callback)

Creates an object and passes to `body` whatever you passed in `data` plus the returned `createdAt` field.

    var dog = {
      name: 'Prince',
      breed: 'Pomeranian'
    };
    var className = 'Dogs';

    kaiseki.createObject(className, dog, function(err, res, body, success) {
      console.log('object created = ', body);
      console.log('object id = ', body.objectId);
    });

#### getObject (className, objectId, params, callback)

Gets an object based on the `objectId`.

The `params` parameter can be an object containing the query options as described [here](https://parse.com/docs/rest#queries-basic). Note that unlike the Parse API Doc, you do not have to pass in strings for the parameter values. This is all taken care of for you.

If you do not want to pass in some query parameters, you can set the callback as the second parameter.

    // query with parameters
    var params = {
      where: { breed: "Chow Chow" },
      order: '-name'
    };
    kaiseki.getObject('<class-name>', '<object-id>', params, function(err, res, body, success) {
      console.log('found object = ', body);
    });

#### updateObject (className, objectId, data, callback)

Updates an object. If successful, body will contain the `updatedAt` value.

    kaiseki.updateObject('<class-name>', '<object-id>',
      {name: 'new object name'},
      function(err, res, body, success) {

      console.log('object updated at = ', body.updatedAt);
    });

#### deleteObject (className, objectId, callback)

Deletes an object.

    kaiseki.deleteObject('<class-name>', '<object-id>', function(err, res, body, success) {
      if (success)
        console.log('deleted!');
      else
        console.log('failed!');
    });

#### getObjects (className, params, callback)

Returns an array of objects in the class name. The `params` parameter can be an object containing the query options as described [here](https://parse.com/docs/rest#queries-basic). Note that unlike the Parse API Doc, you do not have to pass in strings for the parameter values. This is all taken care of for you.

If you do not want to pass in some query parameters, you can set the callback as the first parameter.

The `body` in the callback is an array of the returned objects.

    // get all objects (no parameters)
    kaiseki.getObjects('Dogs', function(err, res, body, success) {
      console.log('all dogs = ', body);
    });

    // query with parameters
    var params = {
      where: { breed: "Chow Chow" },
      order: '-name'
    };
    kaiseki.getObjects('Dogs', params, function(err, res, body, success) {
      console.log('Chow chow dogs = ', body);
    });

##### Using `count` with `getObjects`.

You are allowed to pass in the `count` parameter when using `getObjects`. If you do, the value of `body` will be an object with the properties `results` and `count`. The `results` property contains the objects resulting from the query. See more about counting [here](https://parse.com/docs/rest#queries-counting). If you only need `count`, you may also use the helper method `countObjects`. Using `getObjects` for counting has the advantage of querying for a _limited_ list of objects and getting the total possible objects that can be queried at the same time.

    // Get 10 objects, but also return the total number of objects
    var params = {
      where: { breed: "Chow Chow" },
      limit: 10,
      count: true
    };
    kaiseki.getObjects('Dogs', params, function(err, res, body, success) {
      console.log('The first 10 Chow chow dogs = ', body.results);
      console.log('Total number of Chow chow dogs = ', body.count);
    });

#### countObjects (className, params, callback)

Same as getObjects but returns a count in the `body.count` parameter without returning any objects.

    // count all objects (no parameters)
    kaiseki.countObjects('Dogs', function(err, res, body, success) {
      console.log('number of dogs = ', body.count);
    });

    // query with parameters
    var params = {
      where: { breed: "Chow Chow" },
      order: '-name'
    };
    kaiseki.getObjects('Dogs', params, function(err, res, body, success) {
      console.log('Number of Chow chow dogs = ', body.count);
    });

### Roles

Role methods are similar to the Object methods except that they don't require you to use a classname.

#### createRole (data, callback)

Creates a role and passes to `body` whatever you passed in `data` plus the returned `createdAt` field. You can only create a role if you provide the `kaiseki.masterKey` property.

    var data = {
      name: 'Administrator',
      ACL: {
          "*": {
            "read": true
          }
        },
      roles: {
          "__op": "AddRelation",
          "objects": [
            {
              "__type": "Pointer",
              "className": "_Role",
              "objectId": <role-id>
            }
          ]
        },
      users: {
          "__op": "AddRelation",
          "objects": [
            {
              "__type": "Pointer",
              "className": "_User",
              "objectId": <user-id>
            }
          ]
        }
    };

    kaiseki.createRole(data, function(err, res, body, success) {
      console.log('role created = ', body);
      console.log('object id = ', body.objectId);
    });

#### getRole (objectId, params, callback)

Gets a role based on the `objectId`. The `params` is currently unused but is there for a future use. You can pass in the callback function as the second parameter.

    kaiseki.getRole('<object-id>', function(err, res, body, success) {
      console.log('found role = ', body);
    });

#### updateRole (objectId, data, callback)

Updates a role. If successful, body will contain the `updatedAt` value. You can only update a role if you provide the `kaiseki.masterKey` property or the `kaiseki.sessionToken` property and if that user has write access to the role.

    var data = {
      users: {
          "__op": "RemoveRelation",
          "objects": [
            {
              "__type": "Pointer",
              "className": "_User",
              "objectId": <user-id>
            }
          ]
        }
    };

    kaiseki.updateRole('<role-object-id>', data, function(err, res, body, success) {
      console.log('role updated at = ', body.updatedAt);
    });

#### deleteRole (objectId, callback)

Deletes a role. The REST API does not return anything in the body so it's best to check for `success` if the operation was successful. You can only delete a role if you provide the `kaiseki.masterKey` property or the `kaiseki.sessionToken` property and if that user has write access to the role.

    kaiseki.deleteRole('<object-id>', function(err, res, body, success) {
      if (success)
        console.log('deleted!');
      else
        console.log('failed!');
    });

#### getRoles (params, callback)

Returns an array of roles. The `params` parameter can be an object containing the query options as described [here](https://parse.com/docs/rest#queries-basic). Note that unlike the Parse API Doc, you do not have to pass in strings for the parameter values. This is all taken care for you.

If you do not want to pass in some query parameters, you can set the callback as the first parameter.

The `body` in the callback is an array of the returned roles.

    // get all objects (no parameters)
    kaiseki.getRoles(function(err, res, body, success) {
      console.log('all roles = ', body);
    });

    // query with parameters
    var params = {
      where: { name: "Administrator" }
    };
    kaiseki.getRoles(params, function(err, res, body, success) {
      console.log('Administrator Role = ', body);
    });

### Files

#### uploadFile (filePath, fileName, callback)

Upload a local file. Specifying `fileName` is optional. If successful, the `body` result will contain the Parse `name` and `url` of the file. The value of `name` is what you will use for associating a Parse file to an object.

    var localFilePath = __dirname + '/images/apple.jpg';
    kaiseki.uploadFile(localFilePath, function(err, res, body, success) {
      console.log('uploaded file url:', body.url);
      console.log('uploaded file name:', body.name);
    });

#### uploadFileBuffer (buffer, contentType, fileName, callback)

This is a more specific upload utility. You can specify the buffer or string to be used as the upload data. The `body` result is still the same as `uploadFile()`.

    var buffer = require('fs').readFileSync(localFilePath);
    kaiseki.uploadFileBuffer(buffer, 'image/jpeg', 'orange.jpg', function(err, res, body, success) {
      console.log('uploaded file details', body);
    });

Uploading a string as a text file:

    var buffer = 'my text file contents';
    kaiseki.uploadFileBuffer(buffer, 'text/plain', 'readme.txt', function(err, res, body, success) {
      console.log('uploaded file details', body);
    });

#### deleteFile (name, callback)

Deleting files require the Parse API master key. The value of `name` should be the name generated by Parse during upload.

    kaiseki.masterKey = 'your-api-master-key';
    var parseFileName = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx-files.apple.jpg';
    kaiseki.deleteFile(parseFileName, function(err, res, body, success) {
      // body is empty here
      if (success)
        console.log('successfully deleted file!');
    });

#### Associating Files with Objects

Once you have the Parse file `name` after calling `uploadFile()` or `uploadFileBuffer()`, you can attach it to an object by simple setting a `"File"` data type to a property. More info [here](https://parse.com/docs/rest#files-associating).

    var parseFileName = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx-files.apple.jpg';
    var apple = {
      name: 'Apple',
      rotten: true,
      photo: {
        name: parseFileName,
        __type: 'File'
      }
    };
    kaiseki.createObject('Fruits', apple, function(err, res, body, success) {
      if (success)
        console.log('created an apple object with image');
    });

Associating a file to an existing object:

    var orange = {
      photo: {
        name: parseFileName,
        __type: 'File'
      }
    };
    kaiseki.updateObject('Fruits', '<the-object-id>', orange, function(err, res, body, success) {
      if (success)
        console.log('attached photo to an object');
    });

### Push Notifications

#### sendPushNotification (data, callback)

Send a push notification. The `data` parameter has to follow the data structure as described in the [Parse REST API](https://www.parse.com/docs/rest#push). The following code sample sends a notification to the broadcast channel (all devices) on all platforms (iOS and Android).

*Please note:* For push notifications to work you have to configure your Parse app accordingly. Use the _Settings > Push_ section of your app's dashboard.

    var notification = {
      channels: [''],
      data: {
        alert: "Tune in for the World Series, tonight at 8pm EDT"
      }
    };

    kaiseki.sendPushNotification(notification, function(err, res, body, success) {
      if (success) {
        console.log('Push notification successfully sent:', body);
      } else {
        console.log('Could not send push notification:', err);
      }
    });

### GeoPoints

You can set [GeoPoints](https://parse.com/docs/rest#geo) by simply setting a `"GeoPoint"` data type to a property named `"location"`.

    var place = {
      name: 'Tokyo Coffee Shop',
      location: {
        __type: 'GeoPoint',
        latitude: 40.0,
        longitude: -30.0
      }
    };
    kaiseki.createObject('Places', place, function(err, res, body, success) {
      if (success)
        console.log('Created a place with a GeoPoint.');
    });

### Analytics

You can use the [Analytics API](https://parse.com/docs/rest#analytics) to send analytic events happening in your app.

To record an _AppOpened_ event use it like this.

    kaiseki.sendAnalyticsEvent('AppOpened', function(err, res, body, success) {
      // do nothing
    });

To record a custom event, let's say _Search_, use it like this.

    kaiseki.sendAnalyticsEvent('Search', {
      'priceRange': '1000-1500',
      'source': 'craigslist',
      'dayType': 'weekday'
    }, function(err, res, body, success) {
      // do nothing
    );

Tests
-------------
The tests use [mocha](http://visionmedia.github.com/mocha/) and have to be run on an empty Parse application. Please provide your own API keys in `test/config.js`. To run the test:

    make mocha


text:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fb.h>
#include <linux/leds.h>
#include "leds.h"

#define BLANK		1
#define UNBLANK		0

struct bl_trig_notifier {
	struct led_classdev *led;
	int brightness;
	int old_status;
	struct notifier_block notifier;
};

static int fb_notifier_callback(struct notifier_block *p,
				unsigned long event, void *data)
{
	struct bl_trig_notifier *n = container_of(p,
					struct bl_trig_notifier, notifier);
	struct led_classdev *led = n->led;
	struct fb_event *fb_event = data;
	int *blank = fb_event->data;

	switch (event) {
	case FB_EVENT_BLANK :
		if (*blank && n->old_status == UNBLANK) {
			n->brightness = led->brightness;
			led_set_brightness(led, LED_OFF);
			n->old_status = BLANK;
		} else if (!*blank && n->old_status == BLANK) {
			led_set_brightness(led, n->brightness);
			n->old_status = UNBLANK;
		}
		break;
	}

	return 0;
}

static void bl_trig_activate(struct led_classdev *led)
{
	int ret;

	struct bl_trig_notifier *n;

	n = kzalloc(sizeof(struct bl_trig_notifier), GFP_KERNEL);
	led->trigger_data = n;
	if (!n) {
		dev_err(led->dev, "unable to allocate backlight trigger\n");
		return;
	}

	n->led = led;
	n->brightness = led->brightness;
	n->old_status = UNBLANK;
	n->notifier.notifier_call = fb_notifier_callback;

	ret = fb_register_client(&n->notifier);
	if (ret)
		dev_err(led->dev, "unable to register backlight trigger\n");
}

static void bl_trig_deactivate(struct led_classdev *led)
{
	struct bl_trig_notifier *n =
		(struct bl_trig_notifier *) led->trigger_data;

	if (n) {
		fb_unregister_client(&n->notifier);
		kfree(n);
	}
}

static struct led_trigger bl_led_trigger = {
	.name		= "backlight",
	.activate	= bl_trig_activate,
	.deactivate	= bl_trig_deactivate
};

static int __init bl_trig_init(void)
{
	return led_trigger_register(&bl_led_trigger);
}

static void __exit bl_trig_exit(void)
{
	led_trigger_unregister(&bl_led_trigger);
}

module_init(bl_trig_init);
module_exit(bl_trig_exit);

MODULE_AUTHOR("Rodolfo Giometti <giometti@linux.it>");
MODULE_DESCRIPTION("Backlight emulation LED trigger");
MODULE_LICENSE("GPL v2");


text:
package com.yammer.metrics.jetty;

import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.CounterMetric;
import com.yammer.metrics.core.MeterMetric;
import com.yammer.metrics.core.MetricsRegistry;
import com.yammer.metrics.core.TimerMetric;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.server.nio.SelectChannelConnector;

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

public class InstrumentedSelectChannelConnector extends SelectChannelConnector {
    private final TimerMetric duration;
    private final MeterMetric accepts, connects, disconnects;
    private final CounterMetric connections;

    public InstrumentedSelectChannelConnector(int port) {
        this(Metrics.defaultRegistry(), port);
    }

    public InstrumentedSelectChannelConnector(MetricsRegistry registry,
                                              int port) {
        super();
        setPort(port);
        this.duration = registry.newTimer(SelectChannelConnector.class,
                                          "connection-duration",
                                          Integer.toString(port),
                                          TimeUnit.MILLISECONDS,
                                          TimeUnit.SECONDS);
        this.accepts = registry.newMeter(SelectChannelConnector.class,
                                         "accepts",
                                         Integer.toString(port),
                                         "connections",
                                         TimeUnit.SECONDS);
        this.connects = registry.newMeter(SelectChannelConnector.class,
                                          "connects",
                                          Integer.toString(port),
                                          "connections",
                                          TimeUnit.SECONDS);
        this.disconnects = registry.newMeter(SelectChannelConnector.class,
                                             "disconnects",
                                             Integer.toString(port),
                                             "connections",
                                             TimeUnit.SECONDS);
        this.connections = registry.newCounter(SelectChannelConnector.class,
                                               "active-connections",
                                               Integer.toString(port));
    }

    @Override
    public void accept(int acceptorID) throws IOException {
        super.accept(acceptorID);
        accepts.mark();
    }

    @Override
    protected void connectionOpened(Connection connection) {
        connections.inc();
        super.connectionOpened(connection);
        connects.mark();
    }

    @Override
    protected void connectionClosed(Connection connection) {
        super.connectionClosed(connection);
        disconnects.mark();
        long duration = System.currentTimeMillis() - connection.getTimeStamp();
        this.duration.update(duration, TimeUnit.MILLISECONDS);
        connections.dec();
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Cci.Writers
{
    public interface ICciDeclarationWriter
    {
        void WriteDeclaration(IDefinition definition);
        void WriteAttribute(ICustomAttribute attribute);
    }
}


text:
namespace llvm {

// Number of bits in data that are used for the sanitizer kind. Needs to match
// __sanitizer::kKindBits in compiler-rt/lib/stats/stats.h
enum { kSanitizerStatKindBits = 3 };

enum SanitizerStatKind {
  SanStat_CFI_VCall,
  SanStat_CFI_NVCall,
  SanStat_CFI_DerivedCast,
  SanStat_CFI_UnrelatedCast,
  SanStat_CFI_ICall,
};

struct SanitizerStatReport {
  SanitizerStatReport(Module *M);

  /// Generates code into B that increments a location-specific counter tagged
  /// with the given sanitizer kind SK.
  void create(IRBuilder<> &B, SanitizerStatKind SK);

  /// Finalize module stats array and add global constructor to register it.
  void finish();

private:
  Module *M;
  GlobalVariable *ModuleStatsGV;
  ArrayType *StatTy;
  StructType *EmptyModuleStatsTy;

  std::vector<Constant *> Inits;
  ArrayType *makeModuleStatsArrayTy();
  StructType *makeModuleStatsTy();
};

}

#endif


text:
package model

import (
	"fmt"
	"github.com/kubeflow/arena/pkg/apis/types"
	"github.com/kubeflow/arena/pkg/argsbuilder"
	"strings"
)

type ModelEvaluateJobBuilder struct {
	args      *types.ModelEvaluateArgs
	argValues map[string]interface{}
	argsbuilder.ArgsBuilder
}

func NewModelEvaluateJobBuilder() *ModelEvaluateJobBuilder {
	args := &types.ModelEvaluateArgs{
		CommonModelArgs: types.CommonModelArgs{
			Image:     argsbuilder.DefaultModelJobImage,
			Namespace: "default",
		},
	}
	return &ModelEvaluateJobBuilder{
		args:        args,
		argValues:   map[string]interface{}{},
		ArgsBuilder: argsbuilder.NewModelEvaluateArgsBuilder(args),
	}
}

// Name is used to set job name,match option --name
func (m *ModelEvaluateJobBuilder) Name(name string) *ModelEvaluateJobBuilder {
	if name != "" {
		m.args.Name = name
	}
	return m
}

// Namespace is used to set job namespace,match option --namespace
func (m *ModelEvaluateJobBuilder) Namespace(namespace string) *ModelEvaluateJobBuilder {
	if namespace != "" {
		m.args.Namespace = namespace
	}
	return m
}

// Shell is used to specify linux shell type
func (m *ModelEvaluateJobBuilder) Shell(shell string) *ModelEvaluateJobBuilder {
	if shell != "" {
		m.args.Shell = shell
	}
	return m
}

// Command is used to set job command
func (m *ModelEvaluateJobBuilder) Command(args []string) *ModelEvaluateJobBuilder {
	m.args.Command = strings.Join(args, " ")
	return m
}

// Image is used to set job image,match the option --image
func (m *ModelEvaluateJobBuilder) Image(image string) *ModelEvaluateJobBuilder {
	if image != "" {
		m.args.Image = image
	}
	return m
}

// ImagePullPolicy is used to set image pull policy,match the option --image-pull-policy
func (m *ModelEvaluateJobBuilder) ImagePullPolicy(policy string) *ModelEvaluateJobBuilder {
	if policy != "" {
		m.args.ImagePullPolicy = policy
	}
	return m
}

// ImagePullSecrets is used to set image pull secrests,match option --image-pull-secret
func (m *ModelEvaluateJobBuilder) ImagePullSecrets(secrets []string) *ModelEvaluateJobBuilder {
	if secrets != nil {
		m.argValues["image-pull-secret"] = &secrets
	}
	return m
}

// GPUCount is used to set count of gpu for the job,match the option --gpus
func (m *ModelEvaluateJobBuilder) GPUCount(count int) *ModelEvaluateJobBuilder {
	if count > 0 {
		m.args.GPUCount = count
	}
	return m
}

// GPUMemory is used to set gpu memory for the job,match the option --gpumemory
func (m *ModelEvaluateJobBuilder) GPUMemory(memory int) *ModelEvaluateJobBuilder {
	if memory > 0 {
		m.args.GPUMemory = memory
	}
	return m
}

// GPUCore is used to set gpu core for the job,match the option --gpumemory
func (m *ModelEvaluateJobBuilder) GPUCore(core int) *ModelEvaluateJobBuilder {
	if core > 0 {
		m.args.GPUCore = core
	}
	return m
}

// CPU assign cpu limits,match the option --cpu
func (m *ModelEvaluateJobBuilder) CPU(cpu string) *ModelEvaluateJobBuilder {
	if cpu != "" {
		m.args.Cpu = cpu
	}
	return m
}

// Memory assign memory limits,match option --memory
func (m *ModelEvaluateJobBuilder) Memory(memory string) *ModelEvaluateJobBuilder {
	if memory != "" {
		m.args.Memory = memory
	}
	return m
}

// Envs is used to set env of job containers,match option --env
func (m *ModelEvaluateJobBuilder) Envs(envs map[string]string) *ModelEvaluateJobBuilder {
	if envs != nil && len(envs) != 0 {
		envSlice := []string{}
		for key, value := range envs {
			envSlice = append(envSlice, fmt.Sprintf("%v=%v", key, value))
		}
		m.argValues["env"] = &envSlice
	}
	return m
}

// Tolerations is used to set tolerations for tolerate nodes,match option --toleration
func (m *ModelEvaluateJobBuilder) Tolerations(tolerations []string) *ModelEvaluateJobBuilder {
	m.argValues["toleration"] = &tolerations
	return m
}

// NodeSelectors is used to set node selectors for scheduling job,match option --selector
func (m *ModelEvaluateJobBuilder) NodeSelectors(selectors map[string]string) *ModelEvaluateJobBuilder {
	if selectors != nil && len(selectors) != 0 {
		selectorsSlice := []string{}
		for key, value := range selectors {
			selectorsSlice = append(selectorsSlice, fmt.Sprintf("%v=%v", key, value))
		}
		m.argValues["selector"] = &selectorsSlice
	}
	return m
}

// Annotations is used to add annotations for job pods,match option --annotation
func (m *ModelEvaluateJobBuilder) Annotations(annotations map[string]string) *ModelEvaluateJobBuilder {
	if annotations != nil && len(annotations) != 0 {
		s := []string{}
		for key, value := range annotations {
			s = append(s, fmt.Sprintf("%v=%v", key, value))
		}
		m.argValues["annotation"] = &s
	}
	return m
}

// Labels is used to add labels for job
func (m *ModelEvaluateJobBuilder) Labels(labels map[string]string) *ModelEvaluateJobBuilder {
	if labels != nil && len(labels) != 0 {
		s := []string{}
		for key, value := range labels {
			s = append(s, fmt.Sprintf("%v=%v", key, value))
		}
		m.argValues["label"] = &s
	}
	return m
}

// Datas is used to mount k8s pvc to job pods,match option --data
func (m *ModelEvaluateJobBuilder) Datas(volumes map[string]string) *ModelEvaluateJobBuilder {
	if volumes != nil && len(volumes) != 0 {
		s := []string{}
		for key, value := range volumes {
			s = append(s, fmt.Sprintf("%v:%v", key, value))
		}
		m.argValues["data"] = &s
	}
	return m
}

// DataDirs is used to mount host files to job containers,match option --data-dir
func (m *ModelEvaluateJobBuilder) DataDirs(volumes map[string]string) *ModelEvaluateJobBuilder {
	if volumes != nil && len(volumes) != 0 {
		s := []string{}
		for key, value := range volumes {
			s = append(s, fmt.Sprintf("%v:%v", key, value))
		}
		m.argValues["data-dir"] = &s
	}
	return m
}

// SyncImage is used to set syncing image,match option --sync-image
func (m *ModelEvaluateJobBuilder) SyncImage(image string) *ModelEvaluateJobBuilder {
	if image != "" {
		m.args.SyncImage = image
	}
	return m
}

// SyncMode is used to set syncing mode,match option --sync-mode
func (m *ModelEvaluateJobBuilder) SyncMode(mode string) *ModelEvaluateJobBuilder {
	if mode != "" {
		m.args.SyncMode = mode
	}
	return m
}

// SyncSource is used to set syncing source,match option --sync-source
func (m *ModelEvaluateJobBuilder) SyncSource(source string) *ModelEvaluateJobBuilder {
	if source != "" {
		m.args.SyncSource = source
	}
	return m
}

// ModelPath is used to set model path,match the option --model-path
func (m *ModelEvaluateJobBuilder) ModelPath(path string) *ModelEvaluateJobBuilder {
	if path != "" {
		m.args.ModelPath = path
	}
	return m
}

// ModelPlatform specify the model platform, such as torchscript/tensorflow
func (m *ModelEvaluateJobBuilder) ModelPlatform(modelPlatform string) *ModelEvaluateJobBuilder {
	if modelPlatform != "" {
		m.args.ModelPlatform = modelPlatform
	}
	return m
}

// DatasetPath is the dataset to evaluate model
func (m *ModelEvaluateJobBuilder) DatasetPath(datasetPath string) *ModelEvaluateJobBuilder {
	if datasetPath != "" {
		m.args.DatasetPath = datasetPath
	}
	return m
}

// BatchSize is the batch size of evaluate
func (m *ModelEvaluateJobBuilder) BatchSize(batchSize int) *ModelEvaluateJobBuilder {
	if batchSize > 0 {
		m.args.BatchSize = batchSize
	}
	return m
}

// ReportPath is used to specify evaluate result path
func (m *ModelEvaluateJobBuilder) ReportPath(reportPath string) *ModelEvaluateJobBuilder {
	if reportPath != "" {
		m.args.ReportPath = reportPath
	}
	return m
}

// Build is used to build the job
func (m *ModelEvaluateJobBuilder) Build() (*Job, error) {
	for key, value := range m.argValues {
		m.AddArgValue(key, value)
	}
	if err := m.PreBuild(); err != nil {
		return nil, err
	}
	if err := m.ArgsBuilder.Build(); err != nil {
		return nil, err
	}
	return NewJob(m.args.Name, types.ModelEvaluateJob, m.args), nil
}


text:
layout: redirect
title: "GitHub & Gist"
moved_to: blog/2012/github-gist/
---


text:
using System;

namespace Lib.AspNetCore.Security.Http.Headers
{
    /// <summary>
    /// The names of HTTP headers
    /// </summary>
    public static class HeaderNames
    {
        /// <summary>
        /// The Clear-Site-Data header.
        /// </summary>
        public const string ClearSiteData = "Clear-Site-Data";

        /// <summary>
        /// The Content-Security-Policy header.
        /// </summary>
        public const string ContentSecurityPolicy = "Content-Security-Policy";

        /// <summary>
        /// The Content-Security-Policy-Report-Only header.
        /// </summary>
        public const string ContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only";

        /// <summary>
        /// The Expect-CT header.
        /// </summary>
        public const string ExpectCt = "Expect-CT";

        /// <summary>
        /// The Feature-Policy header.
        /// </summary>
        [Obsolete("Feature Policy has been replaced with Permissions Policy.")]
        public const string FeaturePolicy = "Feature-Policy";

        /// <summary>
        /// The Permissions-Policy header.
        /// </summary>
        public const string PermissionsPolicy = "Permissions-Policy";

        /// <summary>
        /// The Referrer-Policy header.
        /// </summary>
        public const string ReferrerPolicy = "Referrer-Policy";

        /// <summary>
        /// The Strict-Transport-Security header.
        /// </summary>
        public const string StrictTransportSecurity = "Strict-Transport-Security";

        /// <summary>
        /// The X-Content-Type-Options header.
        /// </summary>
        public const string XContentTypeOptions = "X-Content-Type-Options";

        /// <summary>
        /// The X-Download-Options header.
        /// </summary>
        public const string XDownloadOptions = "X-Download-Options";

        /// <summary>
        /// The X-Frame-Options header.
        /// </summary>
        public const string XFrameOptions = "X-Frame-Options";

        /// <summary>
        /// The X-Permitted-Cross-Domain-Policies header.
        /// </summary>
        public const string XPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies";

        /// <summary>
        /// The X-XSS-Protection header.
        /// </summary>
        public const string XXssProtection = "X-XSS-Protection";
    }
}


text:
package main
import . "fmt"

const Hello = "hello"
var world = "world"

func main() {
	world := world + "!"
	Println(Hello, world)
}


text:
package web

import (
	"fmt"
	"net/http"

	log "github.com/Sirupsen/logrus"
)

func (handler WebserviceHandler) DeployFront(w http.ResponseWriter, r *http.Request) {
	file, _, err := r.FormFile("bundle")
	if err != nil {
		log.Warnf("%s", err)
		fmt.Fprintf(w, "ERROR_BAD_FILE")
		return
	}
	defer file.Close()
	err = handler.sutils.ExtractZipToHttpDir(file, r.ContentLength)
	if err == nil {
		fmt.Fprintf(w, "OK")
	} else {
		log.Warnf("%s", err)
		fmt.Fprintf(w, "ERROR")
	}
}

func (handler WebserviceHandler) DeployCal(w http.ResponseWriter, r *http.Request) {
	log.Debug("Receiving calendar file")
	file, _, err := r.FormFile("bundle")
	if err != nil {
		log.Warnf("%s", err)
		fmt.Fprintf(w, "Error receiving excel file: %v", err)
		return
	}
	log.Debug("Copying file to folder")
	err = handler.sutils.CopyFileToExcelDir(file, "calendar.xlsx")
	if err != nil {
		log.Warnf("%s", err)
		fmt.Fprintf(w, "Error copying excel file: %v", err)
		return
	}
	err = handler.repo.ResetCalendar()
	if err != nil {
		log.Warnf("%s", err)
		fmt.Fprintf(w, "Error resetting calendar: %v", err)
		return
	}
	fmt.Fprintf(w, "OK")
}

func (handler WebserviceHandler) DeployDb(w http.ResponseWriter, r *http.Request) {
	log.Debug("Receiving db file")
	file, _, err := r.FormFile("bundle")
	if err != nil {
		log.Warnf("%s", err)
		fmt.Fprintf(w, "Error receiving excel file: %v", err)
		return
	}
	defer file.Close()
	log.Debug("Copying file to folder")
	err = handler.sutils.CopyFileToExcelDir(file, "mydb.xlsx")
	if err != nil {
		log.Warnf("%s", err)
		fmt.Fprintf(w, "Error copying excel file: %v", err)
		return
	}
	err = handler.repo.ResetDB()
	if err != nil {
		log.Warnf("%s", err)
		fmt.Fprintf(w, "Error resetting database: %v", err)
		return
	}
	fmt.Fprintf(w, "OK")
}


text:
var Randomizer = (function () {
    function Randomizer(random) {
        if (typeof random === "undefined") { random = Math.random; }
        this.random = random;
    }
    Randomizer.prototype.randomInt = function (max) {
        return Math.round(this.random() * max) * 10 / 10;
    };

    Randomizer.prototype.randomBetween = function (from, to, step) {
        var out = +from + this.random() * (to - from);
        out = Math.round(out / step) * step;
        return out * 10 / 10;
    };
    return Randomizer;
})();

module.exports = Randomizer;


text:
import datetime
import os.path

from django.db import models
from django.contrib.auth.models import User
from django.core.files.base import ContentFile
from django.utils.translation import ugettext as _

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

try:
    from PIL import Image
except ImportError:
    import Image

from avatar import AVATAR_STORAGE_DIR, AVATAR_RESIZE_METHOD

def avatar_file_path(instance=None, filename=None, user=None):
    user = user or instance.user
    return os.path.join(AVATAR_STORAGE_DIR, user.username, filename)

class Avatar(models.Model):
    user = models.ForeignKey(User)
    primary = models.BooleanField(default=False)
    avatar = models.ImageField(max_length=1024, upload_to=avatar_file_path, blank=True)
    date_uploaded = models.DateTimeField(default=datetime.datetime.now)

    def __unicode__(self):
        return _(u'Avatar for %s') % self.user

    def save(self, force_insert=False, force_update=False):
        if self.primary:
            avatars = Avatar.objects.filter(user=self.user, primary=True)\
                .exclude(id=self.id)
            avatars.update(primary=False)
        super(Avatar, self).save(force_insert, force_update)

    def thumbnail_exists(self, size):
        return self.avatar.storage.exists(self.avatar_name(size))

    def create_thumbnail(self, size):
        try:
            orig = self.avatar.storage.open(self.avatar.name, 'rb').read()
            image = Image.open(StringIO(orig))
        except IOError:
            return # What should we do here?  Render a "sorry, didn't work" img?
        (w, h) = image.size
        if w != size or h != size:
            if w > h:
                diff = (w - h) / 2
                image = image.crop((diff, 0, w - diff, h))
            else:
                diff = (h - w) / 2
                image = image.crop((0, diff, w, h - diff))
            image = image.resize((size, size), AVATAR_RESIZE_METHOD)
            if image.mode != "RGB":
                image = image.convert("RGB")
            thumb = StringIO()
            image.save(thumb, "JPEG")
            thumb_file = ContentFile(thumb.getvalue())
        else:
            thumb_file = ContentFile(orig)
        thumb = self.avatar.storage.save(self.avatar_name(size), thumb_file)

    def avatar_url(self, size):
        return self.avatar.storage.url(self.avatar_name(size))

    def avatar_name(self, size):
        return os.path.join(AVATAR_STORAGE_DIR, self.user.username,
            'resized', str(size), self.avatar.name)


text:
file(REMOVE_RECURSE
  "CMakeFiles/LogicToolbox-lib_test.dir/test_hello.cpp.o"
  "CMakeFiles/LogicToolbox-lib_test.dir/__/src/Core/Operators.cpp.o"
  "../bin/LogicToolbox-lib_test.pdb"
  "../bin/LogicToolbox-lib_test"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/LogicToolbox-lib_test.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
/**
 * This module demonstrates how to implement the CommonKV API by
 * providing a very simple in-memory CommonKV implementation
 * It is intended as an example or for testing.
 *
 * @author w.a.barnhill@gmail.com Bill Barnhill
 */
module.exports = {

 /**
  * This is how any store will be created.  The options are store specific
  * but some commonalities are expected, such as 'server' for redis, etc.
  *
  * @param {Object} options The options needed to initialize and open store
  * @param {function} callback The callback to receive results or err
  * @result {CommonKVStore} The opened and initialized store
  */
 openStore : function(options, callback) {
    var store = new MemStore();
    callback(false, store);
  }
};

 /**
  * This is a simple in-memory implementation of the CommonKV
  * API. More as an example than for actual use.
  *
  * @constructor
  * @this {MemStore}
  */
function MemStore() {
  if(false === (this instanceof MemStore)) {
    return new MemStore();
  }
  this.data = {};
}

MemStore.prototype = {

 /**
  * This sets one or more values for the given key.  If there are
  * any existing values then these are replaced by the new ones. The
  * old values are passed to the callback if any exist, or undefined is
  * passed if there are none.
  *
  * @param {String} key The key whose values we are setting
  * @param {Array} vals One or more values for this key
  * @param {function} callback The callback to receive results or err
  * @result {Object} Object of form {'key': {String}, 'values': {Array[*]}, 'old': {Array[*]}}
  */
 setValue : function(key, vals, callback) {
    var prev = this.data[key] || undefined;
    var next = [].concat(vals);
    this.data[key] = next;
    var result = {'key': key, 'values': next, 'old': prev};
    callback(false, result);
  },

 /**
  * This sets one or more values for the given key.  If there are
  * any existing values then the new ones are added to these values.
  * There is no behavior defined as to the order of the values.
  *
  * @param {String} key The key whose values we are adding to
  * @param {Array} vals One or more values for this key
  * @param {function} callback The callback to receive results or err
  * @result {Object} Object of form {'key': {String}, 'values': {Array[*]}, 'old': {Array[*]}}
  */
 addValues : function(key, vals, callback) {
    // Result: {'key': k, 'values': values}
    var prev = this.data[key] || undefined;
    var next = (prev || []).concat(vals);
    this.data[key] = next;
    var result = {'key': key, 'values': next, 'old': prev};
    callback(false, result);
  },

 /**
  * Get a single value for this key. If there are multiple values
  * then the selection of which one to use is implementation dependent.
  * For this reason it's better to use getValues unless you don't care
  * which value you get, as long as it's a value for the key.
  *
  * @param {String} key The key whose value we are getting
  * @param {function} callback The callback to receive results or err
  * @result {Object} Object of form {'key': {String}, 'value': *}
  * @todo wab fix this so one value == one callback call
  */
 getValue : function(key, callback) {
    var val = this.data[key] || undefined;
    var result = {'key':key, 'value': val};
    callback(false, result);
  },

 /**
  * This gets the values mapped to the specified key. The order of the
  * values is not defined.
  *
  * @param {String} key The key whose values we are getting
  * @param {function} callback The callback to receive results or err
  * @result {Object} Object of form {'key': {String}, 'values': {Array[*]}}
  */
 getValues : function(key, callback) {
    var val = this.data[key] || undefined;
    var result = {'key':key, 'values': val};
    callback(false, result);
  },

 /**
  * This allows an async walkthrough of the
  * names of available features. The callback is
  * called once for each feature.  Implementations
  * may provide additional information besides the
  * two standard keys of 'feature' and 'exists'.
  *
  * @param {function} callback The callback to receive results or err
  * @result {Object} Object of form {'feature': {String}, 'exists': {boolean}}
  */
 iterateFeatures : function(callback) {
    callback(false, {'feature': 'commands', 'exists': true});
  },

 /**
  * This allows access to feature specific properties.
  *
  * @param {string} featureName The name of the desired feature
  * @return {Object} The API implementation for the feature
  */
 feature : function(featureName) {
    // Result: object with feature specific properties and/or methods
    var CommandsFeature = require('./feature-commands.js');
    var store = this;
    return new CommandsFeature(store);
  },

 /**
  * Closes the store. In this case that just
  * means nulling out the internal references.
  * Nothing is specified about the non-null object sent if the store
  * is closed successfully, but it could be used by implementations to
  * provide final state information.
  *
  * @param {function} callback The callback to receive results or err
  * @result {Object} A non-null Object is sent if store is successfully closed
  */
 close : function(callback) {
	this.data = null;
	callback(false, {'closed': true});
 }
};


text:
System ACL-i dla DHCPd

CELE:

Zasadniczym celem systemu ACL-i jest zapewnienie silnego, elastycznego
<<<<<<< HEAD
i rozszerzalnego mechanizmu kontroli dostêpu do ró¿nych obiektów
w konfiguracji DHCPd. Obiektami tymi s± sieci wspó³dzielone, podsieci,
grupy hostów i hosty.

System ACL-i pozwala równie¿ na kontrolowanie kilku innych w³a¶ciwo¶ci,
takich jak: unikalno¶æ nazw obiektów, mo¿liwo¶æ zastosowania zmienionej
konfiguracji, przegl±danie i kasowanie dzier¿aw DHCP.

ZASADY:

Plik konfiguracyjny DHCPd posiada strukturê drzewiast±. Ka¿dy wêze³ tego
drzewa reprezentuje sob± konfiguracjê pojedyñczego obiektu DHCP (rys. 0).

System ACL-i posiada dwa poziomy zabezpieczeñ:
=======
i rozszerzalnego mechanizmu kontroli dostępu do różnych obiektów
w konfiguracji DHCPd. Obiektami tymi są sieci współdzielone, podsieci,
grupy hostów i hosty.

System ACL-i pozwala również na kontrolowanie kilku innych właściwości,
takich jak: unikalność nazw obiektów, możliwość zastosowania zmienionej
konfiguracji, przeglądanie i kasowanie dzierżaw DHCP.

ZASADY:

Plik konfiguracyjny DHCPd posiada strukturę drzewiastą. Każdy węzeł tego
drzewa reprezentuje sobą konfigurację pojedyńczego obiektu DHCP (rys. 0).

System ACL-i posiada dwa poziomy zabezpieczeń:
>>>>>>> upstream/master

poziom ogólny: odczyt, zapis, tworzenie;

dla poszczególnych obiektów: odczyt, zapis.

<<<<<<>>>>>> upstream/master
obiektach danego typu:

ogólne uprawnienia do tworzenia,

ogólne uprawnienia do odczytu,

ogólne uprawnienia do zapisu.

<<<<<<< HEAD
Uprawnienia dla poszczególnych obiektów umo¿liwiaj± kontrolê dostêpu
w bardziej elastyczny sposób. ACL-e uprawnieñ dla poszczególnych
obiektów istniej± dla ka¿dego pojedyñczego obiektu. Obecnie ACL-e dla
poszczególnych obiektów zaimplementowane s± jedynie dla hostów
=======
Uprawnienia dla poszczególnych obiektów umożliwiają kontrolę dostępu
w bardziej elastyczny sposób. ACL-e uprawnień dla poszczególnych
obiektów istnieją dla każdego pojedyńczego obiektu. Obecnie ACL-e dla
poszczególnych obiektów zaimplementowane są jedynie dla hostów
>>>>>>> upstream/master
i podsieci:

uprawnienia do zapisu dla poszczególnych obiektów,

uprawnienia do odczytu dla poszczególnych obiektów.

<<<<<<< HEAD
System ACL-i mo¿e dzia³aæ przy czterech ró¿nych poziomach (trybach) zabezpieczeñ.

=======
System ACL-i może działać przy czterech różnych poziomach (trybach) zabezpieczeń.

>>>>>>> upstream/master


text:
title:  "Ka Setšoantšo sa Oona"
date:  17/07/2022
---

>

> "Hobane bao o itsebetseng bona pele, o bile o ba reretse pele, hore ba tla bapa le setšoantšo sa Mor'a oona, hore eena e tle e be oa letsibolo har'a baena ba bangata" (Ba-Roma 8:29).

Tšimolohong Molimo o re entse ka setšoantšo sa oona (Gen. 1:27), empa setšoantšo seo se sentsoe ke sebe.

`Ke ka litsela life re bonang ho fela ha setšoantšo sa Molimo bathong?`

Ho hlakile: bohle re singlafalitsoe ke sebe (Ba-Ba-Roma 3:10-19). Empa, takatso ea Molimo ke ho re khutlisetsa ho seo re neng re le sona qalong. Ke moo temana ea rōna ea kajeno e kenang. E senola morero oa Molimo oa hore bohle ba nehelanang ka maphelo a bona ho Moea o Halalelang hore ba tle ba "bape le setšoantšo sa Mor'a oona" (Baroma 8:29).

Empa ho na le lehlakore le leng. "Sona setšoantšo sa Molimo se lokela ho hlahisoa bocha bathong. Tlotla ea Molimo, tlotla ea Kreste, e ea kenella phethahatsong ea semelo sa batho hae."—Ellen G. White, The Desire of Ages, p. 671.

`U utloisisa joang seo Ellen G. White a re bolellang sona qotsulong ee e kaholimo? Sheba hape Jobo 1, Matt. 5:16, 1 Ba-Kor. 4:9, Ba-Efe. 3:10.`

Re le Bakreste, re lokela ho se lebale hore re ka hara ntoa e kholo. Toantšano e lipakeng tsa Kreste le Satane e ntse kupa 'me e re potile ka hohle. Ntoa e nka litšobotsi tse ngata le ho hlaha ka litsela tse ngata. Leha boholo bo patehile, re ka utloisisa re le balateli ba Kreste, re na le karolo eo re lokelang ho e bapala toantšanong ena le ho tlisa tlotla ho Kreste ka maphelo a rōna.

`Nahana u se u le ka lebaleng la stadium se seholo. Ho lutse ka lehlakoreng le leng libopuoa tsa leholimo tse tšepahallang Morena; ha ka lehlakoreng le leng e le libopuoa tse oeleng le Lusifera. Ha e ne e ba bophelo ba hao lihoreng tse mashome a mabeli a metso e mene tse fetileng bo ne bo ka behoa bohareng ba lebala, ke lehlakore lefe le neng le tla thoholetsa haholo? Karabo ea hao e u bolella'ng ka uena?`


text:
import models from '../../server/models';

export default function createPost(newPost, callback) {

  // Do the DB query, etc
  console.log('Creating a new post...');

  models.Post.create(newPost, callback);
}