text:
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_down_main(object):
    def setupUi(self, down_main):
        down_main.setObjectName(_fromUtf8("down_main"))
        down_main.resize(344, 150)
        down_main.setMinimumSize(QtCore.QSize(344, 150))
        down_main.setMaximumSize(QtCore.QSize(344, 150))
        down_main.setWindowIcon(QtGui.QIcon("bin/icon.png"));
        down_main.setStyleSheet(_fromUtf8("QDialog { background-color: white; }\n"
"QProgressBar { border: 2px solid grey; border-radius: 5px; text-align: center; font-family: Liberation Mono; color: black; }\n"
"QProgressBar::chunk { background-color: #CD96CD; width: 10px; margin: 0.5px; }\n"
"QPushButton { background-color: white; font-family: Liberation Mono; color: black; }\n"
"QPushButton:pressed { color: white; background-color: #CD96CD; }"))
        self.cancelButton = QtGui.QPushButton(down_main)
        self.cancelButton.setGeometry(QtCore.QRect(69, 90, 96, 32))
        self.cancelButton.setFocusPolicy(QtCore.Qt.NoFocus)
        self.cancelButton.setStyleSheet(_fromUtf8("border: 2px solid grey; font-weight: bold; border-radius: 5px;"))
        self.cancelButton.setObjectName(_fromUtf8("cancelButton"))
        self.closeButton = QtGui.QPushButton(down_main)
        self.closeButton.setGeometry(QtCore.QRect(180, 90, 96, 32))
        self.closeButton.setFocusPolicy(QtCore.Qt.NoFocus)
        self.closeButton.setAutoFillBackground(False)
        self.closeButton.setStyleSheet(_fromUtf8("border: 2px solid grey; font-weight: bold; border-radius: 5px;"))
        self.closeButton.setObjectName(_fromUtf8("closeButton"))
        self.progressBar = QtGui.QProgressBar(down_main)
        self.progressBar.setGeometry(QtCore.QRect(31, 30, 280, 31))
        self.progressBar.setStyleSheet(_fromUtf8("font-weight: bold;"))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName(_fromUtf8("progressBar"))

        self.retranslateUi(down_main)
        QtCore.QMetaObject.connectSlotsByName(down_main)

    def retranslateUi(self, down_main):
        down_main.setWindowTitle(_translate("down_main", "Downloader", None))
        self.cancelButton.setText(_translate("down_main", "Cancel", None))
        self.closeButton.setText(_translate("down_main", "Close", None))


text:
package org.consumersunion.stories.dashboard.client.application.ui.block;

import org.consumersunion.stories.common.shared.i18n.CommonI18nLabels;
import org.consumersunion.stories.common.shared.model.document.BlockType;
import org.consumersunion.stories.common.shared.model.questionnaire.Question;
import org.consumersunion.stories.common.shared.model.type.DataType;
import org.consumersunion.stories.common.shared.model.type.State;

import com.google.inject.Inject;

public class StandardQuestionFactory {
    private final CommonI18nLabels labels;

    @Inject
    StandardQuestionFactory(CommonI18nLabels labels) {
        this.labels = labels;
    }

    public Question createStandardQuestion(BlockType blockType) {
        Question question = new Question();
        question.setRequired(blockType.isRequired());
        question.setBlockType(blockType);

        if (blockType == BlockType.FIRST_NAME) {
            question.setLabel(labels.standQuestFirstName());
            question.setText(labels.standQuestFirstName());
            question.setDataType(DataType.DATA_NAME.code());
        } else if (blockType == BlockType.LAST_NAME) {
            question.setLabel(labels.standQuestLastName());
            question.setText(labels.standQuestLastName());
            question.setDataType(DataType.DATA_NAME.code());
        } else if (blockType == BlockType.STREET_ADDRESS_1) {
            question.setLabel(labels.standQuestStreet());
            question.setText(labels.standQuestStreet());
            question.setDataType(DataType.DATA_STRING.code());
        } else if (blockType == BlockType.CITY) {
            question.setLabel(labels.standQuestCity());
            question.setText(labels.standQuestCity());
            question.setDataType(DataType.DATA_NAME.code());
        } else if (blockType == BlockType.STATE) {
            question.setLabel(labels.standQuestState());
            question.setText(labels.standQuestState());
            for (State state : State.values()) {
                question.addOption(state.name(), state.name());
            }
        } else if (blockType == BlockType.ZIP_CODE) {
            question.setLabel(labels.standQuestZip());
            question.setText(labels.standQuestZip());
            question.setDataType(DataType.DATA_ZIP.code());
        } else if (blockType == BlockType.MAILING_OPT_IN) {
            question.setLabel(labels.standOptIn());
            question.setText(labels.standOptIn());
        } else if (blockType == BlockType.PREFERRED_EMAIL_FORMAT) {
            question.setLabel(labels.standPreferredEmailFormat());
            question.setText(labels.standPreferredEmailFormat());
            question.addOption("Plain Text", "Plain Text");
            question.addOption("HTML", "HTML");
        } else if (blockType == BlockType.STORY_ASK_RICH
        		|| blockType == BlockType.STORY_ASK_PLAIN) {
            question.setLabel(labels.tellYourStory());
            question.setText(labels.tellYourStory());
        } else if (blockType == BlockType.UPDATES_OPT_IN) {
            question.setLabel(labels.updatesOptIn());
            question.setText(labels.updatesOptIn());
            question.addOption(labels.optInDetails(), labels.optInDetails());
        } else if (blockType == BlockType.STORY_TITLE) {
            question.setLabel(labels.giveYourStoryATitle());
            question.setText(labels.giveYourStoryATitle());
            question.setHelpText("");
        }

        return question;
    }
}

redpajama_set_name: RedPajamaGithub


text:
var CreateReplyPage = function () {

	return {

		openCreateReplyDialog: function () {
			return element(by.css('[aria-label="Reply"]')).click();
		},

		fillInputFields: function (reply) {
			browser.switchTo().frame(element(by.css('.cke_wysiwyg_frame')).click());
			browser.actions().sendKeys(reply).perform();
			browser.driver.sleep(500);
			browser.switchTo().defaultContent();
		},

		createReply: function () {
			return element(by.css('[aria-label="Reply"] button[type="submit"]')).click();
		},

		getAllReplies: function() {
			return replies = element.all(by.binding('reply.content'));
		},

		getAllReplies2: function() {
			return element.all(by.repeater('reply in dc.replies'));
		}
	};
};

module.exports = CreateReplyPage();


text:
"""
Script that imports locally stored data as a new dataset for the user
Usage: import id outputfile
"""
import sys, os
from shutil import copyfile
#tempfile, shutil
BUFFER = 1048576

uids = sys.argv[1].split(",")
out_file1 = sys.argv[2]

#remove NONE from uids
have_none = True
while have_none:
    try:
        uids.remove('None')
    except:
        have_none = False

#create dictionary keyed by uid of tuples of (displayName,filePath,build) for all files
available_files = {}
try:
    for line in open( "/cache/encode_datasets/encode_datasets.loc" ):
        if line[0:1] == "#" : continue

        fields = line.split('\t')
        #read each line, if not enough fields, go to next line
        try:
            encode_group = fields[0]
            build = fields[1]
            description = fields[2]
            uid = fields[3]
            path = fields[4]
            path = path.replace("\n","")
            path = path.replace("\r","")
            try:
                file_type = fields[5]
                #remove newlines from file type
                file_type = file_type.replace("\n","")
                file_type = file_type.replace("\r","")
            except:
                file_type = "bed"

        except:
            continue
        available_files[uid]=(description,path,build,file_type)
except:
    print >>sys.stderr, "It appears that the configuration file for this tool is missing."

#create list of tuples of (displayName,FileName,build) for desired files
desired_files = []
for uid in uids:
    try:
        desired_files.append(available_files[uid])
    except:
        continue

#copy first file to contents of given output file
file1_copied = False
while not file1_copied:
    try:
        first_file = desired_files.pop(0)
    except:
        print >>sys.stderr, "There were no valid files requested."
        sys.exit()
    file1_desc, file1_path, file1_build, file1_type = first_file
    try:
        copyfile(file1_path,out_file1)
        print "#File1\t"+file1_desc+"\t"+file1_build+"\t"+file1_type
        file1_copied = True
    except:
        print >>sys.stderr, "The file specified is missing."
        continue
        #print >>sys.stderr, "The file specified is missing."

#Tell post-process filter where remaining files reside
for extra_output in desired_files:
    file_desc, file_path, file_build, file_type = extra_output
    print "#NewFile\t"+file_desc+"\t"+file_build+"\t"+file_path+"\t"+file_type


text:
import datetime

import mock
from oslo_serialization import jsonutils
import six
import webob

from nova.api.openstack.compute import flavor_access as flavor_access_v21
from nova.api.openstack.compute import flavor_manage as flavormanage_v21
from nova.api.openstack.compute.legacy_v2.contrib import flavor_access \
        as flavor_access_v2
from nova.api.openstack.compute.legacy_v2.contrib import flavormanage \
        as flavormanage_v2
from nova.compute import flavors
from nova import db
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes

def fake_db_flavor(**updates):
    db_flavor = {
        'root_gb': 1,
        'ephemeral_gb': 1,
        'name': u'frob',
        'deleted': False,
        'created_at': datetime.datetime(2012, 1, 19, 18, 49, 30, 877329),
        'updated_at': None,
        'memory_mb': 256,
        'vcpus': 1,
        'flavorid': 1,
        'swap': 0,
        'rxtx_factor': 1.0,
        'extra_specs': {},
        'deleted_at': None,
        'vcpu_weight': None,
        'id': 7,
        'is_public': True,
        'disabled': False,
    }
    if updates:
        db_flavor.update(updates)
    return db_flavor

def fake_get_flavor_by_flavor_id(flavorid, ctxt=None, read_deleted='yes'):
    if flavorid == 'failtest':
        raise exception.FlavorNotFound(flavor_id=flavorid)
    elif not str(flavorid) == '1234':
        raise Exception("This test expects flavorid 1234, not %s" % flavorid)
    if read_deleted != 'no':
        raise test.TestingException("Should not be reading deleted")
    return fake_db_flavor(flavorid=flavorid)

def fake_destroy(flavorname):
    pass

def fake_create(context, kwargs, projects=None):
    newflavor = fake_db_flavor()

    flavorid = kwargs.get('flavorid')
    if flavorid is None:
        flavorid = 1234

    newflavor['flavorid'] = flavorid
    newflavor["name"] = kwargs.get('name')
    newflavor["memory_mb"] = int(kwargs.get('memory_mb'))
    newflavor["vcpus"] = int(kwargs.get('vcpus'))
    newflavor["root_gb"] = int(kwargs.get('root_gb'))
    newflavor["ephemeral_gb"] = int(kwargs.get('ephemeral_gb'))
    newflavor["swap"] = kwargs.get('swap')
    newflavor["rxtx_factor"] = float(kwargs.get('rxtx_factor'))
    newflavor["is_public"] = bool(kwargs.get('is_public'))
    newflavor["disabled"] = bool(kwargs.get('disabled'))

    return newflavor

