text:
import React from "react"
import { push, goBack } from 'react-router-redux'
import fetch from 'isomorphic-fetch'
import * as actionTypes from "./action-types"
import { toastr } from 'react-redux-toastr'
import { actions as toastrActions } from 'react-redux-toastr'
import * as utils from "../utils"
import * as apiUtils from "./api-utils"
import * as urls from "../urls"
import * as forms from "../forms"
import moment from "moment"
import momentLocalizer from "react-widgets/lib/localizers/moment"
import * as mtparts from "../media-type-parts"

let urlPrefix
if (process.env.NODE_ENV == 'production') {
    urlPrefix = "https://www.gasjot.com"
} else {
    urlPrefix = "http://dev.gasjot.com"
}

const LIGHT_LOGIN_URI          = urlPrefix + "/gasjot/d/light-login"
const LOGIN_URI                = urlPrefix + "/gasjot/d/login"
const SIGNUP_URI               = urlPrefix + "/gasjot/d/users"
const SEND_PWD_RESET_EMAIL_URI = urlPrefix + "/gasjot/d/send-password-reset-email"
const PASSWORD_RESET_URI       = urlPrefix + "/gasjot/d/password-reset"

console.log("GASJOT_VERSION: " + process.env.GASJOT_VERSION)

function resendVerificationEmailUri(userUri) {
    return userUri + "/send-verification-email"
}

export function cancelRecordEdit() {
    return { type: actionTypes.CANCEL_RECORD_EDIT }
}

export function clearErrors() {
    return { type: actionTypes.CLEAR_ERRORS }
}

export function receiveServerSnapshot(serverSnapshot) {
    return { type: actionTypes.SERVER_SNAPSHOT_RECEIVED, serverSnapshot }
}

export function receiveServerUser(serverUser) {
    return { type: actionTypes.SERVER_USER_RECEIVED, serverUser }
}

export function serverUserNotFound() {
    return { type: actionTypes.SERVER_USER_NOT_FOUND }
}

export function serverUserNotFound(userId) {
    return { type: actionTypes.SERVER_USER_NOT_FOUND }
}

export function serverUserNotFoundUserAcknowledged() {
    return { type: actionTypes.SERVER_USER_NOT_FOUND_USER_ACK }
}

export function receiveServerChangelog(serverChangelog) {
    return { type: actionTypes.SERVER_CHANGELOG_RECEIVED, serverChangelog }
}

export function receiveServerVehicleDeletedAck(serverVehicleId) {
    return { type: actionTypes.SERVER_VEHICLE_DELETED_ACK_RECEIVED, serverVehicleId }
}

export function receiveServerVehicle(serverVehicle) {
    return { type: actionTypes.SERVER_VEHICLE_RECEIVED, serverVehicle }
}

export function receiveServerVehicleLocation(serverVehicleId, serverVehicleLocation) {
    return { type: actionTypes.SERVER_VEHICLE_LOCATION_RECEIVED,
             serverVehicleId: serverVehicleId,
             serverVehicleLocation: serverVehicleLocation }
}

export function receiveServerVehicleMediaType(serverVehicleId, serverVehicleMediaType) {
    return { type: actionTypes.SERVER_VEHICLE_MEDIATYPE_RECEIVED,
             serverVehicleId: serverVehicleId,
             serverVehicleMediaType }
}

export function serverVehicleNotFound(serverVehicleId) {
    return { type: actionTypes.SERVER_VEHICLE_NOT_FOUND,
             serverVehicleId: serverVehicleId }
}

export function serverVehicleNotFoundUserAcknowledged(serverVehicleId) {
    return { type: actionTypes.SERVER_VEHICLE_NOT_FOUND_USER_ACK,
             serverVehicleId: serverVehicleId }
}

export function becameReauthenticated() {
    return { type: actionTypes.BECAME_REAUTHENTICATED }
}

export function passwordResetEmailSent() {
    return { type: actionTypes.PASSWORD_RESET_EMAIL_SENT }
}

export function presentedLightLoginForm() {
    return { type: actionTypes.PRESENTED_LIGHT_LOGIN_FORM }
}

export function receiveServerFuelstation(serverFuelstation) {
    return { type: actionTypes.SERVER_FUELSTATION_RECEIVED, serverFuelstation }
}

export function receiveServerFuelstationDeletedAck(serverFuelstationId) {
    return { type: actionTypes.SERVER_FUELSTATION_DELETED_ACK_RECEIVED, serverFuelstationId }
}

export function receiveServerFuelstationLocation(serverFuelstationId, serverFuelstationLocation) {
    return { type: actionTypes.SERVER_FUELSTATION_LOCATION_RECEIVED,
             serverFuelstationId: serverFuelstationId,
             serverFuelstationLocation: serverFuelstationLocation }
}

export function receiveServerFuelstationMediaType(serverFuelstationId, serverFuelstationMediaType) {
    return { type: actionTypes.SERVER_FUELSTATION_MEDIATYPE_RECEIVED,
             serverFuelstationId: serverFuelstationId,
             serverFuelstationMediaType }
}

export function serverFuelstationNotFound(serverFuelstationId) {
    return { type: actionTypes.SERVER_FUELSTATION_NOT_FOUND,
             serverFuelstationId: serverFuelstationId }
}

export function serverFuelstationNotFoundUserAcknowledged(serverFuelstationId) {
    return { type: actionTypes.SERVER_FUELSTATION_NOT_FOUND_USER_ACK,
             serverFuelstationId: serverFuelstationId }
}

export function receiveServerOdometerLog(serverOdometerLog) {
    return { type: actionTypes.SERVER_ODOMETERLOG_RECEIVED, serverOdometerLog }
}

export function receiveServerOdometerLogDeletedAck(serverOdometerLogId) {
    return { type: actionTypes.SERVER_ODOMETERLOG_DELETED_ACK_RECEIVED, serverOdometerLogId }
}

export function receiveServerOdometerLogLocation(serverOdometerLogId, serverOdometerLogLocation) {
    return { type: actionTypes.SERVER_ODOMETERLOG_LOCATION_RECEIVED,
             serverOdometerLogId: serverOdometerLogId,
             serverOdometerLogLocation: serverOdometerLogLocation }
}

export function receiveServerOdometerLogMediaType(serverOdometerLogId, serverOdometerLogMediaType) {
    return { type: actionTypes.SERVER_ODOMETERLOG_MEDIATYPE_RECEIVED,
             serverOdometerLogId: serverOdometerLogId,
             serverOdometerLogMediaType }
}

export function serverOdometerLogNotFound(serverOdometerLogId) {
    return { type: actionTypes.SERVER_ODOMETERLOG_NOT_FOUND,
             serverOdometerLogId: serverOdometerLogId }
}

export function serverOdometerLogNotFoundUserAcknowledged(serverOdometerLogId) {
    return { type: actionTypes.SERVER_ODOMETERLOG_NOT_FOUND_USER_ACK,
             serverOdometerLogId: serverOdometerLogId }
}

export function receiveServerGasLog(serverGasLog) {
    return { type: actionTypes.SERVER_GASLOG_RECEIVED, serverGasLog }
}

export function receiveServerGasLogDeletedAck(serverGasLogId) {
    return { type: actionTypes.SERVER_GASLOG_DELETED_ACK_RECEIVED, serverGasLogId }
}

export function receiveServerGasLogLocation(serverGasLogId, serverGasLogLocation) {
    return { type: actionTypes.SERVER_GASLOG_LOCATION_RECEIVED,
             serverGasLogId: serverGasLogId,
             serverGasLogLocation: serverGasLogLocation }
}

export function receiveServerGasLogMediaType(serverGasLogId, serverGasLogMediaType) {
    return { type: actionTypes.SERVER_GASLOG_MEDIATYPE_RECEIVED,
             serverGasLogId: serverGasLogId,
             serverGasLogMediaType }
}

export function serverGasLogNotFound(serverGasLogId) {
    return { type: actionTypes.SERVER_GASLOG_NOT_FOUND,
             serverGasLogId: serverGasLogId }
}

export function serverGasLogNotFoundUserAcknowledged(serverGasLogId) {
    return { type: actionTypes.SERVER_GASLOG_NOT_FOUND_USER_ACK,
             serverGasLogId: serverGasLogId }
}

export function receiveAuthenticationToken(authToken) {
    return { type: actionTypes.AUTH_TOKEN_RECEIVED, authToken }
}

export function receiveUserUri(userUri) {
    return { type: actionTypes.USER_URI_RECEIVED, userUri }
}

export function logoutRequestInitiated() {
    return { type: actionTypes.LOGOUT_REQUEST_INITIATED }
}

export function logoutRequestDone() {
    return { type: actionTypes.LOGOUT_REQUEST_DONE }
}

export function markUserForEdit() {
    return { type: actionTypes.MARK_USER_FOR_EDIT }
}

export function markVehicleForEdit(vehicleId) {
    return { type: actionTypes.MARK_VEHICLE_FOR_EDIT, vehicleId }
}

export function markFuelstationForEdit(fuelstationId) {
    return { type: actionTypes.MARK_FUELSTATION_FOR_EDIT, fuelstationId }
}

export function markOdometerLogForEdit(odometerLogId) {
    return { type: actionTypes.MARK_ODOMETERLOG_FOR_EDIT, odometerLogId }
}

export function markGasLogForEdit(gasLogId) {
    return { type: actionTypes.MARK_GASLOG_FOR_EDIT, gasLogId }
}

const makeMediaType = entityName => "application/vnd.fp." + entityName + "-v0.0.1+json"
const makeContentType = (mediaType, charset) => mediaType + ";charset=" + charset

const charset = "UTF-8"

const userMediaType = makeMediaType(mtparts.USER_MT_PART)
const userContentType = makeContentType(userMediaType, charset)

const changelogMediaType = makeMediaType(mtparts.CHANGELOG_MT_PART)

const vehicleMediaType = makeMediaType(mtparts.VEHICLE_MT_PART)
const vehicleContentType = makeContentType(vehicleMediaType, charset)

const fuelstationMediaType = makeMediaType(mtparts.FUELSTATION_MT_PART)
const fuelstationContentType = makeContentType(fuelstationMediaType, charset)

const odometerLogMediaType = makeMediaType(mtparts.ENVLOG_MT_PART)
const odometerLogContentType = makeContentType(odometerLogMediaType, charset)

const gasLogMediaType = makeMediaType(mtparts.FPLOG_MT_PART)
const gasLogContentType = makeContentType(gasLogMediaType, charset)

export function logout(logoutUri, authToken) {
    return (dispatch) => {
        toastr.info('Processing logout...', apiUtils.toastConfigWorkingOnIt())
        dispatch(apiUtils.apiRequestInitiated())
        const headers = new Headers()
        apiUtils.appendContentType(headers, userContentType)
        apiUtils.appendAuthenticatedCommonHeaders(headers, userMediaType, authToken)
        return fetch(logoutUri, apiUtils.postInitForFetch(headers, {}))
            .then(response => {
                dispatch(apiUtils.apiRequestDone())
                dispatch(logoutRequestDone())
                dispatch(push(urls.LOGGED_OUT_URI))
                toastr.clean()
            })
            .catch(error => {
                // because we're not going to 'gracefully' handle this from a user-perspective...because the user can't
                // really do anything about it, and, because we'll still be deleting from localStorage the authentication
                // token, we're pretty much good
                dispatch(apiUtils.apiRequestDone())
                dispatch(logoutRequestDone())
                dispatch(push(urls.LOGGED_OUT_URI))
                toastr.clean()
            })
    }
}

