text:
//Copyright 2017 Alexander Kaschta
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.

package de.codeteddy.robotics.first;

import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.MotorSafety;
import edu.wpi.first.wpilibj.MotorSafetyHelper;
import edu.wpi.first.wpilibj.PWM;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.hal.HAL;

import com.ctre.CANTalon;

/**
 * This is an advanced version of the RobotDrive of the WPILIB for FIRST, that is able
 * to control a robot with 6 motors, 3 on each side
 * @author Alexander Kaschta
 * @version 1.0
 * @since 2017-02-05
 *
 */
public class AdvancedRobotDrive implements MotorSafety {

    protected MotorSafetyHelper m_safetyHelper;
    public static final double kDefaultExpirationTime = 0.1D;
    public static final double kDefaultSensitivity = 0.5D;
    public static final double kDefaultMaxOutput = 1.0D;
    protected static final int kMaxNumberOfMotors = 4;
    protected double m_sensitivity;
    protected double m_maxOutput;
    protected SpeedController m_left1;
    protected SpeedController m_left2;
    protected SpeedController m_left3;
    protected SpeedController m_rigth1;
    protected SpeedController m_rigth2;
    protected SpeedController m_rigth3;
    protected boolean m_allocatedSpeedControllers;

    /**
     * This interface is used in the code and other methods to identify a single motor
     * @author Alexander Kaschta
     *
     */
    public static enum MotorType {
        kLeft1(0), kLeft2(1), kLeft3(2), kRigth4(3), kRigth5(4), kRigth6(5);

        public final int value;

        private MotorType(int value) {
            this.value = value;
        }
    }

    protected static boolean kArcadeRatioCurve_Reported = false;
    protected static boolean kTank_Reported = false;
    protected static boolean kArcadeStandard_Reported = false;
    protected static boolean kMecanumCartesian_Reported = false;
    protected static boolean kMecanumPolar_Reported = false;

    /**
     * Constructor of the AdvancedRobotDrive that takes the port numbers of the motors.
     *
     * @author Alexander Kaschta
     * @param left1 Port number of the first motor on the left side
     * @param left2	Port number of the second motor on the left side
     * @param left3 Port number of the third motor on the left side
     * @param rigth4 Port number of the first motor on the right side
     * @param rigth5 Port number of the second motor on the right side
     * @param rigth6 Port number of the third motor on the right side
     */
    public AdvancedRobotDrive(int left1, int left2, int left3, int rigth4, int rigth5, int rigth6) //AK
    {
        this.m_sensitivity = 0.5D;
        this.m_maxOutput = 1.0D;
        this.m_left1 = new Talon(left1);
        this.m_left2 = new Talon(left2);
        this.m_left3 = new Talon(left3);
        this.m_rigth1 = new Talon(rigth4);
        this.m_rigth2 = new Talon(rigth5);
        this.m_rigth3 = new Talon(rigth6);
        this.m_allocatedSpeedControllers = true;
        setupMotorSafety();
    }

    /**
     * Constructor that takes CANTalon objects instead port numbers.
     * This can be used nice, when you use a RobotMap, where you contain all of your robot
     * parts.
     *
     * @author Alexander Kaschta
     * @param left1 CANTalon, that is the first motor on the left side
     * @param left2	CANTalon, that is the second motor on the left side
     * @param left3 CANTalon, that is the third motor on the left side
     * @param rigth4 CANTalon, that is the first motor on the right side
     * @param rigth5 CANTalon, that is the second motor on the right side
     * @param rigth6 CANTalon, that is the third motor on the right side
     */
    public AdvancedRobotDrive(CANTalon left1, CANTalon left2 ,CANTalon left3, CANTalon rigth4, CANTalon rigth5, CANTalon rigth6){
    	this.m_sensitivity = 0.5D;
        this.m_maxOutput = 1.0D;
        this.m_left1 = left1;
        this.m_left2 = left2;
        this.m_left3 = left3;
        this.m_rigth1 = rigth4;
        this.m_rigth2 = rigth5;
        this.m_rigth3 = rigth6;
        this.m_allocatedSpeedControllers = true;
        setupMotorSafety();
    }

    /**
     * Constructor that takes Talon objects instead port numbers.
     * This can be used nice, when you use a RobotMap, where you contain all of your robot
     * parts.
     *
     * @author Alexander Kaschta
     * @param left1 Talon, that is the first motor on the left side
     * @param left2	Talon, that is the second motor on the left side
     * @param left3 Talon, that is the third motor on the left side
     * @param rigth4 Talon, that is the first motor on the right side
     * @param rigth5 Talon, that is the second motor on the right side
     * @param rigth6 Talon, that is the third motor on the right side
     */
    public AdvancedRobotDrive(Talon left1, Talon left2 ,Talon left3, Talon rigth4, Talon rigth5, Talon rigth6){
    	this.m_sensitivity = 0.5D;
        this.m_maxOutput = 1.0D;
        this.m_left1 = left1;
        this.m_left2 = left2;
        this.m_left3 = left3;
        this.m_rigth1 = rigth4;
        this.m_rigth2 = rigth5;
        this.m_rigth3 = rigth6;
        this.m_allocatedSpeedControllers = true;
        setupMotorSafety();
    }

    /**
     * This uses two joysticks to control the robot like a tank
     * @author Alexander Kaschta
     * @exception NullPointerException Null HID provided
     * @param leftStick stick for the left motors
     * @param rightStick stick for the right motors
     */
    public void tankDrive(GenericHID leftStick, GenericHID rightStick) {
        if ((leftStick == null) || (rightStick == null)) {
            throw new NullPointerException("Null HID provided");
        }
        tankDrive(leftStick.getY(), rightStick.getY(), true);
    }

    /**
     * This uses two joysticks to control the robot like a tank
     * @author Alexander Kaschta
     * @param leftValue joystick for the left motors
     * @param rightValue joystick for the right motors
     * @param squaredInputs are the input values already squared?
     * @exception NullPointerException Null HID provided
     */
    public void tankDrive(GenericHID leftStick, GenericHID rightStick, boolean squaredInputs) {
        if ((leftStick == null) || (rightStick == null)) {
            throw new NullPointerException("Null HID provided");
        }
        tankDrive(leftStick.getY(), rightStick.getY(), squaredInputs);
    }