class FlavorManageTestV21(test.NoDBTestCase):
    controller = flavormanage_v21.FlavorManageController()
    validation_error = exception.ValidationError
    base_url = '/v2/fake/flavors'

    def setUp(self):
        super(FlavorManageTestV21, self).setUp()
        self.stubs.Set(flavors,
                       "get_flavor_by_flavor_id",
                       fake_get_flavor_by_flavor_id)
        self.stubs.Set(flavors, "destroy", fake_destroy)
        self.stubs.Set(db, "flavor_create", fake_create)
        self.app = self._setup_app()

        self.request_body = {
            "flavor": {
                "name": "test",
                "ram": 512,
                "vcpus": 2,
                "disk": 1,
                "OS-FLV-EXT-DATA:ephemeral": 1,
                "id": six.text_type('1234'),
                "swap": 512,
                "rxtx_factor": 1,
                "os-flavor-access:is_public": True,
            }
        }
        self.expected_flavor = self.request_body

    def _get_http_request(self, url=''):
        return fakes.HTTPRequest.blank(url)

    def _setup_app(self):
        return fakes.wsgi_app_v21(init_only=('os-flavor-manage',
                                             'os-flavor-rxtx',
                                             'os-flavor-access', 'flavors',
                                             'os-flavor-extra-data'))

    def test_delete(self):
        res = self.controller._delete(self._get_http_request(), 1234)

        # NOTE: on v2.1, http status code is set as wsgi_code of API
        # method instead of status_int in a response object.
        if isinstance(self.controller,
                      flavormanage_v21.FlavorManageController):
            status_int = self.controller._delete.wsgi_code
        else:
            status_int = res.status_int
        self.assertEqual(202, status_int)

        # subsequent delete should fail
        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller._delete, self._get_http_request(),
                          "failtest")

    def _test_create_missing_parameter(self, parameter):
        body = {
            "flavor": {
                "name": "azAZ09. -_",
                "ram": 512,
                "vcpus": 2,
                "disk": 1,
                "OS-FLV-EXT-DATA:ephemeral": 1,
                "id": six.text_type('1234'),
                "swap": 512,
                "rxtx_factor": 1,
                "os-flavor-access:is_public": True,
            }
        }

        del body['flavor'][parameter]

        self.assertRaises(self.validation_error, self.controller._create,
                          self._get_http_request(), body=body)

    def test_create_missing_name(self):
        self._test_create_missing_parameter('name')

    def test_create_missing_ram(self):
        self._test_create_missing_parameter('ram')

    def test_create_missing_vcpus(self):
        self._test_create_missing_parameter('vcpus')

    def test_create_missing_disk(self):
        self._test_create_missing_parameter('disk')

    def _create_flavor_success_case(self, body, req=None):
        req = req if req else self._get_http_request(url=self.base_url)
        req.headers['Content-Type'] = 'application/json'
        req.method = 'POST'
        req.body = jsonutils.dumps(body)
        res = req.get_response(self.app)
        self.assertEqual(200, res.status_code)
        return jsonutils.loads(res.body)

    def test_create(self):
        body = self._create_flavor_success_case(self.request_body)
        for key in self.expected_flavor["flavor"]:
            self.assertEqual(body["flavor"][key],
                             self.expected_flavor["flavor"][key])

    def test_create_public_default(self):
        del self.request_body['flavor']['os-flavor-access:is_public']
        body = self._create_flavor_success_case(self.request_body)
        for key in self.expected_flavor["flavor"]:
            self.assertEqual(body["flavor"][key],
                             self.expected_flavor["flavor"][key])

    def test_create_without_flavorid(self):
        del self.request_body['flavor']['id']
        body = self._create_flavor_success_case(self.request_body)
        for key in self.expected_flavor["flavor"]:
            self.assertEqual(body["flavor"][key],
                             self.expected_flavor["flavor"][key])

    def _create_flavor_bad_request_case(self, body):
        self.stubs.UnsetAll()

        self.assertRaises(self.validation_error, self.controller._create,
                          self._get_http_request(), body=body)

    def test_create_invalid_name(self):
        self.request_body['flavor']['name'] = 'bad !@#!$%\x00 name'
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_flavor_name_is_whitespace(self):
        self.request_body['flavor']['name'] = ' '
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_name_too_long(self):
        self.request_body['flavor']['name'] = 'a' * 256
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_name_leading_trailing_spaces(self):
        self.request_body['flavor']['name'] = '  test  '
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_name_leading_trailing_spaces_compat_mode(self):
        req = self._get_http_request(url=self.base_url)
        req.set_legacy_v2()
        self.request_body['flavor']['name'] = '  test  '
        body = self._create_flavor_success_case(self.request_body, req)
        self.assertEqual('test', body['flavor']['name'])

    def test_create_without_flavorname(self):
        del self.request_body['flavor']['name']
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_empty_body(self):
        body = {
            "flavor": {}
        }
        self._create_flavor_bad_request_case(body)

    def test_create_no_body(self):
        body = {}
        self._create_flavor_bad_request_case(body)

    def test_create_invalid_format_body(self):
        body = {
            "flavor": []
        }
        self._create_flavor_bad_request_case(body)

    def test_create_invalid_flavorid(self):
        self.request_body['flavor']['id'] = "!@#!$#!$^#&^$&"
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_check_flavor_id_length(self):
        MAX_LENGTH = 255
        self.request_body['flavor']['id'] = "a" * (MAX_LENGTH + 1)
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_leading_trailing_whitespaces_in_flavor_id(self):
        self.request_body['flavor']['id'] = "   bad_id   "
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_without_ram(self):
        del self.request_body['flavor']['ram']
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_0_ram(self):
        self.request_body['flavor']['ram'] = 0
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_without_vcpus(self):
        del self.request_body['flavor']['vcpus']
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_0_vcpus(self):
        self.request_body['flavor']['vcpus'] = 0
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_without_disk(self):
        del self.request_body['flavor']['disk']
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_minus_disk(self):
        self.request_body['flavor']['disk'] = -1
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_minus_ephemeral(self):
        self.request_body['flavor']['OS-FLV-EXT-DATA:ephemeral'] = -1
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_minus_swap(self):
        self.request_body['flavor']['swap'] = -1
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_minus_rxtx_factor(self):
        self.request_body['flavor']['rxtx_factor'] = -1
        self._create_flavor_bad_request_case(self.request_body)

    def test_create_with_non_boolean_is_public(self):
        self.request_body['flavor']['os-flavor-access:is_public'] = 123
        self._create_flavor_bad_request_case(self.request_body)

    def test_flavor_exists_exception_returns_409(self):
        expected = {
            "flavor": {
                "name": "test",
                "ram": 512,
                "vcpus": 2,
                "disk": 1,
                "OS-FLV-EXT-DATA:ephemeral": 1,
                "id": 1235,
                "swap": 512,
                "rxtx_factor": 1,
                "os-flavor-access:is_public": True,
            }
        }

        def fake_create(name, memory_mb, vcpus, root_gb, ephemeral_gb,
                        flavorid, swap, rxtx_factor, is_public):
            raise exception.FlavorExists(name=name)

        self.stubs.Set(flavors, "create", fake_create)
        self.assertRaises(webob.exc.HTTPConflict, self.controller._create,
                          self._get_http_request(), body=expected)

    @mock.patch('nova.compute.flavors.create',
                side_effect=exception.FlavorCreateFailed)
    def test_flavor_create_db_failed(self, mock_create):
        request_dict = {
            "flavor": {
                "name": "test",
                'id': "12345",
                "ram": 512,
                "vcpus": 2,
                "disk": 1,
                "OS-FLV-EXT-DATA:ephemeral": 1,
                "swap": 512,
                "rxtx_factor": 1,
                "os-flavor-access:is_public": True,
            }
        }
        ex = self.assertRaises(webob.exc.HTTPInternalServerError,
                               self.controller._create,
                               self._get_http_request(), body=request_dict)
        self.assertIn('Unable to create flavor', ex.explanation)

    def test_invalid_memory_mb(self):
        """Check negative and decimal number can't be accepted."""

        self.stubs.UnsetAll()
        self.assertRaises(exception.InvalidInput, flavors.create, "abc",
                          -512, 2, 1, 1, 1234, 512, 1, True)
        self.assertRaises(exception.InvalidInput, flavors.create, "abcd",
                          512.2, 2, 1, 1, 1234, 512, 1, True)
        self.assertRaises(exception.InvalidInput, flavors.create, "abcde",
                          None, 2, 1, 1, 1234, 512, 1, True)
        self.assertRaises(exception.InvalidInput, flavors.create, "abcdef",
                          512, 2, None, 1, 1234, 512, 1, True)
        self.assertRaises(exception.InvalidInput, flavors.create, "abcdef",
                          "test_memory_mb", 2, None, 1, 1234, 512, 1, True)

class PrivateFlavorManageTestV21(test.TestCase):
    controller = flavormanage_v21.FlavorManageController()
    base_url = '/v2/fake/flavors'

    def setUp(self):
        super(PrivateFlavorManageTestV21, self).setUp()
        self.flavor_access_controller = (flavor_access_v21.
                                         FlavorAccessController())
        self.app = self._setup_app()
        self.expected = {
            "flavor": {
                "name": "test",
                "ram": 512,
                "vcpus": 2,
                "disk": 1,
                "OS-FLV-EXT-DATA:ephemeral": 1,
                "swap": 512,
                "rxtx_factor": 1
            }
        }

    def _setup_app(self):
        return fakes.wsgi_app_v21(init_only=('os-flavor-manage',
                                             'os-flavor-access',
                                             'os-flavor-rxtx', 'flavors',
                                             'os-flavor-extra-data'),
                                 fake_auth_context=self._get_http_request().
                                     environ['nova.context'])

    def _get_http_request(self, url=''):
        return fakes.HTTPRequest.blank(url)

    def _get_response(self):
        req = self._get_http_request(self.base_url)
        req.headers['Content-Type'] = 'application/json'
        req.method = 'POST'
        req.body = jsonutils.dumps(self.expected)
        res = req.get_response(self.app)
        return jsonutils.loads(res.body)

    def test_create_private_flavor_should_not_grant_flavor_access(self):
        self.expected["flavor"]["os-flavor-access:is_public"] = False
        body = self._get_response()
        for key in self.expected["flavor"]:
            self.assertEqual(body["flavor"][key], self.expected["flavor"][key])
        # Because for normal user can't access the non-public flavor without
        # access. So it need admin context at here.
        flavor_access_body = self.flavor_access_controller.index(
            fakes.HTTPRequest.blank('', use_admin_context=True),
            body["flavor"]["id"])
        expected_flavor_access_body = {
            "tenant_id": 'fake',
            "flavor_id": "%s" % body["flavor"]["id"]
        }
        self.assertNotIn(expected_flavor_access_body,
                         flavor_access_body["flavor_access"])

    def test_create_public_flavor_should_not_create_flavor_access(self):
        self.expected["flavor"]["os-flavor-access:is_public"] = True
        body = self._get_response()
        for key in self.expected["flavor"]:
            self.assertEqual(body["flavor"][key], self.expected["flavor"][key])