export function attemptSignUp() {
    return (dispatch, getState) => {
        const state = getState()
        toastr.info('Creating account...', apiUtils.toastConfigWorkingOnIt())
        dispatch(apiUtils.apiRequestInitiated())
        const headers = new Headers()
        apiUtils.appendContentType(headers, userContentType)
        apiUtils.appendCommonHeaders(headers, userMediaType)
        headers.append(apiUtils.FP_ESTABLISH_SESSION_HEADER, "true")
        headers.append(apiUtils.FP_DESIRED_EMBEDDED_FORMAT_HEADER, apiUtils.FP_ID_KEYED_EMBEDDED_FORMAT)
        const requestPayload = {
            "user/name": state.form.signup.name.value,
            "user/email": _.trim(state.form.signup.email.value),
            "user/password": state.form.signup.password.value
        };
        return fetch(SIGNUP_URI, apiUtils.postInitForFetch(headers, requestPayload))
            .then(response => {
                dispatch(toastrActions.clean())
                dispatch(apiUtils.apiRequestDone())
                dispatch(apiUtils.receiveResponseStatus(response.status, response.headers.get(apiUtils.FP_ERR_MASK_HEADER)))
                if (response.status == 201) {
                    dispatch(receiveAuthenticationToken(response.headers.get(apiUtils.FP_AUTH_TOKEN_HEADER)))
                    dispatch(receiveUserUri(response.headers.get("Location")))
                    return response.json().then(json => {
                        dispatch(receiveServerSnapshot(json))
                        dispatch(toastrActions.clean())
                        dispatch(push(urls.ACCOUNT_CREATED_URI))
                        toastr.success("Account created successfully!", apiUtils.toastConfigSuccess())
                    })
                } else if (!response.ok) {
                    toastr.error("We're sorry, but there was a problem creating your account.  Please try again later.", apiUtils.toastConfigError())
                }
            })
            .catch(error => {
                toastr.error("We're sorry, but there was a problem creating your account.  Please try again later.", apiUtils.toastConfigError())
            })
    }
}

export function attemptResendVerificationEmail() {
    return (dispatch, getState) => {
        toastr.info("Sending verification email...", apiUtils.toastConfigWorkingOnIt())
        dispatch(apiUtils.apiRequestInitiated())
        const state = getState()
        const headers = new Headers()
        apiUtils.appendContentType(headers, userContentType)
        apiUtils.appendAuthenticatedCommonHeaders(headers, userMediaType, state.authToken)
        let init = {}
        init.method = "POST"
        init.headers = headers
        init.body = JSON.stringify({})
        return fetch(resendVerificationEmailUri(state.userUri), init)
            .then(response => {
                toastr.clean()
                dispatch(apiUtils.apiRequestDone())
                dispatch(apiUtils.receiveResponseStatus(response.status, response.headers.get(apiUtils.FP_ERR_MASK_HEADER)))
                if (!apiUtils.checkBecameUnauthenticated(response, dispatch)) {
                    if (response.status == 204) {
                        toastr.success("Verificaton email sent to you at: " + state.serverSnapshot['user/email'], apiUtils.toastConfigSuccess())
                    } else if (!response.ok) {
                        toastr.error("Oops.  There was a problem.  Try this again a bit later.", apiUtils.toastConfigError())
                    }
                }
            })
            .catch(error => {
                toastr.clean()
                dispatch(apiUtils.apiRequestDone())
                toastr.error("Oops.  There was a problem.  Try this again a bit later.", apiUtils.toastConfigError())
            })
    }
}

export function attemptResetPassword(email, resetToken) {
    return (dispatch, getState) => {
        toastr.info("Resetting your password...", apiUtils.toastConfigWorkingOnIt())
        dispatch(apiUtils.apiRequestInitiated())
        const state = getState()
        const headers = new Headers()
        apiUtils.appendContentType(headers, userContentType)
        let init = {}
        init.method = "POST"
        init.headers = headers
        let requestPayload = { email: email }
        requestPayload["password-reset-token"] = resetToken
        requestPayload["new-password"] = state.form.resetpassword.password.value
        init.body = JSON.stringify(requestPayload)
        return fetch(PASSWORD_RESET_URI, init)
            .then(response => {
                toastr.clean()
                dispatch(apiUtils.apiRequestDone())
                dispatch(apiUtils.receiveResponseStatus(response.status, response.headers.get(apiUtils.FP_ERR_MASK_HEADER)))
                if (response.status == 204) {
                    dispatch(push(urls.PASSWORD_RESET_SUCCESS_URI))
                    toastr.success("Password reset successful!", apiUtils.toastConfigSuccess())
                } else if (!response.ok) {
                    toastr.error("Oops.  There was a problem.  Try this again a bit later.", apiUtils.toastConfigError())
                }
            })
            .catch(error => {
                toastr.clean()
                dispatch(apiUtils.apiRequestDone())
                toastr.error("Oops.  There was a problem.  Try this again a bit later.", apiUtils.toastConfigError())
            })
    }
}

export function attemptLogin(nextSuccessPathname) {
    return (dispatch, getState) => {
        const state = getState()
        toastr.info('Logging you in...', apiUtils.toastConfigWorkingOnIt())
        dispatch(apiUtils.apiRequestInitiated())
        const headers = new Headers()
        apiUtils.appendContentType(headers, userContentType)
        apiUtils.appendCommonHeaders(headers, userMediaType)
        headers.append(apiUtils.FP_DESIRED_EMBEDDED_FORMAT_HEADER, apiUtils.FP_ID_KEYED_EMBEDDED_FORMAT)
        const requestPayload = {
            "user/username-or-email": _.trim(state.form.login.usernameOrEmail.value),
            "user/password": state.form.login.password.value
        };
        return fetch(LOGIN_URI, apiUtils.postInitForFetch(headers, requestPayload))
            .then(response => {
                dispatch(apiUtils.apiRequestDone())
                dispatch(receiveAuthenticationToken(response.headers.get(apiUtils.FP_AUTH_TOKEN_HEADER)))
                dispatch(receiveUserUri(response.headers.get("Location")))
                dispatch(apiUtils.receiveResponseStatus(response.status, response.headers.get(apiUtils.FP_ERR_MASK_HEADER)))
                if (response.status == 401) {
                    toastr.clean()
                    toastr.error("Login failed.", apiUtils.toastConfigError())
                } else {
                    return response.json().then(json => {
                        dispatch(receiveServerSnapshot(json))
                        dispatch(push(nextSuccessPathname))
                        toastr.clean()
                        toastr.success("Welcome Back", "You are now logged in.", apiUtils.toastConfigSuccess())
                    })
                }
            })
            .catch(error => {
                dispatch(apiUtils.apiRequestDone())
                toastr.clean()
                toastr.error("Server error.  Please try again.", apiUtils.toastConfigError())
            })
    }
}

export function attemptLightLogin(operationOnSuccess) {
    return (dispatch, getState) => {
        const state = getState()
        toastr.info('Re-authenticating...', apiUtils.toastConfigWorkingOnIt())
        dispatch(apiUtils.apiRequestInitiated())
        const headers = new Headers()
        apiUtils.appendContentType(headers, userContentType)
        apiUtils.appendCommonHeaders(headers, userMediaType)
        headers.append(apiUtils.FP_DESIRED_EMBEDDED_FORMAT_HEADER, apiUtils.FP_ID_KEYED_EMBEDDED_FORMAT)
        const requestPayload = {
            "user/username-or-email": _.trim(state.form.login.usernameOrEmail.value),
            "user/password": state.form.login.password.value
        };
        return fetch(LIGHT_LOGIN_URI, apiUtils.postInitForFetch(headers, requestPayload))
            .then(response => {
                dispatch(apiUtils.apiRequestDone())
                dispatch(receiveAuthenticationToken(response.headers.get(apiUtils.FP_AUTH_TOKEN_HEADER)))
                dispatch(apiUtils.receiveResponseStatus(response.status, response.headers.get(apiUtils.FP_ERR_MASK_HEADER)))
                if (response.status == 204) {
                    toastr.clean()
                    dispatch(becameReauthenticated())
                    if (operationOnSuccess != null) {
                        operationOnSuccess() // this will presumably come with its own toasts, so we won't bother with the 'You've been re-auth'd' toast
                    } else {
                        toastr.success("Success", "You've been re-authenticated.", apiUtils.toastConfigSuccess())
                    }
                } else {
                    toastr.clean()
                    dispatch(apiUtils.apiRequestDone())
                }
            })
            .catch(error => {
                toastr.clean()
                dispatch(apiUtils.apiRequestDone())
            })
    }
}

export function attemptSendPasswordResetEmail() {
    return (dispatch, getState) => {
        const state = getState()
        toastr.info('Please wait...', apiUtils.toastConfigWorkingOnIt())
        dispatch(apiUtils.apiRequestInitiated())
        const headers = new Headers()
        apiUtils.appendContentType(headers, userContentType)
        apiUtils.appendCommonHeaders(headers, userMediaType)
        const requestPayload = {
            "user/email": _.trim(state.form.forgotpassword.email.value)
        };
        return fetch(SEND_PWD_RESET_EMAIL_URI, apiUtils.postInitForFetch(headers, requestPayload))
            .then(response => {
                dispatch(apiUtils.apiRequestDone())
                dispatch(apiUtils.receiveResponseStatus(response.status, response.headers.get(apiUtils.FP_ERR_MASK_HEADER)))
                if (response.status == 204) {
                    dispatch(toastrActions.clean())
                    dispatch(passwordResetEmailSent())
                    dispatch(push(urls.PASSWORD_RESET_EMAIL_SENT_URI))
                    toastr.success("Password reset email sent", apiUtils.toastConfigSuccess())
                } else {
                    toastr.clean()
                    dispatch(apiUtils.apiRequestDone())
                }
            })
            .catch(error => {
                dispatch(apiUtils.apiRequestDone())
                toastr.clean()
                toastr.error("There was a problem sending your the password reset email.", toastConfigError())
            })
    }
}

const vehicleRequestPayload = form => {
    let payload = {}
    utils.formToModelIfNotNull(form, "name",                  payload, "fpvehicle/name");
    utils.formToModelIfNotNull(form, "plate",                 payload, "fpvehicle/plate");
    utils.formToModelIfNotNull(form, "vin",                   payload, "fpvehicle/vin");
    utils.formToModelIfNotNull(form, "fuelCapacity",          payload, "fpvehicle/fuel-capacity", null, _.toNumber);
    utils.formToModelIfNotNull(form, "defaultOctane",         payload, "fpvehicle/default-octane", null, _.toNumber);
    utils.formToModelIfNotNull(form, "takesDiesel",           payload, "fpvehicle/is-diesel");
    utils.formToModelIfNotNull(form, "hasMpgReadout",         payload, "fpvehicle/has-mpg-readout");
    utils.formToModelIfNotNull(form, "hasMphReadout",         payload, "fpvehicle/has-mph-readout");
    utils.formToModelIfNotNull(form, "hasDteReadout",         payload, "fpvehicle/has-dte-readout");
    utils.formToModelIfNotNull(form, "hasOutsideTempReadout", payload, "fpvehicle/has-outside-temp-readout");
    return payload
}

const userRequestPayload = form => {
    let payload = {}
    utils.formToModelIfNotNull(form, "name", payload, "user/name")
    utils.formToModelIfNotNull(form, "email", payload, "user/email")
    if (form.password.value != null && !_.isEmpty(form.password.value)) {
        payload["user/password"] = form.password.value
    }
    return payload
}

function getUserAccountUri(state, userId) {
    return state.userUri
}

function getUserAccountUpdatedAt(state, userId) {
    return state.serverSnapshot["user/updated-at"]
}

function getChangelogUri(state, NOT_USED) {
    return state.serverSnapshot._links.changelog.href
}

function getChangelogUpdatedAt(state, NOT_USED) {
    return state.mostRecentUpdatedAt
}

function getVehiclesUri(state) {
    return state.serverSnapshot._links.vehicles.href
}

function getVehicleUri(state, vehicleId) {
    return state.serverSnapshot._embedded.vehicles[vehicleId].location
}

function getVehicleUpdatedAt(state, vehicleId) {
    return state.serverSnapshot._embedded.vehicles[vehicleId].payload["fpvehicle/updated-at"]
}

function getFuelstationsUri(state) {
    return state.serverSnapshot._links.fuelstations.href
}

function getFuelstationUri(state, fuelstationId) {
    return state.serverSnapshot._embedded.fuelstations[fuelstationId].location
}

function getFuelstationUpdatedAt(state, fuelstationId) {
    return state.serverSnapshot._embedded.fuelstations[fuelstationId].payload["fpfuelstation/updated-at"]
}

function getOdometerLogsUri(state) {
    return state.serverSnapshot._links["environment-logs"].href
}

function getOdometerLogUri(state, odometerLogId) {
    return state.serverSnapshot._embedded.envlogs[odometerLogId].location
}

function getOdometerLogUpdatedAt(state, odometerLogId) {
    return state.serverSnapshot._embedded.envlogs[odometerLogId].payload["envlog/updated-at"]
}

function getGasLogsUri(state) {
    return state.serverSnapshot._links["fuelpurchase-logs"].href
}

function getGasLogUri(state, gasLogId) {
    return state.serverSnapshot._embedded.fplogs[gasLogId].location
}

function getGasLogUpdatedAt(state, gasLogId) {
    return state.serverSnapshot._embedded.fplogs[gasLogId].payload["fplog/updated-at"]
}