    /**
     * This uses two joysticks to control the robot like a tank
     * @author Alexander Kaschta
     * @param leftStick joystick for the left motors
     * @param leftAxis index of the axis of that joystick
     * @param rightStick joystick for the right motors
     * @param rightAxis index of the axis of that joystick
     * @exception NullPointerException Null HID provided
     */
    public void tankDrive(GenericHID leftStick, int leftAxis, GenericHID rightStick, int rightAxis) {
        if ((leftStick == null) || (rightStick == null)) {
            throw new NullPointerException("Null HID provided");
        }
        tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), true);
    }

    /**
     * This uses two joysticks to control the robot like a tank
     * @author Alexander Kaschta
     * @param leftStick joystick for the left motors
     * @param leftAxis index of the axis of that joystick
     * @param rightStick joystick for the right motors
     * @param rightAxis index of the axis of that joystick
     * @param squaredInputs are the input values already squared?
     * @exception NullPointerException Null HID provided
     */
    public void tankDrive(GenericHID leftStick, int leftAxis, GenericHID rightStick, int rightAxis, boolean squaredInputs) {
        if ((leftStick == null) || (rightStick == null)) {
            throw new NullPointerException("Null HID provided");
        }
        tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), squaredInputs);
    }

    /**
     * Simple method to drive the robot like a tank
     * @author Alexander Kaschta
     * @param leftValue value for the left motors
     * @param rightValue value for the right motors
     * @param squaredInputs are the input values already squared?
     */
    public void tankDrive(double leftValue, double rightValue, boolean squaredInputs) {
        if (!kTank_Reported) {
            HAL.report(31, getNumMotors(), 4);

            kTank_Reported = true;
        }
        leftValue = limit(leftValue);
        rightValue = limit(rightValue);
        if (squaredInputs) {
            if (leftValue >= 0.0D) {
                leftValue *= leftValue;
            } else {
                leftValue = -(leftValue * leftValue);
            }
            if (rightValue >= 0.0D) {
                rightValue *= rightValue;
            } else {
                rightValue = -(rightValue * rightValue);
            }
        }
        setLeftRightMotorOutputs(leftValue, rightValue);
    }

    /**
     * Simple method to drive the robot like a tank
     * @author Alexander Kaschta
     * @param leftValue value for the left motors
     * @param rightValue value for the right motors
     */
    public void tankDrive(double leftValue, double rightValue) {
        tankDrive(leftValue, rightValue, true);
    }

    /**
     * Very simple arcade drive method that uses only one joystick to control the complete robot
     * @author Alexander Kaschta
     * @param stick joystick to control the robot
     * @param squaredInputs are the input values already squared?
     */
    public void arcadeDrive(GenericHID stick, boolean squaredInputs) {
        arcadeDrive(stick.getY(), stick.getX(), squaredInputs);
    }

    /**
     * Very simple arcade drive method that uses only one joystick to control the complete robot
     * @author Alexander Kaschta
     * @param stick joystick to control the robot
     */
    public void arcadeDrive(GenericHID stick) {
        arcadeDrive(stick, true);
    }

    /**
     * More customizable method to control the robot using arcade drive
     * @author Alexander Kaschta
     * @param moveStick joystick from which the value should be used to control the robot
     * @param moveAxis index of axis that should be used from the joystick moveStick
     * @param rotateStick joystick that should be used to control the rotation of the robot
     * @param rotateAxis index of the axis that should be used from the joystick rotateStick
     * @param squaredInputs are the input values already squared?
     */
    public void arcadeDrive(GenericHID moveStick, int moveAxis, GenericHID rotateStick, int rotateAxis, boolean squaredInputs) {
        double moveValue = moveStick.getRawAxis(moveAxis);
        double rotateValue = rotateStick.getRawAxis(rotateAxis);

        arcadeDrive(moveValue, rotateValue, squaredInputs);
    }

    /**
     * More customizable method to control the robot using arcade drive
     * @author Alexander Kaschta
     * @param moveStick joystick from which the value should be used to control the robot
     * @param moveAxis index of axis that should be used from the joystick moveStick
     * @param rotateStick joystick that should be used to control the rotation of the robot
     * @param rotateAxis index of the axis that should be used from the joystick rotateStick
     */
    public void arcadeDrive(GenericHID moveStick, int moveAxis, GenericHID rotateStick, int rotateAxis) {
        arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis, true);
    }

    /**
     * More advanced method to control the robot with just one joystick
     * @author Alexander Kaschta
     * @param moveValue value that show how much the robot should go forward (y-axis)
     * @param rotateValue value how much the robot should rotate (x-axis)
     * @param squaredInputs show's if the input values already had been squared (usually true)
     */
    public void arcadeDrive(double moveValue, double rotateValue, boolean squaredInputs) {
        if (!kArcadeStandard_Reported) {
            HAL.report(31, getNumMotors(), 1);

            kArcadeStandard_Reported = true;
        }

        moveValue = limit(moveValue);
        rotateValue = limit(rotateValue);

        if (squaredInputs) {
            if (moveValue >= 0.0D) {
                moveValue *= moveValue;
            } else {
                moveValue = -(moveValue * moveValue);
            }

            if (rotateValue >= 0.0D) {
                rotateValue *= rotateValue;
            } else {
                rotateValue = -(rotateValue * rotateValue);
            }
        }

        double rightMotorSpeed;
        double leftMotorSpeed;

        if (moveValue > 0.0D) {
            if (rotateValue > 0.0D) {
                leftMotorSpeed = moveValue - rotateValue;
                rightMotorSpeed = Math.max(moveValue, rotateValue);
            } else {
                leftMotorSpeed = Math.max(moveValue, -rotateValue);
                rightMotorSpeed = moveValue + rotateValue;
            }
        } else {

            if (rotateValue > 0.0D) {
                leftMotorSpeed = -Math.max(-moveValue, rotateValue);
                rightMotorSpeed = moveValue + rotateValue;
            } else {
                leftMotorSpeed = moveValue - rotateValue;
                rightMotorSpeed = -Math.max(-moveValue, -rotateValue);
            }
        }

        setLeftRightMotorOutputs(leftMotorSpeed, rightMotorSpeed);
    }

    /**
     * Method that uses values of only one joystick to drive the robot
     * @author Alexander Kaschta
     * @param moveValue value that show how much the robot should go forward (y-axis)
     * @param rotateValue value how much the robot should rotate (x-axis)
     */
    public void arcadeDrive(double moveValue, double rotateValue) {
        arcadeDrive(moveValue, rotateValue, true);
    }

    /**
     * Set's the output of the motors
     * @param leftOutput value for the motors on the left side
     * @param rightOutput value for the motors on the right side
     * @author Alexander Kaschta
     * @exception NullPointerException No motor provided
     */
    public void setLeftRightMotorOutputs(double leftOutput, double rightOutput) {
        if ((this.m_left1 == null) || (this.m_left2 == null) || (this.m_left3 == null)) {
            throw new NullPointerException("No motor provided");
        }
        if ((this.m_rigth1 == null) || (this.m_rigth2 == null) || (this.m_rigth3 == null)) {
            throw new NullPointerException("No motor is provided");
        }
        if (this.m_left1 != null) {
            this.m_left1.set(limit(leftOutput) * this.m_maxOutput);
        }
        if (this.m_left2 != null) {
            this.m_left2.set(limit(leftOutput) * this.m_maxOutput);
        }
        if (this.m_left3 != null) {
            this.m_left3.set(limit(leftOutput) * this.m_maxOutput);
        }
        if (this.m_rigth1 != null) {
            this.m_rigth1.set(-limit(rightOutput) * this.m_maxOutput);
        }
        if (this.m_rigth2 != null) {
            this.m_rigth2.set(-limit(rightOutput) * this.m_maxOutput);
        }
        if (this.m_rigth3 != null) {
            this.m_rigth3.set(-limit(rightOutput) * this.m_maxOutput);
        }

        if (this.m_safetyHelper != null) {
            this.m_safetyHelper.feed();
        }
    }

    /**
     * Method to check if input is in range
     * @param number to check
     * @return checked number
     * @author Alexander Kaschta
     */
    protected static double limit(double number) {
        if (number > 1.0D) {
            return 1.0D;
        }
        if (number < -1.0D) {
            return -1.0D;
        }
        return number;
    }

    /**
     * @deprecated
     * @author Alexander Kaschta
     * @param wheelSpeeds
     */
    protected static void normalize(double[] wheelSpeeds) {
        double maxMagnitude = Math.abs(wheelSpeeds[0]);
        for (int i = 1; i < 4; i++) {
            double temp = Math.abs(wheelSpeeds[i]);
            if (maxMagnitude < temp) {
                maxMagnitude = temp;
            }
        }
        if (maxMagnitude > 1.0D) {
            for (int i = 0; i < 4; i++) {
                wheelSpeeds[i] /= maxMagnitude;
            }
        }
    }

    /**
     * @author Alexander Kaschta
     * @deprecated
     * @param x
     * @param y
     * @param angle
     * @return
     */
    protected static double[] rotateVector(double x, double y, double angle) {
        double cosA = Math.cos(angle * 0.017453277777777776D);
        double sinA = Math.sin(angle * 0.017453277777777776D);
        double[] out = new double[2];
        out[0] = (x * cosA - y * sinA);
        out[1] = (x * sinA + y * cosA);
        return out;
    }

    /**
     * Method to invert a single motor
     * @author Alexander Kaschta
     * @param motor representing the motor you want to change
     * @param isInverted If should be inverted, true, else false
     * @exception IllegalArgumentException Illegal motor type
     */
    public void setInvertedMotor(MotorType motor, boolean isInverted) {
        switch (motor) {
            case kLeft1:
                this.m_left1.setInverted(isInverted);
                break;
            case kLeft2:
                this.m_left2.setInverted(isInverted);
                break;
            case kLeft3:
                this.m_left3.setInverted(isInverted);
                break;
            case kRigth4:
                this.m_rigth1.setInverted(isInverted);
                break;
            case kRigth5:
                this.m_rigth2.setInverted(isInverted);
                break;
            case kRigth6:
                this.m_rigth3.setInverted(isInverted);
                break;
            default:
                throw new IllegalArgumentException("Illegal motor type: " + motor);
        }
    }

    /**
     * This set's the sensitivity of the Motor safety (Standard is 0.5D).
     * @author Alexander Kaschta
     * @param sensitivity representing the sensitivity
     */
    public void setSensitivity(double sensitivity) {
        this.m_sensitivity = sensitivity;
    }

    /**
     * Method to change the maximum output for the Talons controlling the robot.
     * (Standard is 1)
     * @author Alexander Kaschta
     * @param maxOutput representing the maximum output for the motors
     */
    public void setMaxOutput(double maxOutput) {
        this.m_maxOutput = maxOutput;
    }

    /**
     * This method free's all PWM channels from their motors
     * @author Alexander Kaschta
     */
    public void free() {
        if (this.m_allocatedSpeedControllers) {
            if (this.m_left1 != null) {
                ((PWM) this.m_left1).free();
            }
            if (this.m_left2 != null) {
                ((PWM) this.m_left2).free();
            }
            if (this.m_left3 != null) {
                ((PWM) this.m_left3).free();
            }
            if (this.m_rigth1 != null) {
                ((PWM) this.m_rigth1).free();
            }
            if (this.m_rigth2 != null) {
                ((PWM) this.m_rigth2).free();
            }
            if (this.m_rigth3 != null) {
                ((PWM) this.m_rigth3).free();
            }
        }
    }

    /**
     * Method to set the timeout of the safety helper
     * @author Alexander Kaschta
     * @param timeout double value in seconds
     */
    public void setExpiration(double timeout) {
        this.m_safetyHelper.setExpiration(timeout);
    }

    /**
     * Method to get the timeout to which the safety helper is set
     * @author Alexander Kaschta
     * @return double containing the actual timeout value
     */
    public double getExpiration() {
        return this.m_safetyHelper.getExpiration();
    }

    /**
     * Returns a boolean telling you, if the safety helper is still alive
     * @author Alexander Kaschta
     * @return boolean, which is true, when the safety helper is alive
     * @see SafetyHelper
     */
    public boolean isAlive() {
        return this.m_safetyHelper.isAlive();
    }

    /**
     * Returns if safety is enabled on the robot
     * @author Alexander Kaschta
     * @return boolean containing the status, if the safety helper is enabled
     */
    public boolean isSafetyEnabled() {
        return this.m_safetyHelper.isSafetyEnabled();
    }

    /**
     * This method is used to enable or disable Safety on the Robot Drive. Put true to
     * enable, false to disable.
     * @param enabled Boolean that represents the status to which it should be changed to
     * @author Alexander Kaschta
     */
    public void setSafetyEnabled(boolean enabled) {
        this.m_safetyHelper.setSafetyEnabled(enabled);
    }

    /**
     * @author Alexander Kaschta
     * @return a String with a description of the function of the Advanced Robot Drive
     */
    public String getDescription() {
        return "Robot Drive";
    }

    /**
     * This method is used for getting the author of that code
     * @author Alexander Kaschta
     * @return String containing the name of the author
     */
    public String getAuthor(){
    	return "Alexander Kaschta";
    }

    /**
     * Stops all motors
     * @author Alexander Kaschta
     */
    public void stopMotor() {
        if (this.m_left1 != null) {
            this.m_left1.stopMotor();
        }
        if (this.m_left2 != null) {
            this.m_left2.stopMotor();
        }
        if (this.m_left3 != null) {
            this.m_left3.stopMotor();
        }
        if (this.m_rigth1 != null) {
            this.m_rigth1.stopMotor();
        }
        if (this.m_rigth2 != null) {
            this.m_rigth2.stopMotor();
        }
        if (this.m_rigth3 != null) {
            this.m_rigth3.stopMotor();
        }
        if (this.m_safetyHelper != null) {
            this.m_safetyHelper.feed();
        }
    }

    /**
     * Enables motor safety for the robot
     * @author Alexander Kaschta
     */
    private void setupMotorSafety() {
        this.m_safetyHelper = new MotorSafetyHelper(this);
        this.m_safetyHelper.setExpiration(0.1D);
        this.m_safetyHelper.setSafetyEnabled(true);
    }

    /**
     * Method to figure out, how much motors does the RobotDrive has
     * @return Number of Motors on the robot
     * @author Alexander Kaschta
     */
    protected int getNumMotors() {
        int motors = 0;
        if (this.m_left1 != null) {
            motors++;
        }
        if (this.m_left2 != null) {
            motors++;
        }
        if (this.m_left3 != null) {
            motors++;
        }
        if (this.m_rigth1 != null) {
            motors++;
        }
        if (this.m_rigth2 != null) {
            motors++;
        }
        if (this.m_rigth3 != null) {
            motors++;
        }
        return motors;
    }
}