class FlavorManageTestV2(FlavorManageTestV21):
    controller = flavormanage_v2.FlavorManageController()
    validation_error = webob.exc.HTTPBadRequest

    def setUp(self):
        super(FlavorManageTestV2, self).setUp()
        self.flags(
            osapi_compute_extension=[
                'nova.api.openstack.compute.contrib.select_extensions'],
            osapi_compute_ext_list=['Flavormanage', 'Flavorextradata',
                'Flavor_access', 'Flavor_rxtx', 'Flavor_swap'])

    def _setup_app(self):
        return fakes.wsgi_app(init_only=('flavors',),
                              fake_auth_context=self._get_http_request().
                                  environ['nova.context'])

    def _get_http_request(self, url=''):
        return fakes.HTTPRequest.blank(url, use_admin_context=False)

    def test_create_with_name_leading_trailing_spaces(self):
        req = self._get_http_request(url=self.base_url)
        self.request_body['flavor']['name'] = '  test  '
        body = self._create_flavor_success_case(self.request_body, req)
        self.assertEqual('test', body['flavor']['name'])

    def test_create_with_name_leading_trailing_spaces_compat_mode(self):
        pass

class PrivateFlavorManageTestV2(PrivateFlavorManageTestV21):
    controller = flavormanage_v2.FlavorManageController()

    def setUp(self):
        super(PrivateFlavorManageTestV2, self).setUp()
        self.flags(
            osapi_compute_extension=[
                'nova.api.openstack.compute.contrib.select_extensions'],
            osapi_compute_ext_list=['Flavormanage', 'Flavorextradata',
                'Flavor_access', 'Flavor_rxtx', 'Flavor_swap'])
        self.flavor_access_controller = (flavor_access_v2.
                                         FlavorAccessController())

    def _setup_app(self):
        return fakes.wsgi_app(init_only=('flavors',),
                              fake_auth_context=self._get_http_request().
                                  environ['nova.context'])

    def _get_http_request(self, url=''):
        return fakes.HTTPRequest.blank(url, use_admin_context=False)

class FlavorManagerPolicyEnforcementV21(test.NoDBTestCase):

    def setUp(self):
        super(FlavorManagerPolicyEnforcementV21, self).setUp()
        self.controller = flavormanage_v21.FlavorManageController()

    def test_create_policy_failed(self):
        rule_name = "os_compute_api:os-flavor-manage"
        self.policy.set_rules({rule_name: "project:non_fake"})
        req = fakes.HTTPRequest.blank('')
        exc = self.assertRaises(
            exception.PolicyNotAuthorized,
            self.controller._create, req,
            body={"flavor": {
                "name": "test",
                "ram": 512,
                "vcpus": 2,
                "disk": 1,
                "swap": 512,
                "rxtx_factor": 1,
            }})
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())

    def test_delete_policy_failed(self):
        rule_name = "os_compute_api:os-flavor-manage"
        self.policy.set_rules({rule_name: "project:non_fake"})
        req = fakes.HTTPRequest.blank('')
        exc = self.assertRaises(
            exception.PolicyNotAuthorized,
            self.controller._delete, req,
            fakes.FAKE_UUID)
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())


text:
require 'test_helper'

class PerItemCalculatorTest < ActiveSupport::TestCase
  context "Calculator::PerItem" do
    [Coupon, ShippingMethod].each do |calculable|
      should "be available to #{calculable.to_s}" do
       assert calculable.calculators.include?(Calculator::PerItem)
      end
    end
    should "not be available to TaxRate" do
      assert !TaxRate.calculators.include?(Calculator::PerItem)
    end
  end
end


text:
/**
 *
 */
package edu.neu.ccs.nuir.tempsum;

/**
 * @author mattea
 *
 */
public class Token {
	public int id;
	public double score;
	public String text;
	public String pos;
	// TODO: Add relationships
	public Token(String text) {
		this.text = text;
	}
}


text:
package org.onosproject.yms.app.ych.defaultcodecs.xml;

import org.dom4j.Element;
import org.onosproject.yms.ydt.YdtContext;

import java.util.Stack;

/**
 * Represents a single instance leaf node handler in YCH.
 */
public class XmlCodecSingleInstanceLeafHandler extends XmlCodecHandler {