export function attemptSaveUser_orig() {
    return (dispatch, getState) => {
        toastr.info('Saving user account...', apiUtils.toastConfigWorkingOnIt())
        dispatch(apiUtils.apiRequestInitiated())
        const state = getState()
        const headers = new Headers()
        apiUtils.appendContentType(headers, userContentType)
        apiUtils.appendAuthenticatedCommonHeaders(headers, userMediaType, state.authToken)
        const userUri = state.userUri
        const requestPayload = userRequestPayload(state.form.userAccountEdit)
        return fetch(userUri, apiUtils.putInitForFetch(headers, requestPayload))
            .then(response => {
                dispatch(apiUtils.apiRequestDone())
                dispatch(apiUtils.receiveResponseStatus(response.status, response.headers.get(apiUtils.FP_ERR_MASK_HEADER)))
                return response.json()
            })
            .then(json => {
                dispatch(toastrActions.clean())
                dispatch(receiveServerUser(json))
                dispatch(goBack())
                toastr.success("User account saved.", apiUtils.toastConfigSuccess())
            })
            .catch(error => {
                dispatch(apiUtils.apiRequestDone())
                toastr.clean()
                toastr.error("User account save failedd.")
            })
    }
}

export const attemptDownloadUserAccount = apiUtils.makeAttemptDownloadEntityFn(
    "user account",
    userMediaType,
    getUserAccountUpdatedAt,
    getUserAccountUri,
    receiveServerUser,
    serverUserNotFound,
    "You're good.  There have been no updates to your user account information since your last login.",
    null,
    null,
    NOT_USED => "Your latest user account information has been updated.")

export const attemptSaveUserAccount = apiUtils.makeAttemptSaveEntityFn(
    "user account",
    userContentType,
    userMediaType,
    getUserAccountUpdatedAt,
    getUserAccountUri,
    userRequestPayload,
    "userAccountEdit",
    attemptDownloadUserAccount,
    (userId) => urls.EDIT_ACCOUNT_URI,
    receiveServerUser,
    serverUserNotFound)

function countChangesForChangelogEntity(changeCounts,
                                        changelogEntityMediaType,
                                        changelogEntityPayload,
                                        mtpart,
                                        currentServerSnapshot,
                                        entitiesKey,
                                        entityIdKey,
                                        entityDeletedAtKey,
                                        entityUpdatedAtKey) {
    if (changelogEntityMediaType.includes(mtpart)) {
        const matchingEntity = currentServerSnapshot._embedded[entitiesKey][changelogEntityPayload[entityIdKey]]
        if (matchingEntity != null) {
            if (changelogEntityPayload[entityDeletedAtKey] != null) {
                _.update(changeCounts, "deleted", currentCount => currentCount + 1)
            } else if (changelogEntityPayload[entityUpdatedAtKey] != matchingEntity.payload[entityUpdatedAtKey]) {
                _.update(changeCounts, "updated", currentCount => currentCount + 1)
            } else {
                // the changelog entity downloaded was due to edits made to it in the user's browser
            }
        } else {
            if (changelogEntityPayload[entityDeletedAtKey] != null) {
                // the entity was created and deleted before it was ever downloaded to the user's browser
            } else {
                _.update(changeCounts, "added", currentCount => currentCount + 1)
            }
        }
    }
}

function changeCountsFromChangelog(currentServerSnapshot, changelog) {
    let changeCounts = {deleted: 0, updated: 0, added: 0}
    const changedEntities = changelog._embedded
    for (let i = 0; i < changedEntities.length; i++) {
        const changelogEntityMediaType = changedEntities[i]["media-type"]
        const changelogEntityPayload = changedEntities[i]["payload"]
        if (changelogEntityMediaType.includes(mtparts.USER_MT_PART)) {
            if (changelogEntityPayload["user/updated-at"] != currentServerSnapshot["user/updated-at"]) {
                _.update(changeCounts, "updated", currentCount => currentCount + 1)
            }
        }
        countChangesForChangelogEntity(changeCounts,
                                       changelogEntityMediaType,
                                       changelogEntityPayload,
                                       mtparts.VEHICLE_MT_PART,
                                       currentServerSnapshot,
                                       "vehicles",
                                       "fpvehicle/id",
                                       "fpvehicle/deleted-at",
                                       "fpvehicle/updated-at")
        countChangesForChangelogEntity(changeCounts,
                                       changelogEntityMediaType,
                                       changelogEntityPayload,
                                       mtparts.FUELSTATION_MT_PART,
                                       currentServerSnapshot,
                                       "fuelstations",
                                       "fpfuelstation/id",
                                       "fpfuelstation/deleted-at",
                                       "fpfuelstation/updated-at")
        countChangesForChangelogEntity(changeCounts,
                                       changelogEntityMediaType,
                                       changelogEntityPayload,
                                       mtparts.FPLOG_MT_PART,
                                       currentServerSnapshot,
                                       "fplogs",
                                       "fplog/id",
                                       "fplog/deleted-at",
                                       "fplog/updated-at")
        countChangesForChangelogEntity(changeCounts,
                                       changelogEntityMediaType,
                                       changelogEntityPayload,
                                       mtparts.ENVLOG_MT_PART,
                                       currentServerSnapshot,
                                       "envlogs",
                                       "envlog/id",
                                       "envlog/deleted-at",
                                       "envlog/updated-at")
    }
    return changeCounts
}

export const attemptDownloadChangelog = apiUtils.makeAttemptDownloadEntityFn(
    "change log",
    changelogMediaType,
    getChangelogUpdatedAt,
    getChangelogUri,
    receiveServerChangelog,
    null, // 404 handler
    "You're good.  There have been no updates to any of your data records on other devices since you last checked or logged in.",
    changeCountsFromChangelog,
    (changeCounts) => {
        return changeCounts.deleted > 0 || changeCounts.added > 0 || changeCounts.updated > 0
    },
    (changeCounts) => {
        return "Your data records have been updated.  Number of records deleted: " + changeCounts.deleted + ", added: " + changeCounts.added + " and updated: " + changeCounts.updated
    })

export const attemptDownloadVehicle = apiUtils.makeAttemptDownloadEntityFn(
    "vehicle",
    vehicleMediaType,
    getVehicleUpdatedAt,
    getVehicleUri,
    receiveServerVehicle,
    serverVehicleNotFound)

export const attemptSaveVehicle = apiUtils.makeAttemptSaveEntityFn(
    "vehicle",
    vehicleContentType,
    vehicleMediaType,
    getVehicleUpdatedAt,
    getVehicleUri,
    vehicleRequestPayload,
    forms.VEHICLE_FORM,
    attemptDownloadVehicle,
    urls.vehicleEditUrl,
    receiveServerVehicle,
    serverVehicleNotFound)

export const attemptDeleteVehicle = apiUtils.makeAttemptDeleteEntityFn(
    "vehicle",
    vehicleMediaType,
    getVehicleUpdatedAt,
    getVehicleUri,
    attemptDownloadVehicle,
    urls.vehicleDetailUrl,
    receiveServerVehicleDeletedAck,
    serverVehicleNotFound,
    urls.VEHICLES_URI)

export const attemptSaveNewVehicle = apiUtils.makeAttemptSaveNewEntity(
    "vehicle",
    vehicleContentType,
    vehicleMediaType,
    getVehiclesUri,
    vehicleRequestPayload,
    forms.VEHICLE_FORM,
    "fpvehicle/id",
    receiveServerVehicleLocation,
    receiveServerVehicleMediaType,
    receiveServerVehicle)

const fuelstationRequestPayload = form => {
    var payload = {}
    utils.formToModelIfNotNull(form, "name",                  payload, "fpfuelstation/name");
    utils.formToModelIfNotNull(form, "typeId",                payload, "fpfuelstation/type-id", "id", null);
    utils.formToModelIfNotNull(form, "street",                payload, "fpfuelstation/street");
    utils.formToModelIfNotNull(form, "city",                  payload, "fpfuelstation/city");
    utils.formToModelIfNotNull(form, "state",                 payload, "fpfuelstation/state");
    utils.formToModelIfNotNull(form, "zip",                   payload, "fpfuelstation/zip");
    utils.formToModelIfNotNull(form, "latitude",              payload, "fpfuelstation/latitude", null, _.toNumber);
    utils.formToModelIfNotNull(form, "longitude",             payload, "fpfuelstation/longitude", null, _.toNumber);
    return payload
}

export const attemptDownloadFuelstation = apiUtils.makeAttemptDownloadEntityFn(
    "gas station",
    fuelstationMediaType,
    getFuelstationUpdatedAt,
    getFuelstationUri,
    receiveServerFuelstation,
    serverFuelstationNotFound)

export const attemptSaveFuelstation = apiUtils.makeAttemptSaveEntityFn(
    "gas station",
    fuelstationContentType,
    fuelstationMediaType,
    getFuelstationUpdatedAt,
    getFuelstationUri,
    fuelstationRequestPayload,
    forms.GAS_STATION_FORM,
    attemptDownloadFuelstation,
    urls.fuelstationEditUrl,
    receiveServerFuelstation,
    serverFuelstationNotFound)

export const attemptDeleteFuelstation = apiUtils.makeAttemptDeleteEntityFn(
    "fuelstation",
    fuelstationMediaType,
    getFuelstationUpdatedAt,
    getFuelstationUri,
    attemptDownloadFuelstation,
    urls.fuelstationDetailUrl,
    receiveServerFuelstationDeletedAck,
    serverFuelstationNotFound,
    urls.FUELSTATIONS_URI)

export const attemptSaveNewFuelstation = apiUtils.makeAttemptSaveNewEntity(
    "fuelstation",
    fuelstationContentType,
    fuelstationMediaType,
    getFuelstationsUri,
    fuelstationRequestPayload,
    forms.GAS_STATION_FORM,
    "fpfuelstation/id",
    receiveServerFuelstationLocation,
    receiveServerFuelstationMediaType,
    receiveServerFuelstation)

const odometerLogRequestPayloadFnMaker = vehicles => {
    return form => {
        momentLocalizer(moment)
        var payload = {}
        utils.formToModelIfNotNull(form, "vehicleId",          payload, "envlog/vehicle",               "fpvehicle/id", vehicleId => vehicles[vehicleId].location)
        utils.formToModelIfNotNull(form, "logDate",            payload, "envlog/logged-at",             null,           loggedAtStr => utils.toUnixEpoch(moment, loggedAtStr))
        utils.formToModelIfNotNull(form, "odometer",           payload, "envlog/odometer",              null,           _.toNumber)
        utils.formToModelIfNotNull(form, "avgMpgReadout",      payload, "envlog/reported-avg-mpg",      null,           _.toNumber)
        utils.formToModelIfNotNull(form, "avgMphReadout",      payload, "envlog/reported-avg-mph",      null,           _.toNumber)
        utils.formToModelIfNotNull(form, "rangeReadout",       payload, "envlog/dte",                   null,           _.toNumber)
        utils.formToModelIfNotNull(form, "outsideTempReadout", payload, "envlog/reported-outside-temp", null,           _.toNumber)
        return payload
    }
}

export const attemptDownloadOdometerLog = apiUtils.makeAttemptDownloadEntityFn(
    "odometer log",
    odometerLogMediaType,
    getOdometerLogUpdatedAt,
    getOdometerLogUri,
    receiveServerOdometerLog,
    serverOdometerLogNotFound)

export const attemptSaveOdometerLogFnMaker = vehicles =>
    apiUtils.makeAttemptSaveEntityFn(
        "odometer log",
        odometerLogContentType,
        odometerLogMediaType,
        getOdometerLogUpdatedAt,
        getOdometerLogUri,
        odometerLogRequestPayloadFnMaker(vehicles),
        forms.ODOMETER_LOG_FORM,
        attemptDownloadOdometerLog,
        urls.odometerLogEditUrl,
        receiveServerOdometerLog,
        serverOdometerLogNotFound)

export const attemptDeleteOdometerLog = apiUtils.makeAttemptDeleteEntityFn(
    "odometer log",
    odometerLogMediaType,
    getOdometerLogUpdatedAt,
    getOdometerLogUri,
    attemptDownloadOdometerLog,
    urls.odometerLogDetailUrl,
    receiveServerOdometerLogDeletedAck,
    serverOdometerLogNotFound,
    urls.ODOMETER_LOGS_URI)