text:
@interface IDEBatchFindStatusCell : NSActionCell
{
}

- (void)drawInteriorWithFrame:(struct CGRect)arg1 inView:(id)arg2;
- (struct CGSize)cellSizeForBounds:(struct CGRect)arg1;

@end

redpajama_set_name: RedPajamaGithub


text:
package com.pineone.icbms.so.resources.vo;

import java.io.Serializable;

/**
 * Generic virtual object.<BR/>
 * Created by uni4love on 2015. 10. 7..
 */
abstract public class AGenericVirtualObject implements IGenericVirtualObject, Serializable
{
    /**
     * id
     */
    protected String id = null;

    /**
     * name
     */
    protected String name = null;

    @Override
    public String getId()
    {
        return this.id;
    }

    public void setId(String id)
    {
        this.id = id;
    }

    @Override
    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    @Override
    public String toString()
    {
        StringBuffer sb = new StringBuffer();
        sb.append("\nid: ").append(id);
        sb.append("\nname: ").append(name);
        return sb.toString();
    }
}


text:
Imports DotNetNuke.Data
Imports DotNetNuke.Framework
Imports System.Collections.Generic
imports System.ComponentModel

Namespace Connect.Modules.Kickstart.Entities

	<DataObject(True)> _
	Public Class ProjectController

#Region "Private Methods"
        Public Shared Function GetNull(ByVal Field As Object) As Object
            Return DotNetNuke.Common.Utilities.Null.GetNull(Field, DBNull.Value)
        End Function
#End Region

#Region "Public Methods"

        Public Shared Function [Get](ByVal projectId As Integer) As ProjectInfo

            Return CType(CBO.FillObject(DotNetNuke.Data.DataProvider.Instance().ExecuteReader("Connect_Kickstart_Project_Get", projectId), GetType(ProjectInfo)), ProjectInfo)

        End Function

        <DataObjectMethod(DataObjectMethodType.Select, True)> _
        Public Shared Function [List]() As List(Of ProjectInfo)

            Return CBO.FillCollection(Of ProjectInfo)(CType(DotNetNuke.Data.DataProvider.Instance().ExecuteReader("Connect_Kickstart_Project_List"), IDataReader))

        End Function

        <DataObjectMethod(DataObjectMethodType.Select, True)> _
        Public Shared Function [PublicProjectCount](ByVal ModuleId As Integer) As Integer

            Return DotNetNuke.Data.DataProvider.Instance().ExecuteScalar(Of Integer)("Connect_Kickstart_Project_GetPublicProjectCount", ModuleId)

        End Function

        <DataObjectMethod(DataObjectMethodType.Select, True)> _
        Public Shared Function [PublicList](ByVal ModuleId As Integer, ByVal SortColumn As String, ByVal PageNo As Integer, RecordsPerPage As Integer, IsVisible As Integer, IsDeleted As Integer, CreatedBy As Integer, LeadBy As Integer) As List(Of ProjectInfo)

            Return CBO.FillCollection(Of ProjectInfo)(CType(DotNetNuke.Data.DataProvider.Instance().ExecuteReader("Connect_Kickstart_Project_GetPageByModules", SortColumn, PageNo, RecordsPerPage, ModuleId, GetNull(IsVisible), GetNull(IsDeleted), GetNull(CreatedBy), GetNull(LeadBy)), IDataReader))

        End Function

        <DataObjectMethod(DataObjectMethodType.Insert, True)> _
        Public Shared Function Add(ByVal objProjectInfo As ProjectInfo) As Integer

            Return DotNetNuke.Data.DataProvider.Instance().ExecuteScalar(Of Integer)("Connect_Kickstart_Project_Add", objProjectInfo.ModuleId, objProjectInfo.ContentItemId, objProjectInfo.Status, objProjectInfo.Subject, objProjectInfo.Summary, objProjectInfo.Content, GetNull(objProjectInfo.ProjectUrl), GetNull(objProjectInfo.ProjectPlatform), GetNull(objProjectInfo.PlatformRssUrl), GetNull(objProjectInfo.DateScheduled), GetNull(objProjectInfo.DateDelivered), objProjectInfo.DateCreated, GetNull(objProjectInfo.DateLocked), GetNull(objProjectInfo.DateDeleted), objProjectInfo.CreatedBy, GetNull(objProjectInfo.LockedBy), GetNull(objProjectInfo.DeletedBy), GetNull(objProjectInfo.LeadBy), objProjectInfo.IsVisible, objProjectInfo.IsLocked, objProjectInfo.IsDeleted, objProjectInfo.IsDelivered, objProjectInfo.Views, objProjectInfo.Comments, objProjectInfo.Votes, objProjectInfo.TeamMembers)

        End Function

        <DataObjectMethod(DataObjectMethodType.Update, True)> _
        Public Shared Sub Update(ByVal objProjectInfo As ProjectInfo)

            DotNetNuke.Data.DataProvider.Instance().ExecuteNonQuery("Connect_Kickstart_Project_Update", objProjectInfo.ProjectId, objProjectInfo.ModuleId, objProjectInfo.ContentItemId, objProjectInfo.Status, objProjectInfo.Subject, objProjectInfo.Summary, objProjectInfo.Content, GetNull(objProjectInfo.ProjectUrl), GetNull(objProjectInfo.ProjectPlatform), GetNull(objProjectInfo.PlatformRssUrl), GetNull(objProjectInfo.DateScheduled), GetNull(objProjectInfo.DateDelivered), objProjectInfo.DateCreated, GetNull(objProjectInfo.DateLocked), GetNull(objProjectInfo.DateDeleted), objProjectInfo.CreatedBy, GetNull(objProjectInfo.LockedBy), GetNull(objProjectInfo.DeletedBy), GetNull(objProjectInfo.LeadBy), objProjectInfo.IsVisible, objProjectInfo.IsLocked, objProjectInfo.IsDeleted, objProjectInfo.IsDelivered, objProjectInfo.Views, objProjectInfo.Comments, objProjectInfo.Votes, objProjectInfo.TeamMembers)
        End Sub

        Public Shared Sub Lock(objProject As ProjectInfo, UserId As Integer)
            objProject.IsLocked = True
            objProject.LockedBy = UserId
            objProject.DateLocked = Date.Now
            Update(objProject)
        End Sub

        Public Shared Sub UnLock(objProject As ProjectInfo, UserId As Integer)
            objProject.IsLocked = False
            objProject.LockedBy = Null.NullInteger
            objProject.DateLocked = Null.NullDate
            Update(objProject)
        End Sub

        Public Shared Sub Delete(objProject As ProjectInfo, UserId As Integer)
            objProject.IsDeleted = True
            objProject.DeletedBy = UserId
            objProject.DateDeleted = Date.Now
            Update(objProject)
        End Sub

        Public Shared Sub Restore(objProject As ProjectInfo, UserId As Integer)
            objProject.IsDeleted = False
            objProject.DeletedBy = Null.NullInteger
            objProject.DateDeleted = Null.NullDate
            Update(objProject)
        End Sub

        <DataObjectMethod(DataObjectMethodType.Delete, True)> _
        Public Shared Sub HardDelete(ByVal ProjectId As Integer)

            DotNetNuke.Data.DataProvider.Instance().ExecuteNonQuery("Connect_Kickstart_Project_Delete", ProjectId)

        End Sub

#End Region

	End Class

End Namespace


text:
.monaco-workbench-container {
	position: absolute;
}

.monaco-workbench {
	font-size: 13px;
	line-height: 1.4em;
	position: relative;
	z-index: 1;
	overflow: hidden;
}

.monaco-workbench > .part {
	position: absolute;
	box-sizing:	border-box;
}

.monaco-workbench .monaco-action-bar .select-box {
	margin-top: 8px; /* Center the select box */
}

.monaco-workbench.windows .monaco-action-bar .select-box {
	margin-top: 7px; /* Center the select box */
}

#monaco-workbench-drop-overlay {
	position: absolute;
	top: 0;
	left: 0;
	height: 100%;
	width: 100%;
	z-index: 10000;
}


text:
package javax.annotation;