    @Override
    public void setXmlValue(YdtContext ydtContext,
                            Stack<Element> elementStack) {

        if (ydtContext.getValue() != null) {
            elementStack.peek().setText(ydtContext.getValue());
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Grayscale - Start Bootstrap Theme</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/grayscale.css" rel="stylesheet">

    <link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                      Start Bootstrap

                        A

                        Regex

                        Node annotations ideas

Grayscale

A free, responsive, one page Bootstrap theme.
Created by Start Bootstrap.

TODO: Блять, переписать это все. так влом

About Grayscale

Grayscale is a free Bootstrap 3 theme created by Start Bootstrap. It can be yours right now, simply download the template on the preview page. The theme is open source, and you can use it for any purpose, personal or commercial.

This theme features stock photos by Gratisography along with a custom Google Maps skin courtesy of Snazzy Maps.

Grayscale includes full HTML, CSS, and custom JavaScript files along with LESS files for easy customization.

My regex

Sciencist notation

^([0-9])?(\.[0-9]+)?(e[-+]?[0-9]+(\.[0-9]+)?)?$

Numbers

(\d)(?=(?:\d\d\d){2,}(?!\d))|(\d\d)(?=(?:\d\d\d)(?!\d))/$&,/g

replace 123123123 to 123,123,123, but not: 2034

Tests

4324534 ->

13245345443 ->

3132 ->

Ideas to node

@async
function ()
{
    var b = 45;
    var c = 23;

    var g <= mysql.query("sel * from bananas where b = ?", [b]);
    var d = await mysql.query("sel * from ss where c = ?", [c]);
    //alias

    return g.merge(d);
}

// will be:
function(cb)
{
    var b = 45;
    var c = 23;

    mysql.query("sel * from bananas where b = ?", [b], function(err, g)
    {
        if (err) cb(err)
        else
        {
         mysq.query("self * from ss where c = ?", [c], function(err, d)
         {
           if (err) cb(err)
           else
           {
             cb(null, g.merge(d);
           }
         });
        }
    });
}

@route('/user/:uid')
@get
function(uid)
{
    @send {a: uid}
}

@post
function(uid)
{
    @send {b: uid * 4}
}

app.get('/user', function(req, res)
{
    var uid = ...;
	res.send(JSON.strungify({a: uid}));
}

app.post('/user', function(req, res))
{
    var uid = ...;
	res.send(JSON.stringify({b: uid}));
}

Copyright © Your Website 2014


text:
#include "simpletools.h"                         // Include simpletools function defs

void set_states(int endPin, int startPin, int pattern)
{
  unsigned int andMask = -1;
  andMask <<= (31 - (endPin-startPin));
  andMask >>= (31 - endPin);
  andMask = ~andMask;
  int orMask = pattern << (startPin);
  OUTA = (OUTA & andMask) | orMask;

  int mask = OUTA << (31-endPin);
  mask = mask >> (31 - endPin + startPin);
  mask ^= pattern;
  mask <<= startPin;
  OUTA ^= mask;
}

/**
 * TERMS OF USE: MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */


text:
$machineNames = 'ServerA', 'ServerB'

configuration TestMaintenance
{
param
(
    [string[]]$ComputerName
)
    Import-DscResource -ModuleName xDscHelper
    Import-DscResource -ModuleName PSDesiredStateConfiguration

    node $ComputerName
    {
        # Default type once
        xMaintenanceWindow mw
        {
            ScheduleStart = (Get-Date).AddHours(-1)
            ScheduleEnd = (Get-Date).AddHours(2)
            ScheduleType = 'Once'
        }

        # Type daily, not in window --> Will error during configuraiton
        xMaintenanceWindow mw1
        {
            ScheduleStart = (Get-Date).AddHours(1).AddMinutes(1)
            ScheduleEnd = (Get-Date).AddHours(2).AddMinutes(1)
            ScheduleType = 'Daily'
        }

        # Type weekly, current day. In maintenance window, will create dependent file resource
        xMaintenanceWindow mw2
        {
            ScheduleStart = (Get-Date).AddHours(-1).AddMinutes(2)
            ScheduleEnd = (Get-Date).AddHours(2).AddMinutes(2)
            ScheduleType = 'Weekly'
            DayOfWeek = (Get-Date).DayOfWeek
        }

        # Type monthly, 2nd wednesday of the month. Will err any other day...
        xMaintenanceWindow mw3
        {
            ScheduleStart = (Get-Date).AddHours(-1).AddMinutes(3)
            ScheduleEnd = (Get-Date).AddHours(2).AddMinutes(3)
            ScheduleType = 'Monthly'
            DayOfWeek = 'Wednesday'
            DayOfMonth = 2
        }

        File test
        {
            DestinationPath = 'C:\IShouldBe.here0'
            Type =  'File'
            DependsOn = '[xMaintenanceWindow]mw'
            Contents = 'mw'
        }

        File test1
        {
            DestinationPath = 'C:\IShouldNotBe.here1'
            Type =  'File'
            DependsOn = '[xMaintenanceWindow]mw1'
            Contents = 'mw1'
        }

        File test2
        {
            DestinationPath = 'C:\IShouldBe.here2'
            Type =  'File'
            DependsOn = '[xMaintenanceWindow]mw2'
            Contents = 'mw2'
        }

        File test3
        {
            DestinationPath = 'C:\IShouldNotBe.here3'
            Type =  'File'
            DependsOn = '[xMaintenanceWindow]mw3'
            Contents = 'Unless it is the second wednesday of the month'
        }
    }
}

TestMaintenance -ComputerName $machineNames

Start-DscConfiguration -Verbose -Wait -Force -Path .\TestMaintenance


text:
package ar.com.quark.mathematic;

/**
 * Represent an immutable {@linkplain Vector3f}.
 */
public final class ImmutableVector3f extends Vector3f {
    public final static ImmutableVector3f ZERO = zero();

    /**
     *
Default constructor

     */
    public ImmutableVector3f(float x, float y, float z) {
        super(x, y, z);
    }

    /**
     *
Creates a new vector where each component value is 0.0f

     *
     * @return a new vector
     */
    public static ImmutableVector3f zero() {
        return new ImmutableVector3f(0.0f, 0.0f, 0.0f);
    }

    /**
     *
Creates a new vector where each component value is 1.0f

     *
     * @return a new vector
     */
    public static ImmutableVector3f one() {
        return new ImmutableVector3f(1.0f, 1.0f, 1.0f);
    }

    /**
     *
Creates a new vector of length one in the x-axis

     *
     * @return a new vector
     */
    public static ImmutableVector3f unitX() {
        return new ImmutableVector3f(1.0f, 0.0f, 0.0f);
    }

    /**
     *
Creates a new vector of length one in the y-axis

     *
     * @return a new vector
     */
    public static ImmutableVector3f unitY() {
        return new ImmutableVector3f(0.0f, 1.0f, 0.0f);
    }

    /**
     *
Creates a new vector of length one in the z-axis

     *
     * @return a new vector
     */
    public static ImmutableVector3f unitZ() {
        return new ImmutableVector3f(0.0f, 0.0f, 1.0f);
    }

    /**
     *
Creates a new vector of length minus one in the z-axis

     *
     * @return a new vector
     */
    public static ImmutableVector3f unitNegativeZ() {
        return new ImmutableVector3f(0.0f, 0.0f, -1.0f);
    }

    /**
     *
Creates a new vector where each component value is {@link Float#NaN}

     *
     * @return a new vector
     */
    public static ImmutableVector3f nan() {
        return new ImmutableVector3f(Float.NaN, Float.NaN, Float.NaN);
    }

    /**
     *
Creates a new vector where each component value is {@link Float#POSITIVE_INFINITY}

     *
     * @return a new vector
     */
    public static ImmutableVector3f positiveInfinity() {
        return new ImmutableVector3f(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY);
    }

    /**
     *
Creates a new vector where each component value is {@link Float#NEGATIVE_INFINITY}

     *
     * @return a new vector
     */
    public static ImmutableVector3f negativeInfinity() {
        return new ImmutableVector3f(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY);
    }
}


text:
<?php namespace Brick;

class Implementation extends \Eve\Implement {

    /**
     * Handle dynamic static method calls.
     *
     * @param string $method
     * @param array $arguments
     * @return mixed
     */
    public static function __callStatic($method, array $arguments)
    {
        $method = \str_replace('for', 'an', $method);

        return \call_user_func_array([new static, $method], $arguments);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the soi-toolkit project under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The soi-toolkit project licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans"
	xmlns:jms="http://www.mulesoft.org/schema/mule/jms"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-current.xsd
		http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
		http://www.mulesoft.org/schema/mule/jms  http://www.mulesoft.org/schema/mule/jms/current/mule-jms.xsd">

	<spring:beans>
		<spring:import resource="classpath:soitoolkit-mule-jms-connector-commons.xml" />
	</spring:beans>

    <!--
    Sample configuration settings in the property-file:

    SOITOOLKIT_MULE_HORNETQ_HOST=localhost
    SOITOOLKIT_MULE_HORNETQ_PORT=5445

#    SOITOOLKIT_MULE_HORNETQ_CONNECTION_TTL=1000

    Sample queue-definition in ${HORNETQ_HOME}/config/stand-alone/non-clustered/hornetq-jms.xml:

   <queue name="SOITOOLKIT.LOG.INFO">
      <entry name="SOITOOLKIT.LOG.INFO"/>
   </queue>

   <queue name="SOITOOLKIT.LOG.ERROR">
      <entry name="SOITOOLKIT.LOG.ERROR"/>
   </queue>

   <queue name="MY.QUEUE">
      <entry name="MY.QUEUE"/>
   </queue>
    -->

    <spring:bean name="soitoolkit-jms-connection-factory" class="org.hornetq.jms.client.HornetQJMSConnectionFactory">
        <spring:constructor-arg type="boolean" value="false"/>
        <spring:constructor-arg>
            <spring:bean name="transportConfiguration" class="org.hornetq.api.core.TransportConfiguration">
                <spring:constructor-arg value="org.hornetq.core.remoting.impl.netty.NettyConnectorFactory"/>
                <spring:constructor-arg>
                    <spring:map key-type="java.lang.String" value-type="java.lang.Object">
                        <spring:entry key="host" value="${SOITOOLKIT_MULE_HORNETQ_HOST}"/>
                        <spring:entry key="port" value="${SOITOOLKIT_MULE_HORNETQ_PORT}"/>
                    </spring:map>
                </spring:constructor-arg>
            </spring:bean>
        </spring:constructor-arg>
<!--
        <spring:property name="ConnectionTTL" value="${SOITOOLKIT_MULE_HORNETQ_CONNECTION_TTL}"/>
 -->
    </spring:bean>

    <jms:connector
        name="soitoolkit-jms-connector"
        username="guest"
        password="guest"
        specification="1.1"
        connectionFactory-ref="soitoolkit-jms-connection-factory"
        maxRedelivery="-1"
    />

</mule>


text:
- Fix plugin registration in `dart_plugin_registrant.dart`

## 0.1.1

- Fixes repository URL of the package.

## 0.1.0

- Adds an initial implementation of Windows support for the geolocator plugin.


text:
import * as Koa from 'koa'
import env from '../env'
import apiDelegate from '../apiDelegate'

const delegate: apiDelegate = new apiDelegate()

const { owner, repo } = delegate
const { HOST, PORT } = env

export default async (
  ctx: Koa.Context,
  next: () => Promise<any>
): Promise<any> => {
  ctx.state = {
    ...ctx.state,
    host: `//${HOST}:${PORT}`,
    owner,
    repo
  }
  return await next()
}


text:
<?php

namespace Hydrogen\Http\Request\Client;

class CurlMulti
{
	private $_curl = null;
	private $_attachedHandle = array();

	public function __construct()
	{
		$this->_curl = curl_multi_init();
	}

	public function addHandle()
	{
		$curlHandles = func_get_args();
		foreach ($curlHandles as $curlHandle) {
            if (0 === curl_multi_add_handle($this->_curl, $curlHandle)) {
                $this->_attachedHandle[] = $curlHandle;
            }
        }
	}

	public function exec()
	{
		$running = null;
		do {
			curl_multi_exec($this->_curl, $running);
		} while(0 < $running);
	}

	public function getContent()
	{
		return curl_multi_getcontent($this->_curl);
	}

	public function infoRead($msgs_in_queue = null)
	{
		return curl_multi_info_read($this->_curl, $msgs_in_queue);
	}

	public function close()
	{
		foreach ($this->_attachedHandle as $ch) {
			curl_multi_remove_handle($this->_curl, $ch);
		}
		curl_multi_close($this->_curl);
	}

	public function __destruct()
	{
		$this->close();
	}
}


text:
<?php namespace Core;

use Core\View;

/**
 * Description of Controller
 *
 * @author Angel De La Cruz
 */

Abstract class Controller {

    abstract public function index();

    public $view;

    public function __construct() {
        $this->view = new View();

    }

    /**
     * URL
     * @return string
     */
    public function URL_SELF(){

        $http = $_SERVER['REQUEST_SCHEME'];
        $url = $_SERVER['PHP_SELF'];
        $addr = $_SERVER['SERVER_ADDR'];
        $url = str_replace('index.php','',$url);

        return $http.'://'.$addr.$url;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Lichenology in Latin America. History, Current Knowledge and Applications (São Paulo), [Proceedings of GLAL-3, Terceiro Encontro do Grupo Latino-Americano de Liquenólogos, São Paulo, Brazil, 24-28 September, 1997] 136 (1998)

#### Original name
Peltigera membranacea f. fibrilloides Gyeln.

### Remarks
null


text:
<!doctype html>

<title>IAT Experimenter Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link type="text/css" href="core/css/overcast/jquery-ui-1.8.18.custom.css" rel="stylesheet" />
<link type="text/css" href="core/css/experimenter.css" rel="stylesheet" />

Active:

None

Templates

				[New Template]

			<input type="button" id="set-active" name="set-active" value="Set Active">


text:
import { act, fireEvent } from "@testing-library/react-native"
import { RequestForPriceEstimateBannerTestsQuery } from "__generated__/RequestForPriceEstimateBannerTestsQuery.graphql"
import { __globalStoreTestUtils__, GlobalStoreProvider } from "app/store/GlobalStore"
import { mockTrackEvent } from "app/tests/globallyMockedStuff"
import { renderWithWrappers } from "app/tests/renderWithWrappers"
import { graphql, QueryRenderer } from "react-relay"
import { createMockEnvironment, MockPayloadGenerator } from "relay-test-utils"
import { RequestForPriceEstimateBanner } from "./RequestForPriceEstimateBanner"

jest.unmock("react-relay")

describe("RequestForPriceEstimateBanner", () => {
  let mockEnvironment: ReturnType<typeof createMockEnvironment>
  const TestRenderer = () => (
    <QueryRenderer<RequestForPriceEstimateBannerTestsQuery>
      environment={mockEnvironment}
      query={graphql`
        query RequestForPriceEstimateBannerTestsQuery @relay_test_operation {
          artwork(id: "foo") {
            ...RequestForPriceEstimateBanner_artwork
          }
          marketPriceInsights(artistId: "some-artist-id", medium: "painting") {
            ...RequestForPriceEstimateBanner_marketPriceInsights
          }
          me {
            ...RequestForPriceEstimateBanner_me
          }
        }
      `}
      variables={{}}
      render={({ props }) => {
        if (props?.artwork && props?.marketPriceInsights && props?.me) {
          return (
            <GlobalStoreProvider>
              <RequestForPriceEstimateBanner
                me={props.me}
                artwork={props.artwork}
                marketPriceInsights={props.marketPriceInsights}
              />
            </GlobalStoreProvider>
          )
        }
        return null
      }}
    />
  )

  beforeEach(() => {
    mockEnvironment = createMockEnvironment()
    __globalStoreTestUtils__?.injectFeatureFlags({ AREnableNewRequestPriceEstimateLogic: true })
  })

  afterEach(() => {
    jest.clearAllMocks()
    __globalStoreTestUtils__?.reset()
  })

  const resolveData = (passedProps = {}) => {
    mockEnvironment.mock.resolveMostRecentOperation((operation) =>
      MockPayloadGenerator.generate(operation, passedProps)
    )
  }

  it("renders without throwing an error", () => {
    const { getByTestId } = renderWithWrappers(<TestRenderer />)
    resolveData({
      Artwork: () => ({
        internalID: "some-internal-id",
        submissionId: null,
        hasPriceEstimateRequest: false,
        artist: {
          targetSupply: {
            isP1: true,
          },
        },
      }),
      MarketPriceInsights: () => ({
        demandRank: 7.5,
      }),
    })
    expect(getByTestId("request-price-estimate-button")).toBeDefined()
    expect(getByTestId("request-price-estimate-banner-title")).toBeDefined()
    expect(getByTestId("request-price-estimate-banner-description")).toBeDefined()
  })

  it("renders 'requested' state if in global store without throwing an error", () => {
    const { getByText } = renderWithWrappers(<TestRenderer />)
    resolveData({
      Artwork: () => ({
        internalID: "artwork-id",
        slug: "artwork-id",
        hasPriceEstimateRequest: null,
      }),
      MarketPriceInsights: () => ({
        demandRank: 7.5,
      }),
    })
    __globalStoreTestUtils__?.injectState({
      requestedPriceEstimates: {
        requestedPriceEstimates: {
          "artwork-id": {
            artworkId: "artwork-id",
            requestedAt: 1666015648950,
          },
        },
      },
    })
    expect(getByText("Price Estimate Request Sent")).toBeDefined()
  })

  it("renders 'requested' state if hasPriceEstimateRequest is true", () => {
    const { getByText } = renderWithWrappers(<TestRenderer />)
    resolveData({
      Artwork: () => ({
        internalID: "artwork-id",
        slug: "artwork-id",
        hasPriceEstimateRequest: true,
      }),
      MarketPriceInsights: () => ({
        demandRank: 7.5,
      }),
    })
    expect(getByText("Price Estimate Request Sent")).toBeDefined()
  })

  it("tracks analytics event when RequestForEstimate button is tapped", () => {
    const { getByTestId } = renderWithWrappers(<TestRenderer />)
    resolveData({
      Artwork: () => ({
        internalID: "artwork-id",
        slug: "artwork-slug",
        submissionId: null,
        hasPriceEstimateRequest: false,
        artist: {
          targetSupply: {
            isP1: true,
          },
        },
      }),
      MarketPriceInsights: () => ({
        demandRank: 7.5,
      }),
    })

    const TheButton = getByTestId("request-price-estimate-button")

    act(() => {
      fireEvent.press(TheButton)
    })

    expect(mockTrackEvent).toHaveBeenCalledTimes(1)
    expect(mockTrackEvent).toHaveBeenCalledWith({
      action: "tappedRequestPriceEstimate",
      context_module: "myCollectionArtworkInsights",
      context_screen: "MyCollectionArtworkInsights",
      context_screen_owner_type: "myCollectionArtwork",
      context_screen_owner_id: "artwork-id",
      context_screen_owner_slug: "artwork-slug",
      demand_index: 7.5,
    })
  })
})


text:
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { routeActions } from 'react-router-redux';
import classNames from 'classnames';

const requireAuthentication = (ComposedComponent) => {
  const mapStateToProps = (state) => ({
    isAuthenticated: state.auth.isAuthenticated,
  });

  class AuthenticatedComponent extends Component {
    static propTypes = {
      dispatch: PropTypes.func.isRequired,
      isAuthenticated: PropTypes.bool.isRequired,
    };

    componentWillMount() {
      this.checkAuth(this.props);
    }

    componentWillReceiveProps(props) {
      this.checkAuth(props);
    }

    checkAuth(props) {
      if (!props.isAuthenticated) {
        this.redirectToLogin();
      }
    }

    redirectToLogin() {
      // this would dispatch a notification then a route change.
      this.props.dispatch(routeActions.replace({ pathname: '/' }));
    }

    render() {
      const { isAuthenticated } = this.props;
      const wrapperClass = classNames({
        'is-authenticated': isAuthenticated,
        'requires-authentication': !isAuthenticated,
      });

      return (
        <div className={wrapperClass}>
          { isAuthenticated ? <ComposedComponent {...this.props} /> : null }
        </div>
      );
    }
  }

  return connect(mapStateToProps)(AuthenticatedComponent);
};

export {
  requireAuthentication,
};


text:
<title>TestNG:  ServerLatestJobCompletedTest</title>
<link href="../testng.css" rel="stylesheet" type="text/css" />
<link href="../my-testng.css" rel="stylesheet" type="text/css" />

ServerLatestJobCompletedTest

Tests passed/Failed/Skipped:	1/0/0

Started on:	Tue Jan 12 01:12:08 CST 2016

Total time:	0 seconds (16 ms)

Included groups:

Excluded groups:

(Hover the method name to see the test class name)

PASSED TESTS

Test method
Exception
Time (seconds)
Instance

testPredicate
Test class: org.jclouds.gogrid.predicates.ServerLatestJobCompletedTest

0
org.jclouds.gogrid.predicates.ServerLatestJobCompletedTest@c86119


text:
package com.consol.citrus.ws.actions;

import com.consol.citrus.actions.ReceiveMessageAction;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.exceptions.CitrusRuntimeException;
import com.consol.citrus.message.Message;
import com.consol.citrus.ws.message.SoapAttachment;
import com.consol.citrus.ws.message.SoapMessage;
import com.consol.citrus.ws.validation.SimpleSoapAttachmentValidator;
import com.consol.citrus.ws.validation.SoapAttachmentValidator;

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

/**
 * Message receiver for SOAP messaging.
 *
 * This special implementation offers SOAP attachment validation in addition to
 * the normal message receiver.
 *
 * @author Christoph Deppisch
 */
public class ReceiveSoapMessageAction extends ReceiveMessageAction {
    /** Control attachment */
    private List<SoapAttachment> attachments = new ArrayList<SoapAttachment>();

    /** SOAP attachment validator */
    private SoapAttachmentValidator attachmentValidator = new SimpleSoapAttachmentValidator();

    /**
     * Default constructor.
     */
    public ReceiveSoapMessageAction() {
        setName("receive");
    }

    @Override
    protected void validateMessage(Message receivedMessage, TestContext context) {
        try {
            super.validateMessage(receivedMessage, context);

            if (!attachments.isEmpty() && !(receivedMessage instanceof SoapMessage)) {
                throw new CitrusRuntimeException(String.format("Unable to perform SOAP attachment validation on message type '%s'", receivedMessage.getClass()));
            }

            for (SoapAttachment attachment : attachments) {
                attachment.setTestContext(context);
            }

            if (!attachments.isEmpty()) {
                attachmentValidator.validateAttachment((SoapMessage) receivedMessage, attachments);
            }

        } catch (IOException e) {
            throw new CitrusRuntimeException(e);
        }
    }

    /**
     * Gets the control attachments.
     * @return the control attachments
     */
    public List<SoapAttachment> getAttachments() {
        return attachments;
    }

    /**
     * Sets the control attachments.
     * @param attachments the control attachments
     */
    public ReceiveSoapMessageAction setAttachments(List<SoapAttachment> attachments) {
        this.attachments = attachments;
        return this;
    }

    /**
     * Set the attachment validator.
     * @param attachmentValidator the attachmentValidator to set
     */
    public ReceiveSoapMessageAction setAttachmentValidator(SoapAttachmentValidator attachmentValidator) {
        this.attachmentValidator = attachmentValidator;
        return this;
    }

    /**
     * Gets the attachmentValidator.
     * @return the attachmentValidator
     */
    public SoapAttachmentValidator getAttachmentValidator() {
        return attachmentValidator;
    }
}


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Las animaciones deben funcionar correctamente; de lo contrario, tendrán un impacto negativo en la experiencia del usuario.

{# wf_updated_on: 2016-08-23 #}
{# wf_published_on: 2014-08-08 #}

# Animaciones y rendimiento {: .page-title }

{% include "web/_shared/contributors/paullewis.html" %}
{% include "web/_shared/contributors/samthorogood.html" %}

Cada vez que se hace una animación, se deben mantener 60 fps, ya que un número menor daría como resultado parpadeos o bloqueos que los usuarios podrían notar, y esto tendría un impacto negativo en sus experiencias.

### TL;DR {: .hide-from-toc }
* Debes procurar que tus animaciones no causen problemas de rendimiento. Asegúrate de conocer el impacto que tiene animar una determinada propiedad de CSS.
* La animación de propiedades que modifican las características geométricas de la página (diseño) o generan efectos de pintura implican un consumo de recursos particularmente alto.
* Siempre que puedas, limítate a realizar cambios en las transformaciones y opacidad.
* Usa will-change para asegurarte de que el navegador reconozca lo que deseas animar.

La animación de propiedades tiene consecuencias, y para algunas propiedades supone un menor consumo de recursos que para otras. Por ejemplo, si se animan las propiedades `width` y `height` de un elemento, se modifica su geometría y esto podría hacer que otros elementos de la página se desplacen o cambien de tamaño. Este proceso se denomina *diseño* (o *reprocesamiento* en los navegadores basados en Gecko, como Firefox) y puede consumir muchos recursos si tu página contiene muchos elementos. Cada vez que se genere un diseño, normalmente se deberá pintar la página o parte de ella, lo cual suele requerir aún más recursos que la operación de diseño.

Siempre que sea posible, debes evitar animar propiedades que activen diseño o pintura. En el caso de los navegadores más modernos, esto significa limitar las animaciones a `opacity` o `transform`, ya que el navegador puede optimizar ambas propiedades en gran medida, independientemente de que la animación se administre con JavaScript o CSS.

Para encontrar una lista completa de los trabajos generados mediante propiedades individuales de CSS, consulta [Desencadenadores CSS](http://csstriggers.com). Puedes encontrar una guía completa sobre cómo crear [Animaciones de alto rendimiento en HTML5 Rocks](http://www.html5rocks.com/en/tutorials/speed/high-performance-animations/).

### Uso de la propiedad will-change

Usa [`will-change`](https://dev.w3.org/csswg/css-will-change/) para asegurarte de que el navegador reconozca que deseas modificar la propiedad de un elemento. De este modo, el navegador puede aplicar las optimizaciones más adecuadas antes de que realices el cambio. Sin embargo, no uses `will-change` demasiado porque puede causar que el navegador desperdicie recursos, y esto también causa más problemas de rendimiento.

La regla de oro es que, si la animación podría desencadenarse en los próximos 200 ms, ya sea mediante la interacción de un usuario o debido al estado de tu app, se recomienda aplicar la propiedad `will-change` en los elementos animados. En la mayoría de los casos, entonces, cualquier elemento de la vista actual de tu aplicación que desees animar debe tener la propiedad `will-change` habilitada para las propiedades que vayas a modificar. En el caso del ejemplo del cuadro que usamos en las guías anteriores, la adición de `will-change` para los atributos transforms y opacity se vería de la siguiente manera:

    .box {
      will-change: transform, opacity;
    }

Ahora los navegadores compatibles con esto, [actualmente Chrome, Firefox y Opera](http://caniuse.com/#feat=will-change), realizarán las optimizaciones adecuadas de manera subyacente para admitir los cambios o las animaciones en dichas propiedades.

## Rendimiento de CSS en comparación con JavaScript

Existe una gran cantidad de páginas y comentarios en la web en los cuales se tratan las ventajas relativas de las animaciones de CSS y JavaScript desde la perspectiva del rendimiento. A continuación se muestran algunos puntos que debes tener en cuenta:

* Las animaciones basadas en CSS, y las animaciones web cuando exista compatibilidad nativa, generalmente se manejan con un subproceso conocido como "subproceso compositor". Es diferente al "subproceso principal" del navegador, donde se ejecutan el estilo, el diseño, la pintura y JavaScript. Esto significa que, si el navegador tiene en ejecución algunas tareas con alta demanda de recursos en el subproceso principal, es muy probable que las animaciones se sigan ejecutando sin interrupciones.

* En muchos casos, el subproceso compositor también puede administrar otras modificaciones de las propiedades transforms y opacity.

* Si alguna animación activa elementos de pintura, diseño o de ambas clases, el "subproceso principal" deberá hacer el trabajo. Esto se aplica a las animaciones basadas en CSS y JavaScript, y es probable que la sobrecarga de diseño o pintura reduzca la cantidad de trabajo asociado con la ejecución de CSS o JavaScript, por lo cual el asunto sería irrelevante.

Para obtener más información sobre qué trabajo se desencadena al animar una propiedad determinada, consulta [Desencadenadores de CSS](http://csstriggers.com).

{# wf_devsite_translation #}


text:
package com.hazelcast.replicatedmap.impl.client;

import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.nio.serialization.Portable;
import com.hazelcast.nio.serialization.PortableReader;
import com.hazelcast.nio.serialization.PortableWriter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * Class implementing a replicated map value collection result
 */
public class ReplicatedMapValueCollection implements Portable {

    private Collection<Data> values;

    ReplicatedMapValueCollection() {
    }

    public ReplicatedMapValueCollection(Collection<Data> values) {
        this.values = values;
    }

    public Collection<Data> getValues() {
        return values;
    }

    @Override
    public void writePortable(PortableWriter writer) throws IOException {
        writer.writeInt("size", values.size());
        ObjectDataOutput out = writer.getRawDataOutput();
        for (Data value : values) {
            out.writeData(value);
        }
    }

    @Override
    public void readPortable(PortableReader reader) throws IOException {
        int size = reader.readInt("size");
        ObjectDataInput in = reader.getRawDataInput();
        values = new ArrayList<Data>(size);
        for (int i = 0; i < size; i++) {
            values.add(in.readData());
        }
    }

    @Override
    public int getFactoryId() {
        return ReplicatedMapPortableHook.F_ID;
    }

    @Override
    public int getClassId() {
        return ReplicatedMapPortableHook.VALUES_COLLECTION;
    }
}


text:
require 'spec_helper'
require 'slack_bot_server/local_queue'

RSpec.describe SlackBotServer::LocalQueue do
  it "returns nil when empty and pop is called" do
    expect(subject.pop).to be_nil
  end

  it "can have objects pushed on it" do
    subject.push('hello')
    expect(subject.pop).to eq 'hello'
  end

  it 'returns the first object pushed' do
    subject.push('well')
    subject.push('hello')
    expect(subject.pop).to eq 'well'
    expect(subject.pop).to eq 'hello'
  end
end


text:
package com.moscase.shouhuan.fragment;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.moscase.shouhuan.R;
import com.moscase.shouhuan.bean.HeartTimes;
import com.moscase.shouhuan.view.DigitalGroupView;
import com.moscase.shouhuan.view.DividerItemDecoration;
import com.moscase.shouhuan.view.HeartbeatView;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by 陈航 on 2017/7/20.
 *
 * 我挥舞着键盘和本子,发誓要把世界写个明明白白
 */
@SuppressLint("ValidFragment")
public class XinlvFragment extends Fragment {
    private HeartbeatView mHeartbeatView;
    private RecyclerView mHeartbeatRecycler;
    private List<HeartbeatEntity> mData = new ArrayList<>();
    private Adapter mAdapter;
    private DigitalGroupView mDigiResult;
    private TextView mTextUnit;
    private Calendar mC;
    private List<HeartTimes> mHeartTimesList = new ArrayList<>();
    private int HeartTimeId = 0;
    private Context mContext;

    @SuppressLint("ValidFragment")
    public XinlvFragment(Context context) {
        mContext = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_xinlv, container, false);

        initView(view);

        initDatas();

        return view;
    }

    private void initView(View view) {
        SQLiteDatabase db = Connector.getDatabase();
        mC = Calendar.getInstance();
        mHeartbeatView = (HeartbeatView) view.findViewById(R.id.heartbeat);
        mDigiResult = (DigitalGroupView) view.findViewById(R.id.digi_heartbeat_result);
        mTextUnit = (TextView) view.findViewById(R.id.text_unit);
        mHeartbeatRecycler = (RecyclerView) view.findViewById(R.id.recycler_heartbeat);
    }

    private void initDatas() {

        mHeartbeatView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHeartbeatView.startAnim();
                hideResult();
            }
        });

        mHeartbeatView.setHeartBeatAnimListener(new HeartbeatView.HeartBeatAnimImpl() {
            @Override
            public void onAnimFinished() {
                if (mHeartbeatView.isAutoEnd()){
                    showResult();
                    Log.d("koma","到了这一步");
                }else {
                    int randomNum = (int) (50 + Math.random() * 50);
                    HeartbeatEntity e = new HeartbeatEntity();
                    SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String date = sDateFormat.format(new java.util.Date());
                    e.date = date;
                    e.datum = String.valueOf(randomNum);
                    HeartTimes mHeartTimes = new HeartTimes();
                    mHeartTimes.setTime(e.date);
                    mHeartTimes.setTimes(e.datum);
                    mHeartTimes.setDate(new Date());
                    mHeartTimes.setId(HeartTimeId);
                    HeartTimeId += 1;
                    mHeartTimes.save();
                    mHeartTimesList.add(0, mHeartTimes);

                    mAdapter.notifyItemInserted(0);
                    mHeartbeatRecycler.scrollToPosition(0);
                    showResult();
                    mDigiResult.setDigits(randomNum);
                }
            }
        });

        List<HeartTimes> heartTimes = DataSupport.where("times > ?", "0").order("mDate desc")
                .find(HeartTimes.class);
        for (HeartTimes heartTime : heartTimes) {
            HeartTimes e = new HeartTimes();
            e.setTime(heartTime.getTime());
            e.setTimes(heartTime.getTimes());
            e.setId(heartTime.getId());
            mHeartTimesList.add(e);
        }

        //这里使用了自定义的WrapContentLinearLayoutManager是因为我用的第三方的adapter,在设置emptyview的时候在底层
        //直接就报错了
        mHeartbeatRecycler.setLayoutManager(new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mHeartbeatRecycler.addItemDecoration(new DividerItemDecoration(mContext,
                LinearLayoutManager.VERTICAL));
        mHeartbeatRecycler.setItemAnimator(new DefaultItemAnimator());
        mAdapter = new Adapter(R.layout.item_heartbeat, mHeartTimesList);
        mAdapter.setEmptyView(R.layout.empty_view, (ViewGroup) mHeartbeatRecycler.getParent());
        mHeartbeatRecycler.setAdapter(mAdapter);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        mAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, final int
                    position) {
                new AlertDialog.Builder(mContext).setMessage("是否删除此数据").setPositiveButton("是",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                DataSupport.delete(HeartTimes.class, DataSupport.find(HeartTimes.class,
                                        mHeartTimesList.get(position).getId()).getId());
                                mHeartTimesList.remove(position);
                                mAdapter.notifyDataSetChanged();
                                mDigiResult.setDigits(0);
                            }
                        }).setNegativeButton("否", null).show();
                return true;
            }
        });

    }

    private void hideResult() {
        AlphaAnimation mHiddenAction = new AlphaAnimation(1f, 0f);
        mHiddenAction.setDuration(400);

        mTextUnit.setAnimation(mHiddenAction);
        mDigiResult.setAnimation(mHiddenAction);

        mTextUnit.setVisibility(View.GONE);
        mDigiResult.setVisibility(View.GONE);
    }

    private void showResult() {
        AlphaAnimation mHiddenAction = new AlphaAnimation(1f, 0f);
        mHiddenAction.setDuration(400);

        mTextUnit.setAnimation(mHiddenAction);
        mDigiResult.setAnimation(mHiddenAction);

        mTextUnit.setVisibility(View.VISIBLE);
        mDigiResult.setVisibility(View.VISIBLE);
    }

    class HeartbeatEntity {
        String date;
        String datum;
    }

//    private void setGuideView() {
//        ImageView iv = new ImageView(mContext);
//        iv.setImageResource(R.drawable.img_new_task_guide1);
////        TextView textView = new TextView(mContext);
////        textView.setText("点击开始测量心跳");
//
//        guideView = GuideView.Builder
//                .newInstance(mContext)
//                .setTargetView(mDigiResult)//设置目标
//                .setCustomGuideView(iv)
//                .setDirction(GuideView.Direction.LEFT_BOTTOM)
//                .setShape(GuideView.MyShape.CIRCULAR)   // 设置圆形显示区域,
//                .setBgColor(getResources().getColor(R.color.shadow))
//                .setOnclickListener(new GuideView.OnClickCallback() {
//                    @Override
//                    public void onClickedGuideView() {
//                        guideView.hide();
//                    }
//                }).build();
//        guideView.show();
//    }

    @Override
    public void onResume() {
        super.onResume();
//        setGuideView();
    }

    public class Adapter extends BaseQuickAdapter<HeartTimes, BaseViewHolder> {

        @Override
        protected void startAnim(Animator anim, int index) {
            super.startAnim(anim, index);
            if (index < mHeartTimesList.size())
                anim.setStartDelay(index * 150);
        }

        public Adapter(@LayoutRes int layoutResId, @Nullable List<HeartTimes> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, HeartTimes item) {
            helper.setText(R.id.date, item.getTime())
                    .setText(R.id.datum, item.getTimes());
        }
    }

    public class WrapContentLinearLayoutManager extends LinearLayoutManager {
        public WrapContentLinearLayoutManager(Context context) {
            super(context);
        }

        public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }

        public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (hidden){
            mHeartbeatView.stopAnim();
        }
    }

}


text:
Really fast audio in iOS and Mac OS X using Audio Units is hard, and will leave you scarred and bloody. What used to take days can now be done with just a few lines of code.

### Getting Audio
``` objective-c
Novocaine *audioManager = [Novocaine audioManager];
[audioManager setInputBlock:^(float *newAudio, UInt32 numSamples, UInt32 numChannels) {
	// Now you're getting audio from the microphone every 20 milliseconds or so. How's that for easy?
	// Audio comes in interleaved, so,
	// if numChannels = 2, newAudio[0] is channel 1, newAudio[1] is channel 2, newAudio[2] is channel 1, etc.
}];
[audioManager play];
```

### Playing Audio
``` objective-c
Novocaine *audioManager = [Novocaine audioManager];
[audioManager setOutputBlock:^(float *audioToPlay, UInt32 numSamples, UInt32 numChannels) {
	// All you have to do is put your audio into "audioToPlay".
}];
[audioManager play];
```

### Does anybody actually use it?
Yep. Novocaine is result of three years of work on the audio engine of [Octave](https://itunes.apple.com/us/app/octave-an-rta-for-the-iphone/id386083594?mt=8), [Fourier](https://itunes.apple.com/us/app/fourier/id386084557?mt=8) and [oScope](https://itunes.apple.com/us/app/oscope/id344345859?mt=8), a powerful suite of audio analysis apps. Please do check them out!

### A thing to note:
The RingBuffer class is written in C++ to make things extra zippy, so the classes that use it will have to be Objective-C++. Change all the files that use RingBuffer from MyClass.m to MyClass.mm.

### Want some examples?
Inside of ViewController.mm are a bunch of tiny little examples I wrote. Uncomment one and see how it sounds.
Do note, however, for examples involving play-through, that you should be using headphones. Having the
mic and speaker close to each other will produce some gnarly feedback.

### Want to learn the nitty-gritty of Core Audio?
If you want to get down and dirty, if you want to get brave and get close to the hardware, I can only point you to the places where I learned how to do this stuff. Chris Adamson and Michael Tyson are two giants in the field of iOS audio, and they each wrote indispensable blog posts ([this is Chris's](http://www.subfurther.com/blog/2009/04/28/an-iphone-core-audio-brain-dump/), [this is Michael's](http://atastypixel.com/blog/using-remoteio-audio-unit/)). Also, Chris Adamson now has a [whole gosh-darned BOOK on Core Audio](http://www.amazon.com/gp/product/0321636848/ref=as_li_ss_tl?ie=UTF8&tag=tico07-20&linkCode=as2&camp=1789&creative=390957&creativeASIN=0321636848
). I would have done unspeakable things to get my hands on this when I was first starting.

[![Analytics](https://ga-beacon.appspot.com/UA-17672588-2/novocaine/readme)](https://github.com/igrigorik/ga-beacon)


text:
'use strict';

const models = require('./index');

/**
 * Information about the event hub destination for an event subscription
 *
 * @extends models['EventSubscriptionDestination']
 */
class EventHubEventSubscriptionDestination extends models['EventSubscriptionDestination'] {
  /**
   * Create a EventHubEventSubscriptionDestination.
   * @property {string} [resourceId] The Azure Resource Id that represents the
   * endpoint of an Event Hub destination of an event subscription.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of EventHubEventSubscriptionDestination
   *
   * @returns {object} metadata of EventHubEventSubscriptionDestination
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'EventHub',
      type: {
        name: 'Composite',
        polymorphicDiscriminator: {
          serializedName: 'endpointType',
          clientName: 'endpointType'
        },
        uberParent: 'EventSubscriptionDestination',
        className: 'EventHubEventSubscriptionDestination',
        modelProperties: {
          endpointType: {
            required: true,
            serializedName: 'endpointType',
            isPolymorphicDiscriminator: true,
            type: {
              name: 'String'
            }
          },
          resourceId: {
            required: false,
            serializedName: 'properties.resourceId',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = EventHubEventSubscriptionDestination;


text:
@implementation BMWeakTimerTarget
{
    __weak id _target;
    SEL _selector;
}

- (instancetype) initWithTarget: (id) target andSelector: (SEL) selector
{
    self = [super init];
    if (self) {
        _target = target;
        _selector = selector;
    }
    return self;
}

- (void) dealloc
{
}

- (void)timerDidFire:(NSTimer *)timer
{
    if(_target)
    {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [_target performSelector:_selector withObject:timer];
#pragma clang diagnostic pop
    }
    else
    {
        [timer invalidate];
    }
}

@end


text:
package com.fanfou.app.opensource.update;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;

import com.fanfou.app.opensource.AppContext;

/**
 * @author mcxiaoke
 * @version 1.0 2011.09.04
 * @version 2.0 2011.10.31
 *
 */
public final class AppVersionInfo implements Parcelable {

    public static final String TYPE_BUGFIX = "bugfix";
    public static final String TYPE_MINOR = "minor";
    public static final String TYPE_MAJOR = "major";

    public int versionCode;// 版本号
    public String versionName;// 版本显示
    public String releaseDate;// 发布日期
    public String changelog;// 升级日志
    public String downloadUrl;// 下载地址
    public String versionType;// 升级类型:BUG修复,功能改进,重大更新
    public String packageName;// 安装包文件名
    public static final Parcelable.Creator<AppVersionInfo> CREATOR = new Parcelable.Creator<AppVersionInfo>() {

        @Override
        public AppVersionInfo createFromParcel(final Parcel source) {
            final Bundle bundle = source.readBundle();
            return AppVersionInfo.parseBundle(bundle);
        }

        @Override
        public AppVersionInfo[] newArray(final int size) {
            return new AppVersionInfo[size];
        }

    };

    public static AppVersionInfo parse(final String response) {
        try {
            final JSONObject o = new JSONObject(response);
            final AppVersionInfo info = new AppVersionInfo();
            info.versionCode = o.getInt("versionCode");
            info.versionName = o.getString("versionName");
            info.releaseDate = o.getString("releaseDate");
            info.changelog = o.getString("changelog");
            info.downloadUrl = o.getString("downloadUrl");
            info.versionType = o.getString("versionType");
            info.packageName = o.getString("packageName");
            info.forceUpdate = o.getBoolean("forceUpdate");
            return info;
        } catch (final JSONException e) {
            if (AppContext.DEBUG) {
                e.printStackTrace();
            }
            return null;
        }
    }

    public static AppVersionInfo parseBundle(final Bundle bundle) {
        final AppVersionInfo info = new AppVersionInfo();
        info.versionCode = bundle.getInt("versionCode");
        info.versionName = bundle.getString("versionName");
        info.releaseDate = bundle.getString("releaseDate");
        info.changelog = bundle.getString("changelog");
        info.downloadUrl = bundle.getString("downloadUrl");
        info.versionType = bundle.getString("versionType");
        info.packageName = bundle.getString("packageName");
        info.forceUpdate = bundle.getBoolean("forceUpdate");
        if (info.versionCode > 0) {
            return info;
        } else {
            return null;
        }
    }

    public boolean forceUpdate;// 是否强制升级

    public AppVersionInfo() {
    }

    public AppVersionInfo(final Parcel in) {
        this();
        final Bundle bundle = in.readBundle();
        readFromBundle(bundle);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public void readFromBundle(final Bundle bundle) {
        this.versionCode = bundle.getInt("versionCode");
        this.versionName = bundle.getString("versionName");
        this.releaseDate = bundle.getString("releaseDate");
        this.changelog = bundle.getString("changelog");
        this.downloadUrl = bundle.getString("downloadUrl");
        this.versionType = bundle.getString("versionType");
        this.packageName = bundle.getString("packageName");
        this.forceUpdate = bundle.getBoolean("forceUpdate");
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer();
        sb.append("[VersionInfo] versionCode=" + this.versionCode);
        sb.append("[VersionInfo] versionName=" + this.versionName);
        sb.append("[VersionInfo] releaseDate=" + this.releaseDate);
        sb.append("[VersionInfo] changelog=(" + this.changelog).append(")");
        sb.append("[VersionInfo] downloadUrl=" + this.downloadUrl);
        sb.append("[VersionInfo] versionType=" + this.versionType);
        sb.append("[VersionInfo] packageName=" + this.packageName);
        sb.append("[VersionInfo] forceUpdate=" + this.forceUpdate);
        return sb.toString();
    }

    @Override
    public void writeToParcel(final Parcel dest, final int flags) {
        final Bundle bundle = new Bundle();
        bundle.putInt("versionCode", this.versionCode);
        bundle.putString("versionName", this.versionName);
        bundle.putString("releaseDate", this.releaseDate);
        bundle.putString("changelog", this.changelog);
        bundle.putString("downloadUrl", this.downloadUrl);
        bundle.putString("versionType", this.versionType);
        bundle.putString("packageName", this.packageName);
        bundle.putBoolean("forceUpdate", this.forceUpdate);
        dest.writeBundle(bundle);
    }

}


text:
set +x -eu -o pipefail

# Only deploy if this not a PR. PRs are deployed early in `build.sh`.
if [[ $TRAVIS_PULL_REQUEST != "false" ]]; then
  echo "Skipping deploy because this is a PR build."
  exit 0
fi

# Do not deploy if the current commit is not the latest on its branch.
readonly LATEST_COMMIT=$(git ls-remote origin $TRAVIS_BRANCH | cut -c1-40)
if [[ $TRAVIS_COMMIT != $LATEST_COMMIT ]]; then
  echo "Skipping deploy because $TRAVIS_COMMIT is not the latest commit ($LATEST_COMMIT)."
  exit 0
fi

# The deployment mode is computed based on the branch we are building
if [[ $TRAVIS_BRANCH == master ]]; then
  readonly deployEnv=next
elif [[ $TRAVIS_BRANCH == $STABLE_BRANCH ]]; then
    readonly deployEnv=stable
else
  # Extract the major versions from the branches, e.g. the 4 from 4.3.x
  readonly majorVersion=${TRAVIS_BRANCH%%.*}
  readonly majorVersionStable=${STABLE_BRANCH%%.*}

  # Do not deploy if the major version is not less than the stable branch major version
  if [[ !( "$majorVersion" < "$majorVersionStable" ) ]]; then
    echo "Skipping deploy of branch \"${TRAVIS_BRANCH}\" to firebase."
    echo "We only deploy archive branches with the major version less than the stable branch: \"${STABLE_BRANCH}\""
    exit 0
  fi

  # Find the branch that has highest minor version for the given `$majorVersion`
  readonly mostRecentMinorVersion=$(
    # List the branches that start with the major version
    git ls-remote origin refs/heads/${majorVersion}.*.x |
    # Extract the version number
    awk -F'/' '{print $3}' |
    # Sort by the minor version
    sort -t. -k 2,2n |
    # Get the highest version
    tail -n1
  )

  # Do not deploy as it is not the latest branch for the given major version
  if [[ $TRAVIS_BRANCH != $mostRecentMinorVersion ]]; then
    echo "Skipping deploy of branch \"${TRAVIS_BRANCH}\" to firebase."
    echo "There is a more recent branch with the same major version: \"${mostRecentMinorVersion}\""
    exit 0
  fi

  readonly deployEnv=archive
fi

case $deployEnv in
  next)
    readonly projectId=aio-staging
    readonly deployedUrl=https://next.angular.io/
    readonly firebaseToken=$FIREBASE_TOKEN
    ;;
  stable)
    readonly projectId=angular-io
    readonly deployedUrl=https://angular.io/
    readonly firebaseToken=$FIREBASE_TOKEN
    ;;
  archive)
    readonly projectId=angular-io-${majorVersion}
    readonly deployedUrl=https://v${majorVersion}.angular.io/
    readonly firebaseToken=$FIREBASE_TOKEN
    ;;
esac

echo "Git branch        : $TRAVIS_BRANCH"
echo "Build/deploy mode : $deployEnv"
echo "Firebase project  : $projectId"
echo "Deployment URL    : $deployedUrl"

if [[ ${1:-} == "--dry-run" ]]; then
  exit 0
fi

# Deploy
(
  cd "`dirname $0`/.."

  # Build the app
  yarn build --env=$deployEnv

  # Include any mode-specific files
  cp -rf src/extra-files/$deployEnv/. dist/

  # Check payload size
  yarn payload-size

  # Deploy to Firebase
  firebase use "$projectId" --token "$firebaseToken"
  firebase deploy --message "Commit: $TRAVIS_COMMIT" --non-interactive --token "$firebaseToken"

  # Run PWA-score tests
  yarn test-pwa-score "$deployedUrl" "$MIN_PWA_SCORE"
)


text:
package org.stormenroute.bundleboy

import java.io._
import org.scalatest._

class ZipBundleSpec extends FlatSpec with Matchers {

  val testTxtContents = "This is a test file.\n"

  val resourcesDir = {
    if (new File("resources").exists) "resources"
    else "bundleboy/resources"
  }

  "ZipBundle.ClazzLoader" should "load the class correctly" in {
    val loader = new ZipBundle.ZipClassLoader(resourcesDir + "/example-classes.bundle", () => "".toCharArray)
    val cls = loader.findClass("org.storm.bundleboy.TestExampleClass")
    val inst = cls.newInstance
    val string = cls.getMethod("someString").invoke(inst)
    string should equal ("test string")
  }

  "ZipBundle" should "fetch the resources correctly" in {
    val bundle = new ZipBundle("testBundle", resourcesDir + "/example-classes.bundle", () => "".toCharArray)

    val textContents = bundle.files.docs.text("test.txt")
    assert(textContents == testTxtContents)

    val image = bundle.files.imgs.image("ski.png")
    assert(image != null)
  }

  it should "instantiate the class object" in {
    val bundle = new ZipBundle("testBundle", resourcesDir + "/example-classes.bundle", () => "".toCharArray)
    val cls = bundle.classes.org.storm.bundleboy.TestExampleClass.get
    val inst = cls.newInstance
    val string = cls.getMethod("someString").invoke(inst)
    string should equal ("test string")
  }

  it should "retrieve all the classes in a package" in {
    val bundle = new ZipBundle("testBundle", resourcesDir + "/example-classes.bundle", () => "".toCharArray)
    val cs = bundle.classes.org.storm.bundleboy.all
    cs.map(_.getSimpleName) should equal (Set("TestExampleClass", "TestExampleClass2"))
    val cs2 = bundle.classes.org.storm.all
    cs2.map(_.getSimpleName) should equal (Set("TestExampleClass", "TestExampleClass2", "TestExampleClassAbove"))
  }

  it should "retrieve all the subclasses in a package" in {
    val bundle = new ZipBundle("testBundle", resourcesDir + "/example-classes.bundle", () => "".toCharArray)
    val cs = bundle.classes.org.storm.bundleboy.subclasses(classOf[Serializable])
    cs.map(_.getSimpleName) should equal (Set("TestExampleClass"))
  }

}

// (new ZipBundleCreator).fromFolders(List(resourcesDir + "/docs", resourcesDir + "/org", resourcesDir + "/imgs").map(x => new java.io.File(x)), "example-classes.bundle", () => "".toCharArray)
// (new ZipBundleCreator).fromFolders(List(resourcesDir + "/docs2").map(x => new java.io.File(x)), "example-classes-2.bundle", () => "".toCharArray)


text:
<?php

namespace Symfony\Component\Console\Tests\Formatter;

use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;

class OutputFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function testEmptyTag()
    {
        $formatter = new OutputFormatter(true);
        $this->assertEquals("foo<>bar", $formatter->format('foo<>bar'));
    }

    public function testLGCharEscaping()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals("foo<bar", $formatter->format('foo\\<bar'));
        $this->assertEquals("<info>some info</info>", $formatter->format('\\<info>some info\\</info>'));
        $this->assertEquals("\\<info>some info\\</info>", OutputFormatter::escape('<info>some info</info>'));

        $this->assertEquals(
            "\033[33mSymfony\\Component\\Console does work very well!\033[39m",
            $formatter->format('<comment>Symfony\Component\Console does work very well!</comment>')
        );
    }

    public function testBundledStyles()
    {
        $formatter = new OutputFormatter(true);

        $this->assertTrue($formatter->hasStyle('error'));
        $this->assertTrue($formatter->hasStyle('info'));
        $this->assertTrue($formatter->hasStyle('comment'));
        $this->assertTrue($formatter->hasStyle('question'));

        $this->assertEquals(
            "\033[37;41msome error\033[39;49m",
            $formatter->format('<error>some error</error>')
        );
        $this->assertEquals(
            "\033[32msome info\033[39m",
            $formatter->format('<info>some info</info>')
        );
        $this->assertEquals(
            "\033[33msome comment\033[39m",
            $formatter->format('<comment>some comment</comment>')
        );
        $this->assertEquals(
            "\033[30;46msome question\033[39;49m",
            $formatter->format('<question>some question</question>')
        );
    }

    public function testNestedStyles()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(
            "\033[37;41msome \033[39;49m\033[32msome info\033[39m\033[37;41m error\033[39;49m",
            $formatter->format('<error>some <info>some info</info> error</error>')
        );
    }

    public function testAdjacentStyles()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(
            "\033[37;41msome error\033[39;49m\033[32msome info\033[39m",
            $formatter->format('<error>some error</error><info>some info</info>')
        );
    }

    public function testStyleMatchingNotGreedy()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(
            "(\033[32m>=2.0,<2.3\033[39m)",
            $formatter->format('(<info>>=2.0,<2.3</info>)')
        );
    }

    public function testStyleEscaping()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(
            "(\033[32mz>=2.0,<a2.3\033[39m)",
            $formatter->format('(<info>'.$formatter->escape('z>=2.0,<a2.3').'</info>)')
        );
    }

    public function testDeepNestedStyles()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(
            "\033[37;41merror\033[39;49m\033[32minfo\033[39m\033[33mcomment\033[39m\033[37;41merror\033[39;49m",
            $formatter->format('<error>error<info>info<comment>comment</info>error</error>')
        );
    }

    public function testNewStyle()
    {
        $formatter = new OutputFormatter(true);

        $style = new OutputFormatterStyle('blue', 'white');
        $formatter->setStyle('test', $style);

        $this->assertEquals($style, $formatter->getStyle('test'));
        $this->assertNotEquals($style, $formatter->getStyle('info'));

        $style = new OutputFormatterStyle('blue', 'white');
        $formatter->setStyle('b', $style);

        $this->assertEquals("\033[34;47msome \033[39;49m\033[34;47mcustom\033[39;49m\033[34;47m msg\033[39;49m", $formatter->format('<test>some custom msg</test>'));
    }

    public function testRedefineStyle()
    {
        $formatter = new OutputFormatter(true);

        $style = new OutputFormatterStyle('blue', 'white');
        $formatter->setStyle('info', $style);

        $this->assertEquals("\033[34;47msome custom msg\033[39;49m", $formatter->format('<info>some custom msg</info>'));
    }

    public function testInlineStyle()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals("\033[34;41msome text\033[39;49m", $formatter->format('<fg=blue;bg=red>some text</>'));
        $this->assertEquals("\033[34;41msome text\033[39;49m", $formatter->format('<fg=blue;bg=red>some text</fg=blue;bg=red>'));
    }

    public function testNonStyleTag()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals("\033[32msome \033[39m\033[32m<tag>\033[39m\033[32m \033[39m\033[32m<setting=value>\033[39m\033[32m styled \033[39m\033[32m
\033[39m\033[32msingle-char tag\033[39m\033[32m
\033[39m", $formatter->format('<info>some <tag> <setting=value> styled
single-char tag
</info>'));
    }

    public function testFormatLongString()
    {
        $formatter = new OutputFormatter(true);
        $long = str_repeat("\\", 14000);
        $this->assertEquals("\033[37;41msome error\033[39;49m".$long, $formatter->format('<error>some error</error>'.$long));
    }

    public function testNotDecoratedFormatter()
    {
        $formatter = new OutputFormatter(false);

        $this->assertTrue($formatter->hasStyle('error'));
        $this->assertTrue($formatter->hasStyle('info'));
        $this->assertTrue($formatter->hasStyle('comment'));
        $this->assertTrue($formatter->hasStyle('question'));

        $this->assertEquals(
            "some error", $formatter->format('<error>some error</error>')
        );
        $this->assertEquals(
            "some info", $formatter->format('<info>some info</info>')
        );
        $this->assertEquals(
            "some comment", $formatter->format('<comment>some comment</comment>')
        );
        $this->assertEquals(
            "some question", $formatter->format('<question>some question</question>')
        );

        $formatter->setDecorated(true);

        $this->assertEquals(
            "\033[37;41msome error\033[39;49m", $formatter->format('<error>some error</error>')
        );
        $this->assertEquals(
            "\033[32msome info\033[39m", $formatter->format('<info>some info</info>')
        );
        $this->assertEquals(
            "\033[33msome comment\033[39m", $formatter->format('<comment>some comment</comment>')
        );
        $this->assertEquals(
            "\033[30;46msome question\033[39;49m", $formatter->format('<question>some question</question>')
        );
    }

    public function testContentWithLineBreaks()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(<<<EOF
\033[32m
some text\033[39m
EOF
            , $formatter->format(<<<EOF
<info>
some text</info>
EOF
        ));

        $this->assertEquals(<<<EOF
\033[32msome text
\033[39m
EOF
            , $formatter->format(<<<EOF
<info>some text
</info>
EOF
        ));

        $this->assertEquals(<<<EOF
\033[32m
some text
\033[39m
EOF
            , $formatter->format(<<<EOF
<info>
some text
</info>
EOF
        ));

        $this->assertEquals(<<<EOF
\033[32m
some text
more text
\033[39m
EOF
            , $formatter->format(<<<EOF
<info>
some text
more text
</info>
EOF
        ));
    }
}


text:
package number

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import common.CommonTest
import java.io.File
import number.api.SkillState

@RunWith(classOf[JUnitRunner])
class WriteTest extends CommonTest {

  test("write 1.2M numbers") {
    val startTime = System.nanoTime

    val limit: Int = 6e5.toInt
    val file = File.createTempFile("writetest", ".sf")
    val path = file.toPath()

    val σ = SkillState.create
    for (i ← -limit until limit)
      σ.Number(i)

    σ.write(path)

    val d = SkillState.read(path).Number.all
    var cond = true
    for (i ← -limit until limit)
      cond &&= (i == d.next.number)
    assert(cond, "match failed")

//    file.delete
  }
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "imgITools.h"
#include "gfxContext.h"

#define NS_IMGTOOLS_CID \
{ /* fd9a9e8a-a77b-496a-b7bb-263df9715149 */         \
     0xfd9a9e8a,                                     \
     0xa77b,                                         \
     0x496a,                                         \
    {0xb7, 0xbb, 0x26, 0x3d, 0xf9, 0x71, 0x51, 0x49} \
}

class imgTools : public imgITools
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_IMGITOOLS

  imgTools();
  virtual ~imgTools();

private:
  NS_IMETHODIMP EncodeImageData(gfxImageSurface *aSurface,
                                const nsACString& aMimeType,
                                const nsAString& aOutputOptions,
                                nsIInputStream **aStream);

  NS_IMETHODIMP GetFirstImageFrame(imgIContainer *aContainer,
                                   gfxImageSurface **aSurface);
};


text:
import * as module from 'https://{{domains[www1]}}:{{ports[https][0]}}/workers/modules/resources/export-referrer-checker.py';
if ('DedicatedWorkerGlobalScope' in self &&
    self instanceof DedicatedWorkerGlobalScope) {
  postMessage(module.referrer);
} else if (
    'SharedWorkerGlobalScope' in self &&
    self instanceof SharedWorkerGlobalScope) {
  onconnect = e => {
    e.ports[0].postMessage(module.referrer);
  };
}