export const attemptSaveNewOdometerLogFnMaker = vehicles =>
    apiUtils.makeAttemptSaveNewEntity(
        "odometer log",
        odometerLogContentType,
        odometerLogMediaType,
        getOdometerLogsUri,
        odometerLogRequestPayloadFnMaker(vehicles),
        forms.ODOMETER_LOG_FORM,
        "envlog/id",
        receiveServerOdometerLogLocation,
        receiveServerOdometerLogMediaType,
        receiveServerOdometerLog)

const gasLogRequestPayloadFnMaker = (vehicles, fuelstations) => {
    return form => {
        momentLocalizer(moment)
        var payload = {}
        utils.formToModelIfNotNull(form, "vehicleId",                payload, "fplog/vehicle",                   "fpvehicle/id",     vehicleId => vehicles[vehicleId].location)
        utils.formToModelIfNotNull(form, "fuelstationId",            payload, "fplog/fuelstation",               "fpfuelstation/id", fuelstationId => fuelstations[fuelstationId].location)
        utils.formToModelIfNotNull(form, "purchaseDate",             payload, "fplog/purchased-at",              null,               purchasedAtStr => utils.toUnixEpoch(moment, purchasedAtStr))
        utils.formToModelIfNotNull(form, "octane",                   payload, "fplog/octane",                    null, _.toNumber)
        utils.formToModelIfNotNull(form, "odometer",                 payload, "fplog/odometer",                  null, _.toNumber)
        utils.formToModelIfNotNull(form, "pricePerGallon",           payload, "fplog/gallon-price",              null, _.toNumber)
        utils.formToModelIfNotNull(form, "gotCarWash",               payload, "fplog/got-car-wash")
        utils.formToModelIfNotNull(form, "carWashPerGallonDiscount", payload, "fplog/car-wash-per-gal-discount", null, _.toNumber)
        utils.formToModelIfNotNull(form, "numGallons",               payload, "fplog/num-gallons",               null, _.toNumber)
        return payload
    }
}

export const attemptDownloadGasLog = apiUtils.makeAttemptDownloadEntityFn(
    "gas log",
    gasLogMediaType,
    getGasLogUpdatedAt,
    getGasLogUri,
    receiveServerGasLog,
    serverGasLogNotFound)

export const attemptSaveGasLogFnMaker = (vehicles, fuelstations) =>
    apiUtils.makeAttemptSaveEntityFn(
        "gas log",
        gasLogContentType,
        gasLogMediaType,
        getGasLogUpdatedAt,
        getGasLogUri,
        gasLogRequestPayloadFnMaker(vehicles, fuelstations),
        forms.GAS_LOG_FORM,
        attemptDownloadGasLog,
        urls.gasLogEditUrl,
        receiveServerGasLog,
        serverGasLogNotFound)

export const attemptDeleteGasLog = apiUtils.makeAttemptDeleteEntityFn(
    "gas log",
    gasLogMediaType,
    getGasLogUpdatedAt,
    getGasLogUri,
    attemptDownloadGasLog,
    urls.gasLogDetailUrl,
    receiveServerGasLogDeletedAck,
    serverGasLogNotFound,
    urls.GAS_LOGS_URI)

export const attemptSaveNewGasLogFnMaker = (vehicles, fuelstations) =>
    apiUtils.makeAttemptSaveNewEntity(
        "gas log",
        gasLogContentType,
        gasLogMediaType,
        getGasLogsUri,
        gasLogRequestPayloadFnMaker(vehicles, fuelstations),
        forms.GAS_LOG_FORM,
        "fplog/id",
        receiveServerGasLogLocation,
        receiveServerGasLogMediaType,
        receiveServerGasLog)


text:
#import "ZXTelParsedResultTestCase.h"

@implementation ZXTelParsedResultTestCase

- (void)testTel {
  [self doTestWithContents:@"tel:+15551212" number:@"+15551212" title:nil];
  [self doTestWithContents:@"tel:2125551212" number:@"2125551212" title:nil];
}

- (void)doTestWithContents:(NSString *)contents number:(NSString *)number title:(NSString *)title {
  ZXResult *fakeResult = [ZXResult resultWithText:contents rawBytes:nil resultPoints:nil format:kBarcodeFormatQRCode];
  ZXParsedResult *result = [ZXResultParser parseResult:fakeResult];
  XCTAssertEqual(kParsedResultTypeTel, result.type);
  ZXTelParsedResult *telResult = (ZXTelParsedResult *)result;
  XCTAssertEqualObjects(number, telResult.number);
  XCTAssertEqualObjects(title, telResult.title);
  XCTAssertEqualObjects([@"tel:" stringByAppendingString:number], telResult.telURI);
}

@end

redpajama_set_name: RedPajamaGithub


text:
package cromwell.services.instrumentation.impl.statsd

import java.net.InetSocketAddress

import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.io.{IO, Udp}
import akka.testkit.{TestActorRef, TestProbe}
import cats.data.NonEmptyList
import com.typesafe.config.ConfigFactory
import cromwell.core.TestKitSuite
import cromwell.services.instrumentation.InstrumentationService.InstrumentationServiceMessage
import cromwell.services.instrumentation._
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}

import scala.concurrent.duration._
class StatsDInstrumentationServiceActorSpec extends TestKitSuite with FlatSpecLike with BeforeAndAfterAll with Matchers {
  behavior of "StatsDInstrumentationServiceActor"

  val config = ConfigFactory.parseString(
    """statsd {
      |hostname = "localhost"
      |port = 8125
      |prefix = "prefix_value" # can be used to prefix all metrics with an api key for example
      |flush-rate = 100 ms # rate at which aggregated metrics will be sent to statsd
      |}
    """.stripMargin
  )

  val udpProbe = TestProbe()
  val patience = 1.second
  val testBucket = CromwellBucket(List("test_prefix"), NonEmptyList.of("test", "metric", "bucket"))

  var udpListenerActor: ActorRef = _

  override def beforeAll(): Unit = {
    // Start an actor listening to the UDP port and forwarding messages to the udpProbe
    udpListenerActor = system.actorOf(Props(new UDPListenerActor(new InetSocketAddress("localhost", 8125), udpProbe.ref)))
    // Give a sec to the actor to open an UDP socket
    Thread.sleep(1.second.toMillis)
    super.beforeAll()
  }

  override def afterAll(): Unit = {
    udpListenerActor ! Udp.Unbind
    super.afterAll()
  }

  case class StatsDTestBit(description: String, metric: CromwellMetric, expectedPackets: Set[String])

  // Note: The current StatsD implementation sends everything as StatsD gauges so we expect all packets to be "...|g"
  List(
    StatsDTestBit("increment counters", CromwellIncrement(testBucket),
      Set("prefix_value.cromwell.test_prefix.count.test.metric.bucket.samples:1|g",
        "prefix_value.cromwell.test_prefix.count.test.metric.bucket.m1_rate:0.00|g"
      )
    ),
    StatsDTestBit("add count", CromwellCount(testBucket, 80),
      Set("prefix_value.cromwell.test_prefix.count.test.metric.bucket.samples:81|g",
        "prefix_value.cromwell.test_prefix.count.test.metric.bucket.m1_rate:0.00|g"
      )
    ),
    StatsDTestBit("set gauges", CromwellGauge(testBucket, 89),
      Set("prefix_value.cromwell.test_prefix.test.metric.bucket:89|g")
    ),
    StatsDTestBit("set timings", CromwellTiming(testBucket, 5.seconds),
      Set("prefix_value.cromwell.test_prefix.timing.test.metric.bucket.stddev:0.00|g",
        "prefix_value.cromwell.test_prefix.timing.test.metric.bucket.samples:1|g",
        "prefix_value.cromwell.test_prefix.timing.test.metric.bucket.p95:5000.00|g",
        "prefix_value.cromwell.test_prefix.timing.test.metric.bucket.mean:5000.00|g",
        "prefix_value.cromwell.test_prefix.timing.test.metric.bucket.m1_rate:0.00|g"
      )
    )
  ) foreach {
    case StatsDTestBit(description, metric, expectedPackets) =>
      it should description in {
        val instrumentationActor = TestActorRef(new StatsDInstrumentationServiceActor(config, ConfigFactory.load()))
        instrumentationActor ! InstrumentationServiceMessage(metric)
        val received = udpProbe.receiveWhile(patience) {
          case Udp.Received(data, _) => data.utf8String
        }

        expectedPackets foreach { packet => if (!received.contains(packet)) fail(s"Missing packet: $packet") }
      }
  }

  private class UDPListenerActor(remote: InetSocketAddress, sendTo: ActorRef) extends Actor with ActorLogging {
    implicit val system =  context.system
    IO(Udp) ! Udp.Bind(sendTo, remote)

    def receive = {
      case Udp.Bound(_) => context.become(ready(sender()))
    }

    def ready(socket: ActorRef): Receive = {
      case Udp.Unbind  => socket ! Udp.Unbind
      case Udp.Unbound => context.stop(self)
      case other => log.error(s"received unexpected message: $other")
    }
  }
}


text:
'use strict';

var file = require('@ciscospark/test-helper-file');
var schemas = require('./schemas');
var primitives = require('./primitives');

/**
 * @param {Object} chai
 * @returns {undefined}
 */
module.exports = function registerAssertions(chai) {
  var Assertion = chai.Assertion;

  /* eslint no-unused-expressions: [0] */

  Assertion.addMethod('statusCode', function expectStatusCode(statusCode) {
    this.assert(
      (this._obj.statusCode || this._obj) === statusCode,
      'expected #{this} to have an HTTP Status Code of ' + statusCode,
      'expected #{this} to not have an HTTP Status Code of ' + statusCode
    );
  });

  chai.assert.statusCode = function assertStatusCode(obj, statusCode, msg) {
    new Assertion(obj, msg).to.have.statusCode(statusCode);
  };

  Assertion.addProperty('blobLike', function blobLike() {
    this.assert(
      file.isBlobLike(this._obj),
      'expected #{this} to be a Buffer (nodejs) or Blob (browser)',
      'expected #{this} not to be a Buffer (nodejs) or Blob (browser)'
    );
  });

  Assertion.addProperty('bufferLike', function bufferLike() {
    this.assert(
      file.isBufferLike(this._obj),
      'expected #{this} to be a Buffer (nodejs) or ArrayBuffer (browser)',
      'expected #{this} not to be a Buffer (nodejs) or ArrayBuffer (browser)'
    );
  });

  chai.assert.isBlobLike = function isBlobLike(obj, msg) {
    new Assertion(obj, msg).to.be.blobLike;
  };

  chai.assert.isNotBlobLike = function isNotBlobLike(obj, msg) {
    new Assertion(obj, msg).not.to.be.blobLike;
  };

  chai.assert.isBufferLike = function isBufferLike(obj, msg) {
    new Assertion(obj, msg).to.be.bufferLike;
  };

  chai.assert.isNotBufferLike = function isNotBufferLike(obj, msg) {
    new Assertion(obj, msg).not.to.be.bufferLike;
  };

  primitives(chai);
  schemas(chai);
};


text:
/* Driver for USB Mass Storage compliant devices
 * SCSI layer glue code
 *
 * Current development and maintenance by:
 *   (c) 1999-2002 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
 *
 * Developed with the assistance of:
 *   (c) 2000 David L. Brown, Jr. (usb-storage@davidb.org)
 *   (c) 2000 Stephen J. Gowdy (SGowdy@lbl.gov)
 *
 * Initial work by:
 *   (c) 1999 Michael Gee (michael@linuxspecific.com)
 *
 * This driver is based on the 'USB Mass Storage Class' document. This
 * describes in detail the protocol used to communicate with such
 * devices.  Clearly, the designers had SCSI and ATAPI commands in
 * mind when they created this document.  The commands are all very
 * similar to commands in the SCSI-II and ATAPI specifications.
 *
 * It is important to note that in a number of cases this class
 * exhibits class-specific exemptions from the USB specification.
 * Notably the usage of NAK, STALL and ACK differs from the norm, in
 * that they are used to communicate wait, failed and OK on commands.
 *
 * Also, for certain devices, the interrupt endpoint is used to convey
 * status of a command.
 *
 * Please see http://www.one-eyed-alien.net/~mdharm/linux-usb for more
 * information about this driver.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <linux/slab.h>
#include <linux/module.h>
#include <linux/mutex.h>

#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_devinfo.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_eh.h>

#include "usb.h"
#include "scsiglue.h"
#include "debug.h"
#include "transport.h"
#include "protocol.h"

/* Vendor IDs for companies that seem to include the READ CAPACITY bug
 * in all their devices
 */