@java.lang.annotation.Target(java.lang.annotation.ElementType.METHOD)
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface OverridingMethodsMustInvokeSuper
{
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sequentialAlgorithm>
	<!-- default <analysisTimes type="fromObservationTimes" ></analysisTimes>
		<analysisTimes type="fixed" timeFormat="dateTimeString" >201008241130,201008241140,...,201008242350</analysisTimes>
		<analysisTimes type="fixed" >201008240000,201008240300,201008240600</analysisTimes>
		<analysisTimes type="fixed" timeFormat="mjd" >48259.0,48259.125,48259.25</analysisTimes> -->
	<analysisTimes type="fromObservationTimes" skipAtInitialTime="false" skipAtFinalTime="false"></analysisTimes>
	<!-- selection to add noise to a model. This should probably be false unless you are generating data for a
	twin-experpiment -->
	<mainModel stochParameter="false" stochForcing="false" stochInit="false" />
	<ensembleSize>3</ensembleSize>
	<!-- selection to add noise to the ensemble members.
	This should probably be true unless your model has difficulty with the changes of parameters, initial state
	or the forcing -->
	<ensembleModel stochParameter="false" stochForcing="true" stochInit="false" />
</sequentialAlgorithm>


text:
/** @type {Construct} */
export const blankLine: Construct
export type Construct = import('micromark-util-types').Construct
export type Tokenizer = import('micromark-util-types').Tokenizer
export type State = import('micromark-util-types').State


text:
import * as types from "./offersTypes";
import OffersApi from "../API/offers/offersApi"

const offersApi = new OffersApi();

const request = () => {
    return {
        type: types.REQUEST_ONGOING
    }
}

const receivedError = error => {
    return {
        type: types.RECEIVED_ERROR
    }
}

const getAllSuccess = data => {
    return {
        type: types.RECEIVED_ALL_OFFERS,
        data: data.docs
    }
}

export const getAllOffers = () => {
    return dispatch => {
        dispatch(request())
        offersApi.getAll(response => {
            if ( response.error )
                dispatch(receivedError(response.error))
            else
                dispatch(getAllSuccess(response))
        });
    }
}

export const display_offer = offer => {
    return {
        type: types.SHOW_OFFER,
        offer
    };
}
export const hide_offer = () => {
    return {
        type: types.HIDE_OFFER
    };
}


text:
package com.github.datasnap.stats;

public class DsClientStats extends Stats {

	private static final long serialVersionUID = 5469315718941515883L;

	private static String DROPPED_KEY = "Dropped";
	private static String EVENT_KEY = "Event";
	private static String FAILED_KEY = "Failed";
	private static String FLUSHED_ATTEMPTS_KEY = "Flushed Attempts";
	private static String INSERTED_KEY = "Inserted";
	private static String QUEUED_KEY = "Queued";
	private static String REQUEST_TIME_KEY = "Request Time";
	private static String SUCCESSFUL_KEY = "Successful";

	public Stat getDropped() {
		return ensure(DROPPED_KEY);
	}

	public void updateDropped(double val) {
		update(DROPPED_KEY, val);
	}

	public Stat getEvents() {
		return ensure(EVENT_KEY);
	}

	public void updateEvents(double val) {
		update(EVENT_KEY, val);
	}

	public Stat getFailed() {
		return ensure(FAILED_KEY);
	}

	public void updateFailed(double val) {
		update(FAILED_KEY, val);
	}

	public Stat getFlushAttempts() {
		return ensure(FLUSHED_ATTEMPTS_KEY);
	}

	public void updateFlushAttempts(double val) {
		update(FLUSHED_ATTEMPTS_KEY, val);
	}

	public Stat getInserted() {
		return ensure(INSERTED_KEY);
	}

	public void updateInserted(double val) {
		update(INSERTED_KEY, val);
	}

	public Stat getRequestTime() {
		return ensure(REQUEST_TIME_KEY);
	}

	public void updateRequestTime(double val) {
		update(REQUEST_TIME_KEY, val);
	}

	public Stat getSuccessful() {
		return ensure(SUCCESSFUL_KEY);
	}

	public void updateSuccessful(double val) {
		update(SUCCESSFUL_KEY, val);
	}
	public Stat getQueued() {
		return ensure(QUEUED_KEY);
	}

	public void updateQueued(double val) {
		update(QUEUED_KEY, val);
	}

}


text:
package org.tensorflow.ndarray.impl.dimension;

import org.tensorflow.ndarray.index.Index;

public interface Dimension {

  default Dimension withIndex(Index index) {
    return new IndexedDimension(index, this);
  }

  long numElements();

  long elementSize();

  long physicalSize();

  long positionOf(long coord);

  boolean isSegmented();
}


text:
<?php

namespace Zelenin\Telegram\Bot;

use Exception;

class NotOkException extends Exception
{
}


text:
<?php

use Illuminate\Routing\Generators\ControllerGenerator;
use L4\Tests\BackwardCompatibleTestCase;
use Mockery as m;

class RoutingMakeControllerCommandTest extends BackwardCompatibleTestCase
{

    protected function tearDown(): void
    {
        m::close();
    }

    public function testGeneratorIsCalledWithProperOptions()
    {
        $command = new Illuminate\Routing\Console\MakeControllerCommand(
            $gen = m::mock(ControllerGenerator::class), __DIR__
        );
        $gen->shouldReceive('make')->once()->with(
            'FooController',
            __DIR__,
            ['only' => [], 'except' => []]
        );
        $this->runCommand($command, ['name' => 'FooController']);
	}

	public function testGeneratorIsCalledWithProperOptionsForExceptAndOnly()
	{
		$command = new Illuminate\Routing\Console\MakeControllerCommand($gen = m::mock(
            ControllerGenerator::class
        ), __DIR__);
		$gen->shouldReceive('make')->once()->with('FooController', __DIR__.'/foo/bar', ['only' => ['foo', 'bar'], 'except' => ['baz', 'boom']]
        );
		$command->setLaravel(['path.base' => __DIR__.'/foo']);
		$this->runCommand($command, ['name' => 'FooController', '--only' => 'foo,bar', '--except' => 'baz,boom', '--path' => 'bar']
        );
	}

	public function runCommand($command, $input = [], $output = null)
	{
		$output = $output ?: new Symfony\Component\Console\Output\NullOutput;

		return $command->run(new Symfony\Component\Console\Input\ArrayInput($input), $output);
	}

}


text:
require 'rails_helper'

RSpec.describe Admin::ClassContactListsController, :type => :controller do

end


text:
Shell scripts to manage database backups, asset backups, file permissions, asset syncing, cache clearing, and database syncing between Craft CMS environments

## Overview

There are several scripts included in `craft-scripts`, each of which perform different functions. They all use a shared `.env.sh` to function. This `.env.sh` should be created on each environment where you wish to run the `craft-scripts`, and it should be excluded from your git repo via `.gitignore`.

Craft-Scripts works with both Craft 2.x & Craft 3.x, and has built-in support for both `mysql` as well as `postgres` databases.

## Installation
* Copy the scripts folder into the root directory of your Craft CMS project
* Duplicate the example.env.sh file, and rename it to .env.sh
* Add .env.sh to your .gitignore file
* Then open up the .env.sh file into your favorite editor, and replace REPLACE_ME with the appropriate settings.

## Upgrading

To upgrade to a later version of Craft-Scripts, replace the contents of your `scripts` folder with the newest Craft-Scripts, while preserving your existing `.env.sh` file.

Craft-Scripts comes with defaults so that even older `.env.sh` files should work with the latest Craft-Scripts.

### set_perms.sh

The `set_perms.sh` script sets the Craft CMS install file permissions in a strict manner, to assist in hardening Craft CMS installs.

See [Hardening Craft CMS Permissions](https://nystudio107.com/blog/hardening-craft-cms-permissions) for a detailed writeup.

Note: if you use `git`, please see the [**Permissions and Git**](#permissions-and-git) section below.

### clear_caches.sh

The `clear_caches.sh` script clears the Craft CMS caches by removing all of the `craft/storage/runtime/` cache dirs, as well as emptying the `craft_templatecaches` db table.

It can also clear Redis db caches if `LOCAL_REDIS_DB_ID` is set, and it can clear FastCGI Cache if `LOCAL_FASTCGI_CACHE_DIR` is set.

If you want to add this to your Forge / DeployBot / Buddy.works deploy script so that caches are auto-cleared on deploy, set up the `.env.sh` on your remote server(s) and then add this to your deploy script:

    scripts/clear_caches.sh

The above assumes that the current working directory is the project root already.

### pull_db.sh

The `pull_db.sh` script pulls down a database dump from a remote server, and then dumps it into your local database. It backs up your local database before doing the dump.

The db dumps that `craft-scripts` does will exclude tables that are temporary/cache tables that we don't want in our backups/restores, such as the `templatecaches` table.

See [Database & Asset Syncing Between Environments in Craft CMS](https://nystudio107.com/blog/database-asset-syncing-between-environments-in-craft-cms) for a detailed writeup.

**N.B.:** The `pull_db.sh` script can be used even if the local and remote are on the same server.

### pull_assets.sh

The `pull_assets.sh` script pulls down an arbitrary number of asset directories from a remote server, since we keep client-uploadable assets out of the git repo. The directories it will pull down are specified in `LOCAL_ASSETS_DIRS`

It will also pull down the Craft `userphotos` and `rebrand` directories from `craft/storage` by default. The directories it will pull down are specified in `LOCAL_CRAFT_FILE_DIRS`

See [Database & Asset Syncing Between Environments in Craft CMS](https://nystudio107.com/blog/database-asset-syncing-between-environments-in-craft-cms) for a detailed writeup.

**N.B.:** The `pull_assets.sh` script can be used even if the local and remote are on the same server.

### pull_backups.sh

The `pull_backups.sh` script pulls down the backups created by `craft-scripts` from a remote server, and synced into the `LOCAL_BACKUPS_PATH`

For database backups, a sub-directory `REMOTE_DB_NAME/db` inside the `REMOTE_BACKUPS_PATH` directory is used for the database backups.

For asset backups, a sub-directory `REMOTE_DB_NAME/assets` inside the `REMOTE_BACKUPS_PATH` directory is used for the asset backups.

Because `rsync` is used for these backups, you can put a `.rsync-filter` in any directory to define files/folders to ignore. [More info](http://serverfault.com/questions/414358/rsync-filter-file-rules-for-subpath)

See [Mitigating Disaster via Website Backups](https://nystudio107.com/blog/mitigating-disaster-via-website-backups) for a detailed writeup.

### sync_backups_to_s3.sh

The `sync_backups_to_s3.sh` script syncs the backups from `LOCAL_BACKUPS_PATH` to the Amazon S3 bucket specified in `REMOTE_S3_BUCKET`.

If you have defined a optional subfolder, it will contain the backups to the path defined in `REMOTE_S3_PATH`.

This script assumes that you have already [installed awscli](http://docs.aws.amazon.com/cli/latest/userguide/installing.html) and have [configured it](http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html) with your credentials.

It's recommended that you set up a separate user with access to only S3, and set up a private S3 bucket for your backups.

You can set `LOCAL_AWS_PROFILE` to determine which AWS profile to connect with.

See [Mitigating Disaster via Website Backups](https://nystudio107.com/blog/mitigating-disaster-via-website-backups) for a detailed writeup.

### backup_db.sh

The `backup_db.sh` script backs up the local database into a timestamped, `gzip` compressed archive into the directory set via `LOCAL_BACKUPS_PATH`. It will also automatically rotate out (delete) any backups that are older than `GLOBAL_DB_BACKUPS_MAX_AGE` old.

The database backups exclude temporary/cache tables, and are stored in the sub-directory `LOCAL_DB_NAME/db`, inside of `LOCAL_BACKUPS_PATH`.

The numbers at the end of the backup archive are a timestamp in the format of `YYYYMMDD-HHMMSS`.

See the [**Automated Script Execution**](#automatic-script-execution) section below for details on how to run this automatically

See [Mitigating Disaster via Website Backups](https://nystudio107.com/blog/mitigating-disaster-via-website-backups) for a detailed writeup.

### backup_assets.sh

The `backup_assets.sh` script backs up an arbitrary number of asset directories to the directory specified in `LOCAL_BACKUPS_PATH`. The directories it backs are up specified in `LOCAL_ASSETS_DIRS`, just as they were for the `pull_assets.sh` script.

It will also back up the Craft `userphotos` and `rebrand` directories from `craft/storage` by default. The directories it will backup are specified in `LOCAL_CRAFT_FILE_DIRS`

Because `rsync` is used for these backups, you can put a `.rsync-filter` in any directory to define files/folders to ignore. [More info](http://serverfault.com/questions/414358/rsync-filter-file-rules-for-subpath)

For example, if you don't want any Craft image transforms backed up, your `.rsync-filter` file in each assets directory might look like this:

    # This file allows you to add filter rules to rsync, one per line, preceded by either
    # `-` or `exclude` and then a pattern to exclude, or `+` or `include` and then a pattern
    # to include. More info: http://askubuntu.com/questions/291322/how-to-exclude-files-in-rsync
    - _*/**

See the [**Automated Script Execution**](#automatic-script-execution) section below for details on how to run this automatically

See [Mitigating Disaster via Website Backups](https://nystudio107.com/blog/mitigating-disaster-via-website-backups) for a detailed writeup.

### backup_dirs.sh

The `backup_dirs.sh` script backs up an arbitrary number of directories to the directory specified in `LOCAL_BACKUPS_PATH`. The directories it backs are up specified in `LOCAL_DIRS_TO_BACKUP`.

This script is provided in case you have other files outside of your project that need backing up. For example, you might have a separate wiki or directory of config files.

Because `rsync` is used for these backups, you can put a `.rsync-filter` in any directory to define files/folders to ignore. [More info](http://serverfault.com/questions/414358/rsync-filter-file-rules-for-subpath)

For example, if you have a wiki with `data/cache` and `data/tmp` directories that you don't want backed up, your `.rsync-filter` file in the wiki directory might look like this:

    # This file allows you to add filter rules to rsync, one per line, preceded by either
    # `-` or `exclude` and then a pattern to exclude, or `+` or `include` and then a pattern
    # to include. More info: http://askubuntu.com/questions/291322/how-to-exclude-files-in-rsync
    - public/data/cache
    - public/data/tmp

See the [**Automated Script Execution**](#automatic-script-execution) section below for details on how to run this automatically

See [Mitigating Disaster via Website Backups](https://nystudio107.com/blog/mitigating-disaster-via-website-backups) for a detailed writeup.

### restore_db.sh

The `restore_db.sh` restores the local database to the database dumb passed in via command line argument. It backs up your local database before doing the restore.

You can pass in either a path to a `.sql` file or ` .gz` file to `restore_db.sh`, and it will do the right thing based on the file type.

See [Mitigating Disaster via Website Backups](https://nystudio107.com/blog/mitigating-disaster-via-website-backups) for a detailed writeup.

### restore_assets.sh

The `restore_assets.sh` restores the assets from the backup that has been created with `backup_assets.sh`.

### restore_dirs.sh

The `restore_dirs.sh` restores the dirs from the backup that has been created with `backup_dirs.sh`.

### Setting it up

1. Download or clone the `craft-scripts` git repo
2. Copy the `scripts` directory into the root directory of your Craft CMS project
3. In the `scripts` directory, duplicate the `craft2-example.env.sh` (for Craft 2.x projects) or `craft3-example.env.sh` (for Craft 3.x projects) file, and rename it to `.env.sh`. These `*-example.env.sh` files are largely the same, just with some different defaults for Craft 2.x and Craft 3.x.
4. Add `.env.sh` to your `.gitignore` file
5. Then open up the `.env.sh` file into your favorite editor, and replace `REPLACE_ME` with the appropriate settings.

All configuration is done in the `.env.sh` file, rather than in the scripts themselves. This is is so that the same scripts can be used in multiple environments such as `local` dev, `staging`, and `live` production without modification. Just create a `.env.sh` file in each environment, and keep it out of your git repo via `.gitignore`.

#### Global Settings

All settings that are prefaced with `GLOBAL_` apply to **all** environments.

`GLOBAL_DB_TABLE_PREFIX` is the Craft database table prefix, usually `craft_`

`GLOBAL_CRAFT_PATH` is the path of the `craft` folder, relative to the root path. This should normally be `craft/`, unless you have moved it elsewhere. Paths should always have a trailing `/`

`GLOBAL_DB_BACKUPS_MAX_AGE` Is the maximum age of local backups in days; backups older than this will be automatically rotated out (removed).

`GLOBAL_DB_DRIVER` is the database driver for this Craft install (`mysql` or `pgsql`)

#### Local Settings

All settings that are prefaced with `LOCAL_` refer to the local environment where the script will be run, **not** your `local` dev environment.

`LOCAL_ROOT_PATH` is the absolute path to the root of your local Craft install, with a trailing `/` after it.

`LOCAL_ASSETS_PATH` is the relative path to your local assets directories, with a trailing `/` after it.

`LOCAL_CHOWN_USER` is the user that is the owner of your entire Craft install.

`LOCAL_CHOWN_GROUP` is your webserver's group, usually either `nginx` or `apache`.

`LOCAL_WRITEABLE_DIRS` is a quoted list of directories relative to `LOCAL_ROOT_PATH` that should be writeable by your webserver.

`LOCAL_ASSETS_DIRS` is a quoted list of asset directories relative to `LOCAL_ASSETS_PATH` that you want to pull down from the remote server. It's done this way in case you wish to sync some asset directories, but not others. If you want to pull down all asset directories in `LOCAL_ASSETS_PATH`, just leave one blank quoted string in this array

`LOCAL_CRAFT_FILE_DIRS` is a quoted list of Craft file directories relative to `LOCAL_CRAFT_FILES_PATH` that you want to pull down from the remote server. By default, it will pull down the `userphotos` and `rebrand` directories in `craft/storage`, which typically are not kept in `git`. If you don't want it to sync anything, just leave the setting empty, e.g.: `LOCAL_CRAFT_FILE_DIRS=()`

`LOCAL_DIRS_TO_BACKUP` is an array of bsolute paths to directories to back up, in addition to `LOCAL_ASSETS_DIRS` and `LOCAL_CRAFT_FILE_DIRS`

`LOCAL_FASTCGI_CACHE_DIR` is the local FastCGI Cache path; leave it empty ("") if you're not using FastCGI Cache; paths should always have a trailing `/`. The `clear_caches.sh` script will delete everything in this directory when it is executed (say, on deploy)

`LOCAL_REDIS_DB_ID` is the local Redis database ID; leave it empty ("") if you're not using Redis. The `clear_caches.sh` script will purge this Redis database when it is executed (say, on deploy)

`LOCAL_DB_NAME` is the name of the local mysql Craft CMS database

`LOCAL_DB_PASSWORD` is the password for the local mysql Craft CMS database

`LOCAL_DB_USER` is the user for the local mysql Craft CMS database

`LOCAL_DB_HOST` is the host name of the local mysql database host. This is normally `localhost`

`LOCAL_DB_PORT` is the port number of the local mysql database host. This is normally `3306` for `mysql`, and `5432` for `postgres`.

`LOCAL_MYSQL_CMD` is the command for the local mysql executable, normally just `mysql`. It is provided because some setups like MAMP require a full path to a copy of `mysql` inside of the application bundle.

`LOCAL_MYSQLDUMP_CMD` is the command for the local mysqldump executable, normally just `mysqldump`. It is provided because some setups like MAMP require a full path to a copy of `mysqldump` inside of the application bundle.

`LOCAL_PSQL_CMD` is the command for the local postgres executable, normally just `psql`.

`LOCAL_PG_DUMP_CMD` is the command for the local pg_dump executable, normally just `pg_dump`.

`LOCAL_DB_LOGIN_PATH` if this is set, it will use `--login-path=` for your local db credentials instead of sending them in via the commandline (see below)

`LOCAL_BACKUPS_PATH` is the absolute path to the directory where local backups should be stored. For database backups, a sub-directory `LOCAL_DB_NAME/db` will be created inside the `LOCAL_BACKUPS_PATH` directory to store the database backups. Paths should always have a trailing `/`

`LOCAL_AWS_PROFILE` is an [AWS named profile](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) you can set to determine which profile to connect to S3 with.

##### Using mysql within a local docker container

`LOCAL_MYSQL_CMD` which is normally just `mysql`, is prepended with `docker exec -i CONTAINER_NAME` to execute the command within the container. (Example: `docker exec -i container_mysql_1 mysql`)

`LOCAL_MYSQLDUMP_CMD` which is normally just `mysqldump`, is prepended with `docker exec CONTAINER_NAME` to execute the command within the container. (Example: `docker exec container_mysql_1 mysqldump`)

#### Remote Settings

All settings that are prefaced with `REMOTE_` refer to the remote environment where assets and the database will be pulled from.

`REMOTE_SSH_LOGIN` is your ssh login to the remote server, e.g.: `user@domain.com`

`REMOTE_SSH_PORT` is the port to use for ssh on the remote server. This is normally `22`

`REMOTE_DB_USING_SSH` determines whether the database connection needs to be done over `ssh`, or the database should be directly connected to (such as for Heroku or Amazon RDS services). This is normally `yes`

`REMOTE_ROOT_PATH` is the absolute path to the root of your Craft install on the remote server, with a trailing `/` after it.

`REMOTE_ASSETS_PATH` is the relative path to the remote assets directories, with a trailing `/` after it.

`REMOTE_DB_NAME` is the name of the remote mysql Craft CMS database

`REMOTE_DB_PASSWORD` is the password for the remote mysql Craft CMS database

`REMOTE_DB_USER` is the user for the remote mysql Craft CMS database

`REMOTE_DB_HOST` is the host name of the remote mysql database host. This is normally `localhost`

`REMOTE_DB_PORT` is the port number of the remote mysql database host. This is normally `3306` for `mysql`, and `5432` for `postgres`.

`REMOTE_MYSQL_CMD` is the command for the local mysql executable, normally just `mysql`.

`REMOTE_MYSQLDUMP_CMD` is the command for the local mysqldump executable, normally just `mysqldump`.

`REMOTE_PSQL_CMD` is the command for the remote postgres executable, normally just `psql`.

`REMOTE_PG_DUMP_CMD` is the command for the remote pg_dump executable, normally just `pg_dump`.

`REMOTE_DB_LOGIN_PATH` if this is set, it will use `--login-path=` for your remote db credentials instead of sending them in via the commandline (see below)

`REMOTE_BACKUPS_PATH` is the absolute path to the directory where the remote backups are stored. For database backups, a sub-directory `REMOTE_DB_NAME/db` inside the `REMOTE_BACKUPS_PATH` directory is used for the database backups. Paths should always have a trailing `/`

`REMOTE_S3_BUCKET` is the name of the Amazon S3 bucket to backup to via the `sync_backups_to_s3.sh` script

`REMOTE_S3_PATH` is a optional path relative to the Amazon S3 bucket where the `sync_backups_to_s3.sh` script will contain the backups if specified

### Setting up SSH Keys

Normally when you `ssh` into a remote server (as some of the `craft-scripts` do), you have to enter your password. Best practices from a security POV is to not allow for password-based logins, but instead use [SSH Keys](https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2).

The day in, day out benefit of setting up SSH Keys is that you never have to enter your password again, so it allows for automated execution of the various `craft-scripts`. Use the excellent [How To Set Up SSH Keys](https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2) artice as a guide for setting up your SSH keys.

### Permissions and Git

If you use `git`, a sample `.gitignore` file that you can modify & use for your Craft CMS projects is included in `craft-scripts` as `example.gitignore`. If you wish to use it, the file should be copied to your Craft CMS project root, and renamed `.gitignore`

If you change file permissions on your remote server, you may encounter git complaining about `overwriting existing local changes` when you try to deploy. This is because git considers changing the executable flag to be a change in the file, so it thinks you changed the files on your server (and the changes are not checked into your git repo).

To fix this, we just need to tell git to ignore permission changes on the server. You can change the `fileMode` setting for `git` on your server, telling it to ignore permission changes of the files on the server:

    git config --global core.fileMode false

See the [git-config man page](https://git-scm.com/docs/git-config#git-config-corefileMode) for details.

The other way to fix this is to set the permission using `set_perms.sh` in `local` dev, and then check the files into your git repo. This will cause them to be saved with the correct permissions in your git repo to begin with.

The downside to the latter approach is that you must have matching user/groups in both `local` dev and on `live` production.

### Automatic Script Execution

If you want to run any of these scripts automatically at a set schedule, here's how to do it. We'll use the `backup_db.sh` script as an example, but the same applies to any of the scripts.

Please see the [**Setting up SSH Keys**](#setting-up-ssh-keys) section and set up your SSH keys before you set up automatic script execution.

#### On Linux

If you're using [Forge](https://forge.laravel.com/) you can set the `backup_db.sh` script to run nightly (or whatever interval you want) via the Scheduler. If you're using [ServerPilot.io](https://serverpilot.io/community/articles/how-to-use-cron-to-schedule-scripts.html) or are managing the server yourself, just set the `backup_db.sh` script to run via `cron` at whatever interval you desire.

`craft-scripts` includes a `crontab-helper.txt` that you can add to your `crontab` to make configuring `cron` easier. Remember to use full, absolute paths to the scripts when running them via `cron`, as `cron` does not have access to your environment paths, e.g.:

    /home/forge/nystudio107.com/scripts/backup_db.sh

#### On a Mac

If you're using a Mac and you want to execute the script locally, Apple uses [Launch Daemons](https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html) instead of `cron`.

**N.B.:** Even if you _are_ on a Mac, if you run your `local` dev in a VM like Vagrant/Homestead, you'll want to execute the `craft-scripts` from inside of the VM itself, not on your local Mac. If you use something like Valet or Mamp, read on.

Included in `craft-scripts` is a `com.example.launch_daemon.plist` to help you get started. This file is an `XML` file, and the name should be a unique, reverse-DNS-style name suffixed with `.plist`. This file is analogous to a single line in a `crontab` file.

Rename `com.example.launch_daemon.plist` to something unique to your project/script, e.g.: `com.clientdomain.backup_db.plist` and place it in `/Library/LaunchDaemons/` (you'll need to `sudo` to do this).

The Launch Daemon `.plist` file is an `XML` file with a series of `<key></key>`s followed by some type that is a value for that key. The value for the `<key>Label</key>` should match the name of the file, minus the `.plist` extension, e.g.: `<string>com.clientdomain.backup_db</string>`. The value for the `<key>UserName</key>` should be the user name that you want the task to run as, e.g.: `<string>andrew</string>`

The value for the `<key>Program</key>` is a path to the command to execute, e.g.: `<string>/Users/andrew/webdev/sites/nystudio107/scripts/backup_db.sh</string>`

Launch Daemons offer any number of ways to schedule when and how they execute; please see the [Launch Daemon documentation](https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html) for details.

Once the file has been created in `/Library/LaunchDaemons/`, it'll need to be loaded (you only need to do this once) via `launchctl`, e.g.:

    sudo launchctl load /Library/LaunchDaemons/com.clientdomain.backup_db.plist

For more information on configuring Launch Daemons, please see the excellent [launchd.info](http://www.launchd.info/) website.

### Using login-path with mysql 5.6

If you're using `mysql 5.6` or later, you'll note the warning from mysql (this is [not an issue if you're using MariaDB](https://mariadb.com/kb/en/mariadb/mysql_config_editor-compatibility/)):

    mysql: [Warning] Using a password on the command line interface can be insecure.

What the `craft-scripts` is doing isn't any less secure than if you typed it on the command line yourself; everything sent over the wire is always encrypted via ssh. However, you can set up `login-path` to store your credentials in an encrypted file as per the [Passwordless authentication using mysql_config_editor with MySQL 5.6](https://opensourcedbms.com/dbms/passwordless-authentication-using-mysql_config_editor-with-mysql-5-6/) article.

If you set `LOCAL_DB_LOGIN_PATH` or `REMOTE_DB_LOGIN_PATH` it will use `--login-path=` for your db credentials on the respective environments instead of sending them in via the commandline.

For example, for my `local` dev setup:

    mysql_config_editor set --login-path=localdev --user=homestead --host=localhost --port=3306 --password

...and then enter the password for that user. And then in the `.env.sh` I set it to:

    LOCAL_DB_LOGIN_PATH="localdev"

...and it will use my stored, encrypted credentials instead of passing them in via commandline. You can also set this up on your remote server, and then set it via `REMOTE_DB_LOGIN_PATH`

Brought to you by [nystudio107](https://nystudio107.com/)


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Adding field 'Msg.subject'
        db.add_column(u'sb_msg', 'subject', self.gf('django.db.models.fields.CharField')(max_length=80, null=True, blank=True), keep_default=False)

    def backwards(self, orm):

        # Deleting field 'Msg.subject'
        db.delete_column(u'sb_msg', 'subject')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 22, 18, 45, 6, 654196)'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 22, 18, 45, 6, 653709)'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'sb.comment': {
            'Meta': {'object_name': 'Comment'},
            'author': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}),
            'body': ('django.db.models.fields.TextField', [], {}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'post': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'comments'", 'null': 'True', 'to': u"orm['sb.Post']"})
        },
        u'sb.message': {
            'Meta': {'ordering': "['-created']", 'object_name': 'Message'},
            'body': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'null': 'True', 'blank': 'True'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_read': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'recipient': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}),
            'sender': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'messages'", 'to': u"orm['auth.User']"})
        },
        u'sb.msg': {
            'Meta': {'ordering': "['-created']", 'object_name': 'Msg'},
            'body': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'null': 'True', 'blank': 'True'}),
            'cc': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'inbox': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_read': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'recipient': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}),
            'sender': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'msgs'", 'to': u"orm['auth.User']"}),
            'sent': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'subject': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'})
        },
        u'sb.post': {
            'Meta': {'ordering': "['-created']", 'object_name': 'Post'},
            'body': ('django.db.models.fields.TextField', [], {}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '60'})
        },
        u'sb.sbprofile': {
            'Meta': {'object_name': 'SBProfile'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_viewed_message': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sb.Message']", 'null': 'True', 'blank': 'True'}),
            'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'sbprofile'", 'unique': 'True', 'to': u"orm['auth.User']"})
        }
    }

    complete_apps = ['sb']


text:
"""
While SQLAlchemy/sqlalchemy-migrate should abstract this correctly,
there are known issues with these libraries so SQLite and non-SQLite
migrations must be done separately.
"""

import migrate
import sqlalchemy

from glance.openstack.common import uuidutils

meta = sqlalchemy.MetaData()
and_ = sqlalchemy.and_
or_ = sqlalchemy.or_

def upgrade(migrate_engine):
    """
    Call the correct dialect-specific upgrade.
    """
    meta.bind = migrate_engine

    t_images = _get_table('images', meta)
    t_image_members = _get_table('image_members', meta)
    t_image_properties = _get_table('image_properties', meta)
    dialect = migrate_engine.url.get_dialect().name
    if dialect == "sqlite":
        _upgrade_sqlite(t_images, t_image_members, t_image_properties)
        _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)
    else:
        _upgrade_other(t_images, t_image_members, t_image_properties, dialect)

def downgrade(migrate_engine):
    """
    Call the correct dialect-specific downgrade.
    """
    meta.bind = migrate_engine

    t_images = _get_table('images', meta)
    t_image_members = _get_table('image_members', meta)
    t_image_properties = _get_table('image_properties', meta)
    dialect = migrate_engine.url.get_dialect().name
    if dialect == "sqlite":
        _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties)
        _downgrade_sqlite(t_images, t_image_members, t_image_properties)
    else:
        _downgrade_other(t_images, t_image_members, t_image_properties,
                         dialect)

def _upgrade_sqlite(t_images, t_image_members, t_image_properties):
    """
    Upgrade 011 -> 012 with special SQLite-compatible logic.
    """

    sql_commands = [
        """CREATE TABLE images_backup (
           id VARCHAR(36) NOT NULL,
           name VARCHAR(255),
           size INTEGER,
           status VARCHAR(30) NOT NULL,
           is_public BOOLEAN NOT NULL,
           location TEXT,
           created_at DATETIME NOT NULL,
           updated_at DATETIME,
           deleted_at DATETIME,
           deleted BOOLEAN NOT NULL,
           disk_format VARCHAR(20),
           container_format VARCHAR(20),
           checksum VARCHAR(32),
           owner VARCHAR(255),
           min_disk INTEGER NOT NULL,
           min_ram INTEGER NOT NULL,
           PRIMARY KEY (id),
           CHECK (is_public IN (0, 1)),
           CHECK (deleted IN (0, 1))
        );""",
        """INSERT INTO images_backup
           SELECT * FROM images;""",
        """CREATE TABLE image_members_backup (
            id INTEGER NOT NULL,
            image_id VARCHAR(36) NOT NULL,
            member VARCHAR(255) NOT NULL,
            can_share BOOLEAN NOT NULL,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            UNIQUE (image_id, member),
            CHECK (can_share IN (0, 1)),
            CHECK (deleted IN (0, 1)),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_members_backup
            SELECT * FROM image_members;""",
        """CREATE TABLE image_properties_backup (
            id INTEGER NOT NULL,
            image_id VARCHAR(36) NOT NULL,
            name VARCHAR(255) NOT NULL,
            value TEXT,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            CHECK (deleted IN (0, 1)),
            UNIQUE (image_id, name),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_properties_backup
            SELECT * FROM image_properties;""",
    ]

    for command in sql_commands:
        meta.bind.execute(command)

    _sqlite_table_swap(t_image_members, t_image_properties, t_images)

def _downgrade_sqlite(t_images, t_image_members, t_image_properties):
    """
    Downgrade 012 -> 011 with special SQLite-compatible logic.
    """

    sql_commands = [
        """CREATE TABLE images_backup (
           id INTEGER NOT NULL,
           name VARCHAR(255),
           size INTEGER,
           status VARCHAR(30) NOT NULL,
           is_public BOOLEAN NOT NULL,
           location TEXT,
           created_at DATETIME NOT NULL,
           updated_at DATETIME,
           deleted_at DATETIME,
           deleted BOOLEAN NOT NULL,
           disk_format VARCHAR(20),
           container_format VARCHAR(20),
           checksum VARCHAR(32),
           owner VARCHAR(255),
           min_disk INTEGER NOT NULL,
           min_ram INTEGER NOT NULL,
           PRIMARY KEY (id),
           CHECK (is_public IN (0, 1)),
           CHECK (deleted IN (0, 1))
        );""",
        """INSERT INTO images_backup
           SELECT * FROM images;""",
        """CREATE TABLE image_members_backup (
            id INTEGER NOT NULL,
            image_id INTEGER NOT NULL,
            member VARCHAR(255) NOT NULL,
            can_share BOOLEAN NOT NULL,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            UNIQUE (image_id, member),
            CHECK (can_share IN (0, 1)),
            CHECK (deleted IN (0, 1)),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_members_backup
            SELECT * FROM image_members;""",
        """CREATE TABLE image_properties_backup (
            id INTEGER NOT NULL,
            image_id INTEGER  NOT NULL,
            name VARCHAR(255) NOT NULL,
            value TEXT,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            CHECK (deleted IN (0, 1)),
            UNIQUE (image_id, name),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_properties_backup
            SELECT * FROM image_properties;""",
    ]

    for command in sql_commands:
        meta.bind.execute(command)

    _sqlite_table_swap(t_image_members, t_image_properties, t_images)

def _upgrade_other(t_images, t_image_members, t_image_properties, dialect):
    """
    Upgrade 011 -> 012 with logic for non-SQLite databases.
    """
    foreign_keys = _get_foreign_keys(t_images,
                                     t_image_members,
                                     t_image_properties, dialect)

    for fk in foreign_keys:
        fk.drop()

    t_images.c.id.alter(sqlalchemy.String(36), primary_key=True)
    t_image_members.c.image_id.alter(sqlalchemy.String(36))
    t_image_properties.c.image_id.alter(sqlalchemy.String(36))

    _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)

    for fk in foreign_keys:
        fk.create()

def _downgrade_other(t_images, t_image_members, t_image_properties, dialect):
    """
    Downgrade 012 -> 011 with logic for non-SQLite databases.
    """
    foreign_keys = _get_foreign_keys(t_images,
                                     t_image_members,
                                     t_image_properties, dialect)

    for fk in foreign_keys:
        fk.drop()

    t_images.c.id.alter(sqlalchemy.Integer(), primary_key=True)
    t_image_members.c.image_id.alter(sqlalchemy.Integer())
    t_image_properties.c.image_id.alter(sqlalchemy.Integer())

    _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties)

    for fk in foreign_keys:
        fk.create()

def _sqlite_table_swap(t_image_members, t_image_properties, t_images):
    t_image_members.drop()
    t_image_properties.drop()
    t_images.drop()

    meta.bind.execute("ALTER TABLE images_backup "
                      "RENAME TO images")
    meta.bind.execute("ALTER TABLE image_members_backup "
                      "RENAME TO image_members")
    meta.bind.execute("ALTER TABLE image_properties_backup "
                      "RENAME TO image_properties")
    meta.bind.execute("""CREATE INDEX ix_image_properties_deleted
                          ON image_properties (deleted);""")
    meta.bind.execute("""CREATE INDEX ix_image_properties_name
                          ON image_properties (name);""")

def _get_table(table_name, metadata):
    """Return a sqlalchemy Table definition with associated metadata."""
    return sqlalchemy.Table(table_name, metadata, autoload=True)

def _get_foreign_keys(t_images, t_image_members, t_image_properties, dialect):
    """Retrieve and return foreign keys for members/properties tables."""
    foreign_keys = []
    if t_image_members.foreign_keys:
        img_members_fk_name = list(t_image_members.foreign_keys)[0].name
        if dialect == 'mysql':
            fk1 = migrate.ForeignKeyConstraint([t_image_members.c.image_id],
                                               [t_images.c.id],
                                               name=img_members_fk_name)
        else:
            fk1 = migrate.ForeignKeyConstraint([t_image_members.c.image_id],
                                               [t_images.c.id])
        foreign_keys.append(fk1)

    if t_image_properties.foreign_keys:
        img_properties_fk_name = list(t_image_properties.foreign_keys)[0].name
        if dialect == 'mysql':
            fk2 = migrate.ForeignKeyConstraint([t_image_properties.c.image_id],
                                               [t_images.c.id],
                                               name=img_properties_fk_name)
        else:
            fk2 = migrate.ForeignKeyConstraint([t_image_properties.c.image_id],
                                               [t_images.c.id])
        foreign_keys.append(fk2)

    return foreign_keys

def _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties):
    """Transition from INTEGER id to VARCHAR(36) id."""
    images = list(t_images.select().execute())

    for image in images:
        old_id = image["id"]
        new_id = uuidutils.generate_uuid()

        t_images.update().\
            where(t_images.c.id == old_id).\
            values(id=new_id).execute()

        t_image_members.update().\
            where(t_image_members.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(t_image_properties.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(and_(or_(t_image_properties.c.name == 'kernel_id',
                           t_image_properties.c.name == 'ramdisk_id'),
                       t_image_properties.c.value == old_id)).\
            values(value=new_id).execute()

def _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties):
    """Transition from VARCHAR(36) id to INTEGER id."""
    images = list(t_images.select().execute())

    new_id = 1
    for image in images:
        old_id = image["id"]

        t_images.update().\
            where(t_images.c.id == old_id).\
            values(id=new_id).execute()

        t_image_members.update().\
            where(t_image_members.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(t_image_properties.c.image_id == old_id).\
            values(image_id=new_id).execute()

        t_image_properties.update().\
            where(and_(or_(t_image_properties.c.name == 'kernel_id',
                           t_image_properties.c.name == 'ramdisk_id'),
                       t_image_properties.c.value == old_id)).\
            values(value=new_id).execute()

        new_id += 1


text:
order: 5
title:
  zh-CN: 异步加载
  en-US: Asynchronous loading
---

## zh-CN

异步加载树节点。

## en-US

Asynchronous loading tree node.

```tsx
import type { TreeSelectProps } from 'antd';
import { TreeSelect } from 'antd';
import type { DefaultOptionType } from 'antd/es/select';
import React, { useState } from 'react';

const App: React.FC = () => {
  const [value, setValue] = useState<string>();
  const [treeData, setTreeData] = useState<Omit<DefaultOptionType, 'label'>[]>([
    { id: 1, pId: 0, value: '1', title: 'Expand to load' },
    { id: 2, pId: 0, value: '2', title: 'Expand to load' },
    { id: 3, pId: 0, value: '3', title: 'Tree Node', isLeaf: true },
  ]);

  const genTreeNode = (parentId: number, isLeaf = false) => {
    const random = Math.random().toString(36).substring(2, 6);
    return {
      id: random,
      pId: parentId,
      value: random,
      title: isLeaf ? 'Tree Node' : 'Expand to load',
      isLeaf,
    };
  };

  const onLoadData: TreeSelectProps['loadData'] = ({ id }) =>
    new Promise(resolve => {
      setTimeout(() => {
        setTreeData(
          treeData.concat([genTreeNode(id, false), genTreeNode(id, true), genTreeNode(id, true)]),
        );
        resolve(undefined);
      }, 300);
    });

  const onChange = (newValue: string) => {
    console.log(newValue);
    setValue(newValue);
  };

  return (
    <TreeSelect
      treeDataSimpleMode
      style={{ width: '100%' }}
      value={value}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      placeholder="Please select"
      onChange={onChange}
      loadData={onLoadData}
      treeData={treeData}
    />
  );
};

export default App;
```


text:
<?xml version="1.0" ?>
<srv:container xmlns="http://doctrine-project.org/schemas/symfony-dic/cache"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:srv="http://symfony.com/schema/dic/services"
               xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
                        http://doctrine-project.org/schemas/symfony-dic/cache  http://doctrine-project.org/schemas/symfony-dic/cache/doctrine_cache-1.0.xsd">

    <doctrine-cache>
        <acl-cache id="doctrine_cache.providers.acl_apc_provider"/>

        <provider name="acl_apc_provider" type="apc"/>
    </doctrine-cache>
</srv:container>


text:
package org.apache.mesos.hbase.client;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

/**
 *
 * @author jzajic
 */
public class TestConnectToHbase
{

  public static final String HBASE_CONFIGURATION_ZOOKEEPER_QUORUM = "hbase.zookeeper.quorum";
  public static final String HBASE_CONFIGURATION_ZOOKEEPER_CLIENTPORT = "hbase.zookeeper.property.clientPort";

  public static void main(String[] args) throws Exception
    {
        String hbaseZookeeperQuorum="127.0.0.1,192.168.0.1";
        int hbaseZookeeperClientPort=2181;
        // You need a configuration object to tell the client where to connect.
        // When you create a HBaseConfiguration, it reads in whatever you've set
        // into your hbase-site.xml and in hbase-default.xml, as long as these can
        // be found on the CLASSPATH
        Configuration hConf = HBaseConfiguration.create();
        hConf.set(TestConnectToHbase.HBASE_CONFIGURATION_ZOOKEEPER_QUORUM, hbaseZookeeperQuorum);
        hConf.set(TestConnectToHbase.HBASE_CONFIGURATION_ZOOKEEPER_CLIENTPORT, String.valueOf(hbaseZookeeperClientPort));
        hConf.set("hbase.cluster.distributed", "true");
        hConf.set("hbase.rootdir", "hdfs://hdfs/hbase");
        //timeout settings - see http://hadoop-hbase.blogspot.cz/2012/09/hbase-client-timeouts.html
        String smallTimeout = "200";
        hConf.set("zookeeper.session.timeout", smallTimeout);
        hConf.set("hbase.rpc.timeout", smallTimeout);
        hConf.set("zookeeper.recovery.retry", "2");
        hConf.set("zookeeper.recovery.retry.intervalmill", "10");
        hConf.set("hbase.client.retries.number", "2");
        hConf.set("hbase.client.pause", "10");
        hConf.set("hbase.client.operation.timeout", "100");

        try (Connection connection = ConnectionFactory.createConnection(hConf);)
        {
            if(!connection.isAborted())
            {
                try(Table table = connection.getTable(TableName.valueOf("myLittleHBaseTable"));)
                {
                    Put p = new Put(Bytes.toBytes("myLittleRow"));
                    p.addColumn(Bytes.toBytes("myLittleFamily"), Bytes.toBytes("someQualifier"), Bytes.toBytes("Some Value"));
                    table.put(p);
                }
            }
        }
    }
}


text:
/*******************************************************************
* 版权所有: 深圳市震有科技有限公司
* 文件名称: AutoCompleteBoxAutomationPeer.cs
* 作   者: chenzhifen
* 创建日期: 2014-03-31 0:51
* 文件版本: 1.0.0.0
* 修改时间:             修改人:                修改内容:
*******************************************************************/

using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using ModernUI.ExtendedToolkit;

namespace ModernUI.Automation.Peers
{
    /// <summary>
    ///     Exposes AutoCompleteBox types to UI Automation.
    /// </summary>
    /// <QualityBand>Stable</QualityBand>
    public sealed class AutoCompleteBoxAutomationPeer : FrameworkElementAutomationPeer, IValueProvider,
        IExpandCollapseProvider, ISelectionProvider
    {
        /// <summary>
        ///     The name reported as the core class name.
        /// </summary>
        private const string AutoCompleteBoxClassNameCore = "AutoCompleteBox";

        /// <summary>
        ///     Initializes a new instance of the AutoCompleteBoxAutomationPeer
        ///     class.
        /// </summary>
        /// <param name="owner">
        ///     The AutoCompleteBox that is associated with this
        ///     AutoCompleteBoxAutomationPeer.
        /// </param>
        public AutoCompleteBoxAutomationPeer(AutoCompleteBox owner)
            : base(owner)
        {
        }

        /// <summary>
        ///     Gets the AutoCompleteBox that owns this
        ///     AutoCompleteBoxAutomationPeer.
        /// </summary>
        private AutoCompleteBox OwnerAutoCompleteBox
        {
            get { return (AutoCompleteBox)Owner; }
        }

        /// <summary>
        ///     Gets a value indicating whether the UI automation provider allows
        ///     more than one child element to be selected concurrently.
        /// </summary>
        /// <remarks>
        ///     This API supports the .NET Framework infrastructure and is not
        ///     intended to be used directly from your code.
        /// </remarks>
        /// <value>True if multiple selection is allowed; otherwise, false.</value>
        bool ISelectionProvider.CanSelectMultiple
        {
            get { return false; }
        }

        /// <summary>
        ///     Gets a value indicating whether the UI automation provider
        ///     requires at least one child element to be selected.
        /// </summary>
        /// <remarks>
        ///     This API supports the .NET Framework infrastructure and is not
        ///     intended to be used directly from your code.
        /// </remarks>
        /// <value>True if selection is required; otherwise, false.</value>
        bool ISelectionProvider.IsSelectionRequired
        {
            get { return false; }
        }

        /// <summary>
        ///     Retrieves a UI automation provider for each child element that is
        ///     selected.
        /// </summary>
        /// <returns>An array of UI automation providers.</returns>
        /// <remarks>
        ///     This API supports the .NET Framework infrastructure and is not
        ///     intended to be used directly from your code.
        /// </remarks>
        IRawElementProviderSimple[] ISelectionProvider.GetSelection()
        {
            if (OwnerAutoCompleteBox.SelectionAdapter != null)
            {
                object selectedItem = OwnerAutoCompleteBox.SelectionAdapter.SelectedItem;
                if (selectedItem != null)
                {
                    UIElement uie = selectedItem as UIElement;
                    if (uie != null)
                    {
                        AutomationPeer peer = UIElementAutomationPeer.CreatePeerForElement(uie);
                        if (peer != null)
                        {
                            return new[] { ProviderFromPeer(peer) };
                        }
                    }
                }
            }

            return new IRawElementProviderSimple[] { };
        }

        /// <summary>
        ///     Gets the control type for the AutoCompleteBox that is associated
        ///     with this AutoCompleteBoxAutomationPeer. This method is called by
        ///     GetAutomationControlType.
        /// </summary>
        /// <returns>ComboBox AutomationControlType.</returns>
        protected override AutomationControlType GetAutomationControlTypeCore()
        {
            return AutomationControlType.ComboBox;
        }

        /// <summary>
        ///     Gets the name of the AutoCompleteBox that is associated with this
        ///     AutoCompleteBoxAutomationPeer. This method is called by
        ///     GetClassName.
        /// </summary>
        /// <returns>The name AutoCompleteBox.</returns>
        protected override string GetClassNameCore()
        {
            return AutoCompleteBoxClassNameCore;
        }

        /// <summary>
        ///     Gets the control pattern for the AutoCompleteBox that is associated
        ///     with this AutoCompleteBoxAutomationPeer.
        /// </summary>
        /// <param name="patternInterface">The desired PatternInterface.</param>
        /// <returns>The desired AutomationPeer or null.</returns>
        public override object GetPattern(PatternInterface patternInterface)
        {
            object iface = null;
            AutoCompleteBox owner = OwnerAutoCompleteBox;

            if (patternInterface == PatternInterface.Value)
            {
                iface = this;
            }
            else if (patternInterface == PatternInterface.ExpandCollapse)
            {
                iface = this;
            }
            else if (owner.SelectionAdapter != null)
            {
                AutomationPeer peer = owner.SelectionAdapter.CreateAutomationPeer();
                if (peer != null)
                {
                    iface = peer.GetPattern(patternInterface);
                }
            }

            if (iface == null)
            {
                iface = base.GetPattern(patternInterface);
            }

            return iface;
        }

        /// <summary>
        ///     Gets the collection of child elements of the AutoCompleteBox that
        ///     are associated with this AutoCompleteBoxAutomationPeer. This method
        ///     is called by GetChildren.
        /// </summary>
        /// <returns>
        ///     A collection of automation peer elements, or an empty collection
        ///     if there are no child elements.
        /// </returns>
        [SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "Required by automation")
        ]
        protected override List<AutomationPeer> GetChildrenCore()
        {
            List<AutomationPeer> children = new List<AutomationPeer>();
            AutoCompleteBox owner = OwnerAutoCompleteBox;

            // TextBox part.
            TextBox textBox = owner.TextBox;
            if (textBox != null)
            {
                AutomationPeer peer = UIElementAutomationPeer.CreatePeerForElement(textBox);
                if (peer != null)
                {
                    children.Insert(0, peer);
                }
            }

            // Include SelectionAdapter's children.
            if (owner.SelectionAdapter != null)
            {
                AutomationPeer selectionAdapterPeer = owner.SelectionAdapter.CreateAutomationPeer();
                if (selectionAdapterPeer != null)
                {
                    List<AutomationPeer> listChildren = selectionAdapterPeer.GetChildren();
                    if (listChildren != null)
                    {
                        foreach (AutomationPeer child in listChildren)
                        {
                            children.Add(child);
                        }
                    }
                }
            }

            return children;
        }

        #region ExpandCollapse

        /// <summary>
        ///     Blocking method that returns after the element has been expanded.
        /// </summary>
        /// <remarks>
        ///     This API supports the .NET Framework infrastructure and is not
        ///     intended to be used directly from your code.
        /// </remarks>
        void IExpandCollapseProvider.Expand()
        {
            if (!IsEnabled())
            {
                throw new ElementNotEnabledException();
            }

            OwnerAutoCompleteBox.IsDropDownOpen = true;
        }

        /// <summary>
        ///     Blocking method that returns after the element has been collapsed.
        /// </summary>
        /// <remarks>
        ///     This API supports the .NET Framework infrastructure and is not
        ///     intended to be used directly from your code.
        /// </remarks>
        void IExpandCollapseProvider.Collapse()
        {
            if (!IsEnabled())
            {
                throw new ElementNotEnabledException();
            }

            OwnerAutoCompleteBox.IsDropDownOpen = false;
        }

        /// <summary>
        ///     Gets an element's current Collapsed or Expanded state.
        /// </summary>
        /// <remarks>
        ///     This API supports the .NET Framework infrastructure and is not
        ///     intended to be used directly from your code.
        /// </remarks>
        ExpandCollapseState IExpandCollapseProvider.ExpandCollapseState
        {
            get
            {
                return OwnerAutoCompleteBox.IsDropDownOpen ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed;
            }
        }

        /// <summary>
        ///     Raises the ExpandCollapse automation event.
        /// </summary>
        /// <param name="oldValue">The old value.</param>
        /// <param name="newValue">The new value.</param>
        internal void RaiseExpandCollapseAutomationEvent(bool oldValue, bool newValue)
        {
            RaisePropertyChangedEvent(
                ExpandCollapsePatternIdentifiers.ExpandCollapseStateProperty,
                oldValue ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed,
                newValue ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed);
        }

        #endregion ExpandCollapse

        #region ValueProvider

        /// <summary>
        ///     Sets the value of a control.
        /// </summary>
        /// <param name="value">
        ///     The value to set. The provider is responsible
        ///     for converting the value to the appropriate data type.
        /// </param>
        void IValueProvider.SetValue(string value)
        {
            OwnerAutoCompleteBox.Text = value;
        }

        /// <summary>
        ///     Gets a value indicating whether the value of a control is
        ///     read-only.
        /// </summary>
        /// <value>True if the value is read-only; false if it can be modified.</value>
        bool IValueProvider.IsReadOnly
        {
            get { return !OwnerAutoCompleteBox.IsEnabled; }
        }

        /// <summary>
        ///     Gets the value of the control.
        /// </summary>
        /// <value>The value of the control.</value>
        string IValueProvider.Value
        {
            get { return OwnerAutoCompleteBox.Text ?? string.Empty; }
        }

        #endregion
    }
}