#define VENDOR_ID_NOKIA		0x0421
#define VENDOR_ID_NIKON		0x04b0
#define VENDOR_ID_PENTAX	0x0a17
#define VENDOR_ID_MOTOROLA	0x22b8

/***********************************************************************
 * Host functions
 ***********************************************************************/

static const char* host_info(struct Scsi_Host *host)
{
	return "SCSI emulation for USB Mass Storage devices";
}

static int slave_alloc (struct scsi_device *sdev)
{
	struct us_data *us = host_to_us(sdev->host);

	/*
	 * Set the INQUIRY transfer length to 36.  We don't use any of
	 * the extra data and many devices choke if asked for more or
	 * less than 36 bytes.
	 */
	sdev->inquiry_len = 36;

	/* USB has unusual DMA-alignment requirements: Although the
	 * starting address of each scatter-gather element doesn't matter,
	 * the length of each element except the last must be divisible
	 * by the Bulk maxpacket value.  There's currently no way to
	 * express this by block-layer constraints, so we'll cop out
	 * and simply require addresses to be aligned at 512-byte
	 * boundaries.  This is okay since most block I/O involves
	 * hardware sectors that are multiples of 512 bytes in length,
	 * and since host controllers up through USB 2.0 have maxpacket
	 * values no larger than 512.
	 *
	 * But it doesn't suffice for Wireless USB, where Bulk maxpacket
	 * values can be as large as 2048.  To make that work properly
	 * will require changes to the block layer.
	 */
	blk_queue_update_dma_alignment(sdev->request_queue, (512 - 1));

	/*
	 * The UFI spec treates the Peripheral Qualifier bits in an
	 * INQUIRY result as reserved and requires devices to set them
	 * to 0.  However the SCSI spec requires these bits to be set
	 * to 3 to indicate when a LUN is not present.
	 *
	 * Let the scanning code know if this target merely sets
	 * Peripheral Device Type to 0x1f to indicate no LUN.
	 */
	if (us->subclass == US_SC_UFI)
		sdev->sdev_target->pdt_1f_for_no_lun = 1;

	return 0;
}

static int slave_configure(struct scsi_device *sdev)
{
	struct us_data *us = host_to_us(sdev->host);

	/* Many devices have trouble transfering more than 32KB at a time,
	 * while others have trouble with more than 64K. At this time we
	 * are limiting both to 32K (64 sectores).
	 */
	if (us->fflags & (US_FL_MAX_SECTORS_64 | US_FL_MAX_SECTORS_MIN)) {
		unsigned int max_sectors = 64;

		if (us->fflags & US_FL_MAX_SECTORS_MIN)
			max_sectors = PAGE_CACHE_SIZE >> 9;
		if (queue_max_sectors(sdev->request_queue) > max_sectors)
			blk_queue_max_sectors(sdev->request_queue,
					      max_sectors);
	} else if (sdev->type == TYPE_TAPE) {
		/* Tapes need much higher max_sector limits, so just
		 * raise it to the maximum possible (4 GB / 512) and
		 * let the queue segment size sort out the real limit.
		 */
		blk_queue_max_sectors(sdev->request_queue, 0x7FFFFF);
	}

	/* Some USB host controllers can't do DMA; they have to use PIO.
	 * They indicate this by setting their dma_mask to NULL.  For
	 * such controllers we need to make sure the block layer sets
	 * up bounce buffers in addressable memory.
	 */
	if (!us->pusb_dev->bus->controller->dma_mask)
		blk_queue_bounce_limit(sdev->request_queue, BLK_BOUNCE_HIGH);

	/* We can't put these settings in slave_alloc() because that gets
	 * called before the device type is known.  Consequently these
	 * settings can't be overridden via the scsi devinfo mechanism. */
	if (sdev->type == TYPE_DISK) {

		/* Some vendors seem to put the READ CAPACITY bug into
		 * all their devices -- primarily makers of cell phones
		 * and digital cameras.  Since these devices always use
		 * flash media and can be expected to have an even number
		 * of sectors, we will always enable the CAPACITY_HEURISTICS
		 * flag unless told otherwise. */
		switch (le16_to_cpu(us->pusb_dev->descriptor.idVendor)) {
		case VENDOR_ID_NOKIA:
		case VENDOR_ID_NIKON:
		case VENDOR_ID_PENTAX:
		case VENDOR_ID_MOTOROLA:
			if (!(us->fflags & (US_FL_FIX_CAPACITY |
					US_FL_CAPACITY_OK)))
				us->fflags |= US_FL_CAPACITY_HEURISTICS;
			break;
		}

		/* Disk-type devices use MODE SENSE(6) if the protocol
		 * (SubClass) is Transparent SCSI, otherwise they use
		 * MODE SENSE(10). */
		if (us->subclass != US_SC_SCSI && us->subclass != US_SC_CYP_ATACB)
			sdev->use_10_for_ms = 1;

		/* Many disks only accept MODE SENSE transfer lengths of
		 * 192 bytes (that's what Windows uses). */
		sdev->use_192_bytes_for_3f = 1;

		/* Some devices don't like MODE SENSE with page=0x3f,
		 * which is the command used for checking if a device
		 * is write-protected.  Now that we tell the sd driver
		 * to do a 192-byte transfer with this command the
		 * majority of devices work fine, but a few still can't
		 * handle it.  The sd driver will simply assume those
		 * devices are write-enabled. */
		if (us->fflags & US_FL_NO_WP_DETECT)
			sdev->skip_ms_page_3f = 1;

		/* A number of devices have problems with MODE SENSE for
		 * page x08, so we will skip it. */
		sdev->skip_ms_page_8 = 1;

		/* Some disks return the total number of blocks in response
		 * to READ CAPACITY rather than the highest block number.
		 * If this device makes that mistake, tell the sd driver. */
		if (us->fflags & US_FL_FIX_CAPACITY)
			sdev->fix_capacity = 1;

		/* A few disks have two indistinguishable version, one of
		 * which reports the correct capacity and the other does not.
		 * The sd driver has to guess which is the case. */
		if (us->fflags & US_FL_CAPACITY_HEURISTICS)
			sdev->guess_capacity = 1;

		/* assume SPC3 or latter devices support sense size > 18 */
		if (sdev->scsi_level > SCSI_SPC_2)
			us->fflags |= US_FL_SANE_SENSE;

		/* Some devices report a SCSI revision level above 2 but are
		 * unable to handle the REPORT LUNS command (for which
		 * support is mandatory at level 3).  Since we already have
		 * a Get-Max-LUN request, we won't lose much by setting the
		 * revision level down to 2.  The only devices that would be
		 * affected are those with sparse LUNs. */
		if (sdev->scsi_level > SCSI_2)
			sdev->sdev_target->scsi_level =
					sdev->scsi_level = SCSI_2;

		/* USB-IDE bridges tend to report SK = 0x04 (Non-recoverable
		 * Hardware Error) when any low-level error occurs,
		 * recoverable or not.  Setting this flag tells the SCSI
		 * midlayer to retry such commands, which frequently will
		 * succeed and fix the error.  The worst this can lead to
		 * is an occasional series of retries that will all fail. */
		sdev->retry_hwerror = 1;

		/* USB disks should allow restart.  Some drives spin down
		 * automatically, requiring a START-STOP UNIT command. */
		sdev->allow_restart = 1;

		/* Some USB cardreaders have trouble reading an sdcard's last
		 * sector in a larger then 1 sector read, since the performance
		 * impact is negible we set this flag for all USB disks */
		sdev->last_sector_bug = 1;

		/* Enable last-sector hacks for single-target devices using
		 * the Bulk-only transport, unless we already know the
		 * capacity will be decremented or is correct. */
		if (!(us->fflags & (US_FL_FIX_CAPACITY | US_FL_CAPACITY_OK |
					US_FL_SCM_MULT_TARG)) &&
				us->protocol == US_PR_BULK)
			us->use_last_sector_hacks = 1;
	} else {

		/* Non-disk-type devices don't need to blacklist any pages
		 * or to force 192-byte transfer lengths for MODE SENSE.
		 * But they do need to use MODE SENSE(10). */
		sdev->use_10_for_ms = 1;
	}

	/* The CB and CBI transports have no way to pass LUN values
	 * other than the bits in the second byte of a CDB.  But those
	 * bits don't get set to the LUN value if the device reports
	 * scsi_level == 0 (UNKNOWN).  Hence such devices must necessarily
	 * be single-LUN.
	 */
	if ((us->protocol == US_PR_CB || us->protocol == US_PR_CBI) &&
			sdev->scsi_level == SCSI_UNKNOWN)
		us->max_lun = 0;

	/* Some devices choke when they receive a PREVENT-ALLOW MEDIUM
	 * REMOVAL command, so suppress those commands. */
	if (us->fflags & US_FL_NOT_LOCKABLE)
		sdev->lockable = 0;

	/* this is to satisfy the compiler, tho I don't think the
	 * return code is ever checked anywhere. */
	return 0;
}

/* queue a command */
/* This is always called with scsi_lock(host) held */
static int queuecommand(struct scsi_cmnd *srb,
			void (*done)(struct scsi_cmnd *))
{
	struct us_data *us = host_to_us(srb->device->host);

	US_DEBUGP("%s called\n", __func__);

	/* check for state-transition errors */
	if (us->srb != NULL) {
		printk(KERN_ERR USB_STORAGE "Error in %s: us->srb = %p\n",
			__func__, us->srb);
		return SCSI_MLQUEUE_HOST_BUSY;
	}

	/* fail the command if we are disconnecting */
	if (test_bit(US_FLIDX_DISCONNECTING, &us->dflags)) {
		US_DEBUGP("Fail command during disconnect\n");
		srb->result = DID_NO_CONNECT << 16;
		done(srb);
		return 0;
	}

	/* enqueue the command and wake up the control thread */
	srb->scsi_done = done;
	us->srb = srb;
	complete(&us->cmnd_ready);

	return 0;
}

/***********************************************************************
 * Error handling functions
 ***********************************************************************/

/* Command timeout and abort */
static int command_abort(struct scsi_cmnd *srb)
{
	struct us_data *us = host_to_us(srb->device->host);

	US_DEBUGP("%s called\n", __func__);

	/* us->srb together with the TIMED_OUT, RESETTING, and ABORTING
	 * bits are protected by the host lock. */
	scsi_lock(us_to_host(us));

	/* Is this command still active? */
	if (us->srb != srb) {
		scsi_unlock(us_to_host(us));
		US_DEBUGP ("-- nothing to abort\n");
		return FAILED;
	}

	/* Set the TIMED_OUT bit.  Also set the ABORTING bit, but only if
	 * a device reset isn't already in progress (to avoid interfering
	 * with the reset).  Note that we must retain the host lock while
	 * calling usb_stor_stop_transport(); otherwise it might interfere
	 * with an auto-reset that begins as soon as we release the lock. */
	set_bit(US_FLIDX_TIMED_OUT, &us->dflags);
	if (!test_bit(US_FLIDX_RESETTING, &us->dflags)) {
		set_bit(US_FLIDX_ABORTING, &us->dflags);
		usb_stor_stop_transport(us);
	}
	scsi_unlock(us_to_host(us));

	/* Wait for the aborted command to finish */
	wait_for_completion(&us->notify);
	return SUCCESS;
}

/* This invokes the transport reset mechanism to reset the state of the
 * device */
static int device_reset(struct scsi_cmnd *srb)
{
	struct us_data *us = host_to_us(srb->device->host);
	int result;

	US_DEBUGP("%s called\n", __func__);

	/* lock the device pointers and do the reset */
	mutex_lock(&(us->dev_mutex));
	result = us->transport_reset(us);
	mutex_unlock(&us->dev_mutex);

	return result < 0 ? FAILED : SUCCESS;
}

/* Simulate a SCSI bus reset by resetting the device's USB port. */
static int bus_reset(struct scsi_cmnd *srb)
{
	struct us_data *us = host_to_us(srb->device->host);
	int result;

	US_DEBUGP("%s called\n", __func__);
	result = usb_stor_port_reset(us);
	return result < 0 ? FAILED : SUCCESS;
}

/* Report a driver-initiated device reset to the SCSI layer.
 * Calling this for a SCSI-initiated reset is unnecessary but harmless.
 * The caller must own the SCSI host lock. */
void usb_stor_report_device_reset(struct us_data *us)
{
	int i;
	struct Scsi_Host *host = us_to_host(us);

	scsi_report_device_reset(host, 0, 0);
	if (us->fflags & US_FL_SCM_MULT_TARG) {
		for (i = 1; i < host->max_id; ++i)
			scsi_report_device_reset(host, 0, i);
	}
}

/* Report a driver-initiated bus reset to the SCSI layer.
 * Calling this for a SCSI-initiated reset is unnecessary but harmless.
 * The caller must not own the SCSI host lock. */
void usb_stor_report_bus_reset(struct us_data *us)
{
	struct Scsi_Host *host = us_to_host(us);

	scsi_lock(host);
	scsi_report_bus_reset(host, 0);
	scsi_unlock(host);
}

/***********************************************************************
 * /proc/scsi/ functions
 ***********************************************************************/

/* we use this macro to help us write into the buffer */
#undef SPRINTF
#define SPRINTF(args...) \
	do { if (pos < buffer+length) pos += sprintf(pos, ## args); } while (0)

static int proc_info (struct Scsi_Host *host, char *buffer,
		char **start, off_t offset, int length, int inout)
{
	struct us_data *us = host_to_us(host);
	char *pos = buffer;
	const char *string;

	/* if someone is sending us data, just throw it away */
	if (inout)
		return length;

	/* print the controller name */
	SPRINTF("   Host scsi%d: usb-storage\n", host->host_no);

	/* print product, vendor, and serial number strings */
	if (us->pusb_dev->manufacturer)
		string = us->pusb_dev->manufacturer;
	else if (us->unusual_dev->vendorName)
		string = us->unusual_dev->vendorName;
	else
		string = "Unknown";
	SPRINTF("       Vendor: %s\n", string);
	if (us->pusb_dev->product)
		string = us->pusb_dev->product;
	else if (us->unusual_dev->productName)
		string = us->unusual_dev->productName;
	else
		string = "Unknown";
	SPRINTF("      Product: %s\n", string);
	if (us->pusb_dev->serial)
		string = us->pusb_dev->serial;
	else
		string = "None";
	SPRINTF("Serial Number: %s\n", string);

	/* show the protocol and transport */
	SPRINTF("     Protocol: %s\n", us->protocol_name);
	SPRINTF("    Transport: %s\n", us->transport_name);

	/* show the device flags */
	if (pos < buffer + length) {
		pos += sprintf(pos, "       Quirks:");

#define US_FLAG(name, value) \
	if (us->fflags & value) pos += sprintf(pos, " " #name);
US_DO_ALL_FLAGS
#undef US_FLAG

		*(pos++) = '\n';
	}

	/*
	 * Calculate start of next buffer, and return value.
	 */
	*start = buffer + offset;

	if ((pos - buffer) < offset)
		return (0);
	else if ((pos - buffer - offset) < length)
		return (pos - buffer - offset);
	else
		return (length);
}

/***********************************************************************
 * Sysfs interface
 ***********************************************************************/

/* Output routine for the sysfs max_sectors file */
static ssize_t show_max_sectors(struct device *dev, struct device_attribute *attr, char *buf)
{
	struct scsi_device *sdev = to_scsi_device(dev);

	return sprintf(buf, "%u\n", queue_max_sectors(sdev->request_queue));
}

/* Input routine for the sysfs max_sectors file */
static ssize_t store_max_sectors(struct device *dev, struct device_attribute *attr, const char *buf,
		size_t count)
{
	struct scsi_device *sdev = to_scsi_device(dev);
	unsigned short ms;

	if (sscanf(buf, "%hu", &ms) > 0 && ms <= SCSI_DEFAULT_MAX_SECTORS) {
		blk_queue_max_sectors(sdev->request_queue, ms);
		return strlen(buf);
	}
	return -EINVAL;
}

static DEVICE_ATTR(max_sectors, S_IRUGO | S_IWUSR, show_max_sectors,
		store_max_sectors);

static struct device_attribute *sysfs_device_attr_list[] = {
		&dev_attr_max_sectors,
		NULL,
		};

/*
 * this defines our host template, with which we'll allocate hosts
 */

struct scsi_host_template usb_stor_host_template = {
	/* basic userland interface stuff */
	.name =				"usb-storage",
	.proc_name =			"usb-storage",
	.proc_info =			proc_info,
	.info =				host_info,

	/* command interface -- queued only */
	.queuecommand =			queuecommand,

	/* error and abort handlers */
	.eh_abort_handler =		command_abort,
	.eh_device_reset_handler =	device_reset,
	.eh_bus_reset_handler =		bus_reset,

	/* queue commands only, only one command per LUN */
	.can_queue =			1,
	.cmd_per_lun =			1,

	/* unknown initiator id */
	.this_id =			-1,

	.slave_alloc =			slave_alloc,
	.slave_configure =		slave_configure,

	/* lots of sg segments can be handled */
	.sg_tablesize =			SG_ALL,

	/* limit the total size of a transfer to 120 KB */
	.max_sectors =                  240,

	/* merge commands... this seems to help performance, but
	 * periodically someone should test to see which setting is more
	 * optimal.
	 */
	.use_clustering =		1,

	/* emulated HBA */
	.emulated =			1,

	/* we do our own delay after a device or bus reset */
	.skip_settle_delay =		1,

	/* sysfs device attributes */
	.sdev_attrs =			sysfs_device_attr_list,

	/* module management */
	.module =			THIS_MODULE
};

/* To Report "Illegal Request: Invalid Field in CDB */
unsigned char usb_stor_sense_invalidCDB[18] = {
	[0]	= 0x70,			    /* current error */
	[2]	= ILLEGAL_REQUEST,	    /* Illegal Request = 0x05 */
	[7]	= 0x0a,			    /* additional length */
	[12]	= 0x24			    /* Invalid Field in CDB */
};
EXPORT_SYMBOL_GPL(usb_stor_sense_invalidCDB);


text:
from django.contrib import admin
from models import *

class MatchAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {'fields': ('game', 'state')}),
        )
    list_display = ('game', 'play_link')
admin.site.register(Match, MatchAdmin)


text:
const JSONPackageFile = require('./JSONPackageFile.js')

const typeURL = 'https://github.com/smeans/neo#NeoAuthorFile';

var self = module.exports = class Author {
  /** Check if given path is a neo author profile. */
  static isAuthor(filePath) {
    // !!!LATER!!! add verification of type URL
    return ['.naf'].indexOf(path.extname(filePath).toLowerCase()) > -1;
  }

  /** Construct a new Author from a JSONPackageFile path. */
  constructor(filePath) {
    this.jpf = new JSONPackageFile(filePath, typeURL);
  }

  /** Attempts to return the author's first name. */
  get firstName() {
    var names = this.metadata.fullName.split(/\s+/);
    return names[0];
  }

  get metadata() {
    return this.jpf.getChunk('jpf_metadata');
  }

  getPref(key) {
    var prefs = this.jpf.getChunk('neo_prefs');

    return prefs.values && prefs.values[key];
  }

  setPref(key, val) {
    var prefs = this.jpf.getChunk('neo_prefs');
    if (!('values' in prefs)) {
      prefs.values = {};
    }

    prefs.values[key] = val;

    this.jpf.write();
  }

  updateChunk(chunkType, fn) {
    this.jpf.updateChunk(chunkType, fn);
  }
}


text:
package bleve

import (
	"sort"
	"sync"

	"github.com/blevesearch/bleve/document"
	"github.com/blevesearch/bleve/search"
)

type indexAliasImpl struct {
	indexes []Index
	mutex   sync.RWMutex
	open    bool
}

// NewIndexAlias creates a new IndexAlias over the provided
// Index objects.
func NewIndexAlias(indexes ...Index) *indexAliasImpl {
	return &indexAliasImpl{
		indexes: indexes,
		open:    true,
	}
}

func (i *indexAliasImpl) isAliasToSingleIndex() error {
	if len(i.indexes) < 1 {
		return ErrorAliasEmpty
	} else if len(i.indexes) > 1 {
		return ErrorAliasMulti
	}
	return nil
}

func (i *indexAliasImpl) Index(id string, data interface{}) error {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return ErrorIndexClosed
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return err
	}

	return i.indexes[0].Index(id, data)
}

func (i *indexAliasImpl) Delete(id string) error {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return ErrorIndexClosed
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return err
	}

	return i.indexes[0].Delete(id)
}

func (i *indexAliasImpl) Batch(b *Batch) error {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return ErrorIndexClosed
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return err
	}

	return i.indexes[0].Batch(b)
}

func (i *indexAliasImpl) Document(id string) (*document.Document, error) {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil, ErrorIndexClosed
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return nil, err
	}

	return i.indexes[0].Document(id)
}

func (i *indexAliasImpl) DocCount() (uint64, error) {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	rv := uint64(0)

	if !i.open {
		return 0, ErrorIndexClosed
	}

	for _, index := range i.indexes {
		otherCount, err := index.DocCount()
		if err != nil {
			return 0, err
		}
		rv += otherCount
	}

	return rv, nil
}

func (i *indexAliasImpl) Search(req *SearchRequest) (*SearchResult, error) {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil, ErrorIndexClosed
	}

	if len(i.indexes) < 1 {
		return nil, ErrorAliasEmpty
	}

	// short circuit the simple case
	if len(i.indexes) == 1 {
		return i.indexes[0].Search(req)
	}

	return MultiSearch(req, i.indexes...)
}

func (i *indexAliasImpl) Fields() ([]string, error) {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil, ErrorIndexClosed
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return nil, err
	}

	return i.indexes[0].Fields()
}

func (i *indexAliasImpl) DumpAll() chan interface{} {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return nil
	}

	return i.indexes[0].DumpAll()
}

func (i *indexAliasImpl) DumpDoc(id string) chan interface{} {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return nil
	}

	return i.indexes[0].DumpDoc(id)
}

func (i *indexAliasImpl) DumpFields() chan interface{} {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return nil
	}

	return i.indexes[0].DumpFields()
}

func (i *indexAliasImpl) Close() error {
	i.mutex.Lock()
	defer i.mutex.Unlock()

	i.open = false
	return nil
}

func (i *indexAliasImpl) Mapping() *IndexMapping {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return nil
	}

	return i.indexes[0].Mapping()
}

func (i *indexAliasImpl) Stats() *IndexStat {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return nil
	}

	return i.indexes[0].Stats()
}

func (i *indexAliasImpl) GetInternal(key []byte) ([]byte, error) {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil, ErrorIndexClosed
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return nil, err
	}

	return i.indexes[0].GetInternal(key)
}

func (i *indexAliasImpl) SetInternal(key, val []byte) error {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return ErrorIndexClosed
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return err
	}

	return i.indexes[0].SetInternal(key, val)
}

func (i *indexAliasImpl) DeleteInternal(key []byte) error {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return ErrorIndexClosed
	}

	err := i.isAliasToSingleIndex()
	if err != nil {
		return err
	}

	return i.indexes[0].DeleteInternal(key)
}

func (i *indexAliasImpl) Add(indexes ...Index) {
	i.mutex.Lock()
	defer i.mutex.Unlock()

	i.indexes = append(i.indexes, indexes...)
}

func (i *indexAliasImpl) removeSingle(index Index) {
	for pos, in := range i.indexes {
		if in == index {
			i.indexes = append(i.indexes[:pos], i.indexes[pos+1:]...)
			break
		}
	}
}

func (i *indexAliasImpl) Remove(indexes ...Index) {
	i.mutex.Lock()
	defer i.mutex.Unlock()

	for _, in := range indexes {
		i.removeSingle(in)
	}
}

func (i *indexAliasImpl) Swap(in, out []Index) {
	i.mutex.Lock()
	defer i.mutex.Unlock()

	// add
	i.indexes = append(i.indexes, in...)

	// delete
	for _, ind := range out {
		i.removeSingle(ind)
	}
}

// MultiSearch executes a SearchRequest across multiple
// Index objects, then merges the results.
func MultiSearch(req *SearchRequest, indexes ...Index) (*SearchResult, error) {
	results := make(chan *SearchResult)
	errs := make(chan error)

	// remember the original from and size
	size := req.Size
	req.Size += req.From
	from := req.From
	req.From = 0

	// FIXME should create new request for
	// child queries, disable highlighting
	// and field loading
	// then, perform these steps only on
	// the final results

	// run search on each index in separate go routine
	var waitGroup sync.WaitGroup

	var searchChildIndex = func(waitGroup *sync.WaitGroup, in Index, results chan *SearchResult, errs chan error) {
		go func() {
			defer waitGroup.Done()
			searchResult, err := in.Search(req)
			if err != nil {
				errs <- err
			} else {
				results <- searchResult
			}
		}()
	}

	for _, in := range indexes {
		waitGroup.Add(1)
		searchChildIndex(&waitGroup, in, results, errs)
	}

	// on another go routine, close after finished
	go func() {
		waitGroup.Wait()
		close(results)
		close(errs)
	}()

	var sr *SearchResult
	var err error
	var result *SearchResult
	ok := true
	for ok {
		select {
		case result, ok = <-results:
			if ok {
				if sr == nil {
					// first result
					sr = result
				} else {
					// merge with previous
					sr.Merge(result)
				}
			}
		case err, ok = <-errs:
			// for now stop on any error
			// FIXME offer other behaviors
			if err != nil {
				return nil, err
			}
		}
	}

	// merge just concatenated all the hits
	// now lets clean it up

	// first sort it by score
	sort.Sort(sr.Hits)

	// now skip over the correct From
	req.From = from
	if req.From > 0 && len(sr.Hits) > req.From {
		sr.Hits = sr.Hits[req.From:]
	} else if req.From > 0 {
		sr.Hits = search.DocumentMatchCollection{}
	}

	// now trim to the correct size
	req.Size = size
	if req.Size > 0 && len(sr.Hits) > req.Size {
		sr.Hits = sr.Hits[0:req.Size]
	}

	// fix up facets
	for name, fr := range req.Facets {
		sr.Facets.Fixup(name, fr.Size)
	}

	return sr, nil
}


text:
@implementation MTDoctor

@end


text:
import {Directive, forwardRef} from '@angular/core';
import {Select} from '@ui-model/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';

const SELECT_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => SelectDirective),
  multi: true,
};

@Directive({
  selector: '[uiSelect]',
  exportAs: 'uiSelect',
  providers: [SELECT_VALUE_ACCESSOR],
})
export class SelectDirective<T> extends Select<T> implements ControlValueAccessor {
  constructor() {
    super();
  }

  protected changed(): void {
    super.changed();
    if (this._onChange) {
      this._onChange(this.selection);
    }
    this.touched();
  }

  protected touched(): void {
    if (this._onTouched) {
      this._onTouched();
    }
  }

  private _onChange: (value: T) => {};
  private _onTouched: () => {};

  writeValue(value: T): void {
    this.selection = value;
  }

  registerOnChange(fn: (value: T) => {}): void {
    this._onChange = fn;
  }

  registerOnTouched(fn: () => {}): void {
    this._onTouched = fn;
  }
}


text:
    <button type="button" class="navbar-toggle" ng-click="navCollapsed = !navCollapsed">
      Toggle navigation

    </button>

      Pypicloud

        {{ option.title }}

      Admin

        Simple

            Log in

              {{ USER }}

                Account

                Log out

            Account

            Log out


text:
Robot-Code
==========

Robot Code for team 1277


text: """ TODO: Write some tests """


text:
<?xml version="1.0" encoding="UTF-8"?>

DEXTROSE 50%- dextrose monohydrate liquid
Radix Laboratories, Inc.

Disclaimer: This drug has not been found by FDA to be safe and effective, and this labeling has not been approved by FDA. For further information about unapproved drugs, click here.

DEXTROSE MONOHYDRATE

• CONTENTS (grams/100ml):

Dextrose as monohydrate .....50

Inactives:

Purified Water  q.s.

Methylparaben

Propylparaben

Indications:

For use as a supplemental nutritive source of dextrose in cattle.

  Storage:

Store at controlled room temperature between 59oF to 86oF (15oC -30oC).

Warnings:

Avoid storage at cold temperatures which can cause product to become cloudy.

To clarify place product in warm water bath (100oF-120oF) for about 30 minutes.

Dosage and administration:

Administer orally as a drench or by use of a stomach tube.

The usual recommended dose in adult cattle is 16.9 fl. oz (500mL) to 33.8 fl.oz (1000mL) depending on size and condition.

Keep away from children.

Principal Display Panel

  Item image

DEXTROSE 50%

dextrose monohydrate liquid

Product Information

Product Type
OTC ANIMAL DRUG LABEL
Item Code (Source)
NDC:50480-132

Route of Administration
ORAL
DEA Schedule

Active Ingredient/Active Moiety

Ingredient Name
Basis of Strength
Strength

DEXTROSE MONOHYDRATE (ANHYDROUS DEXTROSE)
DEXTROSE MONOHYDRATE
50 g  in 100 mL

Packaging

#
Item Code
Package Description
Marketing Start Date
Marketing End Date

1
NDC:50480-132-50
12  in 1 CARTON

1

500 mL in 1 BOTTLE, PLASTIC

Marketing Information

Marketing Category
Application Number or Monograph Citation
Marketing Start Date
Marketing End Date

unapproved drug other

09/27/2013

Labeler - Radix Laboratories, Inc.
							(108500091)

Revised: 12/2014

Document Id: efc37da1-a732-4387-aaba-030049d014ec

Set id: fe237543-f1f9-42f9-a262-d34b581cfeb3

Version: 4

Effective Time: 20141223

Radix Laboratories, Inc.


text:
layout: page
show_meta: false
title: "pm"
subheadline: "转行产品经理中..."
permalink: "/pm/"
---
{% include list-posts.html category='pm' %}


text:
namespace pythonic
{

  namespace __dispatch__
  {
    template <class Any>
    auto conjugate(Any const &any) -> decltype(numpy::functor::conjugate{}(any))
    {
      return numpy::functor::conjugate{}(any);
    }

    DEFINE_FUNCTOR(pythonic::__dispatch__, conjugate);
  }
}

#endif


text:
Gets the value of a CloudFormation stack output.

 * `AWS_ACCESS_KEY_ID`: an AWS access key;
 * `AWS_SECRET_ACCESS_KEY`: the secret key for the above account.

Call as

    cloudformation-get-stack-output --region=<region> --stack-name <stack_name> --output-key-name <output_key_name>


text:
function genData(section)
{
	var data = [];
	for(i=0;i<5;i++){
		data.push({properties:{title:'Section '+section+' Item '+i, backgroundColor:'white'}})
	}

	return data;
}

function genSections()
{
	var sections = [];
	for(j=0;j<5;j++){
		var section = Ti.UI.createListSection({headerTitle:'Section '+j});
		section.setItems(genData(j));
		sections.push(section);
	}

	return sections;
}

function list_v2_ui_misc(_args) {
	var win = Ti.UI.createWindow({
		title:'Miscellaneous',
		layout:'vertical'
	});

	var b1 = Ti.UI.createButton({
		left:20,
		right:20,
		title:'Toggle canScroll'
	})

	var b2 = Ti.UI.createButton({
		left:20,
		right:20,
		top:10,
		title:'Toggle insets'
	})

	var listView = Ti.UI.createListView({
		sections: genSections(),
		top:10,
		backgroundColor:'red'
	})

	win.add(b1);
	win.add(b2);
	win.add(listView);

	var canScroll = true;
	var zeroInsets = true;
	var animate = true;
	b1.addEventListener('click',function(){
		canScroll = !canScroll;
		listView.canScroll = canScroll;
	})

	b2.addEventListener('click',function(){
		if (zeroInsets == true) {
			listView.setContentInsets({top:20,bottom:20}, {animated:animate})
		} else {
			listView.setContentInsets({top:0,left:0,right:0,bottom:0}, {animated:animate});
			animate = !animate;
		}
		zeroInsets = !zeroInsets;
	})

	return win;
};

module.exports = list_v2_ui_misc;


text:
create table #dblib0024 (i int not null, s char(10) not null)
go
insert into #dblib0024 values (0, 'row 000')
go
insert into #dblib0024 values (1, 'row 001')
go
insert into #dblib0024 values (2, 'row 002')
go
insert into #dblib0024 values (3, 'row 003')
go
insert into #dblib0024 values (4, 'row 004')
go
insert into #dblib0024 values (5, 'row 005')
go
insert into #dblib0024 values (6, 'row 006')
go
insert into #dblib0024 values (7, 'row 007')
go
insert into #dblib0024 values (8, 'row 008')
go
insert into #dblib0024 values (9, 'row 009')
go
select count(*) from #dblib0024 -- order by i
go
select count(*) from sysusers
select name from sysobjects
go


text:
import logging
from django.db import migrations

logger = logging.getLogger()

def update_bearing_manufacturer(apps, schema_editor):
    Bearing = apps.get_model('bearing', 'Bearing')
    BearingManufacturer = apps.get_model('bearing', 'BearingManufacturer')
    for item in Bearing.objects.all():
        try:
            item.manufacturer = BearingManufacturer.objects.get(name=item.cipher)
            item.save()
        except BearingManufacturer.DoesNotExist:
            logger.error('Cipher %s does not exists' % item.cipher)

class Migration(migrations.Migration):

    dependencies = [
        ('bearing', '0012_create_manufacturers'),
    ]

    operations = [
        migrations.RunPython(update_bearing_manufacturer),
    ]


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CheckinStudent extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('checkin_student', function (Blueprint $table) {
            $table->integer('checkin_id')->unsigned()->index();
            $table->foreign('checkin_id')->references('id')->on('checkins')->onDelete('cascade');

            $table->integer('student_id')->unsigned()->index();
            $table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('checkin_student');
    }
}


text:
package org.kie.workbench.common.stunner.core.client.canvas.resources;

import org.jboss.errai.ui.shared.api.annotations.TranslationKey;

public class StunnerClientCommonConstants {

    @TranslationKey(defaultValue = "")
    public static final String DeleteNodeConfirmationImpl_ConfirmationDescription = "DeleteNodeConfirmationDialogImpl.ConfirmationDescription";

    @TranslationKey(defaultValue = "")
    public static final String DeleteNodeConfirmationImpl_Question = "DeleteNodeConfirmationDialogImpl.Question";

    @TranslationKey(defaultValue = "")
    public static final String DeleteNodeConfirmationImpl_Title = "DeleteNodeConfirmationDialogImpl.Title";
}


text:
/**
 * It provides an exception to be used in general-purpose search.
 */
package tubame.wsearch.ui.ex;


text:
<res:CQLQueryResults targetClassname="gov.nih.nci.cacoresdk.domain.inheritance.multiplechild.UndergraduateStudent" xmlns:res="http://CQL.caBIG/2/org.cagrid.cql2.results">
 <res:ObjectResult>
  <ns1:UndergraduateStudent xmlns:ns1="gme://caCORE.caCORE/3.2/gov.nih.nci.cacoresdk.domain.inheritance.multiplechild">
   <ns1:id displayable="true" extension="1" reliability="ISS" root="2.16.12.123.456.1" scope="OBJ" xsi:type="ns2:II" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="uri:iso.org:21090"/>
   <ns1:name value="Student_Name1" xsi:type="ns3:ST" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="uri:iso.org:21090"/>
  </ns1:UndergraduateStudent>
 </res:ObjectResult>
 <res:ObjectResult>
  <ns1:UndergraduateStudent xmlns:ns1="gme://caCORE.caCORE/3.2/gov.nih.nci.cacoresdk.domain.inheritance.multiplechild">
   <ns1:id displayable="true" extension="2" reliability="ISS" root="2.16.12.123.456.1" scope="OBJ" xsi:type="ns2:II" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="uri:iso.org:21090"/>
   <ns1:name value="Student_Name2" xsi:type="ns3:ST" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="uri:iso.org:21090"/>
  </ns1:UndergraduateStudent>
 </res:ObjectResult>
 <res:ObjectResult>
  <ns1:UndergraduateStudent xmlns:ns1="gme://caCORE.caCORE/3.2/gov.nih.nci.cacoresdk.domain.inheritance.multiplechild">
   <ns1:id displayable="true" extension="3" reliability="ISS" root="2.16.12.123.456.1" scope="OBJ" xsi:type="ns2:II" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="uri:iso.org:21090"/>
   <ns1:name value="Student_Name3" xsi:type="ns3:ST" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="uri:iso.org:21090"/>
  </ns1:UndergraduateStudent>
 </res:ObjectResult>
 <res:ObjectResult>
  <ns1:UndergraduateStudent xmlns:ns1="gme://caCORE.caCORE/3.2/gov.nih.nci.cacoresdk.domain.inheritance.multiplechild">
   <ns1:id displayable="true" extension="4" reliability="ISS" root="2.16.12.123.456.1" scope="OBJ" xsi:type="ns2:II" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="uri:iso.org:21090"/>
   <ns1:name value="Student_Name4" xsi:type="ns3:ST" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="uri:iso.org:21090"/>
  </ns1:UndergraduateStudent>
 </res:ObjectResult>
 <res:ObjectResult>
  <ns1:UndergraduateStudent xmlns:ns1="gme://caCORE.caCORE/3.2/gov.nih.nci.cacoresdk.domain.inheritance.multiplechild">
   <ns1:id displayable="true" extension="5" reliability="ISS" root="2.16.12.123.456.1" scope="OBJ" xsi:type="ns2:II" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="uri:iso.org:21090"/>
   <ns1:name value="Student_Name5" xsi:type="ns3:ST" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="uri:iso.org:21090"/>
  </ns1:UndergraduateStudent>
 </res:ObjectResult>
</res:CQLQueryResults>


text:
require 'test/unit'
require_relative '../lib/alnum'
require_relative './support/test_data'

class TestAlnum < Test::Unit::TestCase

  def test_amount_of_symbols
    assert_equal Alnum::SYMBOLS.length, SYMBOLS.length
  end

  def test_symbols_should_be_the_same
    assert_equal Alnum::SYMBOLS, SYMBOLS
  end

end


text:
<?php
namespace ConfigTree\Spec\ConfigTree\Tree;

use ConfigTree\Tree\ConfigTree;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class ConfigTreeSpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith(
            [
                'node1' => [
                    'node2' => 'value',
                    'node3' => 'value',
                    'node5' => [
                        'node6' => 'value'
                    ]
                ]
            ]
        );
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('ConfigTree\Tree\ConfigTree');
    }

    function it_can_become_an_array()
    {
        $this->toArray()->shouldBe(
            [
                'node1' => [
                    'node2' => 'value',
                    'node3' => 'value',
                    'node5' => [
                        'node6' => 'value'
                    ]
                ]
            ]
        );
    }

    function it_can_retrieve_values()
    {
        $this->getSettingFromPath('node1/node2')->shouldBe('value');
    }

    function it_can_throw_an_exception_if_config_option_not_set()
    {
        $this
            ->shouldThrow('\ConfigTree\Exception\ConfigTreeParamNotSet')
            ->during('getSettingFromPath', ['setting/not/set/in/file'])
        ;
    }

    function it_can_do_merging(ConfigTree $anotherConfigTree)
    {
        $otherConfigAsArray = [
            'node1' => [
                'node2' => 'value-that-should-override-other',
                'node4' => 'value-that-should-be-added'
            ]
        ];

        $expectedMergeResult = [
            'node1' => [
                'node2' => 'value-that-should-override-other',
                'node3' => 'value',
                'node4' => 'value-that-should-be-added',
                'node5' => [
                    'node6' => 'value'
                ],
            ]
        ];

        $anotherConfigTree->toArray()->willReturn($otherConfigAsArray);

        $this->withAnotherConfigTreeMergedIn($anotherConfigTree)->shouldBeLike(new ConfigTree($expectedMergeResult));
    }

    function it_can_return_subtrees()
    {
        $this->getSubtreeFromPath('node1/node5')->shouldBeLike(new ConfigTree(['node6' => 'value']));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <help><!-- If checked, EDA's error handling framework is disabled. --></help>
    <label><!-- Disable Error Handling --></label>
    <name>Disable_Error_Handling__c</name>
</CustomFieldTranslation>


text:
// -*- C++ -*-
// Module:  Log4CPLUS
// File:    socket.h
// Created: 1/2010
// Author:  Vaclav Haisman
//
//
//  Copyright (C) 2010-2015, Vaclav Haisman. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modifica-
//  tion, are permitted provided that the following conditions are met:
//
//  1. Redistributions of  source code must  retain the above copyright  notice,
//     this list of conditions and the following disclaimer.
//
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
//  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//  FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
//  APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
//  DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
//  OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
//  ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
//  (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
//  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/** @file
 * This header contains declaration internal to log4cplus. They must never be
 * visible from user accesible headers or exported in DLL/shared libray.
 */

#ifndef LOG4CPLUS_INTERNAL_SOCKET_H_
#define LOG4CPLUS_INTERNAL_SOCKET_H_

#include <log4cplus/config.hxx>

#if defined (LOG4CPLUS_HAVE_PRAGMA_ONCE)
#pragma once
#endif

#if ! defined (INSIDE_LOG4CPLUS)
#  error "This header must not be be used outside log4cplus' implementation files."
#endif

#if defined(_WIN32)
#include <log4cplus/config/windowsh-inc.h>
#endif
#include <log4cplus/helpers/socket.h>

#include <cerrno>
#ifdef LOG4CPLUS_HAVE_ERRNO_H
#include <errno.h>
#endif

#ifdef LOG4CPLUS_HAVE_UNISTD_H
#include <unistd.h>
#endif

#if defined (LOG4CPLUS_HAVE_NETDB_H)
#include <netdb.h>
#endif

namespace log4cplus {

namespace helpers {

#if defined(_WIN32)
typedef SOCKET os_socket_type;
os_socket_type const INVALID_OS_SOCKET_VALUE = INVALID_SOCKET;

struct ADDRINFOT_deleter
{
    void
    operator () (ADDRINFOA * ptr) const
    {
        FreeAddrInfoA(ptr);
    }

    void
    operator () (ADDRINFOW * ptr) const
    {
        FreeAddrInfoW(ptr);
    }
};

struct socket_closer
{
    void
    operator () (SOCKET s)
    {
        if (s && s != INVALID_OS_SOCKET_VALUE)
        {
            DWORD const eno = WSAGetLastError();
            ::closesocket(s);
            WSASetLastError(eno);
        }
    }
};

#else
typedef int os_socket_type;
os_socket_type const INVALID_OS_SOCKET_VALUE = -1;

struct addrinfo_deleter
{
    void
    operator () (struct addrinfo * ptr) const
    {
        freeaddrinfo(ptr);
    }
};

struct socket_closer
{
    void
    operator () (os_socket_type s)
    {
        if (s >= 0)
        {
            int const eno = errno;
            close(s);
            errno = eno;
        }
    }
};

#endif

struct socket_holder
{
    os_socket_type sock;

    socket_holder()
        : sock(INVALID_OS_SOCKET_VALUE)
    { }

    socket_holder(os_socket_type s)
        : sock(s)
    { }

    ~socket_holder()
    {
        socket_closer()(sock);
    }

    void
    reset(os_socket_type s = INVALID_OS_SOCKET_VALUE)
    {
        if (sock != INVALID_OS_SOCKET_VALUE)
            socket_closer()(sock);

        sock = s;
    }

    os_socket_type
    detach()
    {
        os_socket_type s = sock;
        sock = INVALID_OS_SOCKET_VALUE;
        return s;
    }

    socket_holder(socket_holder &&) = delete;
    socket_holder(socket_holder const &) = delete;

    socket_holder operator = (socket_holder &&) = delete;
    socket_holder operator = (socket_holder const &) = delete;
};

static inline
os_socket_type
to_os_socket (SOCKET_TYPE const & x)
{
    return static_cast<os_socket_type>(x);
}

static inline
SOCKET_TYPE
to_log4cplus_socket (os_socket_type const & x)
{
    return static_cast<SOCKET_TYPE>(x);
}

static inline
void
set_last_socket_error (int err)
{
    errno = err;
}

static inline
int
get_last_socket_error ()
{
    return errno;
}

} // namespace helpers {

} // namespace log4cplus {

#endif // LOG4CPLUS_INTERNAL_SOCKET_H_


text:
package com.orientechnologies.orient.core.sql.functions.conversion;

import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.sql.executor.LiveQueryListenerImpl;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.method.misc.OAbstractSQLMethod;

/**
 * ONLY FOR LIVE QUERY. Returns the value of current record (as an OResult) before it was updated.
 * Null if the record is new

 * eg. on update, get only records whose "name" attribute was update
 * db.live("select from Person where @this.beforeUpdate().name != name
 *
 *
 * @author Luigi Dell'Aquila (l.dellaquila--(at)--orientdb.com)
 */
public class OSQLMethodBeforeUpdate extends OAbstractSQLMethod {

  public static final String NAME = "beforeUpdate";

  public OSQLMethodBeforeUpdate() {
    super(NAME, 0, 0);
  }

  @Override
  public String getSyntax() {
    return "beforeUpdate()";
  }

  @Override
  public Object execute(
      Object iThis,
      OIdentifiable iCurrentRecord,
      OCommandContext iContext,
      Object ioResult,
      Object[] iParams) {
    if (iThis instanceof OResult) {
      return ((OResult) iThis).getMetadata(LiveQueryListenerImpl.BEFORE_METADATA_KEY);
    }
    return null;
  }
}


text:
{-# LANGUAGE OverloadedStrings #-}
module Bead.View.Content.CourseOverview.Page (
    courseOverview
  ) where

import           Control.Monad.IO.Class
import           Data.String (fromString)
import           Data.Time (UTCTime, getCurrentTime)

import qualified Bead.Controller.UserStories as Story
import           Bead.View.Content
import qualified Bead.View.Content.Bootstrap as Bootstrap
import           Bead.View.RequestParams
import           Bead.View.Content.SubmissionTable

data PageData
  = CourseSubmissions UTCTime SubmissionTableContext SubmissionTableInfo

pageDataCata
  courseSubmissions
  p = case p of
    CourseSubmissions now stc sti -> courseSubmissions now stc sti

courseOverview :: ViewHandler
courseOverview = ViewHandler courseSubmissionsPage

courseSubmissionsPage :: GETContentHandler
courseSubmissionsPage = do
  ck <- getParameter (customCourseKeyPrm courseKeyParamName)
  now <- liftIO $ getCurrentTime
  (stc,sti) <- userStory $ do
    stc <- submissionTableContext
    sti <- sortUserLines <$> Story.courseSubmissionTable ck
    return (stc, sti)
  return . content $ CourseSubmissions now stc sti

content :: PageData -> IHtml
content = pageDataCata courseSubmissionsContent

courseSubmissionsContent :: UTCTime -> SubmissionTableContext -> SubmissionTableInfo -> IHtml
courseSubmissionsContent now c s = do
  msg <- getI18N
  return $ do
    Bootstrap.rowColMd12 $
      fromString  . msg $ msg_Home_SubmissionTable_Info $ concat
        [ "Assignments may be modified by clicking on their identifiers if you have rights for the modification (their names are shown in the tooltip).  "
        , "Students may be unregistered from the courses or the groups by checking the boxes in the Remove column "
        , "then clicking on the button."
        ]
    i18n msg $ submissionTable "course-table" now c s


text:
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { RouterModule, Routes } from '@angular/router'
import { SessionListingComponent } from './session-listing.component'
import { HttpClientModule } from '@angular/common/http'
import { WorkspaceComponent } from '../workspace/workspace.component'

describe('SessionListingComponent', () => {
  let component: SessionListingComponent
  let fixture: ComponentFixture<SessionListingComponent>
  const appRoutes: Routes = [{ path: 'workspace', component: WorkspaceComponent }]

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [SessionListingComponent],
      imports: [HttpClientModule, RouterModule.forRoot(appRoutes)],
    }).compileComponents()
  })

  beforeEach(() => {
    fixture = TestBed.createComponent(SessionListingComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
  })

  it('should create', () => {
    expect(component).toBeTruthy()
  })
})


text:
<?php
require_once dirname(dirname(dirname(__FILE__))).'/index.php';
$modx->request->handleRequest(array('location' => 'element/plugin/event'));


text:
<changes>
    <change>
        <version>1.0.0</version>
        <tasks>
            <task>
                <taskName>Create DB</taskName>
                <script>
                    create table test(version integer, test date);
                    alter table test add column another varchar(64);
                    create table second(version varchar(64))
                </script>
                <type>ScriptTask</type>
            </task>
        </tasks>
    </change>
    <change>
        <version>1.0.1</version>
        <tasks>
            <task>
                <taskName>Fix Bug</taskName>
                <taskOrder>1</taskOrder>
                <filePath>src\test\files\test.sql</filePath>
                <type>FileTask</type>
            </task>
        </tasks>
    </change>
    <change>
        <version>1.1.0</version>
        <tasks>
            <task>
                <taskName>Add Feature</taskName>
                <filePath>classpath:classpathTest.sql</filePath>
                <type>FileTask</type>
            </task>
        </tasks>
    </change>
    <change>
        <version>1.2.0</version>
        <tasks>
            <task>
                <taskName>New Version</taskName>
                <taskOrder>1</taskOrder>
            </task>
            <task>
                <taskName>Security Fix</taskName>
                <taskOrder>2</taskOrder>
            </task>
        </tasks>
    </change>
</changes>