import * as THREE from 'three';

const UNIFORMS = {
    // rgba
    u_g1_color: new THREE.Uniform(new THREE.Vector4(0, 0, 0, 1))
};

const CNC_LASER_VERT_SHADER = [
    'varying float v_g_code;',
    'attribute float a_g_code;',
    'void main(){',
    '    v_g_code = a_g_code;',
    '    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
    '}'
].join('');

const CNC_LASER_FRAG_SHADER = [
    'uniform vec4 u_g1_color;',
    'varying float v_g_code;',
    'void main(){',
    '    if(v_g_code == 0.0){',
    '        discard;',
    '    }',
    '    gl_FragColor = u_g1_color;',
    '}'
].join('');

const motionColor = {
    'G0': new THREE.Color(0xc8c8c8),
    'G1': new THREE.Color(0x000000),
    'unknown': new THREE.Color(0x000000)
};

class ToolPathRenderer {
    render(toolPath) {
        const { headerType, mode, movementMode, data } = toolPath;

        // now only support cnc&laser
        if (!['cnc', 'laser'].includes(headerType)) {
            return null;
        }

        if (headerType === 'laser') {
            if (mode === 'greyscale' && movementMode === 'greyscale-dot') {
                return this.parseToPoints(data);
            } else {
                return this.parseToLine(data);
            }
        } else {
            return this.parseToLine(data);
        }
    }

    parseToLine(data) {
        const positions = [];
        const gCodes = [];

        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if ((state.G === 1) && (newState.G === 0)) {
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(newState.G);
            }

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(state.G);
            }
        }

        const bufferGeometry = new THREE.BufferGeometry();
        const positionAttribute = new THREE.Float32BufferAttribute(positions, 3);
        const gCodeAttribute = new THREE.Float32BufferAttribute(gCodes, 1);
        bufferGeometry.addAttribute('position', positionAttribute);
        bufferGeometry.addAttribute('a_g_code', gCodeAttribute);
        const material = new THREE.ShaderMaterial({
            uniforms: UNIFORMS,
            vertexShader: CNC_LASER_VERT_SHADER,
            fragmentShader: CNC_LASER_FRAG_SHADER,
            side: THREE.DoubleSide,
            transparent: true,
            linewidth: 1
        });
        return new THREE.Line(bufferGeometry, material);
    }

    parseToPoints(data) {
        const geometry = new THREE.Geometry();
        const material = new THREE.PointsMaterial({
            size: 0.1,
            vertexColors: THREE.VertexColors,
            opacity: 0.9,
            transparent: true
        });
        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                geometry.vertices.push(new THREE.Vector3(state.X, state.Y, state.Z));
                if (state.G === 0) {
                    geometry.colors.push(motionColor.G0);
                } else if (state.G === 1) {
                    geometry.colors.push(motionColor.G1);
                } else {
                    geometry.colors.push(motionColor.unknown);
                }
            }
        }
        return new THREE.Points(geometry, material);
    }
}

export default ToolPathRenderer;

package reflect

import (
	"math/rand"
	"reflect"

	randplus "github.com/cheetah-fun-gs/goplus/math/rand"
)

// Mock 生成 随机值的 mock 数据
func Mock(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), false)
}

// MockKeep 生成 原值或0值的 mock 数据
func MockKeep(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), true)
}

func randomNew(typ reflect.Type) interface{} {
	switch typ.Kind() {
	case reflect.Bool:
		return false
	case reflect.Int:
		return int(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int8:
		return int8(randplus.MustRandint(-128, 127))
	case reflect.Int16:
		return int16(randplus.MustRandint(-32768, 32767))
	case reflect.Int32:
		return int32(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int64:
		return int64(randplus.MustRandint(-9223372036854775808, 9223372036854775807))
	case reflect.Uint:
		return uint(randplus.MustRandint(1, 4294967295))
	case reflect.Uint8:
		return uint8(randplus.MustRandint(1, 255))
	case reflect.Uint16:
		return uint16(randplus.MustRandint(1, 65535))
	case reflect.Uint32:
		return uint32(randplus.MustRandint(1, 4294967295))
	case reflect.Uint64:
		return uint64(randplus.MustRandint(1, 9223372036854775807))
	case reflect.Float32:
		return float32(rand.Float32())
	case reflect.Float64:
		return float64(rand.Float64())
	case reflect.Complex64:
		return complex64(complex(rand.Float32(), rand.Float32()))
	case reflect.Complex128:
		return complex128(complex(rand.Float64(), rand.Float64()))
	case reflect.String:
		samples := []string{"abc", "test", "this is a string"}
		weights := []int{}
		for i := 0; i < len(samples); i++ {
			weights = append(weights, 1)
		}
		index := randplus.MustWeightSample(weights)
		return samples[index]
	default:
		return nil
	}
}

func mockAny(v reflect.Value, isKeep bool) interface{} {
	v = DeepElemValue(v)
	switch v.Kind() {
	case reflect.Map:
		return mockMap(v, isKeep, true)
	case reflect.Struct:
		return mockStruct(v, isKeep, true)
	case reflect.Slice:
		return mockSlice(v, isKeep, true)
	case reflect.Array:
		return mockArray(v, isKeep, true)
	case reflect.Chan, reflect.Func, reflect.Interface:
		return nil
	default:
		if isKeep {
			if !v.IsValid() {
				return reflect.New(v.Type()).Interface()
			}
			return v.Interface()
		}
		return randomNew(v.Type())
	}
}

// MockStruct ...
func MockStruct(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockStruct(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockStruct ..
func mockStruct(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	for i := 0; i < v.NumField(); i++ {
		fieldValue := v.Field(i)
		fieldType := v.Type().Field(i)
		if fieldType.PkgPath == "" { // 只处理导出的字段
			key := structFieldName(fieldType, "json")
			var val interface{}
			if isRecurse {
				val = mockAny(reflect.New(fieldType.Type), isKeep)
			} else {
				val = DeepElemValue(fieldValue).Interface()
			}
			result[key] = val
		}
	}
	if len(result) == 0 {
		return v.Interface()
	}
	return result
}

// MockSlice ...
func MockSlice(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockSlice(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockSlice ..
func mockSlice(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := mockArray(v, isKeep, isRecurse).([]interface{})
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockArray ...
func MockArray(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockArray(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockArray ..
func mockArray(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := []interface{}{}
	for i := 0; i < v.Len(); i++ {
		var val interface{}
		if isRecurse {
			val = mockAny(v.Index(i), isKeep)
		} else {
			val = v.Index(i).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockMap ...
func MockMap(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockMap(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockMap ..
func mockMap(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	iter := v.MapRange()
	for iter.Next() {
		key := iter.Key().String()
		var val interface{}
		if isRecurse {
			val = mockAny(iter.Value(), isKeep)
		} else {
			val = iter.Value().Interface()
		}
		result[key] = val
	}
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result[""] = val
	}
	return result
}

import * as THREE from 'three';

const UNIFORMS = {
    // rgba
    u_g1_color: new THREE.Uniform(new THREE.Vector4(0, 0, 0, 1))
};

const CNC_LASER_VERT_SHADER = [
    'varying float v_g_code;',
    'attribute float a_g_code;',
    'void main(){',
    '    v_g_code = a_g_code;',
    '    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
    '}'
].join('');

const CNC_LASER_FRAG_SHADER = [
    'uniform vec4 u_g1_color;',
    'varying float v_g_code;',
    'void main(){',
    '    if(v_g_code == 0.0){',
    '        discard;',
    '    }',
    '    gl_FragColor = u_g1_color;',
    '}'
].join('');

const motionColor = {
    'G0': new THREE.Color(0xc8c8c8),
    'G1': new THREE.Color(0x000000),
    'unknown': new THREE.Color(0x000000)
};

class ToolPathRenderer {
    render(toolPath) {
        const { headerType, mode, movementMode, data } = toolPath;

        // now only support cnc&laser
        if (!['cnc', 'laser'].includes(headerType)) {
            return null;
        }

        if (headerType === 'laser') {
            if (mode === 'greyscale' && movementMode === 'greyscale-dot') {
                return this.parseToPoints(data);
            } else {
                return this.parseToLine(data);
            }
        } else {
            return this.parseToLine(data);
        }
    }

    parseToLine(data) {
        const positions = [];
        const gCodes = [];

        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if ((state.G === 1) && (newState.G === 0)) {
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(newState.G);
            }

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(state.G);
            }
        }

        const bufferGeometry = new THREE.BufferGeometry();
        const positionAttribute = new THREE.Float32BufferAttribute(positions, 3);
        const gCodeAttribute = new THREE.Float32BufferAttribute(gCodes, 1);
        bufferGeometry.addAttribute('position', positionAttribute);
        bufferGeometry.addAttribute('a_g_code', gCodeAttribute);
        const material = new THREE.ShaderMaterial({
            uniforms: UNIFORMS,
            vertexShader: CNC_LASER_VERT_SHADER,
            fragmentShader: CNC_LASER_FRAG_SHADER,
            side: THREE.DoubleSide,
            transparent: true,
            linewidth: 1
        });
        return new THREE.Line(bufferGeometry, material);
    }

    parseToPoints(data) {
        const geometry = new THREE.Geometry();
        const material = new THREE.PointsMaterial({
            size: 0.1,
            vertexColors: THREE.VertexColors,
            opacity: 0.9,
            transparent: true
        });
        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                geometry.vertices.push(new THREE.Vector3(state.X, state.Y, state.Z));
                if (state.G === 0) {
                    geometry.colors.push(motionColor.G0);
                } else if (state.G === 1) {
                    geometry.colors.push(motionColor.G1);
                } else {
                    geometry.colors.push(motionColor.unknown);
                }
            }
        }
        return new THREE.Points(geometry, material);
    }
}

export default ToolPathRenderer;

package reflect

import (
	"math/rand"
	"reflect"

	randplus "github.com/cheetah-fun-gs/goplus/math/rand"
)

// Mock 生成 随机值的 mock 数据
func Mock(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), false)
}

// MockKeep 生成 原值或0值的 mock 数据
func MockKeep(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), true)
}

func randomNew(typ reflect.Type) interface{} {
	switch typ.Kind() {
	case reflect.Bool:
		return false
	case reflect.Int:
		return int(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int8:
		return int8(randplus.MustRandint(-128, 127))
	case reflect.Int16:
		return int16(randplus.MustRandint(-32768, 32767))
	case reflect.Int32:
		return int32(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int64:
		return int64(randplus.MustRandint(-9223372036854775808, 9223372036854775807))
	case reflect.Uint:
		return uint(randplus.MustRandint(1, 4294967295))
	case reflect.Uint8:
		return uint8(randplus.MustRandint(1, 255))
	case reflect.Uint16:
		return uint16(randplus.MustRandint(1, 65535))
	case reflect.Uint32:
		return uint32(randplus.MustRandint(1, 4294967295))
	case reflect.Uint64:
		return uint64(randplus.MustRandint(1, 9223372036854775807))
	case reflect.Float32:
		return float32(rand.Float32())
	case reflect.Float64:
		return float64(rand.Float64())
	case reflect.Complex64:
		return complex64(complex(rand.Float32(), rand.Float32()))
	case reflect.Complex128:
		return complex128(complex(rand.Float64(), rand.Float64()))
	case reflect.String:
		samples := []string{"abc", "test", "this is a string"}
		weights := []int{}
		for i := 0; i < len(samples); i++ {
			weights = append(weights, 1)
		}
		index := randplus.MustWeightSample(weights)
		return samples[index]
	default:
		return nil
	}
}

func mockAny(v reflect.Value, isKeep bool) interface{} {
	v = DeepElemValue(v)
	switch v.Kind() {
	case reflect.Map:
		return mockMap(v, isKeep, true)
	case reflect.Struct:
		return mockStruct(v, isKeep, true)
	case reflect.Slice:
		return mockSlice(v, isKeep, true)
	case reflect.Array:
		return mockArray(v, isKeep, true)
	case reflect.Chan, reflect.Func, reflect.Interface:
		return nil
	default:
		if isKeep {
			if !v.IsValid() {
				return reflect.New(v.Type()).Interface()
			}
			return v.Interface()
		}
		return randomNew(v.Type())
	}
}

// MockStruct ...
func MockStruct(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockStruct(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockStruct ..
func mockStruct(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	for i := 0; i < v.NumField(); i++ {
		fieldValue := v.Field(i)
		fieldType := v.Type().Field(i)
		if fieldType.PkgPath == "" { // 只处理导出的字段
			key := structFieldName(fieldType, "json")
			var val interface{}
			if isRecurse {
				val = mockAny(reflect.New(fieldType.Type), isKeep)
			} else {
				val = DeepElemValue(fieldValue).Interface()
			}
			result[key] = val
		}
	}
	if len(result) == 0 {
		return v.Interface()
	}
	return result
}

// MockSlice ...
func MockSlice(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockSlice(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockSlice ..
func mockSlice(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := mockArray(v, isKeep, isRecurse).([]interface{})
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockArray ...
func MockArray(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockArray(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockArray ..
func mockArray(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := []interface{}{}
	for i := 0; i < v.Len(); i++ {
		var val interface{}
		if isRecurse {
			val = mockAny(v.Index(i), isKeep)
		} else {
			val = v.Index(i).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockMap ...
func MockMap(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockMap(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockMap ..
func mockMap(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	iter := v.MapRange()
	for iter.Next() {
		key := iter.Key().String()
		var val interface{}
		if isRecurse {
			val = mockAny(iter.Value(), isKeep)
		} else {
			val = iter.Value().Interface()
		}
		result[key] = val
	}
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result[""] = val
	}
	return result
}

import * as THREE from 'three';

const UNIFORMS = {
    // rgba
    u_g1_color: new THREE.Uniform(new THREE.Vector4(0, 0, 0, 1))
};

const CNC_LASER_VERT_SHADER = [
    'varying float v_g_code;',
    'attribute float a_g_code;',
    'void main(){',
    '    v_g_code = a_g_code;',
    '    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
    '}'
].join('');

const CNC_LASER_FRAG_SHADER = [
    'uniform vec4 u_g1_color;',
    'varying float v_g_code;',
    'void main(){',
    '    if(v_g_code == 0.0){',
    '        discard;',
    '    }',
    '    gl_FragColor = u_g1_color;',
    '}'
].join('');

const motionColor = {
    'G0': new THREE.Color(0xc8c8c8),
    'G1': new THREE.Color(0x000000),
    'unknown': new THREE.Color(0x000000)
};

class ToolPathRenderer {
    render(toolPath) {
        const { headerType, mode, movementMode, data } = toolPath;

        // now only support cnc&laser
        if (!['cnc', 'laser'].includes(headerType)) {
            return null;
        }

        if (headerType === 'laser') {
            if (mode === 'greyscale' && movementMode === 'greyscale-dot') {
                return this.parseToPoints(data);
            } else {
                return this.parseToLine(data);
            }
        } else {
            return this.parseToLine(data);
        }
    }

    parseToLine(data) {
        const positions = [];
        const gCodes = [];

        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if ((state.G === 1) && (newState.G === 0)) {
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(newState.G);
            }

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(state.G);
            }
        }

        const bufferGeometry = new THREE.BufferGeometry();
        const positionAttribute = new THREE.Float32BufferAttribute(positions, 3);
        const gCodeAttribute = new THREE.Float32BufferAttribute(gCodes, 1);
        bufferGeometry.addAttribute('position', positionAttribute);
        bufferGeometry.addAttribute('a_g_code', gCodeAttribute);
        const material = new THREE.ShaderMaterial({
            uniforms: UNIFORMS,
            vertexShader: CNC_LASER_VERT_SHADER,
            fragmentShader: CNC_LASER_FRAG_SHADER,
            side: THREE.DoubleSide,
            transparent: true,
            linewidth: 1
        });
        return new THREE.Line(bufferGeometry, material);
    }

    parseToPoints(data) {
        const geometry = new THREE.Geometry();
        const material = new THREE.PointsMaterial({
            size: 0.1,
            vertexColors: THREE.VertexColors,
            opacity: 0.9,
            transparent: true
        });
        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                geometry.vertices.push(new THREE.Vector3(state.X, state.Y, state.Z));
                if (state.G === 0) {
                    geometry.colors.push(motionColor.G0);
                } else if (state.G === 1) {
                    geometry.colors.push(motionColor.G1);
                } else {
                    geometry.colors.push(motionColor.unknown);
                }
            }
        }
        return new THREE.Points(geometry, material);
    }
}

export default ToolPathRenderer;

package reflect

import (
	"math/rand"
	"reflect"

	randplus "github.com/cheetah-fun-gs/goplus/math/rand"
)

// Mock 生成 随机值的 mock 数据
func Mock(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), false)
}

// MockKeep 生成 原值或0值的 mock 数据
func MockKeep(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), true)
}

func randomNew(typ reflect.Type) interface{} {
	switch typ.Kind() {
	case reflect.Bool:
		return false
	case reflect.Int:
		return int(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int8:
		return int8(randplus.MustRandint(-128, 127))
	case reflect.Int16:
		return int16(randplus.MustRandint(-32768, 32767))
	case reflect.Int32:
		return int32(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int64:
		return int64(randplus.MustRandint(-9223372036854775808, 9223372036854775807))
	case reflect.Uint:
		return uint(randplus.MustRandint(1, 4294967295))
	case reflect.Uint8:
		return uint8(randplus.MustRandint(1, 255))
	case reflect.Uint16:
		return uint16(randplus.MustRandint(1, 65535))
	case reflect.Uint32:
		return uint32(randplus.MustRandint(1, 4294967295))
	case reflect.Uint64:
		return uint64(randplus.MustRandint(1, 9223372036854775807))
	case reflect.Float32:
		return float32(rand.Float32())
	case reflect.Float64:
		return float64(rand.Float64())
	case reflect.Complex64:
		return complex64(complex(rand.Float32(), rand.Float32()))
	case reflect.Complex128:
		return complex128(complex(rand.Float64(), rand.Float64()))
	case reflect.String:
		samples := []string{"abc", "test", "this is a string"}
		weights := []int{}
		for i := 0; i < len(samples); i++ {
			weights = append(weights, 1)
		}
		index := randplus.MustWeightSample(weights)
		return samples[index]
	default:
		return nil
	}
}

func mockAny(v reflect.Value, isKeep bool) interface{} {
	v = DeepElemValue(v)
	switch v.Kind() {
	case reflect.Map:
		return mockMap(v, isKeep, true)
	case reflect.Struct:
		return mockStruct(v, isKeep, true)
	case reflect.Slice:
		return mockSlice(v, isKeep, true)
	case reflect.Array:
		return mockArray(v, isKeep, true)
	case reflect.Chan, reflect.Func, reflect.Interface:
		return nil
	default:
		if isKeep {
			if !v.IsValid() {
				return reflect.New(v.Type()).Interface()
			}
			return v.Interface()
		}
		return randomNew(v.Type())
	}
}

// MockStruct ...
func MockStruct(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockStruct(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockStruct ..
func mockStruct(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	for i := 0; i < v.NumField(); i++ {
		fieldValue := v.Field(i)
		fieldType := v.Type().Field(i)
		if fieldType.PkgPath == "" { // 只处理导出的字段
			key := structFieldName(fieldType, "json")
			var val interface{}
			if isRecurse {
				val = mockAny(reflect.New(fieldType.Type), isKeep)
			} else {
				val = DeepElemValue(fieldValue).Interface()
			}
			result[key] = val
		}
	}
	if len(result) == 0 {
		return v.Interface()
	}
	return result
}

// MockSlice ...
func MockSlice(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockSlice(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockSlice ..
func mockSlice(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := mockArray(v, isKeep, isRecurse).([]interface{})
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockArray ...
func MockArray(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockArray(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockArray ..
func mockArray(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := []interface{}{}
	for i := 0; i < v.Len(); i++ {
		var val interface{}
		if isRecurse {
			val = mockAny(v.Index(i), isKeep)
		} else {
			val = v.Index(i).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockMap ...
func MockMap(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockMap(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockMap ..
func mockMap(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	iter := v.MapRange()
	for iter.Next() {
		key := iter.Key().String()
		var val interface{}
		if isRecurse {
			val = mockAny(iter.Value(), isKeep)
		} else {
			val = iter.Value().Interface()
		}
		result[key] = val
	}
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result[""] = val
	}
	return result
}

---
layout: post
title: 4. Cartesian Control
category: ROS
tag: ROS
---
- to understand TF look at the my [](https://leechangyo.github.io/robotics/2019/10/04/Kinematic-Model/) post

# Cartesian Control

> Cartesian Control


```python
#!/usr/bin/env python

import math
import numpy
import time
from threading import Thread, Lock

import rospy
import tf
from geometry_msgs.msg import Transform
from sensor_msgs.msg import JointState
from std_msgs.msg import Float32
from urdf_parser_py.urdf import URDF

def S_matrix(w):
    S = numpy.zeros((3,3))
    S[0,1] = -w[2]
    S[0,2] =  w[1]
    S[1,0] =  w[2]
    S[1,2] = -w[0]
    S[2,0] = -w[1]
    S[2,1] =  w[0]
    return S

# This is the function that must be filled in as part of the Project.
def cartesian_control(joint_transforms, b_T_ee_current, b_T_ee_desired,
                      red_control, q_current, q0_desired):
    num_joints = len(joint_transforms)
    dq = numpy.zeros(num_joints)
    #-------------------- Fill in your code here ---------------------------
    J = numpy.zeros((6,num_joints))
    ee_V_ee = numpy.zeros(6) # array([0., 0., 0., 0., 0., 0.])

    T_to_desired = numpy.dot(numpy.linalg.inv(b_T_ee_current),b_T_ee_desired) # symmetry make

    angle, axis = rotation_from_matrix(T_to_desired)
    ## in base frame
    delta_p = T_to_desired[:3,3] #
    delta_theta = numpy.dot(axis,angle)

    p_dot = delta_p*1
    theta_dot = delta_theta*1

    #ee_T_b = numpy.linalg.inv(b_T_ee_current)
    ee_R_b = T_to_desired[:3,:3]

    ee_V_ee[:3] = numpy.dot(ee_R_b,p_dot)
    ee_V_ee[3:] = numpy.dot(ee_R_b,theta_dot)

    for i in range(num_joints):
        J[:,i] = adjoint_matrix(numpy.dot(numpy.linalg.inv(b_T_ee_current),joint_transforms[i]))[:,5]
    dq = numpy.dot(numpy.linalg.pinv(J,0.01),ee_V_ee)
    #----------------------------------------------------------------------
    return dq

def convert_from_message(t):
    trans = tf.transformations.translation_matrix((t.translation.x,
                                                  t.translation.y,
                                                  t.translation.z))
    rot = tf.transformations.quaternion_matrix((t.rotation.x,
                                                t.rotation.y,
                                                t.rotation.z,
                                                t.rotation.w))
    T = numpy.dot(trans,rot)
    return T

def adjoint_matrix(i_T_j):

    i_p_j = numpy.linalg.inv(i_T_j)[:3, 3] # raw column
    i_R_j = i_T_j[:3, :3]
    Ad = numpy.zeros((6,6))
    Ad[:3,:3] = i_R_j
    Ad[3:,3:] = i_R_j
    Ad[:3,3:] = -numpy.dot(i_R_j,S_matrix(i_p_j))

    return Ad

# Returns the angle-axis representation of the rotation contained in the input matrix
# Use like this:
# angle, axis = rotation_from_matrix(R)
def rotation_from_matrix(matrix):
    R = numpy.array(matrix, dtype=numpy.float64, copy=False)
    R33 = R[:3, :3]
    # axis: unit eigenvector of R33 corresponding to eigenvalue of 1
    l, W = numpy.linalg.eig(R33.T)
    i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
    if not len(i):
        raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
    axis = numpy.real(W[:, i[-1]]).squeeze()
    # point: unit eigenvector of R33 corresponding to eigenvalue of 1
    l, Q = numpy.linalg.eig(R)
    i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
    if not len(i):
        raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
    # rotation angle depending on axis
    cosa = (numpy.trace(R33) - 1.0) / 2.0
    if abs(axis[2]) > 1e-8:
        sina = (R[1, 0] + (cosa-1.0)*axis[0]*axis[1]) / axis[2]
    elif abs(axis[1]) > 1e-8:
        sina = (R[0, 2] + (cosa-1.0)*axis[0]*axis[2]) / axis[1]
    else:
        sina = (R[2, 1] + (cosa-1.0)*axis[1]*axis[2]) / axis[0]
    angle = math.atan2(sina, cosa)
    return angle, axis

class CartesianControl(object):

    #Initialization
    def __init__(self):
        #Loads the robot model, which contains the robot's kinematics information
        self.robot = URDF.from_parameter_server()

        #Subscribes to information about what the current joint values are.
        rospy.Subscriber("/joint_states", JointState, self.joint_callback)

        #Subscribes to command for end-effector pose
        rospy.Subscriber("/cartesian_command", Transform, self.command_callback)

        #Subscribes to command for redundant dof
        rospy.Subscriber("/redundancy_command", Float32, self.redundancy_callback)

        # Publishes desired joint velocities
        self.pub_vel = rospy.Publisher("/joint_velocities", JointState, queue_size=1)

        #This is where we hold the most recent joint transforms
        self.joint_transforms = []
        self.q_current = []
        self.x_current = tf.transformations.identity_matrix()
        self.R_base = tf.transformations.identity_matrix()
        self.x_target = tf.transformations.identity_matrix()
        self.q0_desired = 0
        self.last_command_time = 0
        self.last_red_command_time = 0

        # Initialize timer that will trigger callbacks
        self.mutex = Lock()
        self.timer = rospy.Timer(rospy.Duration(0.1), self.timer_callback)

    def command_callback(self, command):
        self.mutex.acquire()
        self.x_target = convert_from_message(command)
        self.last_command_time = time.time()
        self.mutex.release()

    def redundancy_callback(self, command):
        self.mutex.acquire()
        self.q0_desired = command.data
        self.last_red_command_time = time.time()
        self.mutex.release()        

    def timer_callback(self, event):
        msg = JointState()
        self.mutex.acquire()
        if time.time() - self.last_command_time < 0.5:
            dq = cartesian_control(self.joint_transforms,
                                   self.x_current, self.x_target,
                                   False, self.q_current, self.q0_desired)
            msg.velocity = dq
        elif time.time() - self.last_red_command_time < 0.5:
            dq = cartesian_control(self.joint_transforms,
                                   self.x_current, self.x_current,
                                   True, self.q_current, self.q0_desired)
            msg.velocity = dq
        else:            
            msg.velocity = numpy.zeros(7)
        self.mutex.release()
        self.pub_vel.publish(msg)

    def joint_callback(self, joint_values):
        root = self.robot.get_root()
        T = tf.transformations.identity_matrix()
        self.mutex.acquire()
        self.joint_transforms = []
        self.q_current = joint_values.position
        self.process_link_recursive(root, T, joint_values)
        self.mutex.release()

    def align_with_z(self, axis):
        T = tf.transformations.identity_matrix()
        z = numpy.array([0,0,1])
        x = numpy.array([1,0,0])
        dot = numpy.dot(z,axis)
        if dot == 1: return T
        if dot == -1: return tf.transformation.rotation_matrix(math.pi, x)
        rot_axis = numpy.cross(z, axis)
        angle = math.acos(dot)
        return tf.transformations.rotation_matrix(angle, rot_axis)

    def process_link_recursive(self, link, T, joint_values):
        if link not in self.robot.child_map:
            self.x_current = T
            return
        for i in range(0,len(self.robot.child_map[link])):
            (joint_name, next_link) = self.robot.child_map[link][i]
            if joint_name not in self.robot.joint_map:
                rospy.logerror("Joint not found in map")
                continue
            current_joint = self.robot.joint_map[joint_name]        

            trans_matrix = tf.transformations.translation_matrix((current_joint.origin.xyz[0],
                                                                  current_joint.origin.xyz[1],
                                                                  current_joint.origin.xyz[2]))
            rot_matrix = tf.transformations.euler_matrix(current_joint.origin.rpy[0],
                                                         current_joint.origin.rpy[1],
                                                         current_joint.origin.rpy[2], 'rxyz')
            origin_T = numpy.dot(trans_matrix, rot_matrix)
            current_joint_T = numpy.dot(T, origin_T)
            if current_joint.type != 'fixed':
                if current_joint.name not in joint_values.name:
                    rospy.logerror("Joint not found in list")
                    continue
                # compute transform that aligns rotation axis with z
                aligned_joint_T = numpy.dot(current_joint_T, self.align_with_z(current_joint.axis))
                self.joint_transforms.append(aligned_joint_T)
                index = joint_values.name.index(current_joint.name)
                angle = joint_values.position[index]
                joint_rot_T = tf.transformations.rotation_matrix(angle,
                                                                 numpy.asarray(current_joint.axis))
                next_link_T = numpy.dot(current_joint_T, joint_rot_T)
            else:
                next_link_T = current_joint_T

            self.process_link_recursive(next_link, next_link_T, joint_values)

if __name__ == '__main__':
    rospy.init_node('cartesian_control', anonymous=True)
    cc = CartesianControl()
    rospy.spin()



```

<a href="https://postimg.cc/Hc2jxBXX"><img src="https://i.postimg.cc/wMKNwrBf/Capture.png" width="700px" title="source: imgur.com" /><a>
<a href="https://postimg.cc/xJkFjFWF"><img src="https://i.postimg.cc/ZRjkcGjZ/Capture.png" width="700px" title="source: imgur.com" /><a>
<a href="https://postimg.cc/Yv9Py9dH"><img src="https://i.postimg.cc/Hk4Cn85V/Capture.png" width="700px" title="source: imgur.com" /><a>

package io.github.poulad.hnp.web.error;

import javax.annotation.Nonnull;
import lombok.Value;

@Value
public class ValidationError {

  @Nonnull
  String parameter;

  @Nonnull
  RequestParameterType parameterType;

  @Nonnull
  String errorMessage;
}

#!/usr/bin/env python

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write("<html><body><h1>hello from the other side!</h1></body></html>")

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])  # <--- Gets the size of data
        post_data = self.rfile.read(content_length)  # <--- Gets the data itself
        print "RECEIVED DATA FROM POST" , post_data # <-- Print post data
        print "\n \n"
        self._set_headers()
        self.wfile.write("<html><body><h1>POST!</h1><pre>" + post_data + "</pre></body></html>")

def run(server_class=HTTPServer, handler_class=S,ip='127.0.0.1' port=8081):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print 'Starting HTTP server at {0}:{1} .....'.format(ip,port)
    httpd.serve_forever()


if __name__ == "__main__":
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

#pragma once
#include <functional>

namespace Server
{
    enum class WhatHappened
    {
        LibraryLoadingError,
        AddressInitializationError,
        AddressBindingError,
        SocketCreationError,
        Ok,
        RequestHandlerIsNull,
        SocketInitializationFailed,
        RequestProcessingFatalError,
        RecvFailed,
        SendFailed,
        ConnectionClosed
    };

    using Handler = const std::function<std::string(const std::string_view)> &;

    std::string ToString(const WhatHappened what);

    WhatHappened Start(Handler onRequest);
}
var styles = [
      {
          "featureType": "administrative",
          "elementType": "geometry",
          "stylers": [
              {
                  "color": "#dfeae3"
              }
          ]
      },
      {
          "featureType": "administrative",
          "elementType": "labels.text.fill",
          "stylers": [
              {
                  "color": "#444444"
              }
          ]
      },
      {
          "featureType": "administrative.locality",
          "elementType": "labels",
          "stylers": [
              {
                  "visibility": "on"
              }
          ]
      },
      {
          "featureType": "landscape",
          "elementType": "all",
          "stylers": [
              {
                  "color": "#f2f2f2"
              },
              {
                  "visibility": "simplified"
              }
          ]
      },
      {
          "featureType": "poi",
          "elementType": "all",
          "stylers": [
              {
                  "visibility": "on"
              }
          ]
      },
      {
          "featureType": "poi",
          "elementType": "geometry",
          "stylers": [
              {
                  "visibility": "simplified"
              },
              {
                  "saturation": "-65"
              },
              {
                  "lightness": "45"
              },
              {
                  "gamma": "1.78"
              }
          ]
      },
      {
          "featureType": "poi",
          "elementType": "labels",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "poi",
          "elementType": "labels.icon",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "road",
          "elementType": "all",
          "stylers": [
              {
                  "saturation": -100
              },
              {
                  "lightness": 45
              }
          ]
      },
      {
          "featureType": "road",
          "elementType": "labels",
          "stylers": [
              {
                  "visibility": "on"
              }
          ]
      },
      {
          "featureType": "road",
          "elementType": "labels.icon",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "road.highway",
          "elementType": "all",
          "stylers": [
              {
                  "visibility": "simplified"
              }
          ]
      },
      {
          "featureType": "road.highway",
          "elementType": "labels.icon",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "road.arterial",
          "elementType": "labels.icon",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "transit.line",
          "elementType": "geometry",
          "stylers": [
              {
                  "saturation": "-33"
              },
              {
                  "lightness": "22"
              },
              {
                  "gamma": "2.08"
              }
          ]
      },
      {
          "featureType": "transit.station.airport",
          "elementType": "geometry",
          "stylers": [
              {
                  "gamma": "2.08"
              },
              {
                  "hue": "#ffa200"
              }
          ]
      },
      {
          "featureType": "transit.station.airport",
          "elementType": "labels",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "transit.station.rail",
          "elementType": "labels.text",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "transit.station.rail",
          "elementType": "labels.icon",
          "stylers": [
              {
                  "visibility": "simplified"
              },
              {
                  "saturation": "-55"
              },
              {
                  "lightness": "-2"
              },
              {
                  "gamma": "1.88"
              },
              {
                  "hue": "#ffab00"
              }
          ]
      },
      {
          "featureType": "water",
          "elementType": "all",
          "stylers": [
              {
                  "color": "#bbd9e5"
              },
              {
                  "visibility": "simplified"
              }
          ]
      }
]

if (document.getElementById('map-canvas')) {

  function initialize() {
      var myLatlng = new google.maps.LatLng(47.245236, -122.362339);
      var mapOptions = {
          zoom: 13,
          styles: styles,
          center: myLatlng,
          draggable: false,
          scrollwheel: false,
          mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

       //=====Initialise Default Marker
      var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          title: 'marker',
          icon: {
            url: mapIncludes.markericon,
            size: new google.maps.Size(21, 38),
            scaledSize: new google.maps.Size(21, 38),
            anchor: new google.maps.Point(21, 38)
          }
       //=====You can even customize the icons here
      });

      /*
       //=====Initialise InfoWindow
      var infowindow = new google.maps.InfoWindow({
        // TODO: Confirm this content?
        content: "<B>Skyway Dr</B>"
    });

     //=====Eventlistener for InfoWindow
    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });
    */
  }

  google.maps.event.addDomListener(window, 'load', initialize);
}

package com.skt.nugu.sdk.core.network

import com.skt.nugu.sdk.core.interfaces.connection.ConnectionStatusListener
import com.skt.nugu.sdk.core.interfaces.connection.ConnectionManagerInterface
import com.skt.nugu.sdk.core.interfaces.message.*
import java.util.concurrent.CopyOnWriteArraySet

/**
 * This class is designed to manage connections.
 */
class NetworkManager private constructor(
    private val messageRouter: MessageRouterInterface
) : ConnectionManagerInterface,
    MessageSender by messageRouter,
    MessageRouterObserverInterface {

    companion object {
        /**
         * Create a [NetworkManager]
         * @return a [NetworkManager] instance
         */
        fun create(messageRouter: MessageRouterInterface): NetworkManager {
            val connectionManager = NetworkManager(messageRouter)

            messageRouter.setObserver(connectionManager)

            return connectionManager
        }
    }

    private var enabled = false
    private val messageObservers = CopyOnWriteArraySet<MessageObserver>()
    private val connectionStatusObservers = CopyOnWriteArraySet<ConnectionStatusListener>()
    /**
     * Initiate a connection to DeviceGateway.
     */
    override fun enable() {
        enabled = true
        messageRouter.enable()
    }
    /**
     * Disconnect from DeviceGateway.
     */
    override fun disable() {
        enabled = false
        messageRouter.disable()
    }
    /**
     * check whether a enable
     */
    override fun isEnabled(): Boolean = enabled

    /**
     * reconnect from DeviceGateway.
     */
    override fun reconnect() {
        if (enabled) {
            messageRouter.disable()
            messageRouter.enable()
        }
    }
    /**
     * Returns whether this object is currently connected to DeviceGateway.
     */
    override fun isConnected(): Boolean =
        messageRouter.getConnectionStatus() == ConnectionStatusListener.Status.CONNECTED

    /**
     * Adds an observer to be notified when a message arrives from DeviceGateway.
     * @param observer The observer to add.
     */
    override fun addMessageObserver(observer: MessageObserver) {
        messageObservers.add(observer)
    }

    /**
     * Removes an observer to be notified when a message arrives from DeviceGateway.
     * @param observer The observer to remove.
     */
    override fun removeMessageObserver(observer: MessageObserver) {
        messageObservers.remove(observer)
    }

    /**
     * Adds an observer to be notified of connection status changes.
     * @param observer The observer to add.
     */
    override fun addConnectionStatusListener(listener: ConnectionStatusListener) {
        connectionStatusObservers.add(listener)
        listener.onConnectionStatusChanged(
            messageRouter.getConnectionStatus(),
            ConnectionStatusListener.ChangedReason.NONE
        )
    }

    /**
     * Removes an observer from being notified of connection status changes.
     * @param observer The observer to remove.
     */
    override fun removeConnectionStatusListener(listener: ConnectionStatusListener) {
        connectionStatusObservers.remove(listener)
    }

    /**
     * Receives the connection status changes.
     */
    override fun onConnectionStatusChanged(
        status: ConnectionStatusListener.Status,
        reason: ConnectionStatusListener.ChangedReason
    ) {
        connectionStatusObservers.forEach { it.onConnectionStatusChanged(status,reason) }
    }

    override fun receiveDirectives(directives: List<DirectiveMessage>) {
        messageObservers.forEach {
            it.receiveDirectives(directives)
        }
    }

    override fun receiveAttachment(attachment: AttachmentMessage) {
        messageObservers.forEach {
            it.receiveAttachment(attachment)
        }
    }

    /**
     *  handoff connection from SystemCapability
     */
    override fun handoffConnection(
        protocol: String,
        hostname: String,
        address: String,
        port: Int,
        retryCountLimit: Int,
        connectionTimeout: Int,
        charge: String
    ) {
        messageRouter.handoffConnection(protocol, hostname, address, port, retryCountLimit, connectionTimeout, charge)
    }

    /**
     * Resets the connection immediately.
     */
    override fun resetConnection(description: String?) {
        messageRouter.resetConnection(description)
    }

    /**
     * Set the keepConnection
     */
    override fun keepConnection(enabled: Boolean) = messageRouter.keepConnection(enabled)
}
package com.monet.bidder

import android.os.Bundle
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner

@RunWith(RobolectricTestRunner::class)
class DfpRequestHelperTest {
    private val adSize = AdSize(300, 250)
    @Test
    fun `Given ADUNIT_KEYWORD_KEY is present in Bundle  get adUnitId from customEventExtras`() {
        val adUnitId = "adUnitId"
        val serverParameter = "serverParam"
        val customEventExtras = Bundle()
        customEventExtras.putString(Constants.Dfp.ADUNIT_KEYWORD_KEY, adUnitId)
        val helperAdUnit = DfpRequestHelper.getAdUnitID(customEventExtras, serverParameter, adSize)
        Assert.assertEquals(helperAdUnit, adUnitId)
    }

    @Test
    fun `Given ADUNIT_KEYWORD_KEY is not present and serverParameter is not null, 'default' or 'AMAdSize' and it starts with $ sign`() {
        val adUnit = DfpRequestHelper.getAdUnitID(Bundle(), "$100", adSize);
        Assert.assertEquals("300x250", adUnit)
    }

    @Test
    fun `Given ADUNIT_KEYWORD_KEY is not present and serverParameter is not null, 'default' or 'AMAdSize' and it does not start with $ sign (adunit cpm format)`() {
        val serverParam = "test_interstitial@$100"
        val adUnit = DfpRequestHelper.getAdUnitID(Bundle(), serverParam, adSize)
        Assert.assertEquals(adUnit, "test_interstitial")
    }

    @Test
    fun `Given ADUNIT_KEYWORD_KEY is not present and serverParameter is not null, 'default' or 'AMAdSize' and it does not start with $ sign (normal format)`() {
        val normalAdUnitServerParam = "only_ad_unit"
        val adUnit = DfpRequestHelper.getAdUnitID(Bundle(), normalAdUnitServerParam, adSize)
        Assert.assertEquals(adUnit, normalAdUnitServerParam)
    }

    @Test
    fun `Given ADUNIT_KEYWORD_KEY is not present and serverParameters default or AMAdSize`() {
        val defaultServerParam = "default"
        val adUnit = DfpRequestHelper.getAdUnitID(Bundle(), defaultServerParam, adSize)
        Assert.assertEquals(adUnit, "300x250")
        val amAdSizeServerParam = "AMAdSize"
        val unit = DfpRequestHelper.getAdUnitID(Bundle(), amAdSizeServerParam, adSize)
        Assert.assertEquals(unit, "300x250")
    }

    @Test
    fun `Given ADUNIT_KEYWORD_KEY is not present and serverParameter is empty get ad size as adUnit`() {
        val serverParam = ""
        val adUnit = DfpRequestHelper.getAdUnitID(Bundle(), serverParam, adSize)
        Assert.assertEquals(adUnit, "300x250")
    }

    @Test
    fun `Given serverParameter is empty or null return 0 cpm`() {
        Assert.assertEquals(DfpRequestHelper.getCpm(""), 0.0, 0.0)
        Assert.assertEquals(DfpRequestHelper.getCpm(null), 0.0, 0.0)
    }

    @Test
    fun `Given serverParameter starts with $ sign followed by a number`() {
        val cpm = DfpRequestHelper.getCpm("$5.00")
        Assert.assertEquals(cpm, 5.00, 5.00)
    }

    @Test
    fun `Given serverParameter starts with $sign followed by not a number`() {
        val cpm = DfpRequestHelper.getCpm("\$JOSE")
        Assert.assertEquals(cpm, 0.0, 0.0)
    }

    @Test
    fun `Given serverParameter has adUnitId and cpm`(){
        val cpm = DfpRequestHelper.getCpm("test_adunit@$5.00")
        Assert.assertEquals(cpm, 5.0, 5.0)
    }

    @Test
    fun `Given serverParameter has adUnitId and cpm not as a number`(){
        val cpm = DfpRequestHelper.getCpm("test_adunit@\$JOSE")
        Assert.assertEquals(cpm, 0.0, 0.0)
    }
}
module.exports = `body{
    margin:0;   
}

a{
    text-decoration: none !important;
    color: #000 !important;
}

.hide{
    display: none;
}

@media (min-width:200px) and (max-width:740px){
    .matias-navigation{
        z-index: 9999999999;
        margin-top: 0px;
        top: 0;
        width: 100%;
        text-align: center;
        padding-top: 0px;
		height: 100%;
        position: fixed;
        background: #FFF;
        overflow: auto;
    }
}

nav.matias-navigation ul{
    list-style: none;
    width: 100%;
    margin: 0px auto;
}

.matias-navigation__logo{
    width: 100%;
    float: none;
    text-align: center;
    margin: 0px auto;
    background: #000;
    padding-top: 10px;
    padding-bottom: 10px;
}

.matias-navigation__logo a img {
    max-width: 60px;
}

.matias-navigation__logoCloseMobile{
    width: 25%;
    left: 0px;
    position: absolute;
    top: 30px;
    right: 0px;
    z-index: 999;
}

.matias-navigation__logoCloseMobile img {
    width: 20px;
    cursor: pointer;
}

.matias-navigation__upperMenu{
    display: flex;
}

.matias-navigation__upperMenu ul li {
    position: relative;
    width: 31.50%;
    max-width: 170px;
    float: left;
    font-family: 'Asap', sans-serif;
    font-weight: 700;
    margin: 15px 10px 10px;
    transition: 0.3s ease-in-out;
    padding: 0 3px;
    outline: none;
}

.matias-navigation__upperMenu ul li img {
    border-radius: 5px;
    max-height: 85px;
    height: 85px;
    width: 100%;
    object-fit: cover;
}

.matias-navigation__upperMenu ul li span {
    position: absolute;
    top: 50%;
    transform: translate(0px , -50%);
    left: 12px;
}

.matias-navigation__upperMenu ul li span a {
    padding: 4px 7px;
    border-radius: 3px;
    background-color: #fff;
    text-transform: uppercase;
    font-size: 12px;
    color: black;
    text-decoration: none;
}


.accordion-content{
    display: none;
    padding: 0 8px;
    flex-direction: column;
    margin: 10px 0 0 0;
}

.accordion-content11{
    display: block;
}

.accordion-row{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100px;
    background-color: #f2f2f2;
    padding-left: 10px;
    min-height: 90px;
    line-height: 90px;
    text-transform: uppercase;
    font-family: 'Asap', sans-serif;
    font-weight: 700;
    color: #000;
    border-radius: 3px;
    margin-bottom: 6px;
}

.accordion-row img {
    max-height: 100px;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
}

.animate__animated.animate__fadeInLeft {
    --animate-duration: 0.75s;
}
  
.matias-navigation__upperMenu ul {
    padding-left: 0 !important;
}
 
.shifter-open{
  overflow:hidden;
  display:block;
}`;

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;
namespace XBMCRPC.List.Filter
{
   public class MusicVideosAnd
   {
       public global::System.Collections.Generic.List<object> and { get; set; }
    }
}

# File upload modal component

The file upload modal is a component that allows users to upload, browse, and modify files. When a save is triggered, the files are then uploaded to the database. The uploaded and/or selected files are returned in an object when the modal is closed.

A common approach to using the File Upload Modal component is within a form, giving users the chance to select files to be attached to a Project, for example. Such an implementation would go as follows:

1. Put a button within the form of the Project edit screen.
2. In your button press handler, specify options for the file-upload-modal, then launch it. See below for more details.
3. When the modal is saved by the user, the files will be uploaded. The file-upload-modal will return the ObjectID of each selected image. You can save these ObjectIDs in your form.

## Setting modal options and launching

The modal technology used with is [NGX Smart modal](https://github.com/maximelafarie/ngx-smart-modal). To set the file-upload-modal data, import the ngxSmartModalService in your component, then call the `setModalData` method:

```
this.ngxSmartModalService.setModalData({
  ...yourOptions
}, 'file-upload-modal', true);
```
After setting the data, use the `open` method to launch the modal:

```
this.ngxSmartModalService.open('file-upload-modal');
```

## Options API

All options are optional except for projectID, which is needed to make sure files are saved to a particular project.

#### __title__ _String_
The title of the modal window. Example: "Select project logo(s)."
### __projectID__ _String_
Should be the project the modal is being launched from. Files will be saved with this project ID.
#### __fileExt__ _String_
A string of accepted file types separated by commas. Example: 'jpg, jpeg, png'
#### __altRequired__ _Boolean_
Whether or not the selected files must each have alt tags specified. Used when specifying image files.
#### __fileNum__ _Number_
Maximum number of files the user can select. If -1 is entered, there is no limit.
#### __returnedFiles__ _Document[]_
An array of document objects returned from the files having been saved. It's not recommended that you set this manually. The File Upload Modal uses this to return files
after they've been saved and the modal has been closed.

## Accessing the returned files

Set up an event listener to check if the File Upload Modal has closed for any reason.
It's recommended you do this in the AfterViewInit lifecycle method.

```
ngAfterViewInit(): void {
  this.ngxSmartModalService.getModal('file-upload-modal').onAnyCloseEventFinished.subscribe((modal: NgxSmartModalComponent) => {
    console.log('The returned data:', modal.getData());
  });
}
```

If the files were successfully saved, you should get an object with a `returnedFiles` containing an array of documents.

#! /usr/bin/env python

from openturns import *

TESTPREAMBLE()

try :

    center = NumericalPoint(4, 0.0)
    center.setName("center")
    center[0] = 0.5
    center[1] = 1.5
    center[2] = 2.5
    center[3] = 3.5
    levels = NumericalPoint(3, 0.0)
    levels.setName("levels")
    levels[0] = 4
    levels[1] = 8
    levels[2] = 16
    myPlane = Factorial(center, levels)
    print "myPlane = " , myPlane
    sample = myPlane.generate()
    print "sample = " , repr(sample)

except :
    import sys
    print "t_Factorial_std.py", sys.exc_type, sys.exc_value

package api

import (
	"net/http"

	"db"
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"gopkg.in/mgo.v2/bson"
	"io/ioutil"
	"time"
	// "strconv"
)

// Input failed validation.
// swagger:response validationError
type ValidationError struct {
	// The error message
	// in: body
	Body struct {
		Code    int32  `json:"code"`
		Message string `json:"message"`
		Field   string `json:"field"`
	} `json:"body"`
}

// Success Answer
// swagger:response successAnswer
type successAnswer struct {
	// The error message
	// in: body
	Body struct {
		Code    int32  `json:"code"`
		Message string `json:"message"`
		Field   string `json:"field"`
	} `json:"body"`
}

// Server id
// swagger:parameters deleteServer getServerById updateServer
type id struct {
	// id Server Generated
	//
	// in: path
	// required: true
	ID int64 `json:"id"`
}

// Server Param
// swagger:parameters createServer updateServer
type myServerBodyParams struct {
	// Server to submit
	//
	// in: body
	// required: true
	Server *db.Server `json:"server"`
}

// Server Multi
// swagger:parameters  importServer
type myMultipleServerBodyParams struct {
	// Server to submit
	//
	// in: body
	// required: true
	Server *[]db.Server `json:"multiserver"`
}

// swagger:route GET /servers servers listServer
//
// Lists servers
//
// This will show all available asset by default.
//
//
//     Responses:
//       default: validationError
//       200: []server
func GetAllItems(w http.ResponseWriter, req *http.Request) {
	rs, err := db.GetAll()
	if err != nil {
		handleError(err, "Failed to load database items: %v", w)
		return
	}
	bs, err := json.MarshalIndent(rs, "", "    ")
	if err != nil {
		handleError(err, "Failed to load marshal data: %v", w)
		return
	}
	w.Write(bs)
}

func handleError(err error, message string, w http.ResponseWriter) {
	w.WriteHeader(http.StatusInternalServerError)
	w.Write([]byte(fmt.Sprintf(message, err)))
}

// swagger:route POST /servers servers createServer
//
// Add a server
//
// This will register asset.
//
//     Responses:
//       default: validationError
//       200: successAnswer
func PostItem(w http.ResponseWriter, req *http.Request) {
	var server db.Server

	decoder := json.NewDecoder(req.Body)

	// debug, err := json.MarshalIndent(decoder, "", "    ")
	// fmt.Println(" debug", debug)
	// fmt.Println(" err", err)

	errjson := decoder.Decode(&server)

	if errjson != nil {
		fmt.Println("Incorrect body")
		fmt.Println(errjson)
		return
	}
	// fmt.Println(server)

	id := bson.NewObjectId()
	ref := id.Hex()
	Name := server.CMDBName
	Function := server.Function
	SerialNumber := server.SerialNumber
	AssetCode := server.AssetCode
	Model := server.HardwareDefinition.Model
	CPU := server.HardwareDefinition.CPU
	RAM := server.HardwareDefinition.RAM
	Room := server.Localisation.Room
	Building := server.Localisation.Building
	Rack := server.Localisation.Rack
	Remarks := server.Remarks
	Status := server.Status
	UpdateTime := time.Now()
	InsertTime := time.Now()

	fmt.Println(UpdateTime)
	fmt.Println(InsertTime)

	// IpAddr := server.Networking[0].IpAddr
	// PatchPanel := server.Networking[0].PatchPanel
	// ServerPort := server.Networking[0].ServerPort
	// Switch := server.Networking[0].Switch
	// Vlan := server.Networking[0].Vlan
	// MAC := server.Networking[0].MAC

	// item := db.Server{ID: id, CMDBName: Name, Networking: []db.Networks{{IpAddr: IpAddr, PatchPanel: PatchPanel, ServerPort: ServerPort, Switch: Switch, Vlan: Vlan, MAC: MAC}}}

	item := db.Server{ID: id, CMDBName: Name, Function: Function, SerialNumber: SerialNumber, AssetCode: AssetCode, HardwareDefinition: db.HardwareDefinition{Model: Model, CPU: CPU, RAM: RAM}, Localisation: db.Localisation{Room: Room, Building: Building, Rack: Rack}, Remarks: Remarks, Status: Status, UpdateTime: UpdateTime, InsertTime: InsertTime}
	if err := db.Save(item); err != nil {
		handleError(err, "Failed to save data: %v", w)
		return
	}

	// Idea is add static field and use loop for update array of networks
	// Networking: []db.Networks{{IpAddr: IpAddr, PatchPanel: PatchPanel, ServerPort: ServerPort, Switch: Switch, Vlan: Vlan, MAC: MAC}},
	var collec string
	collec = "networking"
	fmt.Println(server.Networking)

	for _, net := range server.Networking {
		fmt.Println(net)
		// Launch update with id = id
		if err := db.Update(ref, collec, net); err != nil {
			handleError(err, "Failed to save data: %v", w)
			return
		}
	}
	w.Write([]byte("OK"))
}

// swagger:route DELETE /servers/{id} servers deleteServer
//
// Delete servers
//
// This will delete asset.
//
//     Responses:
//       default: validationError
//       200: successAnswer
func DeleteItem(w http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	id := vars["id"]

	if err := db.Remove(id); err != nil {
		handleError(err, "Failed to remove item: %v", w)
		return
	}
	w.Write([]byte("OK"))
}

// swagger:route GET /servers/{id} servers getServerById
//
// Lists specific server
//
// This will list details for specific server.
//
//     Responses:
//       default: validationError
//       200: server
func GetItem(w http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	id := vars["id"]
	fmt.Println("id", id)

	rs, err := db.GetOne(id)
	// fmt.Println("rs", rs)
	// fmt.Println("err", err)

	if err != nil {
		handleError(err, "Failed to read database: %v", w)
		return
	}

	bs, err := json.Marshal(rs)
	if err != nil {
		handleError(err, "Failed to marshal data: %v", w)
		return
	}
	w.Write(bs)
}

// swagger:route PATCH /servers/{id} servers updateServer
//
// Update specific server
//
// This will update details for specific server.
//
//     Responses:
//       default: validationError
//       200: successAnswer
func UpdateItem(w http.ResponseWriter, req *http.Request) {
	// fmt.Println("Im in update api")
	vars := mux.Vars(req)
	id := vars["id"]
	// fmt.Println("id", id)

	var server db.Server

	decoder := json.NewDecoder(req.Body)

	errjson := decoder.Decode(&server)

	if errjson != nil {
		fmt.Println("Incorrect body")
		fmt.Println(errjson)
		return
	}

	if erro, err := db.Updatemain(id, server); err != nil && erro != nil {
		handleError(err, "Failed to save data: %v", w)
		return
	}
	w.Write([]byte("OK"))
}

// swagger:route POST /servers/import servers importServer
//
// Import / Add multiple Servers
//
// This will insert multiple servers.
//
//     Responses:
//       default: validationError
//       200: successAnswer
func PostMultipleItems(w http.ResponseWriter, req *http.Request) {
	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		panic(err)
	}
	var server []db.Server
	err = json.Unmarshal(body, &server)
	// fmt.Println("Body:", body)
	if err != nil {
		//handle error
	}
	// Loop for multiple of server included in JSON
	for i := range server {
		fmt.Println(server[i].CMDBName)
		fmt.Println(server[i])
		if err := db.Save(server[i]); err != nil {
			handleError(err, "Failed to save data: %v", w)
			return
		}

	}
}
const glob = require('glob');
const { stat, readFile } = require('fs/promises');

const { consoleError } = require('./constants');

function getFilesList(paths = []) {
  if (!Array.isArray(paths)) {
    throw new TypeError(`${consoleError}: Argument "paths" should be an array!`);
  }

  let filesList = [];

  for (const path of paths) {
    const files = glob.sync(path);

    filesList = filesList.concat(files);
  }

  return filesList;
}

async function getFileData(filePath) {
  try {
    if (!filePath || typeof filePath !== 'string') {
      throw new TypeError('filePath must be a string!');
    }

    const fileStat = await stat(filePath);
    const fileData = await readFile(filePath, 'utf8');

    return { fileStat, fileData };
  } catch (error) {
    throw new Error(`${consoleError}: ${error}`);
  }
}

async function startPlugins(filePath, config) {
  try {
    const { fileStat, fileData } = await getFileData(filePath);

    for (const plugin of config.plugins) {
      plugin({ fileData, fileStat }, config);
    }
  } catch (error) {
    throw new Error(`${consoleError}: ${error}`);
  }
}

module.exports = { getFilesList, getFileData, startPlugins };

package io.rsocket.transport.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import io.netty.util.CharsetUtil;

public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

  private final WebSocketClientHandshaker handshaker;
  private ChannelPromise handshakeFuture;

  public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
    this.handshaker = handshaker;
  }

  public ChannelFuture handshakeFuture() {
    return handshakeFuture;
  }

  @Override
  public void handlerAdded(ChannelHandlerContext ctx) {
    handshakeFuture = ctx.newPromise();
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) {
    handshaker.handshake(ctx.channel());
  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) {
    System.out.println("WebSocket Client disconnected!");
  }

  @Override
  public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
      try {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
      } catch (WebSocketHandshakeException e) {
        System.out.println("WebSocket Client failed to connect");
        handshakeFuture.setFailure(e);
      }
      return;
    }

    if (msg instanceof FullHttpResponse) {
      FullHttpResponse response = (FullHttpResponse) msg;
      throw new IllegalStateException(
          "Unexpected FullHttpResponse (getStatus="
              + response.status()
              + ", content="
              + response.content().toString(CharsetUtil.UTF_8)
              + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
      TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
      System.out.println("WebSocket Client received message: " + textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
      System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
      System.out.println("WebSocket Client received closing");
      ch.close();
    }
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    if (!handshakeFuture.isDone()) {
      handshakeFuture.setFailure(cause);
    }
    ctx.close();
  }
}

import 'dotenv/config';
import express from 'express';
import UserController from './app/controllers/UserController';
import BullBoard from 'bull-board';
import Queue from './app/lib/Queue';

const app = express();
BullBoard.setQueues(Queue.queues.map(queue => queue.bull));

app.use(express.json());
app.post('/users', UserController.store);

app.use('/admin/queues', BullBoard.UI);

app.listen(3333, () => {
  console.log('Server running on localhost:3333');
});
module.exports = function getZerosCount(number, base) {
//next function is the sieve of Eratosfen
  function sieve(upper_bound){
    let grains = [0, 0];
    for (let i = 2; i <= upper_bound; i++)
      grains.push(i);
    for (let i = 2; i < Math.sqrt(upper_bound); i++)
      for (let j = i*i; j <= upper_bound; j+=i)
        if (grains[j] != 0) grains[j] = 0;
    return grains.filter(function(x) {return x != 0});
  }

//next function find prime factorization of base (array of couples: prime and its degree)
  function factorization(base_number_system, prime_numbers) {
  let prime_dividers = [];
  for (let i = 0; prime_numbers[i] <= base; i++) {
    let p = prime_numbers[i], count = 0;
    while ((base_number_system >= prime_numbers[i]) && (base_number_system % prime_numbers[i] == 0)) {
      base_number_system = base_number_system / prime_numbers[i];
      p = prime_numbers[i];  
      count++;
    }
    if (count)
      prime_dividers.push([p, count]);
    }
  return prime_dividers;
  }

// Next function find how many zeros in the end of number, which is factorial of `number` in `prime_base` base system
  function getZerosForPrimeBase(number, prime_base) {
    let zeros = 0;
    for (let i = 1; Math.pow(prime_base, i) <= number; i++)
      zeros += Math.floor(number / Math.pow(prime_base, i));
    return zeros;
  }

//let's do it
//first, we seek prime numbers
prime_numbers_before_base = sieve(base);

//second, we add number of zeros to our array of couples and get array of trios: [prime, its degree, zeros]
  candidates = factorization(base, prime_numbers_before_base);
  for (let i = 0; i < candidates.length; i++) 
    candidates[i].push(getZerosForPrimeBase(number, candidates[i][0]));

//and finally, we will chose THE ONE (just believe me, Neo)
  neo = candidates.reduce(function(x, y) {return ((x[2] / x[1]) < (y[2] / y[1]))?x:y;});
  return Math.floor(neo[2] / neo[1]);
} 
/*******************************************************************************
 * Copyright (C) 2021 Mohd Hariz Afiq Bin Abdul Rahman
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ******************************************************************************/
package com.harix.VoucherSystem.SpecialOffer;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping(value = "/api/specialoffer")
public class SpecialOfferController {

	@Autowired
	private SpecialOfferService spOfferService;
	
	@PostMapping(value = "/create")
	public Optional<SpecialOffer> createNewSpecialOffer(@Validated @RequestBody SpecialOffer spOffer) {
		return spOfferService.createNewSpecialOffer(spOffer);
	}
	
	@GetMapping(value = "/list")
	public List<SpecialOffer> retrieveAllSpecialOffer(){
		return spOfferService.listSpecialOffer();
	}
	
	@DeleteMapping(value = "/delete/{id}")
	public void deleteSpecialOffer(@PathVariable(value = "id") int spOfferId) {
		spOfferService.deleteSpecialOffer(spOfferId);
	}
}

package cn.xishan.oftenporter.demo.oftendb.base;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import cn.xishan.oftenporter.oftendb.data.impl.MysqlSource;
import cn.xishan.oftenporter.oftendb.db.DBException;
import cn.xishan.oftenporter.oftendb.db.DBHandle;
import cn.xishan.oftenporter.oftendb.db.mysql.SqlHandle;
import cn.xishan.oftenporter.porter.core.util.WPTool;

public class SqlDBSource extends MysqlSource
{

    public SqlDBSource()
    {
        super((wObject, configed, configing) -> configing.setCollectionName("test1"));
        Connection connection = null;
        Statement statement = null;
        try
        {
            String initSql =
                    "CREATE TABLE IF NOT EXISTS `test1` (\n" + "  `_id` char(32) NOT NULL,\n"
                            + "  `name` varchar(35) NOT NULL,\n"
                            + "  `age` int(11) NOT NULL,\n"
                            + "  `sex` varchar(2) NOT NULL,\n"
                            + "  `time` datetime NOT NULL,\n"
                            + "  PRIMARY KEY (`_id`)\n"
                            + ") ENGINE=InnoDB DEFAULT CHARSET=utf8";
            connection = getConn();
             statement = connection.createStatement();
            statement.execute(initSql);
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            WPTool.close(statement);
            WPTool.close(connection);
        }
    }

    @Override
    public Connection getConnection()
    {
        return getConn();
    }

    private Connection getConn()
    {

        try
        {
            Class.forName("org.h2.Driver");
            Connection conn = DriverManager.getConnection(
                    "jdbc:h2:~/PorterDemo/oftendb;MODE=MySQL", "sa", "");
            return conn;
        } catch (Exception e)
        {
            throw new DBException(e);
        }

    }

    @Override
    public DBHandle getDBHandle()
            throws DBException
    {
        SqlHandle sqlHandle = new SqlHandle(getConn());
        return sqlHandle;
    }

}

package com.githup.hicoincom.exception;

/**
 * @author ZPZ
 */
public class ArgsNullException extends RuntimeException{
    public ArgsNullException(){ super();}
    public ArgsNullException(String msg){super(msg);}
}

/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE126_Buffer_Overread__new_char_loop_83_goodG2B.cpp
Label Definition File: CWE126_Buffer_Overread__new.label.xml
Template File: sources-sink-83_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 126 Buffer Over-read
 * BadSource:  Use a small buffer
 * GoodSource: Use a large buffer
 * Sinks: loop
 *    BadSink : Copy data to string using a loop
 * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE126_Buffer_Overread__new_char_loop_83.h"

namespace CWE126_Buffer_Overread__new_char_loop_83
{
CWE126_Buffer_Overread__new_char_loop_83_goodG2B::CWE126_Buffer_Overread__new_char_loop_83_goodG2B(char * dataCopy)
{
    data = dataCopy;
    /* FIX: Use a large buffer */
    data = new char[100];
    memset(data, 'A', 100-1); /* fill with 'A's */
    data[100-1] = '\0'; /* null terminate */
}

CWE126_Buffer_Overread__new_char_loop_83_goodG2B::~CWE126_Buffer_Overread__new_char_loop_83_goodG2B()
{
    {
        size_t i, destLen;
        char dest[100];
        memset(dest, 'C', 100-1);
        dest[100-1] = '\0'; /* null terminate */
        destLen = strlen(dest);
        /* POTENTIAL FLAW: using length of the dest where data
         * could be smaller than dest causing buffer overread */
        for (i = 0; i < destLen; i++)
        {
            dest[i] = data[i];
        }
        dest[100-1] = '\0';
        printLine(dest);
        delete [] data;
    }
}
}
#endif /* OMITGOOD */

package com.fich.wafproject.dao;
 
import com.fich.wafproject.model.Event;
import java.util.List;
 
public interface EventDao {
 
    void saveEvent(Event event);
    
    Event findByTransactionId(String transactionId);
    
    List<Event> findAllEvent(int pageNumber, String[] targets, String[] names, String[] values, boolean pagination);
    
    List<Event> findAllEvent();
    
    Event findById(Integer id);
    
    List<Event> findEventsByProperties(String[] properties, String[] values);
    
    public void delete(Integer id);
    
    public void deletAll();
     
}
#include "../../non_core/joypad.h"

#if defined(_WIN32) || defined(_MSC_VER) || defined(__ANDROID__)
#include "SDL.h"
#else 
#include <SDL2/SDL.h>
#endif

#if defined(__ANDROID__) 
#include <jni.h>
#endif

#ifdef PSVITA
#include <psp2/ctrl.h>
#endif

#include "stdlib.h"
#include "../../core/mmu/mbc.h"
#include "../../non_core/logger.h"

SDL_Joystick *joystick;

typedef struct {
    int x;
    int y;
    int w;
    int h;
} b_rect;

typedef struct {
    int key_code; // Key code on the keyboard which
                       // maps to the given gameboy button
    int state; // 1 pressed, 0 unpressed
    b_rect rect;
} button_state;


enum {UP = 0, DOWN, LEFT, RIGHT, A, B, START, SELECT};

#if defined(__SWITCH__)
#define JOY_A     0
#define JOY_B     1
#define JOY_X     2
#define JOY_Y     3
#define JOY_PLUS  10
#define JOY_MINUS 11
#define JOY_LEFT  12
#define JOY_UP    13
#define JOY_RIGHT 14
#define JOY_DOWN  15

int button_config[] = {JOY_UP, JOY_DOWN, JOY_LEFT, JOY_RIGHT, JOY_A, JOY_B, JOY_PLUS, JOY_MINUS};

#elif defined(PSVITA)

#define SDLK_VITA_TRIANGLE 0
#define SDLK_VITA_CIRCLE 1 
#define SDLK_VITA_CROSS 2
#define SDLK_VITA_SQUARE 3

#define SDLK_VITA_LTRIGGER 4
#define SDLK_VITA_RTRIGGER 5

#define SDLK_VITA_DOWN 6
#define SDLK_VITA_LEFT 7
#define SDLK_VITA_UP 8
#define SDLK_VITA_RIGHT 9

#define SDLK_VITA_SELECT 10
#define SDLK_VITA_START 11

int button_config[] = {SDLK_VITA_UP, SDLK_VITA_DOWN, SDLK_VITA_LEFT, SDLK_VITA_RIGHT
    , SDLK_VITA_CROSS, SDLK_VITA_CIRCLE, SDLK_VITA_START, SDLK_VITA_SELECT};

#else

int button_config[] = {SDLK_UP, SDLK_DOWN, SDLK_LEFT, SDLK_RIGHT, SDLK_a, SDLK_s, SDLK_RETURN, SDLK_SPACE};

#endif

button_state buttons[8];

#define TOTAL_BUTTONS (sizeof(buttons)/sizeof(buttons[0]))

static SDL_DisplayMode current;
static SDL_Haptic *haptic;
static int rumble_on = 0; // If rumble is activated

#if defined(__ANDROID__) 
static void vibrate() {

    // Retrieve the JNI environment
    JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();

    // retrieve the Java instance of the SDL Activity
    jobject activity = (jobject)SDL_AndroidGetActivity();

    // find the Java class of the activity. It should be SDLActivity or a subclass of it.
    jclass c = (*env)->GetObjectClass(env, activity);
    if (c == 0) {
        log_message(LOG_ERROR, "JNI: Unable to find the \"PlutoboyActivity\" class\n");
        return ; 
    }

    // Get the Vibrate method id
    jmethodID mid = (*env)->GetMethodID(env, c, "vibrate", "()V");
    if (mid == 0) {
        log_message(LOG_ERROR, "JNI: Unable to find the \"vibrate\" method id\n");
        return ; 
    }
    
    (*env)->CallVoidMethod(env, activity, mid); 

    // clean up the local references.
    (*env)->DeleteLocalRef(env, activity);
    (*env)->DeleteLocalRef(env, c);
}
#endif


static int isValidEvent(void * userdata, SDL_Event* event)
{
    return event->type == SDL_QUIT ||
           event->type == SDL_KEYDOWN || 
           event->type == SDL_KEYUP || 
           event->type == SDL_JOYBUTTONDOWN || 
           event->type == SDL_JOYBUTTONUP || 
           event->type == SDL_FINGERUP || 
           event->type == SDL_FINGERDOWN || 
           event->type == SDL_FINGERMOTION; 
}

/*  Intialize the joypad, should be called before any other
 *  joypad functions */
void init_joypad() { 

    #if defined(__ANDROID__)   
    rumble_on = 1;
    #else
    rumble_on = 0;
    #endif

    joystick = 0;
    if (SDL_NumJoysticks() > 0) {
        joystick = SDL_JoystickOpen(0);
    }

#ifndef PSVITA 
    // Attempt to setup Haptic Feedback
    haptic = SDL_HapticOpen(0);
    if (haptic == NULL) {
        log_message(LOG_WARN, "Unable to open haptic device %s\n", SDL_GetError());
    } else {
        if (haptic != NULL && SDL_HapticRumbleInit(haptic) != 0) {
            rumble_on = 1;
        } else {
            log_message(LOG_WARN, "Unable to initialize rumble %s\n", SDL_GetError());
        }
    } 
#endif
    // Setup buttons 
    SDL_GetCurrentDisplayMode(0, &current);    
     
    buttons[UP].state = 0;
    buttons[UP].key_code = button_config[UP];
    b_rect rect_u = {DPAD_UP_X, DPAD_UP_Y(current.h), DPAD_UP_W, DPAD_UP_H};
    buttons[UP].rect = rect_u;

    buttons[DOWN].state = 0;
    buttons[DOWN].key_code = button_config[DOWN];
    b_rect rect_d = {DPAD_DOWN_X, DPAD_DOWN_Y(current.h), DPAD_DOWN_W, DPAD_DOWN_H};
    buttons[DOWN].rect = rect_d; 

    buttons[LEFT].state = 0;
    buttons[LEFT].key_code = button_config[LEFT];
    b_rect rect_l = {DPAD_LEFT_X, DPAD_LEFT_Y(current.h), DPAD_LEFT_W, DPAD_LEFT_H};
    buttons[LEFT].rect = rect_l; 

    buttons[RIGHT].state = 0;
    buttons[RIGHT].key_code = button_config[RIGHT];
    b_rect rect_r = {DPAD_RIGHT_X, DPAD_RIGHT_Y(current.h), DPAD_RIGHT_W, DPAD_RIGHT_H};
    buttons[RIGHT].rect = rect_r; 

    buttons[A].state = 0;
    buttons[A].key_code = button_config[A];
    b_rect rect_a = {A_X(current.w), A_Y(current.h), A_W, A_H};
    buttons[A].rect = rect_a; 

    buttons[B].state = 0;
    buttons[B].key_code = button_config[B];
    b_rect rect_b = {B_X(current.w), B_Y(current.h), B_W, B_H};
    buttons[B].rect = rect_b; 

    buttons[START].state = 0;
    buttons[START].key_code = button_config[START];
    b_rect rect_st = {START_X, START_Y(current.h), START_W, START_H};
    buttons[START].rect = rect_st; 
   
    buttons[SELECT].state = 0;
    buttons[SELECT].key_code = button_config[SELECT];
    b_rect rect_se = {SELECT_X, SELECT_Y(current.h), SELECT_W, SELECT_H};
    buttons[SELECT].rect = rect_se; 

    SDL_SetEventFilter(isValidEvent, NULL);
}

/* Check each individual GameBoy key. Returns 1 if
 * the specified key is being held down, 0 otherwise */
int down_pressed()   { return buttons[DOWN].state;  }  
int up_pressed()     { return buttons[UP].state; }
int left_pressed()   { return buttons[LEFT].state;}
int right_pressed()  { return buttons[RIGHT].state;} 
int a_pressed()      { return buttons[A].state; }
int b_pressed()      { return buttons[B].state;}
int start_pressed()  { return buttons[START].state; }
int select_pressed() { return buttons[SELECT].state; } 

/* Returns 1 if any of the 8 GameBoy keys are being held down,
 * 0 otherwise */
int key_pressed() {

    return down_pressed() || up_pressed() || left_pressed() || right_pressed()
    || a_pressed() || b_pressed() || start_pressed() || select_pressed();
}


// Given relative screen x and y positions and an on/off state
// sets any buttons those co-ordinates are in to the given state.
void check_keys_pressed(float x, float y, int state) {
    float p_x = x * current.w;
    float p_y = y * current.h;
   
     for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
        if (p_x >= buttons[i].rect.x && 
                p_x <= buttons[i].rect.x + buttons[i].rect.w &&
                p_y >= buttons[i].rect.y &&
                p_y <= buttons[i].rect.y + buttons[i].rect.h) {
            
            // If activating button, send rumble feedback
            if (rumble_on && !buttons[i].state && state) {
               // SDL_HapticRumblePlay(haptic, 0.5, 100);
               #if defined(__ANDROID__)
                  vibrate();
               #endif
            }
            buttons[i].state = state;
            
         }
    }
}

// Given new x/y relative screen positions and x/y movement 
// determines which keys are now pressed
void check_keys_moved(float x, float y, float mv_x, float mv_y) {
    // Pixel positions after movement
    float p_x = x * current.w;
    float p_y = y * current.h;

    // Pixel positions before movement
    float old_p_x = (x - mv_x) * current.w;
    float old_p_y = (y - mv_y) * current.h;
   
    int activated = 0;

     for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
        int was_on = (old_p_x >= buttons[i].rect.x) &&
                     (old_p_x <= buttons[i].rect.x + buttons[i].rect.w) &&
                     (old_p_y >= buttons[i].rect.y) &&
                     (old_p_y <= buttons[i].rect.y + buttons[i].rect.h);

        int is_on = (p_x >= buttons[i].rect.x) && 
                    (p_x <= buttons[i].rect.x + buttons[i].rect.w) &&
                    (p_y >= buttons[i].rect.y) &&
                    (p_y <= buttons[i].rect.y + buttons[i].rect.h);
            
        if (!was_on && is_on) {
            activated = 1;
            buttons[i].state = 1;           
        }

        if (was_on && !is_on) {
            buttons[i].state = 0;
        }    
    } 

         
    // If activating button, send rumble feedback
    if (rumble_on && activated) {
        // SDL_HapticRumblePlay(haptic, 0.5, 100);
        #if defined(__ANDROID__)
        vibrate();
        #endif
    }
}


void unset_keys() {
    for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
        buttons[i].state = 0;
    }
}


/* Update current state of GameBoy keys as well as control
 * other external actions for the emulator */
int update_keys() {
        SDL_Event event;

        if (SDL_PollEvent(&event)) {

            switch (event.type) {
                    // exit if the window is closed
                case SDL_QUIT:
                            write_SRAM();
                            return 1;
                            break;

#if !defined(PSVITA) && !defined(__SWITCH__)
                case SDL_KEYDOWN: // Key pressed
                    if (event.key.keysym.sym == SDLK_ESCAPE) {
                        write_SRAM();
                        return 1;
                    }

                    for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
                            if (buttons[i].key_code == event.key.keysym.sym) {
                                buttons[i].state = 1;
                                break;
                            }
                        }
                        break;

                case SDL_KEYUP: //Key released
                    for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
                            if (buttons[i].key_code == event.key.keysym.sym) {
                                buttons[i].state = 0;
                                break;
                            }
                        }
                    break;

#else
                case SDL_JOYBUTTONDOWN:
                case SDL_JOYBUTTONUP:
                    for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
                        if (buttons[i].key_code == event.jbutton.button) {
                            buttons[i].state = (event.jbutton.state == SDL_PRESSED);
                            break;
                        }
                    }
                break;

#endif
#ifndef PSVITA          
                case SDL_FINGERDOWN:
                    check_keys_pressed(event.tfinger.x, event.tfinger.y, 1);
                    break;

                case SDL_FINGERUP:
                    check_keys_pressed(event.tfinger.x, event.tfinger.y, 0);
                    break;

                // Assume only one finger can be on a button at a time considering
                // the size of the buttons. It would be more accurate in the future
                // to keep track of finger ids for each button 
                case SDL_FINGERMOTION:
                    check_keys_moved(event.tfinger.x, event.tfinger.y,
                                     event.tfinger.dx, event.tfinger.dy);
                    break;
                default: 
                    printf("%d\n",  event.type);
                    
#endif
            }                   
        }
    return 0;
}

<?php

/**
 * Module: SmartFAQ
 * Author: The SmartFactory <www.smartfactory.ca>
 * Licence: GNU
 */

use XoopsModules\Smartfaq;

global $xoopsTpl, $xoopsModule;

$uid     = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
$isAdmin = (Smartfaq\Utility::userIsAdmin() || Smartfaq\Utility::hasModerator());

/** @var Smartfaq\Helper $helper */
$helper = Smartfaq\Helper::getInstance();

$xoopsTpl->assign('sf_adminpage', "<a href='" . XOOPS_URL . "/modules/smartfaq/admin/index.php'>" . _MD_SF_ADMIN_PAGE . '</a>');
$xoopsTpl->assign('isAdmin', $isAdmin);

$xoopsTpl->assign(
    [
        'lang_on'       => _MD_SF_ON,
        'lang_postedby' => _MD_SF_POSTEDBY,
        'lang_faq'      => _MD_SF_QUESTION,
        'lang_datesub'  => _MD_SF_DATESUB,
        'lang_hits'     => _MD_SF_HITS,
    ]
);
$xoopsTpl->assign('sectionname', $myts->displayTarea($xoopsModule->getVar('name')));

$xoopsTpl->assign('modulename', $xoopsModule->dirname());
$xoopsTpl->assign('displaylastfaq', $helper->getConfig('displaylastfaq'));
$xoopsTpl->assign('displaysubcatdsc', $helper->getConfig('displaysubcatdsc'));
$xoopsTpl->assign('displaycollaps', $helper->getConfig('displaycollaps'));
$xoopsTpl->assign('display_date_col', $helper->getConfig('display_date_col'));
$xoopsTpl->assign('display_hits_col', $helper->getConfig('display_hits_col'));

$xoopsTpl->assign('displaytopcatdsc', $helper->getConfig('displaytopcatdsc'));

$xoopsTpl->assign('ref_smartfaq', 'SmartFAQ is developed by The SmartFactory (http://www.smartfactory.ca), a division of InBox Solutions (http://www.inboxsolutions.net)');

$xoopsTpl->assign('xoops_module_header', "<link rel='stylesheet' type='text/css' href='" . XOOPS_URL . "/modules/smartfaq/assets/css/smartfaq.css'>");

package com.codepath.apps.restclienttemplate.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.codepath.apps.restclienttemplate.TwitterApp;
import com.codepath.apps.restclienttemplate.TwitterClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Arielle on 03-Mar-18.
 */

public class UserTimelineFragment extends TweetsListFragment {
    TwitterClient client;
    public static UserTimelineFragment newInstance(String  screenName){
       UserTimelineFragment userTimelineFragment = new UserTimelineFragment();
       Bundle args= new Bundle();
       args.putString("screen_name", screenName);
       userTimelineFragment.setArguments(args);
       return userTimelineFragment;


    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        client = TwitterApp.getRestClient();
        populateTimeLine();
    }

    private void populateTimeLine() {
        //comes from the activity
        String screenName = getArguments().getString("screen_name");

        client.getUserTimeline(screenName, new JsonHttpResponseHandler() {
                                   @Override
                                   public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                       Log.d("TwitterClient", response.toString());

                                   }

                                   @Override
                                   public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                                       addItems(response);
                                       //    Log.d("TwitterClient",response.toString());

                                       //iterate trought the JSON array
                                       //for each entry, deserialyze the JSON object
                                       for (int i = 0; i < response.length(); i++) {
                                           //convert each object to a Tweet model
                                           //add that tweet model to our data source
                                           //notify the adapter that we've added an item


                                       }
                                   }

                                   @Override
                                   public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                       Log.d("TwitterClient", responseString);
                                       throwable.printStackTrace();
                                   }

                                   @Override
                                   public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                                       Log.d("TwitterClient", errorResponse.toString());
                                       throwable.printStackTrace();
                                   }

                                   @Override
                                   public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                                       Log.d("TwitterClient", errorResponse.toString());
                                       throwable.printStackTrace();
                                   }


                                           //         Log.d("TwitterClient",response.toString());
            //iterate trought the JSON array
            //for each entry, deserialize the JSON object


        });
}}

package org.apache.kyuubi.engine.spark

import org.apache.curator.framework.CuratorFramework

import org.apache.kyuubi.Utils
import org.apache.kyuubi.config.KyuubiConf
import org.apache.kyuubi.ha.HighAvailabilityConf.{HA_ZK_AUTH_TYPE, HA_ZK_NAMESPACE, HA_ZK_QUORUM}
import org.apache.kyuubi.ha.client.{ZooKeeperAuthTypes, ZooKeeperClientProvider}
import org.apache.kyuubi.zookeeper.{EmbeddedZookeeper, ZookeeperConf}

trait WithDiscoverySparkSQLEngine extends WithSparkSQLEngine {
  private var zkServer: EmbeddedZookeeper = _
  def namespace: String
  override def withKyuubiConf: Map[String, String] = {
    assert(zkServer != null)
    Map(
      HA_ZK_QUORUM.key -> zkServer.getConnectString,
      HA_ZK_AUTH_TYPE.key -> ZooKeeperAuthTypes.NONE.toString,
      HA_ZK_NAMESPACE.key -> namespace)
  }

  override def beforeAll(): Unit = {
    zkServer = new EmbeddedZookeeper()
    val zkData = Utils.createTempDir()
    val tmpConf = KyuubiConf()
    tmpConf.set(ZookeeperConf.ZK_CLIENT_PORT, 0)
    tmpConf.set(ZookeeperConf.ZK_DATA_DIR, zkData.toString)
    zkServer.initialize(tmpConf)
    zkServer.start()
  }

  override def afterAll(): Unit = {
    if (zkServer != null) {
      zkServer.stop()
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    startSparkEngine()
  }

  override protected def afterEach(): Unit = {
    super.afterEach()
    stopSparkEngine()
  }

  def withZkClient(f: CuratorFramework => Unit): Unit = {
    ZooKeeperClientProvider.withZkClient(kyuubiConf)(f)
  }

  protected def getDiscoveryConnectionString: String = {
    if (zkServer == null) {
      ""
    } else {
      zkServer.getConnectString
    }
  }
}
---
title: "Recitation 3 Note"
author: "Yiming Gong"
date: "2021-07-22T02:56:26Z"
link: "https://bookdown.org/yg484/rec_3_note/"
length_weight: "7.8%"
pinned: false
---

This is class note for recitation 3 on July 22th. [...] restrict the time scale to two instants only: The price of one share at time \(t\) will be denoted by \(S(t)\). The
current stock price \(S(0)\) is known to all investors \(A(t)\) and \(A(0)\) \[
S(t)-S(0)
\] The return is defined as: \[
K_S = \frac{S(t)-S(0)}{S(0)}, t= 1
\] Is the return \(K_S\) a fixed value or a random value? Similar for return of bond: \[
K_A = \frac{A(t)-A(0)}{A(0)}, t = 1
\] Is the return \(K_A\) a fixed value or a random value? The future stock price \(S(1)\) is a random variable with at least two
different ...

'use strict';

var memo = require('./');

/**
 * When a string is passed, a function is returned
 */

var cwd = memo(process.cwd());

// use `cwd`
var foo = cwd('foo');
var bar = cwd('bar');
var baz = cwd('baz');

// use `foo`
var qux = foo('a/b/c');
// use `qux`
var fez = qux('x/y/z');

/**
 * Get a memoized path by calling the function
 */

console.log(cwd());
//=> /User/dev/memo-path
console.log(foo());
//=> /User/dev/memo-path/foo
console.log(bar());
//=> /User/dev/memo-path/bar
console.log(baz());
//=> /User/dev/memo-path/baz
console.log(qux());
//=> /User/dev/memo-path/foo/a/b/c
console.log(fez());
//=> /User/dev/memo-path/foo/a/b/c/x/y/z


/**
 * The memoized path is also exposed on the function's `.path` property
 */

console.log(cwd.path);
//=> /User/dev/memo-path
console.log(foo.path);
//=> /User/dev/memo-path/foo
console.log(bar.path);
//=> /User/dev/memo-path/bar
console.log(baz.path);
//=> /User/dev/memo-path/baz
console.log(qux.path);
//=> /User/dev/memo-path/foo/a/b/c
console.log(fez.path);
//=> /User/dev/memo-path/foo/a/b/c/x/y/z

<?php 
namespace App\Http\Controllers;

use App\Language;
    use App\Film;

     
class LanguageController extends Controller {

    /**
    * Display a listing of the resource.
    *
    * @return  Response
    */
    public function index()
    {
        request()->session()->forget("keyword");
        request()->session()->forget("clear");
        request()->session()->forget("defaultSelect");
        session(["mutate" => '1']);


        return view('language_show', ['languages' => Language::paginate(20)]);
    }

    /**
    * Show the form for creating a new resource.
    *
    * @return  Response
    */
    public function create()
    {
        return view('language');
    }

    /**
    * Store a newly created resource in storage.
    *
    * @return  Response
    */
    public function store()
    {
            $data = request()->all();

    $language = Language::create([
             "name" => $data["name"],
          ]);

      
        return redirect('/language');;
    }

    /**
    * Display the specified resource.
    *
    * @param    Mixed
    * @return  Response
    */
    public function show(Language $language )
    {
        request()->session()->forget("mutate");
        $language->load(array("film",));
        return view('language_display', compact('language'));        }

    /**
    * Show the form for editing the specified resource.
    *
    * @param    Mixed
    * @return  Response
    */
    public function edit(Language $language )
    {
        request()->session()->forget("mutate");
        $language->load(array("film",));
        return view('language_edit', compact('language'));
    }

    /**
    * Update the specified resource in storage.
    *
    * @param    Mixed
    * @return  Response
    */
    public function update(Language $language )
    {
            $language->update(request()->all());

        return back();
    }

    /**
    * Remove the specified resource from storage.
    *
    * @param    Mixed
    * @return  Response
    */
    public function destroy(Language $language )
    {
            $language->delete();
        return back();
    }

    /**
    * Load and display related tables.
    * @param    Mixed
    * @return  Response
    */
    public function related(Language $language ){

        session(["mutate" => '1']);
        if(request()->exists('cs')){
            request()->session()->forget("keyword");
            return back();
        }

        if(request()->exists('tab') && session("clear", "none") != request()->get('tab')){
            request()->session()->forget("keyword");
            session(["clear" => request()->get('tab')]);
        }

        $table = request()->get('tab');
        $language->load(array("film",));
return view('language_related', compact(['language', 'table']));
    }

    /**
    * Search Table element By keyword
    * @return  Response
    */
    public function search(){
        $keyword = request()->get('keyword');

        if(request()->exists('tab')){
            session(['keyword' => $keyword]);
            return back();
        }

        session(["keyword" => $keyword]);

        $keyword = '%'.$keyword.'%';

        $languages = Language::where('language_id', 'like', $keyword)
         ->orWhere('language_id', 'like', $keyword)

         ->orWhere('name', 'like', $keyword)

         ->orWhere('last_update', 'like', $keyword)

        ->paginate(20);
    $languages->setPath("search?keyword=$keyword");
    return view('language_show', compact('languages'));
    }

    /**
    * Sort Table element
    * @return  Response
    */
    public function sort(){
        $path = "";

            request()->session()->forget("sortKey");
    request()->session()->forget("sortOrder");
    if(!request()->exists('tab')){
$languages = Language::query();
         if(request()->exists('name')){
            $languages = $languages->orderBy('name', $this->getOrder('name'));
            $path = "name";
        }else{
            request()->session()->forget("name");
        }
          $languages = $languages->paginate(20);
        $languages->setPath("sort?$path");
        return view('language_show', compact('languages'));

    }else{

    if(request()->exists('tab') == 'film'){

                  if(request()->exists('title')){
             session(['sortOrder' => $this->getOrder('title')]);
             session(['sortKey' => 'title']);
        }else{
            request()->session()->forget("title");
        }

                 if(request()->exists('description')){
             session(['sortOrder' => $this->getOrder('description')]);
             session(['sortKey' => 'description']);
        }else{
            request()->session()->forget("description");
        }

                 if(request()->exists('release_year')){
             session(['sortOrder' => $this->getOrder('release_year')]);
             session(['sortKey' => 'release_year']);
        }else{
            request()->session()->forget("release_year");
        }

                  if(request()->exists('rental_duration')){
             session(['sortOrder' => $this->getOrder('rental_duration')]);
             session(['sortKey' => 'rental_duration']);
        }else{
            request()->session()->forget("rental_duration");
        }

                 if(request()->exists('rental_rate')){
             session(['sortOrder' => $this->getOrder('rental_rate')]);
             session(['sortKey' => 'rental_rate']);
        }else{
            request()->session()->forget("rental_rate");
        }

                 if(request()->exists('length')){
             session(['sortOrder' => $this->getOrder('length')]);
             session(['sortKey' => 'length']);
        }else{
            request()->session()->forget("length");
        }

                 if(request()->exists('replacement_cost')){
             session(['sortOrder' => $this->getOrder('replacement_cost')]);
             session(['sortKey' => 'replacement_cost']);
        }else{
            request()->session()->forget("replacement_cost");
        }

                    }
             return back();
    }
    }

    /**
    * Clear Search Pattern
    *
    */
    public function clearSearch(){
        request()->session()->forget("keyword");
        return back();
    }



    function addFilm(Language $language ){
    $language->film()->sync(request()->get('film'));
    return back();
}
 
    private function getOrder($param){
        if(session($param, "none") != "none"){
            session([$param => session($param, 'asc') == 'asc' ? 'desc':'asc']);
        }else{
            session([$param => 'asc']);
        }
        return session($param);
    }



}


package ru.rsmu.olympreg.utils.restconnector.examsapimodel;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;

/**
 * @author leonid.
 */
@XmlRootElement( name = "exam" )
public class ExamFacade {
    private long id;
    private String subject;
    private String eventType;
    private String name;
    private Date date;


    public long getId() {
        return id;
    }

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

    public String getSubject() {
        return subject;
    }

    public void setSubject( String subject ) {
        this.subject = subject;
    }

    public String getEventType() {
        return eventType;
    }

    public void setEventType( String eventType ) {
        this.eventType = eventType;
    }

    public String getName() {
        return name;
    }

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

    public Date getDate() {
        return date;
    }

    public void setDate( Date date ) {
        this.date = date;
    }
}

require "application_system_test_case"

class InstitutionsTest < ApplicationSystemTestCase
  setup do
    @institution = institutions(:one)
  end

  test "visiting the index" do
    visit institutions_url
    assert_selector "h1", text: "Institutions"
  end

  test "creating a Institution" do
    visit institutions_url
    click_on "New Institution"

    fill_in "Description", with: @institution.description
    fill_in "Name", with: @institution.name
    click_on "Create Institution"

    assert_text "Institution was successfully created"
    click_on "Back"
  end

  test "updating a Institution" do
    visit institutions_url
    click_on "Edit", match: :first

    fill_in "Description", with: @institution.description
    fill_in "Name", with: @institution.name
    click_on "Update Institution"

    assert_text "Institution was successfully updated"
    click_on "Back"
  end

  test "destroying a Institution" do
    visit institutions_url
    page.accept_confirm do
      click_on "Destroy", match: :first
    end

    assert_text "Institution was successfully destroyed"
  end
end

import axiosWithAuth from "../../utils/axiosWithAuth.js";

export const LOADING_START = "LOADING_START";
export const LOADING_DONE = "LOADING_DONE";
export const LOGIN_FAILED = "LOGIN_FAILED";
export const LOGOUT = "LOGOUT";
export const SET_CURRENT_USER = "SET_CURRENT_USER";
export const SET_OTHER_USER = "SET_OTHER_USER";
export const WIPE_OTHER_USER = "WIPE_OTHER_USER";
export const SAVED_JOBS = "SAVED_JOBS";
export const DELETE_JOBS = "DELETE_JOBS";
export const DELETE_APPLIED = "DELETE_APPLIED";
export const GET_SAVED_APPLIED_JOBS = "GET_SAVED_APPLIED_JOBS";
export const APPLIED_JOBS = "APPLIED_JOBS";

// export const loadingStart = () =>{
//     return { type: LOADING_START, payload: null };
// }
export const loadingDone = () => {
  return { type: LOADING_DONE, payload: null };
};
export const login = (user) => {
  return { type: SET_CURRENT_USER, payload: user };
};
export const logout = () => {
  return { type: LOGOUT, payload: null };
};
export const getCurrentUser = () => (dispatch) => {
  axiosWithAuth()
    .get("/users/user")
    .then((res) => {
      dispatch({ type: SET_CURRENT_USER, payload: res.data });
    })
    .catch((err) => {
      dispatch({ type: LOGIN_FAILED, payload: err });
      console.log("GetCurrentUser CATCH ERROR: ", err.response.data.message);
    });
  return null;
};

export const updateUser = (userObj, setLoading) => (dispatch) => {
  axiosWithAuth()
    .put(`/users/user`, userObj)
    .then((res) => {
      console.log("update user", res);
      dispatch({ type: SET_CURRENT_USER, payload: res.data });
      dispatch({ type: SET_OTHER_USER, payload: res.data });
    })
    .catch((err) => {
      setLoading(false);
      console.log("updateUser CATCH ERROR: ", err.response.data.message);
      alert(err.response.data.message);
    });
  return null;
};

export const updateProfilePicture = (formData, setPictureLoading) => (
  dispatch
) => {
  // console.log('updateProfilePicture firing', formData);
  axiosWithAuth()
    .put("/users/user/picture", formData)
    .then((res) => {
      console.log("updateProfilePicture res: ", res);
      dispatch({ type: SET_CURRENT_USER, payload: res.data });
      setPictureLoading(false);
    })
    .catch((err) => {
      console.log(
        "updateProfilePicture CATCH ERROR: ",
        err.response.data.message
      );
      alert(err.response.data.message);
      setPictureLoading(false);
    });
  return null;
};
export const deleteProfilePicture = (setPictureLoading) => (dispatch) => {
  console.log("deleteProfilePicture firing");
  axiosWithAuth()
    .delete("/users/user/picture")
    .then((res) => {
      dispatch({ type: SET_CURRENT_USER, payload: { profile_img: "" } });
      setPictureLoading(false);
    })
    .catch((err) => {
      console.log(
        "deleteProfilePicture CATCH ERROR: ",
        err.response.data.message
      );
      alert(err.response.data.message);
      setPictureLoading(false);
    });
  return null;
};

export const updateSaved = (saved, user_id) => (dispatch) => {
  axiosWithAuth()
    .post("/saved/", saved)
    .then((res) => {
      axiosWithAuth()
        .get(`/saved/${user_id}`)
        .then((res) => {
          dispatch({ type: SAVED_JOBS, payload: res.data });
        })
        .catch((error) => {
          console.error(error.message);
        });
    })
    .catch((err) => {
      console.log(err);
    });
  return null;
};

export const deleteSaved = (job_id) => (dispatch) => {
  axiosWithAuth()
    .delete(`/saved/${job_id}`)
    .then((res) => {
      dispatch({ type: DELETE_JOBS, payload: job_id });
    })
    .catch((err) => {
      console.log(err);
    });
  return null;
};

export const deleteApplied = (job_id) => (dispatch) => {
  axiosWithAuth()
    .delete(`/saved/${job_id}`)
    .then((res) => {
      dispatch({ type: DELETE_APPLIED, payload: job_id });
    })
    .catch((err) => {
      console.log(err);
    });
  return null;
};

export const getSavedAppliedJobs = (user_id) => (dispatch) => {
  axiosWithAuth()
    .get(`/saved/${user_id}`)
    .then((res) => {
      dispatch({ type: GET_SAVED_APPLIED_JOBS, payload: res.data });
    })
    .catch((error) => {
      console.error(error.message);
    });
};

export const updateApplied = (applied, user_id) => (dispatch) => {
  axiosWithAuth()
    .post("/saved/", applied)
    .then((res) => {
      axiosWithAuth()
        .get(`/saved/${user_id}`)
        .then((res) => {
          dispatch({ type: APPLIED_JOBS, payload: res.data });
        })
        .catch((error) => {
          console.error(error.message);
        });
    })
    .catch((err) => {
      console.log(err);
    });
};

<?php
/* @var $this InvoiceHeaderController */
/* @var $model InvoiceHeader */

$this->breadcrumbs = array(
    'Invoice Headers' => array('admin'),
    'Manage',
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
    $('.search-form').slideToggle(600);
    $('.bulk-action').toggle();
    $(this).toggleClass('active');
    if ($(this).hasClass('active')) {
            $(this).text('');
    } else {
            $(this).text('Advanced Search');
    }
    return false;
});

$('#invoiceSearch').submit(function(){
    $('#invoice-header-grid').yiiGridView('update', {
        data: $(this).serialize()
    });
    return false;
});
");
?>

<div id="maincontent">
    <div class="row">
        <div class="small-12 columns">
            <div class="clearfix page-action">
                <!-- <a class="button success right" href="<?php //echo Yii::app()->baseUrl.'/transaction/invoiceHeader/create'; ?>"><span class="fa fa-plus"></span>Create Invoice Headers</a> -->
                <h2>Manage Invoice Headers</h2>
            </div>

            <div class="search-bar">
                <div class="clearfix button-bar">
                    <div class="form">
                        <?php $form = $this->beginWidget('CActiveForm', array(
                            'action' => Yii::app()->createUrl($this->route),
                            'method' => 'get',
                            'id' => 'invoiceSearch',
                        )); ?>

                        <div class="row">
                            <div class="medium-6 columns">
                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <?php echo $form->label($model, 'customer_name', array('class' => 'prefix')); ?>
                                        </div>
                                        <div class="small-8 columns">
                                            <?php echo $form->textField($model, 'customer_name'); ?>
                                        </div>
                                    </div>
                                </div>	
                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <?php echo $form->label($model, 'customer_type', array('class' => 'prefix')); ?>
                                        </div>
                                        <div class="small-8 columns">
                                            <?php echo $form->dropDownList($model, 'customer_type', array('Individual' => 'Individual', 'Company' => 'Company',), array('prompt' => 'Select',)); ?>
                                        </div>
                                    </div>
                                </div>

                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <label class="prefix"><?php echo $form->labelEx($model, 'invoice_date'); ?></label>
                                        </div>
                                        <div class="small-8 columns">
                                            <div class="row">
                                                <div class="medium-5 columns">
                                                    <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                                        'model' => $model,
                                                        'attribute' => "invoice_date",
                                                        // additional javascript options for the date picker plugin
                                                        'options' => array(
                                                            'dateFormat' => 'yy-mm-dd',
                                                        //'changeMonth'=>true,
                                                        // 'changeYear'=>true,
                                                        // 'yearRange'=>'1900:2020'
                                                        ),
                                                        'htmlOptions' => array(),
                                                    )); ?>
                                                    <?php echo $form->error($model, 'invoice_date'); ?>

                                                </div>
                                                <div class="medium-7 columns">
                                                    <div class="field">
                                                        <div class="row collapse">
                                                            <div class="small-4 columns">
                                                                <label class="prefix">To</label>
                                                            </div>
                                                            <div class="small-8 columns">
                                                                <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                                                    'model' => $model,
                                                                    'attribute' => "invoice_date_to",
                                                                    // additional javascript options for the date picker plugin
                                                                    'options' => array(
                                                                        'dateFormat' => 'yy-mm-dd',
                                                                    //             'changeMonth'=>true,
                                                                    // 'changeYear'=>true,
                                                                    // 'yearRange'=>'1900:2020'
                                                                    ),
                                                                    'htmlOptions' => array(),
                                                                )); ?>
                                                            </div>
                                                        </div>
                                                    </div>

                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>	

                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <label class="prefix"><?php echo $form->labelEx($model, 'due_date'); ?></label>
                                        </div>
                                        <div class="small-8 columns">
                                            <div class="row">
                                                <div class="medium-5 columns">
                                                    <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                                        'model' => $model,
                                                        'attribute' => "due_date",
                                                        // additional javascript options for the date picker plugin
                                                        'options' => array(
                                                            'dateFormat' => 'yy-mm-dd',
                                                        //             'changeMonth'=>true,
                                                        // 'changeYear'=>true,
                                                        // 'yearRange'=>'1900:2020'
                                                        ),
                                                        'htmlOptions' => array(),
                                                    )); ?>
                                                    <?php echo $form->error($model, 'due_date'); ?>
                                                </div>
                                                <div class="medium-7 columns">
                                                    <div class="field">
                                                        <div class="row collapse">
                                                            <div class="small-4 columns">
                                                                <label class="prefix">To</label>
                                                            </div>
                                                            <div class="small-8 columns">
                                                                <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                                                    'model' => $model,
                                                                    'attribute' => "due_date_to",
                                                                    // additional javascript options for the date picker plugin
                                                                    'options' => array(
                                                                        'dateFormat' => 'yy-mm-dd',
                                                                    //             'changeMonth'=>true,
                                                                    // 'changeYear'=>true,
                                                                    // 'yearRange'=>'1900:2020'
                                                                    ),
                                                                    'htmlOptions' => array(),
                                                                )); ?>
                                                                <?php echo $form->error($model, 'due_date_to'); ?>
                                                            </div>
                                                        </div>
                                                    </div>															
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>	
                            </div>	
                            <div class="medium-6 columns">

                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <?php echo $form->label($model, 'invoice_number', array('class' => 'prefix')); ?>
                                        </div>
                                        <div class="small-8 columns">
                                            <?php echo $form->textField($model, 'invoice_number'); ?>
                                        </div>
                                    </div>
                                </div>	

                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <?php echo $form->label($model, 'status', array('class' => 'prefix')); ?>
                                        </div>
                                        <div class="small-8 columns">						
                                            <?php echo $form->dropDownList($model, 'status', array('PAID' => 'PAID', 'NOT PAID' => 'NOT PAID',), array('prompt' => 'Select',)); ?>
                                        </div>
                                    </div>
                                </div>	

                                <div class="buttons text-right">
                                    <?php echo CHtml::submitButton('Search', array('class' => 'button cbutton')); ?>
                                </div>

                            </div>
                        </div>

                        <?php $this->endWidget(); ?>
                    </div>
                </div>
            </div>

            <div class="grid-view">
                <?php $this->widget('zii.widgets.grid.CGridView', array(
                    'id' => 'invoice-header-grid',
                    'dataProvider' => $model->search(),
                    'filter' => $model,
                    // 'summaryText'=>'',
                    'rowCssClassExpression' => '(($data->status == "PAID")?"hijau":"merah")',
                    'template' => '{items}<!--<div class="clearfix">{summary}{pager}</div>-->',
                    'pager' => array(
                        'cssFile' => false,
                        'header' => '',
                    ),
                    'columns' => array(
                        array(
                            'class' => 'CCheckBoxColumn', //CHECKBOX COLUMN ADDED.
                            'selectableRows' => 2, //MULTIPLE ROWS CAN BE SELECTED.
                            'checked' => function($data) use($prChecked) {
                                return in_array($data->id, $prChecked);
                            },
                        ),
                        array(
                            'name' => 'invoice_number', 
                            'value' => 'CHtml::link($data->invoice_number, array("view", "id"=>$data->id))', 
                            'type' => 'raw'
                        ),
                        'invoice_date',
                        'due_date',
                        array(
                            'name' => 'reference_type', 
                            'value' => '$data->reference_type == 1 ? "Sales Order" : "Retail Sales"'
                        ),
                        array(
                            'name' => 'sales_order_id', 
                            'value' => '$data->sales_order_id != null ? $data->salesOrder->sale_order_no : CHtml::link($data->registrationTransaction->sales_order_number, array("/frontDesk/registrationTransaction/view", "id"=>$data->registration_transaction_id))',
                            'type' => 'raw'
                        ),
                        array(
                            'header' => 'WO #', 
                            'value' => '$data->sales_order_id != null ? "" : $data->registrationTransaction->work_order_number'
                        ),
                        array(
                            'name' => 'customer_id', 
                            'value' => '$data->customer_id != null ? $data->customer->name : ""'
                        ),
                        array(
                            'name' => 'customer_type', 
                            'value' => '$data->customer_id != null ? $data->customer->customer_type : ""'
                        ),
                        'status',
                    ),
                )); ?>

                <div class="button-group">
                    <?php if (Yii::app()->user->checkAccess("saleInvoiceEdit")): ?>
                        <?php echo CHtml::button("View Invoice", array("id" => "btnProses", 'class' => 'button cbutton')); ?>
                    <?php endif; ?>
                    <?php if (Yii::app()->user->checkAccess("saleInvoiceEdit")): ?>
                        <?php echo CHtml::button("Export PDF", array("id" => "btnProsesPdf", 'class' => 'button cbutton')); ?>
                    <?php endif; ?>

                    <?php echo CHtml::button("Clear Selected", array("id" => "btnClear", 'class' => 'button cbutton')); ?>
                </div>
            </div>
        </div>
    </div> <!-- end row -->
</div> <!-- end maintenance -->

<?php Yii::app()->clientScript->registerScript('centang', '
	$("#btnProses").click(function(){
        var checked=$("#invoice-header-grid").yiiGridView("getChecked","invoice-header-grid_c0");
        var count=checked.length;
        if (count>0){
            $.ajax({
                    data:{checked:checked},
                    url:"' . CHtml::normalizeUrl(array('invoiceHeader/prTemp')) . '",
                    success:function(data){
                    	$("#invoice-header-grid").yiiGridView("update",{});
                    	window.location.href = "' . CHtml::normalizeUrl(array('invoiceHeader/viewInvoices')) . '";
                    },              
            });
        } else {
            console.log("No Invoice items selected");
            alert("No Invoice items selected");
        }
    });

    $("#btnProsesPdf").click(function(){
        var checked=$("#invoice-header-grid").yiiGridView("getChecked","invoice-header-grid_c0");
        var count=checked.length;
        if (count > 0){
            $.ajax({
                data:{checked:checked},
                url:"' . CHtml::normalizeUrl(array('invoiceHeader/prTemp')) . '",
                success:function(data){
                    $("#invoice-header-grid").yiiGridView("update",{});
                    window.location.href = "' . CHtml::normalizeUrl(array('invoiceHeader/pdfAll')) . '";
                },              
            });
        } else {
            console.log("No Invoice items selected");
            alert("No Invoice items selected");
        }
    });

    $("#btnClear").click(function(){
        var checked="clear";
        $.ajax({
            data:{checked:checked},
            url:"' . CHtml::normalizeUrl(array('invoiceHeader/prTemp')) . '",
            success:function(data){
                $("#invoice-header-grid").yiiGridView("update",{});
            },              
        });
    });
'); ?>

/*
 <codex>
 <abstract>Simple 4x4 matrix computations</abstract>
 </codex>
 */

#ifndef MATRIX_H
#define MATRIX_H

void mat4f_LoadIdentity(float* m);
void mat4f_LoadScale(float* s, float* m);

void mat4f_LoadXRotation(float radians, float* mout);
void mat4f_LoadYRotation(float radians, float* mout);
void mat4f_LoadZRotation(float radians, float* mout);

void mat4f_LoadTranslation(float* t, float* mout);

void mat4f_LoadPerspective(float fov_radians, float aspect, float zNear, float zFar, float* mout);
void mat4f_LoadOrtho(float left, float right, float bottom, float top, float near, float far, float* mout);

void mat4f_MultiplyMat4f(const float* a, const float* b, float* mout);

#endif /* MATRIX_H */

<template>
  <div class="pay">
    <div class="pay-type">
      <span>交易方式:</span>
      <div :class="payType === 'union' ? 'unionSelected' : 'union'"
        @click="changePayType('union')"></div>
      <div :class="payType === 'deposit' ? 'depositSelected' : 'deposit'"
        @click="changePayType('deposit')"></div>
      <div :class="payType === 'alipay' ? 'alipaySelected' : 'alipay'"
        @click="changePayType('alipay')"></div>
      <div :class="payType === 'wepay' ? 'wepaySelected' : 'wepay'"
        @click="changePayType('wepay')"></div>
    </div>
    <!-- <div class="pay-total">
      <div class="pt-count">
        总计:
        <span>货品种类:{{od.total_type}}类</span>
        <span>数量总计:{{od.total_quantity}}件</span>
      </div>
      <div class="pt-pay">
        <span>运费共计:<span class="money">{{od.total_carriage}}</span></span>
        <span>货品总金额:<span class="money">¥{{od.total_money}}</span></span>
        <span class="ptp-total">应付总额(不含运费):<span class="money">¥{{od.total_money}}</span></span>
      </div>
    </div> -->
  </div>
</template>

<script>
export default {
  props: ['od', 'payType'],
  methods: {
    changePayType(type) {
      if(type === 'alipay' || type === 'wepay') this.$emit('updatePayType', {type})
      else this.$message('功能暂未开通...')
    }
  }
}
</script>

<style scoped lang="less">
.pay {
  width: 1024px;
  // height: 192px;

  @eColor: #ec6337;

  .p-box {
    display: flex;
    align-items: center;
    height: 112px;
    width: 1024px;
    padding: 0 10px;
    margin-bottom: 10px;
    font-size: 14px;
    color: #666;
    background-color: white;
  }

  .pay-type {
    .p-box;
    align-items: center;

    div {
      margin-left: 10px;
      width: 140px;
      height: 40px;
      box-sizing: border-box;
      cursor: pointer;
      border-radius: 4px;
    }

    .union {
      background: url(/static/img/p_union.png) 0 0 ~'/' 140px auto no-repeat;
      cursor: not-allowed;
    }

    .unionSelected {
      border: 1px solid @eColor;
      background: url(/static/img/p_union_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }

    .deposit {
      background: url(/static/img/p_deposit.png) 0 0 ~'/' 140px auto no-repeat;
      cursor: not-allowed;
    }

    .depositSelected {
      border: 1px solid @eColor;
      background: url(/static/img/p_deposit_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }

    .alipay {
      border: 1px solid #d8d8d8;
      background: url(/static/img/p_alipay_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }

    .alipaySelected {
      border: 1px solid @eColor;
      background: url(/static/img/p_alipay_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }

    .wepay {
      border: 1px solid #d8d8d8;
      background: url(/static/img/p_wepay_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }

    .wepaySelected {
      border: 1px solid @eColor;
      background: url(/static/img/p_wepay_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }
  }

  // .pay-total {
  //   .p-box;
  //   justify-content: space-between;

  //   .pt-count {

  //   }

  //   .pt-pay {
  //     display: flex;
  //     flex-direction: column;
  //     align-items: flex-end;
  //     font-size: 12px;

  //     .ptp-total {
  //       font-size: 14px;
  //     }

  //     .money {
  //       color: #ec6337;
  //       margin-left: 4px;
  //     }
  //   }
  // }
}
</style>

<!DOCTYPE html>
<html lang="en">

<head>

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

  <title><?= $title ?></title>

  <!-- Custom fonts for this template-->
  <link href="<?= base_url(); ?>assets/sbadmin/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

  <!-- Custom styles for this template-->
  <link href="<?= base_url(); ?>assets/sbadmin/css/sb-admin-2.min.css" rel="stylesheet">
  <style>
    html { 
      background: url(<?= base_url(); ?>assets/img/backgroundpnp.jpeg) no-repeat center center fixed; 
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
    }
    body {
      background-color: transparent;
    }
    .special-card {
      background-color: rgba(245, 245, 245, 1);
      opacity: .91;
    }
  </style>

</head>

<body>
const axios = require("../connectionService").axios
const { JSDOM } = require("jsdom");
const unwanted = JSON.parse(process.env.unwanted)
const banList = JSON.parse(process.env.banList)
const extraStrategy = require('./extraStrategy')
async function getBestPriceForCard(dom, edition, extras){
    extraStrategy.removeUselessExtras(extras)
    const cheapestStorePdp = getCheapestOptionURL(dom, edition, extras)
    return await getPriceFromCheapestStore(cheapestStorePdp, edition, extras)
}

function getCheapestOptionURL(dom, edition, extras){
    const availableOptions = [...dom.window.document.querySelectorAll("#aba-cards>.estoque-linha")]
    let rightEdition = availableOptions.filter(item => item.querySelector(".ed-simb") && 
        item.querySelector(".ed-simb").href.endsWith(`=${edition}`))
    if(extras.length)
      rightEdition = filterExtras(rightEdition, extras)
    rightEdition = removeUnwantedQualityGrades(rightEdition)
    rightEdition = removeStoresFromBanlist(rightEdition)
    const url = "https://www.ligamagic.com.br/" +rightEdition[0].querySelector(".goto").href
    const selectedGrade =  rightEdition[0].querySelector(".e-col4>font").innerHTML
    return {url, selectedGrade}
}

function removeStoresFromBanlist(rightEdition){
    return rightEdition.filter(item => {
        const img = item.querySelector(".e-col1 img").title;
        return !banList.some(store => img.includes(store))
    })
}

function filterExtras(rightEdition, extras){
    return rightEdition.filter(
        item => item.querySelector("p.extras") 
        && extras.every(
            extra => item.querySelector("p.extras").innerHTML.split(", ").includes(extra)
            )
        )
}

function removeUnwantedQualityGrades(rightEdition){
    return rightEdition.filter(item => 
        {
            const quality = item.querySelector(".e-col4>font")
            return !unwanted.some(qlty =>
                quality && quality.innerHTML.includes(qlty)) 
        })
}

async function getPriceFromCheapestStore(cheapestStorePdp, edition, extras){
    const page = await(axios.get(cheapestStorePdp.url))
    const dom = new JSDOM(page.data)
    let options = [...dom.window.document.querySelectorAll(".itemMain table table:last-child tbody tr")].slice(1)
    options = options.filter(item => filterFoils(item, extras)).filter(filterOutOfStock)
    const selected = options.filter(item => 
        item.querySelector(".very2Small") &&
        item.querySelector(".very2Small").innerHTML.includes(cheapestStorePdp.selectedGrade)
        && item.querySelector("img").src.toLowerCase().includes(`/${edition.toLowerCase()}_`))[0]
    if(selected.querySelector(".itemPreco").childElementCount > 0)
        return selected.querySelector(".itemPreco").lastElementChild.innerHTML
    else
        return selected.querySelector(".itemPreco").innerHTML
}

function filterOutOfStock(item){
    return item.querySelector(".hmin30:nth-child(5)").innerHTML !== "0 unid.";
}

function filterFoils(item, extras){
    const inner = (auction) => {
        return auction.querySelector(".hmin30:nth-child(4)")
            && extraStrategy.containsAllExtras(auction.querySelector(".hmin30:nth-child(4)"), extras)
    }

    return extras ? inner(item) : !inner(item)

}



exports.getBestPriceForCard = getBestPriceForCard;
import Foundation
import ExecutionContext
import Future
import Result

public protocol TransactionType : DataConsumerType {
    func tryConsume(content:ContentType) -> Bool
    
    var action:Future<AbstractActionType> {get}
    
    func selfProcess()
}

class Transaction<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType> : TransactionType {
    let app:Express
    let routeId:String
    let out:DataConsumerType
    let head:RequestHeadType
    let factory:RequestContent.Factory
    let content:Future<RequestContent.Factory.Content>
    let actionPromise:Promise<AbstractActionType>
    let action:Future<AbstractActionType>
    let request:Promise<Request<RequestContent>>
    
    internal required init(app:Express, routeId:String, head:RequestHeadType, out:DataConsumerType) {
        self.app = app
        self.routeId = routeId
        self.out = out
        self.head = head
        self.factory = RequestContent.Factory(response: head)
        self.content = factory.content()
        self.actionPromise = Promise()
        self.action = actionPromise.future
        self.request = Promise<Request<RequestContent>>()
        content.settle(in: ExecutionContext.user).onSuccess() { content in
            let request = Request<RequestContent>(app: app, head: head, body: content as? RequestContent)
            self.request.trySuccess(value: request)
        }
        content.onFailure { e in
            self.actionPromise.tryFail(error: e)
        }
    }
    
    convenience init(app:Express, routeId:String, head:RequestHeadType, out:DataConsumerType, handler:@escaping (Request<RequestContent>) -> Future<Action<ResponseContent>>) {
        self.init(app: app, routeId: routeId, head: head, out: out)
        request.future.onSuccess { request in
            let action = handler(request)
            action.onSuccess { action in
                self.actionPromise.trySuccess(value: action)
            }
            action.onFailure { e in
                self.failAction(e: e)
            }
        }
    }
    
    func failAction(e:Error) {
        self.actionPromise.tryFail(error: e)
    }
    
    func handleActionWithRequest<C : ConstructableContentType>(actionAndRequest:Future<(AbstractActionType, Request<C>?)>) {
        actionAndRequest.onComplete { result in
            let action = Future(result: result.map {$0.0})
            self.handleAction(action: action, request: result.value?.1)
        }
    }
    
    func handleAction<C : ConstructableContentType>(action:Future<AbstractActionType>, request:Request<C>?) {
        action.settle(in:ExecutionContext.action ).onSuccess{ action in
            if let request = request {
                self.processAction(action: action, request: request)
            } else {
                //yes we certainly have request here
                
                self.request.future.onSuccess{value in
                    self.processAction(action: action, request: value)
                }
            }
        }
        action.onFailure { e in
            //yes, we always have at least the default error handler
            let next = self.app.errorHandler.handle(e: e)!
            
            if let request = request {
                self.processAction(action: next, request: request)
            } else {
                self.request.future.onSuccess { request in
                    self.processAction(action: next, request: request)
                }
            }
        }
    }
    
    func selfProcess() {
        handleAction(action: action, request: Optional<Request<RequestContent>>.none)
    }
    
    func processAction<C : ConstructableContentType>(action:AbstractActionType, request:Request<C>) {
        switch action {
            case let flushableAction as FlushableAction: flushableAction.flushTo(out: out)
            case let intermediateAction as IntermediateActionType:
                let actAndReq = intermediateAction.nextAction(request: request)
                handleActionWithRequest(actionAndRequest: actAndReq)
            case let selfSufficientAction as SelfSufficientActionType:
                selfSufficientAction.handle(app: app, routeId: routeId, request: request, out: out).onFailure { e in
                    let action = Future<AbstractActionType>(error: e)
                    self.handleAction(action: action, request: request)
                }
            default:
                //TODO: handle server error
                print("wierd action... can do nothing with it")
        }
    }
    
    func tryConsume(content:ContentType) -> Bool {
        return factory.tryConsume(content: content)
    }
    
    func consume(data:Array<UInt8>) -> Future<Void> {
        return factory.consume(data: data)
    }
    
    func dataEnd() throws {
        try factory.dataEnd()
    }
}

typealias TransactionFactory = (RequestHeadType, DataConsumerType)->TransactionType
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;

import { IController } from "../interfaces/IController.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title IntegrationRegistry
 * @author Set Protocol
 *
 * The IntegrationRegistry holds state relating to the Modules and the integrations they are connected with.
 * The state is combined into a single Registry to allow governance updates to be aggregated to one contract.
 */
contract IntegrationRegistry is Ownable {

    /* ============ Events ============ */

    event IntegrationAdded(address indexed _module, address indexed _adapter, string _integrationName);
    event IntegrationRemoved(address indexed _module, address indexed _adapter, string _integrationName);
    event IntegrationEdited(
        address indexed _module,
        address _newAdapter,
        string _integrationName
    );

    /* ============ State Variables ============ */

    // Address of the Controller contract
    IController public controller;

    // Mapping of module => integration identifier => adapter address
    mapping(address => mapping(bytes32 => address)) private integrations;

    /* ============ Constructor ============ */

    /**
     * Initializes the controller
     *
     * @param _controller          Instance of the controller
     */
    constructor(IController _controller) public {
        controller = _controller;
    }

    /* ============ External Functions ============ */

    /**
     * GOVERNANCE FUNCTION: Add a new integration to the registry
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _name         Human readable string identifying the integration
     * @param  _adapter      Address of the adapter contract to add
     */
    function addIntegration(
        address _module,
        string memory _name,
        address _adapter
    )
        public
        onlyOwner
    {
        bytes32 hashedName = _nameHash(_name);
        require(controller.isModule(_module), "Must be valid module.");
        require(integrations[_module][hashedName] == address(0), "Integration exists already.");
        require(_adapter != address(0), "Adapter address must exist.");

        integrations[_module][hashedName] = _adapter;

        emit IntegrationAdded(_module, _adapter, _name);
    }

    /**
     * GOVERNANCE FUNCTION: Batch add new adapters. Reverts if exists on any module and name
     *
     * @param  _modules      Array of addresses of the modules associated with integration
     * @param  _names        Array of human readable strings identifying the integration
     * @param  _adapters     Array of addresses of the adapter contracts to add
     */
    function batchAddIntegration(
        address[] memory _modules,
        string[] memory _names,
        address[] memory _adapters
    )
        external
        onlyOwner
    {
        // Storing modules count to local variable to save on invocation
        uint256 modulesCount = _modules.length;

        require(modulesCount > 0, "Modules must not be empty");
        require(modulesCount == _names.length, "Module and name lengths mismatch");
        require(modulesCount == _adapters.length, "Module and adapter lengths mismatch");

        for (uint256 i = 0; i < modulesCount; i++) {
            // Add integrations to the specified module. Will revert if module and name combination exists
            addIntegration(
                _modules[i],
                _names[i],
                _adapters[i]
            );
        }
    }

    /**
     * GOVERNANCE FUNCTION: Edit an existing integration on the registry
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _name         Human readable string identifying the integration
     * @param  _adapter      Address of the adapter contract to edit
     */
    function editIntegration(
        address _module,
        string memory _name,
        address _adapter
    )
        public
        onlyOwner
    {
        bytes32 hashedName = _nameHash(_name);

        require(controller.isModule(_module), "Must be valid module.");
        require(integrations[_module][hashedName] != address(0), "Integration does not exist.");
        require(_adapter != address(0), "Adapter address must exist.");

        integrations[_module][hashedName] = _adapter;

        emit IntegrationEdited(_module, _adapter, _name);
    }

    /**
     * GOVERNANCE FUNCTION: Batch edit adapters for modules. Reverts if module and
     * adapter name don't map to an adapter address
     *
     * @param  _modules      Array of addresses of the modules associated with integration
     * @param  _names        Array of human readable strings identifying the integration
     * @param  _adapters     Array of addresses of the adapter contracts to add
     */
    function batchEditIntegration(
        address[] memory _modules,
        string[] memory _names,
        address[] memory _adapters
    )
        external
        onlyOwner
    {
        // Storing name count to local variable to save on invocation
        uint256 modulesCount = _modules.length;

        require(modulesCount > 0, "Modules must not be empty");
        require(modulesCount == _names.length, "Module and name lengths mismatch");
        require(modulesCount == _adapters.length, "Module and adapter lengths mismatch");

        for (uint256 i = 0; i < modulesCount; i++) {
            // Edits integrations to the specified module. Will revert if module and name combination does not exist
            editIntegration(
                _modules[i],
                _names[i],
                _adapters[i]
            );
        }
    }

    /**
     * GOVERNANCE FUNCTION: Remove an existing integration on the registry
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _name         Human readable string identifying the integration
     */
    function removeIntegration(address _module, string memory _name) external onlyOwner {
        bytes32 hashedName = _nameHash(_name);
        require(integrations[_module][hashedName] != address(0), "Integration does not exist.");

        address oldAdapter = integrations[_module][hashedName];
        delete integrations[_module][hashedName];

        emit IntegrationRemoved(_module, oldAdapter, _name);
    }

    /* ============ External Getter Functions ============ */

    /**
     * Get integration adapter address associated with passed human readable name
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _name         Human readable adapter name
     *
     * @return               Address of adapter
     */
    function getIntegrationAdapter(address _module, string memory _name) external view returns (address) {
        return integrations[_module][_nameHash(_name)];
    }

    /**
     * Get integration adapter address associated with passed hashed name
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _nameHash     Hash of human readable adapter name
     *
     * @return               Address of adapter
     */
    function getIntegrationAdapterWithHash(address _module, bytes32 _nameHash) external view returns (address) {
        return integrations[_module][_nameHash];
    }

    /**
     * Check if adapter name is valid
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _name         Human readable string identifying the integration
     *
     * @return               Boolean indicating if valid
     */
    function isValidIntegration(address _module, string memory _name) external view returns (bool) {
        return integrations[_module][_nameHash(_name)] != address(0);
    }

    /* ============ Internal Functions ============ */

    /**
     * Hashes the string and returns a bytes32 value
     */
    function _nameHash(string memory _name) internal pure returns(bytes32) {
        return keccak256(bytes(_name));
    }
}
import React from 'react';
import styled from 'styled-components/native';

export const Container = styled.SafeAreaView`
    flex: 1;
    justify-content:center;
    width:100%;
    /* background-color:#F2F6F8; */
    background-color:${props=>props.theme.background};
    padding:20px 20px 0 20px;
    
`;

export const Scroler = styled.ScrollView`
    flex: 1;
`;
export const Loading = styled.ActivityIndicator`
    margin:20px 0;
    color:${props=>props.theme.color};
`;
export const DadosCovid = styled.View`
`;

export const Graficos = styled.View`
    
`;

export const GraficosView = styled.View`
    margin:1px;
`;

export const Texto = styled.Text`

`;
export const Angola = styled.View`
    margin:1px;
    
    
    
    
`;
export const DadosAngola = styled.View`
    flex-direction:row;
    justify-content:space-between;
    flex:1;
    
   
`;

export const Dados = styled.View`
    background-color:${props=>props.theme.container};
    width:49%;
    padding:10px;
    overflow:hidden;
    border-radius:12px;
    elevation:2;
    margin-bottom:10px;
    height:90px;
    
`;

export const DadosCont = styled.View`
`;

export const TextoCont = styled.View`
    flex-direction:row;
    justify-content:space-between;
    align-items:center;
    margin-top:20px;
`;
export const TituloDado = styled.Text`
    font-family:"Poppins-Bold";
    letter-spacing:1px;
    font-size:18px;
    text-align:right;
    color:${props=>props.theme.color};
`;

export const TituloDadoNew = styled.Text`
    font-family:"Poppins-Bold";
    letter-spacing:1px;
    font-size:10px;
    text-align:right;
    margin-right:6px;
    color:${props=>props.theme.color};
    
`;
export const TituloDadoCritico = styled.Text`

    font-family:"Poppins-Bold";
    letter-spacing:1px;
    font-size:14px;
    color:${props=>props.theme.color};
`;
export const DadosCovidAngola = styled.View`

`;

export const DadosPais = styled.View`
    
    /* position:absolute; */
    /* top:-10px; */
`;
/* export const Texto = styled.Text`
font-size:16px;
    font-family:"Poppins-Bold";
    color:${props=>props.theme.color};
    margin-left:4px;
    background-color:${props=>props.theme.container};;
`; */

export const Titulo = styled.View`
    flex-direction:row;
    align-items:center;
    justify-content:space-between;
`;
export const TextoPais = styled.Text`
    font-size:18px;
    font-family:"Poppins-Bold";
    color:${props=>props.theme.color};
    margin-left:4px;
`;
export const Flag = styled.Image`
`;
export const TextoContinente = styled.View`
    flex-direction:row;
    margin-top:20px;
`;
export const TextoContinenteTexto = styled.Text`
    font-size:12px;
    font-family:"Poppins-Medium";
    color:${props=>props.theme.color};
`;
export const DadosDetalhes = styled.View`
    width:100%;
    margin:1px 1px 20px 1px;
    background-color:${props=>props.theme.container};;
    elevation:2;
    border-radius:8px;
    padding:10px;
    margin-top: 20px;
`;
export const MapaContainer = styled.View`
    margin-top:20px;
    width:100%;
`;
export const Botao = styled.TouchableOpacity`
    justify-content:center;
    width:100%;
    align-items:center;
`;
export const BotaoText = styled.Text`
    font-family:"Poppins-Bold";
    font-size:12px;
    color:${props=>props.theme.background};
    background-color:${props=>props.theme.color};
    padding:4px 30px;
    border-radius:4px;
    letter-spacing:1px;
`;
/**
 * Created by terminator10 on 2/11/15.
 */

//Create variables Global
var contador = 1;
//End Variables Global
function main () {
    $('.menu_bar').click(function(){
        if (contador == 1) {
            $('nav').animate({
                left: '0'
            });
            $('.menu_bar span').css({
               'background':'rgb(248,248,248)',
            });
            contador = 0;
        } else {
            $('.menu_bar span').css({
                'background':'#fff'
            });
            contador = 1;
            $('nav').animate({
                left: '100%'
            });

        }
    });
    // Mostramos y ocultamos submenus
    $('.submenu').click(function(){
        $(this).children('.children').slideToggle();
    });
}
/*Funciones para validar usuarios y email*/
function Validador(email){
    var tester = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z0-9]{2,4})+$/;
    return tester.test(email);
}
function caracter(username){
    var caract = /^([a-zA-Z0-9_-])/;
    return caract.test(username)
}
function pass(password){
    var pass = /(^(?=.*[a-z])(?=.*[A-Z])(?=.*\d){7,20}.+$)/;
    return pass.test(password)
}

$(document).ready(function(){
    main();
    /*Verificacion de usurios   $(document).ready(main);*/
    /*Validacion el password*/
   document.getElementById('password').addEventListener('blur',function(){
        var password = document.getElementById('password').value;
        if(pass(password) == false){
            $('.password-validate').css({
                'color': '#fff'
            });
            $('.validate-pass').html('<i class="icon-warning"></i>').show();
            $('.validate-pass').css({
                'color': '#b20000'
            });
            return false;
        }else{
            $('.password-validate').css({
                'color': '#8c8c8c'
            });
            $('.validate-pass').html('<i class="icon-checkmark"></i>').show();
            $('.validate-pass').css({
                'color': 'rgba(72, 130, 255, 1)'
            });
        }
    });
    document.getElementById('username').addEventListener('blur',function(){
        var username = document.getElementById('username').value;
        if (username.length > 0) {
            if (caracter(username) == false) {
                $('.loader').html("<i class='icon-user'></i> Nombre de usuario no es válido o ya adoptadas.").show().delay(2000).hide(200);
                $('.validate-user').css({
                    'color': '#b20000'
                });
                $('.validate-user').html('<i class="icon-warning"></i>').show();
                return false;
            }else {
                $('.loader').html('').hide();
                $.ajax({
                    type:'POST',
                    url:'server/app_server_whereis.php',
                    data:{username:username, wis:'verify_user'},
                    success: function (data) {
                        if (data == 0) {
                            $('.validate-user').css({
                                'color': '#b20000'
                            });
                            $('.validate-user').html('<i class="icon-warning"></i>').show();
                            $('.loader').html("<i class='icon-user'></i> Nombre de usuario no es válido o ya adoptadas.").show().delay(2000).hide(200);
                        } else if (data == 1) {
                            $('.validate-user').css({
                                'color': 'rgba(72, 130, 255, 1)'
                            });
                            $('.validate-user').html('<i class="icon-checkmark"></i>').show();
                        }
                    }
                });
            }
        }
    });
    document.getElementById('email').addEventListener('blur',function(){
        var email = document.getElementById('email').value;
        if (email.length > 0) {
            if (Validador(email) == false) {
                $('.loader').html("<i class='icon-mail2'></i> Correo electronico no es válido o ya adoptadas.").show().delay(2000).hide(200);
                $('.validate-email').css({
                    'color': '#b20000'
                });
                $('.validate-email').html('<i class="icon-warning"></i>').show();
                return false;
            } else {
                $('.loader').html('').hide();
                $.ajax({
                    type: 'POST',
                    url: 'server/app_server_whereis.php',
                    data: {email: email, wis: 'verify_email'},
                    success: function (data) {

                        if (data == 0) {
                            $('.validate-email').css({
                                'color': '#b20000'
                            });
                            $('.validate-email').html('<i class="icon-warning"></i>').show();
                            $('.loader').html("<i class='icon-mail2'></i> Correo electronico no es válido o ya adoptadas.").show().delay(2000).hide(200);
                        }else if (data == 1) {
                            $('.validate-email').css({
                                'color': 'rgba(72, 130, 255, 1)'
                            });
                            $('.validate-email').html('<i class="icon-checkmark"></i>').show();
                        }
                    }
                });

            }
        }
    });
});

function login_data_user(){
    var username = document.getElementById('username').value;
    var email = document.getElementById('email').value;
    var password = document.getElementById('password').value;
    var len = username.length * email.length * password.length;
    if(len == "" && Validador(email) == false && caracter(username) == false && pass(password) == false){
        $('.loader').html('<i class="icon-warning"></i> Ohh! Datos introducidos incorrectos o campos estan vacios.').show().delay(2000).hide(200);
        return false;
    }else {
        $.ajax({
            type: 'POST',
            url: 'server/app_server_whereis.php',
            data: {username: username, email: email, password: password, wis: 'login_whereis'},
            success: function (data) {
                if (data == 1) {
                    $('.register-button').html("Creando su cuenta").show();
                    $('.loader').html('<div class="loader-inner ball-pulse-sync"><div></div><div></div><div></div></div>').show();
                    setTimeout(function () {
                        window.location = "inicio";
                    }, 3000);
                } else if (data == 2) {
                    $('.loader').html('<i class="icon-shocked"></i> Ohh! Hubo problemas para crear tu cuenta o datos ya adoptados. ').show().delay(2000).hide(200);
                } else if (data == 3) {
                    $('.loader').html('<i class="icon-sad"></i> Ohh! Asegurate de que tu usuario y email son correctos.').show().delay(2000).hide(200);
                }
            }
        });
    }
}







﻿// License
// --------------------------------------------------------------------------------------------------------------------
// (C) Copyright 2021 Cato Léan Trütschel and contributors
// (github.com/CatoLeanTruetschel/AsyncQueryableAdapterPrototype)
//
// 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
//
//      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.
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncQueryableAdapter.Sample
{
    internal static class Program
    {
        private static Repository Repository { get; } = new Repository();

#pragma warning disable CS1998, IDE0060
        private static async Task Main(string[] args)
#pragma warning restore CS1998, IDE0060
        {
            var lastNamesSync = from person in Repository.People
                                where person.Age > 25 && person.LastName != "Adams" && person.Gender != Gender.Unknown
                                select person.LastName;

            lastNamesSync = lastNamesSync.Where(p => p.Length > 6);

            Console.WriteLine("Last names: " + string.Join(", ", lastNamesSync));

            var lastNamesAsync = from person in Repository.QueryAdapter.GetAsyncQueryable<Person>()
                                 where person.Age > 25 && person.LastName != "Adams" && person.Gender != Gender.Unknown
                                 select person.LastName;

            var lastNames = await lastNamesAsync.WhereAwait(p => new ValueTask<bool>(p.Length > 6)).ToArrayAsync();

            Console.WriteLine("Last names: " + string.Join(", ", lastNames));
            Console.WriteLine("Last names count: " + await lastNamesAsync.CountAsync());
            Console.WriteLine("Last names max length: " + await lastNamesAsync.Select(p => p.Length).MaxAsync());
        }
    }

    internal sealed class Repository
    {
        private readonly List<Person> _people;
        private readonly List<Relationship> _relationships;

        public Repository()
        {
            QueryAdapter = new RepositoryQueryAdapter(this);
            (_people, _relationships) = SeedData();
        }

        private static (List<Person> people, List<Relationship> relationships) SeedData()
        {
            var relationships = new List<Relationship>();

            var christopherWagner = new Person("Christopher", "Wagner", 22, Gender.Male);
            var juanaMartinez = new Person("Juana", "Martinez", 30);
            var davidEstes = new Person("David", "Estes", 53, Gender.Male);
            var ashSapp = new Person("Ash", "Sapp", 21, Gender.Diverse);

            var jasonRandolph = new Person("Jason", "Randolph", 46, Gender.Male);
            var patriciaStone = new Person("Patricia", "Stone", 48, Gender.Female);
            relationships.Add(new Relationship(jasonRandolph, patriciaStone));

            var julieDaniels = new Person("Julie", "Daniels", 29, Gender.Female);
            var deborahFerguson = new Person("Deborah", "Ferguson", 31, Gender.Female);
            relationships.Add(new Relationship(julieDaniels, deborahFerguson));

            var lewisAdams = new Person("Lewis", "Adams", 46, Gender.Male);
            var rondaBelle = new Person("Ronda", "Belle", 41, Gender.Diverse);
            relationships.Add(new Relationship(lewisAdams, rondaBelle));

            var robertPhillips = new Person("Robert", "Phillips", 36, Gender.Male);
            var meghanPhillips = new Person("Meghan", "Phillips", 34, Gender.Female);
            relationships.Add(new Relationship(robertPhillips, meghanPhillips));

            var people = new List<Person>
            {
                christopherWagner,
                juanaMartinez,
                davidEstes,
                ashSapp,
                jasonRandolph,
                patriciaStone,
                julieDaniels,
                deborahFerguson,
                lewisAdams,
                rondaBelle,
                robertPhillips,
                meghanPhillips
            };

            return (people, relationships);
        }

        public IQueryable<Person> People => _people.AsQueryable();
        public IQueryable<Relationship> Relationships => _relationships.AsQueryable();

        public RepositoryQueryAdapter QueryAdapter { get; }
    }

    internal sealed class RepositoryQueryAdapter : QueryAdapterBase
    {
        private readonly Repository _repository;

        public RepositoryQueryAdapter(Repository repository)
            : base(Microsoft.Extensions.Options.Options.Create(new AsyncQueryableOptions()))
        {
            if (repository is null)
                throw new ArgumentNullException(nameof(repository));

            _repository = repository;
        }

        protected override IQueryable<T> GetQueryable<T>()
        {
            if (typeof(T) == typeof(Person))
            {
                return (IQueryable<T>)_repository.People;
            }

            if (typeof(T) == typeof(Relationship))
            {
                return (IQueryable<T>)_repository.Relationships;
            }

            return Enumerable.Empty<T>().AsQueryable();
        }

        protected override IAsyncEnumerable<T> EvaluateAsync<T>(
            IQueryable<T> queryable,
            CancellationToken cancellation)
        {
            return queryable.ToAsyncEnumerable();
        }
    }

    internal record Person(string FirstName, string LastName, int Age, Gender Gender = Gender.Unknown);

    internal record Relationship(Person Partner1, Person Pertner2);

    internal enum Gender
    {
        Unknown,
        Female,
        Male,
        Diverse,
        Other,
        None
    }
}

from core.terraform.resources import BaseTerraformVariable, TerraformData, TerraformResource
from core.config import Settings
from core.terraform.utils import get_terraform_resource_path, get_terraform_latest_output_file, get_terraform_status_file
from core.log import SysLog
from core import constants as K
from core.lib.python_terraform import *
from datetime import datetime
from core.utils import exists_teraform_lock
import inspect
import json


class PyTerraform():
    log_obj = SysLog()

    def terraform_init(self):
        if exists_teraform_lock():
            raise Exception(K.ANOTHER_PROCESS_RUNNING)

        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
        )
        self.log_obj.write_debug_log(K.TERRAFORM_INIT_STARTED)
        response = terraform.init()

        if response[0] == 1:
            self.log_obj.write_debug_log(K.TERRAFORM_INIT_ERROR)
            raise Exception(response[2])

        self.log_obj.write_terraform_init_log(response)

        return response

    def terraform_plan(self, resources=None):
        if exists_teraform_lock():
            raise Exception(K.ANOTHER_PROCESS_RUNNING)

        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
            targets=self.get_target_resources(resources)
        )

        self.log_obj.write_debug_log(K.TERRAFORM_PLAN_STARTED)
        response = terraform.plan()

        if response[0] == 1:
            self.log_obj.write_debug_log(K.TERRAFORM_PLAN_ERROR)
            raise Exception(response[2])

        self.log_obj.write_terraform_plan_log(response)

        return response

    def terraform_apply(self, resources=None):
        if exists_teraform_lock():
            raise Exception(K.ANOTHER_PROCESS_RUNNING)

        CMD = Settings.get('running_command', "Terraform Apply")
        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
            targets=self.get_target_resources(resources),
            stdout_log_file=self.log_obj.get_terraform_install_log_file()
        )

        self.log_obj.write_terraform_apply_log_header()
        # In order to -auto-approve we need to pass skip_plan=True for python3
        response = terraform.apply(skip_plan=True)

        if response[0] == 1:
            self.log_obj.write_debug_log(K.TERRAFORM_APPLY_ERROR)
            self.write_current_status(CMD, K.APPLY_STATUS_ERROR, response[2])
            raise Exception(response[2])

        self.write_current_status(CMD, K.APPLY_STATUS_COMPLETED, K.TERRAFORM_APPLY_COMPLETED)
        return response

    def terraform_destroy(self, resources=None):
        if exists_teraform_lock():
            raise Exception(K.ANOTHER_PROCESS_RUNNING)

        CMD = Settings.get('running_command', "Terraform Destroy")
        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
            targets=self.get_target_resources(resources),
            stdout_log_file=self.log_obj.get_terraform_destroy_log_file()
        )

        self.log_obj.write_terraform_destroy_log_header()
        kwargs = {"auto_approve": True}
        response = terraform.destroy(**kwargs)

        if response[0] == 1:
            self.log_obj.write_debug_log(K.TERRAFORM_DESTROY_ERROR)
            self.write_current_status(CMD, K.DESTROY_STATUS_ERROR, response[2])
            raise Exception(response[2])

        self.write_current_status(CMD, K.DESTROY_STATUS_COMPLETED, K.TERRAFORM_DESTROY_COMPLETED)
        return response

    def process_destroy_result(self, p):
        response = Terraform().return_process_result(p)
        CMD = Settings.get('running_command', "Terraform Destroy")

        if response[0] == 1:
            self.log_obj.write_debug_log(K.TERRAFORM_DESTROY_ERROR)
            self.write_current_status(CMD, K.DESTROY_STATUS_ERROR, response[2])
            raise Exception(response[2])

        self.write_current_status(CMD, K.DESTROY_STATUS_COMPLETED, K.TERRAFORM_DESTROY_COMPLETED)

    def terraform_taint(self, resources):
        if exists_teraform_lock():
            raise Exception(K.ANOTHER_PROCESS_RUNNING)

        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
        )

        taint_resources = self.get_taint_resources(resources)

        self.log_obj.write_debug_log(K.TERRAFORM_TAINT_STARTED)

        for resource_name in taint_resources:
            response = terraform.cmd("taint", resource_name)
            if response[0] == 1:
                self.log_obj.write_debug_log(K.TERRAFORM_TAINT_ERROR)
                raise Exception(response[2])

        self.log_obj.write_debug_log(K.TERRAFORM_TAINT_COMPLETED)

        return response

    def get_target_resources(self, resources):
        if resources:
            targets = []
            for resource in resources:
                # DO NOT process this resource as its definiiton asked to skip
                if resource.PROCESS is False:
                    continue

                if BaseTerraformVariable not in inspect.getmro(resource.__class__) and TerraformData not in inspect.getmro(resource.__class__):
                    targets.append(get_terraform_resource_path(resource))

            return targets

        return None

    def get_taint_resources(self, resources):
        taint_resources = []
        for resource in resources:
            if TerraformResource in inspect.getmro(resource.__class__):
                taint_resources.append(get_terraform_resource_path(resource))

        return taint_resources

    @classmethod
    def save_terraform_output(cls):
        tf_output_file = get_terraform_latest_output_file()
        output_dict = cls.load_terraform_output()

        with open(tf_output_file, 'w') as jsonfile:
            json.dump(output_dict, jsonfile, indent=4)
        cls.log_obj.write_debug_log(K.TERRAFORM_OUTPUT_STORED)

        return output_dict

    @classmethod
    def load_terraform_output(cls):
        output_dict = {}

        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
        )
        response = terraform.output()
        if response:
            for key, item in response.items():
                key_splitted = key.split('-')
                resource_key = '-'.join(key_splitted[0:-1])

                if resource_key in output_dict:
                    output_dict[resource_key][key_splitted[-1]] = item['value']
                else:
                    output_dict[resource_key] = {key_splitted[-1]: item['value']}

        return output_dict

    @classmethod
    def load_terraform_output_from_json_file(cls):
        tf_output_file = get_terraform_latest_output_file()
        output_dict = {}
        if os.path.exists(tf_output_file):
            with open(tf_output_file) as jsonfile:
                output_dict = json.load(jsonfile)

        return output_dict

    def write_current_status(self, command, status_code, description=""):
        current_status = self.get_current_status()
        prev_status = None

        if current_status:
            prev_status = {
                'status_code': current_status['status_code'],
                'description': current_status['description'],
                'last_exec_command': current_status['last_exec_command'],
                'executed_time': current_status['executed_time']
            }

        current_status['status_code'] = status_code
        current_status['description'] = description
        current_status['last_exec_command'] = command
        current_status['executed_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        if prev_status:  # FIrst time previous status won't be available
            current_status[prev_status['executed_time']] = prev_status

        status_file = get_terraform_status_file()
        with open(status_file, 'w') as jsonfile:
            json.dump(current_status, jsonfile, indent=4)

    @classmethod
    def get_current_status(self):
        status_file = get_terraform_status_file()
        status_dict = {}
        if os.path.exists(status_file):
            with open(status_file) as jsonfile:
                status_dict = json.load(jsonfile)

        return status_dict

import UIKit

class HSUserProtocalController: UIViewController {
    
      let  webView : UIWebView = UIWebView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height-64));

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.init(red: 0xf3/255.0, green: 0xf3/255.0, blue: 0xf3/255.0, alpha: 1.0);
        self.title = "用户许可协议";
        self.webView.scalesPageToFit = true;
        self.view.addSubview(self.webView);
        
        let url = NSURL.init(string: "http://www.elitez.cn/html/user_agreement");
        let request = NSURLRequest.init(URL: url!);
        self.webView.loadRequest(request);
    }
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
---
title: 基于报表生成数据馈送（报表生成器和 SSRS）| Microsoft Docs
ms.custom: ''
ms.date: 05/30/2017
ms.prod: reporting-services
ms.prod_service: reporting-services-sharepoint, reporting-services-native
ms.component: report-builder
ms.reviewer: ''
ms.suite: pro-bi
ms.technology: ''
ms.tgt_pltfrm: ''
ms.topic: conceptual
ms.assetid: 4e00789f-6967-42e5-b2b4-03181fdb1e2c
caps.latest.revision: 12
author: maggiesMSFT
ms.author: maggies
manager: kfile
ms.openlocfilehash: 394a6ddd55d78615894b42a983f523827bafa27b
ms.sourcegitcommit: 1740f3090b168c0e809611a7aa6fd514075616bf
ms.translationtype: HT
ms.contentlocale: zh-CN
ms.lasthandoff: 05/03/2018
---
# <a name="generating-data-feeds-from-reports-report-builder-and-ssrs"></a>基于报表生成数据馈送（报表生成器和 SSRS）

  [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] Atom 呈现扩展插件可生成 Atom 服务文档，该文档列出分页报表中可用的数据馈送以及来自报表中的数据区域的数据馈送。 使用此扩展插件生成与 Atom 兼容的数据馈送，这些馈送是可读的，并可以与使用从报表生成的数据馈送的应用程序进行交换。 例如，可以使用 Atom 呈现扩展插件生成随后可用在 Power Pivot 或 Power BI 中的数据馈送。  
  
 Atom 服务文档为报表中的每个数据区域至少列出一个数据馈送。 根据数据区域的类型以及数据区域显示的数据， [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] 可以自数据区域生成多个数据馈送。 例如，矩阵或图表可以提供多个数据馈送。 Atom 呈现扩展插件创建 Atom 服务文档时，将为每个数据馈送创建一个唯一标识符，在 URL 中使用该标识符可以访问数据馈送的内容。  
  
 Atom 呈现扩展插件为数据馈送生成数据的方式类似于逗号分隔值 (CSV) 呈现扩展插件将数据呈现到 CSV 文件的方式。 类似于 CSV 文件，数据馈送是报表数据的平展表示形式。 例如，表中有一个行组对某组中的销售额进行加总时，会对每个数据行重复加总，并没有单独的行仅包含总和。  
  
 可以使用 [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] Web 门户、Report Server 或与 [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)]集成的 SharePoint 站点来生成 Atom 服务文档和数据馈送。  
  
 Atom 应用于一对相关标准。 Atom 服务文档符合 RFC 5023 Atom 发布协议规范，数据馈送符合 RFC 4287 Atom 联合格式协议规范。  
  
 以下各节提供有关如何使用 Atom 呈现扩展插件的附加信息：  
  
 [!INCLUDE[ssRBRDDup](../../includes/ssrbrddup-md.md)]  
  
##  <a name="ReportDataAsDataFeeds"></a> 作为数据馈送的报表  
 可以将生产报表作为数据馈送导出，或者可以创建主要目的是以数据馈送的形式向应用程序提供数据的报表。 将报表用作数据馈送为您在以下情况下提供了另一种向应用程序提供数据的方式：当数据不易通过客户端数据访问接口访问时，或者您更喜欢隐藏数据源的复杂性以使数据的使用更为简便时。 还可以使用 [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] 功能（如安全、计划和报表快照）管理用来提供数据馈送的报表，这是将报表用作数据馈送的另一个优点。  
  
 若要充分利用 Atom 呈现扩展插件，您应该理解报表是如何呈现到数据馈送中的。 如果使用现有报表，则若能预测这些报表能够生成的数据馈送将很有用；如果编写报表的目的是专门用作数据馈送，则重要的是能够包括数据并优化报表布局以充分利用数据馈送。  
  
 有关详细信息，请参阅[从报表生成数据馈送（报表生成器和 SSRS）](../../reporting-services/report-builder/generate-data-feeds-from-a-report-report-builder-and-ssrs.md)。  
  
  
##  <a name="AtomServiceDocument"></a> Atom 服务文档（.atomsvc 文件）  
 Atom 服务文档指定针对一个或多个数据馈送的连接。 该连接至少是指向生成馈送的数据服务的简单 URL。  
  
 使用 Atom 呈现扩展插件呈现报表数据时，Atom 服务文档将列出可用于报表的数据馈送。 该文档为报表中的每个数据区域至少列出一个数据馈送。 表和仪表都只生成一个数据馈送；但矩阵、列表和图表可能生成多个数据馈送，具体取决于它们所显示的数据。  
  
 下图显示了使用两个表和一个图表的报表。  
  
 ![RS_Atom_TableAndChartDataFeeds](../../reporting-services/report-builder/media/rs-atom-tableandchartdatafeeds.gif "RS_Atom_TableAndChartDataFeeds")  
  
 从此报表生成的 Atom 服务文档包括三个数据馈送：两个表各对应一个数据馈送，图表对应一个数据馈送。  
  
 矩阵数据区域可能包括多个数据馈送，这取决于该矩阵的结构。 下图显示的报表使用生成两个数据馈送的矩阵。  
  
 ![RS_Atom_PeerDynamicColumns](../../reporting-services/report-builder/media/rs-atom-peerdynamiccolumns.gif "RS_Atom_PeerDynamicColumns")  
  
 从此报表生成的 Atom 服务文档包括两个数据馈送：两个动态对等列（Territory 和 Year）各对应一个数据馈送。 下图显示了每个数据馈送的内容。  
  
 ![RS_Atom_PeerDynamicDataFeeds](../../reporting-services/report-builder/media/rs-atom-peerdynamicdatafeeds.gif "RS_Atom_PeerDynamicDataFeeds")  
  
  
##  <a name="DataFeeds"></a> 数据馈送  
 数据馈送是一个 XML 文件，它具有一致的不随时间变化的表格格式，以及在每次运行报表时都可能不同的可变数据。 [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] 生成的数据馈送采用与 ADO.NET Data Services 生成的数据馈送相同的格式。  
  
 数据馈送包含两部分：标题和数据。 Atom 规范中定义了各部分中的元素。 标题包括用于数据馈送的字符编码架构之类的信息。  
  
### <a name="header-section"></a>标题部分  
 以下 XML 代码显示数据馈送的标题部分。  
  
 `<?xml version="1.0" encoding="utf-8" standalone="yes"?><feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">`  
  
 `<title type="text"></title>`  
  
 `<id>uuid:1795992c-a6f3-40ec-9243-fbfd0b1a5be3;id=166321</id>`  
  
 `<updated>2009-05-08T23:09:58Z</updated>`  
  
### <a name="data-section"></a>数据部分  
 数据馈送的数据部分为 Atom 呈现扩展插件生成的平展行集中的每一行都包含一个 \<entry> 元素。  
  
 下图显示了使用组和总计的报表。  
  
 ![RS_Atom_ProductSalesSummaryCircledValues](../../reporting-services/report-builder/media/rs-atom-productsalessummarycircledvalues.gif "RS_Atom_ProductSalesSummaryCircledValues")  
  
 下面的 XML 在数据馈送中显示了来自该报表的 \<entry> 元素。 请注意，\<entry> 元素包含该组的销售和订单的总计以及所有组的销售和订单的总计。 \<entry> 元素包含报表中的所有值。  
  
 `<entry><id>uuid:1795992c-a6f3-40ec-9243-fbfd0b1a5be3;id=166322</id><title type="text"></title><updated>2009-05-08T23:09:58Z</updated><author /><content type="application/xml"><m:properties>`  
  
 `<d:ProductCategory_Value>Accessories</d:ProductCategory_Value>`  
  
 `<d:OrderYear_Value m:type="Edm.Int32">2001</d:OrderYear_Value>`  
  
 `<d:SumLineTotal_Value m:type="Edm.Decimal">20235.364608</d:SumLineTotal_Value>`  
  
 `<d:SumOrderQty_Value m:type="Edm.Int32">1003</d:SumOrderQty_Value>`  
  
 `<d:SumLineTotal_Total_2_1 m:type="Edm.Decimal">1272072.883926</d:SumLineTotal_Total_2_1>`  
  
 `<d:SumOrderQty_Total_2_1 m:type="Edm.Double">61932</d:SumOrderQty_Total_2_1>`  
  
 `<d:SumLineTotal_Total_2_2 m:type="Edm.Decimal">109846381.399888</d:SumLineTotal_Total_2_2>`  
  
 `<d:SumOrderQty_Total_2_2 m:type="Edm.Double">274914</d:SumOrderQty_Total_2_2></m:properties></content>`  
  
 `</entry>`  
  
### <a name="working-with-data-feeds"></a>使用数据馈送  
 由报表生成的所有数据馈送都包括生成数据馈送的数据区域父级范围内的报表项。 集成的 SharePoint 站点来生成 Atom 服务文档和数据馈送。 设想有一个报表包含若干表和一个图表。 报表正文中的文本框提供有关每个数据区域的说明性文本。 该报表生成的每个数据馈送中的每个条目都包括该文本框的值。 例如，如果文本为“Chart displays monthly sales averages by sales region”，则所有三个数据馈送都会在每一行中包括此文本。  
  
 如果报表布局包括分层数据关系，如嵌套数据区域，这些关系将包括在报表数据的平展行集中。  
  
 嵌套数据区域的数据行通常较宽，特别是在嵌套表和矩阵包括组和总计的情况下。 您可能会发现，将报表导出到数据馈送并且查看数据馈送以确定生成的数据就是所需数据，这会很有帮助。  
  
 当 Atom 呈现扩展插件创建 Atom 服务文档时，将为数据馈送创建一个唯一标识符，在 URL 中使用该标识符可以查看数据馈送的内容。 示例 Atom 服务文档（如上所示）包括 URL `http://ServerName/ReportServer?%2fProduct+Sales+Summary&rs%3aCommand=Render&rs%3aFormat=ATOM&rc%3aDataFeed=xAx0x1`。 该 URL 标识报表 (Product Sales Summary)、Atom 呈现格式 (ATOM) 以及数据馈送的名称 (xAx0x1)。  
  
 报表项名称默认为报表项的报表定义语言 (RDL) 元素名称，这些名称经常较为直观或容易记忆。 例如，放入报表的第一个矩阵的默认名称为 Tablix 1。 数据馈送使用这些名称。  
  
 若要令数据馈送易于使用，可以使用数据区域的 DataElementName 属性来提供友好名称。 如果为 DataElementName 提供值，数据馈送子元素 \<d> 将使用该值，而不是使用默认的数据区域名称。 例如，如果数据区域的默认名称为 Tablix1，而 DataElementName 设置为 SalesByTerritoryYear，则数据馈送中的 \<d> 将使用 SalesByTerritoryYear。 如果数据区域具有两个数据馈送（类似上述矩阵报表），则数据馈送中使用的名称为 SalesByTerritoryYear _Territory 和 SalesByTerritoryYear _Year。  
  
 如果对报表显示的数据和数据馈送中的数据进行比较，则可能发现一些差异。 报表经常显示格式化的数值和时间/日期数据，但数据馈送包含非格式化的数据。  
  
 数据馈送用 .atom 文件扩展名保存。 可以使用文本或 XML 编辑器（如记事本或 XML 编辑器）来查看文件结构和内容。  
  
  
##  <a name="FlatteningReportData"></a> 平展报表数据  
 Atom 呈现器将报表数据提供为 XML 格式的平展行集。 用于平展数据表的规则与用于 CSV 呈现器的规则相同，只有以下几点例外：  
  
-   范围中的项平展到详细信息级别。 不同于 CSV 呈现器，顶级文本框显示在写入数据馈送的每个条目中。  
  
-   在输出的每一行上呈现报表参数值。  
  
 分层数据和分组数据必须进行平展才能以与 Atom 兼容的格式表示。 呈现扩展插件可将报表平展为用于表示数据区域中嵌套组的树结构。 要平展报表：  
  
-   行层次结构在列层次结构之前进行平展。  
  
-   行层次结构的成员在列层次结构的成员之前呈现到数据馈送。  
  
-   列按照以下顺序排序：表体中的文本框的顺序为从左到右，从上到下，后面紧跟数据区域，后者顺序为从左到右，从上到下。  
  
-   在数据区域中，列按照以下顺序排序：角成员、行层次结构成员、列层次结构成员，然后是单元。  
  
-   对等数据区域是一些共享一个公共数据区域或动态祖先的数据区域或动态组。 对等数据通过平展后的树的分支进行标识。  
  
 有关详细信息，请参阅 [表、矩阵和列表（报表生成器和 SSRS）](../../reporting-services/report-design/tables-matrices-and-lists-report-builder-and-ssrs.md)。  
  
  
##  <a name="AtomRendering"></a> Atom 呈现规则  
 Atom 呈现扩展插件在呈现数据馈送时忽略以下信息：  
  
-   格式设置和布局  
  
-   页眉  
  
-   页脚  
  
-   自定义报表项  
  
-   矩形  
  
-   线条  
  
-   映像  
  
-   自动小计  
  
 对其余的报表项进行排序，先从上到下排，再从左到右排。 之后，每一项将呈现到一列中。 如果报表有嵌套数据项（如列表或表），则会在每一行中重复它的父项。  
  
 下表说明了呈现报表项时这些报表项的外观：  
  
|项|呈现行为|  
|----------|------------------------|  
|表|呈现方式为扩展该表，在只保留最起码的格式的情况下为每一行和每一列都分别创建行和列。 小计行和小计列没有列标题或行标题。 不支持钻取报表。|  
|矩阵|呈现方式为扩展该矩阵，在只保留最起码的格式的情况下为每一行和每一列都分别创建行和列。 小计行和小计列没有列标题或行标题。|  
|列表|为列表中每一明细行或实例呈现一个记录。|  
|子报表|对于内容的每个实例，都会重复它的父项。|  
|图表|为每个图表值呈现具有所有图表标签的记录。 来自系列和类别的标签采用平展的层次结构，并包含在图表值的行中。|  
|数据条|像图表一样呈现。 通常，数据条并不包括层次结构或标签。|  
|迷你图|像图表一样呈现。 通常，迷你图并不包括层次结构或标签。|  
|测量|作为单个记录呈现，具有线性刻度的最小值和最大值、范围的起始和终止值，以及指针的值。|  
|指示器|作为单个记录呈现，具有活动状态名称、可用状态以及数据值。|  
|地图|为每个地图数据区域生成数据馈送。 如果多个地图层使用相同数据区域，数据馈送将包含所有层的数据。 该数据馈送包含一个记录，该记录包含地图层的每个地图成员的标签和值。|  
  
  
##  <a name="DeviceInfo"></a> 设备信息设置  
 您可以更改此呈现器的某些默认设置，包括要使用的编码架构。 有关详细信息，请参阅 [ATOM Device Information Settings](../../reporting-services/atom-device-information-settings.md)。  

## <a name="next-steps"></a>后续步骤

[导出到 CSV 文件](../../reporting-services/report-builder/exporting-to-a-csv-file-report-builder-and-ssrs.md)   
[导出报表](../../reporting-services/report-builder/export-reports-report-builder-and-ssrs.md)  

更多疑问？ [请访问 Reporting Services 论坛](http://go.microsoft.com/fwlink/?LinkId=620231)

namespace backend\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle {

    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/AdminLTE.min.css',
        'css/font-awesome.min.css',
        'css/skins/_all-skins.min.css',
        'css/bootstrap3-wysihtml5.min.css',
        'css/morris.css',
        'css/css.css',
    ];
    public $js = [
        'js/library/jquery-ui.min.js',
        'js/library/morris.min.js',
        'js/library/jquery.slimscroll.min.js',
        'js/library/popup/ejs.js',
        'js/library/popup/tmpl.js',
        'js/library/popup/popup.js',
        'js/library/popup/ajax.js',
        'js/library/fastclick.min.js',
        'js/library/bootstrap.min.js',
        'js/library/bootstrap3-wysihtml5.all.min.js',
        'js/library/base64.js',
        'js/library/textutils.js',
        'js/layout/app.min.js',
        'js/layout/demo.js',
        'js/dev/administrator.js',
        'js/dev/main.js',
        'js/dev/image.js',
        'js/dev/items.js',
        'js/dev/auth.js',
        'js/dev/itemscate.js',
        'js/dev/property.js',
        'js/dev/hotdeal.js',
        'js/dev/search.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];

}
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import datetime as dt

from main_functions import readFile, getData, plotGraph

gpppath = 'all_daily_model_results'
region = 'WI'
site = 'BRW'
start_date = dt.datetime.strptime('2017-01-01', '%Y-%m-%d')   #2017-01-01
end_date = dt.datetime.strptime('2017-12-29', '%Y-%m-%d')   #2017-12-29

doing_GPP = True    #whether or not we're plotting GPP or one of the other variables

mygpp = pd.read_csv("all_daily_model_results.csv", sep=',', skiprows=[1], parse_dates=['year', 'solar_date'], dtype={'GPP':np.float64, 'GPP_lower':np.float64,
                                                                        'GPP_upper':np.float64, 'ER':np.float64, 'ER_lower':np.float64,
                                                                        'ER_upper':np.float64, 'K600':np.float64, 'K600_lower':np.float64,
                                                                        'K600_upper':np.float64}, na_values=['\\N'])
mygpp = mygpp.loc[(mygpp['region']==region) & (mygpp['site']==site)]
mygpp = mygpp.loc[(mygpp['solar_date'] >= start_date) & (mygpp['solar_date'] <= end_date)]
mygpp = mygpp[['solar_date','GPP']]
mygpp.columns = ['DateTime_UTC','value']
READINGS = len(mygpp['value'])      #number of readings of gpp from river! from OC is 687
FRAMESIZE = 1          #how slow we're going through, when one, we go 1frame/0.1sec
#optimal frame for discharge (lightning and pinknoises) is 20 (1frame/2sec)
#for all others, frame=1 is great

path = region + '_' + site + '_' + "sensorData"
variable = "DO_mgL"

myfile = pd.read_csv('csv_files/' + 'Complete_Sensor_Data/' + path + '.csv', sep=',')
myfile['DateTime_UTC'] = pd.to_datetime(myfile['DateTime_UTC'], format='%Y-%m-%d %H:%M:%S')
myfile['value'] = pd.to_numeric(myfile['value'])
myfile = myfile.loc[(myfile['DateTime_UTC'] >= start_date) & (myfile['DateTime_UTC'] <= end_date)]
myfile = myfile.loc[myfile['variable'] == variable]
myfile = myfile[['DateTime_UTC','value']]

myvalues = pd.DataFrame()
skipby = 1

if(doing_GPP):
    myvalues = mygpp
    variable = 'GPP'
    skipby = 1
else:
    myvalues = myfile
    skipby = myvalues.size / READINGS * FRAMESIZE


title = region + ', ' + site + ', ' + variable
y = np.array(myvalues['value'])
x = np.array(myvalues['DateTime_UTC'])
varplot = pd.DataFrame(y,x)

Writer = animation.writers['ffmpeg']
writer = Writer(fps=10, metadata=dict(artist='Me'), bitrate=1800)

fig = plt.figure(figsize=(10,6))
plt.title(title)
plt.plot_date(x,y)
plt.xlabel(variable)
plt.ylabel('Time Stamp')
plt.title(variable + ' over time', fontsize=22)

#plt.clf()

#def init():
#    scat.set_offsets([])
#    return scat

def animate(i):
    data = myvalues.iloc[:int((i+1) * skipby)] #select data range
    p = sns.lineplot(x=data['DateTime_UTC'], y=data['value'], data=data, color="r")
    p.tick_params(labelsize=17)
    plt.setp(p.lines,linewidth=7)

#def animate(i):
#    data = np.hstack((x[:i,np.newaxis], y[:i, np.newaxis]))
#    scat.set_offsets(data)
#    return scat

#init_func=init,
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=int(READINGS/FRAMESIZE),
                               interval=100, blit=False, repeat=True)

ani.save('mp4_files/' + region + '_' + site + '_' + variable + '_animation.mp4', writer=writer)

# ἐπίνοια -ας, ἡ

<!-- Status: S2=NeedsEdits -->
<!-- Lexica used for edits:   -->

## Word data

* Strongs: G19630

* Alternate spellings:



* Principle Parts: 


* Part of speech: 


* Instances in Scripture: 1

* All Scriptures cited: Yes

## Etymology: 

[ἐπινοέω](), to contrive

* LXX/Hebrew glosses: 


* Time Period/Ancient Authors: 


* Related words: 

* Antonyms for all senses

* Synonyms for all senses: 


## Senses 


### Sense  1.0: 

#### Definition: 

#### Glosses: 

a thought, design; 

#### Explanation: 


#### Citations: 

a thought, design: [Ac 8:22](Act 8:22).†

#include <debug.h>
#include <arch.h>
#include <arch/ops.h>
#include <arch/arm64.h>
#include <arch/arm64/mmu.h>
#include <platform.h>

void arch_early_init(void)
{
    /* set the vector base */
    ARM64_WRITE_SYSREG(VBAR_EL1, (uint64_t)&arm64_exception_base);

    /* switch to EL1 */
    unsigned int current_el = ARM64_READ_SYSREG(CURRENTEL) >> 2;
    if (current_el > 1) {
        arm64_el3_to_el1();
    }

    platform_init_mmu_mappings();
}

void arch_init(void)
{
}

void arch_quiesce(void)
{
}

void arch_idle(void)
{
    __asm__ volatile("wfi");
}

void arch_chain_load(void *entry, ulong arg0, ulong arg1, ulong arg2, ulong arg3)
{
    PANIC_UNIMPLEMENTED;
}
<!DOCTYPE HTML>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>

<html lang="en" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#"><head>

	<!-- common -->
	<title>Heatbud | Social Blogging for Bloggers and Businesses</title>
	<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
	<link rel="alternate" type="application/rss+xml" href="https://www.heatbud.com/do/rss" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />

	<!-- icons -->
	<link rel="shortcut icon" href="/resources/images/favicon.ico" type="image/x-icon"/>
    <link rel="apple-touch-icon" href="/resources/images/apple-touch-icon.png"/>
	<link rel="apple-touch-icon" sizes="152x152" href="/resources/images/apple-touch-icon-152x152.png"/>
	<link rel="apple-touch-icon" sizes="144x144" href="/resources/images/apple-touch-icon-144x144.png"/>
	<link rel="apple-touch-icon" sizes="120x120" href="/resources/images/apple-touch-icon-120x120.png"/>
	<link rel="apple-touch-icon" sizes="114x114" href="/resources/images/apple-touch-icon-114x114.png"/>
	<link rel="apple-touch-icon" sizes="76x76" href="/resources/images/apple-touch-icon-76x76.png"/>
	<link rel="apple-touch-icon" sizes="72x72" href="/resources/images/apple-touch-icon-72x72.png"/>
	<link rel="apple-touch-icon" sizes="57x57" href="/resources/images/apple-touch-icon-57x57.png"/>
    <link rel="apple-touch-icon-precomposed" href="/resources/images/apple-touch-icon-76x76.png">
    <link rel="icon" sizes="32x32" href="/resources/images/favicon.ico">
    <meta name="msapplication-TileColor" content="#d3ede7">
	<meta name="msapplication-TileImage" content="/resources/images/apple-touch-icon-114x114.png">

	<!-- for Open Graph (facebook) -->
	<meta property="og:type" content="website"/>
	<meta property="og:title" content="Heatbud | Social Blogging for Businesses"/>
    <meta property="og:description" content="Create Social Blog for your business starting $29 a month. OR, Add Social Blogging to your Business starting $29 a month!"/>
	<meta property="og:url" content="https://www.heatbud.com/top/posts-trending-now"/>
	<meta property="og:image" content="https://www.heatbud.com/resources/images/fb-share-picture.png"/>
	<meta property="og:site_name" content="Heatbud"/>
	<meta property="fb:app_id" content="1444142922465514"/>

	<!-- for Google -->
    <meta name="description" content="Heatbud helps you write sophisticated posts and share them with the world instantly."/>
    <meta name="keywords" content="Social Blogging, Blogging, Business Website, Business, Website, Business Traffic, Traffic"/>
	<meta name="application-name" content="Heatbud"/>
	<link rel="publisher" href="https://plus.google.com/+Heatbud"/>
	<link rel="canonical" href="https://www.heatbud.com/top/posts-trending-now"/>

	<!-- JS includes -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<script src="/resources/js/heatbud-top-charts-min.js?20180530"></script>

    <!-- CSS includes -->
	<link type='text/css' rel='stylesheet' href="https://fonts.googleapis.com/css?family=Arvo%7CDroid+Sans+Mono%7CFauna+One%7CImprima%7CLato%7CMarvel%7COffside%7COpen+Sans%7COxygen+Mono%7CPermanent+Marker%7CRaleway%7CRoboto+Mono%7CScope+One%7CText+Me+One%7CUbuntu">
	<link type="text/css" href="/resources/css/main-min.css?20180530" media="screen" rel="stylesheet"/>

</head><body style="position:relative; background-color:rgb(248, 250, 252)">

	<%-- Begin pretty number --%>
	<script>
	function prettyNumber(n) {
		if ( n < 1000 ) {
			return n;
		} else if ( n >= 1000 && n < 1000000 ) {
			return Math.round(n*10/1000)/10+'k';
		} else {
			return Math.round(n*10/1000000)/10+'m';
		}
	}
	</script>
	<%-- End pretty number --%>

	<%-- Begin header --%>
	<table class="header"><tr style="width:100%">
		<td style="float:left">
			<a href="/"><img alt="Heatbud logo" style="width:140px; padding-top:2px; margin-left:20px; border:none" src="/resources/images/heatbud-logo.png"/></a>
		</td>
		<td style="float:right; font-size:13px; padding-top:14px; padding-bottom:6px">
			<div style="float:left; margin-right:8px"><a href="/top/posts-trending-now" class="mainSelection">TOP CHARTS</a></div>
			<div style="float:left; margin-right:8px"><a href="/post/singing-bowls-singing-bowls-and-chakras" class="mainSelection">BLOG POSTS</a></div>
			<div style="float:left; margin-right:8px"><a href="/do/search" class="mainSelection">SEARCH</a></div>
			<div style="float:left; margin-right:8px"><a href="/do/help" class="mainSelection">HELP CENTER</a></div>
			<sec:authorize access="!isAuthenticated()">
				<div style="float:left"><a href="/do/login" class="mainSelection">LOGIN / SIGNUP</a></div>
			</sec:authorize>
			<sec:authorize access="isAuthenticated()">
				<div style="float:left; font-size:16px">
					<ul id="nav" style="margin-top:0px; margin-bottom:0px">
						<li>
							<span style="color:#ffffff; letter-spacing:1.5px"><sec:authentication property="principal.firstName"/> <sec:authentication property="principal.lastName"/> <img src="/resources/images/menu_header.png" style="padding-left:5px; height:15px"></span>
							<ul>
								<li><a href="/<sec:authentication property="principal.userId"/>" style="margin-top:10px; padding-top:10px">Profile</a></li>
								<li><a href="/user/settings" style="padding-top:10px">Settings</a></li>
								<li><a href="/user/notifications" style="padding-top:10px">Notifications</a></li>
								<li><a href="/user/pages" style="padding-top:10px">Page Manager</a></li>
								<li><a href="/user/orders" style="padding-top:10px">Orders</a></li>
								<li><a href="/user/images" style="padding-top:10px">Images</a></li>
								<li><a href="/user/posts" style="padding-top:10px">Unpublished Posts</a></li>
								<li><a href="<c:url value="/do/logout"/>" style="padding-top:10px">Logout</a></li>
								<li><a href="/user/drop" style="padding-top:10px; padding-bottom:30px">Drop Account</a></li>
							</ul>
						</li>
					</ul>
				</div>
			</sec:authorize>
		</td>
	</tr></table>
	<div style="clear:both"></div>
	<%-- End header --%>

	<%-- Begin page content --%>
	<input id=topChartsNameHidden type=hidden value="${topChartsName}">
	<input id=generateTopChartsJobPeriodHidden type=hidden value="${generateTopChartsJobPeriod}">

	<table style="border-spacing:2px; width:96%; padding-top:60px; margin-left:4%">

	<tr><td colspan="2">
		<%-- Social Blogging revolution --%>
		<div style="width:70%; background-color:#87bdd8; border-radius:4px; padding:10px 30px; margin:0 auto">
			<div style="color:yellow; font-size:1.8em">Join the Social Blogging revolution!</div>
			<div style="width:38%; float:left; color:white; font-size:1.6em">
				<div>For Bloggers</div>
				<div style="font-size:0.7em"><a style="color:white" href="/do/help/main/pricing">&bull; I want to earn followers</a></div>
				<div style="font-size:0.7em"><a style="color:white" href="/do/help/main/pricing">&bull; I want to earn money</a></div>
			</div>
			<div style="width:60%; float:left; color:white; font-size:1.6em">
				<div>For Businesses</div>
				<div style="font-size:0.7em"><a style="color:white" href="/do/help/main/why-1">&bull; I want to create a new website</a></div>
				<div style="font-size:0.7em"><a style="color:white" href="/do/help/main/why-1">&bull; I want to add Social Blog to my existing website</a></div>
			</div>
			<div style="clear:both"></div>
		</div>
	</td></tr>

	<tr><td style="width:65%; vertical-align:top">

		<%-- Page Title --%>
		<div style="float:right">
			<ul id="nav" style="z-index:3">
				<li>
					<div style="font-family:Calibri, Arial, Sans-serif; font-weight:bold; font-size:1.5em; background-color:#FD8A33; color:white; letter-spacing:3px; padding:3px 13px 7px 20px; border-radius:5px">
						<span>${pageTitle}</span>
						<span><img alt="top charts menu" src="/resources/images/menu.png" style="padding-left:8px; height:24px"></span>
					</div>
					<ul style="width:160px">
						<li style="padding-top:6px; padding-left:6px; font-weight:bold; color:#333333; margin-top:15px">TRENDING NOW</li>
						<li><div onclick="switchChart('posts-trending-now')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">POSTS</div></li>
						<li><div onclick="switchChart('zones-trending-now')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">ZONES</div></li>
						<li><div onclick="switchChart('bloggers-trending-now')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">BLOGGERS</div></li>
						<li><div onclick="switchChart('pages-trending-now')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">PAGES</div></li>
						<li style="padding-top:6px; padding-left:6px; font-weight:bold; color:#333333; margin-top:6px">ALL TIME</li>
						<li><div onclick="switchChart('posts-all-time')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">POSTS</div></li>
						<li><div onclick="switchChart('bloggers-all-time')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">BLOGGERS</div></li>
						<li><div onclick="switchChart('pages-all-time')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">PAGES</div></li>
						<li style="padding-top:6px; padding-left:6px; font-weight:bold; color:#333333; margin-top:6px">JUST PUBLISHED</li>
						<li><div onclick="switchChart('posts-just-published')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; margin-bottom:40px; cursor:pointer">POSTS</div></li>
					</ul>
				</li>
			</ul>
		</div>
		<div style="clear:both"></div>
	</td><td style="width:28%; vertical-align:top"></td></tr>

	<tr>
		<td style="width:65%; vertical-align:top; padding-right:11px">

			<div id="topChartsDiv">

				<%-- Top Charts for Posts --%>
				<c:if test="${fn:contains(topChartsName,'post')}">
					<c:forEach var="post" items="${topChartsList}" varStatus="loopStatus">
						<div class="topChartsElement" style="float:right">
							<div style="font-size:18px; font-weight:bold; padding:10px 20px">
								<a href="/post/${post.postId}">${post.postTitle}</a>
							</div>
							<div onclick="location.href='/post/${post.postId}'" class="topChartsThumb grow" style="margin:0 auto; background-image:url(${post.postHeadshot})"></div>
							<div style="font-size:15px; padding:10px 20px">
								<span style="font-size:13px; color:rgb(144, 144, 144)"> By </span>
								<span><a href="/${post.bloggerId}">${post.bloggerName}</a></span>
								<span style="font-size:13px; color:rgb(144, 144, 144)"> Zone </span>
								<span><a href="/zone/${post.zoneId}">${fn:escapeXml(post.zoneName)}</a></span>
							</div>
							<c:if test="${fn:contains(topChartsName,'just')}">
								<div style="padding:3px 20px; color:#8A8C8E"><script>document.write(new Date(${post.updateDate}).toLocaleString());</script></div>
							</c:if>
							<div style="padding:3px 20px">${post.postSummary}</div>
							<div style="padding:5px 20px">
								<img alt="Overall Heat Index" title="Overall Heat Index" style="width:14px; height:18px; border:none" src="/resources/images/favicon.ico"/>
								<span title="Overall Heat Index" style="color:#7A7C7E; font-size:17px"><script>document.write(prettyNumber(${post.hi}));</script></span>
								<c:if test="${fn:contains(topChartsName,'trending')}">
									<c:if test="${post.hiTrending >= 0}">
										<span><img alt="This week's change" title="This week's change" style="width:8px; height:8px; border:none; margin-left:10px" src="/resources/images/trending-up.png"></span>
										<span title="This week's change" style="color:#8A8C8E; font-size:10px">${post.hiTrending}</span>
									</c:if>
									<c:if test="${post.hiTrending < 0}">
										<span><img alt="This week's change" title="This week's change" style="width:8px; height:8px; border:none; margin-left:10px" src="/resources/images/trending-down.png"></span>
										<span title="This week's change" style="color:#8A8C8E; font-size:10px">${-post.hiTrending}</span>
									</c:if>
								</c:if>
							</div>
						</div>
						<c:if test="${loopStatus.index % 2 == 1}">
							<div style="clear:both"></div>
						</c:if>
					</c:forEach>
				</c:if>

				<%-- Top Charts for Zones --%>
				<c:if test="${fn:contains(topChartsName,'zone')}">
					<c:forEach var="zone" items="${topChartsList}" varStatus="loopStatus">
						<div class="topChartsElement" style="float:right">
							<div style="font-size:18px; font-weight:bold; padding:10px 20px">
								<a href="/zone/${zone.zoneId}">${zone.zoneName}</a>
							</div>
							<div onclick="location.href='/zone/${zone.zoneId}'" class="topChartsThumb grow" style="margin:0 auto; background-image:url(${zone.zoneHeadshot})"></div>
							<div style="padding:3px 20px">${zone.zoneDesc}</div>
							<div style="font-size:12px; color:#909090; padding:5px 20px">
								<span>${zone.posts} posts</span>
								<span style="font-weight:bold; color:rgb(144, 144, 144)">&nbsp;.&nbsp;</span>
								<span>${zone.comments} comments</span>
							</div>
						</div>
						<c:if test="${loopStatus.index % 2 == 1}">
							<div style="clear:both"></div>
						</c:if>
					</c:forEach>
				</c:if>

				<%-- Top Charts for entities (bloggers and pages) --%>
				<c:if test="${fn:contains(topChartsName,'blogger') || fn:contains(topChartsName,'page')}">
					<c:forEach var="entity" items="${topChartsList}"  varStatus="loopStatus">
						<div class="topChartsElement" style="float:right">
							<div style="font-size:18px; padding:10px 20px; font-weight:bold">
								<a href="/${entity.entityId}">${entity.entityName}</a>
							</div>
							<c:if test="${empty entity.profilePhoto}">
								<c:if test="${fn:contains(topChartsName,'blogger')}">
									<div onclick="location.href='/${entity.entityId}'" class="topChartsThumb grow" style="margin:0 auto; background-image:url('/resources/images/def-blogger-photo.jpg')"></div>
								</c:if>
								<c:if test="${fn:contains(topChartsName,'page')}">
									<div onclick="location.href='/${entity.entityId}'" class="topChartsThumb grow" style="margin:0 auto; background-image:url('/resources/images/def-page-photo.jpg')"></div>
								</c:if>
							</c:if>
							<c:if test="${not empty entity.profilePhoto}">
								<div onclick="location.href='/${entity.entityId}'" class="topChartsThumb grow" style="margin:0 auto; background-image:url('${entity.profilePhoto}')"></div>
							</c:if>
							<div style="padding:3px 20px; white-space:pre-line">${entity.about}</div>
							<div style="padding:3px 20px">
								<img alt="Overall Heat Index" title="Overall Heat Index" style="width:14px; height:18px; border:none" src="/resources/images/favicon.ico"/>
								<span title="Overall Heat Index" style="color:#7A7C7E; font-size:17px"><script>document.write(prettyNumber(${entity.hi}));</script></span>
								<c:if test="${fn:contains(topChartsName,'trending')}">
									<c:if test="${entity.hiTrending >= 0}">
										<span><img alt="This week's change" title="This week's change" style="width:8px; height:8px; border:none; margin-left:10px" src="/resources/images/trending-up.png"></span>
										<span title="This week's change" style="color:#8A8C8E; font-size:10px">${entity.hiTrending}</span>
									</c:if>
									<c:if test="${entity.hiTrending < 0}">
										<span><img alt="This week's change" title="This week's change" style="width:8px; height:8px; border:none; margin-left:10px" src="/resources/images/trending-down.png"></span>
										<span title="This week's change" style="color:#8A8C8E; font-size:10px">${-entity.hiTrending}</span>
									</c:if>
								</c:if>
							</div>
							<div style="font-size:12px; color:#909090; padding:5px 20px">
								<span>${entity.posts} posts</span>
								<span style="font-weight:bold; color:rgb(144, 144, 144)">&nbsp;.&nbsp;</span>
								<span>${entity.votes} votes</span>
								<span style="font-weight:bold; color:rgb(144, 144, 144)">&nbsp;.&nbsp;</span>
								<span>${entity.comments} comments</span>
							</div>
						</div>
						<c:if test="${loopStatus.index % 2 == 1}">
							<div style="clear:both"></div>
						</c:if>
					</c:forEach>
				</c:if>
			</div>

			<%-- Top Charts navigation --%>
			<div id="topChartsNavigation">
				<%-- previous page link will be hidden on the first page --%>
				<input type=hidden id=topChartsKeyPrevIdHidden value="NULL">
				<input type=hidden id=topChartsKeyPrevHIHidden value="NULL">
				<div id="getTopChartsPreviousDiv" style="width:45%; margin-top:10px; margin-left:15px; float:left; text-align:left; visibility:hidden">
					<a id="getTopChartsPrevious" class="topNextPrev" href="javascript:">BACK</a>
				</div>
				<%-- next page link will be set to visible if the key is not NULL --%>
				<input type=hidden id=topChartsKeyNextIdHidden value="${topChartsKeyNextId}">
				<input type=hidden id=topChartsKeyNextHIHidden value="${topChartsKeyNextHI}">
				<c:if test="${topChartsKeyNextId != 'NULL'}">
					<div id="getTopChartsNextDiv" style="width:45%; margin-top:10px; margin-right:56px; float:right; text-align:right">
						<a id="getTopChartsNext" class="topNextPrev" href="javascript:">MORE</a>
					</div>
				</c:if>
			</div>
			<div style="clear:both"></div>

		</td>
		<td style="width:28%; vertical-align:top">
			<%-- Facebook --%>
			<div class="friendFacebook" style="float:right">
				<a style="color:white" target="_blank" href="https://www.facebook.com/heatbud">Like us on Facebook</a>
			</div>
			<div style="clear:both"></div>
			<%-- Ticker --%>
			<div style="margin-top:10px; margin-bottom:5px; color:#797979; font-size:15px">Recent activity</div>
			<div style="border:1px solid #d1d1d1; padding:20px 10px 30px 20px; background-color:white">
				<c:forEach var="ticker" items="${tickersList}" varStatus="counter">
					<div style="margin-bottom:25px">
						<span style="color:#8A8C8E">&#9898;</span>
						<span style="color:#8A8C8E"><script>document.write(new Date(${ticker.tickerTime}).toLocaleString());</script></span><br/>
						<span>${ticker.tickerDesc}</span>
					</div>
				</c:forEach>
			</div>
		</td>

	</tr></table>

	<%-- Google Ads Horizontal --%>
	<div style="width:100%; text-align:center; margin-top:30px; margin-bottom:40px">
		<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
		<ins class="adsbygoogle"
		     style="display:inline-block;width:728px;height:90px"
		     data-ad-client="ca-pub-3344897177583439"
		     data-ad-slot="5851386905">
		</ins>
		<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
	</div>

	<%-- Begin footer --%>
	<div class="footer">
		<div style="float: right; margin-right: 40px">
			<a href="/top/posts-trending-now">Home</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/help">Help Center</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/privacy">Privacy &amp; Terms</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/partnerships">Partnerships</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/careers">Careers</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/contact">Contact Us</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/newsletters">Newsletters</a>
		</div>
	</div>
	<%-- End footer --%>

	<!-- Google analytics -->
	<script>
	  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
	  ga('create', 'UA-48436913-1', 'heatbud.com');
	  ga('send', 'pageview');
	</script>

</body></html>
#include <time.h>

typedef int (*timer_gettime_test)(timer_t, struct itimerspec *);

int dummyfcn (void)
{
	timer_gettime_test dummyvar;
	dummyvar = timer_gettime;
	return 0;
}
﻿' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.InvertIf
    <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InvertMultiLineIf), [Shared]>
    Friend NotInheritable Class VisualBasicInvertMultiLineIfCodeRefactoringProvider
        Inherits VisualBasicInvertIfCodeRefactoringProvider(Of MultiLineIfBlockSyntax)

        <ImportingConstructor>
        <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
        Public Sub New()
        End Sub

        Protected Overrides Function IsElseless(ifNode As MultiLineIfBlockSyntax) As Boolean
            Return ifNode.ElseBlock Is Nothing
        End Function

        Protected Overrides Function CanInvert(ifNode As MultiLineIfBlockSyntax) As Boolean
            Return ifNode.ElseIfBlocks.IsEmpty
        End Function

        Protected Overrides Function GetCondition(ifNode As MultiLineIfBlockSyntax) As SyntaxNode
            Return ifNode.IfStatement.Condition
        End Function

        Protected Overrides Function GetIfBody(ifNode As MultiLineIfBlockSyntax) As SyntaxList(Of StatementSyntax)
            Return ifNode.Statements
        End Function

        Protected Overrides Function GetElseBody(ifNode As MultiLineIfBlockSyntax) As SyntaxList(Of StatementSyntax)
            Return ifNode.ElseBlock.Statements
        End Function

        Protected Overrides Function UpdateIf(
                sourceText As SourceText,
                ifNode As MultiLineIfBlockSyntax,
                condition As SyntaxNode,
                trueStatement As SyntaxList(Of StatementSyntax),
                Optional falseStatementOpt As SyntaxList(Of StatementSyntax) = Nothing) As MultiLineIfBlockSyntax

            Dim updatedIf = ifNode _
                .WithIfStatement(ifNode.IfStatement.WithCondition(DirectCast(condition, ExpressionSyntax))) _
                .WithStatements(trueStatement)

            If falseStatementOpt.Count > 0 Then
                updatedIf = updatedIf.WithElseBlock(SyntaxFactory.ElseBlock(falseStatementOpt))
            End If

            Return updatedIf
        End Function
    End Class
End Namespace


;;; orary-rust.el --- Rust support for Orary
;;
;;; Commentary:
;; Maybe rust is nice? I'm unlikely to be able to tell if my editor isn't set up for it ;P
;;; Code:

(require 'orary-braces)
(require 'orary-functions)

(use-package cargo)         ;; Build tool wrapper
(use-package racer)         ;; Symbol completion, introspection
(use-package flycheck-rust) ;; Syntax checking

(defun orary/rust-ret-dwim (arg)
  (interactive "P")

  (cond
   ;; We're in a pair of {}, open them
   ((and (looking-at "}")
         (looking-back "{" (- (point) 2)))
    (orary/braces-open-pair))

   ;; We're opening a match; insert {}, open, then expand a yasnippet
   ((looking-back "match.*" (line-beginning-position))
    (sp-insert-pair "{")
    (orary/braces-open-pair)
    ;; NOTE[rdonaldson|2020-05-31] with LSP mode, it's often more ergonomic to
    ;; use an lsp action to fill in match arms. Reconsidering this; might gate
    ;; it behind C-u.
    ;; (yas-expand-snippet "$1 => $0,")
    )

   ;; We're defining an if/else, while, function, struct, enum, unsafe, or trait; insert {}, then open
   ((looking-back "if.*\\|else.*\\|while.*\\|fn .*\\|\\<impl\\>.*\\|trait.*\\|struct.*\\|enum.*\\|mod.*\\|for.*\\|unsafe.*\\|async.*" (line-beginning-position))
    (sp-insert-pair "{")
    (orary/braces-open-pair))

   ;; We're in a match expression
   ((looking-back "=>.*" (line-beginning-position))
    (end-of-line)
    ;; With a prefix arg, jump out of the match
    (if arg
        (progn
          (re-search-forward "}")
          (newline-and-indent))
      (progn
        (unless (looking-back "," (- (point) 1))
          (insert-char ?,))
        (newline-and-indent)
        (yas-expand-snippet "$1 => $0,"))))

   ;; Default: try to add a ; and newline
   (t
    (unless (eolp)
      (re-search-forward ")"))

    (unless (or (looking-at ";")
                (looking-back ";" (- (point) 1))
                (looking-back "^\\s-+" (line-beginning-position)))
      (insert-char ?\;))
    (end-of-line)
    (newline-and-indent))))

(defun orary/rust-insert-arrow ()
  (interactive)
  (orary/insert-key-seq "-" ">" "<")
  (set-transient-map
   (let ((map (make-sparse-keymap)))
     (define-key map (kbd "-") #'orary/rust-insert-arrow)
     map)))

;; The Business
(use-package rust-mode
  :config
  (setq cargo-process--command-clippy "clippy")
  (add-hook 'rust-mode-hook
            (lambda ()
              (cargo-minor-mode +1)
              (subword-mode +1)
              (lsp)
              (flycheck-add-next-checker 'lsp 'rust-clippy)
              (setq comment-start "//")))

  (add-hook 'racer-mode-hook #'eldoc-mode)
  (add-hook 'racer-mode-hook #'company-mode)

  :bind (:map rust-mode-map
              ("C-c C-c" . #'rust-compile)
              ("<C-return>" . #'orary/rust-ret-dwim)
              ("C-o" . #'orary/braces-open-newline)
              ("-" . #'orary/rust-insert-arrow))
  )

(provide 'orary-rust)
;;; orary-rust.el ends here

<?php

namespace Tg\OkoaBundle\Response;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use RuntimeException;

/**
 * Respond with the contents of a file.
 */
class FileResponse extends Response
{

    protected $disposition;

    protected $filename;

    protected $file;

    public function __construct($file, $attach = false, $filename = null)
    {
        parent::__construct(null, 200, [
            'Content-Type' => 'application/octet-stream'
        ]);
        if ($attach) {
            $this->setDispositionAttachment();
        } else {
            $this->setDispositionInline();
        }
        $this->setFile($file);
        $this->setFilename($filename);
        $this->setPrivate();
    }

    public function setContentType($type)
    {
        $this->headers->set('Content-Type', $type);
    }

    public function setDispositionAttachment()
    {
        $this->disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT;
        $this->updateProps();
    }

    public function setDispositionInline()
    {
        $this->disposition = ResponseHeaderBag::DISPOSITION_INLINE;
        $this->updateProps();
    }

    public function setFilename($name)
    {
        $this->filename = $name;
        $this->updateProps();
    }

    public function getFilesize()
    {
        if (is_string($this->file)) {
            return filesize($this->file);
        } else {
            fseek($this->file, 0, SEEK_END);
            $size = ftell($this->file);
            rewind($this->file);
            return $size;
        }
    }

    public function setFile($file, $determineType = true)
    {
        if (is_string($file)) {
            if (!file_exists($file) || !is_readable($file)) {
                throw new RuntimeException("Could not read file '$file'");
            }
        }
        $this->file = $file;
        if (is_string($file) && $determineType) {
            $this->tryDetermineType();
        }
        $this->updateProps();
    }

    public function tryDetermineType()
    {
        if (is_string($this->file) && strlen($this->file) > 0) {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $this->file);
            if (is_string($mime) && strlen($mime) > 0) {
                $this->setContentType($mime);
            }
            finfo_close($finfo);
        }
    }

    public function sendContent()
    {
        if (is_resource($this->file)) {
            $size = $this->getFilesize();
            rewind($this->file);
            print fread($this->file, $size);
        } else {
            readfile($this->file);
        }
    }

    protected function updateProps()
    {
        if (is_string($this->file) || is_resource($this->file)) {
            $disp = $this->disposition;
            if ($disp !== ResponseHeaderBag::DISPOSITION_INLINE && $this->filename !== null) {
                $disp .= '; filename=' . $this->filename;
            }
            $this->headers->set('Content-Disposition', $disp);
            $this->headers->set('Content-Length', $this->getFilesize());
        } else {
            $this->headers->remove('Content-Disposition');
            $this->headers->remove('Content-Length');
        }
    }
}

#include "includes.h"
#include "lib/util/dlinklist.h"
#include "smb_server/smb_server.h"
#include "smbd/service_stream.h"
#include "ntvfs/ntvfs.h"

struct socket_address *smbsrv_get_my_addr(void *p, TALLOC_CTX *mem_ctx)
{
	struct smbsrv_connection *smb_conn = talloc_get_type(p,
					     struct smbsrv_connection);

	return socket_get_my_addr(smb_conn->connection->socket, mem_ctx);
}

struct socket_address *smbsrv_get_peer_addr(void *p, TALLOC_CTX *mem_ctx)
{
	struct smbsrv_connection *smb_conn = talloc_get_type(p,
					     struct smbsrv_connection);

	return socket_get_peer_addr(smb_conn->connection->socket, mem_ctx);
}

/****************************************************************************
init the tcon structures
****************************************************************************/
static NTSTATUS smbsrv_init_tcons(struct smbsrv_tcons_context *tcons_ctx, TALLOC_CTX *mem_ctx, uint32_t limit)
{
	/* 
	 * the idr_* functions take 'int' as limit,
	 * and only work with a max limit 0x00FFFFFF
	 */
	limit &= 0x00FFFFFF;

	tcons_ctx->idtree_tid	= idr_init(mem_ctx);
	NT_STATUS_HAVE_NO_MEMORY(tcons_ctx->idtree_tid);
	tcons_ctx->idtree_limit	= limit;
	tcons_ctx->list		= NULL;

	return NT_STATUS_OK;
}

NTSTATUS smbsrv_smb_init_tcons(struct smbsrv_connection *smb_conn)
{
	return smbsrv_init_tcons(&smb_conn->smb_tcons, smb_conn, UINT16_MAX);
}

NTSTATUS smbsrv_smb2_init_tcons(struct smbsrv_session *smb_sess)
{
	return smbsrv_init_tcons(&smb_sess->smb2_tcons, smb_sess, UINT32_MAX);
}

/****************************************************************************
find a tcon given a tid for SMB
****************************************************************************/
static struct smbsrv_tcon *smbsrv_tcon_find(struct smbsrv_tcons_context *tcons_ctx,
					    uint32_t tid, struct timeval request_time)
{
	void *p;
	struct smbsrv_tcon *tcon;

	if (tid == 0) return NULL;

	if (tid > tcons_ctx->idtree_limit) return NULL;

	p = idr_find(tcons_ctx->idtree_tid, tid);
	if (!p) return NULL;

	tcon = talloc_get_type(p, struct smbsrv_tcon);
	if (!tcon) return NULL;

	tcon->statistics.last_request_time = request_time;

	return tcon;
}

struct smbsrv_tcon *smbsrv_smb_tcon_find(struct smbsrv_connection *smb_conn,
					 uint32_t tid, struct timeval request_time)
{
	return smbsrv_tcon_find(&smb_conn->smb_tcons, tid, request_time);
}

struct smbsrv_tcon *smbsrv_smb2_tcon_find(struct smbsrv_session *smb_sess,
					  uint32_t tid, struct timeval request_time)
{
	if (!smb_sess) return NULL;
	return smbsrv_tcon_find(&smb_sess->smb2_tcons, tid, request_time);
}

/*
  destroy a connection structure
*/
static int smbsrv_tcon_destructor(struct smbsrv_tcon *tcon)
{
	struct smbsrv_tcons_context *tcons_ctx;
	struct socket_address *client_addr;

	client_addr = socket_get_peer_addr(tcon->smb_conn->connection->socket, tcon);
	DEBUG(3,("%s closed connection to service %s\n",
		 client_addr ? client_addr->addr : "(unknown)",
		 tcon->share_name));

	/* tell the ntvfs backend that we are disconnecting */
	if (tcon->ntvfs) {
		ntvfs_disconnect(tcon->ntvfs);
		tcon->ntvfs = NULL;
	}

	if (tcon->smb2.session) {
		tcons_ctx = &tcon->smb2.session->smb2_tcons;
	} else {
		tcons_ctx = &tcon->smb_conn->smb_tcons;
	}

	idr_remove(tcons_ctx->idtree_tid, tcon->tid);
	DLIST_REMOVE(tcons_ctx->list, tcon);
	return 0;
}

/*
  find first available connection slot
*/
static struct smbsrv_tcon *smbsrv_tcon_new(struct smbsrv_connection *smb_conn,
					   struct smbsrv_session *smb_sess,
					   const char *share_name)
{
	TALLOC_CTX *mem_ctx;
	struct smbsrv_tcons_context *tcons_ctx;
	uint32_t handle_uint_max;
	struct smbsrv_tcon *tcon;
	NTSTATUS status;
	int i;

	if (smb_sess) {
		mem_ctx = smb_sess;
		tcons_ctx = &smb_sess->smb2_tcons;
		handle_uint_max = UINT32_MAX;
	} else {
		mem_ctx = smb_conn;
		tcons_ctx = &smb_conn->smb_tcons;
		handle_uint_max = UINT16_MAX;
	}

	tcon = talloc_zero(mem_ctx, struct smbsrv_tcon);
	if (!tcon) return NULL;
	tcon->smb_conn		= smb_conn;
	tcon->smb2.session	= smb_sess;
	tcon->share_name	= talloc_strdup(tcon, share_name);
	if (!tcon->share_name) goto failed;

	/*
	 * the use -1 here, because we don't want to give away the wildcard
	 * fnum used in SMBflush
	 */
	status = smbsrv_init_handles(tcon, handle_uint_max - 1);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1,("ERROR! failed to init handles: %s\n", nt_errstr(status)));
		goto failed;
	}

	i = idr_get_new_random(tcons_ctx->idtree_tid, tcon, tcons_ctx->idtree_limit);
	if (i == -1) {
		DEBUG(1,("ERROR! Out of connection structures\n"));
		goto failed;
	}
	tcon->tid = i;

	DLIST_ADD(tcons_ctx->list, tcon);
	talloc_set_destructor(tcon, smbsrv_tcon_destructor);

	/* now fill in some statistics */
	tcon->statistics.connect_time = timeval_current();

	return tcon;

failed:
	talloc_free(tcon);
	return NULL;
}

struct smbsrv_tcon *smbsrv_smb_tcon_new(struct smbsrv_connection *smb_conn, const char *share_name)
{
	return smbsrv_tcon_new(smb_conn, NULL, share_name);
}

struct smbsrv_tcon *smbsrv_smb2_tcon_new(struct smbsrv_session *smb_sess, const char *share_name)
{
	return smbsrv_tcon_new(smb_sess->smb_conn, smb_sess, share_name);
}
package fr.adrienbrault.idea.symfony2plugin.tests.intentions.yaml;

import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyLightCodeInsightFixtureTestCase;
import org.jetbrains.yaml.YAMLFileType;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 *
 * @see fr.adrienbrault.idea.symfony2plugin.intentions.yaml.YamlServiceTagIntention
 */
public class YamlServiceTagIntentionTest extends SymfonyLightCodeInsightFixtureTestCase {

    public void setUp() throws Exception {
        super.setUp();
        myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("classes.php"));
    }

    protected String getTestDataPath() {
        return "src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/intentions/yaml/fixtures";
    }

    public void testTagIntentionIsAvailable() {
        assertIntentionIsAvailable(
            YAMLFileType.YML,
            "services:\n" +
                "    foo:\n" +
                "        class: Foo<caret>\\Bar",
            "Symfony: Add Tags"
        );

        assertIntentionIsAvailable(
            YAMLFileType.YML,
            "services:\n" +
                "    foo:\n" +
                "        arguments: [Foo<caret>\\Bar] ",
            "Symfony: Add Tags"
        );
    }
}

/* istanbul ignore file */
/* istanbul ignore file */
import React from 'react';
import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import { Provider } from 'react-redux';
import { ToastProvider } from 'react-toast-notifications';

import Routes from './routes';
import store from "./store";

import Header from './components/Header';
import Footer from './components/Footer';
import GlobalStyles from './assets/styles/global';

function App () {

  const history = createHistory({
    basename: "",
    forceRefresh: false
  });

  return (
    <Provider store={store}>
      <Router history={history}>
        <GlobalStyles />
        <Header />
        <ToastProvider>
          <Routes />
        </ToastProvider>
        <Footer />
      </Router>
    </Provider>
  );
}

export default App;

package org.ping.apache.sqoop.mapreduce.db.rsync;

import java.sql.Timestamp;

public class TimeUtil {
	public static String getNowStamp() {
		Timestamp now = new Timestamp(System.currentTimeMillis());
		return getStamp(now);
	}

	public static String getStamp(Timestamp timestamp) {
		String stamp = timestamp.toString();
		stamp = stamp.replaceAll("-", "");
		stamp = stamp.replaceAll(":", "");
		stamp = stamp.replaceAll("\\.", "");
		stamp = stamp.replaceAll(" ", "");
		return stamp;
	}
}

import operator

import numpy as np
import numpy.core.umath_tests as ut

from utils.Quaternions import Quaternions


class Animation:
    """
    Animation is a numpy-like wrapper for animation data
    
    Animation data consists of several arrays consisting
    of F frames and J joints.
    
    The animation is specified by
    
        rotations : (F, J) Quaternions | Joint Rotations
        positions : (F, J, 3) ndarray  | Joint Positions
    
    The base pose is specified by
    
        orients   : (J) Quaternions    | Joint Orientations
        offsets   : (J, 3) ndarray     | Joint Offsets
        
    And the skeletal structure is specified by
        
        parents   : (J) ndarray        | Joint Parents
    """
    
    def __init__(self, rotations, positions, orients, offsets, parents):
        
        self.rotations = rotations
        self.positions = positions
        self.orients   = orients
        self.offsets   = offsets
        self.parents   = parents
    
    def __op__(self, op, other):
        return Animation(
            op(self.rotations, other.rotations),
            op(self.positions, other.positions),
            op(self.orients, other.orients),
            op(self.offsets, other.offsets),
            op(self.parents, other.parents))

    def __iop__(self, op, other):
        self.rotations = op(self.roations, other.rotations)
        self.positions = op(self.roations, other.positions)
        self.orients   = op(self.orients, other.orients)
        self.offsets   = op(self.offsets, other.offsets)
        self.parents   = op(self.parents, other.parents)
        return self
    
    def __sop__(self, op):
        return Animation(
            op(self.rotations),
            op(self.positions),
            op(self.orients),
            op(self.offsets),
            op(self.parents))
    
    def __add__(self, other): return self.__op__(operator.add, other)
    def __sub__(self, other): return self.__op__(operator.sub, other)
    def __mul__(self, other): return self.__op__(operator.mul, other)
    def __div__(self, other): return self.__op__(operator.div, other)
    
    def __abs__(self): return self.__sop__(operator.abs)
    def __neg__(self): return self.__sop__(operator.neg)
    
    def __iadd__(self, other): return self.__iop__(operator.iadd, other)
    def __isub__(self, other): return self.__iop__(operator.isub, other)
    def __imul__(self, other): return self.__iop__(operator.imul, other)
    def __idiv__(self, other): return self.__iop__(operator.idiv, other)
    
    def __len__(self): return len(self.rotations)
    
    def __getitem__(self, k):
        if isinstance(k, tuple):
            return Animation(
                self.rotations[k],
                self.positions[k],
                self.orients[k[1:]],
                self.offsets[k[1:]],
                self.parents[k[1:]]) 
        else:
            return Animation(
                self.rotations[k],
                self.positions[k],
                self.orients,
                self.offsets,
                self.parents) 
        
    def __setitem__(self, k, v): 
        if isinstance(k, tuple):
            self.rotations.__setitem__(k, v.rotations)
            self.positions.__setitem__(k, v.positions)
            self.orients.__setitem__(k[1:], v.orients)
            self.offsets.__setitem__(k[1:], v.offsets)
            self.parents.__setitem__(k[1:], v.parents)
        else:
            self.rotations.__setitem__(k, v.rotations)
            self.positions.__setitem__(k, v.positions)
            self.orients.__setitem__(k, v.orients)
            self.offsets.__setitem__(k, v.offsets)
            self.parents.__setitem__(k, v.parents)
        
    @property
    def shape(self): return (self.rotations.shape[0], self.rotations.shape[1])
            
    def copy(self): return Animation(
        self.rotations.copy(), self.positions.copy(), 
        self.orients.copy(), self.offsets.copy(), 
        self.parents.copy())
    
    def repeat(self, *args, **kw):
        return Animation(
            self.rotations.repeat(*args, **kw),
            self.positions.repeat(*args, **kw),
            self.orients, self.offsets, self.parents)
        
    def ravel(self):
        return np.hstack([
            self.rotations.log().ravel(),
            self.positions.ravel(),
            self.orients.log().ravel(),
            self.offsets.ravel()])
        
    @classmethod
    def unravel(clas, anim, shape, parents):
        nf, nj = shape
        rotations = anim[nf*nj*0:nf*nj*3]
        positions = anim[nf*nj*3:nf*nj*6]
        orients   = anim[nf*nj*6+nj*0:nf*nj*6+nj*3]
        offsets   = anim[nf*nj*6+nj*3:nf*nj*6+nj*6]
        return cls(
            Quaternions.exp(rotations), positions,
            Quaternions.exp(orients), offsets,
            parents.copy())
    
    
""" Maya Interaction """

def load_to_maya(anim, names=None, radius=0.5):
    """
    Load Animation Object into Maya as Joint Skeleton
    loads each frame as a new keyfame in maya.
    
    If the animation is too slow or too fast perhaps
    the framerate needs adjusting before being loaded
    such that it matches the maya scene framerate.
    
    
    Parameters
    ----------
    
    anim : Animation
        Animation to load into Scene
        
    names : [str]
        Optional list of Joint names for Skeleton
    
    Returns
    -------
    
    List of Maya Joint Nodes loaded into scene
    """
    
    import pymel.core as pm
    
    joints = []
    frames = range(1, len(anim)+1)
    
    if names is None: names = ["joint_" + str(i) for i in range(len(anim.parents))]
    
    for i, offset, orient, parent, name in zip(range(len(anim.offsets)), anim.offsets, anim.orients, anim.parents, names):
    
        if parent < 0:
            pm.select(d=True)
        else:
            pm.select(joints[parent])
        
        joint = pm.joint(n=name, p=offset, relative=True, radius=radius)
        joint.setOrientation([orient[1], orient[2], orient[3], orient[0]])
        
        curvex = pm.nodetypes.AnimCurveTA(n=name + "_rotateX")
        curvey = pm.nodetypes.AnimCurveTA(n=name + "_rotateY")
        curvez = pm.nodetypes.AnimCurveTA(n=name + "_rotateZ")  
        
        jrotations = (-Quaternions(orient[np.newaxis]) * anim.rotations[:,i]).euler()
        curvex.addKeys(frames, jrotations[:,0])
        curvey.addKeys(frames, jrotations[:,1])
        curvez.addKeys(frames, jrotations[:,2])
        
        pm.connectAttr(curvex.output, joint.rotateX)
        pm.connectAttr(curvey.output, joint.rotateY)
        pm.connectAttr(curvez.output, joint.rotateZ)
        
        offsetx = pm.nodetypes.AnimCurveTU(n=name + "_translateX")
        offsety = pm.nodetypes.AnimCurveTU(n=name + "_translateY")
        offsetz = pm.nodetypes.AnimCurveTU(n=name + "_translateZ")
        
        offsetx.addKeys(frames, anim.positions[:,i,0])
        offsety.addKeys(frames, anim.positions[:,i,1])
        offsetz.addKeys(frames, anim.positions[:,i,2])
        
        pm.connectAttr(offsetx.output, joint.translateX)
        pm.connectAttr(offsety.output, joint.translateY)
        pm.connectAttr(offsetz.output, joint.translateZ)
        
        joints.append(joint)
    
    return joints
    
def transforms_local(anim):
    """
    Computes Animation Local Transforms
    
    As well as a number of other uses this can
    be used to compute global joint transforms,
    which in turn can be used to compete global
    joint positions
    
    Parameters
    ----------
    
    anim : Animation
        Input animation
        
    Returns
    -------
    
    transforms : (F, J, 4, 4) ndarray
    
        For each frame F, joint local
        transforms for each joint J
    """
    
    transforms = anim.rotations.transforms()
    transforms = np.concatenate([transforms, np.zeros(transforms.shape[:2] + (3, 1))], axis=-1)
    transforms = np.concatenate([transforms, np.zeros(transforms.shape[:2] + (1, 4))], axis=-2)
    transforms[:,:,0:3,3] = anim.positions
    transforms[:,:,3:4,3] = 1.0
    return transforms

    
def transforms_multiply(t0s, t1s):
    """
    Transforms Multiply
    
    Multiplies two arrays of animation transforms
    
    Parameters
    ----------
    
    t0s, t1s : (F, J, 4, 4) ndarray
        Two arrays of transforms
        for each frame F and each
        joint J
        
    Returns
    -------
    
    transforms : (F, J, 4, 4) ndarray
        Array of transforms for each
        frame F and joint J multiplied
        together
    """
    
    return ut.matrix_multiply(t0s, t1s)
    
def transforms_inv(ts):
    fts = ts.reshape(-1, 4, 4)
    fts = np.array(list(map(lambda x: np.linalg.inv(x), fts)))
    return fts.reshape(ts.shape)
    
def transforms_blank(anim):
    """
    Blank Transforms
    
    Parameters
    ----------
    
    anim : Animation
        Input animation
    
    Returns
    -------
    
    transforms : (F, J, 4, 4) ndarray
        Array of identity transforms for 
        each frame F and joint J
    """

    ts = np.zeros(anim.shape + (4, 4)) 
    ts[:,:,0,0] = 1.0; ts[:,:,1,1] = 1.0;
    ts[:,:,2,2] = 1.0; ts[:,:,3,3] = 1.0;
    return ts
    
def transforms_global(anim):
    """
    Global Animation Transforms
    
    This relies on joint ordering
    being incremental. That means a joint
    J1 must not be a ancestor of J0 if
    J0 appears before J1 in the joint
    ordering.
    
    Parameters
    ----------
    
    anim : Animation
        Input animation
    
    Returns
    ------
    
    transforms : (F, J, 4, 4) ndarray
        Array of global transforms for 
        each frame F and joint J
    """
    
    joints  = np.arange(anim.shape[1])
    parents = np.arange(anim.shape[1])
    locals  = transforms_local(anim)
    globals = transforms_blank(anim)

    globals[:,0] = locals[:,0]

    for i in range(1, anim.shape[1]):
        globals[:,i] = transforms_multiply(globals[:,anim.parents[i]], locals[:,i])

    return globals
    
    
def positions_global(anim):
    """
    Global Joint Positions
    
    Given an animation compute the global joint
    positions at at every frame
    
    Parameters
    ----------
    
    anim : Animation
        Input animation
        
    Returns
    -------
    
    positions : (F, J, 3) ndarray
        Positions for every frame F 
        and joint position J
    """
    
    positions = transforms_global(anim)[:,:,:,3]
    return positions[:,:,:3] / positions[:,:,3,np.newaxis]
    
""" Rotations """
    
def rotations_global(anim):
    """
    Global Animation Rotations
    
    This relies on joint ordering
    being incremental. That means a joint
    J1 must not be a ancestor of J0 if
    J0 appears before J1 in the joint
    ordering.
    
    Parameters
    ----------
    
    anim : Animation
        Input animation
        
    Returns
    -------
    
    points : (F, J) Quaternions
        global rotations for every frame F 
        and joint J
    """

    joints  = np.arange(anim.shape[1])
    parents = np.arange(anim.shape[1])
    locals  = anim.rotations
    globals = Quaternions.id(anim.shape)
    
    globals[:,0] = locals[:,0]
    
    for i in range(1, anim.shape[1]):
        globals[:,i] = globals[:,anim.parents[i]] * locals[:,i]
        
    return globals
    
def rotations_parents_global(anim):
    rotations = rotations_global(anim)
    rotations = rotations[:,anim.parents]
    rotations[:,0] = Quaternions.id(len(anim))
    return rotations
    
def rotations_load_to_maya(rotations, positions, names=None):
    """
    Load Rotations into Maya
    
    Loads a Quaternions array into the scene
    via the representation of axis
    
    Parameters
    ----------
    
    rotations : (F, J) Quaternions 
        array of rotations to load
        into the scene where
            F = number of frames
            J = number of joints
    
    positions : (F, J, 3) ndarray 
        array of positions to load
        rotation axis at where:
            F = number of frames
            J = number of joints
            
    names : [str]
        List of joint names
    
    Returns
    -------
    
    maxies : Group
        Grouped Maya Node of all Axis nodes
    """
    
    import pymel.core as pm

    if names is None: names = ["joint_" + str(i) for i in range(rotations.shape[1])]
    
    maxis = []
    frames = range(1, len(positions)+1)
    for i, name in enumerate(names):
    
        name = name + "_axis"
        axis = pm.group(
             pm.curve(p=[(0,0,0), (1,0,0)], d=1, n=name+'_axis_x'),
             pm.curve(p=[(0,0,0), (0,1,0)], d=1, n=name+'_axis_y'),
             pm.curve(p=[(0,0,0), (0,0,1)], d=1, n=name+'_axis_z'),
             n=name)
        
        axis.rotatePivot.set((0,0,0))
        axis.scalePivot.set((0,0,0))
        axis.childAtIndex(0).overrideEnabled.set(1); axis.childAtIndex(0).overrideColor.set(13)
        axis.childAtIndex(1).overrideEnabled.set(1); axis.childAtIndex(1).overrideColor.set(14)
        axis.childAtIndex(2).overrideEnabled.set(1); axis.childAtIndex(2).overrideColor.set(15)
    
        curvex = pm.nodetypes.AnimCurveTA(n=name + "_rotateX")
        curvey = pm.nodetypes.AnimCurveTA(n=name + "_rotateY")
        curvez = pm.nodetypes.AnimCurveTA(n=name + "_rotateZ")  
        
        arotations = rotations[:,i].euler()
        curvex.addKeys(frames, arotations[:,0])
        curvey.addKeys(frames, arotations[:,1])
        curvez.addKeys(frames, arotations[:,2])
        
        pm.connectAttr(curvex.output, axis.rotateX)
        pm.connectAttr(curvey.output, axis.rotateY)
        pm.connectAttr(curvez.output, axis.rotateZ)
        
        offsetx = pm.nodetypes.AnimCurveTU(n=name + "_translateX")
        offsety = pm.nodetypes.AnimCurveTU(n=name + "_translateY")
        offsetz = pm.nodetypes.AnimCurveTU(n=name + "_translateZ")
        
        offsetx.addKeys(frames, positions[:,i,0])
        offsety.addKeys(frames, positions[:,i,1])
        offsetz.addKeys(frames, positions[:,i,2])
        
        pm.connectAttr(offsetx.output, axis.translateX)
        pm.connectAttr(offsety.output, axis.translateY)
        pm.connectAttr(offsetz.output, axis.translateZ)
    
        maxis.append(axis)
        
    return pm.group(*maxis, n='RotationAnimation')   
    
""" Offsets & Orients """

def orients_global(anim):

    joints  = np.arange(anim.shape[1])
    parents = np.arange(anim.shape[1])
    locals  = anim.orients
    globals = Quaternions.id(anim.shape[1])
    
    globals[:,0] = locals[:,0]
    
    for i in range(1, anim.shape[1]):
        globals[:,i] = globals[:,anim.parents[i]] * locals[:,i]
        
    return globals

    
def offsets_transforms_local(anim):
    
    transforms = anim.orients[np.newaxis].transforms()
    transforms = np.concatenate([transforms, np.zeros(transforms.shape[:2] + (3, 1))], axis=-1)
    transforms = np.concatenate([transforms, np.zeros(transforms.shape[:2] + (1, 4))], axis=-2)
    transforms[:,:,0:3,3] = anim.offsets[np.newaxis]
    transforms[:,:,3:4,3] = 1.0
    return transforms
    
    
def offsets_transforms_global(anim):
    
    joints  = np.arange(anim.shape[1])
    parents = np.arange(anim.shape[1])
    locals  = offsets_transforms_local(anim)
    globals = transforms_blank(anim)

    globals[:,0] = locals[:,0]
    
    for i in range(1, anim.shape[1]):
        globals[:,i] = transforms_multiply(globals[:,anim.parents[i]], locals[:,i])
        
    return globals
    
def offsets_global(anim):
    offsets = offsets_transforms_global(anim)[:,:,:,3]
    return offsets[0,:,:3] / offsets[0,:,3,np.newaxis]
    
""" Lengths """

def offset_lengths(anim):
    return np.sum(anim.offsets[1:]**2.0, axis=1)**0.5
    
    
def position_lengths(anim):
    return np.sum(anim.positions[:,1:]**2.0, axis=2)**0.5
    
    
""" Skinning """
def skin(anim, rest, weights, mesh, maxjoints=4):
    full_transforms = transforms_multiply(
        transforms_global(anim), 
        transforms_inv(transforms_global(rest[0:1])))
    
    weightids = np.argsort(-weights, axis=1)[:,:maxjoints]
    weightvls = np.array(list(map(lambda w, i: w[i], weights, weightids)))
    weightvls = weightvls / weightvls.sum(axis=1)[...,np.newaxis]
    
    verts = np.hstack([mesh, np.ones((len(mesh), 1))])
    verts = verts[np.newaxis,:,np.newaxis,:,np.newaxis]
    verts = transforms_multiply(full_transforms[:,weightids], verts)    
    verts = (verts[:,:,:,:3] / verts[:,:,:,3:4])[:,:,:,:,0]

    return np.sum(weightvls[np.newaxis,:,:,np.newaxis] * verts, axis=2)


def load_from_network(translation, rotations, length, third_dimension=1, average_length=5, tanslation_scale=3):
    rotations = rotations.reshape((-1, 17, 4))
    length = length[0]
    rotations = rotations / np.repeat(np.expand_dims(np.sqrt(np.sum(np.square(rotations), axis=-1)), axis=-1), 4, axis=-1)
    rotations = Quaternions(rotations)
    scaling_factor = np.mean(length) / average_length
    length = length / scaling_factor
    translation = translation / scaling_factor / tanslation_scale
    positions = np.expand_dims(translation, axis=1)
    parents = [-1, 0, 1, 2, 0, 4, 5, 0, 7, 8, 9, 8, 11, 12, 8, 14, 15]
    offsets = np.zeros((17, 3))
    offsets[1, 0] = -length[0]
    offsets[4, 0] = length[0]
    offsets[2, third_dimension] = -length[1]
    offsets[5, third_dimension] = -length[1]
    offsets[3, third_dimension] = -length[2]
    offsets[6, third_dimension] = -length[2]
    offsets[7, third_dimension] = length[3]
    offsets[8, third_dimension] = length[4]
    offsets[9, third_dimension] = length[5]
    offsets[10, third_dimension] = length[6]    
    offsets[11, 0] = length[7]
    offsets[12, 0] = length[8]
    offsets[13, 0] = length[9]
    offsets[14, 0] = -length[7]
    offsets[15, 0] = -length[8]
    offsets[16, 0] = -length[9]
    return Animation(rotations, positions, Quaternions.id(0), offsets, np.array(parents))

---
date: '2018-01-26T19:28:52.259Z'
user_id: 865
user_name: OverthrowCPC
user_intro: |-
    打倒加拿大保守党
    ————
    名字含义：Overthrow 为“打倒”，CPC 为“加拿大保守党”（Conservative Party of Canada）。
    本人是个文盲，所有帖子均为软件随机生成，可随便转载不必署名，谢绝各种跨省、跨国、跨球行动。
user_avatar: >-
    /static/upload/thumb/small50-u-thumb-8652ad06054ab4de2b630c1433bcf39da043b3e0921.png
upvote: 36
downvote: 0
comments:
    - ''
    - ''
    - ''
    - ''
    - ''
    - ''
    - ''
    - ''
    - ''
    - ''
---

很多人意想不到的是：**中共自己安插在国府中的鼹鼠，大都是低级别的，真正高级别的鼹鼠，都是苏共安插进去的。当时国府的老大哥美国自己就浑身挂满苏联木马，国府中的苏共间谍，很多是美国推荐给国府的。**

（本文无意于给历史翻案，或者给国府的溃败寻找外在理由，目的在于提醒诸位历史爱好者，在美苏谍对于内战局势的影响是不可忽略的）

  

  

先偷懒搬运下我的另一个回答[《如何评价“麦卡锡主义”？》](https://pin-cong.com/p/25952/?s=26471)：  

上世纪 30 年代到 50 年初，美国政府被苏联红色间谍渗透得千疮百孔，就是 CIA ， FBI 这些组织都不能幸免。美国政府财政部、军工部门的高管，充斥着苏联间谍。甚至曼哈顿绝密工程，斯大林比杜鲁门了解的更清楚。这些在美苏谍极大影响了 40 年代美国的对华政策

一方面，早在二战期间，在美苏谍就在暗中破坏美国的对华（中华民国）援助。当时，美国国会通过的对华援助方案，被财政部的苏联间谍怀特（Harry Dexter White）暗中脱后腿。甚至后来内战期间滥发法币的始作俑者冀朝鼎，也是怀特推荐给国府的。

另一方面，内战期间的中共与苏联联手作戏表演给美国左派，营造一种苏联没有支援中共的假象。当时美国主政的是左派的民主党，只是简单的认为中国的内战不过是一次普通的改朝换代，并没有意识到苏联在背后的作用。来华调停的马歇尔甚至天真的认为美国对华（中华民国）援助导致了对中共的不公平，引起了中国人的反美情绪。如此种种，导致杜鲁门当局在 1946 年 8 月出台了对华武器禁运政策，虽然禁用政策在一年后被解除，但由于在美苏谍暗中作梗，直到国府迁台前美援并未起到太大作用。

直到中国大陆易手之后，当时左派掌握话语权的美国仍然没有对此事予以充分重视，杜鲁门当局屡屡以国府贪腐为借口来掩盖自己援华不力外加防共无能的事实，甚至已经准备放弃迁台后的国府。

韩战爆发之后，参议员麦卡锡重提苏谍渗透问题，美国左派才意识到之前的对华政策可能被苏联间谍误导了，FBI 局长胡佛之前曾警告的问题也得以被摆到国会议程上，但为时已晚。此时，FBI 凭借“维诺那计划”（Venona Project）之前已经查到的线索确定当初在政界破坏美国援华的那些高级官员是奉命行事的苏联间谍，白宫才终于把中国大陆内战爆发以来的事情和韩战整合在一起。

  

关于在美苏谍误导美国对华政策的话题，详见[《美国为何没在国共内战的时候全力支持国民政府？ - 知乎》](https://www.zhihu.com/question/20255728/answer/178205685)（[防删备份](https://archive.is/tSFXe)）。

关于苏联在中国内战期间起的作用，推荐阅读：

《大棋局中的国共关系》社科院的吕迅著，此书为近年来研究国共内战的新作（2015出版），基于最新解密档案写成的（顺便跪求该书的电子版）。

《朝鲜支援东北解放战争纪实》中国学者吕明辉著。

  

**（未完待续，关于国府中苏联间谍的情况，需要查很多资料，有时间我会慢慢补充）**

/// <reference types="react" />
declare const MessageBoxUI_base: (new (..._: any[]) => import("react-vextensions").BaseComponent<{
    id: number;
}, {
    offset: {
        x: number;
        y: number;
    };
}, unknown>) & {
    renderCount: number;
    lastRenderTime: number;
};
export declare class MessageBoxUI extends MessageBoxUI_base {
    moveBar_drag_origOffset: {
        x: number;
        y: number;
    } | n;
    moveBar_drag_mouseDownPos: {
        x: number;
        y: number;
    } | n;
    moveBar_drag_mouseMoveListener: EventListener | n;
    moveBar_drag_mouseUpListener: EventListener | n;
    render(): JSX.Element;
}
export {};

import { K8SContext, ResourceWithActions, ResourceWithActionsAndDocs } from "../core/models";
import { NetworkLayout, ResourceVisibility } from "./ui-enums";

export type Node = { id: string; label: string; group: string; shape?: string; image?: string };
export type Edge = { from: string; to: string; dashes?: number[] };

export type DisplaySettings = {
  SettingsVersion: number;
  Layout: NetworkLayout;
  Resources: { [kind: string]: ResourceVisibility };
  // this is just a map of the Resource field (maps are not correctly serialized when saved to local storage)
  ResourcesMap: Map<string, ResourceVisibility>;
  Context: {
    currentContext: string;
    contexts: K8SContext[];
  };
};

export type ResourceUIModel = ResourceWithActionsAndDocs & {
  ui: {
    location: {
      x: number;
      y: number;
    };
    font?: {
      size: number;
      bold: boolean;
    };
    size?: {
      height: number;
      width: number;
    };
  };
  isGroup: boolean;
};

export type MongodbDeploymentUIModel = {
  resources: ResourceUIModel[];
  resourceGroups: Map<string, ResourceUIModel[]>;
};

---
title: Feature Set and Roadmap
author: ashish161
date: 2021-03-24
category: features
layout: post
---

#PikReview
    
    Quick, hassle free and privcay centric  store front for your business and your data 


## Store Settings
 - Setup your store link, currency, payment instructions.
 - Order and shipping settings 
 - Store communication details 
 - Payment options 
 
## Inventory  management
 Easy inventory setup and ability to customize your products    
 - Description
 - Pricing
 - Variants : Size and Colors
 - Taxes 
 - Shipping 
 - Category 
 - Bulk products using excel for quick on-boarding 

## Order Management 
Fulfill orders from your mobile / desktop and never miss updating your customers 
 - Accept orders and send quick updates to your customers using whatsapp 
 - Get insights of high value and repeat customers
 - Dashboard of pending / shipping and shipped order and revenue  
 - Bulk products using excel for quick on-boarding 

## Roadmap 
- Support for local languages 
- Support for international currencies 
- Payment gateway integration 
- Setup on custom domain 
- Reseller management
- Tie up with shipping and logistic partners   
import os
import platform
import shelve
from logic.utils import clear_folder
from collections import OrderedDict


class Round:

    def __init__(self, name, teams=[], max_points=100):
        self.round_name = name
        self.max_points = max_points
        self.teams = OrderedDict()
        for team in teams:
            self.teams[team["name"]] = team
            self.teams[team["name"]]["score"] = 0

    def __str__(self):
        return str(self.teams)

    def create_self(self):
        # first delete all other files
        clear_folder(os.path.join(os.getcwd(), "data", "*"))
        self.write_to_db()

    def write_to_db(self):
        db_path = os.path.join(os.getcwd(), "data", self.round_name)
        db = shelve.open(db_path)
        for k in self.teams.keys():
            db[k] = self.teams[k]
        db.close()

    def exists(self):
        if platform.system() != "Linux":
            db_path = os.path.join(os.getcwd(), "data", self.round_name + '.dat')
        else:
            db_path = os.path.join(os.getcwd(), "data", self.round_name)
        return os.path.exists(db_path)

    def open_existing(self):
        # expects that round_name already exists
        db_path = os.path.join(os.getcwd(), "data", self.round_name)
        db = shelve.open(db_path)
        db_keys = list(db.keys())
        db_keys.sort()
        for k in db_keys:
            self.teams[k] = db[k]
        db.close()

    def update_from_dict(self, d):
        for k in d.keys():
            if k in self.teams:
                val = int(d[k])
                if val < 0:
                    self.teams[k]["score"] = 0
                else:
                    self.teams[k]["score"] = val if val <= self.max_points else self.max_points
        self.write_to_db()



var config = {}

config.redis = {};
config.http = {};
config.cookie = {};
config.log = {};
config.ubersmith = {};
config.ubersmith.warm_cache = false;
config.log.access_log = './access.log';
config.log.directory = process.env.LOG_DIR || './';

config.redis.uri = process.env.REDIS_URI;
config.redis.host = process.env.REDIS_HOST || 'localhost';
config.redis.port = process.env.REDIS_PORT || 6379;
config.redis.db = process.env.REDIS_DB || 1;

config.http.port = process.env.PORT || 3005;
config.cookie.secret = 'securit3333!!';

module.exports = config;

<?php

namespace App\Http\Controllers\Auth;

use App\Custodian;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use JWTAuth;
use App\UserType;
use App\Department;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    public function userAuth(Request $request){
        $credentials = $request->only('email','password');
        $token = null;

        try{
            if(!$token = JWTAuth::attempt($credentials)){ 
                return response()->json(['error' => 'invalid_credentials'], 404);
            }
        }catch(JWTException $ex){
            return response()->json(['error' => 'something_went_wrong'], 500);
        }

        return response()->json(compact('token'));

        
    }

    public function getAuthenticatedUser(){
        
        try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {
                return response()->json(['user_not_found'], 404);
            }

        } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

            return response()->json(['token_expired'], $e->getStatusCode());

        } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

            return response()->json(['token_invalid'], $e->getStatusCode());

        } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

            return response()->json(['token_absent'], $e->getStatusCode());
        }

        $user_type_name = Usertype::find($user->user_type_id)->role;
        $user->user_type_name =  $user_type_name;

        $user_department_name = Department::find($user->department_id)->name;
        $user->user_department_name =  $user_department_name;

        $data = [];
            $data = [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'position' => $user->position,
                'contact_number' => $user->contact_number,
                'employee_id' => $user->employee_id,
                'user_type_id' => $user->user_type_id,
                'department_id' => $user->department_id,
                'user_type_name' => $user->user_type_name,
                'user_department_name' => $user->user_department_name
            ];
        
        // the token is valid and we have found the user via the sub claim
        return response()->json(compact('data'));
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return Custodian::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

#include "mini_uart.h"
#include "uint.h"
#include "priority_queue.h"
#include "queue.h"
#include "scheduler.h"
#include "task.h"

uint64 freq_thread = 31;

void core_timer_init(){
    uint64 tmp;
    asm volatile("mrs %0, cntkctl_el1" : "=r"(tmp));
    tmp |= 1;
    asm volatile("msr cntkctl_el1, %0" : : "r"(tmp));
    core_timer_disable();
}

void arm_core_timer_intr_handler() {
    core_timer_handler();
}

void core_timer_handler(){
    struct node* node = delete_first_node();
    if(node->next == NULL){
        asm volatile("mrs x0, cntfrq_el0\n"
                     "ldr x1, =10\n"
                     "mul x0, x0, x1\n"
                     "msr cntp_tval_el0, x0\n");
        core_timer_disable();
    }else{
        core_timer_enable();
        uint64 interval = node->next->time_to_ring;
        asm volatile("msr cntp_tval_el0, %[output0]\n"
                     ::[output0] "r" (interval));
    }
    free(node);
    node->todo(node->arguments);
}

void add_timer(void (*callback_f)(void*),void *argu_for_call,int times){
    uint64 clock_hz,now_time,interval;
    asm volatile("mrs %[input0], cntfrq_el0\n"
                 "mrs %[input2], cntp_tval_el0\n"
                 :[input0] "=r" (clock_hz),
                  [input2] "=r" (interval));
    uint64 time_to_ring = add_node(callback_f, argu_for_call, clock_hz / 1000 * times, interval);
    core_timer_enable();
    asm volatile("msr cntp_tval_el0, %[output0]\n"
                 ::[output0] "r" (time_to_ring));
}

void *wakeup(void *p){
    uart_printf("Timeout!!\n");
}

void sleep(int duration){
    add_timer(wakeup,NULL,duration);
    uart_printf("Timer is set...\n");
}

void delay(int duration){
    irq_disable();
    void *argu = get_current();
    add_timer(wakeup_queue,argu,duration);
    irq_enable();
    schedule();
}

void thread_timer_handler(){
    void *t = get_current();
    struct thread *s = t;
    PushToReadyList(s->tid);
    thread_timer();
    task_schedule(t);
}

void thread_timer(){
    while(delete_first_node() != NULL);
    add_timer(thread_timer_handler,NULL,freq_thread);
}

/* eslint-disable @typescript-eslint/no-unused-vars,@typescript-eslint/no-empty-interface,@typescript-eslint/no-explicit-any */
import Vue, { VNode, RenderContext } from 'vue';
import { DefaultProps } from 'vue/types/options';

declare global {
  namespace JSX {
    interface Element extends VNode {}
    interface ElementClass extends Vue {}
    interface IntrinsicElements {
      [elem: string]: any;
    }
  }
}

declare module 'vue/types/index' {
  type FunctionalComponent<Props = DefaultProps> = (
    context: RenderContext<Props>,
  ) => VNode;
}

---
layout: "fluid/docs_base"
version: "3.6.1"
versionHref: "/docs/v3/3.6.1"
path: ""
category: api
id: "app"
title: "App"
header_sub_title: "Ionic API Documentation"
doc: "App"
docType: "class"

---









<h1 class="api-title">
<a class="anchor" name="app" href="#app"></a>

App





</h1>

<a class="improve-v2-docs" href="http://github.com/ionic-team/ionic/edit/v3/src/components/app/app.ts#L16">
Improve this doc
</a>






<p>App is a utility class used in Ionic to get information about various aspects of an app</p>




<!-- @usage tag -->


<!-- @property tags -->



<!-- instance methods on the class -->

<h2><a class="anchor" name="instance-members" href="#instance-members">Instance Members</a></h2>

<div id="getActiveNav"></div>

<h3>
<a class="anchor" name="getActiveNav" href="#getActiveNav">
<code>getActiveNav()</code>


</a>
</h3>








<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>NavController</code> <p>Returns the first Active Nav Controller from the list. This method is deprecated</p>


</div>




<div id="getActiveNavContainers"></div>

<h3>
<a class="anchor" name="getActiveNavContainers" href="#getActiveNavContainers">
<code>getActiveNavContainers()</code>


</a>
</h3>











<div id="getActiveNavs"></div>

<h3>
<a class="anchor" name="getActiveNavs" href="#getActiveNavs">
<code>getActiveNavs()</code>


</a>
</h3>








<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>NavController[]</code> <p>Returns the active NavControllers. Using this method is preferred when we need access to the top-level navigation controller while on the outside views and handlers like <code>registerBackButtonAction()</code></p>


</div>




<div id="getNavByIdOrName"></div>

<h3>
<a class="anchor" name="getNavByIdOrName" href="#getNavByIdOrName">
<code>getNavByIdOrName()</code>


</a>
</h3>











<div id="getRootNav"></div>

<h3>
<a class="anchor" name="getRootNav" href="#getRootNav">
<code>getRootNav()</code>


</a>
</h3>











<div id="getRootNavById"></div>

<h3>
<a class="anchor" name="getRootNavById" href="#getRootNavById">
<code>getRootNavById()</code>


</a>
</h3>








<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>NavController</code> <p>Returns the root NavController</p>


</div>




<div id="getRootNavs"></div>

<h3>
<a class="anchor" name="getRootNavs" href="#getRootNavs">
<code>getRootNavs()</code>


</a>
</h3>











<div id="isScrolling"></div>

<h3>
<a class="anchor" name="isScrolling" href="#isScrolling">
<code>isScrolling()</code>


</a>
</h3>

Boolean if the app is actively scrolling or not.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>boolean</code> <p>returns true or false</p>


</div>




<div id="setTitle"></div>

<h3>
<a class="anchor" name="setTitle" href="#setTitle">
<code>setTitle(val)</code>


</a>
</h3>

Sets the document title.


<table class="table param-table" style="margin:0;">
  <thead>
    <tr>
      <th>Param</th>
      <th>Type</th>
      <th>Details</th>
    </tr>
  </thead>
  <tbody>

    <tr>
      <td>
        val


      </td>
      <td>

  <code>string</code>
      </td>
      <td>
        <p>Value to set the document title to.</p>


      </td>
    </tr>

  </tbody>
</table>








<div id="viewDidEnter"></div>

<h3>
<a class="anchor" name="viewDidEnter" href="#viewDidEnter">
<code>viewDidEnter</code>


</a>
</h3>

Observable that emits after any view is entered in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>




<div id="viewDidLeave"></div>

<h3>
<a class="anchor" name="viewDidLeave" href="#viewDidLeave">
<code>viewDidLeave</code>


</a>
</h3>

Observable that emits after any view is exited in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>




<div id="viewDidLoad"></div>

<h3>
<a class="anchor" name="viewDidLoad" href="#viewDidLoad">
<code>viewDidLoad</code>


</a>
</h3>

Observable that emits whenever a view loads in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>




<div id="viewWillEnter"></div>

<h3>
<a class="anchor" name="viewWillEnter" href="#viewWillEnter">
<code>viewWillEnter</code>


</a>
</h3>

Observable that emits before any view is entered in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>




<div id="viewWillLeave"></div>

<h3>
<a class="anchor" name="viewWillLeave" href="#viewWillLeave">
<code>viewWillLeave</code>


</a>
</h3>

Observable that emits before any view is exited in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>




<div id="viewWillUnload"></div>

<h3>
<a class="anchor" name="viewWillUnload" href="#viewWillUnload">
<code>viewWillUnload</code>


</a>
</h3>

Observable that emits before any view unloads in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>





  <h2 id="sass-variable-header"><a class="anchor" name="sass-variables" href="#sass-variables">Sass Variables</a></h2>
  <div id="sass-variables" ng-controller="SassToggleCtrl">
  <div class="sass-platform-toggle">

    <h3 ng-init="setSassPlatform('base')">All</h3>

  </div>



  <table ng-show="active === 'base'" id="sass-base" class="table param-table" style="margin:0;">
    <thead>
      <tr>
        <th>Property</th>
        <th>Default</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>

      <tr>
        <td><code>$font-size-root</code></td>

          <td><code>62.5%</code></td>

        <td><p>Font size of the root html</p>
</td>
      </tr>

      <tr>
        <td><code>$headings-font-weight</code></td>

          <td><code>500</code></td>

        <td><p>Font weight of all headings</p>
</td>
      </tr>

      <tr>
        <td><code>$headings-line-height</code></td>

          <td><code>1.2</code></td>

        <td><p>Line height of all headings</p>
</td>
      </tr>

      <tr>
        <td><code>$h1-font-size</code></td>

          <td><code>2.6rem</code></td>

        <td><p>Font size of heading level 1</p>
</td>
      </tr>

      <tr>
        <td><code>$h2-font-size</code></td>

          <td><code>2.4rem</code></td>

        <td><p>Font size of heading level 2</p>
</td>
      </tr>

      <tr>
        <td><code>$h3-font-size</code></td>

          <td><code>2.2rem</code></td>

        <td><p>Font size of heading level 3</p>
</td>
      </tr>

      <tr>
        <td><code>$h4-font-size</code></td>

          <td><code>2rem</code></td>

        <td><p>Font size of heading level 4</p>
</td>
      </tr>

      <tr>
        <td><code>$h5-font-size</code></td>

          <td><code>1.8rem</code></td>

        <td><p>Font size of heading level 5</p>
</td>
      </tr>

      <tr>
        <td><code>$h6-font-size</code></td>

          <td><code>1.6rem</code></td>

        <td><p>Font size of heading level 6</p>
</td>
      </tr>

      <tr>
        <td><code>$include-responsive-utilities</code></td>

          <td><code>true</code></td>

        <td><p>Whether to include all of the responsive utility attributes</p>
</td>
      </tr>

      <tr>
        <td><code>$include-text-alignment-utilities</code></td>

          <td><code>$include-responsive-utilities</code></td>

        <td><p>Whether to include all of the responsive text alignment attributes</p>
</td>
      </tr>

      <tr>
        <td><code>$include-text-transform-utilities</code></td>

          <td><code>$include-responsive-utilities</code></td>

        <td><p>Whether to include all of the responsive text transform attributes</p>
</td>
      </tr>

      <tr>
        <td><code>$include-float-element-utilities</code></td>

          <td><code>$include-responsive-utilities</code></td>

        <td><p>Whether to include all of the responsive float attributes</p>
</td>
      </tr>

      <tr>
        <td><code>$screen-breakpoints</code></td>

          <td><code>(&#10;  xs: 0,&#10;  sm: 576px,&#10;  md: 768px,&#10;  lg: 992px,&#10;  xl: 1200px&#10;)</code></td>

        <td><p>The minimum dimensions at which your layout will change,
adapting to different screen sizes, for use in media queries</p>
</td>
      </tr>

    </tbody>
  </table>

</div>



<!-- related link --><!-- end content block -->


<!-- end body block -->


import __SInterface from '@coffeekraken/s-interface';
import __SugarConfig from '@coffeekraken/s-sugar-config';
import __flatten from '@coffeekraken/sugar/shared/object/flatten';
import __postCss from 'postcss';
import __deepMerge from '@coffeekraken/sugar/shared/object/deepMerge';
import __postcss from 'postcss';
import __theme from '../../utils/theme';

class postcssSugarPluginMediaMixinInterface extends __SInterface {
  static definition = {
    query1: {
      type: 'String',
      required: true
    },
    query2: {
      type: 'String'
    },
    query3: {
      type: 'String'
    },
    query4: {
      type: 'String'
    },
    query5: {
      type: 'String'
    },
    query6: {
      type: 'String'
    },
    query7: {
      type: 'String'
    }
  };
}
export { postcssSugarPluginMediaMixinInterface as interface };

/**
 * @name           media
 * @namespace      mixins
 * @type           Mixin
 * @platform      css
 * @status        beta
 *
 * This mixin allows you to apply any media queries that are defined
 * in the config.theme.media.queries configuration stack like "tablet", "mobile", etc...
 *
 * @param       {String}        query       The query string like ">tablet", "<=desktop", etc...
 * @return      {Css}         The generated css
 * 
 * @example         postcss
 * \@sugar.media >=desktop {
 *      // ...
 * }
 * \@sugar.media tablet {
 *      // ...
 * }
 *
 * @since       2.0.0
 * @author         Olivier Bossel <olivier.bossel@gmail.com> (https://olivierbossel.com)
 */
export default function ({
  params,
  atRule,
  postcssApi
}: {
  params: any;
  atRule: any;
  postcssApi: any;
}) {
  const mediaConfig = __theme().config('media');

  const queries: string[] = [];

  Object.keys(params).forEach(queryId => {
    const query = params[queryId].trim();
    query.split(',').forEach(q => {
      queries.push(q.trim());
    });
  });

  // const queries = params.query.split(',').map(l => l.trim());
  const fullQueriesList: string[] = [];

  queries.forEach(query => {

    // const mediasArray: string[] = [];
    // let currentQuery = '';
    // query.replace(/\sand\s/gm, ' , ').replace(/\sor\s/gm, ' _ ').split('').forEach(char => {
    //   if (char === '_') {
    //     mediasArray.push(currentQuery.trim());
    //     mediasArray.push('or');
    //     currentQuery = '';
    //   } else if (char === ',') {
    //     mediasArray.push(currentQuery.trim());
    //     mediasArray.push('and');
    //     currentQuery = '';
    //   } else {
    //     currentQuery += char;
    //   }
    // });
    // mediasArray.push(currentQuery.trim());

    const currentQueryList: string[] = [mediaConfig.defaultQuery, 'and'];

    // mediasArray.forEach((query) => {

      if (query === 'and' || query === 'or') {
        currentQueryList.push(query); 
        return;
      }

      const firstChar = query.slice(0, 1);
      const firstTwoChar = query.slice(0, 2);
      const lastChar = query.slice(-1);
      let action = mediaConfig.defaultAction;
      let mediaName = query;

      if (lastChar === '-' || lastChar === '|')
        mediaName = mediaName.slice(0, -1);

      if (
        firstTwoChar === '>=' ||
        firstTwoChar === '<=' ||
        firstTwoChar === '=='
      ) {
        mediaName = mediaName.slice(2);
        action = firstTwoChar;
      } else if (firstChar === '<' || firstChar === '>' || firstChar === '=') {
        mediaName = mediaName.slice(1);
        action = firstChar;
      }

      const mediaQueryConfig = mediaConfig.queries[mediaName];
      if (!mediaQueryConfig)
        throw new Error(
          `<red>[postcssSugarPlugin.media]</red> Sorry but the requested media "<yellow>${mediaName}</yellow>" does not exists in the config. Here's the available medias: ${Object.keys(
            mediaConfig.queries
          )
            .map((l) => `<green>${l}</green>`)
            .join(',')}`
        );

      const queryList: string[] = [];

      Object.keys(mediaQueryConfig).forEach((prop) => {
        const value = mediaQueryConfig[prop];
        if (!value) return;

        if (
          [
            'min-width',
            'max-width',
            'min-device-width',
            'max-device-width'
          ].indexOf(prop) !== -1
        ) {
          if (action === '>') {
            if (prop === 'max-width' || prop === 'max-device-width') {
              let argName = 'min-width';
              if (prop.includes('-device')) argName = 'min-device-width';
              queryList.push(`(${argName}: ${value + 1}px)`);
            }
          } else if (action === '<') {
            if (prop === 'min-width' || prop === 'min-device-width') {
              let argName = 'max-width';
              if (prop.includes('-device')) argName = 'max-device-width';
              queryList.push(`(${argName}: ${value}px)`);
            }
          } else if (action === '=') {
            queryList.push(`(${prop}: ${value}px)`);
          } else if (action === '>=') {
            if (prop === 'min-width' || prop === 'min-device-width') {
              queryList.push(`(${prop}: ${value}px)`);
            }
          } else if (action === '<=') {
            if (prop === 'max-width' || prop === 'max-device-width') {
              queryList.push(`(${prop}: ${value}px)`);
            }
          } else {
            queryList.push(`(${prop}: ${value}px)`);
          }
        } else {
          queryList.push(`(${prop}: ${value}px)`);
        }
      });

      if (lastChar === '-') {
        queryList.push('(orientation: landscape)');
      } else if (lastChar === '|') {
        queryList.push('(orientation: portrait)');
      }

      currentQueryList.push(queryList.join(' and '));
    // });

    fullQueriesList.push(currentQueryList.join(' '));

  });
  
  const mediaRule = new postcssApi.AtRule({
    name: 'media',
    params: fullQueriesList.join(' ')
  });

  // const AST = __postcss.parse(`@media ${fullQueriesList.join(' ')} {}`);

  // @ts-ignore
  atRule.nodes.forEach(node => {
    mediaRule.append(node);
  });

  atRule.replaceWith(mediaRule);
}

package org.honeysoft.akka.di;

import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Field;

import static org.fest.reflect.util.Accessibles.setAccessible;
import static org.fest.reflect.util.Accessibles.setAccessibleIgnoringExceptions;

public class SpringUntypedActorFactory implements UntypedActorFactory {

    private final DependencyInjectionFactory dependencyInjectionFactory;

    private final ApplicationContext applicationContext;

    public SpringUntypedActorFactory(Class<?> actorClass, ApplicationContext applicationContext) {
        this.dependencyInjectionFactory = new DefaultUntypedActorFactory(actorClass);
        this.applicationContext = applicationContext;
    }

    public SpringUntypedActorFactory(UntypedActorFactory customFactory, ApplicationContext applicationContext) {
        this.dependencyInjectionFactory = new SpecificUntypedActorFactory(customFactory);
        this.applicationContext = applicationContext;
    }

    private interface DependencyInjectionFactory {
        UntypedActor createAndInject();
    }


    private abstract class AbstractUntypedActorFactory implements DependencyInjectionFactory {

        @Override
        public final UntypedActor createAndInject() {
            try {
                UntypedActor untypedActor = create();

                Class<?> aClass = getActorClass();
                for (Field field : aClass.getDeclaredFields()) {

                    if (field.getAnnotation(Autowired.class) != null) {
                        boolean accessible = field.isAccessible();
                        try {
                            setAccessible(field, true);
                            field.set(untypedActor, applicationContext.getBean(field.getType()));
                        } catch (IllegalAccessException e) {
                            throw new IllegalStateException("Unable to create actor instance", e);
                        } finally {
                            setAccessibleIgnoringExceptions(field, accessible);
                        }
                    }
                }
                return untypedActor;

            } catch (Exception e) {
                throw new IllegalStateException("Unable to create actor instance", e);
            }

        }

        protected abstract Class<?> getActorClass();

        protected abstract UntypedActor create() throws Exception;

    }

    private final class SpecificUntypedActorFactory extends AbstractUntypedActorFactory {

        private final UntypedActorFactory specificFactory;
        private volatile Class<?> actorClass;

        private SpecificUntypedActorFactory(UntypedActorFactory specificFactory) {
            this.specificFactory = specificFactory;
        }

        @Override
        protected Class<?> getActorClass() {
            return actorClass;
        }

        @Override
        protected UntypedActor create() throws Exception {
            UntypedActor untypedActor = (UntypedActor) specificFactory.create();
            actorClass = untypedActor.getClass();
            return untypedActor;
        }
    }

    private final class DefaultUntypedActorFactory extends AbstractUntypedActorFactory {
        private final Class<?> actorClass;

        public DefaultUntypedActorFactory(Class<?> actorClass) {
            this.actorClass = actorClass;
        }

        @Override
        protected Class<?> getActorClass() {
            return actorClass;
        }

        @Override
        protected UntypedActor create() throws InstantiationException, IllegalAccessException {
            return (UntypedActor) actorClass.newInstance();
        }
    }

    /**
     * This method must return a different instance upon every call.
     */
    @Override
    public UntypedActor create() {
        return dependencyInjectionFactory.createAndInject();
    }


}
package channel

import (
	"bytes"
)

/**
 * 通道支付完整单据
 */

// 通道链支付票据
type ChannelPayCompleteDocuments struct {
	// 对账票据表
	ProveBodys *ChannelPayProveBodyList
	// 支付签名票据
	ChainPayment *OffChainFormPaymentChannelTransfer
}

func (c ChannelPayCompleteDocuments) Size() uint32 {
	return c.ProveBodys.Size() + c.ChainPayment.Size()
}

func (c ChannelPayCompleteDocuments) Serialize() ([]byte, error) {
	var buffer bytes.Buffer
	var bt1, _ = c.ProveBodys.Serialize()
	buffer.Write(bt1)
	var bt2, _ = c.ChainPayment.Serialize()
	buffer.Write(bt2)
	return buffer.Bytes(), nil
}

func (c *ChannelPayCompleteDocuments) Parse(buf []byte, seek uint32) (uint32, error) {
	var e error
	// 通道
	c.ProveBodys = &ChannelPayProveBodyList{}
	seek, e = c.ProveBodys.Parse(buf, seek)
	if e != nil {
		return 0, e
	}
	c.ChainPayment = &OffChainFormPaymentChannelTransfer{}
	seek, e = c.ChainPayment.Parse(buf, seek)
	if e != nil {
		return 0, e
	}
	return seek, nil
}

import React, { Fragment, Component } from "react";
import LinearProgress from "@material-ui/core/LinearProgress";
import Snackbar from "../../organisms/Snackbar";

export default class FileUpload extends Component {
  constructor(props) {
    super(props);
    this.state = {
      url: props.url || "/upload/image",
      showStatus: true, //props.showStatus,
      showSnackbar: false,
      snackbarSeverity: "error",
      snackbarDuration: 5000,
      snackbarMessage: "",
    };

    this.uploadId = Math.round(Math.random() * 1e9);
    this.fileInput = React.createRef();
  }

  uploadFile = async (e) => {
    if (this.fileInput.current.files[0]) {
      const formData = new FormData();
      let json;
      try {
        formData.append("image", this.fileInput.current.files[0]);
        const response = await fetch(this.state.url, {
          method: "POST",
          body: formData,
        });
        json = await response.json();

        if (this.props.afterUpload) {
          this.props.afterUpload(json);
        }
        this.setState({
          showSnackbar: true,
          snackbarSeverity: "success",
          snackbarMessage: "Upload success.",
        });
      } catch (e) {
        this.setState({
          showSnackbar: true,
          snackbarSeverity: "error",
          snackbarMessage: "Upload failed.",
        });
      }

      this.fileInput.current.value = "";
    }
  };

  render() {
    const {
      showSnackbar,
      snackbarSeverity,
      snackbarDuration,
      snackbarMessage,
    } = this.state;
    return (
      <Fragment>
        <Snackbar
          open={showSnackbar}
          severity={snackbarSeverity}
          duration={snackbarDuration}
          message={snackbarMessage}
          onClose={() => {
            this.setState({ showSnackbar: false });
          }}
        />
        <input
          accept="image/*"
          id={this.uploadId}
          multiple
          type="file"
          onChange={this.uploadFile}
          onBlur={() => {}}
          ref={this.fileInput}
          style={{ display: "none" }}
        />
        <div
          style={{ cursor: "pointer", display: "inline-block" }}
          onClick={(e) => {
            if (!this.fileInput.current.value === "" || this.props.disabled) {
              return;
            }

            document.getElementById(`${this.uploadId}`).click();
          }}
        >
          {this.fileInput &&
          this.fileInput.current &&
          !this.fileInput.current.value === "" &&
          this.state.showStatus ? (
            <LinearProgress style={{ marginTop: "3em" }} />
          ) : (
            this.props.children
          )}
        </div>
      </Fragment>
    );
  }
}

import FontPainter, { FontParserSVG, RenderEngineSVG, RenderBoundsElementWidth } from 'fontpainter';
import './example-simple.scss';

export class Demo {
	immediate = true;

	constructor() {
		this.container = document.querySelector('.example-simple');
		this.painter = new FontPainter();
		this.engine = new RenderEngineSVG();
		this.painter.setEngine(this.engine);
		this.painter.fontSize = 45;
		this.painter.bounds = new RenderBoundsElementWidth(this.container);
	}

	render(copy = '', fontPath) {
		this.painter.loadFont(fontPath, FontParserSVG);
		this.painter.getFont().then(() => {
			this.painter.paint(copy);
			this.container.appendChild(this.engine.svgElement);
		});
	}

	dispose() {
		this.painter.dispose();
	}
}

export const menuName = 'Simple SVG';

export const defaultText = 'The quick brown fox jumps over the lazy dog';

export { default as template } from 'raw-loader!./template.html';


module BestPractices::Scopes
  extend ActiveSupport::Concern

  included do
    scope :ordered, -> { order obsolete: :asc, name: :asc }
  end

  module ClassMethods
    def visible
      setting                      = Current.organization.settings.find_by name: 'hide_obsolete_best_practices'
      hide_obsolete_best_practices = DEFAULT_SETTINGS[:hide_obsolete_best_practices][:value]

      if (setting ? setting.value : hide_obsolete_best_practices) == '0'
        all
      else
        where(obsolete: false)
      end
    end
  end
end

pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;

import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";

import "../interfaces/helpers/IPriceFeed.sol";

import "../abstract/AbstractDependant.sol";

contract PriceFeed is IPriceFeed, AbstractDependant {
    IUniswapV2Router02 public ammRouter;

    address public wrappedToken;
    address public bmiToken;
    address public usdtToken;

    function setDependencies(IContractsRegistry _contractsRegistry)
        external
        override
        onlyInjectorOrZero
    {
        ammRouter = IUniswapV2Router02(_contractsRegistry.getAMMRouterContract());
        wrappedToken = _contractsRegistry.getWrappedTokenContract();
        bmiToken = _contractsRegistry.getBMIContract();
        usdtToken = _contractsRegistry.getUSDTContract();
    }

    function howManyBMIsInUSDT(uint256 usdtAmount) external view override returns (uint256) {
        if (usdtAmount == 0) {
            return 0;
        }

        address[] memory pairs = new address[](3);
        pairs[0] = usdtToken;
        pairs[1] = wrappedToken;
        pairs[2] = bmiToken;

        uint256[] memory amounts = ammRouter.getAmountsOut(usdtAmount, pairs);

        return amounts[amounts.length - 1];
    }

    function howManyUSDTsInBMI(uint256 bmiAmount) external view override returns (uint256) {
        if (bmiAmount == 0) {
            return 0;
        }

        address[] memory pairs = new address[](3);
        pairs[0] = bmiToken;
        pairs[1] = wrappedToken;
        pairs[2] = usdtToken;

        uint256[] memory amounts = ammRouter.getAmountsOut(bmiAmount, pairs);

        return amounts[amounts.length - 1];
    }
}
import fs from 'fs';
import sinon from 'sinon';
import test from 'tape';

import { mockParsedMarkdown } from './_fixtures';

import { DIRECTORIES } from './config/constants';
import { MarkdownParser } from './MarkdownParser';
import { Renderer } from './Renderer';
import { parseContent } from './parseContent';

import type { ParsedContentType } from './parseContent';

type MockDirentProps = {
  isDirectory?: true;
  isFile?: true;
  name: string;
};

const mockDirent = (props: MockDirentProps): fs.Dirent => {
  const { isDirectory, isFile, name } = props;

  return {
    isBlockDevice: () => false,
    isCharacterDevice: () => false,
    isDirectory: () => isDirectory || false,
    isFIFO: () => false,
    isFile: () => isFile || false,
    isSocket: () => false,
    isSymbolicLink: () => false,
    name,
  };
};

test('`parseContent`', async (t: test.Test) => {
  const readdirStub = sinon.stub(fs.promises, 'readdir');
  const readFileStub = sinon.stub(fs.promises, 'readFile');

  readdirStub
    .withArgs('./content/', { withFileTypes: true })
    .resolves([
      mockDirent({ isFile: true, name: 'index.md' }),
      mockDirent({ isFile: true, name: 'draft.md' }),
      mockDirent({ isFile: true, name: 'page.md' }),
      mockDirent({ isFile: true, name: 'asset.jpg' }),
      mockDirent({ isFile: true, name: '_data.json' }),
      mockDirent({ isDirectory: true, name: 'directory' }),
    ]);

  readdirStub
    .withArgs('./content/directory/', { withFileTypes: true })
    .resolves([
      mockDirent({ isFile: true, name: '_index.md' }),
      mockDirent({ isFile: true, name: 'draft.md' }),
      mockDirent({ isFile: true, name: 'page.md' }),
      mockDirent({ isFile: true, name: 'asset.jpg' }),
      mockDirent({ isFile: true, name: '_data.json' }),
      mockDirent({ isDirectory: true, name: 'nested' }),
    ]);

  readdirStub
    .withArgs('./content/directory/nested/', { withFileTypes: true })
    .resolves([
      mockDirent({ isFile: true, name: 'index.md' }),
      mockDirent({ isFile: true, name: 'draft.md' }),
      mockDirent({ isFile: true, name: 'page.md' }),
      mockDirent({ isFile: true, name: 'asset.jpg' }),
      mockDirent({ isFile: true, name: '_data.json' }),
    ]);

  readFileStub.withArgs(sinon.match(/\.md$/)).resolves('Markdown');
  readFileStub
    .withArgs(sinon.match(/draft.md$/))
    .resolves('+++\ndraft = true\n+++\n\nMarkdown');
  readFileStub
    .withArgs(sinon.match(/_data.json$/))
    .resolves('{ "key": "value" }');

  const renderer = new Renderer({ baseTemplate: '', config: {}, partials: {} });
  const markdownParser = new MarkdownParser(renderer, []);

  const content = await parseContent({
    directory: DIRECTORIES.CONTENT,
    markdownParser,
    renderer,
  });

  t.deepEqual(
    content,
    {
      assets: [{ filePath: './content/asset.jpg' }],
      children: {
        directory: {
          assets: [{ filePath: './content/directory/asset.jpg' }],
          children: {
            nested: {
              assets: [{ filePath: './content/directory/nested/asset.jpg' }],
              children: null,
              data: {
                json: { key: 'value' },
                filePath: './content/directory/nested/_data.json',
              },
              pages: [
                {
                  filePath: './content/directory/nested/index.md',
                  markdown: mockParsedMarkdown,
                  name: 'index.md',
                },
                {
                  filePath: './content/directory/nested/page.md',
                  markdown: mockParsedMarkdown,
                  name: 'page.md',
                },
              ],
              section: null,
            },
          },
          data: {
            json: { key: 'value' },
            filePath: './content/directory/_data.json',
          },
          pages: [
            {
              filePath: './content/directory/page.md',
              markdown: mockParsedMarkdown,
              name: 'page.md',
            },
          ],
          section: {
            filePath: './content/directory/_index.md',
            markdown: mockParsedMarkdown,
            name: '_index.md',
          },
        },
      },
      data: { json: { key: 'value' }, filePath: './content/_data.json' },
      pages: [
        {
          filePath: './content/index.md',
          markdown: mockParsedMarkdown,
          name: 'index.md',
        },
        {
          filePath: './content/page.md',
          markdown: mockParsedMarkdown,
          name: 'page.md',
        },
      ],
      section: null,
    } as ParsedContentType,
    'parses all files within the given directory and returns a formatted object'
  );

  readdirStub.restore();
  readFileStub.restore();
  t.end();
});

@extends('errors::layout')

@section('title', 'Error')

{{--@section('message', 'Whoops, looks like something went wrong.')--}}

@section('message')
    500
    <br/><br/>
    服务器出错，请联系您的管理员
@stop

package com.pixelw.net.netty;

import com.pixelw.entity.Client;
import com.pixelw.net.ServerCore;
import com.pixelw.net.ServerListener;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

import java.util.Map;

/**
 * @author Carl Su
 * @date 2020/5/1
 */
public class NettyCore extends ServerCore {

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    public NettyCore(ServerListener listener, int port) {
        super(listener, port);
    }

    @Override
    public void run() {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                bossGroup = new NioEventLoopGroup();
                workerGroup = new NioEventLoopGroup();
                try {
                    ServerBootstrap bootstrap = new ServerBootstrap();
                    bootstrap.group(bossGroup, workerGroup)
                            .channel(NioServerSocketChannel.class)
                            .childHandler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel socketChannel) {
                                    socketChannel.pipeline().addLast(new ServerHandler(listener, NettyCore.this));
                                }
                            })
                            .option(ChannelOption.SO_BACKLOG, 128)
                            .childOption(ChannelOption.SO_KEEPALIVE, true);
                    ChannelFuture future = bootstrap.bind(port).sync();
                    future.channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void sendTextMsg(String msg, Client client) {
        Channel channel = client.getChannel();
        if (channel != null) {
            System.out.println("sendto:" + client.getInetAddress());
            //client is based on stream reader, append a line
            String string = msg + "\n";
            byte[] bytes = string.getBytes(CharsetUtil.UTF_8);
            ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes);
            channel.writeAndFlush(byteBuf);
        }
    }

    @Override
    public void shutdown(Map<String, Client> map) {
        //foreach 或者Iterator
        try {
            if (map.size() > 0) {
                for (String strUserID : map.keySet()) {
                    Client client = map.get(strUserID);
                    client.getChannel().writeAndFlush(CONTROL_TOKEN);
                    client.getChannel().close();
                }
            } else {
                System.out.println("no opened sockets");
            }
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            listener.onClosed(this);
        }

    }
}

import React, {Component} from 'react';
import FailureView from '../views/FailureView';
import PropTypes from 'prop-types';

class Failure extends Component {
  showLogin() {
    const {emitter} = this.props.services;
    emitter.emit('setView', 'Login');
  }

  render() {
    const {error} = this.props.viewParameters;
    return (
      <FailureView
        errorMessage={error}
        onBackClick={this.showLogin.bind(this)}
      />
    );
  }
}

Failure.propTypes = {
  services: PropTypes.object,
  viewParameters: PropTypes.object
};

export default Failure;

package org.lwjgl.opengl;

/**
 * Native bindings to the <a target="_blank" href="https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_gpu_shader_half_float.txt">AMD_gpu_shader_half_float</a> extension.
 * 
 * <p>This extension was developed based on the {@link NVGPUShader5 NV_gpu_shader5} extension to allow implementations supporting half float in shader and expose the
 * feature without the additional requirements that are present in {@code NV_gpu_shader5}.</p>
 * 
 * <p>The extension introduces the following features for all shader types:</p>
 * 
 * <ul>
 * <li>support for half float scalar, vector and matrix data types in shader;</li>
 * <li>new built-in functions to pack and unpack half float types into a 32-bit integer vector;</li>
 * <li>half float support for all existing single float built-in functions, including angle functions, exponential functions, common functions, geometric
 * functions, matrix functions and etc.;</li>
 * </ul>
 * 
 * <p>This extension is designed to be a functional superset of the half-precision floating-point support from NV_gpu_shader5 and to keep source code
 * compatible with that, thus the new procedures, functions, and tokens are identical to those found in that extension.</p>
 * 
 * <p>Requires {@link GL40 OpenGL 4.0} and GLSL 4.00.</p>
 */
public final class AMDGPUShaderHalfFloat {

    /** Returned by the {@code type} parameter of GetActiveAttrib, GetActiveUniform, and GetTransformFeedbackVarying. */
    public static final int
        GL_FLOAT16_MAT2_AMD   = 0x91C5,
        GL_FLOAT16_MAT3_AMD   = 0x91C6,
        GL_FLOAT16_MAT4_AMD   = 0x91C7,
        GL_FLOAT16_MAT2x3_AMD = 0x91C8,
        GL_FLOAT16_MAT2x4_AMD = 0x91C9,
        GL_FLOAT16_MAT3x2_AMD = 0x91CA,
        GL_FLOAT16_MAT3x4_AMD = 0x91CB,
        GL_FLOAT16_MAT4x2_AMD = 0x91CC,
        GL_FLOAT16_MAT4x3_AMD = 0x91CD;

    private AMDGPUShaderHalfFloat() {}

}
package pipelineexecution

import (
	"context"
	"github.com/rancher/norman/controller"
	"github.com/rancher/rancher/pkg/controllers/user/pipeline/engine"
	"github.com/rancher/rancher/pkg/controllers/user/pipeline/utils"
	"github.com/rancher/rancher/pkg/ticker"
	"github.com/rancher/types/apis/management.cattle.io/v3"
	"github.com/sirupsen/logrus"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	"time"
)

const (
	syncStateInterval = 5 * time.Second
)

//ExecutionStateSyncer is responsible for updating pipeline execution states
//by syncing with the pipeline engine
type ExecutionStateSyncer struct {
	clusterName           string
	clusterPipelineLister v3.ClusterPipelineLister

	pipelineLister          v3.PipelineLister
	pipelines               v3.PipelineInterface
	pipelineExecutionLister v3.PipelineExecutionLister
	pipelineExecutions      v3.PipelineExecutionInterface
	pipelineEngine          engine.PipelineEngine
}

func (s *ExecutionStateSyncer) sync(ctx context.Context, syncInterval time.Duration) {
	for range ticker.Context(ctx, syncInterval) {
		s.syncState()
	}

}

func (s *ExecutionStateSyncer) syncState() {
	if !utils.IsPipelineDeploy(s.clusterPipelineLister, s.clusterName) {
		return
	}

	set := labels.Set(map[string]string{utils.PipelineFinishLabel: "false"})
	allExecutions, err := s.pipelineExecutionLister.List("", set.AsSelector())
	if err != nil {
		logrus.Errorf("Error listing PipelineExecutions - %v", err)
		return
	}
	executions := []*v3.PipelineExecution{}
	for _, e := range allExecutions {
		if controller.ObjectInCluster(s.clusterName, e) {
			executions = append(executions, e)
		}
	}
	if len(executions) < 1 {
		return
	}
	if err := s.pipelineEngine.PreCheck(); err != nil {
		//fail to connect engine, mark the remaining executions as failed
		logrus.Errorf("Error get Jenkins engine - %v", err)
		for _, e := range executions {
			e.Status.ExecutionState = utils.StateFail
			v3.PipelineExecutionConditonProvisioned.False(e)
			v3.PipelineExecutionConditonProvisioned.ReasonAndMessageFromError(e, err)
			if err := s.updateExecutionAndLastRunState(e); err != nil {
				logrus.Errorf("Error update pipeline execution - %v", err)
				return
			}
		}
		return
	}
	for _, e := range executions {
		if e.Status.ExecutionState == utils.StateWaiting || e.Status.ExecutionState == utils.StateBuilding {
			updated, err := s.pipelineEngine.SyncExecution(e)
			if err != nil {
				logrus.Errorf("Error sync pipeline execution - %v", err)
				e.Status.ExecutionState = utils.StateFail
				v3.PipelineExecutionConditonProvisioned.False(e)
				v3.PipelineExecutionConditonProvisioned.ReasonAndMessageFromError(e, err)
				updated = true
			}
			if updated {
				if err := s.updateExecutionAndLastRunState(e); err != nil {
					logrus.Errorf("Error update pipeline execution - %v", err)
					return
				}
			}
		} else {
			if err := s.updateExecutionAndLastRunState(e); err != nil {
				logrus.Errorf("Error update pipeline execution - %v", err)
				return
			}
		}
	}
	logrus.Debugf("Sync pipeline execution state complete")
}

func (s *ExecutionStateSyncer) updateExecutionAndLastRunState(execution *v3.PipelineExecution) error {
	if execution.Status.ExecutionState != utils.StateWaiting && execution.Status.ExecutionState != utils.StateBuilding {
		execution.Labels[utils.PipelineFinishLabel] = "true"
	}
	if _, err := s.pipelineExecutions.Update(execution); err != nil {
		return err
	}

	//check and update lastrunstate of the pipeline when necessary
	p, err := s.pipelineLister.Get(execution.Spec.Pipeline.Namespace, execution.Spec.Pipeline.Name)
	if apierrors.IsNotFound(err) {
		logrus.Warningf("pipeline of execution '%s' is not found", execution.Name)
		return nil
	} else if err != nil {
		return err
	}

	if p.Status.LastExecutionID == execution.Namespace+":"+execution.Name &&
		p.Status.LastRunState != execution.Status.ExecutionState {
		p.Status.LastRunState = execution.Status.ExecutionState
		if _, err := s.pipelines.Update(p); err != nil {
			return err
		}
	}
	return nil
}

### [CVE-2006-4327](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-4327)
![](https://img.shields.io/static/v1?label=Product&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Version&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Vulnerability&message=n%2Fa&color=brighgreen)

### Description

Multiple cross-site scripting (XSS) vulnerabilities in add_url.php in CloudNine Interactive Links Manager 2006-06-12 allow remote attackers to inject arbitrary web script or HTML via the (1) title, (2) description, or (3) keywords parameters.

### POC

#### Reference
- http://evuln.com/vulns/136/description.html

#### Github
No PoCs found on GitHub currently.


package io.github.yannici.bedwars.Listener;

import java.util.List;

import io.github.yannici.bedwars.Main;
import io.github.yannici.bedwars.Game.Game;
import io.github.yannici.bedwars.Game.GameState;

import org.bukkit.event.EventHandler;
import org.bukkit.event.weather.WeatherChangeEvent;

public class WeatherListener extends BaseListener {

	public WeatherListener() {
		super();
	}

	@EventHandler
	public void onWeatherEvent(WeatherChangeEvent we) {
	    if(we.isCancelled()) {
	        return;
	    }
	    
	    List<Game> games = Main.getInstance().getGameManager().getGamesByWorld(we.getWorld());
	    
	    if(games.size() == 0) {
	        return;
	    }
	    
	    for(Game game : games) {
	    	if(game.getState() == GameState.STOPPED) {
		        continue;
		    }
	    	
	    	we.setCancelled(true);
	    	return;
	    }
	}

}

package uoc.cbonache.tfg.ui.shippingMap

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.os.Build
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.drawable.DrawableCompat
import android.view.ViewGroup
import uoc.cbonache.tfg.R
import uoc.cbonache.tfg.ui.ManagePermissions
import uoc.cbonache.tfg.ui.Navigator
import uoc.cbonache.tfg.ui.base.BaseActivity
import uoc.cbonache.tfg.ui.model.ShippingViewEntity
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.MapFragment
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.PolylineOptions
import org.jetbrains.anko.contentView
import javax.inject.Inject

/**
 * @author cbonache
 */
class ShippingMapActivity: BaseActivity(), ShippingMapView, OnMapReadyCallback {


    companion object {

        const val CODE = "code"
        @JvmStatic
        fun getIntent(context: Context): Intent {
            return Intent(context, ShippingMapActivity::class.java)
        }
    }

    @Inject lateinit var presenter: ShippingMapPresenter
    @Inject lateinit var managePermissions: ManagePermissions
    @Inject lateinit var navigator: Navigator
    lateinit var locationManager: LocationManager
    lateinit var mapFragment: MapFragment
    lateinit var googleMap: GoogleMap
    lateinit var geocoder: Geocoder
    lateinit var shippingDestination: String

    override fun onRequestLayout(): Int {
        return R.layout.activity_shipping_map
    }

    override fun onViewLoaded() {
        val code = intent.extras.get(CODE) as String
        setUpActionBar()
        presenter.onStart(code)
    }

    override fun showMap() {

        if (googleServicesAvailable()) {
            mapFragment = fragmentManager.findFragmentById(R.id.frame_map) as MapFragment
            mapFragment.getMapAsync(this)
        }
    }

    override fun drawPolyline(polyOptions: PolylineOptions) {

        googleMap.addPolyline(polyOptions)

        setUpMapClick()
    }

    private fun setUpMapClick() {

        googleMap.setOnMapLongClickListener {
            presenter.onClickMap()
        }
    }

    @SuppressLint("MissingPermission")
    override fun getCurrentLocation(): Location? {
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
    }

    override fun getDestination(): String {
        return shippingDestination
    }

    override fun navigateToGoogleMaps() {

        navigator.navigateToGoogleMapsApps(this, shippingDestination)
    }

    private fun googleServicesAvailable(): Boolean {

        val api = GoogleApiAvailability.getInstance()
        val isAvailable = api.isGooglePlayServicesAvailable(this)
        return isAvailable == ConnectionResult.SUCCESS
    }


    private fun setUpActionBar() {

        supportActionBar?.apply {
            title = getString(R.string.shipping_map)
            setDisplayHomeAsUpEnabled(true)
            setDisplayShowHomeEnabled(true)
        }
    }

    override fun showShippingInfo(shippingViewEntity: ShippingViewEntity) {
        shippingDestination = shippingViewEntity.address + " " + shippingViewEntity.cp + " " + shippingViewEntity.city + " " + shippingViewEntity.country
    }

    override fun requestLocationPermission() {

        val permissionsMessage = getString(R.string.permissions_location_message)
        val listener =
                managePermissions.setAllPermissionsListener(this,
                        contentView as ViewGroup, permissionsMessage, { presenter.onLocationPermissionGranted() })
        managePermissions.setRequestPermissions(this, arrayListOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), listener)
    }

    override fun onMapReady(googleMap: GoogleMap) {

        this.googleMap = googleMap
        geocoder = Geocoder(this)
        goToLocation(15f)
        presenter.onMapReady(this)

    }


    private fun goToLocation(zoom: Float) {

        val address = geocoder.getFromLocationName(shippingDestination, 1)
        val it = address.first()
        val ll = LatLng(it.latitude, it.longitude)
        val updateCamera = CameraUpdateFactory.newLatLngZoom(ll, zoom)

        googleMap.moveCamera(updateCamera)
        googleMap.addMarker(MarkerOptions().position(ll))
    }

    override fun showLocation(currentLocation: Location?) {

        currentLocation?.let {
            val latlng = LatLng(currentLocation.latitude, currentLocation.longitude)

            val bitmap = getBitmapFromVectorDrawable(this, R.drawable.ic_noun_814594_cc)
            googleMap.addMarker(MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(bitmap)))
        }
    }

    private fun getBitmapFromVectorDrawable(context: Context, drawableId: Int): Bitmap {
        var drawable = ContextCompat.getDrawable(context, drawableId)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            drawable = DrawableCompat.wrap(drawable).mutate()
        }

        val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth,
                drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)

        return bitmap
    }
}

package net.thinksquared.lilldep.struts;

/*******************************************************
* Creates a new Collection.
* author: Arnold Doray
* date: 19 Mar 2005
* version: 0.0
* Copyright 2005 Arnold Doray   
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
********************************************************/

import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import net.thinksquared.lilldep.database.*;

public final class NewCollectionAction extends Action implements JSPConstants{

    private final String QUERY_PREFIX = "SELECT CONTACT.CONTACT_ID,CONTACT.NAME,CONTACT.DESIGNATION,CONTACT.DEPARTMENT,CONTACT.EMAIL,CONTACT.TEL,CONTACT.FAX,CONTACT.COMPANY,CONTACT.ADDRESS,CONTACT.POSTCODE,CONTACT.COUNTRY,CONTACT.WEBSITE,CONTACT.ACTIVITY,CONTACT.CLASSIFICATION,CONTACT.MEMO, UPPER(CONTACT.COMPANY) AS UCOMPANY FROM CONTACT WHERE ";
    private final String QUERY_SUFFIX = " ORDER BY UCOMPANY";

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
    throws Exception{

            //YOUR IMPLEMENTATION HERE.

            //NOTE: The query passed to ContactPeer's doSelect()
            //      should be QUERY_PREFIX + query + QUERY_SUFFIX

            return null;//REMOVE!
        
    }

}



package org.imagearchive.lsm.toolbox;

import ij.IJ;
import ij.ImagePlus;
import ij.text.TextWindow;

import org.imagearchive.lsm.reader.info.ImageDirectory;
import org.imagearchive.lsm.reader.info.LSMFileInfo;
import org.imagearchive.lsm.toolbox.info.CZLSMInfoExtended;
import org.imagearchive.lsm.toolbox.info.EventList;
import org.imagearchive.lsm.toolbox.info.scaninfo.Recording;

public class StampUtils {
	public static String getTStamps(Reader reader, ImagePlus imp) {
		reader.updateMetadata(imp);
		LSMFileInfo openLSM = (LSMFileInfo) imp.getOriginalFileInfo();
		CZLSMInfoExtended cz = (CZLSMInfoExtended) ((ImageDirectory) openLSM.imageDirectories
				.get(0)).TIF_CZ_LSMINFO;
		int n = new Long(cz.timeStamps.NumberTimeStamps).intValue();
		String[] stamps = new String[n];
		for (int k = 0; k < n; k++)
			stamps[k] = Double.toString(cz.timeStamps.TimeStamps[k]);
		return implode(stamps);
	}

	public static String getZStamps(Reader reader, ImagePlus imp) {
		reader.updateMetadata(imp);
		LSMFileInfo openLSM = (LSMFileInfo) imp.getOriginalFileInfo();
		CZLSMInfoExtended cz = (CZLSMInfoExtended) ((ImageDirectory) openLSM.imageDirectories
				.get(0)).TIF_CZ_LSMINFO;
		Recording r = (Recording) cz.scanInfo.recordings.get(0);
		double planeSpacing = ((Double) r.records.get("PLANE_SPACING")).doubleValue();
		double ps = 0;
		String[] stamps = new String[(int) cz.DimensionZ];
		for (int k = 0; k < cz.DimensionZ; k++){
			stamps[k] = IJ.d2s(ps, 2) + " "+ MasterModel.micrometer;
			ps += planeSpacing;
		}
		return implode(stamps);
	}

	public static String getLStamps(Reader reader, ImagePlus imp) {
		reader.updateMetadata(imp);
		LSMFileInfo openLSM = (LSMFileInfo) imp.getOriginalFileInfo();
		CZLSMInfoExtended cz = (CZLSMInfoExtended) ((ImageDirectory) openLSM.imageDirectories
				.get(0)).TIF_CZ_LSMINFO;
		if (cz.SpectralScan != 1) {
			IJ
					.error("Image not issued from spectral scan. Lambda stamp obsolete!");
			return null;
		}
		String[] stamps = new String[(int) cz.channelWavelength.Channels];
		for (int k = 0; k < cz.channelWavelength.Channels; k++){
			stamps[k] = IJ.d2s(cz.channelWavelength.LambdaStamps[k], 2);

		}
		return implode(stamps);
	}

	public static String getEvents(Reader reader, ImagePlus imp) {
		reader.updateMetadata(imp);
		LSMFileInfo openLSM = (LSMFileInfo) imp.getOriginalFileInfo();
		CZLSMInfoExtended cz = (CZLSMInfoExtended) ((ImageDirectory) openLSM.imageDirectories
				.get(0)).TIF_CZ_LSMINFO;

		EventList events = cz.eventList;
		StringBuffer buffer = new StringBuffer();
		if (events != null) {
			buffer.append("Time (sec) \tEvent Type \tEvent Description");
			buffer.append(events.Description);
		}
		return buffer.toString();
	}

	private static String implode(String[] input) {
		String result;
		if (input.length == 0) {
			result = "";
		} else {
			StringBuffer sb = new StringBuffer();
			sb.append(input[0]);
			for (int i = 1; i < input.length; i++) {
				sb.append(",");
				sb.append(input[i]);
			}
			result = sb.toString();
		}
		return result;
	}


}
var jQuery = function(selector) {
    /* BEGIN arguments unpacking */
    /* END arguments unpacking */
    /* BEGIN function */
    var call_arguments0 = [jstype, selector];
    var call_arguments1 = [$, pythonium_call.apply(undefined, call_arguments0)];
    return pythonium_call.apply(undefined, call_arguments1);
    return __NONE;
};

var call_arguments2 = [jQuery, pythonium_call(str, '[type="text"]')];
input = pythonium_call.apply(undefined, call_arguments2);
var call_arguments3 = [jQuery, pythonium_call(str, '[type="submit"]')];
button = pythonium_call.apply(undefined, call_arguments3);
var call_arguments4 = [jQuery, pythonium_call(str, "#todos")];
todos = pythonium_call.apply(undefined, call_arguments4);
var add_todo = function(text) {
    /* BEGIN arguments unpacking */
    /* END arguments unpacking */
    var li;
    /* BEGIN function */
    li = (pythonium_call(pythonium_get_attribute((pythonium_call(pythonium_get_attribute(pythonium_call(str, "<li>"), "__add__"), text)), "__add__"), pythonium_call(str, "</li>")));
    var call_arguments5 = [jstype, li];
    li = pythonium_call.apply(undefined, call_arguments5);
    var call_arguments6 = [pythonium_get_attribute(todos, "append"), li];
    pythonium_call.apply(undefined, call_arguments6);
};

var on_click = function(event) {
    /* BEGIN arguments unpacking */
    /* END arguments unpacking */
    var text;
    /* BEGIN function */
    var call_arguments7 = [pythonium_get_attribute(input, "val")];
    var call_arguments8 = [str, pythonium_call.apply(undefined, call_arguments7)];
    text = pythonium_call.apply(undefined, call_arguments8);
    var call_arguments9 = [len, text];
    if (pythonium_is_true(pythonium_call.apply(undefined, call_arguments9))) {
        var call_arguments10 = [add_todo, text];
        pythonium_call.apply(undefined, call_arguments10);
    }
};

var call_arguments11 = [pythonium_get_attribute(button, "click"), on_click];
pythonium_call.apply(undefined, call_arguments11);

(defproject coldnew/best5 "0.1.0-SNAPSHOT"
  :description "Get the Taiwan's stock best5 data"
  :url "https://github.com/coldnew/twstock-best5.clj"
  :author "Yen-Chin, Lee"
  :license {:name "MIT License"
            :url "https://github.com/coldnew/twstock-best5.clj/blob/master/LICENSE"}
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [clj-http "3.7.0"]
                 [cheshire "5.8.0"]
                 [http-kit "2.3.0"]
                 [hickory "0.7.1"]
                 [clj-time "0.14.2"]
                 [datascript "0.16.3"]
                 [datascript-transit "0.2.2"]
                 [toucan "1.1.4"]
                 [yesql "0.5.3"]
                 [org.xerial/sqlite-jdbc "3.14.2.1"]
                 [com.layerware/hugsql "0.4.8"]]

  :source-paths ["src"]
  :test-paths ["test"]

  :main coldnew.best5.core
  :jvm-opts ["-Dclojure.compiler.direct-linking=true"
             "-XX:MaxDirectMemorySize=16g" "-XX:+UseLargePages"]

  :profiles {:uberjar
             {:source-paths ["src/clj"]
              :omit-source true
              :aot :all}})

﻿/*
 * Licensed to the SkyAPM under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The SkyAPM licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

using SkyApm.Tracing.Segments;

namespace SkyApm.Tracing
{
    public class CrossThreadCarrier : SegmentReference, ICarrier
    {
        public bool HasValue => true;

        public bool? Sampled { get; set; }
    }
}

import { _SystemTemplateFilter } from "./_SystemTemplateFilter";
import { NodeHttpOptions as __HttpOptions__ } from "@aws-sdk/types";
import * as __aws_sdk_types from "@aws-sdk/types";

/**
 * SearchSystemTemplatesInput shape
 */
export interface SearchSystemTemplatesInput {
  /**
   * <p>An array of filters that limit the result set. The only valid filter is <code>FLOW_TEMPLATE_ID</code>.</p>
   */
  filters?: Array<_SystemTemplateFilter> | Iterable<_SystemTemplateFilter>;

  /**
   * <p>The string that specifies the next page of results. Use this when you're paginating results.</p>
   */
  nextToken?: string;

  /**
   * <p>The maximum number of results to return in the response.</p>
   */
  maxResults?: number;

  /**
   * The maximum number of times this operation should be retried. If set, this value will override the `maxRetries` configuration set on the client for this command.
   */
  $maxRetries?: number;

  /**
   * An object that may be queried to determine if the underlying operation has been aborted.
   *
   * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
   */
  $abortSignal?: __aws_sdk_types.AbortSignal;

  /**
   * Per-request HTTP configuration options. If set, any options specified will override the corresponding HTTP option set on the client for this command.
   */
  $httpOptions?: __HttpOptions__;
}

#! /usr/bin/env python

"""
 *******************************************************************************
 * 
 * $Id: SecureDocXMLRPCServer.py 4 2008-06-04 18:44:13Z yingera $
 * $URL: https://xxxxxx/repos/utils/trunk/tools/SVNRPCServer.py $
 *
 * $Date: 2008-06-04 13:44:13 -0500 (Wed, 04 Jun 2008) $
 * $Author: yingera $
 *
 * Authors: Laszlo Nagy, Andrew Yinger
 *
 * Description: Threaded, Documenting SecureDocXMLRPCServer.py - over HTTPS.
 *
 *  requires pyOpenSSL: http://sourceforge.net/project/showfiles.php?group_id=31249
 *   ...and open SSL certs installed.
 *
 * Based on this article: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549
 *
 *******************************************************************************
"""

import SocketServer
import BaseHTTPServer
import SimpleHTTPServer
import SimpleXMLRPCServer

import socket, os
from OpenSSL import SSL
from threading import Event, currentThread, Thread, Condition
from thread import start_new_thread as start
from DocXMLRPCServer import DocXMLRPCServer, DocXMLRPCRequestHandler

# static stuff
DEFAULTKEYFILE='key.pem'    # Replace with your PEM formatted key file
DEFAULTCERTFILE='certificate.crt'  # Replace with your PEM formatted certificate file


class SecureDocXMLRpcRequestHandler(DocXMLRPCRequestHandler):
    """Secure Doc XML-RPC request handler class.
    It it very similar to DocXMLRPCRequestHandler but it uses HTTPS for transporting XML data.
    """
    def setup(self):
        self.connection = self.request
        self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
        self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)

    def address_string(self):
        "getting 'FQDN' from host seems to stall on some ip addresses, so... just (quickly!) return raw host address"
        host, port = self.client_address
        #return socket.getfqdn(host)
        return host

    def do_POST(self):
        """Handles the HTTPS POST request.
        It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
        """
        try:
            # get arguments
            data = self.rfile.read(int(self.headers["content-length"]))
            # In previous versions of SimpleXMLRPCServer, _dispatch
            # could be overridden in this class, instead of in
            # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
            # check to see if a subclass implements _dispatch and dispatch
            # using that method if present.
            response = self.server._marshaled_dispatch(data, getattr(self, '_dispatch', None))
        except: # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            self.send_response(500)
            self.end_headers()
        else:
            # got a valid XML RPC response
            self.send_response(200)
            self.send_header("Content-type", "text/xml")
            self.send_header("Content-length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)

            # shut down the connection
            self.wfile.flush()
            self.connection.shutdown() # Modified here!

    def do_GET(self):
        """Handles the HTTP GET request.

        Interpret all HTTP GET requests as requests for server
        documentation.
        """
        # Check that the path is legal
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        response = self.server.generate_html_documentation()
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)

        # shut down the connection
        self.wfile.flush()
        self.connection.shutdown() # Modified here!

    def report_404 (self):
        # Report a 404 error
        self.send_response(404)
        response = 'No such page'
        self.send_header("Content-type", "text/plain")
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)
        # shut down the connection
        self.wfile.flush()
        self.connection.shutdown() # Modified here!



class CustomThreadingMixIn:
    """Mix-in class to handle each request in a new thread."""
    # Decides how threads will act upon termination of the main process
    daemon_threads = True

    def process_request_thread(self, request, client_address):
        """Same as in BaseServer but as a thread.
        In addition, exception handling is done here.
        """
        try:
            self.finish_request(request, client_address)
            self.close_request(request)
        except (socket.error, SSL.SysCallError), why:
            print 'socket.error finishing request from "%s"; Error: %s' % (client_address, str(why))
            self.close_request(request)
        except:
            self.handle_error(request, client_address)
            self.close_request(request)

    def process_request(self, request, client_address):
        """Start a new thread to process the request."""
        t = Thread(target = self.process_request_thread, args = (request, client_address))
        if self.daemon_threads:
            t.setDaemon(1)
        t.start()



class SecureDocXMLRPCServer(CustomThreadingMixIn, DocXMLRPCServer):
    def __init__(self, registerInstance, server_address, keyFile=DEFAULTKEYFILE, certFile=DEFAULTCERTFILE, logRequests=True):
        """Secure Documenting XML-RPC server.
        It it very similar to DocXMLRPCServer but it uses HTTPS for transporting XML data.
        """
        DocXMLRPCServer.__init__(self, server_address, SecureDocXMLRpcRequestHandler, logRequests)
        self.logRequests = logRequests

        # stuff for doc server
        try: self.set_server_title(registerInstance.title)
        except AttributeError: self.set_server_title('default title')
        try: self.set_server_name(registerInstance.name)
        except AttributeError: self.set_server_name('default name')
        if registerInstance.__doc__: self.set_server_documentation(registerInstance.__doc__)
        else: self.set_server_documentation('default documentation')
        self.register_introspection_functions()

        # init stuff, handle different versions:
        try:
            SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self)
        except TypeError:
            # An exception is raised in Python 2.5 as the prototype of the __init__
            # method has changed and now has 3 arguments (self, allow_none, encoding)
            SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self, False, None)
        SocketServer.BaseServer.__init__(self, server_address, SecureDocXMLRpcRequestHandler)
        self.register_instance(registerInstance) # for some reason, have to register instance down here!

        # SSL socket stuff
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file(keyFile)
        ctx.use_certificate_file(certFile)
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
        self.server_bind()
        self.server_activate()

        # requests count and condition, to allow for keyboard quit via CTL-C
        self.requests = 0
        self.rCondition = Condition()


    def startup(self):
        'run until quit signaled from keyboard...'
        print 'server starting; hit CTRL-C to quit...'
        while True:
            try:
                self.rCondition.acquire()
                start(self.handle_request, ()) # we do this async, because handle_request blocks!
                while not self.requests:
                    self.rCondition.wait(timeout=3.0)
                if self.requests: self.requests -= 1
                self.rCondition.release()
            except KeyboardInterrupt:
                print "quit signaled, i'm done."
                return

    def get_request(self):
        request, client_address = self.socket.accept()
        self.rCondition.acquire()
        self.requests += 1
        self.rCondition.notifyAll()
        self.rCondition.release()
        return (request, client_address)

    def listMethods(self):
        'return list of method names (strings)'
        methodNames = self.funcs.keys()
        methodNames.sort()
        return methodNames

    def methodHelp(self, methodName):
        'method help'
        if methodName in self.funcs:
            return self.funcs[methodName].__doc__
        else:
            raise Exception('method "%s" is not supported' % methodName)



def TestSampleServer():
    """Test xml rpc over https server"""
    class ExampleRegisters:
        '''just some test methods to try out new secure doc xml-rpc server...'''
        title = 'test server methods'
        name = 'test server'
        def __init__(self):
            import string
            self.python_string = string
            
        def add(self, x, y):
            return x + y
    
        def mult(self,x,y):
            return x*y
    
        def div(self,x,y):
            return x//y

        def poop(self): return 'poop'
        
    server_address = (socket.gethostname(), 9779) # (address, port)
    server = SecureDocXMLRPCServer(ExampleRegisters(), server_address, DEFAULTKEYFILE, DEFAULTCERTFILE)    
    sa = server.socket.getsockname()
    print "Serving HTTPS on", sa[0], "port", sa[1]
    server.startup()


if __name__ == '__main__':
    TestSampleServer()


# Here is an xmlrpc client for testing:
"""
import xmlrpclib

server = xmlrpclib.Server('https://localhost:9777')
print server.add(1,2)
print server.div(10,4)
"""

const salaryInformation = [
  {
    type: 'select',
    name: 'currency_typeSalary',
    label: 'Salary Amount',
    placeholder: '',
    twocol: false,
    colWidth: '0 1 118px',

    options: [{ value: 'RM', label: 'RM' }],
  },
  {
    type: 'input',
    name: 'salary_amount',
    label: '',
    placeholder: 'Amount',
    twocol: false,
    req: true,
    reqmessage: 'Please enter amount',
    colWidth: '1 0 180px',
  },
  {
    type: 'select',
    name: 'payment_method',
    label: 'Payment Method',
    placeholder: 'Select Payment Method',
    twocol: true,
    req: true,
    reqmessage: 'Payment method required',
    options: [
      { value: 'Automatic Payment System (APS)', label: 'Automatic Payment System (APS)' },
      { value: 'Cash', label: 'Cash' },
      { value: 'Cheque', label: 'Cheque' },
    ],
  },
  {
    type: 'select',
    name: 'payment_frequency',
    label: 'Payment Frequency',
    placeholder: '',
    twocol: true,
    req: true,
    reqmessage: 'Payment frequency required',
    options: [
      { value: 'Daily', label: 'Daily' },
      { value: 'Weekly', label: 'Weekly' },
      { value: 'Biweekly', label: 'Biweekly' },
      { value: 'Monthly', label: 'Monthly' },
      { value: 'Quarterly', label: 'Quarterly' },
      { value: 'Annually', label: 'Annually' },
    ],
  },
  {
    type: 'select',
    name: 'payment_type',
    label: 'Payment Type',
    placeholder: '',
    twocol: true,
    options: [
      { value: 'Recurring', label: 'Recurring' },
      { value: 'Once', label: 'Once' },
    ],
  },
  {
    type: 'date',
    name: 'effective_date',
    label: 'Effective Date',
    placeholder: 'Please Select',
    twocol: true,
  },
  {
    type: 'select',
    name: 'tax_currency_type',
    label: 'Tax Ammount',
    placeholder: '',
    twocol: false,
    colWidth: '0 1 118px',
    options: [{ value: 'RM', label: 'RM' }],
  },
  {
    type: 'input',
    name: 'tax_amount',
    label: '',
    placeholder: '',
    twocol: false,
    colWidth: '1 0 180px',
  },
];

export { salaryInformation };

---
title: "ETW Tracing"
ms.date: "03/30/2017"
ms.assetid: ac99a063-e2d2-40cc-b659-d23c2f783f92
---
# ETW Tracing
This sample demonstrates how to implement End-to-End (E2E) tracing using Event Tracing for Windows (ETW) and the `ETWTraceListener` that is provided with this sample. The sample is based on the [Getting Started](../../../../docs/framework/wcf/samples/getting-started-sample.md) and includes ETW tracing.  
  
> [!NOTE]
> The set-up procedure and build instructions for this sample are located at the end of this topic.  
  
 This sample assumes that you are familiar with [Tracing and Message Logging](../../../../docs/framework/wcf/samples/tracing-and-message-logging.md).  
  
 Each trace source in the <xref:System.Diagnostics> tracing model can have multiple trace listeners that determine where and how the data is traced. The type of listener defines the format in which trace data is logged. The following code sample shows how to add the listener to configuration.  
  
```xml  
<system.diagnostics>  
    <sources>  
        <source name="System.ServiceModel"   
             switchValue="Verbose,ActivityTracing"  
             propagateActivity="true">  
            <listeners>  
                <add type=  
                   "System.Diagnostics.DefaultTraceListener"  
                   name="Default">  
                   <filter type="" />  
                </add>  
                <add name="ETW">  
                    <filter type="" />  
                </add>  
            </listeners>  
        </source>  
    </sources>  
    <sharedListeners>  
        <add type=  
            "Microsoft.ServiceModel.Samples.EtwTraceListener, ETWTraceListener"  
            name="ETW" traceOutputOptions="Timestamp">  
            <filter type="" />  
       </add>  
    </sharedListeners>  
</system.diagnostics>  
```  
  
 Before using this listener, an ETW Trace Session must be started. This session can be started by using Logman.exe or Tracelog.exe. A SetupETW.bat file is included with this sample so that you can set up the ETW Trace Session along with a CleanupETW.bat file for closing the session and completing the log file.  
  
> [!NOTE]
> The setup procedure and build instructions for this sample are located at the end of this topic. For more information about these tools, see <https://go.microsoft.com/fwlink/?LinkId=56580>  
  
 When using the ETWTraceListener, traces are logged in binary .etl files. With ServiceModel tracing turned on, all generated traces appear in the same file. Use [Service Trace Viewer Tool (SvcTraceViewer.exe)](../../../../docs/framework/wcf/service-trace-viewer-tool-svctraceviewer-exe.md) for viewing .etl and .svclog log files. The viewer creates an end-to-end view of the system that makes it possible to trace a message from its source to its destination and point of consumption.  
  
 The ETW Trace Listener supports circular logging. To enable this feature, go to **Start**, **Run** and type `cmd` to start a command console. In the following command, replace the `<logfilename>` parameter with the name of your log file.  
  
```console  
logman create trace Wcf -o <logfilename> -p "{411a0819-c24b-428c-83e2-26b41091702e}" -f bincirc -max 1000  
```  
  
 The `-f` and `-max` switches are optional. They specify the binary circular format and max log size of 1000MB respectively. The `-p` switch is used to specify the trace provider. In our example, `"{411a0819-c24b-428c-83e2-26b41091702e}"` is the GUID for "XML ETW Sample Provider".  
  
 To start the session, type in the following command.  
  
```console  
logman start Wcf  
```  
  
 After you have finished logging, you can stop the session with the following command.  
  
```console  
logman stop Wcf  
```  
  
 This process generates binary circular logs that you can process with your tool of choice, including [Service Trace Viewer Tool (SvcTraceViewer.exe)](../../../../docs/framework/wcf/service-trace-viewer-tool-svctraceviewer-exe.md) or Tracerpt.  
  
 You can also review the [Circular Tracing](../../../../docs/framework/wcf/samples/circular-tracing.md) sample for more information on an alternative listener to perform circular logging.  
  
### To set up, build, and run the sample  
  
1. Be sure you have performed the [One-Time Setup Procedure for the Windows Communication Foundation Samples](../../../../docs/framework/wcf/samples/one-time-setup-procedure-for-the-wcf-samples.md).  
  
2. To build the solution, follow the instructions in [Building the Windows Communication Foundation Samples](../../../../docs/framework/wcf/samples/building-the-samples.md).  
  
    > [!NOTE]
    > To use the RegisterProvider.bat, SetupETW.bat and CleanupETW.bat commands, you must run under a local administrator account. If you are using [!INCLUDE[wv](../../../../includes/wv-md.md)] or later, you must also run the command prompt with elevated privileges. To do so, right-click the command prompt icon, then click **Run as administrator**.  
  
3. Before running the sample, run RegisterProvider.bat on the client and server. This sets up the resulting ETWTracingSampleLog.etl file to generate traces that can be read by the Service Trace Viewer. This file can be found in the C:\logs folder. If this folder does not exist, it must be created or no traces are generated. Then, run SetupETW.bat on the client and server computers to begin the ETW Trace Session. The SetupETW.bat file can be found under the CS\Client folder.  
  
4. To run the sample in a single- or cross-computer configuration, follow the instructions in [Running the Windows Communication Foundation Samples](../../../../docs/framework/wcf/samples/running-the-samples.md).  
  
5. When the sample is completed, run CleanupETW.bat to complete the creation of the ETWTracingSampleLog.etl file.  
  
6. Open the ETWTracingSampleLog.etl file from within the Service Trace Viewer. You will be prompted to save the binary formatted file as a .svclog file.  
  
7. Open the newly created .svclog file from within the Service Trace Viewer to view the ETW and ServiceModel traces.  
  
> [!IMPORTANT]
> The samples may already be installed on your computer. Check for the following (default) directory before continuing.  
>   
> `<InstallDrive>:\WF_WCF_Samples`  
>   
> If this directory does not exist, go to [Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4](https://go.microsoft.com/fwlink/?LinkId=150780) to download all Windows Communication Foundation (WCF) and [!INCLUDE[wf1](../../../../includes/wf1-md.md)] samples. This sample is located in the following directory.  
>   
> `<InstallDrive>:\WF_WCF_Samples\WCF\Basic\Management\AnalyticTrace`  
  
## See also

- [AppFabric Monitoring Samples](https://go.microsoft.com/fwlink/?LinkId=193959)

﻿// <Snippet1>
using System;
using System.Reflection;

class Class1
{
    public static void Main()
    {
        // You must supply a valid fully qualified assembly name.
        Assembly SampleAssembly = Assembly.Load
		    ("SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3");
        // Display all the types contained in the specified assembly.
		foreach (Type oType in SampleAssembly.GetTypes()) {
            Console.WriteLine(oType.Name);
        }
    }
}
// </Snippet1>
""" PostProcessorBase.py

Base class for the post processor classes """

# Imports
import xlsxwriter

class PostProcessorBase:
    def __init__(self, inputFileName, outputFileName, logDate):
        """Constructor"""
        # Initialize variables
        self.inputFile = open(inputFileName, "r")
        self.outputFile = xlsxwriter.Workbook(outputFileName)
        self.logDate = logDate
    
    def DetermineChartRows(self, hourOffsets, startHour, endHour):
        """Determine the chart rows that correspond to the hour span"""
        startRow = -1
        endRow = -1
        for hour in range(startHour, endHour):
            if hourOffsets[hour] != -1:
                if hour < (endHour - 1):
                    if startRow == -1:
                        startRow = hourOffsets[hour]
                    endRow = hourOffsets[hour]
                else:
                    endRow = hourOffsets[hour] - 1
        return (startRow, endRow)
    
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AjaxCallController extends BaseController
{
    public function TextBox(Request $request){
        $number = $request->number;

        $html = "<table>";
        for($i = 1; $i <= $number; $i++) {
            $html .= '<tr style="padding:5px;"><td><input type="text" id="'.($i+$i).'" placeholder="Enter left value"> &nbsp;&nbsp;<input type="text" id="'.($i+$i+$i).'" placeholder="Enter right value"> &nbsp;&nbsp;<button class="btn btn-success" onclick="function_'.$i.'($(this))">Submit</button></td>&nbsp;&nbsp;&nbsp;&nbsp;<td><span style="
    padding: 37px;font-weight:bold;font-size:25px;
" id="'.($i+$i+$i+$i+$i).'"></span></td></tr>';  
        }
        $html .= "</table><script>";

        for($j = 1; $j <= $number; $j++) {
            $tot = ($j+$j+$j);
            $tot1 = ($j+$j);
            $tot2 = ($j+$j+$j+$j+$j);
            // $attr = "input[]";
            $html .= "function function_$j(This){ 
                var lowerNumber = $('#$tot1').val(); 
                var higherNumber = $('#$tot').val(); 
                var primenumber = [];
                var pushprin = [];
                for (let i = lowerNumber; i <= higherNumber; i++) {
                    let flag = 0;
                    for (let j = 2; j < i; j++) {
                        if (i % j == 0) {
                            flag = 1;
                            break;
                        }
                    }
                    if (i > 1 && flag == 0) {
                        primenumber.push(i);
                    }
                }

                var number1 = 0; 
                var number2 = 0; 
                $.each(primenumber, function(index, value){
                    if(index == 0){
                        number1 = value;
                    }
                    number2 = value;

                });
                var num3 = number2 - number1;
                $('#$tot2').html(num3);
            }";
        }
        $html .= "</script>";
        return response()->json($html,200);

    }
}

% simpleConeReflectanceModel  Compute reflectance versus time for a swelling cone
%
% Description:
%   Very simple calculation of how light reflected from a cone varies with
%   cone length, taking into account both incoherent reflection and
%   interference between coherent component of light.
%
%   Based on a very simple model where there are two reflecting surfaces.  Light
%   reflects from each surface and interferes at the source side of the first surface.
%
%   The fraction of coherent (interfering) versus incoherent light is simply specified,
%   not computed.  Adding this computation would be a good extension.
%
%   The model has a number of parameters that have physical analogs. These
%   are set and commented in the code below.
%
% Notes:
% * [NOTE: DHB - I tried to understand coherence length from the web. In some places it
%   is defined a length at which phase is totally random.  In others, a
%   more graded definition is used.  We need to understand which the one we
%   calculate represents, if we are to add coherence length into this
%   cacluation.]
%

% History:
%   10/28/17  dhb  Wrote it.

%% Clear
clear; close all;

%% Parameters
%
% Imaging light wavelength
firstLightWavelengthNm = 720;
secondLightWavelengthNm = 1.25*firstLightWavelengthNm; % 850;
refractiveIndex1 = 1.331;
refractiveIndex2 = 1.328;

% Number of cones to simulate
nCones = 400;

% Length between reflecting surfaces
reflectingSurfaceDifferenceNm1 = 10*1e3;
reflectingSurfaceDifferenceNm2 = 7*1e3;

% How much variation in the starting length between surfces is there
% across cones (or trials within measurements for one cone), experessed as a
% fraction of the length between the two reflecting surfaces.
reflectingSurfaceRandomizationFraction = 0.1;

% Maximum length change between reflecting surfaces,
% in response to stimulus.
maxDeltaLengthNm = 150;

% What fraction of a full half sinusoid does length vary over
% in response to a stimulus, and how much trial-to-trial jitter
% is there in that fraction.
%
% Set the fraction to 1 if you think what happens is that the cone
% swells and then contracts to about its original length.  Set the
% fraction to 0.5 if you think it swells and then sits at the swollen
% length over the relevant time frame of the experiment.
%
% The randomization is also expressed as a fraction of the full half
% sinusoid
halfSinusoidFraction = 0.8;
halfSinusoidFractionRandomizationFraction = 0.5;

% Time in seconds for stimulus to have its effect. This just puts
% a time axis on the plots.
stimEffectTimeSecs = 4;

% Number sampling timepoints for simulation of what happens on a trial
nDeltaLengths = 100;
theDeltaTimesSecs = linspace(0,stimEffectTimeSecs,nDeltaLengths);

% Fraction of light reflected from the first and second surfaces.  Model below
% assumes that light not reflected from first surface is transmitted, and
% that light reflected from the second surface passes through the first
% surface both on the way in and on the way out.
firstSurfaceReflectance = 0.2;
secondSurfaceReflectance = 0.4;
thirdSurfaceReflectance = 0.4;

% Coherent fraction
%
% This depends on coherence length relative relative to distance between
% reflecting surfaces Here just making it up, because I don't really
% understand coherence length.
coherentFraction = 0.5;

%% Get intensities of light coming back from each surface
%
% This is calculated at the source side of the first surface; the light
% from the second surface goes through the first surface twice.
firstSurfaceIntensity = firstSurfaceReflectance;
secondSurfaceIntensity = (1-firstSurfaceReflectance)^2*secondSurfaceReflectance;

%% Different starting lengths, drawn at random from a uniform distribution
%
% Distribution is centered on the assumed length
randValues = rand(1,nCones);
theStartingDeltas = reflectingSurfaceRandomizationFraction*reflectingSurfaceDifferenceNm1*(randValues-0.5);

%% Set first phase to 0 without loss of generality
phase0 = 0;

%% Loop over cones/trials
for jj = 1:nCones
    % For each, we choose a random starting length and compute the
    % interferece effect. We also choose a random excursion, jittered
    % around a half sinusoid
    %
    % Get delta lengths as a function of time.
    theDeltaLengthsNm{jj} = maxDeltaLengthNm*sin(halfSinusoidFraction*(1+halfSinusoidFractionRandomizationFraction*(rand(1,1)-0.5))*pi*(0:nDeltaLengths-1)/nDeltaLengths);
    for ii = 1:nDeltaLengths
        
        % Get starting distance between surfaces for this cone, and compute phase of
        % second light at the point of interference.
        distanceNm1(jj,ii) = reflectingSurfaceDifferenceNm1 + theStartingDeltas(jj) + theDeltaLengthsNm{jj}(ii);
        distanceNm2(jj,ii) = reflectingSurfaceDifferenceNm2 + theStartingDeltas(jj) + theDeltaLengthsNm{jj}(ii);

        phaseWl1Sur1(jj,ii) = 2*pi*(2*distanceNm1(jj,ii))*refractiveIndex1/firstLightWavelengthNm;
        phaseWl2Sur1(jj,ii) = 2*pi*(2*distanceNm1(jj,ii))*refractiveIndex2/secondLightWavelengthNm;
        
        phaseWl1Sur2(jj,ii) = 2*pi*(2*distanceNm2(jj,ii))*refractiveIndex1/firstLightWavelengthNm;
        phaseWl2Sur2(jj,ii) = 2*pi*(2*distanceNm2(jj,ii))*refractiveIndex2/secondLightWavelengthNm;
        
        % Get amplitude of coherent component of reflected light, taking interference
        % into account.
        %
        % Formula from Hecht, Optics, 3rd ed, p. 291
        coherentAmplitude1(jj,ii) = sqrt(...
            firstSurfaceIntensity^2 + secondSurfaceIntensity^2 + ...
            2*firstSurfaceIntensity*secondSurfaceIntensity*cos(phase0-phaseWl1Sur1(jj,ii)));
        coherentAmplitude2(jj,ii) = sqrt(...
            firstSurfaceIntensity^2 + secondSurfaceIntensity^2 + ...
            2*firstSurfaceIntensity*secondSurfaceIntensity*cos(phase0-phaseWl2Sur1(jj,ii)));
        
        % Put together coherent and incoherent reflected light to get
        % intensity of total reflected light.  This is a model of what
        % we measure.
        totalAmplitude1(jj,ii) = coherentFraction*coherentAmplitude1(jj,ii) + (1-coherentFraction)*(firstSurfaceIntensity + secondSurfaceIntensity);
        totalAmplitude2(jj,ii) = coherentFraction*coherentAmplitude2(jj,ii) + (1-coherentFraction)*(firstSurfaceIntensity + secondSurfaceIntensity);
        
        
    end
    
    % Get initial slope of responses at both wavelengths
    nTimes = 50;
    initialSlope1(jj) = (totalAmplitude1(jj,nTimes+1)-totalAmplitude1(jj,1))/(theDeltaTimesSecs(nTimes+1)-theDeltaTimesSecs(1));
    initialSlope2(jj) = (totalAmplitude2(jj,nTimes+1)-totalAmplitude2(jj,1))/(theDeltaTimesSecs(nTimes+1)-theDeltaTimesSecs(1));
    
end

%% Make a plot of responses
nConesToPlot = 9;
theColors = ['r' 'g' 'b' 'k' 'y' 'c'];
nColors = length(theColors);
responseFig1 = figure; clf; hold on
responseFig2 = figure; clf; hold on
correlationFig = figure; clf; hold on
whichColor = 1;
for jj = 1:nConesToPlot
    figure(responseFig1);
    plot(theDeltaTimesSecs,totalAmplitude1(jj,:),theColors(whichColor),'LineWidth',3);
    
    figure(responseFig2);
    plot(theDeltaTimesSecs,totalAmplitude2(jj,:),theColors(whichColor),'LineWidth',3);

    figure(correlationFig);
    plot(totalAmplitude1(jj,:),totalAmplitude2(jj,:),'o','Color',theColors(whichColor),'MarkerFaceColor',theColors(whichColor), ...
        'MarkerSize',8);
    
    whichColor = whichColor + 1;
    if (whichColor > nColors)
        whichColor = 1;
    end
end
figure(responseFig1);
set(gca,'YTick',[0.2 0.3 0.4 0.5]);
set(gca,'FontName','Helvetica','FontSize', 16);
xlabel('Time','FontName','Helvetica','FontSize',18);
ylabel('Reflectance','FontName','Helvetica','FontSize',18);
xlim([0 2]);
ylim([0.2 0.5]);
set(gca,'XTickLabel',''); set(gca,'YTickLabel','');
FigureSave('ExampleResponses',responseFig1,'tif');
figure(responseFig2);
xlabel('Time (secs)');
ylabel('Reflectance');
ylim([0.2 0.6]);
figure(correlationFig);
set(gca,'FontName','Helvetica','FontSize', 16);
xlabel(sprintf('Standardized Reflectance %d nm',firstLightWavelengthNm),'FontName','Helvetica','FontSize',18);
ylabel(sprintf('Standardized Reflectance %d nm',secondLightWavelengthNm),'FontName','Helvetica','FontSize',18);
axis('square');
xlim([0.2 0.5]);
set(gca,'XTick',[0.2 0.3 0.4 0.5]);
set(gca,'YTick',[0.2 0.3 0.4 0.5]);
ylim([0.2 0.5]);
FigureSave('TwoWavelengthCompare',correlationFig,'tif');

%% Make a plot of initial slopes at two wavelengths
slopeFig = figure; clf;
plot(initialSlope1,initialSlope2,'ro','MarkerFaceColor','r','MarkerSize',14);
xlabel(sprintf('Initial response slope (%d nm)',firstLightWavelengthNm));
ylabel(sprintf('Initial response slope (%d nm)',secondLightWavelengthNm));
xlim([-0.3 0.3]); ylim([-0.3 0.3]); axis('square');

%% Make a plot of reflectance versus reflectance
slopeFig1 = figure; clf; hold on;
plot(totalAmplitude1(:,1),initialSlope1,'ro','MarkerFaceColor','r','MarkerSize',8);
plot(totalAmplitude2(:,1),initialSlope2,'bo','MarkerFaceColor','b','MarkerSize',8);
xlabel(sprintf('Initial reflectance amplitude',firstLightWavelengthNm));
ylabel(sprintf('Initial response slope',secondLightWavelengthNm));
xlim([0.2 0.6]); ylim([-0.3 0.3]); 
legend({sprintf('%d nm',round(firstLightWavelengthNm)),sprintf('%d nm',round(secondLightWavelengthNm))},'Location','NorthEast')


<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title ></title>
      <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
      <script src="https://cdn.jsdelivr.net/npm/gijgo@1.9.9/js/gijgo.min.js" type="text/javascript"></script>
      <link href="https://cdn.jsdelivr.net/npm/gijgo@1.9.9/css/gijgo.min.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
 <br><br>
<form class="" action="index.html" method="post">
  <div class="container">
      <div class="row justify-content-md-center">
          <h3>ประวัติ</h3><br><br>
      </div>
      <div class="form-group">
        <label for="inputAddress">ชื่อ-นามสกุล :</label>
        <input type="text" class="form-control" required placeholder="ชื่อ-นามสกุล">
      </div>
      <div class="form-row">
        <div class="form-group col-md-5">
          <label for="inputState">เพศ :</label>
          <select id="inputState" class="form-control">
            <option selected>เพศ</option>
            <option>ชาย</option>
            <option>หญิง</option>
          </select>
        </div>
        <div class="form-group col-md-7">
          <label for="inputState">สถานะภาพ :</label>
          <select id="inputState" class="form-control">
            <option selected>สถานะภาพ</option>
            <option>โสด</option>
            <option>สมรส</option>
            <option>หย่า</option>
            <option>หม้าย</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label for="inputAddress">ศาสนา :</label>
        <input type="text" class="form-control" required placeholder="ศาสนา">
      </div>
      <div class="form-group">
        <label for="inputAddress">วัน/เดือน/ปี เกิด :</label>
        <input id="datepicker" width="276">
      </div>
      <div class="form-group">
        <label for="inputAddress">ที่อยู่ :</label>
        <textarea name="address" class="form-control" required rows="4" cols="80"></textarea>
      </div>
      <div class="form-group">
        <label for="inputAddress">เบอร์โทร :</label>
        <input type="number" class="form-control" required  placeholder="เบอร์โทร">
      </div>
      <div class="form-group">
        <label for="inputAddress">จบจาก :</label>
        <input type="text" class="form-control" required placeholder="จบจาก">
      </div>
      <div class="form-group">
        <label for="inputAddress">สาขาวิชาชีพ :</label>
        <input type="text" class="form-control" required placeholder="สาขาวิชาชีพ">
      </div>
      <div class="row justify-content-md-center">
        <button type="submit" class="btn btn-primary">บันทึก</button>
      </div>
  </div>{{-- end container --}}
</form>
<br><br><br><br><br><br>


<script>
        $('#datepicker').datepicker({
            uiLibrary: 'bootstrap4'
        });
    </script>
  </body>
</html>

<?php
	require_once("connect.inc");

	/*** test mysqli_connect 127.0.0.1 ***/
	$mysql = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket);

	$mysql->select_db($db);
	$mysql->query("DROP TABLE IF EXISTS test_048_table_1");

	$mysql->query("CREATE TABLE test_048_table_1(col1 tinyint, col2 smallint,
		col3 int, col4 bigint,
		col5 float, col6 double,
		col7 date, col8 time,
		col9 varbinary(10),
		col10 varchar(50),
		col11 char(20)) ENGINE=" . $engine);

	$mysql->query("INSERT INTO test_048_table_1(col1,col10, col11) VALUES(1,'foo1', 1000),(2,'foo2', 88),(3,'foo3', 389789)");

	$stmt = $mysql->prepare("SELECT col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11 from test_048_table_1");
	$stmt->bind_result($c1, $c2, $c3, $c4, $c5, $c6, $c7, $c8, $c9, $c10, $c11);
	$stmt->execute();

	$stmt->fetch();

	$test = array($c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$c10,$c11);

	var_dump($test);

	$stmt->close();
	$mysql->query("DROP TABLE IF EXISTS test_048_table_1");
	$mysql->close();
	print "done!";
?>
<?php error_reporting(0); ?>
<?php
require_once("connect.inc");
if (!$link = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket))
   printf("[c001] [%d] %s\n", mysqli_connect_errno(), mysqli_connect_error());

if (!mysqli_query($link, "DROP TABLE IF EXISTS test_048_table_1"))
	printf("[c002] Cannot drop table, [%d] %s\n", mysqli_errno($link), mysqli_error($link));

mysqli_close($link);
?>
module.exports = async d =>{
let code = d.command.code 
let inside = d.unpack()
let err = d.inside(inside) 
if(err) return d.error(err) 
let [query,type = "equal", separator = ","] = inside.splits 

if(!["equal","starts","ends","includes"].includes(type)) return d.error(`Invalid Typr Provided in $filterTextSplitElement${inside}`) 

let res;
    switch (type){
      case "equal" :
            res = d.array.filter(x=>x === query)
            break;
            case "starts":
            res = d.array.filter(x=>x.startsWith(query))
            break;
            case "ends" :
            res = d.array.filter(x=>x.endsWith(query)) 
            break;
            case "includes":
            res = d.array.filter(x=>x.includes(query))
            break;
            
            }
   return {
       code: code.replaceLast(`$filterTextSplitElement${inside}`,res.join(separator))
       }
}

from __future__ import print_function
import re
import sys
import ctypes

VALUE_t =  gdb.lookup_type('VALUE')
control_frame_t = gdb.lookup_type('rb_control_frame_t')
RString_t = gdb.lookup_type('struct RString')
RArray_t = gdb.lookup_type('struct RArray')
RBasic_t = gdb.lookup_type('struct RBasic')
RHash_t = gdb.lookup_type('struct RHash')
RObject_t = gdb.lookup_type('struct RObject')
RClass_t = gdb.lookup_type('struct RClass')
global_entry_t = gdb.lookup_type('struct rb_global_entry')
rb_thread_struct_t = gdb.lookup_type('struct rb_thread_struct')

try:
    ID_ENTRY_STR = gdb.parse_and_eval('ID_ENTRY_STR')
    ID_ENTRY_SYM = gdb.parse_and_eval('ID_ENTRY_SYM')
    ID_ENTRY_SIZE = gdb.parse_and_eval('ID_ENTRY_SIZE')
    ID_ENTRY_UNIT = gdb.parse_and_eval('ID_ENTRY_UNIT')
except:
    ID_ENTRY_STR = 0
    ID_ENTRY_SYM = 1
    ID_ENTRY_SIZE = 2
    ID_ENTRY_UNIT =512

try:
    RUBY_FL_USHIFT = gdb.parse_and_eval('RUBY_FL_USHIFT')
    RUBY_FL_USER0  = gdb.parse_and_eval('RUBY_FL_USER0')
    RUBY_FL_USER1  = gdb.parse_and_eval('RUBY_FL_USER1')
    RUBY_FL_USER2  = gdb.parse_and_eval('RUBY_FL_USER2')
    RUBY_FL_USER3  = gdb.parse_and_eval('RUBY_FL_USER3')
    RUBY_FL_USER4  = gdb.parse_and_eval('RUBY_FL_USER4')
    RUBY_FL_USER5  = gdb.parse_and_eval('RUBY_FL_USER5')
    RUBY_FL_USER6  = gdb.parse_and_eval('RUBY_FL_USER6')
    RUBY_FL_USER7  = gdb.parse_and_eval('RUBY_FL_USER7')
    RUBY_FL_USER8  = gdb.parse_and_eval('RUBY_FL_USER8')
    RUBY_FL_USER9  = gdb.parse_and_eval('RUBY_FL_USER9')
    RUBY_FL_USER10 = gdb.parse_and_eval('RUBY_FL_USER10')
    RUBY_FL_USER11 = gdb.parse_and_eval('RUBY_FL_USER11')
    RUBY_FL_USER12 = gdb.parse_and_eval('RUBY_FL_USER12')
    RUBY_FL_USER13 = gdb.parse_and_eval('RUBY_FL_USER13')
    RUBY_FL_USER14 = gdb.parse_and_eval('RUBY_FL_USER14')
    RUBY_FL_USER15 = gdb.parse_and_eval('RUBY_FL_USER15')
    RUBY_FL_USER16 = gdb.parse_and_eval('RUBY_FL_USER16')
    RUBY_FL_USER17 = gdb.parse_and_eval('RUBY_FL_USER17')
    RUBY_FL_USER18 = gdb.parse_and_eval('RUBY_FL_USER18')
    RUBY_FL_USER19 = gdb.parse_and_eval('RUBY_FL_USER19')
    RUBY_FL_SINGLETON = gdb.parse_and_eval('RUBY_FL_SINGLETON')
except:
    RUBY_FL_USHIFT = 12
    RUBY_FL_USER0 = (1<<RUBY_FL_USHIFT+0)
    RUBY_FL_USER1 = (1<<RUBY_FL_USHIFT+1)
    RUBY_FL_USER2 = (1<<RUBY_FL_USHIFT+2)
    RUBY_FL_USER3 = (1<<RUBY_FL_USHIFT+3)
    RUBY_FL_USER4 = (1<<RUBY_FL_USHIFT+4)
    RUBY_FL_USER5 = (1<<RUBY_FL_USHIFT+5)
    RUBY_FL_USER6 = (1<<RUBY_FL_USHIFT+6)
    RUBY_FL_USER7 = (1<<RUBY_FL_USHIFT+7)
    RUBY_FL_USER8 = (1<<RUBY_FL_USHIFT+8)
    RUBY_FL_USER9 = (1<<RUBY_FL_USHIFT+9)
    RUBY_FL_USER10 = (1<<RUBY_FL_USHIFT+10)
    RUBY_FL_USER11 = (1<<RUBY_FL_USHIFT+11)
    RUBY_FL_USER12 = (1<<RUBY_FL_USHIFT+12)
    RUBY_FL_USER13 = (1<<RUBY_FL_USHIFT+13)
    RUBY_FL_USER14 = (1<<RUBY_FL_USHIFT+14)
    RUBY_FL_USER15 = (1<<RUBY_FL_USHIFT+15)
    RUBY_FL_USER16 = (1<<RUBY_FL_USHIFT+16)
    RUBY_FL_USER17 = (1<<RUBY_FL_USHIFT+17)
    RUBY_FL_USER18 = (1<<RUBY_FL_USHIFT+18)
    RUBY_FL_USER19 = (1<<RUBY_FL_USHIFT+19)
    RUBY_FL_SINGLETON = RUBY_FL_USER0

RARRAY_EMBED_FLAG = RUBY_FL_USER1
RARRAY_EMBED_LEN_SHIFT = RUBY_FL_USHIFT+3
RARRAY_EMBED_LEN_MASK = (RUBY_FL_USER4|RUBY_FL_USER3)

tLAST_OP_ID = gdb.parse_and_eval('tLAST_OP_ID')

try:
    ID_SCOPE_SHIFT = gdb.parse_and_eval('RUBY_ID_SCOPE_SHIFT')
except:
    ID_SCOPE_SHIFT = 4

RUBY_Qfalse = gdb.parse_and_eval('RUBY_Qfalse')
RUBY_Qtrue = gdb.parse_and_eval('RUBY_Qtrue')
RUBY_Qnil = gdb.parse_and_eval('RUBY_Qnil')
RUBY_Qundef = gdb.parse_and_eval('RUBY_Qundef')

RUBY_FIXNUM_FLAG = gdb.parse_and_eval('RUBY_FIXNUM_FLAG')
RUBY_SYMBOL_FLAG = gdb.parse_and_eval('RUBY_SYMBOL_FLAG')

RUBY_FLONUM_MASK = gdb.parse_and_eval('RUBY_FLONUM_MASK')
RUBY_FLONUM_FLAG = gdb.parse_and_eval('RUBY_FLONUM_FLAG')

RUBY_SPECIAL_SHIFT = gdb.parse_and_eval('RUBY_SPECIAL_SHIFT')
RUBY_IMMEDIATE_MASK = gdb.parse_and_eval('RUBY_IMMEDIATE_MASK')
RUBY_T_MASK = gdb.parse_and_eval('RUBY_T_MASK')
RUBY_T_NONE = gdb.parse_and_eval('RUBY_T_NONE')
RUBY_T_NIL = gdb.parse_and_eval('RUBY_T_NIL')
RUBY_T_OBJECT = gdb.parse_and_eval('RUBY_T_OBJECT')
RUBY_T_CLASS = gdb.parse_and_eval('RUBY_T_CLASS')
RUBY_T_ICLASS = gdb.parse_and_eval('RUBY_T_ICLASS')
RUBY_T_MODULE = gdb.parse_and_eval('RUBY_T_MODULE')
RUBY_T_FLOAT = gdb.parse_and_eval('RUBY_T_FLOAT')
RUBY_T_STRING = gdb.parse_and_eval('RUBY_T_STRING')
RUBY_T_REGEXP = gdb.parse_and_eval('RUBY_T_REGEXP')
RUBY_T_FIXNUM = gdb.parse_and_eval('RUBY_T_FIXNUM')
RUBY_T_ARRAY = gdb.parse_and_eval('RUBY_T_ARRAY')
RUBY_T_HASH = gdb.parse_and_eval('RUBY_T_HASH')
RUBY_T_STRUCT = gdb.parse_and_eval('RUBY_T_STRUCT')
RUBY_T_BIGNUM = gdb.parse_and_eval('RUBY_T_BIGNUM')
RUBY_T_RATIONAL = gdb.parse_and_eval('RUBY_T_RATIONAL')
RUBY_T_COMPLEX = gdb.parse_and_eval('RUBY_T_COMPLEX')
RUBY_T_FILE = gdb.parse_and_eval('RUBY_T_FILE')
RUBY_T_TRUE = gdb.parse_and_eval('RUBY_T_TRUE')
RUBY_T_FALSE = gdb.parse_and_eval('RUBY_T_FALSE')
RUBY_T_DATA = gdb.parse_and_eval('RUBY_T_MATCH')
RUBY_T_SYMBOL = gdb.parse_and_eval('RUBY_T_SYMBOL')
RUBY_T_UNDEF = gdb.parse_and_eval('RUBY_T_UNDEF')
RUBY_T_NODE = gdb.parse_and_eval('RUBY_T_NODE')
RUBY_T_ZOMBIE = gdb.parse_and_eval('RUBY_T_ZOMBIE')
RUBY_T_NIL = gdb.parse_and_eval('RUBY_T_NIL')

def _rb_id2str(id):
    str = _lookup_id_str(id)
    return str

def _lookup_id_str(id):
    return _get_id_entry(_id_to_serial(id), ID_ENTRY_STR);

def _id_to_serial(id):
    if _is_notop_id(id):
        return id >> ID_SCOPE_SHIFT
    else:
        return id

def _is_notop_id(id):
    return id > tLAST_OP_ID

def _get_id_entry(num, id_entry_type):
    global_symbols = gdb.parse_and_eval('global_symbols')
    if (num != 0 and num <= global_symbols['last_id']):
        idx = num / ID_ENTRY_UNIT
        ids = global_symbols['ids']
        ary = _rb_ary_entry(ids, idx)
        if (idx < _RARRAY_LEN(ids) and (ary != RUBY_Qnil)):
            ary = _rb_ary_entry(ary, (num % ID_ENTRY_UNIT) * ID_ENTRY_SIZE + id_entry_type)
            if (ary != RUBY_Qnil):
                return ary

    return None

def _RARRAY_LEN(ary):
    a = ary.cast(RArray_t.pointer())
    if a['basic']['flags'] & RARRAY_EMBED_FLAG:
        return (a['basic']['flags'] >> RARRAY_EMBED_LEN_SHIFT) & (RARRAY_EMBED_LEN_MASK >> RARRAY_EMBED_LEN_SHIFT)
    else:
        return a['as']['heap']['len']

def _rb_ary_entry(ary, offset):
    if (offset < 0):
        offset += _RARRAY_LEN(ary)

    return _rb_ary_elt(ary, offset)


def _rb_ary_elt(ary, offset):
    len = _RARRAY_LEN(ary)
    if len == 0:
        return None
    if offset < 0 or len <= offset:
        return None

    return _RARRAY_AREF(ary, offset);

def _RARRAY_AREF(a, i):
    return _RARRAY_CONST_PTR(a)[i]

def _RARRAY_CONST_PTR(ary):
    a = ary.cast(RArray_t.pointer())
    if a['basic']['flags'] & RARRAY_EMBED_FLAG:
        return a['as']['ary']
    else:
        return a['as']['heap']['ptr']

def print_ruby_id(v):
    l = _rb_id2str(v)
    if l is not None:
        sys.stdout.write(get_rstring(l))

def print_ruby_class(v):
    print("Class value print not yet supported")

def print_ruby_array(v):
    len = _RARRAY_LEN(v)
    for i in range(0, int(len)):
        print_ruby_value(_rb_ary_entry(v, i))
        sys.stdout.write(" ")

def PACKED_BINS(table):
    return table['as']['packed']['entries']

def PACKED_ENT(table, i):
    return PACKED_BINS(table)[i]

def PKEY(table, i):
    return PACKED_ENT(table, (i))['key']

def PVAL(table, i):
    return PACKED_ENT(table, (i))['val']

def PHASH(table, i):
    return PACKED_ENT(table, (i))['hash']

# Walk through the ruby hashtable and callback the lambda for each key,value
# pair
def st_foreach(table, callback, *args):
    if table == 0:
        return

    if table['entries_packed']:
        for i in range(0, int(table['as']['packed']['real_entries'])):
            key = PKEY(table, i)
            val = PVAL(table, i)
            callback(key, val, *args)
    else:
        ptr = table['as']['big']['head']

        while ptr != 0 and table['as']['big']['head'] != 0:
            key = ptr['key']
            val = ptr['record']
            callback(key, val, *args)
            ptr = ptr['fore']

    return

def print_ruby_hash(v):
    h = v.cast(RHash_t.pointer())
    sys.stdout.write("{ ")
    if h['ntbl']:
        f = lambda key,val: [print_ruby_value(key), sys.stdout.write(" => "), print_ruby_value(val), sys.stdout.write(", ")]
        st_foreach(h['ntbl'], f)
    sys.stdout.write("}")

ROBJECT_EMBED_LEN_MAX = 3

def ROBJECT_NUMIV(o):
    if (o['basic']['flags'] & RUBY_FL_USER1):
        return ROBJECT_EMBED_LEN_MAX
    else:
        return o['as']['heap']['numiv']

def ROBJECT_IVPTR(o):
    if (o['basic']['flags'] & RUBY_FL_USER1):
        return o['as']['ary']
    else:
        return o['as']['heap']['ivptr']

def ROBJECT_IV_INDEX_TBL(o):
    if (o['basic']['flags'] & RUBY_FL_USER1):
        return RCLASS_IV_INDEX_TBL(rb_obj_class(o))
    else:
        return o['as']['heap']['iv_index_tbl']

def RCLASS_IV_INDEX_TBL(c):
    return (RCLASS_EXT(c)['iv_index_tbl'])

def RCLASS_EXT(c):
    return c['ptr']

def RCLASS_IV_TBL(c):
    return RCLASS_EXT(c)['iv_tbl']

def RCLASS_CONST_TBL(c):
    return RCLASS_EXT(c)['const_tbl']

def rb_obj_class(o):
    return rb_class_real(CLASS_OF(o))

def CLASS_OF(v):
    return rb_class_of(v)

def IMMEDIATE_P(x):
    return (x & RUBY_IMMEDIATE_MASK)

def rb_class_of(obj):
    return obj['basic']['klass']
#    if (IMMEDIATE_P(obj)):
#       if (FIXNUM_P(obj)) return rb_cFixnum;
#       if (FLONUM_P(obj)) return rb_cFloat;
#       if (obj == Qtrue)  return rb_cTrueClass;
#       if (STATIC_SYM_P(obj)) return rb_cSymbol;
#     }
#     else if (!RTEST(obj)) {
#       if (obj == Qnil)   return rb_cNilClass;
#       if (obj == Qfalse) return rb_cFalseClass;
#     }
#     return RBASIC(obj)->klass;
# }

def rb_class_real(cl):
    cl = cl.cast(RClass_t.pointer())
    while ((cl != 0) and
           ((cl['basic']['flags'] & RUBY_FL_SINGLETON) or (cl['basic']['flags'] & RUBY_T_MASK) == RUBY_T_ICLASS)):
        cl = cl['super']

    return cl

# Print a ruby object's variables
def print_ruby_object(v):
    obj = v.cast(RObject_t.pointer())
    len = ROBJECT_NUMIV(obj)
    ptr = ROBJECT_IVPTR(obj)
    num = 0;

    # Print instance variables.
    #
    # The instance variable values are stored inside the RObject itself but
    # the names are in class's rb_classext_struct.iv_index_tbl variable. So
    # we will iterate that hash table and print key from it and value from
    # this object's variable
    sys.stdout.write("{{ ")
    f = lambda key,val: [ print_ruby_id(key), sys.stdout.write(" => "),
                          print_ruby_value(ptr[val]), sys.stdout.write(", ")]
    st_foreach(ROBJECT_IV_INDEX_TBL(obj), f)

    # Print class variable (@@myvar).
    f = lambda key,val: [ print_ruby_id(key), sys.stdout.write(" => "),
                          print_ruby_value(val), sys.stdout.write(", ")]
    st_foreach(RCLASS_IV_TBL(rb_obj_class(obj)), f)

    # Print the constants in this object
    st_foreach(RCLASS_CONST_TBL(rb_obj_class(obj)), f)
    sys.stdout.write("}}")

class FLONUM(ctypes.Union):
    _fields_ = [("d", ctypes.c_double),
                ("v", ctypes.c_ulong)]

def print_ruby_value(v):
    if ((v & ~((~0)<<RUBY_SPECIAL_SHIFT)) == RUBY_SYMBOL_FLAG):
        print_ruby_id(v >> RUBY_SPECIAL_SHIFT)
        return

    if v & RUBY_FIXNUM_FLAG:
        sys.stdout.write("%ld" % (v >> 1))
        flags = v.cast(RBasic_t.pointer())['flags']
        return

    if v == RUBY_Qfalse:
        sys.stdout.write("false")
        return

    if v == RUBY_Qtrue:
        sys.stdout.write("true")
        return

    if v == RUBY_Qnil:
        sys.stdout.write("nil")
        return

    if v == RUBY_Qundef:
        sys.stdout.write("undef")
        return

    if (v & RUBY_IMMEDIATE_MASK):
        if (v & RUBY_FLONUM_MASK == RUBY_FLONUM_FLAG):
            if (v != 0x8000000000000002):
                b63 = (v >> 63)
                nv = (2 - b63) | (v & ~0x03)
                nv = ((nv >> 3) | (nv << (8 * 8) - 3))
                f = FLONUM(v=nv)
                sys.stdout.write("%s" % f.d)
        else:
            sys.stdout.write("immediate")
        return

    flags = v.cast(RBasic_t.pointer())['flags']

    if flags & RUBY_T_MASK == RUBY_T_NONE:
        sys.stdout.write("T_NONE : (struct RBasic *)%s" % v)
        return

    if flags & RUBY_T_MASK == RUBY_T_NIL:
        sys.stdout.write("T_NIL : (struct RBasic *)%s" % v)
        return

    if flags & RUBY_T_MASK == RUBY_T_OBJECT:
        #sys.stdout.write("T_OBJECT : (struct RObject *)%s TODO" % v)
        print_ruby_object(v)
        return

    if flags & RUBY_T_MASK == RUBY_T_CLASS:
        s = "*" if (flags & RUBY_FL_SINGLETON) else ""
        sys.stdout.write("T_CLASS %s : (struct RObject *)%s  TODO" % (s, v))
        return

    if flags & RUBY_T_MASK == RUBY_T_ICLASS:
        sys.stdout.write("T_ICLASS : TODO ")
        print_ruby_class(v)
        return

    if flags & RUBY_T_MASK == RUBY_T_MODULE:
        sys.stdout.write("T_MODULE : TODO")
        print_ruby_class(v)
        return

    if flags & RUBY_T_MASK == RUBY_T_FLOAT:
        v.cast(RFloat_t.pointer())['float_value']
        sys.stdout.write("T_FLOAT : %f (struct RFloat *)%s" % (v))
        return

    if flags & RUBY_T_MASK == RUBY_T_STRING:
        sys.stdout.write("\"" + get_rstring(v) + "\"")
        return

    if flags & RUBY_T_MASK == RUBY_T_REGEXP:
        sys.stdout.write("T_REGEX : (struct RRegex *)%s  TODO" % v)
        return

    if flags & RUBY_T_MASK == RUBY_T_ARRAY:
        print_ruby_array(v)
        return

    if flags & RUBY_T_MASK == RUBY_T_HASH:
        print_ruby_hash(v)
        return

    sys.stdout.write("unknown (struct RBasic *)%s" % v)
    # gdb.execute("rp %s" % v)

def try_print_variable(key, val):
    # TODO: fix it
    try:
        global_entry = val.cast(global_entry_t.pointer())
        v = (global_entry['var']['data']).cast(VALUE_t)
        print_ruby_id(key)
        sys.stdout.write(" = ")
        print_ruby_value(v)
    except:
        return
    finally:
        sys.stdout.write("\n")

def print_global_variables():
    rb_global_tbl = gdb.parse_and_eval('rb_global_tbl')
    st_foreach(rb_global_tbl, try_print_variable)

def get_ruby_localvariables(th=None, varname=None):
  if th == None:
      th = gdb.parse_and_eval('ruby_current_thread')
  else:
      th = gdb.parse_and_eval('(rb_thread_t *) %s' % th)

  last_cfp = th['cfp']
  start_cfp = (th['stack'] + th['stack_size']).cast(control_frame_t.pointer()) - 2
  size = start_cfp - last_cfp + 1
  cfp = start_cfp
  call_stack = []
  for i in range(0, int(size)):
      if cfp['iseq'].dereference().address != 0:
          if cfp['pc'].dereference().address != 0:
              call_stack.append(cfp)
      cfp -= 1

  for cfp in reversed(call_stack):
      print(get_func_info(cfp))
      local_table = get_local_table(cfp)
      local_table_size = get_local_table_size(cfp)
      print("local table size = %s" % local_table_size)
      for j in range(0, int(local_table_size)):
          id = local_table[j]
          l = _rb_id2str(id)
          if varname is not None:
              if l is not None or varname is get_rstring(l):
                  continue

          if l is not None:
              sys.stdout.write("%s = " % get_rstring(l))
              v = cfp['ep'] - (local_table_size - j - 1 + 2)
              try:
                  print_ruby_value(v.dereference())
              except:
                  continue
              finally:
                  sys.stdout.write("\n")

def get_rstring(addr):
  if addr is None:
    return None

  s = addr.cast(RString_t.pointer())
  if s['basic']['flags'] & (1 << 13):
    return s['as']['heap']['ptr'].string()
  else:
    return s['as']['ary'].string()

def get_lineno(iseq, pos):
  if pos != 0:
    pos -= 1

  try:
      t = iseq['body']['line_info_table']
      t_size = iseq['body']['line_info_size']
  except:
      t = iseq['line_info_table']
      t_size = iseq['line_info_size']

  if t_size == 0:
    return 0
  elif t_size == 1:
    return t[0]['line_no']

  for i in range(0, int(t_size)):
    if pos == t[i]['position']:
      return t[i]['line_no']
    elif t[i]['position'] > pos:
      return t[i-1]['line_no']

  return t[t_size-1]['line_no']

def get_func_info(cfp):
    try:
        path = get_rstring(cfp['iseq']['location']['path'])
        label = get_rstring(cfp['iseq']['location']['label'])
        lineno = get_lineno(cfp['iseq'], cfp['pc'] - cfp['iseq']['iseq_encoded'])
    except:
        # Ruby 2.3+
        path = get_rstring(cfp['iseq']['body']['location']['path'])
        label = get_rstring(cfp['iseq']['body']['location']['label'])
        lineno = get_lineno(cfp['iseq'], cfp['pc'] - cfp['iseq']['body']['iseq_encoded'])

    return "{}:{}:in `{}'".format(path, lineno, label)

def get_local_table(cfp):
    try:
        local_table = (cfp['iseq']['local_table'])
    except:
        local_table = (cfp['iseq']['body']['local_table'])
    return local_table

def get_local_table_size(cfp):
    try:
        local_table_size = (cfp['iseq']['local_table_size'])
    except:
        local_table_size = (cfp['iseq']['body']['local_table_size'])
    return local_table_size

def get_ruby_stacktrace(th=None, folded=False):
    if th == None:
        th = gdb.parse_and_eval('ruby_current_thread')
    else:
        th = gdb.parse_and_eval('(rb_thread_t *) %s' % th)

    last_cfp = th['cfp']
    start_cfp = (th['stack'] + th['stack_size']).cast(control_frame_t.pointer()) - 2
    size = start_cfp - last_cfp + 1
    cfp = start_cfp
    call_stack = []
    for i in range(0, int(size)):
        if cfp['iseq'].dereference().address != 0:
            if cfp['pc'].dereference().address != 0:
                call_stack.append(get_func_info(cfp))
        cfp -= 1

    for i in reversed(call_stack):
        if folded:
            sys.stdout.write("%s;" % i)
        else:
            print(i)

    if folded:
        print()

def get_rb_thread_for_current_thread():
    # We will get the current thread id from gdb, iterate over all ruby
    # threads and find the corresponding rb_thread_t

    # TODO: Can't we directly pull the thread id out of gdb.selected_thread()?
    t = gdb.selected_thread()
    if t is None:
        print("No current thread")
        return None

    gdb_th_num = t.num
    curr_th_id = re.search('Thread ([0-9a-zx]+)', gdb.execute('info thread %d' % gdb_th_num, to_string=True)).group(1);
    curr_th_id = int(curr_th_id, 16)
    #curr_th_id=gdb.parse_and_eval('(pthread_t)pthread_self()')

    head = gdb.parse_and_eval('&ruby_current_thread->vm->living_threads.n')
    t = gdb.parse_and_eval('ruby_current_thread->vm->living_threads.n.next')
    while (t != head):
        ti = t.cast(rb_thread_struct_t.pointer())
        if ti['thread_id'] == curr_th_id:
            #print("found matching ruby thread")
            return ti
        t = t['next']

    print("Thread {0} (0x{1:x}) is not a ruby thread!".format(gdb_th_num,curr_th_id))

    return None

class AnalyzeSegFaultCmd(gdb.Command):
    "Analyze ruby segfault info"

    def __init__(self):
        gdb.Command.__init__(self, "analyze_ruby_fault", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        for i,inferior in enumerate(gdb.inferiors()):
            if not inferior.is_valid():
                continue

            found_segfault = False

            for j,thread in enumerate(inferior.threads()):
                thread.switch()
                #print("Processing thread %s" % thread.ptid[1])
                frame = gdb.selected_frame()
                while ((frame is not None) and (frame.type() != gdb.SIGTRAMP_FRAME)):
                    frame = frame.older()

                if frame is None:
                    continue

                sigsegv_frame = frame.newer()
                if (sigsegv_frame is None) or sigsegv_frame.name() != "sigsegv":
                    continue

                found_segfault = True
                print("Found segfault frame for pid %s" % inferior.pid)
                sigsegv_frame.select()

                fault_addr = gdb.parse_and_eval("info->si_addr")
                reg_err = gdb.parse_and_eval("((ucontext_t *)ctx)->uc_mcontext.gregs[REG_ERR]")
                reg_err = reg_err.cast(gdb.lookup_type('long long'))

                print("Faulting address : %s" % fault_addr)
                sys.stdout.write("Fault reason : %s (" % hex(int(reg_err)))
                if reg_err & 0x1:
                    sys.stdout.write("ProtectionFault")
                else:
                    sys.stdout.write("NoPageFound")

                if reg_err & 0x2:
                    sys.stdout.write(" WriteAccess")
                else:
                    sys.stdout.write(" ReadAccess")

                if reg_err & 0x4:
                    sys.stdout.write(" UserMode")
                else:
                    sys.stdout.write(" KernelMode")
                print(")")

            if not found_segfault:
                print("Couldn't find segfault frame for pid %s" % inferior.pid)

class RubyStackTraceCmd(gdb.Command):
    "Print Ruby callstack of current GDB thread (which may/may not be current Ruby thread holding GVL)"

    def __init__(self):
        gdb.Command.__init__(self, "ruby_bt", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        ti = get_rb_thread_for_current_thread()
        if ti is None:
            print("Could not find ruby thread info for current gdb thread")
            return

        argv = gdb.string_to_argv(arg)
        folded = False
        if len(argv) > 0 and argv[0] == 'folded':
            folded = True
        get_ruby_stacktrace(th=ti, folded=folded)

class RubyStackTraceCurrCmd(gdb.Command):
    "Print stacktrace of current Ruby thread (which may/may not be current GDB thread)"

    def __init__(self):
        gdb.Command.__init__(self, "ruby_bt_curr", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        get_ruby_stacktrace()

class RubyLocalVariablesCmd(gdb.Command):
    "Print Ruby local variables, by walking current GDB thread's Ruby stack. Pass variable name to filter"

    def __init__(self):
        gdb.Command.__init__(self, "ruby_locals", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        ti = get_rb_thread_for_current_thread()
        if ti is None:
            print("Could not find ruby thread info for current gdb thread")
            return

        argv = gdb.string_to_argv(arg)
        varname = None
        if len(argv) > 0:
            varname = argv[0]

        get_ruby_localvariables(th=ti, varname=varname)

class RubyLocalVariablesCurrCmd(gdb.Command):
    "Print Ruby local variables, by walking current (holding GVL) Ruby thread's stack. Pass variable name to filter"

    def __init__(self):
        gdb.Command.__init__(self, "ruby_locals_curr", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        argv = gdb.string_to_argv(arg)
        varname = None
        if len(argv) > 0:
            varname = argv[0]

        get_ruby_localvariables(varname=varname)

class RubyGlovalVariablesCmd(gdb.Command):
    "Print Ruby global variables"

    def __init__(self):
        gdb.Command.__init__(self, "ruby_globals", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        print_global_variables()

AnalyzeSegFaultCmd()
RubyStackTraceCmd()
RubyStackTraceCurrCmd()
RubyLocalVariablesCmd()
RubyLocalVariablesCurrCmd()
RubyGlovalVariablesCmd()

/*---
es5id: 15.2.3.5-4-251
description: >
    Object.create - one property in 'Properties' is the Math object
    that uses Object's [[Get]] method to access the 'get' property
    (8.10.5 step 7.a)
---*/

            Math.get = function () {
                return "VerifyMathObject";
            };

            var newObj = Object.create({}, {
                prop: Math 
            });

assert.sameValue(newObj.prop, "VerifyMathObject", 'newObj.prop');
package com.serotonin.mango.web.mvc.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ParameterizableViewController;

import com.serotonin.mango.Common;
import com.serotonin.mango.db.dao.ViewDao;
import com.serotonin.mango.view.ShareUser;
import com.serotonin.mango.view.View;

/**
 * @author Matthew Lohbihler
 */
public class PublicViewController extends ParameterizableViewController {
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
        ViewDao viewDao = new ViewDao();

        // Get the view by id.
        String vid = request.getParameter("viewId");
        View view = null;
        if (vid != null) {
            try {
                view = viewDao.getView(Integer.parseInt(vid));
            }
            catch (NumberFormatException e) { /* no op */
            }
        }
        else {
            String name = request.getParameter("viewName");
            if (name != null)
                view = viewDao.getView(name);
            else {
                String xid = request.getParameter("viewXid");
                if (xid != null)
                    view = viewDao.getViewByXid(xid);
            }
        }

        Map<String, Object> model = new HashMap<String, Object>();

        // Ensure the view has anonymously accessible.
        if (view != null && view.getAnonymousAccess() == ShareUser.ACCESS_NONE)
            view = null;

        if (view != null) {
            model.put("view", view);
            view.validateViewComponents(view.getAnonymousAccess() == ShareUser.ACCESS_READ);
            Common.addAnonymousView(request, view);
        }

        return new ModelAndView(getViewName(), model);
    }
}
require 'rails_helper'

RSpec.describe Companies::DestroyCompany do
  include ServiceStubHelpers::Cruncher

  describe '#call' do
    let(:company) { double }
    let(:company_query_stub) { double }
    let(:job_application_query) { double }
    let(:reject_iterator) { double(JobApplications::Reject) }
    let(:subject) do
      Companies::DestroyCompany.new(
        double, company_query_stub, job_application_query, reject_iterator
      )
    end
    context 'cannot find company' do
      before(:each) do
        allow(subject.query).to receive(:find_by_id)
          .and_raise(ActiveRecord::RecordNotFound)
      end

      it 'raises ActiveRecord Exception' do
        expect(subject.query).not_to receive(:destroy)
        expect { subject.call(1) }.to raise_error(ActiveRecord::RecordNotFound)
      end
    end

    context 'user not authorized to delete a company' do
      let(:agency) { FactoryBot.build(:agency) }
      let(:company_with_jobs) do
        job = FactoryBot.build(:job)
        job.id = 1
        company = FactoryBot.build(:company, agencies: [agency], jobs: [job])
        allow(company.jobs).to receive(:exists?).and_return true
        company
      end

      before(:each) do
        expect(subject).to receive(:authorized!)
          .with(company_with_jobs, 'destroy')
          .and_raise(Authorization::NotAuthorizedError)
        company_with_jobs.id = 1
        allow(subject.query).to receive(:find_by_id).and_return(company_with_jobs)
      end

      it 'does not delete the company' do
        expect(subject.query).not_to receive(:destroy)
        expect { subject.call(1) }.to raise_error(Authorization::NotAuthorizedError)
      end
    end

    context 'company with jobs' do
      let(:agency) { FactoryBot.build(:agency) }
      let(:company_with_jobs) do
        job = FactoryBot.build(:job)
        job.id = 1
        company = FactoryBot.build(:company, agencies: [agency], jobs: [job])
        allow(company.jobs).to receive(:exists?).and_return true
        company
      end

      before(:each) do
        stub_cruncher_authenticate
        stub_cruncher_job_create
      end

      context 'no job applications' do
        before(:each) do
          expect(subject).to receive(:authorized!)
            .with(company_with_jobs, 'destroy')
          expect(job_application_query).to receive(:find_by_company)
            .and_return([])
          company_with_jobs.id = 1
          allow(subject.query).to receive(:find_by_id).and_return(company_with_jobs)
          expect(reject_iterator).not_to receive(:call)
        end

        it 'does update the company status to inactive' do
          expect(company_with_jobs).to receive(:inactive)
          result = subject.call(1)
          expect(result).to eq(company_with_jobs)
        end
      end

      context 'a job as application' do
        let(:job_application) do
          FactoryBot.build(:job_application)
        end

        before(:each) do
          expect(subject).to receive(:authorized!)
            .with(company_with_jobs, 'destroy')
          expect(job_application_query).to receive(:find_by_company)
            .and_return([job_application])

          company_with_jobs.id = 1
          allow(subject.query).to receive(:find_by_id).and_return(company_with_jobs)
          expect(reject_iterator).to receive(:call)
            .with(job_application, 'Company removed from the system')
        end

        it 'does update the company status to inactive' do
          expect(company_with_jobs).to receive(:inactive)
          result = subject.call(1)
          expect(result).to eq(company_with_jobs)
        end

        it 'calls the job application rejection iterator' do
          expect(company_with_jobs).to receive(:inactive)
          result = subject.call(10)
          expect(result).to eq(company_with_jobs)
        end
      end
    end

    context 'company without jobs' do
      let(:agency) { FactoryBot.build(:agency) }
      let(:company) do
        FactoryBot.build(:company, agencies: [agency])
      end

      before(:each) do
        expect(subject).to receive(:authorized!)
          .with(company, 'destroy')
        allow(subject.query).to receive(:find_by_id).and_return(company)
        allow(job_application_query).to receive(:find_by_company)
          .and_return([])
      end

      it 'does udpdate the company status to inactive' do
        expect(company).to receive(:inactive)
        result = subject.call(1)
        expect(result).to eq(company)
      end
    end
  end
end

CXX = g++
CXXFLAGS = -std=c++11 -Wall
RM = rm -rf

OBJ = $(patsubst %.cpp,%.o,$(wildcard *.cpp))

.PHONY: all
all: test_all
test_all : $(OBJ)
	$(CXX) $(CXXFLAGS) $^ -o $@
%.o: %.cpp test_tool.h
	$(CXX) $(CXXFLAGS) -c $< -o $@

.PHONY: clean
clean:
	$(RM) $(OBJ) test_all
.PHONY: distclean
distclean: clean

open! IStd

(** visibility of the issue type *)
type visibility =
  | User  (** always add to error log *)
  | Developer  (** only add to error log in some debug modes *)
  | Silent  (** never add to error log *)
[@@deriving compare, equal]

(** severity of the report *)
type severity = Like | Info | Advice | Warning | Error [@@deriving compare, equal, enumerate]

val string_of_severity : severity -> string

type t = private
  { unique_id: string
  ; checker: Checker.t
  ; visibility: visibility
  ; mutable default_severity: severity
        (** used for documentation but can be overriden at report time *)
  ; mutable enabled: bool
  ; mutable hum: string
  ; mutable doc_url: string option
  ; mutable linters_def_file: string option }
[@@deriving compare]

val equal : t -> t -> bool

val all_issues : unit -> t list
(** all the issues declared so far *)

val pp : Format.formatter -> t -> unit
(** pretty print a localised string *)

val find_from_string : id:string -> t option
(** return the issue type if it was previously registered *)

val register_from_string :
     ?enabled:bool
  -> ?hum:string
  -> ?doc_url:string
  -> ?linters_def_file:string
  -> id:string
  -> ?visibility:visibility
  -> severity
  -> Checker.t
  -> t
(** Create a new issue and register it in the list of all issues. NOTE: if the issue with the same
    string id is already registered, overrides `hum`, `doc_url`, and `linters_def_file`, but DOES
    NOT override `enabled`. This trick allows to deal with disabling/enabling dynamic AL issues from
    the config, when we don't know all params yet. Thus, the human-readable description can be
    updated when we encounter the definition of the issue type, eg in AL. *)

val checker_can_report : Checker.t -> t -> bool
(** Whether the issue was registered as coming from the given checker. Important to call this before
    reporting to keep documentation accurate. *)

val set_enabled : t -> bool -> unit

val abduction_case_not_implemented : t

val array_of_pointsto : t

val array_out_of_bounds_l1 : t

val array_out_of_bounds_l2 : t

val array_out_of_bounds_l3 : t

val assert_failure : t

val bad_footprint : t

val biabduction_analysis_stops : t

val biabd_condition_always_false : t

val biabd_condition_always_true : t

val biabd_registered_observer_being_deallocated : t

val biabd_stack_variable_address_escape : t

val biabd_use_after_free : t

val buffer_overrun_l1 : t

val buffer_overrun_l2 : t

val buffer_overrun_l3 : t

val buffer_overrun_l4 : t

val buffer_overrun_l5 : t

val buffer_overrun_r2 : t

val buffer_overrun_s2 : t

val buffer_overrun_t1 : t
(** Tainted values is used in array accesses, causing buffer over/underruns *)

val buffer_overrun_u5 : t

val cannot_star : t

val captured_strong_self : t

val checkers_allocates_memory : t
(** Warning name when a performance critical method directly or indirectly calls a method allocating
    memory *)

val checkers_annotation_reachability_error : t

val checkers_calls_expensive_method : t
(** Warning name when a performance critical method directly or indirectly calls a method annotatd
    as expensive *)

val checkers_expensive_overrides_unexpensive : t
(** Warning name for the subtyping rule: method not annotated as expensive cannot be overridden by a
    method annotated as expensive *)

val checkers_fragment_retain_view : t

val checkers_immutable_cast : t

val checkers_printf_args : t

val class_cast_exception : t

val class_load : t

val complexity_increase : kind:CostKind.t -> is_on_ui_thread:bool -> t

val component_factory_function : t

val component_file_cyclomatic_complexity : t

val component_file_line_count : t

val component_initializer_with_side_effects : t

val component_with_multiple_factory_methods : t

val component_with_unconventional_superclass : t

val condition_always_false : t

val condition_always_true : t

val constant_address_dereference : t

val create_intent_from_uri : t

val cross_site_scripting : t

val dangling_pointer_dereference : t

val dangling_pointer_dereference_maybe : t

val dead_store : t

val deadlock : t

val deallocate_stack_variable : t

val deallocate_static_memory : t

val deallocation_mismatch : t

val divide_by_zero : t

val do_not_report : t
(** an issue type that should never be reported *)

val empty_vector_access : t

val eradicate_condition_redundant : t

val eradicate_field_not_initialized : t

val eradicate_field_not_nullable : t

val eradicate_field_over_annotated : t

val eradicate_inconsistent_subclass_parameter_annotation : t

val eradicate_inconsistent_subclass_return_annotation : t

val eradicate_redundant_nested_class_annotation : t

val eradicate_bad_nested_class_annotation : t

val eradicate_nullable_dereference : t

val eradicate_parameter_not_nullable : t

val eradicate_return_not_nullable : t

val eradicate_return_over_annotated : t

val eradicate_unvetted_third_party_in_nullsafe : t

val eradicate_unchecked_usage_in_nullsafe : t

val eradicate_meta_class_can_be_nullsafe : t

val eradicate_meta_class_needs_improvement : t

val eradicate_meta_class_is_nullsafe : t

val exposed_insecure_intent_handling : t

val failure_exe : t

val field_not_null_checked : t

val guardedby_violation_racerd : t

val impure_function : t

val inefficient_keyset_iterator : t

val inferbo_alloc_is_big : t

val inferbo_alloc_is_negative : t

val inferbo_alloc_is_zero : t

val inferbo_alloc_may_be_big : t

val inferbo_alloc_may_be_negative : t

val inferbo_alloc_may_be_tainted : t

val infinite_cost_call : kind:CostKind.t -> t

val inherently_dangerous_function : t

val insecure_intent_handling : t

val integer_overflow_l1 : t

val integer_overflow_l2 : t

val integer_overflow_l5 : t

val integer_overflow_r2 : t

val integer_overflow_u5 : t

val interface_not_thread_safe : t

val internal_error : t

val invariant_call : t

val javascript_injection : t

val lab_resource_leak : t

val leak_after_array_abstraction : t

val leak_in_footprint : t

val leak_unknown_origin : t

val lockless_violation : t

val lock_consistency_violation : t

val logging_private_data : t

val expensive_loop_invariant_call : t

val memory_leak : t

val missing_fld : t

val missing_required_prop : t

val mixed_self_weakself : t

val multiple_weakself : t

val mutable_local_variable_in_component_file : t

val null_dereference : t

val null_test_after_dereference : t

val nullptr_dereference : t

val parameter_not_null_checked : t

val pointer_size_mismatch : t

val precondition_not_found : t

val precondition_not_met : t

val premature_nil_termination : t

val pulse_memory_leak : t

val pure_function : t

val quandary_taint_error : t

val resource_leak : t

val retain_cycle : t

val skip_function : t

val skip_pointer_dereference : t

val shell_injection : t

val shell_injection_risk : t

val sql_injection : t

val sql_injection_risk : t

val stack_variable_address_escape : t

val starvation : t

val static_initialization_order_fiasco : t

val strict_mode_violation : t

val strong_self_not_checked : t

val symexec_memory_error : t

val thread_safety_violation : t

val topl_error : t

val unary_minus_applied_to_unsigned_expression : t

val uninitialized_value : t

val unreachable_code_after : t

val use_after_delete : t

val use_after_free : t

val use_after_lifetime : t

val untrusted_buffer_access : t

val untrusted_deserialization : t

val untrusted_deserialization_risk : t

val untrusted_file : t

val untrusted_file_risk : t

val untrusted_heap_allocation : t

val untrusted_intent_creation : t

val untrusted_url_risk : t

val untrusted_environment_change_risk : t

val untrusted_variable_length_array : t

val user_controlled_sql_risk : t

val vector_invalidation : t

val weak_self_in_noescape_block : t

val wrong_argument_number : t

val unreachable_cost_call : kind:CostKind.t -> t
public class MessageC2SLoginSendNonceNameAndPassword extends MessageSendByteArray {

	private String username;

	private byte[] password;

	/** Constructor for allowing creation of an empty message */
	public MessageC2SLoginSendNonceNameAndPassword() {
		super(MessageType.C2S_LOGIN_SENDNONCENAMEANDPASSWORD);
	}

	/**
	 * Constructor with a TCP/IP source/destination of the message and the name
	 * of the choosen character.
	 *
	 * @param source
	 *            The TCP/IP address associated to this message
	 * @param nonce
	 *            random number to prevent replay attacks
	 * @param username
	 *            the username of the user that wants to login
	 * @param password
	 *            the plain password of the user that wants to login
	 */
	public MessageC2SLoginSendNonceNameAndPassword(Channel source, byte[] nonce,
	        String username, byte[] password) {
		super(MessageType.C2S_LOGIN_SENDNONCENAMEANDPASSWORD, source, nonce);
		this.username = username;
		this.password = Utility.copy(password);
	}

	/**
	 * This method returns the username
	 *
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * This method returns the encoded password
	 *
	 * @return the password
	 */
	public byte[] getPassword() {
		return Utility.copy(password);

	}

	/**
	 * This method returns a String that represent the object
	 *
	 * @return a string representing the object.
	 */
	@Override
	public String toString() {
		return "Message (C2S Login) from (" + getAddress() + ") CONTENTS: (nonce:"
		        + Hash.toHexString(hash) + "\tusername:" + username + ")";
	}

	@Override
	public void writeObject(OutputSerializer out) throws IOException {
		super.writeObject(out);
		out.write(username);
		out.write(password);
	}

	@Override
	public void readObject(InputSerializer in) throws IOException {
		super.readObject(in);
		username = in.readString();
		password = in.readByteArray();
		if (type != MessageType.C2S_LOGIN_SENDNONCENAMEANDPASSWORD) {
			throw new IOException();
		}
	}
}
export default {
init: function () {
const AK = 'vcM72RPfaB2Wqcqq7QBli94s4GUyOiWY'
const BMapURL = 'https://api.map.baidu.com/api?v=3.0&ak=' + AK + '&s=1&callback=onBMapCallback'
return new Promise((resolve, reject) => {
// 如果已加载直接返回
// if (typeof BMap !== 'undefined') {
// resolve(BMap)
// return true
// }
// 百度地图异步加载回调处理
window.onBMapCallback = function () {
console.log('百度地图脚本初始化成功...')
// eslint-disable-next-line
resolve(BMap)
}

// 插入script脚本
let scriptNode = document.createElement('script')
scriptNode.setAttribute('type', 'text/javascript')
scriptNode.setAttribute('src', BMapURL)
document.body.appendChild(scriptNode)
})
}
}

BOSH Release for PostgreSQL in Docker container
===============================================

This BOSH release has three use cases:

-	run a single Docker container of a PostgreSQL Docker image on a single BOSH VM
-	run a Cloud Foundry service broker that itself runs containers of PostgreSQL Docker image on a BOSH VM based on user requests
-	embedded PostgreSQL Docker image that could be used by another BOSH release

As a Cloud Foundry service broker, there are two version of PostgreSQL that can be offered:

```
$ cf marketplace
Getting services from marketplace in org system / space dev as admin...
OK

service        plans   description
postgresql93   free    postgresql 9.3 service for application development and testing
postgresql94   free    postgresql 9.4 service for application development and testing
```

NOTE: if you're deploying the broker for the first time, it is suggested to only offer the latest database to minimize the operations upset of deprecating and disabling the older one in the future.

The PostgreSQL image can be referenced either:

-	from an embebbed/bundled image stored with each BOSH release version
-	from upstream and/or private registries

Spiff deployment templates are included for:

-	bosh-lite/garden
-	bosh-lite/warden (older bosh-lites, deprecated)
-	bosh/aws

[Learn more](https://blog.starkandwayne.com/2015/04/28/embed-docker-into-bosh-releases/) about embedding Docker images in BOSH releases.

Installation
------------

To use this BOSH release, first upload it to your bosh and the `docker` release

```
bosh upload release https://bosh.io/d/github.com/cf-platform-eng/docker-boshrelease
bosh upload release https://bosh.io/d/github.com/cloudfoundry-community/postgresql-docker-boshrelease
```

For the various Usage cases below you will need this git repo's `templates` folder:

```
git clone https://github.com/cloudfoundry-community/postgresql-docker-boshrelease.git
cd postgresql-docker-boshrelease
```

Usage
-----

### Run a single container of PostgreSQL

For [bosh-lite](https://github.com/cloudfoundry/bosh-lite), you can quickly create a deployment manifest & deploy a single VM:

```
templates/make_manifest warden container embedded
bosh -n deploy
```

This deployment will look like:

```
$ bosh vms postgresql-docker-warden
+------------------------+---------+---------------+--------------+
| Job/index              | State   | Resource Pool | IPs          |
+------------------------+---------+---------------+--------------+
| postgresql_docker_z1/0 | running | small_z1      | 10.244.20.6  |
+------------------------+---------+---------------+--------------+
```

If you want to use the upstream version of the Docker image, reconfigure the deployment manifest:

```
templates/make_manifest warden container upstream
bosh -n deploy
```

To register your Logstash with a Cloud Foundry application on bosh-lite/warden:

```
cf cups postgresql -l syslog://10.244.20.6:514
```

Now bind it to your applications and their STDOUT/STDERR logs will automatically stream to your PostgreSQL.

```
cf bs my-app postgresql
```

### Run a Cloud Foundry service broker for PostgreSQL

For [bosh-lite](https://github.com/cloudfoundry/bosh-lite), you can quickly create a deployment manifest & deploy a single VM that also includes a service broker for Cloud Foundry

```
templates/make_manifest warden broker embedded
bosh -n deploy
```

This deployment will also look like:

```
$ bosh vms postgresql-docker-warden
+------------------------+---------+---------------+--------------+
| Job/index              | State   | Resource Pool | IPs          |
+------------------------+---------+---------------+--------------+
| postgresql_docker_z1/0 | running | small_z1      | 10.244.20.6 |
+------------------------+---------+---------------+--------------+
```

As a Cloud Foundry admin, you can register the broker and the service it provides:

```
cf create-service-broker postgresql-docker containers containers http://10.244.20.6
cf enable-service-access postgresql93
cf marketplace
```

If you want to use the upstream version of the Docker image, reconfigure the deployment manifest:

```
templates/make_manifest warden container upstream
bosh -n deploy
```

### Using Cloud Foundry Service Broker

Users can now provision PostgreSQL services and bind them to their apps.

```
cf cs postgresql93 free my-pg
cf bs my-app my-pg
```

### Versions & configuration

The version of PostgreSQL is determined by the Docker image bundled with the release being used. The source for building the Docker images is in the `images/` folders of this repo. See below for instructions.

### Development of postgresql configuration

To push new ideas/new PostgreSQL versions to an alternate Docker Hub image name:

```
cd images/postgresql95
export DOCKER_USER=<your user>
docker build -t $DOCKER_USER/postgresql .
docker push $DOCKER_USER/postgresql:9.5
```

This will create a new Docker image, based upon the upstream `cfcommunity/postgresql-base:9.5`.

Create an override YAML file, say `my-docker-image.yml`

```yaml
---
meta:
  postgresql_images:
    image: USERNAME/postgresql
    tag: 9.5
```

To deploy this change into BOSH, add the `my-docker-image.yml` file to the end of the `make_manifest` command:

```
./templates/make_manifest warden container upstream my-docker-image.yml
bosh deploy
```

import {Route, RouterModule} from '@angular/router';
import {PlayerComponent} from './player.component';
import {MapComponent} from './map/map.component';
import {AuthGuard} from '../shared/guards/auth.guard';
import {ProfileComponent} from './profile/profile.component';
import {CharacterComponent} from './character/character.component';

/**
 * Routes players are actived when module is lazy loaded.
 * Give access to map, character, forum, ranks, profile
 */
const GAME_ROUTES: Route[] = [
  {path: '', component : PlayerComponent, canActivate: [AuthGuard], children : [
      {path : 'map', component: MapComponent},
      {path : 'character', component: CharacterComponent},
      {path : 'profile', component: ProfileComponent},
      {path : '**', redirectTo : 'map', pathMatch: 'full'}
    ]},
];

export const PlayerRouting = RouterModule.forChild(GAME_ROUTES);

package com.norconex.collector.http.fetch.impl;

import org.junit.jupiter.api.Test;

import com.norconex.commons.lang.xml.XML;

public class GenericHttpFetcherTest  {

    @Test
    public void testWriteRead() {
        GenericHttpFetcherConfig cfg = new GenericHttpFetcherConfig();
        cfg.setValidStatusCodes(200, 201, 202);
        cfg.setNotFoundStatusCodes(404, 405);
        cfg.setHeadersPrefix("blah");
        cfg.setForceCharsetDetection(true);
        cfg.setForceContentTypeDetection(true);

        GenericHttpFetcher f = new GenericHttpFetcher(cfg);
        XML.assertWriteRead(f, "fetcher");
    }
}
package com.handsome.robot.Activity;

import android.content.Context;
import android.opengl.GLSurfaceView;

/**
 * Created by Joern on 2017/08/16.
 */

public class MyGLSurfaceView extends GLSurfaceView {

    private MyPlaneGLRenderer mRenderer;

    public MyGLSurfaceView(Context context) {
        super(context);
       /* // 创建一个OpenGL ES 2.0 context
        setEGLContextClientVersion(2);

        // Set the Renderer for drawing on the GLSurfaceView
        mRenderer = new MyPlaneGLRenderer();
        setRenderer(mRenderer);

        // Render the view only when there is a change in the drawing data
        setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);*/
    }
}

---
title: "Installation des Postfix-Dogu"
---

# Installation des Postfix-Dogu

## Voraussetzung

Für eine erfolgreiche Installation von Postfix muss im etcd vom CES ein Wert für den Relay-Host von Postfix konfiguriert
sein. Dieser wird in der Regel bereits beim Setup des CES gesetzt. Allerdings wird dieser Wert beim Entfernen des Dogus
über den Purge Befehl gelöscht. Der Wert muss dann vor der erneuten Installation vom Postfix neu gesetzt werden. Dies
kann über folgenden Befehl erfolgen:

``` 
etcdctl set /config/postfix/relayhost <Wert für den Relay-Host>
```

## Installation

Postfix can be easily installed via `cesapp` like all other dogus:

```
cesapp install official/postfix
```

/**
 * Logical event-driven API.
 */
export interface IGsLogicalHandler {

	/**
	 * Notify the start of a node.
	 *
	 * @param node Node with its head attributes, his holder property (if it is declared in a map) and its ancestors.
	 *   For empty keys in a map <pre>{key}</pre>, the node type is simple ('') and the body type is empty (''),
	 *   ie a node that has no serialized representation, but a node.holderProp specified.
	 * @param bodyText Must be specified only if node.bodyType==='"', ie a text body node ('"').
	 */
	startNode(node: IGsEventNode, bodyText?: IGsText): void

	/**
	 * Notify the end of a node.
	 * Each startNode() call has it corresponding endNode() call, even for an empty node or an empty key in a map.
	 *
	 * @param node Node with its head and tail attributes and its ancestors
	 */
	endNode(node: IGsEventNode): void
}

/**
 * Low level flat stream event-driven API for whitespaces handling.
 */
export interface IGsStreamHandler {
	headNode(name: IGsName, specialType?: gsSpecialType | null): void

	attribute(name: IGsName, value: IGsValue, specialType?: gsSpecialType | null, spBeforeEq?: string, spAfterEq?: string): void

	text(text: IGsText, inBodyMixed?: boolean): void

	startBody(bodyType: '[' | '{' | '`' | '~`'): void

	property(name: IGsName, isNull: boolean, spBeforeEq?: string): void

	endBody(bodyType: '[' | '{' | '`' | '~`'): void

	tailNode(): void

	whiteSpaces(spaces: string): void
}

/**
 * Serialization strategies and options.
 * - minified: minimize siz but less human readable, elimnating whitespaces when not necessary: <tag att='1'att2='2'>
 * - pretty: spaces are inserted for human readability: <tag att='1' att2='2'>
 * - indented: indentation is added for imbricated nodes.
 * - formatted: nodes are indented, text nodes and attribute values are formatted based on line width.
 */
export type IGsSerializeOptions = {
	method: 'minified'
	unformat?: boolean
} | {
	method: 'pretty'
	unformat?: boolean
} | {
	method: 'indented'
	unformat?: boolean
	indent?: gsIndent
} | {
	method: 'formatted'
	indent?: gsIndent
	lineWidth?: number
};

export type gsIndent = "" | "\t" | " " | "  " | "   " | "    " | "     "

/** Name for a node or an attribute with its escaping rule. */
export interface IGsName {
	name: string;
	nameEsc: gsEscapingStr;
}

/** Attribute value with its escaping rule and its formattable flag. */
export interface IGsValue {
	value: null | string
	valueEsc: gsEscapingValue
	valueFormattable: boolean
}

/**
 * Body Text
 */
export interface IGsText {
	value: string
	valueEsc: gsEscapingText
	valueFormattable: boolean
}

/**
 * Partial node definition used in IGsLogicalHandler
 */
export interface IGsEventNode extends IGsName {
	/** Parent node. */
	readonly parent: IGsEventNode | null

	/** Holder property when the node is declared in a map. */
	readonly holderProp: IGsName | undefined

	/** Depth of this node, ie count of non null parents. */
	readonly depth: number

	/** Node type : standard (null), simple('') or special type('#', '&', '?' or '%').*/
	readonly nodeType: gsNodeType

	/** Name of the node. */
	readonly name: string

	/** Escaping rule for the node. */
	readonly nameEsc: gsEscapingStr

	/** First tail attribute. */
	readonly firstAtt: IGsEventAtt | null

	/** Body type of the node: list ('['), map ('{'), text ('"'), empty (''), mixed ('`') or mixed formattable ('~`'). */
	readonly bodyType: gsEventBodyType

	/** Helper to know if the body type node is mixed or mixed formattable ('`' or '~`'). */
	readonly isBodyMixed: boolean;

	/** Attributes in tail node: only available in IGsLogicalHandler.endNode() and not in IGsLogicalHandler.startNode() */
	readonly firstTailAtt: IGsEventAtt | null

	/**
	 * Get the first attribute with this name and type.
	 * @return the attribute or null if not found.
	 */
	getAttribute(name: string, specialType?: gsSpecialType | null, after?: IGsEventAtt): IGsEventAtt | null

	/**
	 * Get the value of the first attribute with this name and type.
	 * @return null if the attribute exist with no value, undefined if the attribute does not exist.
	 */
	getAttr(name: string, specialType?: gsSpecialType | null): string | null | undefined

	/**
	 * Build a path from the root for retrieving this node. Useful for test and debug.
	 * Path format:
	 * - each anonymous node: {offset} //TODO add offset in IGsEventNode
	 * - each named node: {offset} '~' {name}
	 * - each prop: {name} '='
	 * - node separator: '>'
	 *
	 * Names use the same escaping rules as in GS (raw, quoted or bounded).
	 */
	toPath(): string;
}

/**
 * Attribute definition used in IGsLogicalHandler
 */
export interface IGsEventAtt extends IGsName, IGsValue {
	readonly attType: gsSpecialType | null
	readonly name: string
	readonly nameEsc: gsEscapingStr
	readonly value: string | null
	readonly valueEsc: gsEscapingValue
	readonly valueFormattable: boolean
	readonly offset: number
	readonly inTail: boolean
	readonly next: IGsEventAtt | null

	/**
	 * Build a path from the root for retrieving this attribute. Useful for test and debug.
	 * Attribute format after the owner path: '@' {offset} '~' {name}
	 */
	toPath(owner: IGsEventNode): string;
}


export type gsEscapingStr = /*raw*/ null | /*quoted*/ "'" |  /*bounded*/ `|${string}'`
export type gsEscapingText = /*quoted*/ '"' |  /*bounded*/ `!${string}"` | /*raw for simple node*/ null //TODO | /*base64*/ '$'
export type gsEscapingValue = gsEscapingStr | gsEscapingText

export type gsSpecialType = /*Comment*/ '#' | /*Meta*/ '&' | /*Instruction*/ '%' |  /*Syntax*/ '?'

export type gsNodeType = gsSpecialType | /*standard node*/ null | /*simple node*/ ''

export type gsBodyType = /*empty*/ '' |  /*list*/'[' | /*map*/ '{' | /*text*/ '"' | /*mixed*/ '`'

export type gsEventBodyType = gsBodyType | /*mixed formattable*/ '~`'

/**
 * Regex for avaluate if a string can be serialized as a rawChars (without escaping)
 * rawchars : minusucle || majuscule || -./0-9: || _
 * cardinality '+' in the regExp because an empty string must be quoted: '' or "".
 */
export const rawChars = /^[a-zA-Z\--:_]+$/;

export const whiteSpaces = /^[ \t\r\n]*$/;
// import React from "react"
// import { graphql } from "gatsby"

// export default function Template({
//   data, // this prop will be injected by the GraphQL query below.
// }) {
//   const { blogsJson } = data // data.blogsJson holds our post data
//   const { frontmatter, html } = blogsJson
//   return (
//     <div className="blog-post-container">
//       <div className="blog-post">
//         <h1>{frontmatter.title}</h1>
//         <h2>{frontmatter.date}</h2>
//         <div
//           className="blog-post-content"
//           dangerouslySetInnerHTML={{ __html: html }}
//         />
//       </div>
//     </div>
//   )
// }

// export const pageQuery = graphql`
//   query($path: String!) {
//     blogsJson(frontmatter: { path: { eq: $path } }) {
//       html
//       frontmatter {
//         date(formatString: "MMMM DD, YYYY")
//         path
//         title
//       }
//     }
//   }
// `



// import React from "react"
// import { graphql } from "gatsby"
// import Layout from "../components/layout"

// export default ({ data }) => {
// 	console.log('data:', data);
//   const post = data.markdownRemark
//   return (
//     <Layout>
//       <div>
//         <h1>{post.frontmatter.title}</h1>
//         <div dangerouslySetInnerHTML={{ __html: post.html }} />
//       </div>
//     </Layout>
//   )
// }

// export const query = graphql`
//   query($slug: String!) {
//     markdownRemark(fields: { slug: { eq: $slug } }) {
//       html
//       frontmatter {
//         title
//       }
//     }
//   }
// `
#include "sequence.hpp"
#include "kmer.hpp"
#include "database.hpp"
#include "kmerdb.hpp"

/**************************************************************************************************/

KmerDB::KmerDB(string fastaFileName, int kSize) : Database(), kmerSize(kSize) {
	try { 
	
		kmerDBName = fastaFileName.substr(0,fastaFileName.find_last_of(".")+1) + char('0'+ kmerSize) + "mer";
		
		int power4s[14] = { 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864 };
		count = 0;
		
		maxKmer = power4s[kmerSize];
		kmerLocations.resize(maxKmer+1);
		
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "KmerDB");
		exit(1);
	}	

}
/**************************************************************************************************/
KmerDB::KmerDB() : Database() {}
/**************************************************************************************************/

KmerDB::~KmerDB(){}

/**************************************************************************************************/

vector<int> KmerDB::findClosestSequences(Sequence* candidateSeq, int num){
	try {
		if (num > numSeqs) { m->mothurOut("[WARNING]: you requested " + toString(num) + " closest sequences, but the template only contains " + toString(numSeqs) + ", adjusting."); m->mothurOutEndLine(); num = numSeqs; }
		
		vector<int> topMatches;
		Kmer kmer(kmerSize);
		searchScore = 0;
		Scores.clear();
		
		vector<int> matches(numSeqs, 0);						//	a record of the sequences with shared kmers
		vector<int> timesKmerFound(kmerLocations.size()+1, 0);	//	a record of the kmers that we have already found
		
		int numKmers = candidateSeq->getNumBases() - kmerSize + 1;	
	
		for(int i=0;i<numKmers;i++){
			int kmerNumber = kmer.getKmerNumber(candidateSeq->getUnaligned(), i);		//	go through the query sequence and get a kmer number
			if(timesKmerFound[kmerNumber] == 0){				//	if we haven't seen it before...
				for(int j=0;j<kmerLocations[kmerNumber].size();j++){//increase the count for each sequence that also has
					matches[kmerLocations[kmerNumber][j]]++;	//	that kmer
				}
			}
			timesKmerFound[kmerNumber] = 1;						//	ok, we've seen the kmer now
		}
		
		if (num != 1) {
			vector<seqMatch> seqMatches; seqMatches.resize(numSeqs);
			for(int i=0;i<numSeqs;i++){		
				seqMatches[i].seq = i;
				seqMatches[i].match = matches[i];
			}
			
			//sorts putting largest matches first
			sort(seqMatches.begin(), seqMatches.end(), compareSeqMatches);
			
			searchScore = seqMatches[0].match;
			searchScore = 100 * searchScore / (float) numKmers;		//	return the Sequence object corresponding to the db
		
			//save top matches
			for (int i = 0; i < num; i++) {
				topMatches.push_back(seqMatches[i].seq);
				float thisScore = 100 * seqMatches[i].match / (float) numKmers;
				Scores.push_back(thisScore);
			}
		}else{
			int bestIndex = 0;
			int bestMatch = -1;
			for(int i=0;i<numSeqs;i++){	
				
				if (matches[i] > bestMatch) {
					bestIndex = i;
					bestMatch = matches[i];
				}
			}
			
			searchScore = bestMatch;
			searchScore = 100 * searchScore / (float) numKmers;		//	return the Sequence object corresponding to the db
			topMatches.push_back(bestIndex);
			Scores.push_back(searchScore);
		}
		return topMatches;		
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "findClosestSequences");
		exit(1);
	}	
}

/**************************************************************************************************/

void KmerDB::generateDB(){
	try {
		
		ofstream kmerFile;										//	once we have the kmerLocations folder print it out
		m->openOutputFile(kmerDBName, kmerFile);					//	to a file
		
		//output version
		kmerFile << "#" << m->getVersion() << endl;
		
		for(int i=0;i<maxKmer;i++){								//	step through all of the possible kmer numbers
			kmerFile << i << ' ' << kmerLocations[i].size();	//	print the kmer number and the number of sequences with
			for(int j=0;j<kmerLocations[i].size();j++){			//	that kmer.  then print out the indices of the sequences
				kmerFile << ' ' << kmerLocations[i][j];			//	with that kmer.
			}
			kmerFile << endl;
		}
		kmerFile.close();
		
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "generateDB");
		exit(1);
	}	
	
}
/**************************************************************************************************/
void KmerDB::addSequence(Sequence seq) {
	try {
		Kmer kmer(kmerSize);
		
		string unaligned = seq.getUnaligned();	//	...take the unaligned sequence...
		int numKmers = unaligned.length() - kmerSize + 1;
			
		vector<int> seenBefore(maxKmer+1,0);
		for(int j=0;j<numKmers;j++){						//	...step though the sequence and get each kmer...
			int kmerNumber = kmer.getKmerNumber(unaligned, j);
			if(seenBefore[kmerNumber] == 0){
				kmerLocations[kmerNumber].push_back(count);		//	...insert the sequence index into kmerLocations for
			}												//	the appropriate kmer number
			seenBefore[kmerNumber] = 1;
		}													
	
		count++;
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "addSequence");
		exit(1);
	}	
}
/**************************************************************************************************/

void KmerDB::readKmerDB(ifstream& kmerDBFile){
	try {
					
		kmerDBFile.seekg(0);									//	start at the beginning of the file
		
		//read version
		string line = m->getline(kmerDBFile); m->gobble(kmerDBFile);
		
		string seqName;
		int seqNumber;

		for(int i=0;i<maxKmer;i++){
			int numValues = 0;	
			kmerDBFile >> seqName >> numValues;
			
			for(int j=0;j<numValues;j++){						//	for each kmer number get the...
				kmerDBFile >> seqNumber;						//		1. number of sequences with the kmer number
				kmerLocations[i].push_back(seqNumber);			//		2. sequence indices
			}
		}
		kmerDBFile.close();
		
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "readKmerDB");
		exit(1);
	}	
}

/**************************************************************************************************/
int KmerDB::getCount(int kmer) {
	try {
		if (kmer < 0) { return 0; }  //if user gives negative number
		else if (kmer > maxKmer) {	return 0;	}  //or a kmer that is bigger than maxkmer
		else {	return kmerLocations[kmer].size();	}  // kmer is in vector range
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "getCount");
		exit(1);
	}	
}
/**************************************************************************************************/
int KmerDB::getReversed(int kmerNumber) {
	try {
		Kmer kmer(kmerSize);
		
		if (kmerNumber < 0) { return 0; }  //if user gives negative number
		else if (kmerNumber > maxKmer) {	return 0;	}  //or a kmer that is bigger than maxkmer
		else {	return kmer.getReverseKmerNumber(kmerNumber);	}  // kmer is in vector range
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "getReversed");
		exit(1);
	}	
}
/**************************************************************************************************/
vector<int> KmerDB::getSequencesWithKmer(int kmer) {
	try {
		
		vector<int> seqs;
	
		if (kmer < 0) { }  //if user gives negative number
		else if (kmer > maxKmer) {	}  //or a kmer that is bigger than maxkmer
		else {	seqs = kmerLocations[kmer];	}
		
		return seqs;
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "getSequencesWithKmer");
		exit(1);
	}	
}
/**************************************************************************************************/


/**************************************************************************************************/
<?php

namespace Drupal\commerce;

/**
 * Holds a reference to the current locale, resolved on demand.
 *
 * @see \Drupal\commerce\LocaleContext
 */
interface LocaleContextInterface {

  /**
   * Gets the locale for the current request.
   *
   * @return \Drupal\commerce\Locale
   *   The locale.
   */
  public function getLocale();

}

from ..utils import ApiUtil
from ..utils.ApiUtil import Url


class BlueprintHistories:
    def __init__(self, code, auth_token, blueprint_id):
        self.code = code
        self.auth_token = auth_token
        self.blueprint_id = blueprint_id
        url = Url.blueprintHistoriesList(self.blueprint_id, Url.url)
        data = {
                'auth_token': self.auth_token,
               }
        self.blueprint_histories = ApiUtil.requestGet(url, self.code, data)

    def get_blueprint_history(self, id):
        for blueprint_history in self:
            if blueprint_history['id'] == id:
                return blueprint_history

    def __iter__(self):
        for blueprint_history in self.blueprint_histories:
            yield(blueprint_history)

﻿// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal sealed partial class OverloadResolution
    {
        public void BinaryOperatorOverloadResolution(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);
            Debug.Assert(result.Results.Count == 0);

            // SPEC: An operation of the form x&&y or x||y is processed by applying overload resolution
            // SPEC: as if the operation was written x&y or x|y.

            // SPEC VIOLATION: For compatibility with Dev11, do not apply this rule to built-in conversions.

            BinaryOperatorKind underlyingKind = kind & ~BinaryOperatorKind.Logical;

            // We can do a table lookup for well-known problems in overload resolution.

            BinaryOperatorEasyOut(underlyingKind, left, right, result);
            if (result.Results.Count > 0)
            {
                return;
            }

            // The following is a slight rewording of the specification to emphasize that not all
            // operands of a binary operation need to have a type.

            // SPEC: An operation of the form x op y, where op is an overloadable binary operator is processed as follows:
            // SPEC: The set of candidate user-defined operators provided by the types (if any) of x and y for the 
            // SPEC operation operator op(x, y) is determined. 

            bool hadUserDefinedCandidate = GetUserDefinedOperators(underlyingKind, left, right, result.Results, ref useSiteDiagnostics);

            // @t-mawind
            //   Here, we add in the possibility of having access to a concept
            //   witness defining the binary operator.
            if ((_binder.Flags & BinderFlags.InShim) == 0 && !hadUserDefinedCandidate)
            {
                hadUserDefinedCandidate |= GetBinaryConceptOperators(underlyingKind, left, right, result.Results, ref useSiteDiagnostics);
            }

            // SPEC: If the set of candidate user-defined operators is not empty, then this becomes the set of candidate 
            // SPEC: operators for the operation. Otherwise, the predefined binary operator op implementations, including 
            // SPEC: their lifted forms, become the set of candidate operators for the operation. 

            // Note that the native compiler has a bug in its binary operator overload resolution involving 
            // lifted built-in operators.  The spec says that we should add the lifted and unlifted operators
            // to a candidate set, eliminate the inapplicable operators, and then choose the best of what is left.
            // The lifted operator is defined as, say int? + int? --> int?.  That is not what the native compiler
            // does. The native compiler, rather, effectively says that there are *three* lifted operators:
            // int? + int? --> int?, int + int? --> int? and int? + int --> int?, and it chooses the best operator
            // amongst those choices.  
            //
            // This is a subtle difference; most of the time all it means is that we generate better code because we
            // skip an unnecessary operand conversion to int? when adding int to int?. But some of the time it
            // means that a different user-defined conversion is chosen than the one you would expect, if the
            // operand has a user-defined conversion to both int and int?.
            //
            // Roslyn matches the specification and takes the break from the native compiler.

            if (!hadUserDefinedCandidate)
            {
                result.Results.Clear();
                GetAllBuiltInOperators(kind, left, right, result.Results, ref useSiteDiagnostics);
            }

            // SPEC: The overload resolution rules of 7.5.3 are applied to the set of candidate operators to select the best 
            // SPEC: operator with respect to the argument list (x, y), and this operator becomes the result of the overload 
            // SPEC: resolution process. If overload resolution fails to select a single best operator, a binding-time 
            // SPEC: error occurs.

            BinaryOperatorOverloadResolution(left, right, result, ref useSiteDiagnostics);
        }

        /// <summary>
        /// Populates a list of binary operator results with those from any
        /// witness in scope at the operator site.
        /// </summary>
        /// <param name="kind">
        /// The binary operator kind of the expression.
        /// </param>
        /// <param name="left">
        /// The expression on the left-hand side of the expression.
        /// </param>
        /// <param name="right">
        /// The expression on the right-hand side of the expression.
        /// </param>
        /// <param name="results">
        /// The results list to populate.
        /// </param>
        /// <param name="useSiteDiagnostics">
        /// The set of diagnostics to populate with any errors.
        /// </param>
        /// <returns>
        /// True if we managed to find candidate operators from the concept
        /// witnesses in scope; false otherwise.
        /// </returns>
        private bool GetBinaryConceptOperators(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorAnalysisResult> results, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);

            string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
            var args = ArrayBuilder<BoundExpression>.GetInstance();
            args.Add(left);
            args.Add(right);

            var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
            foreach (var method in GetConceptOperators(name, args.ToImmutableAndFree(), ref useSiteDiagnostics))
            {
                // TODO: nullability
                operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | kind, method.ParameterTypes[0], method.ParameterTypes[1], method.ReturnType, method));
            }

            bool hasCandidates = CandidateOperators(operators, left, right, results, ref useSiteDiagnostics);
            operators.Free();
            return hasCandidates;
        }

        private void AddDelegateOperation(BinaryOperatorKind kind, TypeSymbol delegateType,
            ArrayBuilder<BinaryOperatorSignature> operators)
        {
            switch (kind)
            {
                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, Compilation.GetSpecialType(SpecialType.System_Boolean)));
                    break;

                case BinaryOperatorKind.Addition:
                case BinaryOperatorKind.Subtraction:
                default:
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, delegateType));
                    break;
            }
        }

        private void GetDelegateOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right,
            ArrayBuilder<BinaryOperatorSignature> operators, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);
            AssertNotChecked(kind);

            switch (kind)
            {
                case BinaryOperatorKind.Multiplication:
                case BinaryOperatorKind.Division:
                case BinaryOperatorKind.Remainder:
                case BinaryOperatorKind.RightShift:
                case BinaryOperatorKind.LeftShift:
                case BinaryOperatorKind.And:
                case BinaryOperatorKind.Or:
                case BinaryOperatorKind.Xor:
                case BinaryOperatorKind.GreaterThan:
                case BinaryOperatorKind.LessThan:
                case BinaryOperatorKind.GreaterThanOrEqual:
                case BinaryOperatorKind.LessThanOrEqual:
                case BinaryOperatorKind.LogicalAnd:
                case BinaryOperatorKind.LogicalOr:
                    return;

                case BinaryOperatorKind.Addition:
                case BinaryOperatorKind.Subtraction:
                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                    break;

                default:
                    // Unhandled bin op kind in get delegate operation
                    throw ExceptionUtilities.UnexpectedValue(kind);
            }

            var leftType = left.Type;
            var leftDelegate = (object)leftType != null && leftType.IsDelegateType();
            var rightType = right.Type;
            var rightDelegate = (object)rightType != null && rightType.IsDelegateType();

            // If no operands have delegate types then add nothing.
            if (!leftDelegate && !rightDelegate)
            {
                // Even though neither left nor right type is a delegate type,
                // both types might have implicit conversions to System.Delegate type.

                // Spec 7.10.8: Delegate equality operators:
                // Every delegate type implicitly provides the following predefined comparison operators:
                //     bool operator ==(System.Delegate x, System.Delegate y)
                //     bool operator !=(System.Delegate x, System.Delegate y)

                switch (OperatorKindExtensions.Operator(kind))
                {
                    case BinaryOperatorKind.Equal:
                    case BinaryOperatorKind.NotEqual:
                        TypeSymbol systemDelegateType = _binder.GetSpecialType(SpecialType.System_Delegate, _binder.Compilation.DeclarationDiagnostics, left.Syntax);

                        if (Conversions.ClassifyImplicitConversionFromExpression(left, systemDelegateType, ref useSiteDiagnostics).IsValid &&
                            Conversions.ClassifyImplicitConversionFromExpression(right, systemDelegateType, ref useSiteDiagnostics).IsValid)
                        {
                            AddDelegateOperation(kind, systemDelegateType, operators);
                        }

                        break;
                }

                return;
            }

            // We might have a situation like
            //
            // Func<string> + Func<object>
            // 
            // in which case overload resolution should consider both 
            //
            // Func<string> + Func<string>
            // Func<object> + Func<object>
            //
            // are candidates (and it will pick Func<object>). Similarly,
            // we might have something like:
            //
            // Func<object> + Func<dynamic>
            // 
            // in which case neither candidate is better than the other,
            // resulting in an error.
            //
            // We could as an optimization say that if you are adding two completely
            // dissimilar delegate types D1 and D2, that neither is added to the candidate
            // set because neither can possibly be applicable, but let's not go there.
            // Let's just add them to the set and let overload resolution (and the 
            // error recovery heuristics) have at the real candidate set.
            //
            // However, we will take a spec violation for this scenario:
            //
            // SPEC VIOLATION:
            //
            // Technically the spec implies that we ought to be able to compare 
            // 
            // Func<int> x = whatever;
            // bool y = x == ()=>1;
            //
            // The native compiler does not allow this. I see no
            // reason why we ought to allow this. However, a good question is whether
            // the violation ought to be here, where we are determining the operator
            // candidate set, or in overload resolution where we are determining applicability.
            // In the native compiler we did it during candidate set determination, 
            // so let's stick with that.

            if (leftDelegate && rightDelegate)
            {
                // They are both delegate types. Add them both if they are different types.
                AddDelegateOperation(kind, leftType, operators);

                // There is no reason why we can't compare instances of delegate types that are identity convertible.
                // We can't perform + or - operation on them since it is not clear what the return type of such operation should be.
                bool useIdentityConversion = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;

                if (!(useIdentityConversion ? Conversions.HasIdentityConversion(leftType, rightType) : leftType.Equals(rightType)))
                {
                    AddDelegateOperation(kind, rightType, operators);
                }

                return;
            }

            // One of them is a delegate, the other is not.
            TypeSymbol delegateType = leftDelegate ? leftType : rightType;
            BoundExpression nonDelegate = leftDelegate ? right : left;

            if ((kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual)
                && nonDelegate.Kind == BoundKind.UnboundLambda)
            {
                return;
            }

            AddDelegateOperation(kind, delegateType, operators);
        }

        private void GetEnumOperation(BinaryOperatorKind kind, TypeSymbol enumType, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorSignature> operators)
        {
            Debug.Assert((object)enumType != null);
            AssertNotChecked(kind);

            if (!enumType.IsValidEnumType())
            {
                return;
            }

            var underlying = enumType.GetEnumUnderlyingType();
            Debug.Assert((object)underlying != null);
            Debug.Assert(underlying.SpecialType != SpecialType.None);

            var nullable = Compilation.GetSpecialType(SpecialType.System_Nullable_T);
            var nullableEnum = nullable.Construct(enumType);
            var nullableUnderlying = nullable.Construct(underlying);

            switch (kind)
            {
                case BinaryOperatorKind.Addition:
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingAddition, enumType, underlying, enumType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumAddition, underlying, enumType, enumType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingAddition, nullableEnum, nullableUnderlying, nullableEnum));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumAddition, nullableUnderlying, nullableEnum, nullableEnum));
                    break;
                case BinaryOperatorKind.Subtraction:
                    if (Strict)
                    {
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, underlying));
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, underlying, enumType));
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, nullableEnum, nullableEnum, nullableUnderlying));
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, nullableEnum, nullableUnderlying, nullableEnum));
                    }
                    else
                    {
                        // SPEC VIOLATION:
                        // The native compiler has bugs in overload resolution involving binary operator- for enums,
                        // which we duplicate by hardcoding Priority values among the operators. When present on both
                        // methods being compared during overload resolution, Priority values are used to decide between
                        // two candidates (instead of the usual language-specified rules).
                        bool isExactSubtraction = right.Type?.StrippedType() == underlying;
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, underlying)
                        { Priority = 2 });
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, underlying, enumType)
                        { Priority = isExactSubtraction ? 1 : 3 });
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, nullableEnum, nullableEnum, nullableUnderlying)
                        { Priority = 12 });
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, nullableEnum, nullableUnderlying, nullableEnum)
                        { Priority = isExactSubtraction ? 11 : 13 });

                        // Due to a bug, the native compiler allows "underlying - enum", so Roslyn does as well.
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumSubtraction, underlying, enumType, enumType)
                        { Priority = 4 });
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumSubtraction, nullableUnderlying, nullableEnum, nullableEnum)
                        { Priority = 14 });
                    }
                    break;
                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                case BinaryOperatorKind.GreaterThan:
                case BinaryOperatorKind.LessThan:
                case BinaryOperatorKind.GreaterThanOrEqual:
                case BinaryOperatorKind.LessThanOrEqual:
                    var boolean = Compilation.GetSpecialType(SpecialType.System_Boolean);
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, boolean));
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, nullableEnum, nullableEnum, boolean));
                    break;
                case BinaryOperatorKind.And:
                case BinaryOperatorKind.Or:
                case BinaryOperatorKind.Xor:
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, enumType));
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, nullableEnum, nullableEnum, nullableEnum));
                    break;
            }
        }

        private void GetPointerArithmeticOperators(
            BinaryOperatorKind kind,
            PointerTypeSymbol pointerType,
            ArrayBuilder<BinaryOperatorSignature> operators)
        {
            Debug.Assert((object)pointerType != null);
            AssertNotChecked(kind);

            switch (kind)
            {
                case BinaryOperatorKind.Addition:
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.IntAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType, pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UIntAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType, pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LongAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType, pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.ULongAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType, pointerType));
                    break;
                case BinaryOperatorKind.Subtraction:
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerSubtraction, pointerType, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64)));
                    break;
            }
        }

        private void GetPointerComparisonOperators(
            BinaryOperatorKind kind,
            ArrayBuilder<BinaryOperatorSignature> operators)
        {
            switch (kind)
            {
                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                case BinaryOperatorKind.GreaterThan:
                case BinaryOperatorKind.LessThan:
                case BinaryOperatorKind.GreaterThanOrEqual:
                case BinaryOperatorKind.LessThanOrEqual:
                    var voidPointerType = new PointerTypeSymbol(Compilation.GetSpecialType(SpecialType.System_Void));
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Pointer, voidPointerType, voidPointerType, Compilation.GetSpecialType(SpecialType.System_Boolean)));
                    break;
            }
        }

        private void GetEnumOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorSignature> results)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);
            AssertNotChecked(kind);

            // First take some easy outs:
            switch (kind)
            {
                case BinaryOperatorKind.Multiplication:
                case BinaryOperatorKind.Division:
                case BinaryOperatorKind.Remainder:
                case BinaryOperatorKind.RightShift:
                case BinaryOperatorKind.LeftShift:
                case BinaryOperatorKind.LogicalAnd:
                case BinaryOperatorKind.LogicalOr:
                    return;
            }

            var leftType = left.Type;
            if ((object)leftType != null)
            {
                leftType = leftType.StrippedType();
            }

            var rightType = right.Type;
            if ((object)rightType != null)
            {
                rightType = rightType.StrippedType();
            }

            bool useIdentityConversion;
            switch (kind)
            {
                case BinaryOperatorKind.And:
                case BinaryOperatorKind.Or:
                case BinaryOperatorKind.Xor:
                    // These operations are ambiguous on non-equal identity-convertible types - 
                    // it's not clear what the resulting type of the operation should be:
                    //   C<?>.E operator +(C<dynamic>.E x, C<object>.E y)
                    useIdentityConversion = false;
                    break;

                case BinaryOperatorKind.Addition:
                    // Addition only accepts a single enum type, so operations on non-equal identity-convertible types are not ambiguous. 
                    //   E operator +(E x, U y)
                    //   E operator +(U x, E y)
                    useIdentityConversion = true;
                    break;

                case BinaryOperatorKind.Subtraction:
                    // Subtraction either returns underlying type or only accept a single enum type, so operations on non-equal identity-convertible types are not ambiguous. 
                    //   U operator –(E x, E y)
                    //   E operator –(E x, U y)
                    useIdentityConversion = true;
                    break;

                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                case BinaryOperatorKind.GreaterThan:
                case BinaryOperatorKind.LessThan:
                case BinaryOperatorKind.GreaterThanOrEqual:
                case BinaryOperatorKind.LessThanOrEqual:
                    // Relational operations return Boolean, so operations on non-equal identity-convertible types are not ambiguous. 
                    //   Boolean operator op(C<dynamic>.E, C<object>.E)
                    useIdentityConversion = true;
                    break;

                default:
                    // Unhandled bin op kind in get enum operations
                    throw ExceptionUtilities.UnexpectedValue(kind);
            }

            if ((object)leftType != null)
            {
                GetEnumOperation(kind, leftType, left, right, results);
            }

            if ((object)rightType != null && ((object)leftType == null || !(useIdentityConversion ? Conversions.HasIdentityConversion(rightType, leftType) : rightType.Equals(leftType))))
            {
                GetEnumOperation(kind, rightType, left, right, results);
            }
        }

        private void GetPointerOperators(
            BinaryOperatorKind kind,
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorSignature> results)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);
            AssertNotChecked(kind);

            var leftType = left.Type as PointerTypeSymbol;
            var rightType = right.Type as PointerTypeSymbol;

            if ((object)leftType != null)
            {
                GetPointerArithmeticOperators(kind, leftType, results);
            }

            // The only arithmetic operator that is applicable on two distinct pointer types is
            //   long operator –(T* x, T* y)
            // This operator returns long and so it's not ambiguous to apply it on T1 and T2 that are identity convertible to each other.
            if ((object)rightType != null && ((object)leftType == null || !Conversions.HasIdentityConversion(rightType, leftType)))
            {
                GetPointerArithmeticOperators(kind, rightType, results);
            }

            if ((object)leftType != null || (object)rightType != null)
            {
                // The pointer comparison operators are all "void* OP void*".
                GetPointerComparisonOperators(kind, results);
            }
        }

        private void GetAllBuiltInOperators(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorAnalysisResult> results, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // Strip the "checked" off; the checked-ness of the context does not affect which built-in operators
            // are applicable.
            kind = kind.OperatorWithLogical();
            var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
            bool isEquality = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;
            if (isEquality && UseOnlyReferenceEquality(left, right, ref useSiteDiagnostics))
            {
                // As a special case, if the reference equality operator is applicable (and it
                // is not a string or delegate) we do not check any other operators.  This patches
                // what is otherwise a flaw in the language specification.  See 11426.
                GetReferenceEquality(kind, operators);
            }
            else
            {
                this.Compilation.builtInOperators.GetSimpleBuiltInOperators(kind, operators);

                // SPEC 7.3.4: For predefined enum and delegate operators, the only operators
                // considered are those defined by an enum or delegate type that is the binding
                //-time type of one of the operands.
                GetDelegateOperations(kind, left, right, operators, ref useSiteDiagnostics);
                GetEnumOperations(kind, left, right, operators);

                // We similarly limit pointer operator candidates considered.
                GetPointerOperators(kind, left, right, operators);
            }

            CandidateOperators(operators, left, right, results, ref useSiteDiagnostics);
            operators.Free();
        }

        private bool UseOnlyReferenceEquality(BoundExpression left, BoundExpression right, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            return
                BuiltInOperators.IsValidObjectEquality(Conversions, left.Type, left.IsLiteralNull(), right.Type, right.IsLiteralNull(), ref useSiteDiagnostics) &&
                ((object)left.Type == null || (!left.Type.IsDelegateType() && left.Type.SpecialType != SpecialType.System_String && left.Type.SpecialType != SpecialType.System_Delegate)) &&
                ((object)right.Type == null || (!right.Type.IsDelegateType() && right.Type.SpecialType != SpecialType.System_String && right.Type.SpecialType != SpecialType.System_Delegate));
        }

        private void GetReferenceEquality(BinaryOperatorKind kind, ArrayBuilder<BinaryOperatorSignature> operators)
        {
            var @object = Compilation.GetSpecialType(SpecialType.System_Object);
            operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Object, @object, @object, Compilation.GetSpecialType(SpecialType.System_Boolean)));
        }

        private bool CandidateOperators(
            ArrayBuilder<BinaryOperatorSignature> operators,
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorAnalysisResult> results,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            bool hadApplicableCandidate = false;
            foreach (var op in operators)
            {
                var convLeft = Conversions.ClassifyConversionFromExpression(left, op.LeftType, ref useSiteDiagnostics);
                var convRight = Conversions.ClassifyConversionFromExpression(right, op.RightType, ref useSiteDiagnostics);
                if (convLeft.IsImplicit && convRight.IsImplicit)
                {
                    results.Add(BinaryOperatorAnalysisResult.Applicable(op, convLeft, convRight));
                    hadApplicableCandidate = true;
                }
                else
                {
                    results.Add(BinaryOperatorAnalysisResult.Inapplicable(op, convLeft, convRight));
                }
            }
            return hadApplicableCandidate;
        }

        // Returns an analysis of every matching user-defined binary operator, including whether the
        // operator is applicable or not.

        private bool GetUserDefinedOperators(
            BinaryOperatorKind kind,
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorAnalysisResult> results,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);

            // The following is a slight rewording of the specification to emphasize that not all
            // operands of a binary operation need to have a type.

            // TODO (tomat): The spec needs to be updated to use identity conversion instead of type equality.

            // Spec 7.3.4 Binary operator overload resolution:
            //   An operation of the form x op y, where op is an overloadable binary operator is processed as follows:
            //   The set of candidate user-defined operators provided by the types (if any) of x and y for the 
            //   operation operator op(x, y) is determined. The set consists of the union of the candidate operators
            //   provided by the type of x (if any) and the candidate operators provided by the type of y (if any), 
            //   each determined using the rules of 7.3.5. Candidate operators only occur in the combined set once.

            var operators = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
            TypeSymbol leftType = left.Type;
            TypeSymbol strippedLeftType = leftType?.StrippedType();

            bool hadApplicableCandidate = false;

            if ((object)strippedLeftType != null && !OperatorFacts.DefinitelyHasNoUserDefinedOperators(strippedLeftType))
            {
                hadApplicableCandidate = GetUserDefinedOperators(kind, strippedLeftType, left, right, operators, ref useSiteDiagnostics);
                if (!hadApplicableCandidate)
                {
                    operators.Clear();
                }
            }

            TypeSymbol rightType = right.Type;
            TypeSymbol strippedRightType = rightType?.StrippedType();
            if ((object)strippedRightType != null && !strippedRightType.Equals(strippedLeftType) &&
                !OperatorFacts.DefinitelyHasNoUserDefinedOperators(strippedRightType))
            {
                var rightOperators = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
                hadApplicableCandidate |= GetUserDefinedOperators(kind, strippedRightType, left, right, rightOperators, ref useSiteDiagnostics);
                AddDistinctOperators(operators, rightOperators);
                rightOperators.Free();
            }

            if (hadApplicableCandidate)
            {
                results.AddRange(operators);
            }

            operators.Free();

            return hadApplicableCandidate;
        }

        private static void AddDistinctOperators(ArrayBuilder<BinaryOperatorAnalysisResult> result, ArrayBuilder<BinaryOperatorAnalysisResult> additionalOperators)
        {
            int initialCount = result.Count;

            foreach (var op in additionalOperators)
            {
                bool equivalentToExisting = false;

                for (int i = 0; i < initialCount; i++)
                {
                    var existingSignature = result[i].Signature;

                    Debug.Assert(op.Signature.Kind.Operator() == existingSignature.Kind.Operator());

                    // Return types must match exactly, parameters might match modulo identity conversion.
                    if (op.Signature.Kind == existingSignature.Kind && // Easy out
                        op.Signature.ReturnType.Equals(existingSignature.ReturnType, TypeCompareKind.ConsiderEverything) &&
                        op.Signature.LeftType.Equals(existingSignature.LeftType, TypeCompareKind.IgnoreDynamicAndTupleNames) &&
                        op.Signature.RightType.Equals(existingSignature.RightType, TypeCompareKind.IgnoreDynamicAndTupleNames) &&
                        op.Signature.Method.ContainingType.Equals(existingSignature.Method.ContainingType, TypeCompareKind.IgnoreDynamicAndTupleNames))
                    {
                        equivalentToExisting = true;
                        break;
                    }
                }

                if (!equivalentToExisting)
                {
                    result.Add(op);
                }
            }
        }

        private bool GetUserDefinedOperators(
            BinaryOperatorKind kind,
            TypeSymbol type0,
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorAnalysisResult> results,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // Spec 7.3.5 Candidate user-defined operators
            // SPEC: Given a type T and an operation operator op(A), where op is an overloadable 
            // SPEC: operator and A is an argument list, the set of candidate user-defined operators 
            // SPEC: provided by T for operator op(A) is determined as follows:

            // SPEC: Determine the type T0. If T is a nullable type, T0 is its underlying type, 
            // SPEC: otherwise T0 is equal to T.

            // (The caller has already passed in the stripped type.)

            // SPEC: For all operator op declarations in T0 and all lifted forms of such operators, 
            // SPEC: if at least one operator is applicable (7.5.3.1) with respect to the argument 
            // SPEC: list A, then the set of candidate operators consists of all such applicable 
            // SPEC: operators in T0. Otherwise, if T0 is object, the set of candidate operators is empty.
            // SPEC: Otherwise, the set of candidate operators provided by T0 is the set of candidate 
            // SPEC: operators provided by the direct base class of T0, or the effective base class of
            // SPEC: T0 if T0 is a type parameter.

            string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
            var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
            bool hadApplicableCandidates = false;

            NamedTypeSymbol current = type0 as NamedTypeSymbol;
            if ((object)current == null)
            {
                current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
            }

            if ((object)current == null && type0.IsTypeParameter())
            {
                current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteDiagnostics);
            }

            for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
            {
                operators.Clear();
                GetUserDefinedBinaryOperatorsFromType(current, kind, name, operators);
                results.Clear();
                if (CandidateOperators(operators, left, right, results, ref useSiteDiagnostics))
                {
                    hadApplicableCandidates = true;
                    break;
                }
            }

            operators.Free();

            return hadApplicableCandidates;
        }

        private void GetUserDefinedBinaryOperatorsFromType(
            NamedTypeSymbol type,
            BinaryOperatorKind kind,
            string name,
            ArrayBuilder<BinaryOperatorSignature> operators)
        {
            foreach (MethodSymbol op in type.GetOperators(name))
            {
                // If we're in error recovery, we might have bad operators. Just ignore it.
                if (op.ParameterCount != 2 || op.ReturnsVoid)
                {
                    continue;
                }

                TypeSymbol leftOperandType = op.ParameterTypes[0];
                TypeSymbol rightOperandType = op.ParameterTypes[1];
                TypeSymbol resultType = op.ReturnType;

                operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | kind, leftOperandType, rightOperandType, resultType, op));

                LiftingResult lifting = UserDefinedBinaryOperatorCanBeLifted(leftOperandType, rightOperandType, resultType, kind);

                if (lifting == LiftingResult.LiftOperandsAndResult)
                {
                    operators.Add(new BinaryOperatorSignature(
                        BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind,
                        MakeNullable(leftOperandType), MakeNullable(rightOperandType), MakeNullable(resultType), op));
                }
                else if (lifting == LiftingResult.LiftOperandsButNotResult)
                {
                    operators.Add(new BinaryOperatorSignature(
                        BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind,
                        MakeNullable(leftOperandType), MakeNullable(rightOperandType), resultType, op));
                }
            }
        }

        private enum LiftingResult
        {
            NotLifted,
            LiftOperandsAndResult,
            LiftOperandsButNotResult
        }

        private static LiftingResult UserDefinedBinaryOperatorCanBeLifted(TypeSymbol left, TypeSymbol right, TypeSymbol result, BinaryOperatorKind kind)
        {
            // SPEC: For the binary operators + - * / % & | ^ << >> a lifted form of the
            // SPEC: operator exists if the operand and result types are all non-nullable
            // SPEC: value types. The lifted form is constructed by adding a single ?
            // SPEC: modifier to each operand and result type. 
            //
            // SPEC: For the equality operators == != a lifted form of the operator exists
            // SPEC: if the operand types are both non-nullable value types and if the 
            // SPEC: result type is bool. The lifted form is constructed by adding
            // SPEC: a single ? modifier to each operand type.
            //
            // SPEC: For the relational operators > < >= <= a lifted form of the 
            // SPEC: operator exists if the operand types are both non-nullable value
            // SPEC: types and if the result type is bool. The lifted form is 
            // SPEC: constructed by adding a single ? modifier to each operand type.

            if (!left.IsValueType ||
                left.IsNullableType() ||
                !right.IsValueType ||
                right.IsNullableType())
            {
                return LiftingResult.NotLifted;
            }

            switch (kind)
            {
                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                    // Spec violation: can't lift unless the types match.
                    // The spec doesn't require this, but dev11 does and it reduces ambiguity in some cases.
                    if (left != right) return LiftingResult.NotLifted;
                    goto case BinaryOperatorKind.GreaterThan;
                case BinaryOperatorKind.GreaterThan:
                case BinaryOperatorKind.GreaterThanOrEqual:
                case BinaryOperatorKind.LessThan:
                case BinaryOperatorKind.LessThanOrEqual:
                    return result.SpecialType == SpecialType.System_Boolean ?
                        LiftingResult.LiftOperandsButNotResult :
                        LiftingResult.NotLifted;
                default:
                    return result.IsValueType && !result.IsNullableType() ?
                        LiftingResult.LiftOperandsAndResult :
                        LiftingResult.NotLifted;
            }
        }

        // Takes a list of candidates and mutates the list to throw out the ones that are worse than
        // another applicable candidate.
        private void BinaryOperatorOverloadResolution(
            BoundExpression left,
            BoundExpression right,
            BinaryOperatorOverloadResolutionResult result,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // SPEC: Given the set of applicable candidate function members, the best function member in that set is located. 
            // SPEC: If the set contains only one function member, then that function member is the best function member. 

            if (result.SingleValid())
            {
                return;
            }

            // SPEC: Otherwise, the best function member is the one function member that is better than all other function 
            // SPEC: members with respect to the given argument list, provided that each function member is compared to all 
            // SPEC: other function members using the rules in 7.5.3.2. If there is not exactly one function member that is 
            // SPEC: better than all other function members, then the function member invocation is ambiguous and a binding-time 
            // SPEC: error occurs.

            var candidates = result.Results;
            // Try to find a single best candidate
            int bestIndex = GetTheBestCandidateIndex(left, right, candidates, ref useSiteDiagnostics);
            if (bestIndex != -1)
            {
                // Mark all other candidates as worse
                for (int index = 0; index < candidates.Count; ++index)
                {
                    if (candidates[index].Kind != OperatorAnalysisResultKind.Inapplicable && index != bestIndex)
                    {
                        candidates[index] = candidates[index].Worse();
                    }
                }

                return;
            }

            for (int i = 1; i < candidates.Count; ++i)
            {
                if (candidates[i].Kind != OperatorAnalysisResultKind.Applicable)
                {
                    continue;
                }

                // Is this applicable operator better than every other applicable method?
                for (int j = 0; j < i; ++j)
                {
                    if (candidates[j].Kind == OperatorAnalysisResultKind.Inapplicable)
                    {
                        continue;
                    }

                    var better = BetterOperator(candidates[i].Signature, candidates[j].Signature, left, right, ref useSiteDiagnostics);
                    if (better == BetterResult.Left)
                    {
                        candidates[j] = candidates[j].Worse();
                    }
                    else if (better == BetterResult.Right)
                    {
                        candidates[i] = candidates[i].Worse();
                    }
                }
            }
        }

        private int GetTheBestCandidateIndex(
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorAnalysisResult> candidates,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            int currentBestIndex = -1;
            for (int index = 0; index < candidates.Count; index++)
            {
                if (candidates[index].Kind != OperatorAnalysisResultKind.Applicable)
                {
                    continue;
                }

                // Assume that the current candidate is the best if we don't have any
                if (currentBestIndex == -1)
                {
                    currentBestIndex = index;
                }
                else
                {
                    var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, left, right, ref useSiteDiagnostics);
                    if (better == BetterResult.Right)
                    {
                        // The current best is worse
                        currentBestIndex = index;
                    }
                    else if (better != BetterResult.Left)
                    {
                        // The current best is not better
                        currentBestIndex = -1;
                    }
                }
            }

            // Make sure that every candidate up to the current best is worse
            for (int index = 0; index < currentBestIndex; index++)
            {
                if (candidates[index].Kind == OperatorAnalysisResultKind.Inapplicable)
                {
                    continue;
                }

                var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, left, right, ref useSiteDiagnostics);
                if (better != BetterResult.Left)
                {
                    // The current best is not better
                    return -1;
                }
            }

            return currentBestIndex;
        }

        private BetterResult BetterOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, BoundExpression left, BoundExpression right, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // We use Priority as a tie-breaker to help match native compiler bugs.
            Debug.Assert(op1.Priority.HasValue == op2.Priority.HasValue);
            if (op1.Priority.HasValue && op1.Priority.GetValueOrDefault() != op2.Priority.GetValueOrDefault())
            {
                return (op1.Priority.GetValueOrDefault() < op2.Priority.GetValueOrDefault()) ? BetterResult.Left : BetterResult.Right;
            }

            BetterResult leftBetter = BetterConversionFromExpression(left, op1.LeftType, op2.LeftType, ref useSiteDiagnostics);
            BetterResult rightBetter = BetterConversionFromExpression(right, op1.RightType, op2.RightType, ref useSiteDiagnostics);

            // SPEC: Mp is defined to be a better function member than Mq if:
            // SPEC: * For each argument, the implicit conversion from Ex to Qx is not better than
            // SPEC:   the implicit conversion from Ex to Px, and
            // SPEC: * For at least one argument, the conversion from Ex to Px is better than the 
            // SPEC:   conversion from Ex to Qx.

            // If that is hard to follow, consult this handy chart:
            // op1.Left vs op2.Left     op1.Right vs op2.Right    result
            // -----------------------------------------------------------
            // op1 better               op1 better                op1 better
            // op1 better               neither better            op1 better
            // op1 better               op2 better                neither better
            // neither better           op1 better                op1 better
            // neither better           neither better            neither better
            // neither better           op2 better                op2 better
            // op2 better               op1 better                neither better
            // op2 better               neither better            op2 better
            // op2 better               op2 better                op2 better

            if (leftBetter == BetterResult.Left && rightBetter != BetterResult.Right ||
                leftBetter != BetterResult.Right && rightBetter == BetterResult.Left)
            {
                return BetterResult.Left;
            }

            if (leftBetter == BetterResult.Right && rightBetter != BetterResult.Left ||
                leftBetter != BetterResult.Left && rightBetter == BetterResult.Right)
            {
                return BetterResult.Right;
            }

            // There was no better member on the basis of conversions. Go to the tiebreaking round.

            // SPEC: In case the parameter type sequences P1, P2 and Q1, Q2 are equivalent -- that is, every Pi
            // SPEC: has an identity conversion to the corresponding Qi -- the following tie-breaking rules
            // SPEC: are applied:

            if (Conversions.HasIdentityConversion(op1.LeftType, op2.LeftType) &&
                Conversions.HasIdentityConversion(op1.RightType, op2.RightType))
            {
                // NOTE: The native compiler does not follow these rules; effectively, the native 
                // compiler checks for liftedness first, and then for specificity. For example:
                // struct S<T> where T : struct {
                //   public static bool operator +(S<T> x, int y) { return true; }
                //   public static bool? operator +(S<T>? x, int? y) { return false; }
                // }
                // 
                // bool? b = new S<int>?() + new int?();
                //
                // should reason as follows: the two applicable operators are the lifted
                // form of the first operator and the unlifted second operator. The
                // lifted form of the first operator is *more specific* because int?
                // is more specific than T?.  Therefore it should win. In fact the 
                // native compiler chooses the second operator, because it is unlifted.
                // 
                // Roslyn follows the spec rules; if we decide to change the spec to match
                // the native compiler, or decide to change Roslyn to match the native
                // compiler, we should change the order of the checks here.

                // SPEC: If Mp has more specific parameter types than Mq then Mp is better than Mq.
                BetterResult result = MoreSpecificOperator(op1, op2, ref useSiteDiagnostics);
                if (result == BetterResult.Left || result == BetterResult.Right)
                {
                    return result;
                }

                // SPEC: If one member is a non-lifted operator and the other is a lifted operator,
                // SPEC: the non-lifted one is better.

                bool lifted1 = op1.Kind.IsLifted();
                bool lifted2 = op2.Kind.IsLifted();

                if (lifted1 && !lifted2)
                {
                    return BetterResult.Right;
                }
                else if (!lifted1 && lifted2)
                {
                    return BetterResult.Left;
                }
            }

            return BetterResult.Neither;
        }

        private BetterResult MoreSpecificOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            TypeSymbol op1Left, op1Right, op2Left, op2Right;
            if ((object)op1.Method != null)
            {
                var p = op1.Method.OriginalDefinition.GetParameters();
                op1Left = p[0].Type;
                op1Right = p[1].Type;
                if (op1.Kind.IsLifted())
                {
                    op1Left = MakeNullable(op1Left);
                    op1Right = MakeNullable(op1Right);
                }
            }
            else
            {
                op1Left = op1.LeftType;
                op1Right = op1.RightType;
            }

            if ((object)op2.Method != null)
            {
                var p = op2.Method.OriginalDefinition.GetParameters();
                op2Left = p[0].Type;
                op2Right = p[1].Type;
                if (op2.Kind.IsLifted())
                {
                    op2Left = MakeNullable(op2Left);
                    op2Right = MakeNullable(op2Right);
                }
            }
            else
            {
                op2Left = op2.LeftType;
                op2Right = op2.RightType;
            }

            var uninst1 = ArrayBuilder<TypeSymbol>.GetInstance();
            var uninst2 = ArrayBuilder<TypeSymbol>.GetInstance();

            uninst1.Add(op1Left);
            uninst1.Add(op1Right);

            uninst2.Add(op2Left);
            uninst2.Add(op2Right);

            BetterResult result = MoreSpecificType(uninst1, uninst2, ref useSiteDiagnostics);

            uninst1.Free();
            uninst2.Free();

            return result;
        }

        [Conditional("DEBUG")]
        private static void AssertNotChecked(BinaryOperatorKind kind)
        {
            Debug.Assert((kind & ~BinaryOperatorKind.Checked) == kind, "Did not expect operator to be checked.  Consider using .Operator() to mask.");
        }
    }
}

package extension

import (
	envoy_config_core_v3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
	hcm_filter "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/durationpb"

	extensions "istio.io/api/extensions/v1alpha1"
	"istio.io/istio/pilot/pkg/model"
	"istio.io/istio/pilot/pkg/networking"
	authzmodel "istio.io/istio/pilot/pkg/security/authz/model"
	securitymodel "istio.io/istio/pilot/pkg/security/model"
)

const (
	wasmFilterType  = "envoy.extensions.filters.http.wasm.v3.Wasm"
	statsFilterName = "istio.stats"
)

var defaultConfigSource = &envoy_config_core_v3.ConfigSource{
	ConfigSourceSpecifier: &envoy_config_core_v3.ConfigSource_Ads{
		Ads: &envoy_config_core_v3.AggregatedConfigSource{},
	},
	ResourceApiVersion: envoy_config_core_v3.ApiVersion_V3,
	// we block proxy init until WasmPlugins are loaded because they might be
	// critical for security (e.g. authn/authz)
	InitialFetchTimeout: &durationpb.Duration{Seconds: 0},
}

// AddWasmPluginsToMutableObjects adds WasmPlugins to HTTP filterChains
// Note that the slices in the map must already be ordered by plugin
// priority! This will be the case for maps returned by PushContext.WasmPlugin()
func AddWasmPluginsToMutableObjects(
	mutable *networking.MutableObjects,
	extensionsMap map[extensions.PluginPhase][]*model.WasmPluginWrapper,
) {
	if mutable == nil {
		return
	}

	for fcIndex, fc := range mutable.FilterChains {
		// we currently only support HTTP
		if fc.ListenerProtocol != networking.ListenerProtocolHTTP {
			continue
		}
		mutable.FilterChains[fcIndex].HTTP = injectExtensions(fc.HTTP, extensionsMap)
	}
}

func injectExtensions(filterChain []*hcm_filter.HttpFilter, exts map[extensions.PluginPhase][]*model.WasmPluginWrapper) []*hcm_filter.HttpFilter {
	// copy map as we'll manipulate it in the loop
	extMap := make(map[extensions.PluginPhase][]*model.WasmPluginWrapper)
	for phase, list := range exts {
		extMap[phase] = []*model.WasmPluginWrapper{}
		extMap[phase] = append(extMap[phase], list...)
	}
	newHTTPFilters := make([]*hcm_filter.HttpFilter, 0)
	// The following algorithm tries to make as few assumptions as possible about the filter
	// chain - it might contain any number of filters that will have to retain their ordering.
	// The one assumption we make is about the ordering of the builtin filters. This is used to
	// position WasmPlugins relatively to the builtin filters according to their phase: when
	// we see the Stats filter, we know that all WasmPlugins with phases AUTHN, AUTHZ and STATS
	// must be injected before it. This method allows us to inject WasmPlugins in the right spots
	// while retaining any filters that were unknown at the time of writing this algorithm,
	// in linear time. The assumed ordering of builtin filters is:
	//
	// 1. Istio JWT, 2. Istio AuthN, 3. RBAC, 4. Stats, 5. Metadata Exchange
	//
	// TODO: how to deal with ext-authz? RBAC will be in the chain twice in that case
	for _, httpFilter := range filterChain {
		switch httpFilter.Name {
		case securitymodel.EnvoyJwtFilterName:
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHN)
			newHTTPFilters = append(newHTTPFilters, httpFilter)
		case securitymodel.AuthnFilterName:
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHN)
			newHTTPFilters = append(newHTTPFilters, httpFilter)
		case authzmodel.RBACHTTPFilterName:
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHN)
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHZ)
			newHTTPFilters = append(newHTTPFilters, httpFilter)
		case statsFilterName:
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHN)
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHZ)
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_STATS)
			newHTTPFilters = append(newHTTPFilters, httpFilter)
		default:
			newHTTPFilters = append(newHTTPFilters, httpFilter)
		}
	}
	// append all remaining extensions at the end. This is required because not all builtin filters
	// are always present (e.g. RBAC is only present when an AuthorizationPolicy was created), so
	// we might not have emptied all slices in the map.
	newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHN)
	newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHZ)
	newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_STATS)
	newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_UNSPECIFIED_PHASE)
	return newHTTPFilters
}

func popAppend(list []*hcm_filter.HttpFilter,
	filterMap map[extensions.PluginPhase][]*model.WasmPluginWrapper,
	phase extensions.PluginPhase) []*hcm_filter.HttpFilter {
	for _, ext := range filterMap[phase] {
		list = append(list, toEnvoyHTTPFilter(ext))
	}
	filterMap[phase] = []*model.WasmPluginWrapper{}
	return list
}

func toEnvoyHTTPFilter(wasmPlugin *model.WasmPluginWrapper) *hcm_filter.HttpFilter {
	return &hcm_filter.HttpFilter{
		Name: wasmPlugin.Namespace + "." + wasmPlugin.Name,
		ConfigType: &hcm_filter.HttpFilter_ConfigDiscovery{
			ConfigDiscovery: &envoy_config_core_v3.ExtensionConfigSource{
				ConfigSource: defaultConfigSource,
				TypeUrls:     []string{"type.googleapis.com/" + wasmFilterType},
			},
		},
	}
}

// InsertedExtensionConfigurations returns pre-generated extension configurations added via WasmPlugin.
func InsertedExtensionConfigurations(
	wasmPlugins map[extensions.PluginPhase][]*model.WasmPluginWrapper,
	names []string) []*envoy_config_core_v3.TypedExtensionConfig {
	result := make([]*envoy_config_core_v3.TypedExtensionConfig, 0)
	if len(wasmPlugins) == 0 {
		return result
	}
	hasName := make(map[string]bool)
	for _, n := range names {
		hasName[n] = true
	}
	for _, list := range wasmPlugins {
		for _, p := range list {
			if _, ok := hasName[p.Namespace+"."+p.Name]; !ok {
				continue
			}
			result = append(result, proto.Clone(p.ExtensionConfiguration).(*envoy_config_core_v3.TypedExtensionConfig))
		}
	}
	return result
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.frre.library.data;

/**
 *
 * @author justomiguel
 */
public final class DataSource {
    
    public static String apellidos = "Roma\n" +
"Buzón\n" +
"Sanguino\n" +
"Matesanz\n" +
"Del Rosario\n" +
"Igual\n" +
"San Emeterio\n" +
"José\n" +
"Manresa\n" +
"Planells\n" +
"Victoria\n" +
"Ciobanu\n" +
"Lazar\n" +
"Mayol\n" +
"De Souza\n" +
"Bustillo\n" +
"Lorite\n" +
"Orti\n" +
"Recuero\n" +
"Manchón\n" +
"Salva\n" +
"Verges\n" +
"Miñano\n" +
"Gamiz\n" +
"Villalonga\n" +
"Queralt\n" +
"Bañon\n" +
"Bethencourt\n" +
"Tinoco\n" +
"Cancela\n" +
"Montaña\n" +
"Vivar\n" +
"Ji\n" +
"Espínola\n" +
"Cabanes\n" +
"Arriaga\n" +
"Herrador\n" +
"Limón\n" +
"Mozo\n" +
"Ilie\n" +
"Cara\n" +
"Dolz\n" +
"Pariente\n" +
"Artola\n" +
"Arrizabalaga\n" +
"Fortuny\n" +
"Barquín\n" +
"Vasco\n" +
"Claros\n" +
"Estruch\n" +
"Chinea\n" +
"Benet\n" +
"Villalta\n" +
"Domene\n" +
"Ezquerro\n" +
"Pares\n" +
"Rojano\n" +
"Gras\n" +
"Bohórquez\n" +
"Piris\n" +
"Tendero\n" +
"Bruno\n" +
"Estrella\n" +
"Suero\n" +
"Valenciano\n" +
"Godino\n" +
"Campuzano\n" +
"Garrigós\n" +
"Ligero\n" +
"Humanes\n" +
"Garijo\n" +
"Santacruz\n" +
"Gallart\n" +
"Ollé\n" +
"Santander\n" +
"Isla\n" +
"Comino\n" +
"Rufo\n" +
"Cubillo\n" +
"Llabres\n" +
"Jaume\n" +
"Barrul\n" +
"Ospina\n" +
"Cava\n" +
"Santaella\n" +
"Brown\n" +
"Zapatero\n" +
"Doval\n" +
"Sanjurjo\n" +
"Corredera\n" +
"Gaona\n" +
"Cerón\n" +
"Madariaga\n" +
"Gibert\n" +
"Muller\n" +
"Matute\n" +
"Salgueiro\n" +
"Sillero\n" +
"Villarroya\n" +
"Molto\n" +
"Colas\n" +
"Cárceles\n" +
"Sesma\n" +
"Montaner\n" +
"Carril\n" +
"Dopico\n" +
"Camarasa\n" +
"Olalla\n" +
"Oliveros\n" +
"Londoño\n" +
"Poyatos\n" +
"Villarejo\n" +
"Risco\n" +
"Sarria\n" +
"Callejón\n" +
"Abarca\n" +
"Nava\n" +
"Etxebarria\n" +
"Ulloa\n" +
"Odriozola\n" +
"Marfil\n" +
"Taylor\n" +
"Pol\n" +
"Pernas\n" +
"Arco\n" +
"Rusu\n" +
"Gay\n" +
"Menacho\n" +
"Paños\n" +
"Peñaranda\n" +
"Polanco\n" +
"Palmer\n" +
"Granell\n" +
"Armendáriz\n" +
"Pires\n" +
"Calvet\n" +
"Lama\n" +
"Allende\n" +
"Feito\n" +
"Sureda\n" +
"Arguello\n" +
"Platero\n" +
"Bataller\n" +
"Melchor\n" +
"Tarín\n" +
"Lugo\n" +
"Rubia\n" +
"De los Ríos\n" +
"Serban\n" +
"Olive\n" +
"Cuello\n" +
"Arrebola\n" +
"Cabaleiro\n" +
"Teixidó\n" +
"Balde\n" +
"Riesco\n" +
"Elizalde\n" +
"Stefan\n" +
"Astorga\n" +
"Castelo\n" +
"Pedreira\n" +
"Bocanegra\n" +
"Caño\n" +
"Bel\n" +
"Fariñas\n" +
"Arredondo\n" +
"Juez\n" +
"Orgaz\n" +
"Riba\n" +
"Torrens\n" +
"Gordon\n" +
"Gala\n" +
"Ezquerra\n" +
"Magaña\n" +
"Doblas\n" +
"Adrian\n" +
"Corredor\n" +
"Llamazares\n" +
"Presa\n" +
"Oñate\n" +
"Mestres\n" +
"Cabral\n" +
"Capel\n" +
"Gaya\n" +
"Cuadra\n" +
"Crespi\n" +
"Carazo\n" +
"Ovejero\n" +
"Mamani\n" +
"Clavería\n" +
"Falco\n" +
"Sebastia\n" +
"Cantarero\n" +
"Vigil\n" +
"Solorzano\n" +
"Cavero\n" +
"Salom\n" +
"Alejo\n" +
"Rubiales\n" +
"Pintos\n" +
"Albarracín\n" +
"Malo\n" +
"Larios\n" +
"Almodóvar\n" +
"Justicia\n" +
"Soares\n" +
"Molins\n" +
"Doncel\n" +
"Holguín\n" +
"Moraga\n" +
"Lanza\n" +
"Nogués\n" +
"Escalera\n" +
"Calviño\n" +
"Orihuela\n" +
"Arnedo\n" +
"Palenzuela\n" +
"Armero\n" +
"Monserrat\n" +
"Bonillo\n" +
"Cacho\n" +
"Guedes\n" +
"Barber\n" +
"Ariño\n" +
"Troya\n" +
"Gual\n" +
"Hortelano\n" +
"Gavira\n" +
"Rayo\n" +
"Corominas\n" +
"Williams\n" +
"Dimitrova\n" +
"Gomáriz\n" +
"Lechuga\n" +
"Puebla\n" +
"Mula\n" +
"Augusto\n" +
"Terol\n" +
"Traore\n" +
"Magdaleno\n" +
"Illescas\n" +
"Etxeberria\n" +
"Cremades\n" +
"Marzo\n" +
"Gomila\n" +
"Gregori\n" +
"Montañez\n" +
"Adrover\n" +
"Marchante\n" +
"Zapico\n" +
"Carrascal\n" +
"Elena\n" +
"Villalón\n" +
"Ortín\n" +
"Feliz\n" +
"Lemos\n" +
"Matei\n" +
"Aldea\n" +
"Elorza\n" +
"Adame\n" +
"Garate\n" +
"Fornes\n" +
"Vilaplana\n" +
"Insua\n" +
"Obregón\n" +
"Escolar\n" +
"Llobet\n" +
"Adell\n" +
"Guaman\n" +
"Illán\n" +
"Bouza\n" +
"Castellón\n" +
"Boluda\n" +
"Rioja\n" +
"Portilla\n" +
"Pallas\n" +
"Hu\n" +
"Enrique\n" +
"Trueba\n" +
"Junquera\n" +
"Mayordomo\n" +
"Padin\n" +
"Fandiño\n" +
"Folch\n" +
"Munuera\n" +
"Agustín\n" +
"Góngora\n" +
"Baz\n" +
"Muela\n" +
"Melgarejo\n" +
"Benedicto\n" +
"Laborda\n" +
"Zabaleta\n" +
"Cea\n" +
"Boada\n" +
"Leyva\n" +
"Aranguren\n" +
"Teijeiro\n" +
"Puentes\n" +
"Castellá\n" +
"Salvado\n" +
"Morant\n" +
"Tejeda\n" +
"Antonio\n" +
"Madueño\n" +
"Lasheras\n" +
"Utrilla\n" +
"Cubas\n" +
"Vinuesa\n" +
"Ivars\n" +
"Ricart\n" +
"Viña\n" +
"Darias\n" +
"Verde\n" +
"Gallegos\n" +
"Galdeano\n" +
"David\n" +
"Corona\n" +
"Berbel\n" +
"Escobedo\n" +
"Mendieta\n" +
"Uría\n" +
"Restrepo\n" +
"Ciudad\n" +
"Malló\n" +
"Espí\n" +
"Candel\n" +
"Ledo\n" +
"Alcañiz\n" +
"Piera\n" +
"Varas\n" +
"Jove\n" +
"Palacín\n" +
"Camarena\n" +
"Galdón\n" +
"Belenguer\n" +
"Reverte\n" +
"Pont\n" +
"Lopera\n" +
"Fábregas\n" +
"Roura\n" +
"Collazo\n" +
"De Sousa\n" +
"Canosa\n" +
"Berrio\n" +
"Montserrat\n" +
"Urbina\n" +
"Magro\n" +
"Estepa\n" +
"Miñana\n" +
"Batalla\n" +
"Bouzas\n" +
"Pimentel\n" +
"Vaz\n" +
"Mesas\n" +
"Cruzado\n" +
"Regueira\n" +
"Hermosilla\n" +
"Armenteros\n" +
"Flor\n" +
"Azcona\n" +
"Días\n" +
"Goncalves\n" +
"Troncoso\n" +
"Collantes\n" +
"Sicilia\n" +
"Jiang\n" +
"Novillo\n" +
"Hernán\n" +
"Molano\n" +
"Georgieva\n" +
"Córdova\n" +
"Vilalta\n" +
"Oliveras\n" +
"Larrosa\n" +
"Del Hoyo\n" +
"Machuca\n" +
"Quijada\n" +
"Lerma\n" +
"Del Cerro\n" +
"Mayorga\n" +
"Girona\n" +
"Cañellas\n" +
"Brenes\n" +
"Lumbreras\n" +
"Brotons\n" +
"Chamizo\n" +
"Dios\n" +
"Malagón\n" +
"Moscoso\n" +
"Gamarra\n" +
"Mancera\n" +
"Rodas\n" +
"Llacer\n" +
"Gascó\n" +
"Marquina\n" +
"Zarco\n" +
"Villaescusa\n" +
"Boza\n" +
"Seijo\n" +
"Cabrerizo\n" +
"Torralbo\n" +
"Comesaña\n" +
"Tamarit\n" +
"Gelabert\n" +
"Piquer\n" +
"Pelegrín\n" +
"Hussain\n" +
"Trejo\n" +
"Del Toro\n" +
"Fabra\n" +
"Agustí\n" +
"Callejas\n" +
"Cejudo\n" +
"Perona\n" +
"Balboa\n" +
"Marchena\n" +
"Llop\n" +
"Prades\n" +
"Magán\n" +
"Requejo\n" +
"Hernanz\n" +
"Jareño\n" +
"Moure\n" +
"Cedeño\n" +
"Toral\n" +
"Vivo\n" +
"Bernat\n" +
"Ocampo\n" +
"Gargallo\n" +
"Amengual\n" +
"Alegría\n" +
"Batlle\n" +
"Rodero\n" +
"Gamboa\n" +
"Bárcena\n" +
"Tortajada\n" +
"Pou\n" +
"Callejo\n" +
"Monedero\n" +
"Aracil\n" +
"Gándara\n" +
"Hevia\n" +
"Coloma\n" +
"Hueso\n" +
"Barrado\n" +
"Maeso\n" +
"Dimitrov\n" +
"Galeano\n" +
"Azorín\n" +
"Somoza\n" +
"Asensi\n" +
"Trigueros\n" +
"Borreguero\n" +
"Borrell\n" +
"Baro\n" +
"Bauza\n" +
"Mur\n" +
"Corpas\n" +
"Cuadros\n" +
"Rendón\n" +
"Zarza\n" +
"Villarroel\n" +
"Herráez\n" +
"Pachón\n" +
"Pose\n" +
"Guillamón\n" +
"Bertomeu\n" +
"Alcocer\n" +
"De la Hoz\n" +
"Galarza\n" +
"Castiñeira\n" +
"Iñigo\n" +
"Gabaldón\n" +
"De los Reyes\n" +
"Piedra\n" +
"Calvente\n" +
"Tabares\n" +
"Gaitán\n" +
"Gijón\n" +
"Escolano\n" +
"Serrat\n" +
"Valdivieso\n" +
"Alberola\n" +
"Bayona\n" +
"Patón\n" +
"Losa\n" +
"Popescu\n" +
"Galisteo\n" +
"Oltra\n" +
"Sirvent\n" +
"Chinchilla\n" +
"Huang\n" +
"Avalos\n" +
"Vicario\n" +
"Quintela\n" +
"Vicens\n" +
"Corbalán\n" +
"Varona\n" +
"Algaba\n" +
"Aceituno\n" +
"Jin\n" +
"Noya\n" +
"Tercero\n" +
"Bajo\n" +
"Calabuig\n" +
"Salado\n" +
"Llado\n" +
"Colmenero\n" +
"Hita\n" +
"Gheorghe\n" +
"Notario\n" +
"Vasile\n" +
"Barrachina\n" +
"Pitarch\n" +
"March\n" +
"Torras\n" +
"Fresneda\n" +
"Arango\n" +
"Rego\n" +
"Melo\n" +
"Cruces\n" +
"Pagan\n" +
"Stan\n" +
"Velarde\n" +
"Pajuelo\n" +
"Córcoles\n" +
"Solsona\n" +
"Guillem\n" +
"Quispe\n" +
"Correas\n" +
"Lavín\n" +
"Saborido\n" +
"Espina\n" +
"Zarate\n" +
"Curiel\n" +
"Palencia\n" +
"Mulet\n" +
"Solera\n" +
"De Lucas\n" +
"Monzo\n" +
"Olea\n" +
"Aller\n" +
"Almendros\n" +
"Del Val\n" +
"Rosario\n" +
"Clavero\n" +
"Bedoya\n" +
"Curto\n" +
"De Blas\n" +
"Ballesta\n" +
"Mihai\n" +
"Georgiev\n" +
"Bernárdez\n" +
"Goicoechea\n" +
"Negrín\n" +
"Cao\n" +
"Pintor\n" +
"Barreda\n" +
"Franch\n" +
"Aguero\n" +
"Edo\n" +
"Bellón\n" +
"Lasa\n" +
"Bernad\n" +
"Morente\n" +
"Huete\n" +
"Izaguirre\n" +
"Guasch\n" +
"Mercader\n" +
"Tolosa\n" +
"Albero\n" +
"Pastrana\n" +
"Araque\n" +
"Cueva\n" +
"Mondéjar\n" +
"Stoica\n" +
"Constantin\n" +
"Coto\n" +
"Barquero\n" +
"Blanca\n" +
"Liñán\n" +
"Romeu\n" +
"Rangel\n" +
"Mate\n" +
"Yepes\n" +
"De Juan\n" +
"Pombo\n" +
"Pinedo\n" +
"Regalado\n" +
"Egido\n" +
"Curbelo\n" +
"Artero\n" +
"Navalón\n" +
"Estébanez\n" +
"Ortigosa\n" +
"Parreño\n" +
"Del Rey\n" +
"Llinares\n" +
"Cortina\n" +
"Vivancos\n" +
"Canet\n" +
"Jones\n" +
"Selles\n" +
"Acero\n" +
"Feliu\n" +
"Matilla\n" +
"Motos\n" +
"Arrabal\n" +
"Simarro\n" +
"Borrero\n" +
"Kaur\n" +
"Barral\n" +
"Gadea\n" +
"Lopes\n" +
"Blanes\n" +
"Iranzo\n" +
"Múgica\n" +
"Samaniego\n" +
"Nuño\n" +
"Toscano\n" +
"Carreira\n" +
"Rozas\n" +
"Baquero\n" +
"Lage\n" +
"Funes\n" +
"Alguacil\n" +
"Artigas\n" +
"Borges\n" +
"Bas\n" +
"Liébana\n" +
"Andrades\n" +
"Matamoros\n" +
"Pan\n" +
"Moll\n" +
"Duro\n" +
"Lastra\n" +
"Masip\n" +
"Ferrándiz\n" +
"Vendrell\n" +
"Barrionuevo\n" +
"Pereiro\n" +
"Marina\n" +
"Reinoso\n" +
"Mendizábal\n" +
"Yang\n" +
"Higuera\n" +
"Iborra\n" +
"Gonzálvez\n" +
"Amo\n" +
"Torrecilla\n" +
"Alcolea\n" +
"Valbuena\n" +
"Rosselló\n" +
"Torrico\n" +
"Laso\n" +
"Cayuela\n" +
"Viana\n" +
"Romeo\n" +
"Da Costa\n" +
"Couto\n" +
"Lavado\n" +
"Vicent\n" +
"Rúa\n" +
"Mendes\n" +
"Niño\n" +
"Yanes\n" +
"San Román\n" +
"Posada\n" +
"Pantoja\n" +
"Viejo\n" +
"Orta\n" +
"Arnal\n" +
"Barcia\n" +
"Varo\n" +
"Béjar\n" +
"Brea\n" +
"Cases\n" +
"Devesa\n" +
"Graña\n" +
"Parrado\n" +
"Torrecillas\n" +
"Gonzales\n" +
"Uceda\n" +
"Abadía\n" +
"Orts\n" +
"Busquets\n" +
"Ferri\n" +
"Aramburu\n" +
"Lahoz\n" +
"Ferro\n" +
"Vieira\n" +
"Casillas\n" +
"Landa\n" +
"Pablos\n" +
"Llano\n" +
"Quílez\n" +
"Roque\n" +
"Águila\n" +
"Diz\n" +
"Galiana\n" +
"Barrena\n" +
"Camarero\n" +
"Morata\n" +
"Torrente\n" +
"Cózar\n" +
"Rosas\n" +
"Fontán\n" +
"Artiles\n" +
"Monfort\n" +
"Huguet\n" +
"Seijas\n" +
"Del Barrio\n" +
"Nebot\n" +
"Mengual\n" +
"Mirón\n" +
"Venegas\n" +
"Salvatierra\n" +
"Pablo\n" +
"Escamilla\n" +
"Pedrero\n" +
"Oller\n" +
"Dumitru\n" +
"Carnero\n" +
"Parras\n" +
"Abascal\n" +
"Cutillas\n" +
"Félix\n" +
"Trinidad\n" +
"Henríquez\n" +
"Alsina\n" +
"Mangas\n" +
"Antelo\n" +
"Romano\n" +
"Terán\n" +
"Coronel\n" +
"Bolívar\n" +
"Vilariño\n" +
"Ramis\n" +
"Colom\n" +
"Torrijos\n" +
"Nicolau\n" +
"De Pedro\n" +
"Lledó\n" +
"Conejero\n" +
"Calzado\n" +
"Quintas\n" +
"Vigo\n" +
"Diop\n" +
"Aguayo\n" +
"Jáuregui\n" +
"Campaña\n" +
"Canal\n" +
"Armengol\n" +
"Iñiguez\n" +
"Cuartero\n" +
"Uribe\n" +
"Miras\n" +
"Canals\n" +
"Fabregat\n" +
"Sendra\n" +
"Riveiro\n" +
"Rosillo\n" +
"Cerrato\n" +
"Bazán\n" +
"Gandía\n" +
"Tébar\n" +
"Asencio\n" +
"Machín\n" +
"Escalona\n" +
"Amaro\n" +
"Barco\n" +
"Pradas\n" +
"Villarreal\n" +
"Caraballo\n" +
"Barón\n" +
"Plata\n" +
"Roa\n" +
"Mulero\n" +
"Sotelo\n" +
"Tornero\n" +
"Alcón\n" +
"Pomares\n" +
"De Paz\n" +
"Caravaca\n" +
"Cantón\n" +
"Castejón\n" +
"Concepción\n" +
"Dura\n" +
"Almazán\n" +
"Castell\n" +
"Utrera\n" +
"Rocamora\n" +
"Moliner\n" +
"Arguelles\n" +
"Sedano\n" +
"Manjón\n" +
"Gázquez\n" +
"Arregui\n" +
"Macho\n" +
"Vilas\n" +
"Loureiro\n" +
"Infantes\n" +
"Fortes\n" +
"Monroy\n" +
"Panadero\n" +
"Granero\n" +
"Milla\n" +
"Velásquez\n" +
"Cabañas\n" +
"Morell\n" +
"Moldovan\n" +
"Morgado\n" +
"Maqueda\n" +
"Carbó\n" +
"Valladares\n" +
"Vacas\n" +
"Cepeda\n" +
"Gabarre\n" +
"Carracedo\n" +
"Tenorio\n" +
"Castrillo\n" +
"Triguero\n" +
"Zambrana\n" +
"Morante\n" +
"Plana\n" +
"Priego\n" +
"Arcas\n" +
"Moraleda\n" +
"Ndiaye\n" +
"Querol\n" +
"Abella\n" +
"Ribeiro\n" +
"Peñas\n" +
"Muro\n" +
"Raposo\n" +
"Zheng\n" +
"Porto\n" +
"Puche\n" +
"Palmero\n" +
"Siles\n" +
"Bayo\n" +
"De Frutos\n" +
"Almansa\n" +
"Berlanga\n" +
"Regueiro\n" +
"Agüera\n" +
"Pozuelo\n" +
"Ivanova\n" +
"Roncero\n" +
"Bertrán\n" +
"Barahona\n" +
"De Oliveira\n" +
"María\n" +
"Mico\n" +
"Reguera\n" +
"Justo\n" +
"Terrón\n" +
"Aguiar\n" +
"Pelayo\n" +
"Jodar\n" +
"Teixeira\n" +
"Lluch\n" +
"Radu\n" +
"Carbajo\n" +
"Cisneros\n" +
"Montañés\n" +
"Clavijo\n" +
"Párraga\n" +
"Noriega\n" +
"Montesdeoca\n" +
"Cañada\n" +
"Gea\n" +
"Albarrán\n" +
"Ginés\n" +
"Miguélez\n" +
"Escrivá\n" +
"Sarabia\n" +
"Rabadán\n" +
"Cortijo\n" +
"Roda\n" +
"De Jesús\n" +
"Alberdi\n" +
"Cadenas\n" +
"Antequera\n" +
"Cascales\n" +
"Garrote\n" +
"Buitrago\n" +
"Picón\n" +
"Granda\n" +
"Ángel\n" +
"Giráldez\n" +
"Company\n" +
"Zorrilla\n" +
"Sanabria\n" +
"De Andrés\n" +
"Cuervo\n" +
"Castillejo\n" +
"Zhu\n" +
"Donaire\n" +
"Meneses\n" +
"Valentín\n" +
"Triviño\n" +
"Paya\n" +
"Blanch\n" +
"De la Calle\n" +
"Amigo\n" +
"Portero\n" +
"Dalmau\n" +
"Porta\n" +
"Gregorio\n" +
"De Pablo\n" +
"Carpintero\n" +
"Mediavilla\n" +
"Busto\n" +
"Milán\n" +
"Mancebo\n" +
"Monreal\n" +
"Villalobos\n" +
"Porcel\n" +
"Anguita\n" +
"Molla\n" +
"Miquel\n" +
"Piñol\n" +
"Poza\n" +
"Madrigal\n" +
"Torrent\n" +
"Larrañaga\n" +
"Val\n" +
"Pita\n" +
"Zúñiga\n" +
"Tormo\n" +
"Barreto\n" +
"Blas\n" +
"Donoso\n" +
"Rama\n" +
"Escalante\n" +
"De la Vega\n" +
"Barriga\n" +
"Bou\n" +
"Vadillo\n" +
"Montalbán\n" +
"Capilla\n" +
"Ayllón\n" +
"Salido\n" +
"Pintado\n" +
"Garay\n" +
"Martel\n" +
"Guardia\n" +
"Iriarte\n" +
"Cabo\n" +
"Quintanilla\n" +
"Hierro\n" +
"Ali\n" +
"Espinar\n" +
"Corbacho\n" +
"Torrado\n" +
"Albaladejo\n" +
"Puga\n" +
"Sabaté\n" +
"Ferrández\n" +
"Vilanova\n" +
"Garmendia\n" +
"Briones\n" +
"Monje\n" +
"Esparza\n" +
"Bayón\n" +
"Aragonés\n" +
"Matías\n" +
"Benavent\n" +
"Maestro\n" +
"Ropero\n" +
"Asenjo\n" +
"Palomar\n" +
"Pagés\n" +
"Candela\n" +
"Del Amo\n" +
"Casanovas\n" +
"Agulló\n" +
"Lorca\n" +
"Coello\n" +
"Déniz\n" +
"Arrieta\n" +
"Gallo\n" +
"Daza\n" +
"De Haro\n" +
"Simo\n" +
"Salamanca\n" +
"De la Peña\n" +
"Llorca\n" +
"Cerro\n" +
"Ferreras\n" +
"Cabrero\n" +
"Casero\n" +
"Montalvo\n" +
"Mérida\n" +
"Pajares\n" +
"Rius\n" +
"Mato\n" +
"Verdejo\n" +
"Anaya\n" +
"Vara\n" +
"De la Iglesia\n" +
"Reche\n" +
"Larrea\n" +
"Urrutia\n" +
"Jover\n" +
"Higueras\n" +
"Elías\n" +
"Cueto\n" +
"Bernardo\n" +
"Conejo\n" +
"Ivanov\n" +
"Casares\n" +
"Valderrama\n" +
"Pueyo\n" +
"Ferrera\n" +
"Calzada\n" +
"Chica\n" +
"Ruz\n" +
"Gomis\n" +
"Fernandes\n" +
"Dorta\n" +
"Tur\n" +
"Ugarte\n" +
"Florido\n" +
"Jorda\n" +
"Morato\n" +
"Pereda\n" +
"Abreu\n" +
"Benavente\n" +
"Gavilán\n" +
"Lillo\n" +
"Melgar\n" +
"Barbosa\n" +
"Guirao\n" +
"Paris\n" +
"Betancor\n" +
"Matos\n" +
"Samper\n" +
"Plasencia\n" +
"Barrientos\n" +
"Mármol\n" +
"Casals\n" +
"Espino\n" +
"Saldaña\n" +
"Morera\n" +
"Nogueira\n" +
"Gaspar\n" +
"Julia\n" +
"Oviedo\n" +
"Bastida\n" +
"San Miguel\n" +
"Cardoso\n" +
"Valcárcel\n" +
"Muriel\n" +
"Carranza\n" +
"Olivera\n" +
"Mercado\n" +
"Holgado\n" +
"Castells\n" +
"Tejera\n" +
"Carpio\n" +
"Camino\n" +
"Morilla\n" +
"Gabarri\n" +
"Torrejón\n" +
"Lima\n" +
"Amat\n" +
"Julián\n" +
"Reig\n" +
"Meseguer\n" +
"Smith\n" +
"Martins\n" +
"Campoy\n" +
"Quiñones\n" +
"Amado\n" +
"Chaparro\n" +
"Seco\n" +
"Tudela\n" +
"Cornejo\n" +
"Garriga\n" +
"San Juan\n" +
"Mañas\n" +
"Cerdán\n" +
"Monteagudo\n" +
"Aliaga\n" +
"Portela\n" +
"Aroca\n" +
"Gilabert\n" +
"Maza\n" +
"Trillo\n" +
"Cristóbal\n" +
"Piña\n" +
"Popa\n" +
"Espín\n" +
"Megias\n" +
"Gomes\n" +
"Figueras\n" +
"Cabanillas\n" +
"Gisbert\n" +
"Llanos\n" +
"Berrocal\n" +
"Cañizares\n" +
"Perello\n" +
"Zhou\n" +
"Guevara\n" +
"Liu\n" +
"Arnaiz\n" +
"Galiano\n" +
"Sans\n" +
"Roselló\n" +
"Feijoo\n" +
"Wu\n" +
"Montenegro\n" +
"Postigo\n" +
"Uriarte\n" +
"Canto\n" +
"Guirado\n" +
"Flórez\n" +
"Colomer\n" +
"Hoyos\n" +
"Guardiola\n" +
"Mansilla\n" +
"Verdugo\n" +
"Rio\n" +
"Capdevila\n" +
"Cordón\n" +
"Del Moral\n" +
"Sacristán\n" +
"Antúnez\n" +
"Vico\n" +
"Rosell\n" +
"Fonseca\n" +
"Centeno\n" +
"Sempere\n" +
"Belda\n" +
"Comas\n" +
"Elvira\n" +
"Nieves\n" +
"Benavides\n" +
"Silvestre\n" +
"Cantos\n" +
"Yagüe\n" +
"Lora\n" +
"Palazón\n" +
"Quero\n" +
"Alemany\n" +
"Torralba\n" +
"Vaca\n" +
"Neira\n" +
"Jimeno\n" +
"Jaime\n" +
"Hermoso\n" +
"Parejo\n" +
"Labrador\n" +
"Herraiz\n" +
"Pop\n" +
"Ramiro\n" +
"Sousa\n" +
"Caamaño\n" +
"Chico\n" +
"Li\n" +
"Nevado\n" +
"Toledano\n" +
"Espinoza\n" +
"De Dios\n" +
"Pellicer\n" +
"Revilla\n" +
"Vegas\n" +
"Rus\n" +
"Farré\n" +
"Calatayud\n" +
"Antolín\n" +
"Ribes\n" +
"Amores\n" +
"Adán\n" +
"Riquelme\n" +
"Vilches\n" +
"Mera\n" +
"Diallo\n" +
"Segui\n" +
"Viera\n" +
"Guisado\n" +
"Perera\n" +
"Botella\n" +
"Arellano\n" +
"Carrascosa\n" +
"Girón\n" +
"Romo\n" +
"Álamo\n" +
"Novo\n" +
"Arnau\n" +
"Amor\n" +
"Codina\n" +
"Quiroga\n" +
"Andújar\n" +
"Solana\n" +
"Gordo\n" +
"Sabater\n" +
"Torregrosa\n" +
"Oliveira\n" +
"Pico\n" +
"Mestre\n" +
"Ureña\n" +
"Frutos\n" +
"Cañadas\n" +
"Rial\n" +
"Palau\n" +
"Xu\n" +
"Céspedes\n" +
"Gamero\n" +
"Parada\n" +
"De los Santos\n" +
"Carrero\n" +
"Picazo\n" +
"Lema\n" +
"Goñi\n" +
"Sepúlveda\n" +
"Sales\n" +
"Narváez\n" +
"Zurita\n" +
"Mir\n" +
"Tovar\n" +
"Revuelta\n" +
"Pedraza\n" +
"Acuña\n" +
"Planas\n" +
"Fuente\n" +
"Cañete\n" +
"Piqueras\n" +
"Meléndez\n" +
"Quiles\n" +
"Mariscal\n" +
"Ye\n" +
"Valdivia\n" +
"Fariña\n" +
"Hinojosa\n" +
"Cuellar\n" +
"Fidalgo\n" +
"Mayoral\n" +
"Cervantes\n" +
"Vivas\n" +
"Costas\n" +
"Coca\n" +
"Rodenas\n" +
"Parrilla\n" +
"Saura\n" +
"Camps\n" +
"Melian\n" +
"Boix\n" +
"Martorell\n" +
"Arana\n" +
"Montilla\n" +
"Lloret\n" +
"Encinas\n" +
"Buendía\n" +
"Molinero\n" +
"Carro\n" +
"Monzón\n" +
"Giraldo\n" +
"Palacio\n" +
"Bernabéu\n" +
"Peiro\n" +
"Tome\n" +
"Sanmartín\n" +
"Lamas\n" +
"Badía\n" +
"Toribio\n" +
"Coronado\n" +
"Pina\n" +
"Cubero\n" +
"Peral\n" +
"Téllez\n" +
"Mayo\n" +
"Bernabé\n" +
"Mariño\n" +
"Barbera\n" +
"Talavera\n" +
"Ibarra\n" +
"Puerta\n" +
"Zamorano\n" +
"Granado\n" +
"Matas\n" +
"Espada\n" +
"Prat\n" +
"Bolaños\n" +
"Caparros\n" +
"De Diego\n" +
"Mejía\n" +
"Balaguer\n" +
"Puerto\n" +
"Quevedo\n" +
"Iniesta\n" +
"España\n" +
"Morillas\n" +
"Montaño\n" +
"Perdomo\n" +
"Herreros\n" +
"Segarra\n" +
"Macia\n" +
"De las Heras\n" +
"Acedo\n" +
"Hermida\n" +
"Francés\n" +
"Torre\n" +
"Rodrigues\n" +
"Lujan\n" +
"Merchán\n" +
"Trigo\n" +
"Francisco\n" +
"Robledo\n" +
"Almagro\n" +
"Checa\n" +
"Ares\n" +
"Úbeda\n" +
"Sevillano\n" +
"Ortuño\n" +
"Raya\n" +
"Manzanares\n" +
"Cifuentes\n" +
"Zhang\n" +
"Echevarría\n" +
"Medrano\n" +
"Teruel\n" +
"Lucena\n" +
"Dueñas\n" +
"Canales\n" +
"Villena\n" +
"Novoa\n" +
"Jaramillo\n" +
"Sampedro\n" +
"Del Olmo\n" +
"Villaverde\n" +
"Mota\n" +
"Pinilla\n" +
"Manrique\n" +
"Miro\n" +
"Pedrosa\n" +
"Atienza\n" +
"Echeverría\n" +
"Diego\n" +
"Machado\n" +
"Míguez\n" +
"Viñas\n" +
"Berenguer\n" +
"Nogales\n" +
"Galera\n" +
"Maroto\n" +
"Cerda\n" +
"Yuste\n" +
"Albert\n" +
"Alemán\n" +
"Infante\n" +
"Ribera\n" +
"Maya\n" +
"Peñalver\n" +
"Batista\n" +
"Manso\n" +
"Alves\n" +
"Álvaro\n" +
"Morón\n" +
"Barros\n" +
"Patiño\n" +
"De León\n" +
"Tamayo\n" +
"Abril\n" +
"Prados\n" +
"Padrón\n" +
"Diéguez\n" +
"Báez\n" +
"Ayuso\n" +
"Vásquez\n" +
"Bejarano\n" +
"Amorós\n" +
"Prada\n" +
"Sandoval\n" +
"Lobo\n" +
"Barrero\n" +
"Arteaga\n" +
"San Martin\n" +
"Del Campo\n" +
"Barea\n" +
"Taboada\n" +
"Almeida\n" +
"Climent\n" +
"Tortosa\n" +
"Montiel\n" +
"Mayor\n" +
"Catalá\n" +
"Moro\n" +
"Jordán\n" +
"Jara\n" +
"Fraga\n" +
"Orellana\n" +
"Verdú\n" +
"Ferrando\n" +
"Conesa\n" +
"Jerez\n" +
"Veiga\n" +
"Zabala\n" +
"Mari\n" +
"Sarmiento\n" +
"Ripoll\n" +
"Armas\n" +
"Salmerón\n" +
"Cazorla\n" +
"Pallares\n" +
"Rocha\n" +
"Ferre\n" +
"Tello\n" +
"Bustos\n" +
"Seoane\n" +
"Sobrino\n" +
"Sanjuán\n" +
"Tejedor\n" +
"Acevedo\n" +
"Ledesma\n" +
"Ahmed\n" +
"Monge\n" +
"Vilar\n" +
"Valera\n" +
"Cañas\n" +
"Baños\n" +
"De Castro\n" +
"Nadal\n" +
"Fuster\n" +
"Tejada\n" +
"Enríquez\n" +
"Casal\n" +
"Alegre\n" +
"Campillo\n" +
"Arcos\n" +
"Bustamante\n" +
"Gago\n" +
"Montoro\n" +
"Moreira\n" +
"Murcia\n" +
"Zaragoza\n" +
"Jaén\n" +
"Chávez\n" +
"Luengo\n" +
"Peris\n" +
"Perales\n" +
"Leiva\n" +
"Urbano\n" +
"Wang\n" +
"Vizcaíno\n" +
"Pareja\n" +
"Sebastián\n" +
"Gascón\n" +
"Bellido\n" +
"Olmos\n" +
"Vílchez\n" +
"Carreras\n" +
"Puertas\n" +
"Zafra\n" +
"Baeza\n" +
"Del Pino\n" +
"Felipe\n" +
"Ceballos\n" +
"Lin\n" +
"Mínguez\n" +
"Montesinos\n" +
"Castañeda\n" +
"Borja\n" +
"Prats\n" +
"San José\n" +
"Maestre\n" +
"Osuna\n" +
"Del Castillo\n" +
"Orozco\n" +
"Molero\n" +
"Alvarado\n" +
"Carreño\n" +
"Castello\n" +
"Osorio\n" +
"Palomares\n" +
"Laguna\n" +
"Ribas\n" +
"Mellado\n" +
"Palomino\n" +
"Calle\n" +
"Mira\n" +
"Garcés\n" +
"Fuertes\n" +
"Afonso\n" +
"Barceló\n" +
"Yáñez\n" +
"Bilbao\n" +
"Llopis\n" +
"Borras\n" +
"Valiente\n" +
"Giner\n" +
"Quirós\n" +
"Cabeza\n" +
"Souto\n" +
"Abellán\n" +
"Barranco\n" +
"Hervás\n" +
"Salguero\n" +
"Piñero\n" +
"Andrade\n" +
"Páez\n" +
"Amaya\n" +
"Olmo\n" +
"Haro\n" +
"Brito\n" +
"Arce\n" +
"Poveda\n" +
"Valles\n" +
"Salcedo\n" +
"Mateu\n" +
"Serna\n" +
"Bartolomé\n" +
"Chaves\n" +
"Garzón\n" +
"Araujo\n" +
"Rebollo\n" +
"Noguera\n" +
"Del Pozo\n" +
"Bonet\n" +
"Llorens\n" +
"Heras\n" +
"Pazos\n" +
"Avilés\n" +
"Lafuente\n" +
"Vives\n" +
"Alcalá\n" +
"Paniagua\n" +
"Sáenz\n" +
"De Miguel\n" +
"Ferrero\n" +
"Alcalde\n" +
"Alcázar\n" +
"Tena\n" +
"Figueroa\n" +
"Solano\n" +
"Rosado\n" +
"Pena\n" +
"Zambrano\n" +
"Olmedo\n" +
"Mosquera\n" +
"Huerta\n" +
"Pla\n" +
"Calleja\n" +
"Pizarro\n" +
"Frías\n" +
"Moyano\n" +
"Grande\n" +
"Dorado\n" +
"Dávila\n" +
"Chamorro\n" +
"Criado\n" +
"Freire\n" +
"Duque\n" +
"Valdés\n" +
"Tirado\n" +
"Dos Santos\n" +
"Espejo\n" +
"Rosales\n" +
"Portillo\n" +
"Lobato\n" +
"Galván\n" +
"Tejero\n" +
"Gordillo\n" +
"Real\n" +
"Gonzalo\n" +
"Llamas\n" +
"Agudo\n" +
"Morillo\n" +
"Barrio\n" +
"Royo\n" +
"Melero\n" +
"Alcaide\n" +
"Romera\n" +
"Jorge\n" +
"Cánovas\n" +
"Fajardo\n" +
"Sainz\n" +
"Peinado\n" +
"Ariza\n" +
"Carvajal\n" +
"Pavón\n" +
"Arjona\n" +
"Del Valle\n" +
"Duarte\n" +
"Toro\n" +
"Valenzuela\n" +
"Barbero\n" +
"Guijarro\n" +
"Ruano\n" +
"Aznar\n" +
"Morcillo\n" +
"Borrego\n" +
"Huertas\n" +
"Solé\n" +
"Segovia\n" +
"Ferreiro\n" +
"Cerezo\n" +
"Godoy\n" +
"Estrada\n" +
"Cebrián\n" +
"Alcántara\n" +
"Fraile\n" +
"Barragán\n" +
"Catalán\n" +
"Falcón\n" +
"Castellanos\n" +
"Corrales\n" +
"Egea\n" +
"Sastre\n" +
"Gámez\n" +
"Peralta\n" +
"Campo\n" +
"Rovira\n" +
"Mejías\n" +
"Losada\n" +
"Latorre\n" +
"Singh\n" +
"Alfaro\n" +
"Vergara\n" +
"Bello\n" +
"Valls\n" +
"Granados\n" +
"Tapia\n" +
"Navarrete\n" +
"Ocaña\n" +
"Pujol\n" +
"Ochoa\n" +
"Becerra\n" +
"Vaquero\n" +
"Madrid\n" +
"Puente\n" +
"Vélez\n" +
"Angulo\n" +
"Cervera\n" +
"Cuadrado\n" +
"Cabezas\n" +
"Cobos\n" +
"Barreiro\n" +
"Coll\n" +
"Ventura\n" +
"Barba\n" +
"Palma\n" +
"Pino\n" +
"Muñiz\n" +
"Recio\n" +
"Cardona\n" +
"Arranz\n" +
"Porras\n" +
"Belmonte\n" +
"Herranz\n" +
"Baena\n" +
"Nicolás\n" +
"Lago\n" +
"Rincón\n" +
"Miralles\n" +
"Casanova\n" +
"Sala\n" +
"De la Rosa\n" +
"Arévalo\n" +
"Palomo\n" +
"Sanchís\n" +
"Cantero\n" +
"Castilla\n" +
"Ballester\n" +
"Marrero\n" +
"Pineda\n" +
"Cid\n" +
"Perea\n" +
"Cámara\n" +
"Bosch\n" +
"Quintero\n" +
"Salinas\n" +
"Grau\n" +
"Pinto\n" +
"Solís\n" +
"Esteve\n" +
"Marques\n" +
"Barrios\n" +
"Da Silva\n" +
"Olivares\n" +
"Piñeiro\n" +
"Carballo\n" +
"Luis\n" +
"Ayala\n" +
"Font\n" +
"Sevilla\n" +
"Requena\n" +
"Peláez\n" +
"Alfonso\n" +
"Prado\n" +
"Villegas\n" +
"Arribas\n" +
"Carbonell\n" +
"Salgado\n" +
"Vela\n" +
"Moral\n" +
"Toledo\n" +
"Zapata\n" +
"Llorente\n" +
"Saavedra\n" +
"Chacón\n" +
"Mohamed\n" +
"Sola\n" +
"Riera\n" +
"Velázquez\n" +
"Alcaraz\n" +
"Juárez\n" +
"Domenech\n" +
"Cárdenas\n" +
"Cobo\n" +
"Correa\n" +
"Calero\n" +
"Ferreira\n" +
"Cáceres\n" +
"Córdoba\n" +
"Andreu\n" +
"Rosa\n" +
"Hernando\n" +
"Carrera\n" +
"Castellano\n" +
"Villa\n" +
"Chen\n" +
"Clemente\n" +
"Carrión\n" +
"Aragón\n" +
"Roig\n" +
"Sosa\n" +
"Bonilla\n" +
"Carretero\n" +
"Oliver\n" +
"Burgos\n" +
"Leal\n" +
"Ojeda\n" +
"Amador\n" +
"Linares\n" +
"Moran\n" +
"Reina\n" +
"Paz\n" +
"Villalba\n" +
"Mata\n" +
"Naranjo\n" +
"Aguirre\n" +
"Polo\n" +
"Caro\n" +
"Lucas\n" +
"Valencia\n" +
"Ramón\n" +
"Asensio\n" +
"Mena\n" +
"Vallejo\n" +
"Escribano\n" +
"Galindo\n" +
"Domingo\n" +
"Arenas\n" +
"Soria\n" +
"Aguado\n" +
"Navas\n" +
"Pulido\n" +
"Saiz\n" +
"Rojo\n" +
"Cabello\n" +
"Puig\n" +
"Alba\n" +
"Corral\n" +
"Gimeno\n" +
"Ordoñez\n" +
"Barrera\n" +
"De la Torre\n" +
"Quesada\n" +
"Ros\n" +
"Barroso\n" +
"Marco\n" +
"Cuevas\n" +
"Martos\n" +
"Montoya\n" +
"De la Cruz\n" +
"Cuenca\n" +
"Murillo\n" +
"Pozo\n" +
"Collado\n" +
"Cordero\n" +
"Mas\n" +
"Oliva\n" +
"Juan\n" +
"Lorente\n" +
"Rodrigo\n" +
"Ponce\n" +
"Bautista\n" +
"Valle\n" +
"Maldonado\n" +
"Valverde\n" +
"Ballesteros\n" +
"Antón\n" +
"Paredes\n" +
"Bermejo\n" +
"Salvador\n" +
"Zamora\n" +
"Castaño\n" +
"Luna\n" +
"Alarcón\n" +
"Millán\n" +
"Blasco\n" +
"Escobar\n" +
"Del Rio\n" +
"Mesa\n" +
"Sancho\n" +
"Lázaro\n" +
"De la Fuente\n" +
"Pons\n" +
"Ávila\n" +
"Pacheco\n" +
"Simón\n" +
"Trujillo\n" +
"Rueda\n" +
"Hurtado\n" +
"Tomas\n" +
"Manzano\n" +
"Cuesta\n" +
"Villanueva\n" +
"Guzmán\n" +
"Serra\n" +
"Salazar\n" +
"Santamaría\n" +
"Miguel\n" +
"Bermúdez\n" +
"Costa\n" +
"Roca\n" +
"Blázquez\n" +
"Aranda\n" +
"Acosta\n" +
"Plaza\n" +
"Jurado\n" +
"Quintana\n" +
"Salas\n" +
"Conde\n" +
"Gálvez\n" +
"Abad\n" +
"Calderón\n" +
"Rico\n" +
"Gracia\n" +
"Padilla\n" +
"Beltrán\n" +
"Estévez\n" +
"Rivero\n" +
"Aparicio\n" +
"Casas\n" +
"Aguilera\n" +
"Menéndez\n" +
"Escudero\n" +
"Mateos\n" +
"Guillen\n" +
"Miranda\n" +
"Contreras\n" +
"Villar\n" +
"Mateo\n" +
"Roldan\n" +
"Heredia\n" +
"Bueno\n" +
"Macías\n" +
"Guerra\n" +
"Varela\n" +
"Andrés\n" +
"Benito\n" +
"Pereira\n" +
"Expósito\n" +
"Palacios\n" +
"Valero\n" +
"Vila\n" +
"Bernal\n" +
"Robles\n" +
"Mendoza\n" +
"Soriano\n" +
"Martí\n" +
"Marcos\n" +
"Carrillo\n" +
"Segura\n" +
"Sierra\n" +
"Ríos\n" +
"Montes\n" +
"Luque\n" +
"Galán\n" +
"Otero\n" +
"Vera\n" +
"Camacho\n" +
"Rey\n" +
"Arroyo\n" +
"Redondo\n" +
"Rivera\n" +
"Casado\n" +
"Silva\n" +
"Rivas\n" +
"Lara\n" +
"Espinosa\n" +
"Izquierdo\n" +
"Franco\n" +
"Merino\n" +
"Pardo\n" +
"Rojas\n" +
"Gallardo\n" +
"Bravo\n" +
"Parra\n" +
"Esteban\n" +
"Moya\n" +
"Soler\n" +
"Velasco\n" +
"Sáez\n" +
"Soto\n" +
"Román\n" +
"Pastor\n" +
"Crespo\n" +
"Carmona\n" +
"Vargas\n" +
"Santiago\n" +
"Arias\n" +
"Benítez\n" +
"Mora\n" +
"Vicente\n" +
"Duran\n" +
"Ferrer\n" +
"Giménez\n" +
"Ibáñez\n" +
"Montero\n" +
"Hidalgo\n" +
"Lorenzo\n" +
"Santana\n" +
"Herrero\n" +
"Reyes\n" +
"Pascual\n" +
"Aguilar\n" +
"Nieto\n" +
"Caballero\n" +
"Carrasco\n" +
"Fuentes\n" +
"Diez\n" +
"Vega\n" +
"Campos\n" +
"Flores\n" +
"Cabrera\n" +
"Peña\n" +
"Márquez\n" +
"Herrera\n" +
"León\n" +
"Cruz\n" +
"Gallego\n" +
"Vidal\n" +
"Calvo\n" +
"Méndez\n" +
"Prieto\n" +
"Cano\n" +
"Guerrero\n" +
"Lozano\n" +
"Cortes\n" +
"Castillo\n" +
"Santos\n" +
"Garrido\n" +
"Medina\n" +
"Núñez\n" +
"Iglesias\n" +
"Sanz\n" +
"Marín\n" +
"Rubio\n" +
"Ortiz\n" +
"Castro\n" +
"Delgado\n" +
"Ortega\n" +
"Morales\n" +
"Molina\n" +
"Suarez\n" +
"Blanco\n" +
"Serrano\n" +
"Ramírez\n" +
"Gil\n" +
"Ramos\n" +
"Vázquez\n" +
"Domínguez\n" +
"Torres\n" +
"Navarro\n" +
"Gutiérrez\n" +
"Alonso\n" +
"Romero\n" +
"Muñoz\n" +
"Álvarez\n" +
"Moreno\n" +
"Díaz\n" +
"Hernández\n" +
"Ruiz\n" +
"Jiménez\n" +
"Martin\n" +
"Gómez\n" +
"Pérez\n" +
"Sánchez\n" +
"Martínez\n" +
"López\n" +
"Fernández\n" +
"Rodríguez\n" +
"González\n" +
"García";
    
    public static String nombres = "Mariem\n" +
"Saida\n" +
"Samir\n" +
"Sufian\n" +
"Laila\n" +
"Salma\n" +
"Farida\n" +
"Mina\n" +
"Erhimo\n" +
"Dunia\n" +
"Hamed\n" +
"Habiba\n" +
"Dina\n" +
"Yusef\n" +
"Fátima Sohora\n" +
"Nabil\n" +
"Adam\n" +
"Sohora\n" +
"Soraya\n" +
"Mimount\n" +
"Samira\n" +
"Abdeselam\n" +
"Farah\n" +
"María África\n" +
"Rahma\n" +
"Mimoun\n" +
"Karima\n" +
"Mariam\n" +
"Nora\n" +
"Yamina\n" +
"María Fuencisla\n" +
"Rachida\n" +
"Naima\n" +
"Alí\n" +
"Omar\n" +
"Fadma\n" +
"Karim\n" +
"Nadia\n" +
"Rachid\n" +
"Sonsoles\n" +
"Said\n" +
"Natividad\n" +
"África\n" +
"Yasmina\n" +
"Aicha\n" +
"Bilal\n" +
"Abdelkader\n" +
"Luis Angel\n" +
"Hassan\n" +
"María Sonsoles\n" +
"Blanca\n" +
"Malika\n" +
"Mustafa\n" +
"Celso\n" +
"Agustina\n" +
"Camilo\n" +
"Celsa\n" +
"Elisa\n" +
"Inés\n" +
"José Ángel\n" +
"María Cruz\n" +
"Celia\n" +
"Joel\n" +
"Merce\n" +
"Ahmed\n" +
"María Carme\n" +
"Roger\n" +
"Benito\n" +
"Héctor\n" +
"Cristian\n" +
"María Llanos\n" +
"María Prado\n" +
"Leyre\n" +
"Guadalupe\n" +
"Eduard\n" +
"Olatz\n" +
"Ainara\n" +
"Arnau\n" +
"Enric\n" +
"Elvira\n" +
"Aritz\n" +
"Martí\n" +
"Pino\n" +
"Carla\n" +
"Andoni\n" +
"Jonathan\n" +
"Antonio Manuel\n" +
"Felipe\n" +
"Rodrigo\n" +
"Joseba\n" +
"Carmen Delia\n" +
"Miren\n" +
"Juan María\n" +
"Idoia\n" +
"Igor\n" +
"Irati\n" +
"Joaquina\n" +
"Ramona\n" +
"Margalida\n" +
"Gloria\n" +
"Sagrario\n" +
"Victoria\n" +
"Maialen\n" +
"Iria\n" +
"Maider\n" +
"Bernardo\n" +
"Ana Cristina\n" +
"Juliana\n" +
"Aina\n" +
"Imanol\n" +
"Carles\n" +
"María Angustias\n" +
"César\n" +
"María Paz\n" +
"José Juan\n" +
"Bárbara\n" +
"Julen\n" +
"Adriá\n" +
"Joaquim\n" +
"José Javier\n" +
"Juan Luis\n" +
"Josu\n" +
"Fuensanta\n" +
"Pascual\n" +
"Petra\n" +
"Fátima\n" +
"Gregorio\n" +
"Iratxe\n" +
"María Dolors\n" +
"Lorenzo\n" +
"Gemma\n" +
"María Magdalena\n" +
"Carmelo\n" +
"Carme\n" +
"Carolina\n" +
"Trinidad\n" +
"Pedro José\n" +
"Aurora\n" +
"Carmen María\n" +
"Dolors\n" +
"Alfredo\n" +
"Guillermo\n" +
"Carmen Rosa\n" +
"José Francisco\n" +
"Estibaliz\n" +
"Samuel\n" +
"Candelaria\n" +
"María Aranzazu\n" +
"Víctor Manuel\n" +
"Martín\n" +
"Ascensión\n" +
"María Cinta\n" +
"María Lourdes\n" +
"Asunción\n" +
"María Asunción\n" +
"Antoni\n" +
"Lluis\n" +
"Ismael\n" +
"Antonio José\n" +
"Araceli\n" +
"Pere\n" +
"Itziar\n" +
"Mohammed\n" +
"Emilia\n" +
"Gerard\n" +
"Esperanza\n" +
"Ginés\n" +
"Felisa\n" +
"Remedios\n" +
"Eneko\n" +
"Pau\n" +
"Luisa\n" +
"Francisco Manuel\n" +
"Rafaela\n" +
"Francesc\n" +
"Maite\n" +
"Verónica\n" +
"Bartolomé\n" +
"Miquel\n" +
"José Carlos\n" +
"María Pino\n" +
"Ane\n" +
"Manuel Jesús\n" +
"María Rocío\n" +
"Juana María\n" +
"María Candelaria\n" +
"Purificación\n" +
"Josep María\n" +
"Josefina\n" +
"Gorka\n" +
"Magdalena\n" +
"María Nieves\n" +
"Eva María\n" +
"Ander\n" +
"Domingo\n" +
"Milagros\n" +
"Xabier\n" +
"Leire\n" +
"Unai\n" +
"María Luz\n" +
"Gabriel\n" +
"Begoña\n" +
"Noelia\n" +
"María Antonia\n" +
"Amaia\n" +
"Ainhoa\n" +
"Nerea\n" +
"Jesús María\n" +
"María Victoria\n" +
"Cristóbal\n" +
"Iñaki\n" +
"José Vicente\n" +
"María Amparo\n" +
"Oriol\n" +
"Juan Francisco\n" +
"José Ignacio\n" +
"Iker\n" +
"Asier\n" +
"Jon\n" +
"Gonzalo\n" +
"Paloma\n" +
"María Elena\n" +
"Agustín\n" +
"Iñigo\n" +
"Sebastián\n" +
"Alex\n" +
"Mariano\n" +
"Consuelo\n" +
"María Begoña\n" +
"Vicenta\n" +
"José Miguel\n" +
"Marcos\n" +
"Aitor\n" +
"Ana Belén\n" +
"Mikel\n" +
"Sergi\n" +
"Mireia\n" +
"Antonio Jesús\n" +
"Félix\n" +
"Tomas\n" +
"Laia\n" +
"Julio\n" +
"Esther\n" +
"María Mercedes\n" +
"María Rosa\n" +
"María Concepción\n" +
"Isabel María\n" +
"José Ramón\n" +
"Jaume\n" +
"Eva\n" +
"Amparo\n" +
"Ana Isabel\n" +
"Xavier\n" +
"Albert\n" +
"Catalina\n" +
"Margarita\n" +
"Mohamed\n" +
"Anna\n" +
"Emilio\n" +
"Alba\n" +
"Natalia\n" +
"María Rosario\n" +
"Julián\n" +
"Ángeles\n" +
"Mario\n" +
"Ricardo\n" +
"María Josefa\n" +
"Josep\n" +
"Yolanda\n" +
"Marina\n" +
"Marc\n" +
"Joan\n" +
"Alfonso\n" +
"Ignacio\n" +
"Inmaculada\n" +
"Andrea\n" +
"Sonia\n" +
"Sandra\n" +
"Ángela\n" +
"Jaime\n" +
"Francisco José\n" +
"Alicia\n" +
"Irene\n" +
"María Mar\n" +
"Susana\n" +
"Juan Manuel\n" +
"Salvador\n" +
"Víctor\n" +
"Rocío\n" +
"Jordi\n" +
"Mónica\n" +
"Roberto\n" +
"Nuria\n" +
"Eduardo\n" +
"Julia\n" +
"Encarnación\n" +
"Montserrat\n" +
"Rubén\n" +
"Rosa\n" +
"Vicente\n" +
"Patricia\n" +
"Óscar\n" +
"Joaquín\n" +
"Silvia\n" +
"Santiago\n" +
"Iván\n" +
"Beatriz\n" +
"Rosario\n" +
"Juan Antonio\n" +
"Adrián\n" +
"Diego\n" +
"Ramón\n" +
"Andrés\n" +
"Álvaro\n" +
"Raúl\n" +
"Juana\n" +
"Paula\n" +
"María Jesús\n" +
"Sara\n" +
"Enrique\n" +
"Teresa\n" +
"Raquel\n" +
"Manuela\n" +
"Rosa María\n" +
"Lucia\n" +
"Elena\n" +
"Juan José\n" +
"Mercedes\n" +
"Juan Carlos\n" +
"Concepción\n" +
"María Luisa\n" +
"Pilar\n" +
"Alberto\n" +
"Pablo\n" +
"Jorge\n" +
"Sergio\n" +
"María José\n" +
"María Isabel\n" +
"Marta\n" +
"Luis\n" +
"Fernando\n" +
"Alejandro\n" +
"José María\n" +
"Miguel Ángel\n" +
"Dolores\n" +
"Cristina\n" +
"Antonia\n" +
"María Ángeles\n" +
"Ángel\n" +
"Francisca\n" +
"Laura\n" +
"José Manuel\n" +
"Pedro\n" +
"Rafael\n" +
"Ana\n" +
"María Teresa\n" +
"Miguel\n" +
"Daniel\n" +
"María Pilar\n" +
"María Dolores\n" +
"Carlos\n" +
"Ana María\n" +
"Francisco Javier\n" +
"Javier\n" +
"Jesús\n" +
"Isabel\n" +
"José Luis\n" +
"José Antonio\n" +
"Josefa\n" +
"David\n" +
"Juan\n" +
"Carmen\n" +
"Francisco\n" +
"Manuel\n" +
"María\n" +
"María Carmen\n" +
"José\n" +
"Antonio";
    
    public static String paises = "Ciudad del Vaticano,1000\n" +
"Nauru,10000\n" +
"Tuvalu,10000\n" +
"Palaos,21000\n" +
"San Marino,32000\n" +
"Mónaco,35000\n" +
"Liechtenstein,37000\n" +
"San Cristóbal y Nieves,54000\n" +
"Islas Marshall,56000\n" +
"Dominica,68000\n" +
"Seychelles,87000\n" +
"Andorra,88000\n" +
"Antigua y Barbuda,91000\n" +
"Kiribati,103000\n" +
"Granada,105000\n" +
"Tonga,105000\n" +
"San Vicente y las Granadinas,109000\n" +
"Micronesia,112000\n" +
"Santo Tomé y Príncipe,172000\n" +
"Santa Lucía,178000\n" +
"Samoa,185000\n" +
"Guayana Francesa,243000\n" +
"Vanuatu,252000\n" +
"Barbados,275000\n" +
"Polinesia Francesa,277000\n" +
"Belice,324000\n" +
"Maldivas,324000\n" +
"Islandia,328000\n" +
"Bahamas,351000\n" +
"Brunéi,413000\n" +
"Malta,419000\n" +
"Cabo Verde,505000\n" +
"Luxemburgo,523000\n" +
"Surinam,534000\n" +
"Islas Salomón,566000\n" +
"República Árabe Saharaui Democrática,567000\n" +
"Montenegro,633000\n" +
"Guinea Ecuatorial,740000\n" +
"Bután,750000\n" +
"Guyana,758000\n" +
"Comoras,773000\n" +
"Fiyi,876000\n" +
"Yibuti,923000\n" +
"Chipre,1129000\n" +
"Timor Oriental,1187000\n" +
"Suazilandia,1220000\n" +
"Mauricio,1314000\n" +
"Estonia,1340000\n" +
"Trinidad y Tobago,1351000\n" +
"Baréin,1359000\n" +
"Gabón,1564000\n" +
"Guinea-Bissau,1580000\n" +
"Gambia,1825000\n" +
"Catar,1939000\n" +
"Eslovenia,2040000\n" +
"Botsuana,2053000\n" +
"República de Macedonia,2067000\n" +
"Lesoto,2217000\n" +
"Letonia,2235000\n" +
"Namibia,2364000\n" +
"Jamaica,2761000\n" +
"Mongolia,2844000\n" +
"Kuwait,2892000\n" +
"Omán,2904000\n" +
"Armenia,3109000\n" +
"Albania,3227000\n" +
"Lituania,3292000\n" +
"Uruguay,3391000\n" +
"Moldavia,3519000\n" +
"Mauritania,3623000\n" +
"Panamá,3625000\n" +
"Puerto Rico,3743000\n" +
"Bosnia y Herzegovina,3744000\n" +
"República del Congo,4233000\n" +
"Liberia,4245000\n" +
"Autoridad Nacional Palestina,4271000\n" +
"Líbano,4292000\n" +
"Georgia,4304000\n" +
"Croacia,4387000\n" +
"Nueva Zelanda,4461000\n" +
"República Centroafricana,4576000\n" +
"Irlanda,4579000\n" +
"Costa Rica,4794000\n" +
"Noruega,4960000\n" +
"Turkmenistán,5170000\n" +
"Singapur,5256000\n" +
"Finlandia,5403000\n" +
"Kirguistán,5448000\n" +
"Eslovaquia,5480000\n" +
"Eritrea,5581000\n" +
"Dinamarca,5593000\n" +
"Nicaragua,5955000\n" +
"Sierra Leona,6126000\n" +
"El Salvador,6264000\n" +
"Togo,6283000\n" +
"Laos,6374000\n" +
"Jordania,6457000\n" +
"Libia,6469000\n" +
"Paraguay,6683000\n" +
"Tayikistán,7079000\n" +
"Papúa Nueva Guinea,7170000\n" +
"Hong Kong,7196000\n" +
"Bulgaria,7398000\n" +
"Israel,7695000\n" +
"Suiza,7734000\n" +
"Honduras,7912000\n" +
"Emiratos Árabes Unidos,8106000\n" +
"Austria,8429000\n" +
"Burundi,8749000\n" +
"Benín,9352000\n" +
"Azerbaiyán,9421000\n" +
"Suecia,9495000\n" +
"Bielorrusia,9527000\n" +
"Somalia,9797000\n" +
"Serbia,9847000\n" +
"Hungría,9950000\n" +
"República Dominicana,10183000\n" +
"Bolivia,10248000\n" +
"Haití,10256000\n" +
"Guinea,10481000\n" +
"República Checa,10566000\n" +
"Portugal,10699000\n" +
"Túnez,10705000\n" +
"Bélgica,10788000\n" +
"Cuba,11249000\n" +
"Ruanda,11272000\n" +
"Grecia,11419000\n" +
"Chad,11831000\n" +
"Zimbabue,13014000\n" +
"Senegal,13108000\n" +
"Zambia,13884000\n" +
"Camboya,14478000\n" +
"Ecuador,14865000\n" +
"Guatemala,15138000\n" +
"Malaui,15883000\n" +
"Malí,16319000\n" +
"Kazajistán,16381000\n" +
"Níger,16644000\n" +
"Países Bajos,16714000\n" +
"Chile,17423000\n" +
"Burkina Faso,17482000\n" +
"Angola,20163000\n" +
"Camerún,20469000\n" +
"Costa de Marfil,20595000\n" +
"Siria,21118000\n" +
"Sri Lanka,21224000\n" +
"Rumania,21388000\n" +
"Madagascar,21929000\n" +
"Australia,22919000\n" +
"Mozambique,24475000\n" +
"Corea del Norte,24554000\n" +
"Ghana,25546000\n" +
"Yemen,25569000\n" +
"Uzbekistán,28077000\n" +
"Arabia Saudita,28705000\n" +
"Malasia,29322000\n" +
"Perú,29734000\n" +
"Venezuela,29891000\n" +
"Nepal,31011000\n" +
"Marruecos,32599000\n" +
"Afganistán,33397000\n" +
"Irak,33703000\n" +
"Canadá,34675000\n" +
"Uganda,35621000\n" +
"Argelia,36486000\n" +
"Polonia,38317000\n" +
"Argentina,41119000\n" +
"Kenia,42749000\n" +
"Ucrania,44940000\n" +
"Sudán,45722000\n" +
"España,46772000\n" +
"Colombia,47551000\n" +
"Tanzania,47656000\n" +
"Corea del Sur,48588000\n" +
"Birmania,48724000\n" +
"Sudáfrica,50738000\n" +
"Italia,60964000\n" +
"Reino Unido,62798000\n" +
"Francia,63458000\n" +
"Rep. Dem. del Congo,69575000\n" +
"Tailandia,69892000\n" +
"Turquía,74509000\n" +
"Irán,75612000\n" +
"Alemania,81991000\n" +
"Egipto,83958000\n" +
"Etiopía,86539000\n" +
"Vietnam,89730000\n" +
"Filipinas,96471000\n" +
"México,116147000\n" +
"Japón,126435000\n" +
"Rusia,142703000\n" +
"Bangladés,152409000\n" +
"Nigeria,166629000\n" +
"Pakistán,179951000\n" +
"Brasil,198361000\n" +
"Indonesia,244769000\n" +
"Estados Unidos,315791000\n" +
"India,1258351000\n" +
"China,1353601000";
    
    public static String palabras = "La Abdicación\n" +
"El Abastecimiento\n" +
"El Abceso\n" +
"El Abdomen\n" +
"El Abecedario\n" +
"La Abeja\n" +
"El Abiótico\n" +
"La Abnegación\n" +
"Lo Abovedado\n" +
"El Abraham\n" +
"El Abrasivo\n" +
"La Abreviatura\n" +
"El Abrupto\n" +
"La Absolución\n" +
"La Absorción\n" +
"La Abstención\n" +
"La Abstinencia\n" +
"La Abstracción\n" +
"Lo Abstracto\n" +
"La Abundancia\n" +
"El Acaecimiento\n" +
"El Acceso\n" +
"Lo Accesible\n" +
"Lo Accesorio\n" +
"La Acepción\n" +
"La Aceptación\n" +
"Lo Aconsejable\n" +
"El Acribillamiento\n" +
"La Acrobacia\n" +
"La Actitud\n" +
"La Actividad\n" +
"La Acusación\n" +
"La Adaptación\n" +
"La Adherencia\n" +
"El Adherente\n" +
"La Adhesión\n" +
"El Adhesivo\n" +
"La Adicción\n" +
"La Adivinanza\n" +
"El Adjetivo\n" +
"La Adjudicación\n" +
"La Adjudicación\n" +
"La Admisión\n" +
"El Adolescente\n" +
"La Adquisición\n" +
"La Adsorción\n" +
"El Adverbio\n" +
"El Adversario\n" +
"El Adversativo\n" +
"La Adversidad\n" +
"La Advertencia\n" +
"La Advocación\n" +
"Lo Adyacente\n" +
"La Aflicción\n" +
"La Afluencia\n" +
"El Aforo\n" +
"La Agilidad\n" +
"El Agobiante\n" +
"La Agresividad\n" +
"El Agudizamiento\n" +
"La Aliteración\n" +
"La Ambición\n" +
"La Amnistía\n" +
"El Amstrong\n" +
"El Anhídrido\n" +
"La Anorexia\n" +
"El Antecesor\n" +
"El Antibiótico\n" +
"La Anticipación\n" +
"El Anverso\n" +
"La Aposición\n" +
"La Aristocracia\n" +
"La Arteriosclerosis\n" +
"La Ascendencia\n" +
"El Asentamiento\n" +
"El Aseverativo\n" +
"El Asia\n" +
"La Asimilación\n" +
"El Astigmatismo\n" +
"El Astringente\n" +
"El Astronauta\n" +
"La Asunción\n" +
"La Atribución\n" +
"El Audiovisual\n" +
"La Auscultación\n" +
"La Ausencia\n" +
"La Autarquía\n" +
"El Autoadhesivo\n" +
"El Autótrofo\n" +
"El Aval\n" +
"El Ave\n" +
"La Avidez\n" +
"El Axioma\n" +
"El Azteca\n" +
"La Babilonia\n" +
"El Bacilo\n" +
"La Bacteria\n" +
"La Bahía\n" +
"El Bajorrelieve\n" +
"El Barbarismo\n" +
"El Bario\n" +
"La Báscula\n" +
"Lo Básico\n" +
"La Basílica\n" +
"La Batalla\n" +
"El Bautismo\n" +
"La Beatificación\n" +
"La Bebida\n" +
"Lo Bélico\n" +
"La Bendición\n" +
"La Beneficencia\n" +
"La Biblia\n" +
"La Bibliografía\n" +
"El Bíceps\n" +
"Lo Bicóncavo\n" +
"La Bienaventuranza\n" +
"La Bienvenida\n" +
"La Bifurcación\n" +
"El Bimestre\n" +
"El Binomio\n" +
"La Biografía\n" +
"La Biosfera\n" +
"El Bióxido\n" +
"El Bípedo\n" +
"La Bisectriz\n" +
"El Bisiesto\n" +
"El Bisílabo\n" +
"El Bivalente\n" +
"El Bizcocho\n" +
"La Bombilla\n" +
"El Bovino\n" +
"La Brevedad\n" +
"La Buenaventura\n" +
"La Bulimia\n" +
"El Bullicio\n" +
"El Buscador\n" +
"La Cabeza\n" +
"El Cabildo\n" +
"La Callosidad\n" +
"La Calvicie\n" +
"La Canción\n" +
"La Capacidad\n" +
"La Capilaridad\n" +
"La Capitulación\n" +
"El Carnívoro\n" +
"El Castellano\n" +
"El Cautiverio\n" +
"La Celebración\n" +
"El Centesimal\n" +
"El Centímetro\n" +
"La Cibernética\n" +
"La Ciencia\n" +
"La Científica\n" +
"La Circunferencia\n" +
"Lo Circunstancial\n" +
"El Citoplasma\n" +
"El Cívico\n" +
"El Clásico\n" +
"La Clavícula\n" +
"El Clavo\n" +
"La Coalición\n" +
"La Cocina\n" +
"La Coherencia\n" +
"La Cohesión\n" +
"La Colección\n" +
"La Comercialización\n" +
"El Comezón\n" +
"La Complicación\n" +
"La Composición\n" +
"La Comprensión\n" +
"La Comprobación\n" +
"El Comunicativo\n" +
"Lo Cóncavo\n" +
"La Concentración\n" +
"La Concepción\n" +
"La Concesión\n" +
"La Conciencia\n" +
"El Concilio\n" +
"La Concordancia\n" +
"La Conductividad\n" +
"La Confesión\n" +
"La Congruencia\n" +
"La Conjugación\n" +
"La Conjunción\n" +
"El Conmutativo\n" +
"La Connotación\n" +
"El Conocimiento\n" +
"El Consejo\n" +
"La Conserva\n" +
"La Consideración\n" +
"La Consigna\n" +
"La Consistencia\n" +
"La Constelación\n" +
"La Constitución\n" +
"La Construcción\n" +
"La Contribución\n" +
"La Convalescencia\n" +
"La Conversación\n" +
"La Conversión\n" +
"Lo Convexo\n" +
"La Convivencia\n" +
"La Convocatoria\n" +
"La Coordinación\n" +
"El Cosmos\n" +
"Lo Covalente\n" +
"El Crecimiento\n" +
"El Cuadrúpedo\n" +
"El Cuádruple\n" +
"El Débil\n" +
"La Decadencia\n" +
"El Décimo\n" +
"La Decisión\n" +
"La Definición\n" +
"La Delgadez\n" +
"La Democracia\n" +
"La Depresión\n" +
"La Derivación\n" +
"El Desahogo\n" +
"Lo Desastroso\n" +
"El Descendiente\n" +
"La Descriptiva\n" +
"El Deshabitado\n" +
"La Desinencia\n" +
"El Deslizamiento\n" +
"La Desvalorización\n" +
"La Devastación\n" +
"La Devoción\n" +
"El Diagnóstico\n" +
"El Dibujo\n" +
"El Diezmo\n" +
"El Dihíbrido\n" +
"El Dilúbrido\n" +
"El Diptongo\n" +
"La Disciplina\n" +
"El Discípulo\n" +
"La Discordancia\n" +
"La Discriminación\n" +
"La Disección\n" +
"El Disociamiento\n" +
"La Distribución\n" +
"La Disyunción\n" +
"El Divergente\n" +
"La Diversión\n" +
"El Divisible\n" +
"La División\n" +
"La Divulgación\n" +
"La Eficiencia\n" +
"El Egipto\n" +
"La Elaboración\n" +
"La Elipsis\n" +
"El Encabezamiento\n" +
"El Endocrino\n" +
"El Endoplasmático\n" +
"El Enlace\n" +
"La Enseñanza\n" +
"La Entrevista\n" +
"El Envase\n" +
"El Envío\n" +
"La Envoltura\n" +
"El Erlemeyer\n" +
"La Erosión\n" +
"La Escena\n" +
"La Escenografía\n" +
"La Esclavitud\n" +
"Lo Esencial\n" +
"El Espermatozoide\n" +
"El Estival\n" +
"El Estratega\n" +
"La Estrella\n" +
"La Evaluación\n" +
"El Evangelio\n" +
"La Evaporación\n" +
"La Evolución\n" +
"El Examen\n" +
"La Excavación\n" +
"La Excelencia\n" +
"El Excepcional\n" +
"La Exclusión\n" +
"La Excreción\n" +
"La Excursión\n" +
"La Exhibición\n" +
"La Exhortación\n" +
"La Exigencia\n" +
"El Exilio\n" +
"La Existencia\n" +
"El Éxodo\n" +
"La Expansión\n" +
"La Expedición\n" +
"La Experiencia\n" +
"El Experimento\n" +
"La Explosión\n" +
"La Expresión\n" +
"La Expresiva\n" +
"La Expulsión\n" +
"La Exuberancia\n" +
"La Fabricación\n" +
"La Fábula\n" +
"Lo Fácil\n" +
"La Fenicia\n" +
"La Física\n" +
"La Fisiología\n" +
"El Flagelo\n" +
"La Flexibilidad\n" +
"La Fortuna\n" +
"El Fósil\n" +
"La Fotólisis\n" +
"La Fotometría\n" +
"La Fotoquímica\n" +
"La Fotosíntesis\n" +
"La Frase\n" +
"La Fraternidad\n" +
"La Frontera\n" +
"El Frugívoro\n" +
"La Función\n" +
"La Galaxia\n" +
"La Genealogía\n" +
"La Generalización\n" +
"La Génesis\n" +
"El Genoma\n" +
"El Genotipo\n" +
"La Gimnasia\n" +
"La Globalización\n" +
"El Graffiti\n" +
"La Gramática\n" +
"la Grandiosidad\n" +
"El Guía\n" +
"La Habitación\n" +
"La Habladuría\n" +
"El Hecho\n" +
"El Hallazgo\n" +
"La Hamaca\n" +
"La Hectárea\n" +
"El Hemisferio\n" +
"El Hemograma\n" +
"Lo Hepático\n" +
"El Heptágono\n" +
"El Herbívoro\n" +
"La Herencia\n" +
"Lo Hervido\n" +
"El Heterótrofo\n" +
"El Híbrido\n" +
"El Hidrofílico\n" +
"El Hidrófobo\n" +
"El Hidrógeno\n" +
"La Hidrólisis\n" +
"El Hiperónimo\n" +
"La Hipertensión\n" +
"El Hipónimo\n" +
"La Hipótesis\n" +
"El Hispanoamericano\n" +
"El Histológico\n" +
"El Hitita\n" +
"El Homónimo\n" +
"El Icónico\n" +
"La Idiosincrasia\n" +
"Lo Implícito\n" +
"Lo Imprescindible\n" +
"La Improvisación\n" +
"La Incisión\n" +
"La Indagación\n" +
"La Inducción\n" +
"La Inecuación\n" +
"El Inefable\n" +
"La Inhabilitación\n" +
"La Insercción\n" +
"Lo Instructivo\n" +
"La Intencionalidad\n" +
"El Interés\n" +
"La Interespecífica\n" +
"La Intervención\n" +
"La Intraespecífica\n" +
"La Introducción\n" +
"El Invasor\n" +
"La Invención\n" +
"El Inverso\n" +
"La Investigación\n" +
"Lo Invisible\n" +
"La Ionización\n" +
"Lo Irregular\n" +
"Lo Irreversible\n" +
"La Izquierda\n" +
"La Jabalina\n" +
"El Jilguero\n" +
"El Joule\n" +
"El Júbilo\n" +
"Lo Jurídico\n" +
"La Jurisdicción\n" +
"La Jurisprudencia\n" +
"La Justicia\n" +
"La Juventud\n" +
"El Laceramiento\n" +
"La Laringe\n" +
"El Levítico\n" +
"La Libertad\n" +
"La Licencia\n" +
"La Limnología\n" +
"El Limo\n" +
"La Línea\n" +
"La Lingüística\n" +
"El Lisosoma\n" +
"La Longitud\n" +
"El Lumen\n" +
"El Lúteo\n" +
"Lo Macrométrico\n" +
"El Magnánimo\n" +
"Lo Maleable\n" +
"La Maquinaria\n" +
"El Medieval\n" +
"El Mesías\n" +
"El Microorganismo\n" +
"El Micrótomo\n" +
"La Misión\n" +
"El Monocárpico\n" +
"El Monohíbrido\n" +
"La Morfología\n" +
"La Motilidad\n" +
"La Movilidad\n" +
"El Municipio\n" +
"El Nacimiento\n" +
"La Nacionalidad\n" +
"El Nacionalismo\n" +
"El Nanómetro\n" +
"La Navegación\n" +
"La Necesidad\n" +
"El Neoclasicismo\n" +
"El Neologismo\n" +
"La Nervadura\n" +
"El Nobiliario\n" +
"La Novela\n" +
"El Nucela\n" +
"La Nueva\n" +
"La Obediencia\n" +
"La Objeción\n" +
"El Objetivo\n" +
"El Objeto\n" +
"La Observación\n" +
"La Obsesión\n" +
"El Obtusángulo\n" +
"La Ocasión\n" +
"El Octosílabo\n" +
"El Oficial\n" +
"El Oleoducto\n" +
"La Omisión\n" +
"El Omnipotente\n" +
"El Omnisciente\n" +
"La Oposición\n" +
"La Organogénesis\n" +
"El Orgánulo\n" +
"El Origen\n" +
"El Ortográfico\n" +
"El Ovíparo\n" +
"El Ovovivíparo\n" +
"El Óvulo\n" +
"La Paciencia\n" +
"El Pacífico\n" +
"La Parábola\n" +
"La Parsimonia\n" +
"La Partenocarpia\n" +
"La Partenogénesis\n" +
"La Participación\n" +
"El Pasivo\n" +
"La Pasteurización\n" +
"El Perezoso\n" +
"La Persistencia\n" +
"El Perspicaz\n" +
"La Persuasión\n" +
"La Placenta\n" +
"El Plancton\n" +
"La Plasmólisis\n" +
"La Polinización\n" +
"La Posesión\n" +
"La Posibilidad\n" +
"La Precipitación\n" +
"La Precisión\n" +
"La Predación\n" +
"El Predecesor\n" +
"El Predicativo\n" +
"La Predilección\n" +
"La Predisposición\n" +
"La Prehistoria\n" +
"La Presencia\n" +
"La Preservación\n" +
"La Pretensión\n" +
"La Prevención\n" +
"La Probabilidad\n" +
"La Procesión\n" +
"La Profesión\n" +
"El Programario\n" +
"La Prohibición\n" +
"La Proposición\n" +
"El Proverbio\n" +
"La Provincia\n" +
"La Provisión\n" +
"La Prueba\n" +
"Lo Psíquico\n" +
"La Recepción\n" +
"La Recesión\n" +
"El Recibimiento\n" +
"El Reciclacimiento\n" +
"El Reconocimiento\n" +
"La Reflexión\n" +
"La Rehabilitación\n" +
"La Relación\n" +
"Lo Relativo\n" +
"La Religión\n" +
"La Reminiscencia\n" +
"El Renacimiento\n" +
"La Repercusión\n" +
"La Representación\n" +
"La Reserva\n" +
"La Residencia\n" +
"La Residencia\n" +
"La Resignación\n" +
"La Resistencia\n" +
"La Resolución\n" +
"La Responsabilidad\n" +
"La Restauración\n" +
"El Retículo\n" +
"La Reverencia\n" +
"Lo Reversible\n" +
"La Revisión\n" +
"El Ribosoma\n" +
"El Saber\n" +
"La Sabiduría\n" +
"La Selección\n" +
"La Selectividad\n" +
"La Selva\n" +
"La Semblanza\n" +
"El Sencillo\n" +
"La Sensibilidad\n" +
"El Septentrional\n" +
"El Servicio\n" +
"La Sílaba\n" +
"El Símbolo\n" +
"El Simposio\n" +
"La Sinalefa\n" +
"La Soberanía\n" +
"La Soberbia\n" +
"La Sociedad\n" +
"El Sosiego\n" +
"La Subida\n" +
"La Sublevación\n" +
"La Subordinación\n" +
"El Subsidio\n" +
"El Suburbio\n" +
"La Subvención\n" +
"La Sucesión\n" +
"La Suciedad\n" +
"La Sugerencia\n" +
"La Supervivencia\n" +
"El Sustantivo\n" +
"La Sustentación\n" +
"La Tecnología\n" +
"El Torbellino\n" +
"La Tradición\n" +
"La Tragedia\n" +
"La Tragicomedia\n" +
"La Transcripción\n" +
"La Transferencia\n" +
"La Transformación\n" +
"La Transfusión\n" +
"La Transición\n" +
"Lo Transitivo\n" +
"La Transmisión\n" +
"La Transpiración\n" +
"El Transporte\n" +
"El Trapezoide\n" +
"Lo Trascendental\n" +
"La Traslación\n" +
"El Triptongo\n" +
"El Tubérculo\n" +
"La Turbulencia\n" +
"La Turgencia\n" +
"El Ultimátum\n" +
"El Único\n" +
"Lo Unilateral\n" +
"El Universo\n" +
"El Unívoco\n" +
"La Urbanización\n" +
"La Urgencia\n" +
"El Vacío\n" +
"La Vacuna\n" +
"La Vegetación\n" +
"El Vegetal\n" +
"La Vellosidad\n" +
"La Ventosidad\n" +
"La Veracidad\n" +
"El Verbo\n" +
"Lo Verboides\n" +
"Lo Verosímil\n" +
"El Versículo\n" +
"La Versificación\n" +
"El Vertebrado\n" +
"El Vértice\n" +
"La Vesícula\n" +
"El Vestíbulo\n" +
"El Vestigio\n" +
"El Víbora\n" +
"La Viceversa\n" +
"La Vicisitud\n" +
"La Violencia\n" +
"El Virus\n" +
"La Víscera\n" +
"La Viscosa\n" +
"Lo Visible\n" +
"La Vivienda\n" +
"El Vivíparo\n" +
"El Vocabulario\n" +
"El Vocativo\n" +
"Lo Voluble\n" +
"La Vuelta\n" +
"La Votación\n" +
"El Vulcanismo\n" +
"Lo Vulnerable\n" +
"La Zambullida\n" +
"La Zoología\n" +
"El Zooplancton\n" +
"La Zootecnia";
    
    public static String localidades = "12 DE OCTUBRE\n" +
"ALGARROBAL ARRIBA\n" +
"ALGARROBAL PUISOYE\n" +
"ALGARROBAL VIEJO\n" +
"ALGARROBALES\n" +
"ALGARROBITO\n" +
"ALGARROBITO 1RO\n" +
"ALGARROBITOS\n" +
"ALGARROBO\n" +
"ALGARROBO DE SORTUE\n" +
"ALGARROBO DEL AGUILA\n" +
"ALGARROBO DEL CURA\n" +
"ALGARROBO GRANDE\n" +
"ALGARROBO PARAJE\n" +
"ALGARROBO VERDE\n" +
"ALGARROBOS GRANDES\n" +
"ALHUAMPA\n" +
"ALIANZA\n" +
"ALICIA\n" +
"ALICURA\n" +
"ALIJILAN\n" +
"ALISOS\n" +
"ALISOS  DE ABAJO\n" +
"ALISOS DE ARRIBA\n" +
"ALIZAL\n" +
"ALLEN\n" +
"ALLENDE\n" +
"ALMA GRANDE\n" +
"ALMACEN CASTRO\n" +
"ALMACEN CRISTIAN SCHUBERT\n" +
"ALMACEN EL CRUCE\n" +
"ALMACEN EL DESCANSO\n" +
"ALTO CARRIZAL\n" +
"ALTO CASTRO\n" +
"ALTO CAZADERA\n" +
"ALTO COMEDERO\n" +
"ALTO CON ZAMPA\n" +
"ALTO DE ANFAMA\n" +
"ALTO DE CASA\n" +
"ALTO DE CASTILLO\n" +
"ALTO DE FIERRO\n" +
"ALTO DE FLORES\n" +
"ALTO DE LA ANGOSTURA\n" +
"ALTO DE LA JUNTA\n" +
"ALTO DE LA LE?A\n" +
"ALTO DE LA SIERRA\n" +
"ALTO DE LAS ARA?AS\n" +
"ALTO DE LAS MULAS\n" +
"ALTO DE LAS PLUMAS\n" +
"ALTO DE LEIVA\n" +
"ALTO DE LOS GIMENEZ\n" +
"ALTO DE LOS MANANTIALES\n" +
"ALTO DE LOS PERROS\n" +
"ALTO DE LOS QUEBRACHOS\n" +
"ALTO DE LOS REALES\n" +
"ALTO DE LOS SAPOS\n" +
"ALTO DE LOZANO\n" +
"ALTO DE MEDINA\n" +
"ALTO DE MOJON\n" +
"ALTO DE SAN PEDRO\n" +
"ALTO DE SIERRA\n" +
"ALTO DEL ANGOSTO\n" +
"ALTO DEL DURAZNO\n" +
"ALTO DEL HUASCHO\n" +
"ALTO DEL LAMPAZO\n" +
"ALTO DEL LEON\n" +
"ALTO DEL MISTOL\n" +
"ALTOS DE CHIPION\n" +
"ALTOS HORNOS GUEMES\n" +
"ALUMBRERA\n" +
"ALUMINE\n" +
"ALURRALDE\n" +
"ALVAREZ\n" +
"ALVAREZ CONDARCO\n" +
"ALVAREZ DE TOLEDO\n" +
"ALVAREZ JONTE\n" +
"ALVARO BARROS\n" +
"ALVEAR\n" +
"ALZA NUEVA\n" +
"ALZAGA\n" +
"AMADORES\n" +
"BARRIO VILLA ADELA\n" +
"BARRIO VILLA COHESA\n" +
"BARRIO VILLA CORDOBA\n" +
"BARRIO VILLA FERNANDEZ\n" +
"BARRIO VILLA MU?IZ\n" +
"BARRIO VILLA ORTEGA\n" +
"BARRIO VILLA SALADILLO\n" +
"BARRIO VILLA UNION\n" +
"CAMPO GENERO\n" +
"CAMPO GIMBATTI\n" +
"CAMPO GIMENEZ\n" +
"CAMPO GOLA\n" +
"CAMPO GORETA\n" +
"CAMPO GRANDE\n" +
"CAMPO HARDY\n" +
"CAMPO HERRERA\n" +
"CAMPO HORQUESCO\n" +
"EL CANO\n" +
"EL CANQUEL\n" +
"EL CANTADERO\n" +
"EL CANTOR\n" +
"EL CAPACHO\n" +
"EL CARACOL\n" +
"EL CARAMELO\n" +
"EL CARANCHITO\n" +
"EL CARANCHO\n" +
"EL CARBALINO\n" +
"PASO ALGARROBO\n" +
"PASO ALSINA\n" +
"PASO ANCHO\n" +
"PASO BANDERA\n" +
"PASO BARDA\n" +
"PASO BERMUDEZ\n" +
"PASO CABRAL\n" +
"PASO CASTELLANOS\n" +
"PASO CATA TUN\n" +
"RIACHO HE HE\n" +
"RIACHO LINDO\n" +
"RIACHO NEGRO\n" +
"RIACHO RAMIREZ\n" +
"RIACHUELITO\n" +
"RIACHUELO\n" +
"CHORRILLO\n" +
"1 DE MAYO\n" +
"EL REMANCE\n" +
"YRAIZOS";
            
    public static String pcias = "BUENOS AIRES                                      \n" +
"CATAMARCA                                         \n" +
"CORDOBA                                           \n" +
"CORRIENTES                                        \n" +
"ENTRE RIOS                                        \n" +
"JUJUY                                             \n" +
"MENDOZA                                           \n" +
"LA RIOJA                                          \n" +
"SALTA                                             \n" +
"SAN JUAN                                          \n" +
"SAN LUIS                                          \n" +
"SANTA FE                                          \n" +
"SANTIAGO DEL ESTERO                               \n" +
"TUCUMAN                                           \n" +
"CHACO                                             \n" +
"CHUBUT                                            \n" +
"FORMOSA                                           \n" +
"MISIONES                                          \n" +
"NEUQUEN                                           \n" +
"LA PAMPA                                          \n" +
"RIO NEGRO                                         \n" +
"SANTA CRUZ                                        \n" +
"TIERRA DEL FUEGO                                  \n" +
"CIUDAD AUTONOMA BUENOS AIRES";

    private DataSource() throws InstantiationException {
        throw new InstantiationException("This class is not created for instntiation");
    }

}

/**
 * These functions are required very early in the Moodle
 * setup process, before any of the main libraries are
 * loaded.
 *
 * @package    core
 * @subpackage lib
 * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

defined('MOODLE_INTERNAL') || die();

// Debug levels - always keep the values in ascending order!
/** No warnings and errors at all */
define('DEBUG_NONE', 0);
/** Fatal errors only */
define('DEBUG_MINIMAL', E_ERROR | E_PARSE);
/** Errors, warnings and notices */
define('DEBUG_NORMAL', E_ERROR | E_PARSE | E_WARNING | E_NOTICE);
/** All problems except strict PHP warnings */
define('DEBUG_ALL', E_ALL & ~E_STRICT);
/** DEBUG_ALL with all debug messages and strict warnings */
define('DEBUG_DEVELOPER', E_ALL | E_STRICT);

/** Remove any memory limits */
define('MEMORY_UNLIMITED', -1);
/** Standard memory limit for given platform */
define('MEMORY_STANDARD', -2);
/**
 * Large memory limit for given platform - used in cron, upgrade, and other places that need a lot of memory.
 * Can be overridden with $CFG->extramemorylimit setting.
 */
define('MEMORY_EXTRA', -3);
/** Extremely large memory limit - not recommended for standard scripts */
define('MEMORY_HUGE', -4);


/**
 * Simple class. It is usually used instead of stdClass because it looks
 * more familiar to Java developers ;-) Do not use for type checking of
 * function parameters. Please use stdClass instead.
 *
 * @package    core
 * @subpackage lib
 * @copyright  2009 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @deprecated since 2.0
 */
class object extends stdClass {};

/**
 * Base Moodle Exception class
 *
 * Although this class is defined here, you cannot throw a moodle_exception until
 * after moodlelib.php has been included (which will happen very soon).
 *
 * @package    core
 * @subpackage lib
 * @copyright  2008 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class moodle_exception extends Exception {

    /**
     * @var string The name of the string from error.php to print
     */
    public $errorcode;

    /**
     * @var string The name of module
     */
    public $module;

    /**
     * @var mixed Extra words and phrases that might be required in the error string
     */
    public $a;

    /**
     * @var string The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
     */
    public $link;

    /**
     * @var string Optional information to aid the debugging process
     */
    public $debuginfo;

    /**
     * Constructor
     * @param string $errorcode The name of the string from error.php to print
     * @param string $module name of module
     * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
     * @param mixed $a Extra words and phrases that might be required in the error string
     * @param string $debuginfo optional debugging information
     */
    function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
        if (empty($module) || $module == 'moodle' || $module == 'core') {
            $module = 'error';
        }

        $this->errorcode = $errorcode;
        $this->module    = $module;
        $this->link      = $link;
        $this->a         = $a;
        $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;

        if (get_string_manager()->string_exists($errorcode, $module)) {
            $message = get_string($errorcode, $module, $a);
            $haserrorstring = true;
        } else {
            $message = $module . '/' . $errorcode;
            $haserrorstring = false;
        }

        if (defined('PHPUNIT_TEST') and PHPUNIT_TEST and $debuginfo) {
            $message = "$message ($debuginfo)";
        }

        if (!$haserrorstring and defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
            // Append the contents of $a to $debuginfo so helpful information isn't lost.
            // This emulates what {@link get_exception_info()} does. Unfortunately that
            // function is not used by phpunit.
            $message .= PHP_EOL.'$a contents: '.print_r($a, true);
        }

        parent::__construct($message, 0);
    }
}

/**
 * Course/activity access exception.
 *
 * This exception is thrown from require_login()
 *
 * @package    core_access
 * @copyright  2010 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class require_login_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $debuginfo Information to aid the debugging process
     */
    function __construct($debuginfo) {
        parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
    }
}

/**
 * Web service parameter exception class
 * @deprecated since Moodle 2.2 - use moodle exception instead
 * This exception must be thrown to the web service client when a web service parameter is invalid
 * The error string is gotten from webservice.php
 */
class webservice_parameter_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $errorcode The name of the string from webservice.php to print
     * @param string $a The name of the parameter
     * @param string $debuginfo Optional information to aid debugging
     */
    function __construct($errorcode=null, $a = '', $debuginfo = null) {
        parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
    }
}

/**
 * Exceptions indicating user does not have permissions to do something
 * and the execution can not continue.
 *
 * @package    core_access
 * @copyright  2009 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class required_capability_exception extends moodle_exception {
    /**
     * Constructor
     * @param context $context The context used for the capability check
     * @param string $capability The required capability
     * @param string $errormessage The error message to show the user
     * @param string $stringfile
     */
    function __construct($context, $capability, $errormessage, $stringfile) {
        $capabilityname = get_capability_string($capability);
        if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
            // we can not go to mod/xx/view.php because we most probably do not have cap to view it, let's go to course instead
            $parentcontext = $context->get_parent_context();
            $link = $parentcontext->get_url();
        } else {
            $link = $context->get_url();
        }
        parent::__construct($errormessage, $stringfile, $link, $capabilityname);
    }
}

/**
 * Exception indicating programming error, must be fixed by a programer. For example
 * a core API might throw this type of exception if a plugin calls it incorrectly.
 *
 * @package    core
 * @subpackage lib
 * @copyright  2008 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class coding_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $hint short description of problem
     * @param string $debuginfo detailed information how to fix problem
     */
    function __construct($hint, $debuginfo=null) {
        parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
    }
}

/**
 * Exception indicating malformed parameter problem.
 * This exception is not supposed to be thrown when processing
 * user submitted data in forms. It is more suitable
 * for WS and other low level stuff.
 *
 * @package    core
 * @subpackage lib
 * @copyright  2009 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class invalid_parameter_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $debuginfo some detailed information
     */
    function __construct($debuginfo=null) {
        parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
    }
}

/**
 * Exception indicating malformed response problem.
 * This exception is not supposed to be thrown when processing
 * user submitted data in forms. It is more suitable
 * for WS and other low level stuff.
 */
class invalid_response_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $debuginfo some detailed information
     */
    function __construct($debuginfo=null) {
        parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
    }
}

/**
 * An exception that indicates something really weird happened. For example,
 * if you do switch ($context->contextlevel), and have one case for each
 * CONTEXT_... constant. You might throw an invalid_state_exception in the
 * default case, to just in case something really weird is going on, and
 * $context->contextlevel is invalid - rather than ignoring this possibility.
 *
 * @package    core
 * @subpackage lib
 * @copyright  2009 onwards Martin Dougiamas  {@link http://moodle.com}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class invalid_state_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $hint short description of problem
     * @param string $debuginfo optional more detailed information
     */
    function __construct($hint, $debuginfo=null) {
        parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
    }
}

/**
 * An exception that indicates incorrect permissions in $CFG->dataroot
 *
 * @package    core
 * @subpackage lib
 * @copyright  2010 Petr Skoda {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class invalid_dataroot_permissions extends moodle_exception {
    /**
     * Constructor
     * @param string $debuginfo optional more detailed information
     */
    function __construct($debuginfo = NULL) {
        parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
    }
}

/**
 * An exception that indicates that file can not be served
 *
 * @package    core
 * @subpackage lib
 * @copyright  2010 Petr Skoda {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class file_serving_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $debuginfo optional more detailed information
     */
    function __construct($debuginfo = NULL) {
        parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
    }
}

/**
 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
 *
 * @param Exception $ex
 * @return void -does not return. Terminates execution!
 */
function default_exception_handler($ex) {
    global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;

    // detect active db transactions, rollback and log as error
    abort_all_db_transactions();

    if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
        $SESSION->wantsurl = qualified_me();
        redirect(get_login_url());
    }

    $info = get_exception_info($ex);

    if (debugging('', DEBUG_MINIMAL)) {
        $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
        error_log($logerrmsg);
    }

    if (is_early_init($info->backtrace)) {
        echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
    } else {
        try {
            if ($DB) {
                // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
                $DB->set_debug(0);
            }
            echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
        } catch (Exception $out_ex) {
            // default exception handler MUST not throw any exceptions!!
            // the problem here is we do not know if page already started or not, we only know that somebody messed up in outputlib or theme
            // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
            if (CLI_SCRIPT or AJAX_SCRIPT) {
                // just ignore the error and send something back using the safest method
                echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
            } else {
                echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
                $outinfo = get_exception_info($out_ex);
                echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
            }
        }
    }

    exit(1); // General error code
}

/**
 * Default error handler, prevents some white screens.
 * @param int $errno
 * @param string $errstr
 * @param string $errfile
 * @param int $errline
 * @param array $errcontext
 * @return bool false means use default error handler
 */
function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    if ($errno == 4096) {
        //fatal catchable error
        throw new coding_exception('PHP catchable fatal error', $errstr);
    }
    return false;
}

/**
 * Unconditionally abort all database transactions, this function
 * should be called from exception handlers only.
 * @return void
 */
function abort_all_db_transactions() {
    global $CFG, $DB, $SCRIPT;

    // default exception handler MUST not throw any exceptions!!

    if ($DB && $DB->is_transaction_started()) {
        error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
        // note: transaction blocks should never change current $_SESSION
        $DB->force_transaction_rollback();
    }
}

/**
 * This function encapsulates the tests for whether an exception was thrown in
 * early init -- either during setup.php or during init of $OUTPUT.
 *
 * If another exception is thrown then, and if we do not take special measures,
 * we would just get a very cryptic message "Exception thrown without a stack
 * frame in Unknown on line 0". That makes debugging very hard, so we do take
 * special measures in default_exception_handler, with the help of this function.
 *
 * @param array $backtrace the stack trace to analyse.
 * @return boolean whether the stack trace is somewhere in output initialisation.
 */
function is_early_init($backtrace) {
    $dangerouscode = array(
        array('function' => 'header', 'type' => '->'),
        array('class' => 'bootstrap_renderer'),
        array('file' => dirname(__FILE__).'/setup.php'),
    );
    foreach ($backtrace as $stackframe) {
        foreach ($dangerouscode as $pattern) {
            $matches = true;
            foreach ($pattern as $property => $value) {
                if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
                    $matches = false;
                }
            }
            if ($matches) {
                return true;
            }
        }
    }
    return false;
}

/**
 * Abort execution by throwing of a general exception,
 * default exception handler displays the error message in most cases.
 *
 * @param string $errorcode The name of the language string containing the error message.
 *      Normally this should be in the error.php lang file.
 * @param string $module The language file to get the error message from.
 * @param string $link The url where the user will be prompted to continue.
 *      If no url is provided the user will be directed to the site index page.
 * @param object $a Extra words and phrases that might be required in the error string
 * @param string $debuginfo optional debugging information
 * @return void, always throws exception!
 */
function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
    throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
}

/**
 * Returns detailed information about specified exception.
 * @param exception $ex
 * @return object
 */
function get_exception_info($ex) {
    global $CFG, $DB, $SESSION;

    if ($ex instanceof moodle_exception) {
        $errorcode = $ex->errorcode;
        $module = $ex->module;
        $a = $ex->a;
        $link = $ex->link;
        $debuginfo = $ex->debuginfo;
    } else {
        $errorcode = 'generalexceptionmessage';
        $module = 'error';
        $a = $ex->getMessage();
        $link = '';
        $debuginfo = '';
    }

    // Append the error code to the debug info to make grepping and googling easier
    $debuginfo .= PHP_EOL."Error code: $errorcode";

    $backtrace = $ex->getTrace();
    $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
    array_unshift($backtrace, $place);

    // Be careful, no guarantee moodlelib.php is loaded.
    if (empty($module) || $module == 'moodle' || $module == 'core') {
        $module = 'error';
    }
    // Search for the $errorcode's associated string
    // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
    if (function_exists('get_string_manager')) {
        if (get_string_manager()->string_exists($errorcode, $module)) {
            $message = get_string($errorcode, $module, $a);
        } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
            // Search in moodle file if error specified - needed for backwards compatibility
            $message = get_string($errorcode, 'moodle', $a);
        } else {
            $message = $module . '/' . $errorcode;
            $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
        }
    } else {
        $message = $module . '/' . $errorcode;
        $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
    }

    // Remove some absolute paths from message and debugging info.
    $searches = array();
    $replaces = array();
    $cfgnames = array('tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
    foreach ($cfgnames as $cfgname) {
        if (property_exists($CFG, $cfgname)) {
            $searches[] = $CFG->$cfgname;
            $replaces[] = "[$cfgname]";
        }
    }
    if (!empty($searches)) {
        $message   = str_replace($searches, $replaces, $message);
        $debuginfo = str_replace($searches, $replaces, $debuginfo);
    }

    // Be careful, no guarantee weblib.php is loaded.
    if (function_exists('clean_text')) {
        $message = clean_text($message);
    } else {
        $message = htmlspecialchars($message);
    }

    if (!empty($CFG->errordocroot)) {
        $errordoclink = $CFG->errordocroot . '/en/';
    } else {
        $errordoclink = get_docs_url();
    }

    if ($module === 'error') {
        $modulelink = 'moodle';
    } else {
        $modulelink = $module;
    }
    $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;

    if (empty($link)) {
        if (!empty($SESSION->fromurl)) {
            $link = $SESSION->fromurl;
            unset($SESSION->fromurl);
        } else {
            $link = $CFG->wwwroot .'/';
        }
    }

    // when printing an error the continue button should never link offsite
    if (stripos($link, $CFG->wwwroot) === false &&
        stripos($link, $CFG->httpswwwroot) === false) {
        $link = $CFG->wwwroot.'/';
    }

    $info = new stdClass();
    $info->message     = $message;
    $info->errorcode   = $errorcode;
    $info->backtrace   = $backtrace;
    $info->link        = $link;
    $info->moreinfourl = $moreinfourl;
    $info->a           = $a;
    $info->debuginfo   = $debuginfo;

    return $info;
}

/**
 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
 *
 * There are three cases:
 *
 * 1. In the normal case, $path will be a short relative path 'component/thing',
 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
 * MoodleDocs in the user's language, and for the appropriate Moodle version.
 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
 *
 * This is the only option that should be used in standard Moodle code. The other
 * two options have been implemented because they are useful for third-party plugins.
 *
 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
 * the link is used as is.
 *
 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
 * $CFG->wwwroot to make the link.
 *
 * @param string $path the place to link to. See above for details.
 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
 */
function get_docs_url($path = null) {
    global $CFG;

    // Absolute URLs are used unmodified.
    if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
        return $path;
    }

    // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
    if (substr($path, 0, 11) === '%%WWWROOT%%') {
        return $CFG->wwwroot . substr($path, 11);
    }

    // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.

    // Check that $CFG->branch has been set up, during installation it won't be.
    if (empty($CFG->branch)) {
        // It's not there yet so look at version.php.
        include($CFG->dirroot.'/version.php');
    } else {
        // We can use $CFG->branch and avoid having to include version.php.
        $branch = $CFG->branch;
    }
    // ensure branch is valid.
    if (!$branch) {
        // We should never get here but in case we do lets set $branch to .
        // the smart one's will know that this is the current directory
        // and the smarter ones will know that there is some smart matching
        // that will ensure people end up at the latest version of the docs.
        $branch = '.';
    }
    if (!empty($CFG->docroot)) {
        return $CFG->docroot . '/' . $branch . '/' . current_language() . '/' . $path;
    } else {
        return 'http://docs.moodle.org/'. $branch . '/' . current_language() . '/' . $path;
    }
}

/**
 * Formats a backtrace ready for output.
 *
 * @param array $callers backtrace array, as returned by debug_backtrace().
 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
 * @return string formatted backtrace, ready for output.
 */
function format_backtrace($callers, $plaintext = false) {
    // do not use $CFG->dirroot because it might not be available in destructors
    $dirroot = dirname(dirname(__FILE__));

    if (empty($callers)) {
        return '';
    }

    $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
    foreach ($callers as $caller) {
        if (!isset($caller['line'])) {
            $caller['line'] = '?'; // probably call_user_func()
        }
        if (!isset($caller['file'])) {
            $caller['file'] = 'unknownfile'; // probably call_user_func()
        }
        $from .= $plaintext ? '* ' : '<li>';
        $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
        if (isset($caller['function'])) {
            $from .= ': call to ';
            if (isset($caller['class'])) {
                $from .= $caller['class'] . $caller['type'];
            }
            $from .= $caller['function'] . '()';
        } else if (isset($caller['exception'])) {
            $from .= ': '.$caller['exception'].' thrown';
        }
        $from .= $plaintext ? "\n" : '</li>';
    }
    $from .= $plaintext ? '' : '</ul>';

    return $from;
}

/**
 * This function makes the return value of ini_get consistent if you are
 * setting server directives through the .htaccess file in apache.
 *
 * Current behavior for value set from php.ini On = 1, Off = [blank]
 * Current behavior for value set from .htaccess On = On, Off = Off
 * Contributed by jdell @ unr.edu
 *
 * @param string $ini_get_arg The argument to get
 * @return bool True for on false for not
 */
function ini_get_bool($ini_get_arg) {
    $temp = ini_get($ini_get_arg);

    if ($temp == '1' or strtolower($temp) == 'on') {
        return true;
    }
    return false;
}

/**
 * This function verifies the sanity of PHP configuration
 * and stops execution if anything critical found.
 */
function setup_validate_php_configuration() {
   // this must be very fast - no slow checks here!!!

   if (ini_get_bool('register_globals')) {
       print_error('globalswarning', 'admin');
   }
   if (ini_get_bool('session.auto_start')) {
       print_error('sessionautostartwarning', 'admin');
   }
   if (ini_get_bool('magic_quotes_runtime')) {
       print_error('fatalmagicquotesruntime', 'admin');
   }
}

/**
 * Initialise global $CFG variable.
 * @private to be used only from lib/setup.php
 */
function initialise_cfg() {
    global $CFG, $DB;

    if (!$DB) {
        // This should not happen.
        return;
    }

    try {
        $localcfg = get_config('core');
    } catch (dml_exception $e) {
        // Most probably empty db, going to install soon.
        return;
    }

    foreach ($localcfg as $name => $value) {
        // Note that get_config() keeps forced settings
        // and normalises values to string if possible.
        $CFG->{$name} = $value;
    }
}

/**
 * Initialises $FULLME and friends. Private function. Should only be called from
 * setup.php.
 */
function initialise_fullme() {
    global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;

    // Detect common config error.
    if (substr($CFG->wwwroot, -1) == '/') {
        print_error('wwwrootslash', 'error');
    }

    if (CLI_SCRIPT) {
        initialise_fullme_cli();
        return;
    }

    $rurl = setup_get_remote_url();
    $wwwroot = parse_url($CFG->wwwroot.'/');

    if (empty($rurl['host'])) {
        // missing host in request header, probably not a real browser, let's ignore them

    } else if (!empty($CFG->reverseproxy)) {
        // $CFG->reverseproxy specifies if reverse proxy server used
        // Used in load balancing scenarios.
        // Do not abuse this to try to solve lan/wan access problems!!!!!

    } else {
        if (($rurl['host'] !== $wwwroot['host']) or
                (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
                (strpos($rurl['path'], $wwwroot['path']) !== 0)) {

            // Explain the problem and redirect them to the right URL
            if (!defined('NO_MOODLE_COOKIES')) {
                define('NO_MOODLE_COOKIES', true);
            }
            // The login/token.php script should call the correct url/port.
            if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
                $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
                $calledurl = $rurl['host'];
                if (!empty($rurl['port'])) {
                    $calledurl .=  ':'. $rurl['port'];
                }
                $correcturl = $wwwroot['host'];
                if (!empty($wwwrootport)) {
                    $correcturl .=  ':'. $wwwrootport;
                }
                throw new moodle_exception('requirecorrectaccess', 'error', '', null,
                    'You called ' . $calledurl .', you should have called ' . $correcturl);
            }
            redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 0);
        }
    }

    // Check that URL is under $CFG->wwwroot.
    if (strpos($rurl['path'], $wwwroot['path']) === 0) {
        $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
    } else {
        // Probably some weird external script
        $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
        return;
    }

    // $CFG->sslproxy specifies if external SSL appliance is used
    // (That is, the Moodle server uses http, with an external box translating everything to https).
    if (empty($CFG->sslproxy)) {
        if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
            print_error('sslonlyaccess', 'error');
        }
    } else {
        if ($wwwroot['scheme'] !== 'https') {
            throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
        }
        $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
    }

    // hopefully this will stop all those "clever" admins trying to set up moodle
    // with two different addresses in intranet and Internet
    if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
        print_error('reverseproxyabused', 'error');
    }

    $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
    if (!empty($wwwroot['port'])) {
        $hostandport .= ':'.$wwwroot['port'];
    }

    $FULLSCRIPT = $hostandport . $rurl['path'];
    $FULLME = $hostandport . $rurl['fullpath'];
    $ME = $rurl['fullpath'];
}

/**
 * Initialises $FULLME and friends for command line scripts.
 * This is a private method for use by initialise_fullme.
 */
function initialise_fullme_cli() {
    global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;

    // Urls do not make much sense in CLI scripts
    $backtrace = debug_backtrace();
    $topfile = array_pop($backtrace);
    $topfile = realpath($topfile['file']);
    $dirroot = realpath($CFG->dirroot);

    if (strpos($topfile, $dirroot) !== 0) {
        // Probably some weird external script
        $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
    } else {
        $relativefile = substr($topfile, strlen($dirroot));
        $relativefile = str_replace('\\', '/', $relativefile); // Win fix
        $SCRIPT = $FULLSCRIPT = $relativefile;
        $FULLME = $ME = null;
    }
}

/**
 * Get the URL that PHP/the web server thinks it is serving. Private function
 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
 * @return array in the same format that parse_url returns, with the addition of
 *      a 'fullpath' element, which includes any slasharguments path.
 */
function setup_get_remote_url() {
    $rurl = array();
    if (isset($_SERVER['HTTP_HOST'])) {
        list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
    } else {
        $rurl['host'] = null;
    }
    $rurl['port'] = $_SERVER['SERVER_PORT'];
    $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
    $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';

    if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
        //Apache server
        $rurl['fullpath'] = $_SERVER['REQUEST_URI'];

    } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
        //IIS - needs a lot of tweaking to make it work
        $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];

        // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
        //       since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
        //       example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]

        if ($_SERVER['QUERY_STRING'] != '') {
            $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
        }
        $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility

/* NOTE: following servers are not fully tested! */

    } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
        //lighttpd - not officially supported
        $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

    } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
        //nginx - not officially supported
        if (!isset($_SERVER['SCRIPT_NAME'])) {
            die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
        }
        $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
         //cherokee - not officially supported
         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
         //zeus - not officially supported
         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

    } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
        //LiteSpeed - not officially supported
        $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

    } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
        //obscure name found on some servers - this is definitely not supported
        $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

    } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
        // built-in PHP Development Server
        $rurl['fullpath'] = $_SERVER['REQUEST_URI'];

    } else {
        throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
    }

    // sanitize the url a bit more, the encoding style may be different in vars above
    $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
    $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);

    return $rurl;
}

/**
 * Try to work around the 'max_input_vars' restriction if necessary.
 */
function workaround_max_input_vars() {
    // Make sure this gets executed only once from lib/setup.php!
    static $executed = false;
    if ($executed) {
        debugging('workaround_max_input_vars() must be called only once!');
        return;
    }
    $executed = true;

    if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
        // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
        return;
    }

    if (!isloggedin() or isguestuser()) {
        // Only real users post huge forms.
        return;
    }

    $max = (int)ini_get('max_input_vars');

    if ($max <= 0) {
        // Most probably PHP < 5.3.9 that does not implement this limit.
        return;
    }

    if ($max >= 200000) {
        // This value should be ok for all our forms, by setting it in php.ini
        // admins may prevent any unexpected regressions caused by this hack.

        // Note there is no need to worry about DDoS caused by making this limit very high
        // because there are very many easier ways to DDoS any Moodle server.
        return;
    }

    if (count($_POST, COUNT_RECURSIVE) < $max) {
        return;
    }

    // Large POST request with enctype supported by php://input.
    // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
    $str = file_get_contents("php://input");
    if ($str === false or $str === '') {
        // Some weird error.
        return;
    }

    $delim = '&';
    $fun = create_function('$p', 'return implode("'.$delim.'", $p);');
    $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));

    foreach ($chunks as $chunk) {
        $values = array();
        parse_str($chunk, $values);

        if (ini_get_bool('magic_quotes_gpc')) {
            // Use the same logic as lib/setup.php to work around deprecated magic quotes.
            $values = array_map('stripslashes_deep', $values);
        }

        merge_query_params($_POST, $values);
        merge_query_params($_REQUEST, $values);
    }
}

/**
 * Merge parsed POST chunks.
 *
 * NOTE: this is not perfect, but it should work in most cases hopefully.
 *
 * @param array $target
 * @param array $values
 */
function merge_query_params(array &$target, array $values) {
    if (isset($values[0]) and isset($target[0])) {
        // This looks like a split [] array, lets verify the keys are continuous starting with 0.
        $keys1 = array_keys($values);
        $keys2 = array_keys($target);
        if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
            foreach ($values as $v) {
                $target[] = $v;
            }
            return;
        }
    }
    foreach ($values as $k => $v) {
        if (!isset($target[$k])) {
            $target[$k] = $v;
            continue;
        }
        if (is_array($target[$k]) and is_array($v)) {
            merge_query_params($target[$k], $v);
            continue;
        }
        // We should not get here unless there are duplicates in params.
        $target[$k] = $v;
    }
}

/**
 * Initializes our performance info early.
 *
 * Pairs up with get_performance_info() which is actually
 * in moodlelib.php. This function is here so that we can
 * call it before all the libs are pulled in.
 *
 * @uses $PERF
 */
function init_performance_info() {

    global $PERF, $CFG, $USER;

    $PERF = new stdClass();
    $PERF->logwrites = 0;
    if (function_exists('microtime')) {
        $PERF->starttime = microtime();
    }
    if (function_exists('memory_get_usage')) {
        $PERF->startmemory = memory_get_usage();
    }
    if (function_exists('posix_times')) {
        $PERF->startposixtimes = posix_times();
    }
}

/**
 * Indicates whether we are in the middle of the initial Moodle install.
 *
 * Very occasionally it is necessary avoid running certain bits of code before the
 * Moodle installation has completed. The installed flag is set in admin/index.php
 * after Moodle core and all the plugins have been installed, but just before
 * the person doing the initial install is asked to choose the admin password.
 *
 * @return boolean true if the initial install is not complete.
 */
function during_initial_install() {
    global $CFG;
    return empty($CFG->rolesactive);
}

/**
 * Function to raise the memory limit to a new value.
 * Will respect the memory limit if it is higher, thus allowing
 * settings in php.ini, apache conf or command line switches
 * to override it.
 *
 * The memory limit should be expressed with a constant
 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
 * It is possible to use strings or integers too (eg:'128M').
 *
 * @param mixed $newlimit the new memory limit
 * @return bool success
 */
function raise_memory_limit($newlimit) {
    global $CFG;

    if ($newlimit == MEMORY_UNLIMITED) {
        ini_set('memory_limit', -1);
        return true;

    } else if ($newlimit == MEMORY_STANDARD) {
        if (PHP_INT_SIZE > 4) {
            $newlimit = get_real_size('128M'); // 64bit needs more memory
        } else {
            $newlimit = get_real_size('96M');
        }

    } else if ($newlimit == MEMORY_EXTRA) {
        if (PHP_INT_SIZE > 4) {
            $newlimit = get_real_size('384M'); // 64bit needs more memory
        } else {
            $newlimit = get_real_size('256M');
        }
        if (!empty($CFG->extramemorylimit)) {
            $extra = get_real_size($CFG->extramemorylimit);
            if ($extra > $newlimit) {
                $newlimit = $extra;
            }
        }

    } else if ($newlimit == MEMORY_HUGE) {
        // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
        $newlimit = get_real_size('2G');
        if (!empty($CFG->extramemorylimit)) {
            $extra = get_real_size($CFG->extramemorylimit);
            if ($extra > $newlimit) {
                $newlimit = $extra;
            }
        }

    } else {
        $newlimit = get_real_size($newlimit);
    }

    if ($newlimit <= 0) {
        debugging('Invalid memory limit specified.');
        return false;
    }

    $cur = ini_get('memory_limit');
    if (empty($cur)) {
        // if php is compiled without --enable-memory-limits
        // apparently memory_limit is set to ''
        $cur = 0;
    } else {
        if ($cur == -1){
            return true; // unlimited mem!
        }
        $cur = get_real_size($cur);
    }

    if ($newlimit > $cur) {
        ini_set('memory_limit', $newlimit);
        return true;
    }
    return false;
}

/**
 * Function to reduce the memory limit to a new value.
 * Will respect the memory limit if it is lower, thus allowing
 * settings in php.ini, apache conf or command line switches
 * to override it
 *
 * The memory limit should be expressed with a string (eg:'64M')
 *
 * @param string $newlimit the new memory limit
 * @return bool
 */
function reduce_memory_limit($newlimit) {
    if (empty($newlimit)) {
        return false;
    }
    $cur = ini_get('memory_limit');
    if (empty($cur)) {
        // if php is compiled without --enable-memory-limits
        // apparently memory_limit is set to ''
        $cur = 0;
    } else {
        if ($cur == -1){
            return true; // unlimited mem!
        }
        $cur = get_real_size($cur);
    }

    $new = get_real_size($newlimit);
    // -1 is smaller, but it means unlimited
    if ($new < $cur && $new != -1) {
        ini_set('memory_limit', $newlimit);
        return true;
    }
    return false;
}

/**
 * Converts numbers like 10M into bytes.
 *
 * @param string $size The size to be converted
 * @return int
 */
function get_real_size($size = 0) {
    if (!$size) {
        return 0;
    }
    $scan = array();
    $scan['GB'] = 1073741824;
    $scan['Gb'] = 1073741824;
    $scan['G'] = 1073741824;
    $scan['MB'] = 1048576;
    $scan['Mb'] = 1048576;
    $scan['M'] = 1048576;
    $scan['m'] = 1048576;
    $scan['KB'] = 1024;
    $scan['Kb'] = 1024;
    $scan['K'] = 1024;
    $scan['k'] = 1024;

    while (list($key) = each($scan)) {
        if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
            $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
            break;
        }
    }
    return $size;
}

/**
 * Try to disable all output buffering and purge
 * all headers.
 *
 * @access private to be called only from lib/setup.php !
 * @return void
 */
function disable_output_buffering() {
    $olddebug = error_reporting(0);

    // disable compression, it would prevent closing of buffers
    if (ini_get_bool('zlib.output_compression')) {
        ini_set('zlib.output_compression', 'Off');
    }

    // try to flush everything all the time
    ob_implicit_flush(true);

    // close all buffers if possible and discard any existing output
    // this can actually work around some whitespace problems in config.php
    while(ob_get_level()) {
        if (!ob_end_clean()) {
            // prevent infinite loop when buffer can not be closed
            break;
        }
    }

    // disable any other output handlers
    ini_set('output_handler', '');

    error_reporting($olddebug);
}

/**
 * Check whether a major upgrade is needed. That is defined as an upgrade that
 * changes something really fundamental in the database, so nothing can possibly
 * work until the database has been updated, and that is defined by the hard-coded
 * version number in this function.
 */
function redirect_if_major_upgrade_required() {
    global $CFG;
    $lastmajordbchanges = 2013100400.02;
    if (empty($CFG->version) or (float)$CFG->version < $lastmajordbchanges or
            during_initial_install() or !empty($CFG->adminsetuppending)) {
        try {
            @\core\session\manager::terminate_current();
        } catch (Exception $e) {
            // Ignore any errors, redirect to upgrade anyway.
        }
        $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
        @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
        @header('Location: ' . $url);
        echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
        exit;
    }
}

/**
 * Makes sure that upgrade process is not running
 *
 * To be inserted in the core functions that can not be called by pluigns during upgrade.
 * Core upgrade should not use any API functions at all.
 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
 *
 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
 * @param bool $warningonly if true displays a warning instead of throwing an exception
 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
 */
function upgrade_ensure_not_running($warningonly = false) {
    global $CFG;
    if (!empty($CFG->upgraderunning)) {
        if (!$warningonly) {
            throw new moodle_exception('cannotexecduringupgrade');
        } else {
            debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
            return false;
        }
    }
    return true;
}

/**
 * Function to check if a directory exists and by default create it if not exists.
 *
 * Previously this was accepting paths only from dataroot, but we now allow
 * files outside of dataroot if you supply custom paths for some settings in config.php.
 * This function does not verify that the directory is writable.
 *
 * NOTE: this function uses current file stat cache,
 *       please use clearstatcache() before this if you expect that the
 *       directories may have been removed recently from a different request.
 *
 * @param string $dir absolute directory path
 * @param boolean $create directory if does not exist
 * @param boolean $recursive create directory recursively
 * @return boolean true if directory exists or created, false otherwise
 */
function check_dir_exists($dir, $create = true, $recursive = true) {
    global $CFG;

    umask($CFG->umaskpermissions);

    if (is_dir($dir)) {
        return true;
    }

    if (!$create) {
        return false;
    }

    return mkdir($dir, $CFG->directorypermissions, $recursive);
}

/**
 * Create a directory and make sure it is writable.
 *
 * @private
 * @param string $dir  the full path of the directory to be created
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function make_writable_directory($dir, $exceptiononerror = true) {
    global $CFG;

    if (file_exists($dir) and !is_dir($dir)) {
        if ($exceptiononerror) {
            throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
        } else {
            return false;
        }
    }

    umask($CFG->umaskpermissions);

    if (!file_exists($dir)) {
        if (!mkdir($dir, $CFG->directorypermissions, true)) {
            clearstatcache();
            // There might be a race condition when creating directory.
            if (!is_dir($dir)) {
                if ($exceptiononerror) {
                    throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
                } else {
                    debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
                    return false;
                }
            }
        }
    }

    if (!is_writable($dir)) {
        if ($exceptiononerror) {
            throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
        } else {
            return false;
        }
    }

    return $dir;
}

/**
 * Protect a directory from web access.
 * Could be extended in the future to support other mechanisms (e.g. other webservers).
 *
 * @private
 * @param string $dir  the full path of the directory to be protected
 */
function protect_directory($dir) {
    global $CFG;
    // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
    if (!file_exists("$dir/.htaccess")) {
        if ($handle = fopen("$dir/.htaccess", 'w')) {   // For safety
            @fwrite($handle, "deny from all\r\nAllowOverride None\r\nNote: this file is broken intentionally, we do not want anybody to undo it in subdirectory!\r\n");
            @fclose($handle);
            @chmod("$dir/.htaccess", $CFG->filepermissions);
        }
    }
}

/**
 * Create a directory under dataroot and make sure it is writable.
 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
 *
 * @param string $directory  the full path of the directory to be created under $CFG->dataroot
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function make_upload_directory($directory, $exceptiononerror = true) {
    global $CFG;

    if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
        debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');

    } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
        debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');

    } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
        debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
    }

    protect_directory($CFG->dataroot);
    return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
}

/**
 * Create a directory under tempdir and make sure it is writable.
 * Temporary files should be used during the current request only!
 *
 * @param string $directory  the full path of the directory to be created under $CFG->tempdir
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function make_temp_directory($directory, $exceptiononerror = true) {
    global $CFG;
    if ($CFG->tempdir !== "$CFG->dataroot/temp") {
        check_dir_exists($CFG->tempdir, true, true);
        protect_directory($CFG->tempdir);
    } else {
        protect_directory($CFG->dataroot);
    }
    return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
}

/**
 * Create a directory under cachedir and make sure it is writable.
 *
 * Note: this cache directory is shared by all cluster nodes.
 *
 * @param string $directory  the full path of the directory to be created under $CFG->cachedir
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function make_cache_directory($directory, $exceptiononerror = true) {
    global $CFG;
    if ($CFG->cachedir !== "$CFG->dataroot/cache") {
        check_dir_exists($CFG->cachedir, true, true);
        protect_directory($CFG->cachedir);
    } else {
        protect_directory($CFG->dataroot);
    }
    return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
}

/**
 * Create a directory under localcachedir and make sure it is writable.
 * The files in this directory MUST NOT change, use revisions or content hashes to
 * work around this limitation - this means you can only add new files here.
 *
 * The content of this directory gets purged automatically on all cluster nodes
 * after calling purge_all_caches() before new data is written to this directory.
 *
 * Note: this local cache directory does not need to be shared by cluster nodes.
 *
 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function make_localcache_directory($directory, $exceptiononerror = true) {
    global $CFG;

    make_writable_directory($CFG->localcachedir, $exceptiononerror);

    if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
        protect_directory($CFG->localcachedir);
    } else {
        protect_directory($CFG->dataroot);
    }

    if (!isset($CFG->localcachedirpurged)) {
        $CFG->localcachedirpurged = 0;
    }
    $timestampfile = "$CFG->localcachedir/.lastpurged";

    if (!file_exists($timestampfile)) {
        touch($timestampfile);
        @chmod($timestampfile, $CFG->filepermissions);

    } else if (filemtime($timestampfile) <  $CFG->localcachedirpurged) {
        // This means our local cached dir was not purged yet.
        remove_dir($CFG->localcachedir, true);
        if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
            protect_directory($CFG->localcachedir);
        }
        touch($timestampfile);
        @chmod($timestampfile, $CFG->filepermissions);
        clearstatcache();
    }

    if ($directory === '') {
        return $CFG->localcachedir;
    }

    return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
}

/**
 * Checks if current user is a web crawler.
 *
 * This list can not be made complete, this is not a security
 * restriction, we make the list only to help these sites
 * especially when automatic guest login is disabled.
 *
 * If admin needs security they should enable forcelogin
 * and disable guest access!!
 *
 * @return bool
 */
function is_web_crawler() {
    if (!empty($_SERVER['HTTP_USER_AGENT'])) {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) {  // Yahoo
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) {  // Zoomspider
            return true;
        } else if (stripos($_SERVER['HTTP_USER_AGENT'], 'msnbot') !== false ) {  // MSN Search
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'bingbot') !== false ) {  // Bing
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yandex') !== false ) {
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'AltaVista') !== false ) {
            return true;
        } else if (stripos($_SERVER['HTTP_USER_AGENT'], 'baiduspider') !== false ) {  // Baidu
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Teoma') !== false ) {  // Ask.com
            return true;
        }
    }
    return false;
}

/**
 * This class solves the problem of how to initialise $OUTPUT.
 *
 * The problem is caused be two factors
 * <ol>
 * <li>On the one hand, we cannot be sure when output will start. In particular,
 * an error, which needs to be displayed, could be thrown at any time.</li>
 * <li>On the other hand, we cannot be sure when we will have all the information
 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
 * (potentially) depends on the current course, course categories, and logged in user.
 * It also depends on whether the current page requires HTTPS.</li>
 * </ol>
 *
 * So, it is hard to find a single natural place during Moodle script execution,
 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
 * adopt the following strategy
 * <ol>
 * <li>We will initialise $OUTPUT the first time it is used.</li>
 * <li>If, after $OUTPUT has been initialised, the script tries to change something
 * that $OUTPUT depends on, we throw an exception making it clear that the script
 * did something wrong.
 * </ol>
 *
 * The only problem with that is, how do we initialise $OUTPUT on first use if,
 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
 *
 * Note that this class is used before lib/outputlib.php has been loaded, so we
 * must be careful referring to classes/functions from there, they may not be
 * defined yet, and we must avoid fatal errors.
 *
 * @copyright 2009 Tim Hunt
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since     Moodle 2.0
 */
class bootstrap_renderer {
    /**
     * Handles re-entrancy. Without this, errors or debugging output that occur
     * during the initialisation of $OUTPUT, cause infinite recursion.
     * @var boolean
     */
    protected $initialising = false;

    /**
     * Have we started output yet?
     * @return boolean true if the header has been printed.
     */
    public function has_started() {
        return false;
    }

    /**
     * Constructor - to be used by core code only.
     * @param string $method The method to call
     * @param array $arguments Arguments to pass to the method being called
     * @return string
     */
    public function __call($method, $arguments) {
        global $OUTPUT, $PAGE;

        $recursing = false;
        if ($method == 'notification') {
            // Catch infinite recursion caused by debugging output during print_header.
            $backtrace = debug_backtrace();
            array_shift($backtrace);
            array_shift($backtrace);
            $recursing = is_early_init($backtrace);
        }

        $earlymethods = array(
            'fatal_error' => 'early_error',
            'notification' => 'early_notification',
        );

        // If lib/outputlib.php has been loaded, call it.
        if (!empty($PAGE) && !$recursing) {
            if (array_key_exists($method, $earlymethods)) {
                //prevent PAGE->context warnings - exceptions might appear before we set any context
                $PAGE->set_context(null);
            }
            $PAGE->initialise_theme_and_output();
            return call_user_func_array(array($OUTPUT, $method), $arguments);
        }

        $this->initialising = true;

        // Too soon to initialise $OUTPUT, provide a couple of key methods.
        if (array_key_exists($method, $earlymethods)) {
            return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
        }

        throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
    }

    /**
     * Returns nicely formatted error message in a div box.
     * @static
     * @param string $message error message
     * @param string $moreinfourl (ignored in early errors)
     * @param string $link (ignored in early errors)
     * @param array $backtrace
     * @param string $debuginfo
     * @return string
     */
    public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
        global $CFG;

        $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
width: 80%; -moz-border-radius: 20px; padding: 15px">
' . $message . '
</div>';
        // Check whether debug is set.
        $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
        // Also check we have it set in the config file. This occurs if the method to read the config table from the
        // database fails, reading from the config table is the first database interaction we have.
        $debug = $debug || (!empty($CFG->config_php_settings['debug'])  && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
        if ($debug) {
            if (!empty($debuginfo)) {
                $debuginfo = s($debuginfo); // removes all nasty JS
                $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
                $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
            }
            if (!empty($backtrace)) {
                $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
            }
        }

        return $content;
    }

    /**
     * This function should only be called by this class, or from exception handlers
     * @static
     * @param string $message error message
     * @param string $moreinfourl (ignored in early errors)
     * @param string $link (ignored in early errors)
     * @param array $backtrace
     * @param string $debuginfo extra information for developers
     * @return string
     */
    public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
        global $CFG;

        if (CLI_SCRIPT) {
            echo "!!! $message !!!\n";
            if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
                if (!empty($debuginfo)) {
                    echo "\nDebug info: $debuginfo";
                }
                if (!empty($backtrace)) {
                    echo "\nStack trace: " . format_backtrace($backtrace, true);
                }
            }
            return;

        } else if (AJAX_SCRIPT) {
            $e = new stdClass();
            $e->error      = $message;
            $e->stacktrace = NULL;
            $e->debuginfo  = NULL;
            if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
                if (!empty($debuginfo)) {
                    $e->debuginfo = $debuginfo;
                }
                if (!empty($backtrace)) {
                    $e->stacktrace = format_backtrace($backtrace, true);
                }
            }
            $e->errorcode  = $errorcode;
            @header('Content-Type: application/json; charset=utf-8');
            echo json_encode($e);
            return;
        }

        // In the name of protocol correctness, monitoring and performance
        // profiling, set the appropriate error headers for machine consumption.
        $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
        @header($protocol . ' 503 Service Unavailable');

        // better disable any caching
        @header('Content-Type: text/html; charset=utf-8');
        @header('X-UA-Compatible: IE=edge');
        @header('Cache-Control: no-store, no-cache, must-revalidate');
        @header('Cache-Control: post-check=0, pre-check=0', false);
        @header('Pragma: no-cache');
        @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
        @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');

        if (function_exists('get_string')) {
            $strerror = get_string('error');
        } else {
            $strerror = 'Error';
        }

        $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);

        return self::plain_page($strerror, $content);
    }

    /**
     * Early notification message
     * @static
     * @param string $message
     * @param string $classes usually notifyproblem or notifysuccess
     * @return string
     */
    public static function early_notification($message, $classes = 'notifyproblem') {
        return '<div class="' . $classes . '">' . $message . '</div>';
    }

    /**
     * Page should redirect message.
     * @static
     * @param string $encodedurl redirect url
     * @return string
     */
    public static function plain_redirect_message($encodedurl) {
        $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
                $encodedurl .'">'. get_string('continue') .'</a></div>';
        return self::plain_page(get_string('redirect'), $message);
    }

    /**
     * Early redirection page, used before full init of $PAGE global
     * @static
     * @param string $encodedurl redirect url
     * @param string $message redirect message
     * @param int $delay time in seconds
     * @return string redirect page
     */
    public static function early_redirect_message($encodedurl, $message, $delay) {
        $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
        $content = self::early_error_content($message, null, null, null);
        $content .= self::plain_redirect_message($encodedurl);

        return self::plain_page(get_string('redirect'), $content, $meta);
    }

    /**
     * Output basic html page.
     * @static
     * @param string $title page title
     * @param string $content page content
     * @param string $meta meta tag
     * @return string html page
     */
    public static function plain_page($title, $content, $meta = '') {
        if (function_exists('get_string') && function_exists('get_html_lang')) {
            $htmllang = get_html_lang();
        } else {
            $htmllang = '';
        }

        $footer = '';
        if (MDL_PERF_TEST) {
            $perfinfo = get_performance_info();
            $footer = '<footer>' . $perfinfo['html'] . '</footer>';
        }

        return '<!DOCTYPE html>
<html ' . $htmllang . '>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
'.$meta.'
<title>' . $title . '</title>
</head><body>' . $content . $footer . '</body></html>';
    }
}
package poker

import (
	"encoding/json"
	"os"
	"fmt"
	"sort"
)

type FileSystemPlayerStore struct {
	database *json.Encoder
	league   League
}

func FileSystemPlayerStoreFromFile(dbFileName string) (*FileSystemPlayerStore, func(), error) {
	db, err := os.OpenFile(dbFileName, os.O_CREATE|os.O_RDWR, 0666)
	err = ErrorFileOpening(err, dbFileName)
	if err != nil {
		return nil, nil, err
	}
	closeFunc := func() {
		db.Close()
	}
	store, err := NewFileSystemPlayerStore(db)
	err = ErrorFileCreation(err)
	if err != nil {
		return nil, nil, err
	}
	return store, closeFunc, nil
}

func initializePlayerDBFile(file *os.File) error {
	file.Seek(0, 0)
	info, err := file.Stat()
	if err != nil {
		return fmt.Errorf("problem getting file info from file %s, %v", file.Name(), err)
	}
	if info.Size() == 0 {
		file.Write([]byte("[]"))
		file.Seek(0, 0)
	}
	return nil
}

func NewFileSystemPlayerStore(file *os.File) (*FileSystemPlayerStore, error) {
	err := initializePlayerDBFile(file)
	if err != nil {
		return nil, fmt.Errorf("problem initializing player db file, %v", err)
	}
	league, err := NewLeague(file)
	if err != nil {
		return nil, fmt.Errorf("problem loading player store from file %s, %v", file.Name(), err)
	}
	return &FileSystemPlayerStore{json.NewEncoder(&Tape{file}), league}, nil
}

func (i *FileSystemPlayerStore) getPlayerScore(player string) int {
	play := i.GetLeague().Find(player)
	if play != nil {
		return play.Wins
	}
	return 0
}

func (i *FileSystemPlayerStore) RecordWin(player string) {
	play := i.league.Find(player)
	if play != nil {
		play.Wins++
	} else {
		i.league = append(i.league, Player{player, 1})
	}
	i.database.Encode(i.league)
}

func (i *FileSystemPlayerStore) GetLeague() League {
	sort.SliceStable(i.league, func(k, j int) bool {
		return i.league[k].Wins > i.league[j].Wins
	})
	return i.league
}
#include "WinSystemMirGLContext.h"

bool CWinSystemMirGLContext::CreateNewWindow(const std::string& name,
                                               bool fullScreen,
                                               const RESOLUTION_INFO& res)
{
  if (!m_pGLContext.CreateDisplay(m_connection,
                                  EGL_OPENGL_BIT,
                                  EGL_OPENGL_API))
  {
    return false;
  }

  m_pixel_format = mir_connection_get_egl_pixel_format(m_connection,
                                                       m_pGLContext.m_eglDisplay,
                                                       m_pGLContext.m_eglConfig);

  CWinSystemMir::CreateNewWindow(name, fullScreen, res);

  if (!m_pGLContext.CreateSurface(m_window))
  {
    return false;
  }

  if (!m_pGLContext.CreateContext())
  {
    return false;
  }

  return SetFullScreen(fullScreen, res, false);
}

bool CWinSystemMirGLContext::SetFullScreen(bool fullScreen, const RESOLUTION_INFO& res, bool blankOtherDisplays)
{
  auto ret = CWinSystemMir::SetFullScreen(fullScreen, res, blankOtherDisplays);
  if (ret)
  {
    CRenderSystemGL::ResetRenderSystem(res.iWidth, res.iHeight);
  }

  return ret;
}

void CWinSystemMirGLContext::SetVSyncImpl(bool enable)
{
  m_pGLContext.SetVSync(enable);
}

void CWinSystemMirGLContext::PresentRenderImpl(bool rendered)
{
  if (rendered)
  {
    m_pGLContext.SwapBuffers();
  }
}

EGLDisplay CWinSystemMirGLContext::GetEGLDisplay() const
{
  return m_pGLContext.m_eglDisplay;
}

EGLSurface CWinSystemMirGLContext::GetEGLSurface() const
{
  return m_pGLContext.m_eglSurface;
}

EGLContext CWinSystemMirGLContext::GetEGLContext() const
{
  return m_pGLContext.m_eglContext;
}

EGLConfig  CWinSystemMirGLContext::GetEGLConfig() const
{
  return m_pGLContext.m_eglConfig;
}

// FIXME Implement
bool CWinSystemMirGLContext::IsExtSupported(const char* extension)
{
  return false;
}
function disp_path(id) {    
    routeLayer.destroyFeatures();
    features = geojson_reader.read(paths[id]);
    if(features)
        routeLayer.addFeatures(features);
}

function compute() {
    if( areBothMarked() )
    {
        $.getJSON("path", {slon: nodes['start'].lon, 
                slat: nodes['start'].lat,
                dlon: nodes['dest'].lon,
                dlat: nodes['dest'].lat,
                time: $("#datepicker").val()
                },
        function(data) {
                if(data.error) {
                    $("#path_costs").html("<span class=\"errorOrange\">No route found</span>");
                clearPath();
                clearArrow("start");
                clearArrow("dest");
                }
            else {
                $("#path_costs").html("<span class=\"tableDes\">Costs:</span>\n<table id=\"costs_table\" class=\"tablesorter\">\n");
                $("#path_costs table").append("<thead><tr>");
                $.each(data.objectives, function(key, val){$("#path_costs tr").append(
                                        "<th>"+val+"</th>"
                                    );});
                $("#path_costs table").append("<tbody>");
                    $.each( data.paths, function(key, val){
                        $("#path_costs tbody").append("<tr>");
                        $.each(val.cost, function(k,v){
                        if( k != 0 ) {
                            if( parseInt(v) != 0 )
                                $("#path_costs tbody tr:last").append("<td><span class=\"tableDes\">"+v+"</span></td>");
                            else
                                $("#path_costs tbody tr:last").append("<td><span class=\"tableDes\">None</span></td>");
                        }
                        else {
                            $("#path_costs tbody tr:last").append(
                                        "<td>"+transformToDurationString(v)+"</td>"
                            );
                        }
                    });
                        $("#path_costs tbody tr:last").click(function(){disp_path(key); 
                    $("#path_costs tbody tr").removeClass("hl"); 
                    $(this).addClass("hl"); });});
                    $("#costs_table").tablesorter();
                paths = data.paths;
                disp_path(0);
                if( !fromHash )
                    addToHash();
            }
        });
        }
}

function handleClick(coord, mark) {
    var lonlat = map.getLonLatFromViewPortPx(coord);
    lonlat.transform(proj900913, proj4326);
    nodes['fmouse_'+mark]=true;
    reverseGeocoding(lonlat,mark);
}

// Coordinates in 4326 projection (lon/lat)
function setMark(lonlat, mark)
{
    if(node_markers[mark]) {
        layerMarkers.removeFeatures(node_markers[mark]);
        node_markers[mark].destroy();
        node_markers[mark] = null;
    }
    node_markers[mark] = new OpenLayers.Feature.Vector(LonLatToPoint(LonLatToM(
                                        new OpenLayers.LonLat(lonlat.lon,lonlat.lat))), 
                                        mark, 
                                        icon[mark]
    );
    layerMarkers.addFeatures(node_markers[mark]);
    layerMarkers.drawFeature(node_markers[mark]);
    
} // End of function setMark(lonlat, mark)

function areBothMarked() {
        return nodes['start'].lon && nodes['dest'].lat && nodes['dest'].lon && nodes['dest'].lat; 
}

function addToHash() {
    var tmp = new OpenLayers.LonLat(map.center.lon, map.center.lat).transform(
                                map.getProjectionObject(),
                                new OpenLayers.Projection("EPSG:4326")
    );                      
    $.getJSON("addhash", {
                mlon: tmp.lon,
                mlat: tmp.lat,
                zoom: map.zoom,                                 
                slon: nodes['start'].lon, 
                slat: nodes['start'].lat,
                dlon: nodes['dest'].lon,
                dlat: nodes['dest'].lat,
                time: $("#datepicker").val(),
                saddress: document.getElementById('startAdr').value,
                daddress: document.getElementById('endAdr').value
                },
                function(data)
                {
                    if(data.error)
                    {
                        $("#hash_url").html(
                        "<span class=\"errorOrange\">Couldn't add the route into the database</span>"
                        );
                    }
                    else
                    {
                        $("#hash_url").html(
                        "<p>Send this url to a friend : <br/><span class=\"tinyText\">" +
                        hurl +"h?id="+data.h+"</span></p>"
                        );  
                    }
                }
    );
}

function transformToDurationString(v) {
    var tmp = parseInt(v);
    var minutes = ( tmp / 60) % 60;
    var hours = tmp / 3600;
    if( (Math.ceil(hours) - 1) > 0 )
        return ( (Math.ceil(hours) - 1) + "h" + (Math.ceil(minutes)) + "m");
    else
        return ( (Math.ceil(minutes) ) + "m");
}       

//Initialise the 'map' object
function init() {
    AnyTime.picker( "datepicker", { format: "%e/%m/%Y %H:%i", firstDOW: 1 } );
    $("#datepicker").val(now);
    document.getElementById('startAdr').value = initialStartText;
    document.getElementById('endAdr').value = initialDestText;
    cacheStart = "";
    cacheDest = "";
    nodes['fmouse_start'] = true;
    nodes['fmouse_dest'] = true;
    map = new OpenLayers.Map ("map",
                
                {
                    maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
                    maxResolution: 156543.0399,
                    numZoomLevels: 19,
                    units: 'm',
                    projection: proj900913,
                    displayProjection: proj4326,
                    controls: [
                      new OpenLayers.Control.Navigation({zoomWheelEnabled: true}),
                      new OpenLayers.Control.PanZoomBar(),
                      new OpenLayers.Control.LayerSwitcher(),
                  ]
                }
    );
    // Define the map layer
    // Other defined layers are OpenLayers.Layer.OSM.Mapnik, OpenLayers.Layer.OSM.Maplint and OpenLayers.Layer.OSM.CycleMap
    layerTilesMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
    map.addLayer(layerTilesMapnik);
    var cloudmade = new OpenLayers.Layer.CloudMade("CloudMade", {
    key: 'fff941bc66c34422a2e41a529e34aebc',
    styleId: 7843
});
    map.addLayer(cloudmade);
     layerTilesCycle = new OpenLayers.Layer.OSM.CycleMap("CycleMap");
    map.addLayer(layerTilesCycle);
    layerTilesAtHome = new OpenLayers.Layer.OSM.Osmarender("Osmarender");
    map.addLayer(layerTilesAtHome);
    var styleMap = new OpenLayers.StyleMap({strokeWidth: 3});
    layers[ "connection" ] = {strokeColor: '#830531', strokeDashstyle: 'dashdot', strokeWidth: 2}
    styleMap.addUniqueValueRules("default", "layer", layers);
    routeLayer = new OpenLayers.Layer.Vector("Route", {
                    styleMap: styleMap
                    });
    map.addLayer(routeLayer);
    bikeLayer = new OpenLayers.Layer.Text( "Bike Stations",{
                    location:"./bikes",
                    projection: map.displayProjection
                    });
    map.addLayer(layerMarkers);
    map.addLayer(bikeLayer);
    bikeLayer.setZIndex(730);
    if( ! map.getCenter() ){
        var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
        map.setCenter (lonLat, zoom);
    }
    controlDrag = new OpenLayers.Control.DragFeature(layerMarkers, {
            'onStart': function(feature) {
                feature.style.graphicOpacity = 0.5;
            },
            'onComplete': function(feature) {
                lonlat = new OpenLayers.LonLat(feature.geometry.x,feature.geometry.y);
                ll = MToLonLat(lonlat);
                feature.style.graphicOpacity = 1.0;
                nodes['fmouse_'+feature.data]=true;
                reverseGeocoding(lonlat,feature.data);
                setMark(lonlat,feature.data);
            }
    });
    map.addControl(controlDrag);
    controlDrag.activate();
    if( fromHash ) {
        var tmpStart = new OpenLayers.LonLat(lonStart, latStart);
        var tmpDest = new OpenLayers.LonLat(lonDest, latDest);
        nodes['start'] = {
            'lon': lonStart,
            'lat': latStart
        };
        nodes['dest'] = {
            'lon': lonDest,
            'lat': latDest
        };
        setMark(tmpStart,"start");
        setMark(tmpDest,"dest");
        compute();
    }
    else {
        s = {
            'lon': lonStart,
            'lat': latStart
        }
        d = {
            'lon': lonDest,
            'lat': latDest
        }
        centerToMap(s,d)
    }
    $("#map").contextMenu({
        menu: 'myMenu'
    },
        function(action, el, pos) {
            var tmp = {
                'x': pos.x,
                    'y': pos.y
            };          
            handleClick( tmp, action);
    });
    showDescription( layers );  
} //End of function init()

function hasChanged(mark) {
    if( mark == "start" ) {
        var tmp = document.getElementById('startAdr').value;
        if( tmp.length == cacheStart.length ) {
            if( tmp == cacheStart)
                return false;
            else
                return true;
        }
        else
            return true;
    }
    else if( mark == "dest" ) {
        var tmp = document.getElementById('endAdr').value;
        if( tmp.length == cacheDest.length ) {
            if( tmp == cachDest)
                return false;
            else
                return true;
        }
        else
            return true;
    }
}

function clearPath() {
    $("#routing_description").html("");
    $("#path_costs").html("");
    $("#hash_url").html("");
    routeLayer.destroyFeatures();   
}

function clearArrow(mark) {
    nodes[mark] = null;
    layerMarkers.removeFeatures(node_markers[mark]);
    node_markers[mark].destroy(); 
    node_markers[mark] = null;
}

function geocoding(str,mark) {
    var url = "geo";
    $.getJSON(url, {q: str},
        function(data) {
                if( data.cord_error != '' ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html("<span class=\"errorOrange\">Nothing found. Please type again.</span>");
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html("<span class=\"errorOrange\">Nothing found. Please type again.</span>");
                        clearPath();
                        clearArrow(mark);
                    }               
                }
                else if( !data.is_covered ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html("<span class=\"errorOrange\">Not in covered zone.</span>");
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html("<span class=\"errorOrange\">Not in covered zone.</span>");
                        clearPath();
                        clearArrow(mark);
                    }               
                }               
                else if( data.node_error != '' ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html(
                            "<span class=\"errorOrange\">Can not find a node. Retry with a different address.</span>"
                        );
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html(
                            "<span class=\"errorOrange\">Can not find a node. Retry with a different address.</span>"
                        );
                        clearPath();
                        clearArrow(mark);
                    }               
                }
                else {              
                    var cord = new OpenLayers.LonLat(data.lon, data.lat);
                    if( mark == "start" )
                        document.getElementById('startAdr').value = data.display_name;
                    else if( mark == "dest" )
                        document.getElementById('endAdr').value = data.display_name;
                    if( hasChanged(mark) ) {    
                        nodes['fmouse_'+mark] = false;      
                        nodes[mark] = {
                            'lon': data.lon,
                            'lat': data.lat
                        };                      
                        setMark(cord,mark);
                        if( areBothMarked() ) { 
                            if( !nodes['fmouse_start'] || !nodes['fmouse_dest'] ) {
                                centerToMap(nodes['start'],nodes['dest']);
                            }
                            compute();
                        }
                    }
                }
        }
    );
}

function validateAddresses(f) {
    document.getElementById('startAdr').style.backgroundColor = "#ffffff";
    document.getElementById('endAdr').style.backgroundColor = "#ffffff";
    if($("#startAdr").val() == '') {
        document.getElementById('startAdr').focus();
        document.getElementById('startAdr').style.backgroundColor = "#f64444";
        $("#formError_start").html("<span class=\"errorRed\">Enter a starting address</span>");
        clearPath();
        clearArrow("start");
    }
    else {
        document.getElementById('startAdr').style.backgroundColor = "#ffffff";
        $("#formError_start").html("");
    }
    if($("#endAdr").val() == '') {
        document.getElementById('endAdr').focus();
        document.getElementById('endAdr').style.backgroundColor = "#f64444";
        $("#formError_dest").html("<span class=\"errorRed\">Enter a destination</span>");
        clearPath();
        clearArrow("dest");
    }
    else {
        document.getElementById('endAdr').style.backgroundColor = "#ffffff";
        $("#formError_dest").html("");
    }
    if( ($("#startAdr").val() != '') && ($("#endAdr").val() != '') ) {
        document.getElementById('startAdr').style.backgroundColor = "#ffffff";
        document.getElementById('endAdr').style.backgroundColor = "#ffffff";
        geocoding( $("#startAdr").val(), "start" );
        geocoding( $("#endAdr").val(), "dest" );
    }
}

function reverseLocations() {
    var tmp = document.getElementById("startAdr").value;
    document.getElementById("startAdr").value = document.getElementById("endAdr").value;
    document.getElementById("endAdr").value = tmp;
    return true;
}

function reverseGeocoding(lonlat,mark) {
    var url = "revgeo";
    $.getJSON(url, {lon: lonlat.lon, lat:lonlat.lat},
        function(data) {
            if( data.cord_error != '' ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html("<span class=\"errorOrange\">Nothing found. Please type again.</span>");
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html("<span class=\"errorOrange\">Nothing found. Please type again.</span>");
                        clearPath();
                        clearArrow(mark);
                    }               
                }
                else if( !data.is_covered ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html("<span class=\"errorOrange\">Not in covered zone.</span>");
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html("<span class=\"errorOrange\">Not in covered zone.</span>");
                        clearPath();
                        clearArrow(mark);
                    }               
                }               
                else if( data.node_error != '' ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html(
                            "<span class=\"errorOrange\">Can not find a node. Retry with a different address.</span>"
                        );
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html(
                            "<span class=\"errorOrange\">Can not find a node. Retry with a different address.</span>"
                        );
                        clearPath();
                        clearArrow(mark);
                    }               
                }
                else {              
                    var cord = new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
                    if( mark == "start" ) {
                        document.getElementById('startAdr').value = data.display_name;
                        document.getElementById('startAdr').style.backgroundColor = "#ffffff";
                        $("#formError_start").html("");
                    }
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').value = data.display_name;
                        document.getElementById('endAdr').style.backgroundColor = "#ffffff";
                        $("#formError_dest").html("");
                    }
                    nodes[mark] = {
                        'lon': lonlat.lon,
                        'lat': lonlat.lat
                    };
                    setMark(cord,mark);                 
                    
                     if( areBothMarked() ) { 
                        compute();
                    }
                }
        });
}

function centerToMap(start,dest) {
    var left,right,top,bottom;  
    var tmps = new OpenLayers.LonLat(start.lon, start.lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
    var tmpd = new OpenLayers.LonLat(dest.lon, dest.lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
    if( tmps.lon > tmpd.lon) {
        right = tmps.lon;
        left = tmpd.lon;
    }       
    else {
        left = tmps.lon;
        right = tmpd.lon;
    }   
    if( tmps.lat > tmpd.lat) {
        top = tmps.lat;
        bottom = tmpd.lat;  
    }   
    else {
        bottom = tmps.lat;
        top = tmpd.lat;
    }
    map.zoomToExtent( new OpenLayers.Bounds( left, bottom, right, top ) );
}


function LonLatToPoint(ll) {
    return new OpenLayers.Geometry.Point(ll.lon,ll.lat);
}

function LonLatToM(ll) {
    return ll.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
}

function MToLonLat(ll) {
    return ll.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
}

function showDescription( l ) {
    //$("#routing_description").html("<table><caption><span>Routing description:</span></caption><thread><tr><td><span class=\"tinyText\">Transport</span></td><td><span class=\"tinyText\">Color<span class=\"tinyText\"></td></tr></thread><tbody>");
    $("#routing_description").html("<caption><span>Routing description:</span></caption><thread><tr><td><span class=\"tinyText\">Transport</span></td><td><span class=\"tinyText\">Color<span class=\"tinyText\"></td></tr></thread><tbody>");
    $.each( l, function(key, val){
        $("#routing_description").append("<tr><td><span class=\"tinyText\">" + key + "</span></td><td><hr width=\"60\" size=\"4\" color=\"" + val.strokeColor + "\"></td></tr>");
    });
    $("#routing_description").append("</tbody>");
    
}


import unittest
from unittest.mock import call, patch, Mock, AsyncMock

from datetime import datetime

from bot.cogs import subject
from tests.mocks.discord import MockBot, MockContext, MockGuild, MockTextChannel, MockCategoryChannel, MockMessage, MockEmoji
from tests.mocks.database import MockDatabase, MockSubjectRecord, MockSubjectRegisteredRecord, MockSubjectServerRecord

class SubjectTests(unittest.IsolatedAsyncioTestCase):
    async def test_subject_add_less_then_ten_codes(self):
        bot = MockBot()
        cog = subject.Subject(bot=bot)

        for i in range(10 + 1):
            cog.add_subject = AsyncMock(return_value=None)

            ctx = MockContext()
            subjects = [f"IB{xxx:0>3}" for xxx in range(i)]
            await cog.add.callback(cog, ctx, *subjects)

            cog.add_subject.assert_has_calls([
                call(ctx, code) for code in subjects
            ])

    async def test_subject_add_too_many_codes(self):
        bot = MockBot()
        cog = subject.Subject(bot=bot)

        for i in range(11, 20):
            cog.add_subject = AsyncMock(return_value=None)

            ctx = AsyncMock()
            subjects = [f"IB{xxx:0>3}" for xxx in range(i)]
            await cog.add.callback(cog, ctx, *subjects)

            self.assertEqual(ctx.send_embed.call_count, 1)
            self.assertEqual(cog.add_subject.call_count, 0)

    async def test_in_subject_channel_wrong_room(self):
        bot = MockBot()
        cog = subject.Subject(bot=bot)

        #
        guild_config = Mock()
        guild_config.id = 8
        guild_config.channels.subject_registration = 10

        config = Mock()
        config.guilds = [guild_config]
        #

        channel1 = MockTextChannel(id=10)
        channel2 = MockTextChannel(id=11)
        guild = MockGuild(id=8, text_channels=[channel1, channel2])
        ctx = MockContext(guild=guild, channel=channel2)

        with patch('bot.cogs.subject.Config', config):
            await cog._in_subject_channel(ctx)

        ctx.send_error.assert_called_once()

    async def test_in_subject_channel_non_existing_channel(self):
        bot = MockBot()
        cog = subject.Subject(bot=bot)

        #
        guild_config = Mock()
        guild_config.id = 8
        guild_config.channels.subject_registration = 10

        config = Mock()
        config.guilds = [guild_config]
        #

        guild = MockGuild(id=8, text_channels=[])
        ctx = MockContext(guild=guild)

        with patch('bot.cogs.subject.Config', config):
            await cog._in_subject_channel(ctx)

        ctx.send_error.assert_called_once()

    async def test_pattern_to_faculty_code(self):
        bot = MockBot()
        cog = subject.Subject(bot=bot)

        self.assertEqual(cog.pattern_to_faculty_code("FI:IB000"), ("FI", "IB000"))
        self.assertEqual(cog.pattern_to_faculty_code("IB000"), ("FI", "IB000"))
        self.assertEqual(cog.pattern_to_faculty_code("FF:IB000"), ("FF", "IB000"))
        self.assertEqual(cog.pattern_to_faculty_code("FI:IB0%"), ("FI", "IB0%"))
        self.assertEqual(cog.pattern_to_faculty_code("a:a:a:a"), ("a", "a:a:a"))

    async def test_subject_remove_less_then_ten_codes(self):
        bot = MockBot()
        cog = subject.Subject(bot=bot)

        for i in range(10 + 1):
            cog.remove_subject = AsyncMock(return_value=None)

            ctx = MockContext()
            subjects = [f"IB{xxx:0>3}" for xxx in range(i)]
            await cog.remove.callback(cog, ctx, *subjects)

            cog.remove_subject.assert_has_calls([
                call(ctx, code) for code in subjects
            ])

    async def test_subject_remove_too_many_codes(self):
        bot = MockBot()
        cog = subject.Subject(bot=bot)

        for i in range(11, 20):
            cog.remove_subject = AsyncMock(return_value=None)

            ctx = AsyncMock()
            subjects = [f"IB{xxx:0>3}" for xxx in range(i)]
            await cog.remove.callback(cog, ctx, *subjects)

            self.assertEqual(ctx.send_embed.call_count, 1)
            self.assertEqual(cog.remove_subject.call_count, 0)

    async def test_find_subject_not_found(self):
        bot = MockBot()
        bot.db = MockDatabase()
        cog = subject.Subject(bot=bot)

        subjects = []
        bot.db.subjects.find.return_value = subjects

        found_subject = await cog.find_subject(faculty="FI", code="IB002")
        self.assertEqual(found_subject, None)

    async def test_find_subject_found(self):
        bot = MockBot()
        bot.db = MockDatabase()
        cog = subject.Subject(bot=bot)

        subjects = [
            MockSubjectRecord(faculty="FI", code="IB000", name="MZI", url="muni/fi/ib/000", terms=["jaro 2020"], created_at=datetime(2020, 10, 11)),
        ]
        bot.db.subjects.find.return_value = subjects

        found_subject = await cog.find_subject(faculty="FI", code="IB000")
        self.assertEqual(found_subject, subjects[0])

    async def test_try_to_get_existing_channel(self):
        bot = MockBot()
        bot.db.subjects.set_channel = AsyncMock(return_value=None)
        cog = subject.Subject(bot=bot)

        categories = [
            MockCategoryChannel(id=3, name="IBXXX", position=0),
            MockCategoryChannel(id=5, name="PVXXX", position=1)
        ]
        text_channels = [
            MockTextChannel(id=2, name="IB000", category=categories[0], position=0),
            MockTextChannel(id=4, name="IB002", category=categories[0], position=1),
            MockTextChannel(id=6, name="PV102", category=categories[1], position=0)
        ]
        guild = MockGuild(id=1, text_channels=text_channels, categories=categories)
        ctx = MockContext(guild=guild)

        subject_record = MockSubjectRecord(faculty="FI", code="IB000", name="MZI Of Ab", url="muni/fi/ib/000", terms=["jaro 2020"], created_at=datetime(2020, 10, 11))
        actual = await cog.try_to_get_existing_channel(ctx, subject_record)
        self.assertEqual(actual, text_channels[0])

    async def test_try_to_get_existing_channel_exactly(self):
        bot = MockBot()
        bot.db.subjects.set_channel = AsyncMock(return_value=None)
        cog = subject.Subject(bot=bot)

        categories = [
            MockCategoryChannel(id=3, name="IBXXX", position=0),
            MockCategoryChannel(id=5, name="PVXXX", position=1)
        ]
        text_channels = [
            MockTextChannel(id=1, name="IB000cv", category=categories[0], position=0),
            MockTextChannel(id=2, name="IB000", category=categories[0], position=0),
            MockTextChannel(id=4, name="IB002", category=categories[0], position=1),
            MockTextChannel(id=6, name="PV102", category=categories[1], position=0)
        ]
        guild = MockGuild(id=1, text_channels=text_channels, categories=categories)
        ctx = MockContext(guild=guild)

        subject_record = MockSubjectRecord(faculty="FI", code="IB000", name="MZI Of Ab", url="muni/fi/ib/000", terms=["jaro 2020"], created_at=datetime(2020, 10, 11))
        actual = await cog.try_to_get_existing_channel(ctx, subject_record)
        self.assertEqual(actual, text_channels[1])


    async def test_reorder_in_order(self):
        bot = MockBot()
        cog = subject.Subject(bot=bot)

        cog.is_subject_channel = AsyncMock(return_value=True)

        def side_effect(guild_id, code, faculty):
            return MockSubjectRecord(faculty, code, "", "", [], datetime.now(), None, None)

        bot.db.subjects.get_category = AsyncMock()
        bot.db.subjects.get_category.side_effect = side_effect

        categories = [
            MockCategoryChannel(id=3, name="IBXXX", position=0),
            MockCategoryChannel(id=5, name="PVXXX", position=1)
        ]
        text_channels = [
            MockTextChannel(id=2, name="IB000", category=categories[0], position=0),
            MockTextChannel(id=4, name="IB002", category=categories[0], position=1),
            MockTextChannel(id=6, name="PV102", category=categories[1], position=0)
        ]
        guild = MockGuild(id=1, text_channels=text_channels, categories=categories)

        ctx = MockContext(guild=guild)
        await cog.reorder.callback(cog, ctx)

        guild.create_category.assert_not_called()
        for channel in text_channels:
            channel.edit.assert_not_called()
        for category in categories:
            category.delete.assert_not_called()

    async def test_check_if_engough_users_signed_not_enough_users(self):
        bot = MockBot()
        bot.db.subjects.find_registered = AsyncMock(return_value=MockSubjectRegisteredRecord(faculty="FI", code="IB000", guild_id=8, member_ids=[11, 12, 13]))
        bot.db.subjects.find_serverinfo = AsyncMock(return_value=MockSubjectServerRecord(faculty="FI", code="IB000", guild_id=8, category_id=9, channel_id=10, voice_channel_id=None))

        #
        guild = Mock()
        guild.id = 8
        guild.NEEDED_REACTIONS = 10

        config = Mock()
        config.guilds = [guild]
        #

        guild_id = 8
        _subject = MockSubjectRecord(faculty="FI", code="IB000", name="MZI", url="muni/fi/ib/000", terms=["jaro 2020"], created_at=datetime(2020, 10, 11))

        cog = subject.Subject(bot=bot)
        with patch('bot.cogs.subject.Config', config):
            actual = await cog.check_if_engough_users_signed(guild_id, _subject)
            self.assertFalse(actual)

    async def test_check_if_engough_users_signed_enough_users(self):
        bot = MockBot()
        bot.db.subjects.find_registered = AsyncMock(return_value=MockSubjectRegisteredRecord(faculty="FI", code="IB000", guild_id=8, member_ids=[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]))
        bot.db.subjects.find_serverinfo = AsyncMock(return_value=MockSubjectServerRecord(faculty="FI", code="IB000", guild_id=8, category_id=9, channel_id=10, voice_channel_id=None))

        #
        guild = Mock()
        guild.id = 8
        guild.NEEDED_REACTIONS = 10

        config = Mock()
        config.guilds = [guild]
        #

        guild_id = 8
        _subject = MockSubjectRecord(faculty="FI", code="IB000", name="MZI", url="muni/fi/ib/000", terms=["jaro 2020"], created_at=datetime(2020, 10, 11))

        cog = subject.Subject(bot=bot)
        with patch('bot.cogs.subject.Config', config):
            actual = await cog.check_if_engough_users_signed(guild_id, _subject)
            self.assertTrue(actual)

    async def test_subject_to_channel_name(self):
        bot = MockBot()
        cog = subject.Subject(bot=bot)

        ctx = MockContext()
        ctx.channel_name.side_effect = lambda name: name

        _subject = MockSubjectRecord(faculty="FI", code="IB000", name="MZI Of Ab", url="muni/fi/ib/000", terms=["jaro 2020"], created_at=datetime(2020, 10, 11))
        actual = cog.subject_to_channel_name(ctx, _subject)
        self.assertEqual(actual, "IB000 MZI Of Ab")

        _subject = MockSubjectRecord(faculty="FF", code="ABCDE", name="One of Two", url="muni/fi/ib/000", terms=["jaro 2020"], created_at=datetime(2020, 10, 11))
        actual = cog.subject_to_channel_name(ctx, _subject)
        self.assertEqual(actual, "FF:ABCDE One of Two")

    async def test_group_by_term(self):
        bot = MockBot()
        cog = subject.Subject(bot=bot)

        subjects = [
            MockSubjectRecord(faculty="FI", code="IB000", name="MZI Of Ab", url="muni/fi/ib/000", terms=["jaro 2020"], created_at=datetime(2020, 10, 11)),
            MockSubjectRecord(faculty="FI", code="IB000", name="MZI Of Ab", url="muni/fi/ib/000", terms=["podzim 2020"], created_at=datetime(2020, 10, 11)),
            MockSubjectRecord(faculty="FI", code="IB015", name="GHC Of XX", url="muni/fi/ib/015", terms=["jaro 2021"], created_at=datetime(2020, 10, 11)),
            MockSubjectRecord(faculty="FI", code="IB123", name="123XY", url="muni/fi/ib/123", terms=["podzim 2020"], created_at=datetime(2020, 10, 11)),
            MockSubjectRecord(faculty="FI", code="PV111", name="MZI Of Ab", url="muni/fi/pb/111", terms=["podzim 2020"], created_at=datetime(2020, 10, 11)),
            MockSubjectRecord(faculty="FF", code="ABCDE", name="MZI Of Ab", url="muni/ff/ab/cde", terms=["podzim 2020"], created_at=datetime(2020, 10, 11))
        ]

        expected = {
            'jaro 2020': [
                MockSubjectRecord(faculty="FI", code="IB000", name="MZI Of Ab", url="muni/fi/ib/000", terms=["jaro 2020"], created_at=datetime(2020, 10, 11))
            ],
            'podzim 2020': [
                MockSubjectRecord(faculty="FI", code="IB000", name="MZI Of Ab", url="muni/fi/ib/000", terms=["podzim 2020"], created_at=datetime(2020, 10, 11)),
                MockSubjectRecord(faculty="FI", code="IB123", name="123XY", url="muni/fi/ib/123", terms=["podzim 2020"], created_at=datetime(2020, 10, 11)),
                MockSubjectRecord(faculty="FI", code="PV111", name="MZI Of Ab", url="muni/fi/pb/111", terms=["podzim 2020"], created_at=datetime(2020, 10, 11)),
                MockSubjectRecord(faculty="FF", code="ABCDE", name="MZI Of Ab", url="muni/ff/ab/cde", terms=["podzim 2020"], created_at=datetime(2020, 10, 11))
            ],
            'jaro 2021': [
                MockSubjectRecord(faculty="FI", code="IB015", name="GHC Of XX", url="muni/fi/ib/015", terms=["jaro 2021"], created_at=datetime(2020, 10, 11)),
            ]
        }

        actual = cog.group_by_term(subjects)
        self.assertDictEqual(expected, actual)


## AR Query Matchers
![badge](https://action-badges.now.sh/gusto/ar-query-matchers?action=Run%20Tests)

These RSpec matchers allow guarding against N+1 queries by specifying
exactly how many queries you expect each of your ActiveRecord models to perform.

They could also help reasoning about which database interactions are happening inside a block of code.

This pattern is a based on how Rails itself tests queries:
https://github.com/rails/rails/blob/ac2bc00482c1cf47a57477edb6ab1426a3ba593c/activerecord/test/cases/test_case.rb#L104-L141

Currently, this gem only supports RSpec matchers, but the code is meant to be adapted to support other testing frameworks.
If you'd like to pick that up, please have a look at: https://github.com/Gusto/ar-query-matchers/issues/13

### Usage
Include it in your Gemfile:
```ruby
group :test do
  gem 'ar-query-matchers', '~> 0.2.0', require: false
end
```

Start using it: 
```ruby
require 'ar_query_matchers'

RSpec.describe Employee do
  it 'creating an employee creates exactly one record' do
    expect { 
      Employee.create!(first_name: 'John', last_name: 'Doe') 
    }.to only_create_models('Employee' => '1')
  end
end
```

### Matchers
This gem defines a few categories of matchers:
- **Create**: Which models are created during a block
- **Load**: Which models are fetched during a block
- **Update**: Which models are updated during a block

Each matcher category includes 3 assertions, for example, for the Load category, you could use the following assertions:
- **only_load_models**: Strict assertion, not other query is allowed.
- **not_load_models**: No models are allowed to be loaded.
- **load_models**: Inclusion, other models are allowed to be loaded if not specified in the assertion.


**For example:** 

The following spec will pass only if there are exactly 4 SQL SELECTs that
load User records (and 1 for Address, 1 for Payroll) _and_ no other models
perform any SELECT queries.
```ruby
expect { some_code() }.to only_load_models(
  'User' => 4,
  'Address' => 1,
  'Payroll' => 1,
)
```

The following spec will pass only if there are no select queries.
```ruby
expect { some_code() }.to not_load_models
```

The following spec will pass only if there are exactly 4 SQL SELECTs that
load User records (and 1 for Address, 1 for Payroll).
```ruby
expect { some_code() }.to load_models(
  'User' => 4,
  'Address' => 1,
  'Payroll' => 1,
)
```

This will show some helpful output on failure:

```
Expected to run queries to load models exactly {"Address"=>1, "Payroll"=>1, "User"=>4} queries, got {"Address"=>1, "Payroll"=>1, "User"=>5}
     Expectations that differed:
         User - expected: 4, got: 5 (+1)

     Source lines:
     User loaded from:
         4 call: /spec/controllers/employees_controller_spec.rb:128:in 'block (4 levels) in <top (required)>'
         1 call: /app/models/user.rb:299
```

### High Level Design:
The RSpec matcher delegates to "query counters", asserts expectations and formats error messages to provide meaningful failures.  
The matchers are pretty simple, and delegate instrumentation into specialized QueryCounter classes.
The QueryCounters are different classes which instrument a ruby block by listening on all sql, parsing the queries and returning structured data describing the interactions.

```                
  ┌────────────────────────────────────────────────────────────────────────────────────────┐
┌─┤expect { Employee.create!() }.to only_create_models('Employee' => 1)                    │
│ └────────────────────────────────────────────────────────────────────────────────────────┘
└▶┌────────────────────────────────────────────────────────────────────────────────────────┐
┌─┤Queries::CreateCounter.instrument { Employee.create!() } => QueryStats                  │
│ └────────────────────────────────────────────────────────────────────────────────────────┘
└▶┌────────────────────────────────────────────────────────────────────────────────────────┐
  │QueryCounter.new(CreateQueryFilter.new).instrument { Employee.create!() } => QueryStats │
  └────────────────────────────────────────────────────────────────────────────────────────┘                                                                
```

For more information, see:
1. `ArQueryMatchers::Queries::QueryCounter`
2. `ArQueryMatchers::Queries::CreateCounter`
3. `ArQueryMatchers::Queries::LoadCounter`
4. `ArQueryMatchers::Queries::UpdateCounter`

### Known problems
- The Rails 4 `ActiveRecord::Base#pluck` method doesn't issue a
`Load` or `Exists` named query and therefore we don't capture the counts with
this tool. This may be fixed in Rails 5/6.

{-# LANGUAGE BangPatterns
           , DeriveDataTypeable
           , FlexibleContexts #-}
module Main where

import           Control.Applicative
import           Control.Arrow
import           Control.Concurrent
import           Control.Concurrent.STM
import           Control.Monad
import           Control.Monad.Fix (fix)
import           Control.Monad.IO.Class (MonadIO, liftIO)
import           Data.Accessor
import           Data.Char ( toLower )
import           Data.Colour
import           Data.Colour.RGBSpace
import           Data.Colour.SRGB
import           Data.Colour.Names (white)
import qualified Data.Foldable as Fold
import           Data.IORef
import qualified Data.KDTree as KD
import qualified Data.List as List
import           Data.Map (Map)
import qualified Data.Map as Map
import           Data.Maybe (fromJust, isJust)
import qualified Data.Set as Set
import           Data.Typeable
import           Data.Word (Word16)
import qualified Data.Vector as B
import qualified Data.Vector.Generic as V
import qualified Data.Vector.Unboxed as U
import           Debug.Trace
import qualified Graphics.Rendering.Cairo as C
import qualified Graphics.Rendering.Cairo.Matrix as M
import           Graphics.Rendering.Chart as C
import           Graphics.Rendering.Chart.Grid as C
import           Graphics.UI.Gtk as G
import           Graphics.UI.Gtk.Glade
import           Mescaline.Application (AppT)
import qualified Mescaline.Application as App
import           Mescaline.ColourMap
import qualified Mescaline.Database as DB
import qualified Mescaline.Synth.Sampler.Model as Sampler
import qualified Mescaline.Synth.Sampler.Params as Sampler
import qualified Paths_mescaline_sts as Paths
import           Reactive.Banana hiding (filter)
import qualified Reactive.Banana as R
import           Reactive.Banana.EventSource
import qualified Reactive.Banana.Model as RM
import           Sound.OpenSoundControl (pauseThread, utcr)
import           Sound.SC3.Server.Monad
import           Sound.SC3.Server.Process.Monad
import           Statistics.KernelDensity (Points, epanechnikovPDF, fromPoints)
import           Statistics.Sample
import           System.FilePath
-- import           System.Glib.MainLoop

debugPrint :: Show a => String -> a -> IO ()
debugPrint tag a = putStrLn $ tag ++ " " ++ show a

data SoundFile = SoundFile { fileId :: DB.SourceFileId, file :: DB.SourceFile, marked :: Bool }
                 deriving (Show, Typeable)

type UnitMap = Map DB.UnitId (DB.Unit, Map DB.DescriptorId DB.Feature)

fileColour :: ColourMap DB.SourceFileId a -> DB.SourceFileId -> Colour a
fileColour m s = m Map.! s

colourToGdk :: (Floating a, Fractional a, RealFrac a) => Colour a -> Color
colourToGdk c = Color (r2w (channelRed rgb)) (r2w (channelGreen rgb)) (r2w (channelBlue rgb))
    where
        rgb = toRGBUsingSpace sRGBSpace c
        r2w r = truncate (r * fromIntegral (maxBound :: Word16))

data ScatterPlotAxis = ScatterPlotAxis {
    scatterPlotDescriptorId :: DB.DescriptorId
  , scatterPlotDescriptor :: DB.Descriptor
  , scatterPlotIndex :: Int
  } deriving (Show, Typeable)

scatterPlotAxisTitle :: ScatterPlotAxis -> String
scatterPlotAxisTitle x = descriptorShortName (scatterPlotDescriptor x) ++ " (" ++ show (scatterPlotIndex x) ++ ")"

scatterPlotAxisValue :: V.Vector v a => ScatterPlotAxis -> Map DB.DescriptorId (v a) -> a
scatterPlotAxisValue a m = (m Map.! scatterPlotDescriptorId a) V.! scatterPlotIndex a

data AxisType = XAxis | YAxis
                deriving (Eq, Show, Typeable)

data ScatterPlot = ScatterPlot {
    scatterPlotX :: ScatterPlotAxis
  , scatterPlotY :: ScatterPlotAxis
  } deriving (Show, Typeable)

data ScatterPlotLayer = ScatterPlotForeground | ScatterPlotBackground deriving (Show)

descriptorShortName :: DB.Descriptor -> String
descriptorShortName = takeFileName . DB.descriptorName

scatterPlotAxisMenu :: [(String, [ScatterPlotAxis])] -> (ScatterPlotAxis -> IO ()) -> IO Menu
scatterPlotAxisMenu descr action = do
    menu <- menuNew
    mapM_ (createMenuItem0 menu) descr
    widgetShowAll menu
    return menu
    where
        createMenuItem0 menu (name, axes) = do
            item <- menuItemNewWithLabel name
            menuShellAppend menu item
            case axes of
                [] -> return ()
                _ -> do
                    subMenu <- menuNew
                    menuItemSetSubmenu item subMenu
                    mapM_ (createMenuItem1 subMenu) axes
        createMenuItem1 menu axis = do
            item <- menuItemNewWithLabel (show (scatterPlotIndex axis))
            menuShellAppend menu item
            onActivateLeaf item (action axis)

getFeature :: DB.DescriptorId -> Map DB.DescriptorId DB.Feature -> DB.Feature
getFeature = flip (Map.!)

meanPlot :: AxisType -> ScatterPlotAxis -> FeatureStatMap -> Plot Double Double
meanPlot at a stats =
    let label = "mean"
        ls = line_color ^= opaque black $ defaultPlotLineStyle
        m = featureMean (scatterPlotAxisValue a stats)
        f = case at of
                XAxis -> vlinePlot
                YAxis -> hlinePlot
    in f label ls m

layoutScatterPlot :: ScatterPlotLayer -> ColourMap DB.SourceFileId Double -> PlotData -> ScatterPlot -> Layout1 Double Double
layoutScatterPlot layer colourMap plotData sp = layout
    where
        xAxis = scatterPlotX sp
        yAxis = scatterPlotY sp

        points sf =
            let colour = fileColour colourMap sf
                us = unitMap plotData Map.! sf
                value axis = flip (V.!) (scatterPlotIndex axis)
                           . DB.featureValue
                           . getFeature (scatterPlotDescriptorId axis)
                (xs, as) = List.foldl' (\(!vs, !as) (ui, (_, fs)) ->
                                        let p = (value xAxis fs, value yAxis fs)
                                        in (p:vs, if Set.member ui (activeUnits plotData) then p:as else as))
                                       ([], [])
                                       (Map.assocs us)
            in case layer of
                ScatterPlotForeground ->
                    [ -- Highlight active units
                      plot_points_style ^= hollowCircles 4 2 (opaque black)
                    $ plot_points_values ^= as
                    -- $ plot_points_title ^= "Test data"
                    $ defaultPlotPoints ]
                ScatterPlotBackground ->
                    [ -- Plot units
                      plot_points_style ^= filledCircles 2 (opaque colour)
                    $ plot_points_values ^= xs
                    -- $ plot_points_title ^= "Test data"
                    $ defaultPlotPoints ]

        bottomAxis = -- laxis_title ^= scatterPlotAxisTitle xAxis $
                     laxis_generate ^= axisFn plotData xAxis $
                     defaultLayoutAxis
        leftAxis = -- laxis_title ^= scatterPlotAxisTitle yAxis $
                   -- laxis_generate ^= scaledAxis yAxis $
                   laxis_generate ^= axisFn plotData yAxis $
                   defaultLayoutAxis

        background = case layer of
                        ScatterPlotForeground -> transparent
                        ScatterPlotBackground -> opaque white

        layout = -- layout1_title ^= "Units"
                 layout1_plots ^= concatMap (map (Left . toPlot) . points) (Set.toList (markedSoundFiles plotData))
                                    ++ [ Left $ meanPlot XAxis xAxis (featureStats plotData)
                                       , Left $ meanPlot YAxis yAxis (featureStats plotData) ]
               $ layout1_left_axis ^= leftAxis
               $ layout1_bottom_axis ^= bottomAxis
               $ layout1_background ^= solidFillStyle background
               $ defaultLayout1

layoutKDE :: ScatterPlotLayer
          -> ColourMap DB.SourceFileId Double
          -> Bool
          -> ScatterPlotAxis
          -> DB.SourceFileId
          -> PlotData
          -> Layout1 Double Double
layoutKDE layer colourMap flipped axis sf plotData = layout
    where
        descr = scatterPlotAxisTitle axis

        plots = [ Left $ mkPlot ScatterPlotBackground featureLineStyle (featureStats plotData)
                , Left $ mkPlot ScatterPlotBackground fileLineStyle (fileStats plotData Map.! sf)
                , Left $ meanPlot (if flipped then YAxis else XAxis) axis (featureStats plotData) ]

        layout = -- layout1_title ^= "Densities for \"" ++ descr ++ "\""
                 layout1_plots ^= plots
               $ layout1_bottom_axis ^= (if flipped then pdfAxis else featureAxis)
               $ layout1_left_axis ^= (if flipped then featureAxis else pdfAxis)
               $ defaultLayout1 :: Layout1 Double Double

        pdfAxis = laxis_title ^= "estimate of probability density"
                $ defaultLayoutAxis

        featureAxis = laxis_title ^= descr
                    $ laxis_generate ^= axisFn plotData axis
                    $ defaultLayoutAxis

        featureLineStyle = line_color ^= opaque black $ defaultPlotLineStyle

        fileLineStyle = line_color ^= opaque (fileColour colourMap sf) $ defaultPlotLineStyle

        flipValues xs = if flipped then map (\(a, b) -> (b, a)) xs else xs

        mkPlot layer lineStyle stats = pdfPlot
             where
                 (points, pdf) = featureHist (scatterPlotAxisValue axis stats)
                 xValues = V.toList (fromPoints points)
                 yValues = V.toList (V.map (/ V.sum pdf) pdf)
                 pdfPlot = -- This doesn't work as expected and produces slightly out-of-tune plots
                           case layer of
                            ScatterPlotForeground ->
                                toPlot $ PlotHidden xValues yValues
                            ScatterPlotBackground ->
                                toPlot $ plot_lines_values ^= map flipValues [ zip xValues yValues ]
                                       $ plot_lines_style ^= lineStyle
                                       $ defaultPlotLines

data PickType =
    ScatterPlotPick
  | XHistogramPick
  | YHistogramPick
  deriving (Eq, Show, Typeable)

data Pick = Pick {
    pickType :: PickType
  , pickData :: (Layout1Pick Double Double)
  } deriving (Show, Typeable)

mkChart :: Layout1 Double Double
        -> Layout1 Double Double
        -> Layout1 Double Double
        -> Renderable Pick
mkChart scatterPlot xHist yHist = mapMaybePickFn p r
    where
        r = renderLayout1Matrix scatterPlot [ [ Just yHist, Just scatterPlot ]
                                            , [ Nothing,    Just xHist       ] ]
        p ((0, 1), l) = Just (Pick ScatterPlotPick l)
        p ((1, 1), l) = Just (Pick XHistogramPick l)
        p ((0, 0), l) = Just (Pick YHistogramPick l)
        p _          = Nothing

type Histogram = (Points, U.Vector Double)

data FeatureStatistics = FeatureStatistics {
    featureMin  :: Double
  , featureMax  :: Double
  , featureMean :: Double
  , featureVar  :: Double
  , featureHist :: Histogram
  } deriving (Show)

type FeatureStatMap = Map DB.DescriptorId (B.Vector FeatureStatistics)

data PlotData = PlotData {
    soundFiles       :: [SoundFile]
  , markedSoundFiles :: Set.Set DB.SourceFileId
  , unitMap          :: Map DB.SourceFileId UnitMap
  , activeUnits      :: Set.Set DB.UnitId
  , fileStats        :: Map DB.SourceFileId FeatureStatMap
  , featureStats     :: FeatureStatMap
  } deriving (Show)

getSoundFile :: DB.SourceFileId -> PlotData -> SoundFile
getSoundFile sf = fromJust . List.find ((== sf) . fileId) . soundFiles

axisFn :: PlotData -> ScatterPlotAxis -> AxisFn Double
axisFn pd a = const $ autoAxis [fMin - fPad, fMax + fPad]
    where
        s = scatterPlotAxisValue a (featureStats pd)
        fMin = featureMin s
        fMax = featureMax s
        fPad = (fMax - fMin) * 5e-3

mkFeatureStats :: DB.DescriptorMap -> UnitMap -> Map DB.DescriptorId (B.Vector FeatureStatistics)
mkFeatureStats ds us = Map.mapWithKey (\di -> V.fromList . fmap (mkStats di) . indices) ds
    where
        indices d = [0..DB.descriptorDegree d - 1]
        mkStats di i = stats . V.fromList . map (flip (V.!) i . DB.featureValue . getFeature di . snd) . Map.elems $ us
        estimatePDF :: U.Vector Double -> Histogram
        estimatePDF = epanechnikovPDF 100
        stats :: U.Vector Double -> FeatureStatistics
        stats v = let (μ, σ) = meanVariance v
                  in FeatureStatistics {
                        featureMin  = V.minimum v
                      , featureMax  = V.maximum v
                      , featureMean = μ
                      , featureVar  = σ
                      , featureHist = estimatePDF v
                      }

mkPlotData :: DB.DescriptorMap -> DB.UnitMap -> [SoundFile] -> PlotData
mkPlotData ds us sfs = PlotData sfs ids um Set.empty fileStats featStats
    where
        mkFeatureMap = Map.fromList . map (\f -> (DB.featureDescriptor f, f))
        um = Map.foldrWithKey (\ui (u, fs) ->
                                Map.alter (Just . maybe (Map.singleton ui (u, mkFeatureMap fs))
                                                        (Map.insert ui (u, mkFeatureMap fs)))
                                          (DB.unitSourceFile u))
                              Map.empty us
        ids = Set.fromList (map fileId (filter marked sfs))
        featStats = mkFeatureStats ds (Map.fold Map.union Map.empty (Map.filterWithKey (\k _ -> Set.member k ids) um))
        fileStats = fmap (mkFeatureStats ds) um

setActiveUnits :: Set.Set DB.UnitId -> PlotData -> PlotData
setActiveUnits s p = p { activeUnits = s }

-- ====================================================================
-- kd-Tree for unit lookup

data UnitTree = UnitTree {
    units :: KD.Tree U.Vector (DB.UnitId, (DB.SourceFile, DB.Unit))
  , closestUnit :: U.Vector Double -> Maybe (DB.UnitId, (DB.SourceFile, DB.Unit))
  }

mkUnitTree :: ScatterPlot -> PlotData -> UnitTree
mkUnitTree sp pd = UnitTree
                    tree
                    (fmap (snd . fst) . flip (KD.closest dist) tree)
    where
        xAxis = scatterPlotX sp
        yAxis = scatterPlotY sp
        units :: [(DB.SourceFile, (DB.UnitId, (DB.Unit, Map DB.DescriptorId DB.Feature)))]
        units = concat
              $ fmap (\sf -> let f = file (getSoundFile sf pd) in map ((,)f) (Map.assocs (unitMap pd Map.! sf)))
              $ Set.toList (markedSoundFiles pd)
        coord fs = let fs' = fmap DB.featureValue fs
                       xValue = scatterPlotAxisValue xAxis fs'
                       yValue = scatterPlotAxisValue yAxis fs'
                   in V.fromList [ xValue, yValue ]
        point (sf, (ui, (u, fs))) = (coord fs, (ui, (sf, u)))
        tree :: KD.Tree U.Vector (DB.UnitId, (DB.SourceFile, DB.Unit))
        tree = KD.fromList (map point units)
        mkNorm axis = let s = scatterPlotAxisValue axis (featureStats pd)
                          m = featureMin s
                          r = featureMax s - m
                      in (negate m, if r == 0 then 1 else recip r)
        norm = (first V.fromList >>> second V.fromList)
                    (unzip [ mkNorm xAxis, mkNorm yAxis ])
        -- norm = (V.fromList [0, 0], V.fromList [1, 1])
        normalize = V.zipWith (*) (snd norm) . V.zipWith (+) (fst norm)
        dist a b = KD.sqrEuclidianDistance (normalize a) (normalize b)

-- | Pick function wrapper type.
newtype PickFunction a = PickFunction (PickFn a)
                         deriving (Typeable)

-- | A pick function that never returns a pick.
noPick :: PickFunction a
noPick = PickFunction (const Nothing)

pick :: PickFunction a -> (Double, Double) -> Maybe a
pick (PickFunction f) (x, y) = f (Point x y)

-- | A version opf updateCanvas that passes the pick function to a callback.
updateDrawingArea :: G.DrawingArea -> ((Int, Int) -> C.Render ()) -> IO ()
updateDrawingArea canvas render = do
    win <- G.widgetGetDrawWindow canvas
    size <- G.widgetGetSize canvas
    G.renderWithDrawable win (render size)

renderChart :: Renderable a -> (Int, Int) -> C.Render (PickFunction a)
renderChart r (w,h) = liftM PickFunction $ runCRender (render r (fromIntegral w, fromIntegral h)) bitmapEnv 

-- | User interface event abstraction.
data UIEvent =
    ButtonEvent {
        uiEventTime :: TimeStamp
      , uiEventCoordinates :: (Double,Double)
      , uiEventModifiers :: [Modifier]
      , uiEventButton :: Int
      }
  | MotionEvent {
        uiEventTime :: TimeStamp
      , uiEventCoordinates :: (Double,Double)
      , uiEventModifiers :: [Modifier]
      }
    deriving (Show, Typeable)

hasModifiers :: [Modifier] -> UIEvent -> Bool
hasModifiers ms = (== ms) . uiEventModifiers

hasButton :: Int -> UIEvent -> Bool
hasButton b = (== b) . uiEventButton

satisfies :: [(a -> Bool)] -> a -> Bool
satisfies ps a = all ($a) ps

fromSignal :: Typeable a => self -> Signal self handler -> ((a -> IO ()) -> handler) -> Prepare (Event a)
fromSignal self signal handler = fromAddHandler (void . on self signal . handler)

fromEvent :: (WidgetClass self, Typeable a) => self -> Signal self (EventM t Bool) -> EventM t (a, Bool) -> Prepare (Event a)
fromEvent self signal handler = fromAddHandler $ void . on self signal . \action -> do { (a, b) <- handler ; liftIO (action a) ; return b }

fromEvent_ :: (WidgetClass self, Typeable a) => self -> Signal self (EventM t Bool) -> EventM t a -> Bool -> Prepare (Event a)
fromEvent_ self signal handler override = fromEvent self signal (fmap (flip (,) override) handler)

buttonEventHandler :: EventM EButton UIEvent
buttonEventHandler = ButtonEvent <$> eventTime <*> eventCoordinates <*> eventModifier <*> liftM fromEnum eventButton

buttonPress :: (WidgetClass self) => self -> Bool -> Prepare (Event UIEvent)
buttonPress self = fromEvent_ self buttonPressEvent buttonEventHandler

buttonRelease :: (WidgetClass self) => self -> Bool -> Prepare (Event UIEvent)
buttonRelease self = fromEvent_ self buttonReleaseEvent buttonEventHandler

motionEventHandler :: EventM EMotion UIEvent
motionEventHandler = MotionEvent <$> eventTime <*> eventCoordinates <*> eventModifier

motion :: (WidgetClass self) => self -> Bool -> Prepare (Event UIEvent)
motion self = fromEvent_ self motionNotifyEvent motionEventHandler

resizeEvent :: (WidgetClass self) => self -> Bool -> Prepare (Event (Int, Int))
resizeEvent self = fromEvent_ self configureEvent eventSize

-- buttonMotion :: (WidgetClass self) => Int -> [Modifier] -> self -> Prepare (Behavior (Maybe (Double, Double)))
-- buttonMotion b ms self = do
--     p <- liftM (R.filter f) $ buttonPress self
--     m <-                      motion self
--     r <- liftM (R.filter f) $ buttonRelease self
--     stepper Nothing ((Just . uiEventCoordinates) <$> (p `union` m) `union` Nothing <$ r)
--     where f = satisfies [hasButton b, hasModifiers ms]

defer :: Typeable a => Priority -> Event a -> Prepare (Event a)
defer prio e = do
    src <- liftIO newEventSource
    reactimate $ (\a -> idleAdd (fire src a >> return False) prio >> return ()) <$> e
    fromEventSource src

newtype UnitIdT = UnitIdT { unUnitIdT :: DB.UnitId } deriving (Show, Typeable)

data BackgroundSurface = BackgroundSurface {
    backgroundSurfaceSize :: (Int,Int)
  , backgroundSurface :: C.Surface
  } deriving (Typeable)

mkBackgroundSurface :: MonadIO m => Int -> Int -> m BackgroundSurface
mkBackgroundSurface w h = liftIO (liftM (BackgroundSurface (w,h)) (C.createImageSurface C.FormatRGB24 w h))

newColumn :: ( CellRendererClass cell
             , TreeModelClass (model row)
             , TypedTreeModelClass model ) =>
             model row
          -> String
          -> IO cell
          -> (row -> [AttrOp cell])
          -> IO (TreeViewColumn, cell)
newColumn model label newRenderer attrs = do
    col <- treeViewColumnNew
    treeViewColumnSetTitle col label
    renderer <- newRenderer
    cellLayoutPackStart col renderer True
    cellLayoutSetAttributes col renderer model attrs
    return (col, renderer)

appMain :: AppT IO ()
appMain = do
    [gladeFile, dbFile] <- App.getArgs
    (descriptors, (sfs, us)) <- DB.withDatabase dbFile $ do
        a <- DB.descriptorMap
        b <- DB.queryFeatures (const True) (Map.keys a)
        return (a, b)
    let colourMap = hsv (Map.keys sfs)
        scatterPlotAxes = map (\(di, d) -> (descriptorShortName d, map (ScatterPlotAxis di d) [0..DB.descriptorDegree d - 1]))
                              (Map.toList descriptors)
    liftIO $ do
        initGUI
        unsafeInitGUIForThreadedRTS

        Just xml <- xmlNew gladeFile
        win <- xmlGetWidget xml castToWindow "window"
        onDestroy win mainQuit

        -- create a new list model
        model <- listStoreNew $ fmap (\(si, s) -> SoundFile si s True) $ Map.toList sfs
        view <- xmlGetWidget xml castToTreeView "soundFiles"
        treeViewSetModel view model

        treeViewSetHeadersVisible view True

        -- add a couple columns
        (col1, _) <- newColumn model "File" cellRendererTextNew $ \row -> [ cellText := takeFileName . DB.sourceFileUrl . file $ row
                                                                          , cellTextBackgroundColor := colourToGdk . fileColour colourMap . fileId $ row ]
        treeViewColumnSetResizable col1 True
        treeViewAppendColumn view col1

        (col4, renderer4) <- newColumn model "Active" cellRendererToggleNew $ \row -> [ cellToggleActive := marked row ]
        treeViewAppendColumn view col4

        (col2, _) <- newColumn model "Channels" cellRendererTextNew $ \row -> [ cellText := show . DB.sourceFileNumChannels . file $ row ]
        treeViewAppendColumn view col2

        (col3, _) <- newColumn model "Sample rate" cellRendererTextNew $ \row -> [ cellText := show . DB.sourceFileSampleRate . file $ row ]
        treeViewAppendColumn view col3

        (col5, _) <- newColumn model "Duration" cellRendererTextNew $ \row -> [ cellText := show . DB.sourceFileDuration . file $ row ]
        treeViewAppendColumn view col5

        -- Update the model when the toggle buttons are activated
        on renderer4 cellToggled $ \pathStr -> do
            let (i:_) = stringToTreePath pathStr
            val <- listStoreGetValue model i
            listStoreSetValue model i val { marked = not (marked val) }

        -- enable interactive search
        treeViewSetEnableSearch view True
        treeViewSetSearchEqualFunc view $ Just $ \str iter -> do
            (i:_) <- treeModelGetPath model iter
            row <- listStoreGetValue model i
            return (map toLower str `List.isPrefixOf` map toLower (DB.sourceFileUrl . file $ row))

        -- Drawing area for plots
        canvas <- xmlGetWidget xml castToDrawingArea "plot"
        set canvas [ widgetWidthRequest := 640, widgetHeightRequest := 640 ]
        widgetAddEvents canvas [Button1MotionMask]

        -- Synthesis processes
        synthInput <- newTChanIO
        forkIO $ withDefaultInternal $ do
            synth <- Sampler.new (Sampler.Options "" Nothing Nothing True)
            forever $ do
                (t, e, a1, a2) <- liftIO $ atomically $ readTChan synthInput
                fork $ a1 >> Sampler.playUnit synth t e >> a2

        playbackControl <- newTChanIO
        playbackData <- newTVarIO Nothing
        let setUnit x = atomically $ writeTVar playbackData x
            setPlayback b = atomically $ writeTChan playbackControl b
        forkIO $ forever $ do
            b <- atomically $ readTChan playbackControl
            when b $ do
                fix $ \loop -> do
                    e <- atomically ((Left <$> readTChan playbackControl) `orElse` (Right <$> readTVar playbackData))
                    case e of
                        Left b -> if b then loop else return ()
                        Right (Just ((sf, u), (whenStarting, whenFinished))) -> do
                            t <- utcr
                            let e = Sampler.defaultParams sf u
                            atomically $ writeTChan synthInput (t + 0.2, e, liftIO whenStarting, liftIO whenFinished)
                            pauseThread $ DB.unitDuration u
                            loop
                        _ -> loop

        -- Event sources
        pickFnSrc <- newEventSource
        scatterPlotSrc <- newEventSource
        unitPlayingSrc <- newEventSource
        bgSurfaceSrc <- newEventSource

        -- Set up event network
        prepareEvents $ do
            -- Soundfile list model events
            soundFiles <- fromSignal renderer4 cellToggled $ \a -> const (listStoreToList model >>= a)
            soundFiles0 <- liftIO $ listStoreToList model
            currentSoundFile <- fromSignal view cursorChanged $ \a -> do
                p <- treeViewGetCursor view
                case p of
                    ([i], _) -> listStoreGetValue model i >>= a
                    _ -> return ()
            -- Soundfile list model behaviors
            let selectedSoundFile = stepper (head soundFiles0) currentSoundFile
                selectedSoundFileId = fileId <$> selectedSoundFile
            -- Canvas events
            canvasResized <- resizeEvent canvas True
            bgChanged     <- fromEventSource bgSurfaceSrc
            bgSurface     <- liftM2 stepper
                                    (mkBackgroundSurface 0 0)
                                    (return bgChanged)
            expose        <- fromEvent_ canvas exposeEvent        (return ())        False
            buttonPress   <- fromEvent_ canvas buttonPressEvent   buttonEventHandler False
            buttonRelease <- fromEvent_ canvas buttonReleaseEvent buttonEventHandler False
            buttonMove    <- fromEvent_ canvas motionNotifyEvent  motionEventHandler False
            -- The picks from the plot area ((Double,Double) -> Maybe Pick)
            pickFunction <- liftM (fmap pick . stepper noPick) $ fromEventSource pickFnSrc
            let applyPickFunction es = ((\f e -> (e, f (uiEventCoordinates e))) <$> pickFunction) `apply` es
                -- Button press events occurring on the relevant axes
                buttonPressInAxisTitle = flip mapMaybe (applyPickFunction buttonPress)
                                            $ \(e, p) -> case p of
                                                Just (Pick XHistogramPick (L1P_BottomAxisTitle _)) -> Just (XAxis, e)
                                                Just (Pick YHistogramPick (L1P_LeftAxisTitle _))   -> Just (YAxis, e)
                                                _ -> Nothing
            scatterPlotAxis <- fromEventSource scatterPlotSrc
            unitPlaying <- fromEventSource unitPlayingSrc
            let plotData = setActiveUnits <$> activeUnits <*> (mkPlotData descriptors us <$> stepper soundFiles0 soundFiles)
                scatterPlotState = accumB (ScatterPlot (head . snd . head $ scatterPlotAxes) (head  . snd . head $ scatterPlotAxes))
                                          ((\(at, a) sp ->
                                            case at of
                                                XAxis -> sp { scatterPlotX = a }
                                                YAxis -> sp { scatterPlotY = a }) <$> scatterPlotAxis)
                -- Display
                canvasSize = stepper (0,0) canvasResized
                scatterPlotFG = layoutScatterPlot ScatterPlotForeground colourMap <$> plotData <*> scatterPlotState
                scatterPlotBG = layoutScatterPlot ScatterPlotBackground colourMap <$> plotData <*> scatterPlotState
                kdePlotX l = (layoutKDE l colourMap False . scatterPlotX) <$> scatterPlotState <*> selectedSoundFileId <*> plotData
                kdePlotY l = (layoutKDE l colourMap True  . scatterPlotY) <$> scatterPlotState <*> selectedSoundFileId <*> plotData
                chartFG = mkChart <$> scatterPlotFG <*> kdePlotX ScatterPlotForeground <*> kdePlotY ScatterPlotForeground
                chartBG = mkChart <$> scatterPlotBG <*> kdePlotX ScatterPlotBackground <*> kdePlotY ScatterPlotBackground
                render = (\fg bg _ -> do
                            C.setSourceSurface (backgroundSurface bg) 0 0
                            C.paint
                            void $ renderChart fg (backgroundSurfaceSize bg))
                            <$> chartFG
                            <*> bgSurface
                -- Synthesis
                unitTree = mkUnitTree <$> scatterPlotState <*> plotData
                filterPlayback = R.filter (satisfies [hasButton 1])
                playbackStart = filterPlayback buttonPress
                playbackPos = uiEventCoordinates <$> playbackStart `union` buttonMove
                playback = (True <$ playbackStart) `union` (False <$ filterPlayback buttonRelease)
                scatterPlotCoord = flip mapMaybe (pickFunction `apply` playbackPos) $ \p ->
                                    case p of
                                        Just (Pick ScatterPlotPick (L1P_PlotArea x y _)) -> Just (V.fromList [x, y])
                                        _ -> Nothing
                -- closest = filterMaybe $ ((\t v -> KD.closest KD.sqrEuclidianDistance v t) <$> unitTree)
                --                             `apply` scatterPlotCoord
                -- unit = (snd.fst) <$> closest
                unit = filterMaybe $ (closestUnit <$> unitTree) `apply` scatterPlotCoord
                activeUnits = accumB Set.empty (either (Set.insert . unUnitIdT) (Set.delete . unUnitIdT) <$> unitPlaying)
            -- Update background plot and feed back new background surface and pick function
            redrawBG <- defer priorityDefault $ ignore soundFiles `union` ignore currentSoundFile `union` ignore scatterPlotAxis `union` ignore canvasResized
            reactimate $ ((\chart (w,h) _ -> do
                            bg <- mkBackgroundSurface w h
                            pf <- C.renderWith (backgroundSurface bg) (renderChart chart (backgroundSurfaceSize bg))
                            fire bgSurfaceSrc bg
                            fire pickFnSrc pf) <$> chartBG <*> canvasSize)
                         `apply` redrawBG
            reactimate $ widgetQueueDraw canvas <$ (ignore bgChanged `union` ignore unitPlaying)
            reactimate $ (updateDrawingArea canvas <$> render) `apply_` expose
            -- Display the axis popup menu
            let popupAxisMenu a e = scatterPlotAxisMenu scatterPlotAxes (fire scatterPlotSrc . ((,) a)) >>=
                                        flip menuPopup (Just (toEnum (uiEventButton e), uiEventTime e))
            reactimate $ uncurry popupAxisMenu <$> (R.filter ((==3) . uiEventButton . snd) buttonPressInAxisTitle)
            -- Print the picks when a button is pressed in the plot area
            -- reactimate $ debugPrint "event" <$> (applyPickFunction (buttonPress `union` buttonMove))
            -- reactimate $ print <$> scatterPlotAxis
            -- reactimate $ print <$> activeUnits
            reactimate $ (\(ui, u) -> setUnit (Just (u, (fire unitPlayingSrc (Left (UnitIdT ui)), fire unitPlayingSrc (Right (UnitIdT ui)))))) <$> unit
            reactimate $ setPlayback <$> playback
            -- reactimate $ (const . print <$> activeUnits) `apply` unitPlaying
            -- (R.filter (\(e, p) -> (uiEventModifiers p == [Control]) . uiEventModifiers)) 
            -- reactimate $ ((\s1 s2 -> debugPrint "canvasResized" (s1, s2)) <$> canvasSize) `apply` canvasResized
            -- reactimate $ debugPrint "bgSurfaceE" . backgroundSurfaceSize <$> bgChanged
            -- reactimate $ debugPrint "closest" <$> closest
        widgetShowAll win
        mainGUI

-- type SynthProcess s = Time -> s -> (Synth, (Time, s))

main :: IO ()
main = App.runAppT appMain =<< App.mkApp "MescalineSTS" Paths.version Paths.getBinDir Paths.getDataDir App.defaultConfigFiles

-- Reactive combinators
merge :: FRP f => RM.Event f a -> RM.Event f b -> RM.Event f (Either a b)
merge a b = union (Left <$> a) (Right <$> b)

mapMaybe :: FRP f => (a -> Maybe b) -> RM.Event f a -> RM.Event f b
mapMaybe f = fmap fromJust . R.filter isJust . fmap f

filterMaybe :: FRP f => RM.Event f (Maybe a) -> RM.Event f a
filterMaybe = mapMaybe id

ignore :: Functor f => f a -> f ()
ignore = (<$) ()

unzipF :: Functor f => f (a, b) -> (f a, f b)
unzipF f = (fmap fst f, fmap snd f)

zipA :: Applicative f => f a -> f b -> f (a, b)
zipA a b = (,) <$> a <*> b

apply_ :: FRP f => RM.Behavior f a -> RM.Event f b -> RM.Event f a
apply_ b = apply (fmap const b)

import * as THREE from 'three';

const UNIFORMS = {
    // rgba
    u_g1_color: new THREE.Uniform(new THREE.Vector4(0, 0, 0, 1))
};

const CNC_LASER_VERT_SHADER = [
    'varying float v_g_code;',
    'attribute float a_g_code;',
    'void main(){',
    '    v_g_code = a_g_code;',
    '    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
    '}'
].join('');

const CNC_LASER_FRAG_SHADER = [
    'uniform vec4 u_g1_color;',
    'varying float v_g_code;',
    'void main(){',
    '    if(v_g_code == 0.0){',
    '        discard;',
    '    }',
    '    gl_FragColor = u_g1_color;',
    '}'
].join('');

const motionColor = {
    'G0': new THREE.Color(0xc8c8c8),
    'G1': new THREE.Color(0x000000),
    'unknown': new THREE.Color(0x000000)
};

class ToolPathRenderer {
    render(toolPath) {
        const { headerType, mode, movementMode, data } = toolPath;

        // now only support cnc&laser
        if (!['cnc', 'laser'].includes(headerType)) {
            return null;
        }

        if (headerType === 'laser') {
            if (mode === 'greyscale' && movementMode === 'greyscale-dot') {
                return this.parseToPoints(data);
            } else {
                return this.parseToLine(data);
            }
        } else {
            return this.parseToLine(data);
        }
    }

    parseToLine(data) {
        const positions = [];
        const gCodes = [];

        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if ((state.G === 1) && (newState.G === 0)) {
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(newState.G);
            }

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(state.G);
            }
        }

        const bufferGeometry = new THREE.BufferGeometry();
        const positionAttribute = new THREE.Float32BufferAttribute(positions, 3);
        const gCodeAttribute = new THREE.Float32BufferAttribute(gCodes, 1);
        bufferGeometry.addAttribute('position', positionAttribute);
        bufferGeometry.addAttribute('a_g_code', gCodeAttribute);
        const material = new THREE.ShaderMaterial({
            uniforms: UNIFORMS,
            vertexShader: CNC_LASER_VERT_SHADER,
            fragmentShader: CNC_LASER_FRAG_SHADER,
            side: THREE.DoubleSide,
            transparent: true,
            linewidth: 1
        });
        return new THREE.Line(bufferGeometry, material);
    }

    parseToPoints(data) {
        const geometry = new THREE.Geometry();
        const material = new THREE.PointsMaterial({
            size: 0.1,
            vertexColors: THREE.VertexColors,
            opacity: 0.9,
            transparent: true
        });
        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                geometry.vertices.push(new THREE.Vector3(state.X, state.Y, state.Z));
                if (state.G === 0) {
                    geometry.colors.push(motionColor.G0);
                } else if (state.G === 1) {
                    geometry.colors.push(motionColor.G1);
                } else {
                    geometry.colors.push(motionColor.unknown);
                }
            }
        }
        return new THREE.Points(geometry, material);
    }
}

export default ToolPathRenderer;

package reflect

import (
	"math/rand"
	"reflect"

	randplus "github.com/cheetah-fun-gs/goplus/math/rand"
)

// Mock 生成 随机值的 mock 数据
func Mock(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), false)
}

// MockKeep 生成 原值或0值的 mock 数据
func MockKeep(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), true)
}

func randomNew(typ reflect.Type) interface{} {
	switch typ.Kind() {
	case reflect.Bool:
		return false
	case reflect.Int:
		return int(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int8:
		return int8(randplus.MustRandint(-128, 127))
	case reflect.Int16:
		return int16(randplus.MustRandint(-32768, 32767))
	case reflect.Int32:
		return int32(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int64:
		return int64(randplus.MustRandint(-9223372036854775808, 9223372036854775807))
	case reflect.Uint:
		return uint(randplus.MustRandint(1, 4294967295))
	case reflect.Uint8:
		return uint8(randplus.MustRandint(1, 255))
	case reflect.Uint16:
		return uint16(randplus.MustRandint(1, 65535))
	case reflect.Uint32:
		return uint32(randplus.MustRandint(1, 4294967295))
	case reflect.Uint64:
		return uint64(randplus.MustRandint(1, 9223372036854775807))
	case reflect.Float32:
		return float32(rand.Float32())
	case reflect.Float64:
		return float64(rand.Float64())
	case reflect.Complex64:
		return complex64(complex(rand.Float32(), rand.Float32()))
	case reflect.Complex128:
		return complex128(complex(rand.Float64(), rand.Float64()))
	case reflect.String:
		samples := []string{"abc", "test", "this is a string"}
		weights := []int{}
		for i := 0; i < len(samples); i++ {
			weights = append(weights, 1)
		}
		index := randplus.MustWeightSample(weights)
		return samples[index]
	default:
		return nil
	}
}

func mockAny(v reflect.Value, isKeep bool) interface{} {
	v = DeepElemValue(v)
	switch v.Kind() {
	case reflect.Map:
		return mockMap(v, isKeep, true)
	case reflect.Struct:
		return mockStruct(v, isKeep, true)
	case reflect.Slice:
		return mockSlice(v, isKeep, true)
	case reflect.Array:
		return mockArray(v, isKeep, true)
	case reflect.Chan, reflect.Func, reflect.Interface:
		return nil
	default:
		if isKeep {
			if !v.IsValid() {
				return reflect.New(v.Type()).Interface()
			}
			return v.Interface()
		}
		return randomNew(v.Type())
	}
}

// MockStruct ...
func MockStruct(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockStruct(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockStruct ..
func mockStruct(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	for i := 0; i < v.NumField(); i++ {
		fieldValue := v.Field(i)
		fieldType := v.Type().Field(i)
		if fieldType.PkgPath == "" { // 只处理导出的字段
			key := structFieldName(fieldType, "json")
			var val interface{}
			if isRecurse {
				val = mockAny(reflect.New(fieldType.Type), isKeep)
			} else {
				val = DeepElemValue(fieldValue).Interface()
			}
			result[key] = val
		}
	}
	if len(result) == 0 {
		return v.Interface()
	}
	return result
}

// MockSlice ...
func MockSlice(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockSlice(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockSlice ..
func mockSlice(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := mockArray(v, isKeep, isRecurse).([]interface{})
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockArray ...
func MockArray(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockArray(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockArray ..
func mockArray(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := []interface{}{}
	for i := 0; i < v.Len(); i++ {
		var val interface{}
		if isRecurse {
			val = mockAny(v.Index(i), isKeep)
		} else {
			val = v.Index(i).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockMap ...
func MockMap(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockMap(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockMap ..
func mockMap(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	iter := v.MapRange()
	for iter.Next() {
		key := iter.Key().String()
		var val interface{}
		if isRecurse {
			val = mockAny(iter.Value(), isKeep)
		} else {
			val = iter.Value().Interface()
		}
		result[key] = val
	}
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result[""] = val
	}
	return result
}

import * as THREE from 'three';

const UNIFORMS = {
    // rgba
    u_g1_color: new THREE.Uniform(new THREE.Vector4(0, 0, 0, 1))
};

const CNC_LASER_VERT_SHADER = [
    'varying float v_g_code;',
    'attribute float a_g_code;',
    'void main(){',
    '    v_g_code = a_g_code;',
    '    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
    '}'
].join('');

const CNC_LASER_FRAG_SHADER = [
    'uniform vec4 u_g1_color;',
    'varying float v_g_code;',
    'void main(){',
    '    if(v_g_code == 0.0){',
    '        discard;',
    '    }',
    '    gl_FragColor = u_g1_color;',
    '}'
].join('');

const motionColor = {
    'G0': new THREE.Color(0xc8c8c8),
    'G1': new THREE.Color(0x000000),
    'unknown': new THREE.Color(0x000000)
};

class ToolPathRenderer {
    render(toolPath) {
        const { headerType, mode, movementMode, data } = toolPath;

        // now only support cnc&laser
        if (!['cnc', 'laser'].includes(headerType)) {
            return null;
        }

        if (headerType === 'laser') {
            if (mode === 'greyscale' && movementMode === 'greyscale-dot') {
                return this.parseToPoints(data);
            } else {
                return this.parseToLine(data);
            }
        } else {
            return this.parseToLine(data);
        }
    }

    parseToLine(data) {
        const positions = [];
        const gCodes = [];

        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if ((state.G === 1) && (newState.G === 0)) {
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(newState.G);
            }

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(state.G);
            }
        }

        const bufferGeometry = new THREE.BufferGeometry();
        const positionAttribute = new THREE.Float32BufferAttribute(positions, 3);
        const gCodeAttribute = new THREE.Float32BufferAttribute(gCodes, 1);
        bufferGeometry.addAttribute('position', positionAttribute);
        bufferGeometry.addAttribute('a_g_code', gCodeAttribute);
        const material = new THREE.ShaderMaterial({
            uniforms: UNIFORMS,
            vertexShader: CNC_LASER_VERT_SHADER,
            fragmentShader: CNC_LASER_FRAG_SHADER,
            side: THREE.DoubleSide,
            transparent: true,
            linewidth: 1
        });
        return new THREE.Line(bufferGeometry, material);
    }

    parseToPoints(data) {
        const geometry = new THREE.Geometry();
        const material = new THREE.PointsMaterial({
            size: 0.1,
            vertexColors: THREE.VertexColors,
            opacity: 0.9,
            transparent: true
        });
        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                geometry.vertices.push(new THREE.Vector3(state.X, state.Y, state.Z));
                if (state.G === 0) {
                    geometry.colors.push(motionColor.G0);
                } else if (state.G === 1) {
                    geometry.colors.push(motionColor.G1);
                } else {
                    geometry.colors.push(motionColor.unknown);
                }
            }
        }
        return new THREE.Points(geometry, material);
    }
}

export default ToolPathRenderer;

package reflect

import (
	"math/rand"
	"reflect"

	randplus "github.com/cheetah-fun-gs/goplus/math/rand"
)

// Mock 生成 随机值的 mock 数据
func Mock(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), false)
}

// MockKeep 生成 原值或0值的 mock 数据
func MockKeep(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), true)
}

func randomNew(typ reflect.Type) interface{} {
	switch typ.Kind() {
	case reflect.Bool:
		return false
	case reflect.Int:
		return int(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int8:
		return int8(randplus.MustRandint(-128, 127))
	case reflect.Int16:
		return int16(randplus.MustRandint(-32768, 32767))
	case reflect.Int32:
		return int32(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int64:
		return int64(randplus.MustRandint(-9223372036854775808, 9223372036854775807))
	case reflect.Uint:
		return uint(randplus.MustRandint(1, 4294967295))
	case reflect.Uint8:
		return uint8(randplus.MustRandint(1, 255))
	case reflect.Uint16:
		return uint16(randplus.MustRandint(1, 65535))
	case reflect.Uint32:
		return uint32(randplus.MustRandint(1, 4294967295))
	case reflect.Uint64:
		return uint64(randplus.MustRandint(1, 9223372036854775807))
	case reflect.Float32:
		return float32(rand.Float32())
	case reflect.Float64:
		return float64(rand.Float64())
	case reflect.Complex64:
		return complex64(complex(rand.Float32(), rand.Float32()))
	case reflect.Complex128:
		return complex128(complex(rand.Float64(), rand.Float64()))
	case reflect.String:
		samples := []string{"abc", "test", "this is a string"}
		weights := []int{}
		for i := 0; i < len(samples); i++ {
			weights = append(weights, 1)
		}
		index := randplus.MustWeightSample(weights)
		return samples[index]
	default:
		return nil
	}
}

func mockAny(v reflect.Value, isKeep bool) interface{} {
	v = DeepElemValue(v)
	switch v.Kind() {
	case reflect.Map:
		return mockMap(v, isKeep, true)
	case reflect.Struct:
		return mockStruct(v, isKeep, true)
	case reflect.Slice:
		return mockSlice(v, isKeep, true)
	case reflect.Array:
		return mockArray(v, isKeep, true)
	case reflect.Chan, reflect.Func, reflect.Interface:
		return nil
	default:
		if isKeep {
			if !v.IsValid() {
				return reflect.New(v.Type()).Interface()
			}
			return v.Interface()
		}
		return randomNew(v.Type())
	}
}

// MockStruct ...
func MockStruct(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockStruct(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockStruct ..
func mockStruct(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	for i := 0; i < v.NumField(); i++ {
		fieldValue := v.Field(i)
		fieldType := v.Type().Field(i)
		if fieldType.PkgPath == "" { // 只处理导出的字段
			key := structFieldName(fieldType, "json")
			var val interface{}
			if isRecurse {
				val = mockAny(reflect.New(fieldType.Type), isKeep)
			} else {
				val = DeepElemValue(fieldValue).Interface()
			}
			result[key] = val
		}
	}
	if len(result) == 0 {
		return v.Interface()
	}
	return result
}

// MockSlice ...
func MockSlice(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockSlice(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockSlice ..
func mockSlice(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := mockArray(v, isKeep, isRecurse).([]interface{})
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockArray ...
func MockArray(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockArray(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockArray ..
func mockArray(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := []interface{}{}
	for i := 0; i < v.Len(); i++ {
		var val interface{}
		if isRecurse {
			val = mockAny(v.Index(i), isKeep)
		} else {
			val = v.Index(i).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockMap ...
func MockMap(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockMap(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockMap ..
func mockMap(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	iter := v.MapRange()
	for iter.Next() {
		key := iter.Key().String()
		var val interface{}
		if isRecurse {
			val = mockAny(iter.Value(), isKeep)
		} else {
			val = iter.Value().Interface()
		}
		result[key] = val
	}
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result[""] = val
	}
	return result
}

import * as THREE from 'three';

const UNIFORMS = {
    // rgba
    u_g1_color: new THREE.Uniform(new THREE.Vector4(0, 0, 0, 1))
};

const CNC_LASER_VERT_SHADER = [
    'varying float v_g_code;',
    'attribute float a_g_code;',
    'void main(){',
    '    v_g_code = a_g_code;',
    '    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
    '}'
].join('');

const CNC_LASER_FRAG_SHADER = [
    'uniform vec4 u_g1_color;',
    'varying float v_g_code;',
    'void main(){',
    '    if(v_g_code == 0.0){',
    '        discard;',
    '    }',
    '    gl_FragColor = u_g1_color;',
    '}'
].join('');

const motionColor = {
    'G0': new THREE.Color(0xc8c8c8),
    'G1': new THREE.Color(0x000000),
    'unknown': new THREE.Color(0x000000)
};

class ToolPathRenderer {
    render(toolPath) {
        const { headerType, mode, movementMode, data } = toolPath;

        // now only support cnc&laser
        if (!['cnc', 'laser'].includes(headerType)) {
            return null;
        }

        if (headerType === 'laser') {
            if (mode === 'greyscale' && movementMode === 'greyscale-dot') {
                return this.parseToPoints(data);
            } else {
                return this.parseToLine(data);
            }
        } else {
            return this.parseToLine(data);
        }
    }

    parseToLine(data) {
        const positions = [];
        const gCodes = [];

        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if ((state.G === 1) && (newState.G === 0)) {
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(newState.G);
            }

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                positions.push(state.X);
                positions.push(state.Y);
                positions.push(state.Z);
                gCodes.push(state.G);
            }
        }

        const bufferGeometry = new THREE.BufferGeometry();
        const positionAttribute = new THREE.Float32BufferAttribute(positions, 3);
        const gCodeAttribute = new THREE.Float32BufferAttribute(gCodes, 1);
        bufferGeometry.addAttribute('position', positionAttribute);
        bufferGeometry.addAttribute('a_g_code', gCodeAttribute);
        const material = new THREE.ShaderMaterial({
            uniforms: UNIFORMS,
            vertexShader: CNC_LASER_VERT_SHADER,
            fragmentShader: CNC_LASER_FRAG_SHADER,
            side: THREE.DoubleSide,
            transparent: true,
            linewidth: 1
        });
        return new THREE.Line(bufferGeometry, material);
    }

    parseToPoints(data) {
        const geometry = new THREE.Geometry();
        const material = new THREE.PointsMaterial({
            size: 0.1,
            vertexColors: THREE.VertexColors,
            opacity: 0.9,
            transparent: true
        });
        let state = {
            G: 0,
            X: 0,
            Y: 0,
            Z: 0
        };
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const newState = { ...state };
            item.G !== undefined && (newState.G = item.G);
            item.X !== undefined && (newState.X = item.X);
            item.Y !== undefined && (newState.Y = item.Y);
            item.Z !== undefined && (newState.Z = item.Z);

            if (state.G !== newState.G
                || state.X !== newState.X
                || state.Y !== newState.Y
                || state.Z !== newState.Z) {
                state = newState;
                geometry.vertices.push(new THREE.Vector3(state.X, state.Y, state.Z));
                if (state.G === 0) {
                    geometry.colors.push(motionColor.G0);
                } else if (state.G === 1) {
                    geometry.colors.push(motionColor.G1);
                } else {
                    geometry.colors.push(motionColor.unknown);
                }
            }
        }
        return new THREE.Points(geometry, material);
    }
}

export default ToolPathRenderer;

package reflect

import (
	"math/rand"
	"reflect"

	randplus "github.com/cheetah-fun-gs/goplus/math/rand"
)

// Mock 生成 随机值的 mock 数据
func Mock(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), false)
}

// MockKeep 生成 原值或0值的 mock 数据
func MockKeep(v interface{}) interface{} {
	return mockAny(reflect.ValueOf(v), true)
}

func randomNew(typ reflect.Type) interface{} {
	switch typ.Kind() {
	case reflect.Bool:
		return false
	case reflect.Int:
		return int(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int8:
		return int8(randplus.MustRandint(-128, 127))
	case reflect.Int16:
		return int16(randplus.MustRandint(-32768, 32767))
	case reflect.Int32:
		return int32(randplus.MustRandint(-2147483648, 2147483647))
	case reflect.Int64:
		return int64(randplus.MustRandint(-9223372036854775808, 9223372036854775807))
	case reflect.Uint:
		return uint(randplus.MustRandint(1, 4294967295))
	case reflect.Uint8:
		return uint8(randplus.MustRandint(1, 255))
	case reflect.Uint16:
		return uint16(randplus.MustRandint(1, 65535))
	case reflect.Uint32:
		return uint32(randplus.MustRandint(1, 4294967295))
	case reflect.Uint64:
		return uint64(randplus.MustRandint(1, 9223372036854775807))
	case reflect.Float32:
		return float32(rand.Float32())
	case reflect.Float64:
		return float64(rand.Float64())
	case reflect.Complex64:
		return complex64(complex(rand.Float32(), rand.Float32()))
	case reflect.Complex128:
		return complex128(complex(rand.Float64(), rand.Float64()))
	case reflect.String:
		samples := []string{"abc", "test", "this is a string"}
		weights := []int{}
		for i := 0; i < len(samples); i++ {
			weights = append(weights, 1)
		}
		index := randplus.MustWeightSample(weights)
		return samples[index]
	default:
		return nil
	}
}

func mockAny(v reflect.Value, isKeep bool) interface{} {
	v = DeepElemValue(v)
	switch v.Kind() {
	case reflect.Map:
		return mockMap(v, isKeep, true)
	case reflect.Struct:
		return mockStruct(v, isKeep, true)
	case reflect.Slice:
		return mockSlice(v, isKeep, true)
	case reflect.Array:
		return mockArray(v, isKeep, true)
	case reflect.Chan, reflect.Func, reflect.Interface:
		return nil
	default:
		if isKeep {
			if !v.IsValid() {
				return reflect.New(v.Type()).Interface()
			}
			return v.Interface()
		}
		return randomNew(v.Type())
	}
}

// MockStruct ...
func MockStruct(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockStruct(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockStruct ..
func mockStruct(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	for i := 0; i < v.NumField(); i++ {
		fieldValue := v.Field(i)
		fieldType := v.Type().Field(i)
		if fieldType.PkgPath == "" { // 只处理导出的字段
			key := structFieldName(fieldType, "json")
			var val interface{}
			if isRecurse {
				val = mockAny(reflect.New(fieldType.Type), isKeep)
			} else {
				val = DeepElemValue(fieldValue).Interface()
			}
			result[key] = val
		}
	}
	if len(result) == 0 {
		return v.Interface()
	}
	return result
}

// MockSlice ...
func MockSlice(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockSlice(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockSlice ..
func mockSlice(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := mockArray(v, isKeep, isRecurse).([]interface{})
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockArray ...
func MockArray(v interface{}, isKeep, isRecurse bool) []interface{} {
	return mockArray(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).([]interface{})
}

// mockArray ..
func mockArray(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := []interface{}{}
	for i := 0; i < v.Len(); i++ {
		var val interface{}
		if isRecurse {
			val = mockAny(v.Index(i), isKeep)
		} else {
			val = v.Index(i).Interface()
		}
		result = append(result, val)
	}
	return result
}

// MockMap ...
func MockMap(v interface{}, isKeep, isRecurse bool) map[string]interface{} {
	return mockMap(DeepElemValue(reflect.ValueOf(v)), isKeep, isRecurse).(map[string]interface{})
}

// mockMap ..
func mockMap(v reflect.Value, isKeep, isRecurse bool) interface{} {
	result := map[string]interface{}{}
	iter := v.MapRange()
	for iter.Next() {
		key := iter.Key().String()
		var val interface{}
		if isRecurse {
			val = mockAny(iter.Value(), isKeep)
		} else {
			val = iter.Value().Interface()
		}
		result[key] = val
	}
	if len(result) == 0 {
		var val interface{}
		if isRecurse {
			val = mockAny(DeepElemValue(reflect.New(v.Type().Elem())), isKeep)
		} else {
			val = DeepElemValue(reflect.New(v.Type().Elem())).Interface()
		}
		result[""] = val
	}
	return result
}

---
layout: post
title: 4. Cartesian Control
category: ROS
tag: ROS
---
- to understand TF look at the my [](https://leechangyo.github.io/robotics/2019/10/04/Kinematic-Model/) post

# Cartesian Control

> Cartesian Control


```python
#!/usr/bin/env python

import math
import numpy
import time
from threading import Thread, Lock

import rospy
import tf
from geometry_msgs.msg import Transform
from sensor_msgs.msg import JointState
from std_msgs.msg import Float32
from urdf_parser_py.urdf import URDF

def S_matrix(w):
    S = numpy.zeros((3,3))
    S[0,1] = -w[2]
    S[0,2] =  w[1]
    S[1,0] =  w[2]
    S[1,2] = -w[0]
    S[2,0] = -w[1]
    S[2,1] =  w[0]
    return S

# This is the function that must be filled in as part of the Project.
def cartesian_control(joint_transforms, b_T_ee_current, b_T_ee_desired,
                      red_control, q_current, q0_desired):
    num_joints = len(joint_transforms)
    dq = numpy.zeros(num_joints)
    #-------------------- Fill in your code here ---------------------------
    J = numpy.zeros((6,num_joints))
    ee_V_ee = numpy.zeros(6) # array([0., 0., 0., 0., 0., 0.])

    T_to_desired = numpy.dot(numpy.linalg.inv(b_T_ee_current),b_T_ee_desired) # symmetry make

    angle, axis = rotation_from_matrix(T_to_desired)
    ## in base frame
    delta_p = T_to_desired[:3,3] #
    delta_theta = numpy.dot(axis,angle)

    p_dot = delta_p*1
    theta_dot = delta_theta*1

    #ee_T_b = numpy.linalg.inv(b_T_ee_current)
    ee_R_b = T_to_desired[:3,:3]

    ee_V_ee[:3] = numpy.dot(ee_R_b,p_dot)
    ee_V_ee[3:] = numpy.dot(ee_R_b,theta_dot)

    for i in range(num_joints):
        J[:,i] = adjoint_matrix(numpy.dot(numpy.linalg.inv(b_T_ee_current),joint_transforms[i]))[:,5]
    dq = numpy.dot(numpy.linalg.pinv(J,0.01),ee_V_ee)
    #----------------------------------------------------------------------
    return dq

def convert_from_message(t):
    trans = tf.transformations.translation_matrix((t.translation.x,
                                                  t.translation.y,
                                                  t.translation.z))
    rot = tf.transformations.quaternion_matrix((t.rotation.x,
                                                t.rotation.y,
                                                t.rotation.z,
                                                t.rotation.w))
    T = numpy.dot(trans,rot)
    return T

def adjoint_matrix(i_T_j):

    i_p_j = numpy.linalg.inv(i_T_j)[:3, 3] # raw column
    i_R_j = i_T_j[:3, :3]
    Ad = numpy.zeros((6,6))
    Ad[:3,:3] = i_R_j
    Ad[3:,3:] = i_R_j
    Ad[:3,3:] = -numpy.dot(i_R_j,S_matrix(i_p_j))

    return Ad

# Returns the angle-axis representation of the rotation contained in the input matrix
# Use like this:
# angle, axis = rotation_from_matrix(R)
def rotation_from_matrix(matrix):
    R = numpy.array(matrix, dtype=numpy.float64, copy=False)
    R33 = R[:3, :3]
    # axis: unit eigenvector of R33 corresponding to eigenvalue of 1
    l, W = numpy.linalg.eig(R33.T)
    i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
    if not len(i):
        raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
    axis = numpy.real(W[:, i[-1]]).squeeze()
    # point: unit eigenvector of R33 corresponding to eigenvalue of 1
    l, Q = numpy.linalg.eig(R)
    i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
    if not len(i):
        raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
    # rotation angle depending on axis
    cosa = (numpy.trace(R33) - 1.0) / 2.0
    if abs(axis[2]) > 1e-8:
        sina = (R[1, 0] + (cosa-1.0)*axis[0]*axis[1]) / axis[2]
    elif abs(axis[1]) > 1e-8:
        sina = (R[0, 2] + (cosa-1.0)*axis[0]*axis[2]) / axis[1]
    else:
        sina = (R[2, 1] + (cosa-1.0)*axis[1]*axis[2]) / axis[0]
    angle = math.atan2(sina, cosa)
    return angle, axis

class CartesianControl(object):

    #Initialization
    def __init__(self):
        #Loads the robot model, which contains the robot's kinematics information
        self.robot = URDF.from_parameter_server()

        #Subscribes to information about what the current joint values are.
        rospy.Subscriber("/joint_states", JointState, self.joint_callback)

        #Subscribes to command for end-effector pose
        rospy.Subscriber("/cartesian_command", Transform, self.command_callback)

        #Subscribes to command for redundant dof
        rospy.Subscriber("/redundancy_command", Float32, self.redundancy_callback)

        # Publishes desired joint velocities
        self.pub_vel = rospy.Publisher("/joint_velocities", JointState, queue_size=1)

        #This is where we hold the most recent joint transforms
        self.joint_transforms = []
        self.q_current = []
        self.x_current = tf.transformations.identity_matrix()
        self.R_base = tf.transformations.identity_matrix()
        self.x_target = tf.transformations.identity_matrix()
        self.q0_desired = 0
        self.last_command_time = 0
        self.last_red_command_time = 0

        # Initialize timer that will trigger callbacks
        self.mutex = Lock()
        self.timer = rospy.Timer(rospy.Duration(0.1), self.timer_callback)

    def command_callback(self, command):
        self.mutex.acquire()
        self.x_target = convert_from_message(command)
        self.last_command_time = time.time()
        self.mutex.release()

    def redundancy_callback(self, command):
        self.mutex.acquire()
        self.q0_desired = command.data
        self.last_red_command_time = time.time()
        self.mutex.release()        

    def timer_callback(self, event):
        msg = JointState()
        self.mutex.acquire()
        if time.time() - self.last_command_time < 0.5:
            dq = cartesian_control(self.joint_transforms,
                                   self.x_current, self.x_target,
                                   False, self.q_current, self.q0_desired)
            msg.velocity = dq
        elif time.time() - self.last_red_command_time < 0.5:
            dq = cartesian_control(self.joint_transforms,
                                   self.x_current, self.x_current,
                                   True, self.q_current, self.q0_desired)
            msg.velocity = dq
        else:            
            msg.velocity = numpy.zeros(7)
        self.mutex.release()
        self.pub_vel.publish(msg)

    def joint_callback(self, joint_values):
        root = self.robot.get_root()
        T = tf.transformations.identity_matrix()
        self.mutex.acquire()
        self.joint_transforms = []
        self.q_current = joint_values.position
        self.process_link_recursive(root, T, joint_values)
        self.mutex.release()

    def align_with_z(self, axis):
        T = tf.transformations.identity_matrix()
        z = numpy.array([0,0,1])
        x = numpy.array([1,0,0])
        dot = numpy.dot(z,axis)
        if dot == 1: return T
        if dot == -1: return tf.transformation.rotation_matrix(math.pi, x)
        rot_axis = numpy.cross(z, axis)
        angle = math.acos(dot)
        return tf.transformations.rotation_matrix(angle, rot_axis)

    def process_link_recursive(self, link, T, joint_values):
        if link not in self.robot.child_map:
            self.x_current = T
            return
        for i in range(0,len(self.robot.child_map[link])):
            (joint_name, next_link) = self.robot.child_map[link][i]
            if joint_name not in self.robot.joint_map:
                rospy.logerror("Joint not found in map")
                continue
            current_joint = self.robot.joint_map[joint_name]        

            trans_matrix = tf.transformations.translation_matrix((current_joint.origin.xyz[0],
                                                                  current_joint.origin.xyz[1],
                                                                  current_joint.origin.xyz[2]))
            rot_matrix = tf.transformations.euler_matrix(current_joint.origin.rpy[0],
                                                         current_joint.origin.rpy[1],
                                                         current_joint.origin.rpy[2], 'rxyz')
            origin_T = numpy.dot(trans_matrix, rot_matrix)
            current_joint_T = numpy.dot(T, origin_T)
            if current_joint.type != 'fixed':
                if current_joint.name not in joint_values.name:
                    rospy.logerror("Joint not found in list")
                    continue
                # compute transform that aligns rotation axis with z
                aligned_joint_T = numpy.dot(current_joint_T, self.align_with_z(current_joint.axis))
                self.joint_transforms.append(aligned_joint_T)
                index = joint_values.name.index(current_joint.name)
                angle = joint_values.position[index]
                joint_rot_T = tf.transformations.rotation_matrix(angle,
                                                                 numpy.asarray(current_joint.axis))
                next_link_T = numpy.dot(current_joint_T, joint_rot_T)
            else:
                next_link_T = current_joint_T

            self.process_link_recursive(next_link, next_link_T, joint_values)

if __name__ == '__main__':
    rospy.init_node('cartesian_control', anonymous=True)
    cc = CartesianControl()
    rospy.spin()



```

<a href="https://postimg.cc/Hc2jxBXX"><img src="https://i.postimg.cc/wMKNwrBf/Capture.png" width="700px" title="source: imgur.com" /><a>
<a href="https://postimg.cc/xJkFjFWF"><img src="https://i.postimg.cc/ZRjkcGjZ/Capture.png" width="700px" title="source: imgur.com" /><a>
<a href="https://postimg.cc/Yv9Py9dH"><img src="https://i.postimg.cc/Hk4Cn85V/Capture.png" width="700px" title="source: imgur.com" /><a>

package io.github.poulad.hnp.web.error;

import javax.annotation.Nonnull;
import lombok.Value;

@Value
public class ValidationError {

  @Nonnull
  String parameter;

  @Nonnull
  RequestParameterType parameterType;

  @Nonnull
  String errorMessage;
}

#!/usr/bin/env python

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write("<html><body><h1>hello from the other side!</h1></body></html>")

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])  # <--- Gets the size of data
        post_data = self.rfile.read(content_length)  # <--- Gets the data itself
        print "RECEIVED DATA FROM POST" , post_data # <-- Print post data
        print "\n \n"
        self._set_headers()
        self.wfile.write("<html><body><h1>POST!</h1><pre>" + post_data + "</pre></body></html>")

def run(server_class=HTTPServer, handler_class=S,ip='127.0.0.1' port=8081):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print 'Starting HTTP server at {0}:{1} .....'.format(ip,port)
    httpd.serve_forever()


if __name__ == "__main__":
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

#pragma once
#include <functional>

namespace Server
{
    enum class WhatHappened
    {
        LibraryLoadingError,
        AddressInitializationError,
        AddressBindingError,
        SocketCreationError,
        Ok,
        RequestHandlerIsNull,
        SocketInitializationFailed,
        RequestProcessingFatalError,
        RecvFailed,
        SendFailed,
        ConnectionClosed
    };

    using Handler = const std::function<std::string(const std::string_view)> &;

    std::string ToString(const WhatHappened what);

    WhatHappened Start(Handler onRequest);
}
var styles = [
      {
          "featureType": "administrative",
          "elementType": "geometry",
          "stylers": [
              {
                  "color": "#dfeae3"
              }
          ]
      },
      {
          "featureType": "administrative",
          "elementType": "labels.text.fill",
          "stylers": [
              {
                  "color": "#444444"
              }
          ]
      },
      {
          "featureType": "administrative.locality",
          "elementType": "labels",
          "stylers": [
              {
                  "visibility": "on"
              }
          ]
      },
      {
          "featureType": "landscape",
          "elementType": "all",
          "stylers": [
              {
                  "color": "#f2f2f2"
              },
              {
                  "visibility": "simplified"
              }
          ]
      },
      {
          "featureType": "poi",
          "elementType": "all",
          "stylers": [
              {
                  "visibility": "on"
              }
          ]
      },
      {
          "featureType": "poi",
          "elementType": "geometry",
          "stylers": [
              {
                  "visibility": "simplified"
              },
              {
                  "saturation": "-65"
              },
              {
                  "lightness": "45"
              },
              {
                  "gamma": "1.78"
              }
          ]
      },
      {
          "featureType": "poi",
          "elementType": "labels",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "poi",
          "elementType": "labels.icon",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "road",
          "elementType": "all",
          "stylers": [
              {
                  "saturation": -100
              },
              {
                  "lightness": 45
              }
          ]
      },
      {
          "featureType": "road",
          "elementType": "labels",
          "stylers": [
              {
                  "visibility": "on"
              }
          ]
      },
      {
          "featureType": "road",
          "elementType": "labels.icon",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "road.highway",
          "elementType": "all",
          "stylers": [
              {
                  "visibility": "simplified"
              }
          ]
      },
      {
          "featureType": "road.highway",
          "elementType": "labels.icon",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "road.arterial",
          "elementType": "labels.icon",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "transit.line",
          "elementType": "geometry",
          "stylers": [
              {
                  "saturation": "-33"
              },
              {
                  "lightness": "22"
              },
              {
                  "gamma": "2.08"
              }
          ]
      },
      {
          "featureType": "transit.station.airport",
          "elementType": "geometry",
          "stylers": [
              {
                  "gamma": "2.08"
              },
              {
                  "hue": "#ffa200"
              }
          ]
      },
      {
          "featureType": "transit.station.airport",
          "elementType": "labels",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "transit.station.rail",
          "elementType": "labels.text",
          "stylers": [
              {
                  "visibility": "off"
              }
          ]
      },
      {
          "featureType": "transit.station.rail",
          "elementType": "labels.icon",
          "stylers": [
              {
                  "visibility": "simplified"
              },
              {
                  "saturation": "-55"
              },
              {
                  "lightness": "-2"
              },
              {
                  "gamma": "1.88"
              },
              {
                  "hue": "#ffab00"
              }
          ]
      },
      {
          "featureType": "water",
          "elementType": "all",
          "stylers": [
              {
                  "color": "#bbd9e5"
              },
              {
                  "visibility": "simplified"
              }
          ]
      }
]

if (document.getElementById('map-canvas')) {

  function initialize() {
      var myLatlng = new google.maps.LatLng(47.245236, -122.362339);
      var mapOptions = {
          zoom: 13,
          styles: styles,
          center: myLatlng,
          draggable: false,
          scrollwheel: false,
          mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

       //=====Initialise Default Marker
      var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          title: 'marker',
          icon: {
            url: mapIncludes.markericon,
            size: new google.maps.Size(21, 38),
            scaledSize: new google.maps.Size(21, 38),
            anchor: new google.maps.Point(21, 38)
          }
       //=====You can even customize the icons here
      });

      /*
       //=====Initialise InfoWindow
      var infowindow = new google.maps.InfoWindow({
        // TODO: Confirm this content?
        content: "<B>Skyway Dr</B>"
    });

     //=====Eventlistener for InfoWindow
    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });
    */
  }

  google.maps.event.addDomListener(window, 'load', initialize);
}

package com.skt.nugu.sdk.core.network

import com.skt.nugu.sdk.core.interfaces.connection.ConnectionStatusListener
import com.skt.nugu.sdk.core.interfaces.connection.ConnectionManagerInterface
import com.skt.nugu.sdk.core.interfaces.message.*
import java.util.concurrent.CopyOnWriteArraySet

/**
 * This class is designed to manage connections.
 */
class NetworkManager private constructor(
    private val messageRouter: MessageRouterInterface
) : ConnectionManagerInterface,
    MessageSender by messageRouter,
    MessageRouterObserverInterface {

    companion object {
        /**
         * Create a [NetworkManager]
         * @return a [NetworkManager] instance
         */
        fun create(messageRouter: MessageRouterInterface): NetworkManager {
            val connectionManager = NetworkManager(messageRouter)

            messageRouter.setObserver(connectionManager)

            return connectionManager
        }
    }

    private var enabled = false
    private val messageObservers = CopyOnWriteArraySet<MessageObserver>()
    private val connectionStatusObservers = CopyOnWriteArraySet<ConnectionStatusListener>()
    /**
     * Initiate a connection to DeviceGateway.
     */
    override fun enable() {
        enabled = true
        messageRouter.enable()
    }
    /**
     * Disconnect from DeviceGateway.
     */
    override fun disable() {
        enabled = false
        messageRouter.disable()
    }
    /**
     * check whether a enable
     */
    override fun isEnabled(): Boolean = enabled

    /**
     * reconnect from DeviceGateway.
     */
    override fun reconnect() {
        if (enabled) {
            messageRouter.disable()
            messageRouter.enable()
        }
    }
    /**
     * Returns whether this object is currently connected to DeviceGateway.
     */
    override fun isConnected(): Boolean =
        messageRouter.getConnectionStatus() == ConnectionStatusListener.Status.CONNECTED

    /**
     * Adds an observer to be notified when a message arrives from DeviceGateway.
     * @param observer The observer to add.
     */
    override fun addMessageObserver(observer: MessageObserver) {
        messageObservers.add(observer)
    }

    /**
     * Removes an observer to be notified when a message arrives from DeviceGateway.
     * @param observer The observer to remove.
     */
    override fun removeMessageObserver(observer: MessageObserver) {
        messageObservers.remove(observer)
    }

    /**
     * Adds an observer to be notified of connection status changes.
     * @param observer The observer to add.
     */
    override fun addConnectionStatusListener(listener: ConnectionStatusListener) {
        connectionStatusObservers.add(listener)
        listener.onConnectionStatusChanged(
            messageRouter.getConnectionStatus(),
            ConnectionStatusListener.ChangedReason.NONE
        )
    }

    /**
     * Removes an observer from being notified of connection status changes.
     * @param observer The observer to remove.
     */
    override fun removeConnectionStatusListener(listener: ConnectionStatusListener) {
        connectionStatusObservers.remove(listener)
    }

    /**
     * Receives the connection status changes.
     */
    override fun onConnectionStatusChanged(
        status: ConnectionStatusListener.Status,
        reason: ConnectionStatusListener.ChangedReason
    ) {
        connectionStatusObservers.forEach { it.onConnectionStatusChanged(status,reason) }
    }

    override fun receiveDirectives(directives: List<DirectiveMessage>) {
        messageObservers.forEach {
            it.receiveDirectives(directives)
        }
    }

    override fun receiveAttachment(attachment: AttachmentMessage) {
        messageObservers.forEach {
            it.receiveAttachment(attachment)
        }
    }

    /**
     *  handoff connection from SystemCapability
     */
    override fun handoffConnection(
        protocol: String,
        hostname: String,
        address: String,
        port: Int,
        retryCountLimit: Int,
        connectionTimeout: Int,
        charge: String
    ) {
        messageRouter.handoffConnection(protocol, hostname, address, port, retryCountLimit, connectionTimeout, charge)
    }

    /**
     * Resets the connection immediately.
     */
    override fun resetConnection(description: String?) {
        messageRouter.resetConnection(description)
    }

    /**
     * Set the keepConnection
     */
    override fun keepConnection(enabled: Boolean) = messageRouter.keepConnection(enabled)
}
package com.monet.bidder

import android.os.Bundle
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner

@RunWith(RobolectricTestRunner::class)
class DfpRequestHelperTest {
    private val adSize = AdSize(300, 250)
    @Test
    fun `Given ADUNIT_KEYWORD_KEY is present in Bundle  get adUnitId from customEventExtras`() {
        val adUnitId = "adUnitId"
        val serverParameter = "serverParam"
        val customEventExtras = Bundle()
        customEventExtras.putString(Constants.Dfp.ADUNIT_KEYWORD_KEY, adUnitId)
        val helperAdUnit = DfpRequestHelper.getAdUnitID(customEventExtras, serverParameter, adSize)
        Assert.assertEquals(helperAdUnit, adUnitId)
    }

    @Test
    fun `Given ADUNIT_KEYWORD_KEY is not present and serverParameter is not null, 'default' or 'AMAdSize' and it starts with $ sign`() {
        val adUnit = DfpRequestHelper.getAdUnitID(Bundle(), "$100", adSize);
        Assert.assertEquals("300x250", adUnit)
    }

    @Test
    fun `Given ADUNIT_KEYWORD_KEY is not present and serverParameter is not null, 'default' or 'AMAdSize' and it does not start with $ sign (adunit cpm format)`() {
        val serverParam = "test_interstitial@$100"
        val adUnit = DfpRequestHelper.getAdUnitID(Bundle(), serverParam, adSize)
        Assert.assertEquals(adUnit, "test_interstitial")
    }

    @Test
    fun `Given ADUNIT_KEYWORD_KEY is not present and serverParameter is not null, 'default' or 'AMAdSize' and it does not start with $ sign (normal format)`() {
        val normalAdUnitServerParam = "only_ad_unit"
        val adUnit = DfpRequestHelper.getAdUnitID(Bundle(), normalAdUnitServerParam, adSize)
        Assert.assertEquals(adUnit, normalAdUnitServerParam)
    }

    @Test
    fun `Given ADUNIT_KEYWORD_KEY is not present and serverParameters default or AMAdSize`() {
        val defaultServerParam = "default"
        val adUnit = DfpRequestHelper.getAdUnitID(Bundle(), defaultServerParam, adSize)
        Assert.assertEquals(adUnit, "300x250")
        val amAdSizeServerParam = "AMAdSize"
        val unit = DfpRequestHelper.getAdUnitID(Bundle(), amAdSizeServerParam, adSize)
        Assert.assertEquals(unit, "300x250")
    }

    @Test
    fun `Given ADUNIT_KEYWORD_KEY is not present and serverParameter is empty get ad size as adUnit`() {
        val serverParam = ""
        val adUnit = DfpRequestHelper.getAdUnitID(Bundle(), serverParam, adSize)
        Assert.assertEquals(adUnit, "300x250")
    }

    @Test
    fun `Given serverParameter is empty or null return 0 cpm`() {
        Assert.assertEquals(DfpRequestHelper.getCpm(""), 0.0, 0.0)
        Assert.assertEquals(DfpRequestHelper.getCpm(null), 0.0, 0.0)
    }

    @Test
    fun `Given serverParameter starts with $ sign followed by a number`() {
        val cpm = DfpRequestHelper.getCpm("$5.00")
        Assert.assertEquals(cpm, 5.00, 5.00)
    }

    @Test
    fun `Given serverParameter starts with $sign followed by not a number`() {
        val cpm = DfpRequestHelper.getCpm("\$JOSE")
        Assert.assertEquals(cpm, 0.0, 0.0)
    }

    @Test
    fun `Given serverParameter has adUnitId and cpm`(){
        val cpm = DfpRequestHelper.getCpm("test_adunit@$5.00")
        Assert.assertEquals(cpm, 5.0, 5.0)
    }

    @Test
    fun `Given serverParameter has adUnitId and cpm not as a number`(){
        val cpm = DfpRequestHelper.getCpm("test_adunit@\$JOSE")
        Assert.assertEquals(cpm, 0.0, 0.0)
    }
}
module.exports = `body{
    margin:0;   
}

a{
    text-decoration: none !important;
    color: #000 !important;
}

.hide{
    display: none;
}

@media (min-width:200px) and (max-width:740px){
    .matias-navigation{
        z-index: 9999999999;
        margin-top: 0px;
        top: 0;
        width: 100%;
        text-align: center;
        padding-top: 0px;
		height: 100%;
        position: fixed;
        background: #FFF;
        overflow: auto;
    }
}

nav.matias-navigation ul{
    list-style: none;
    width: 100%;
    margin: 0px auto;
}

.matias-navigation__logo{
    width: 100%;
    float: none;
    text-align: center;
    margin: 0px auto;
    background: #000;
    padding-top: 10px;
    padding-bottom: 10px;
}

.matias-navigation__logo a img {
    max-width: 60px;
}

.matias-navigation__logoCloseMobile{
    width: 25%;
    left: 0px;
    position: absolute;
    top: 30px;
    right: 0px;
    z-index: 999;
}

.matias-navigation__logoCloseMobile img {
    width: 20px;
    cursor: pointer;
}

.matias-navigation__upperMenu{
    display: flex;
}

.matias-navigation__upperMenu ul li {
    position: relative;
    width: 31.50%;
    max-width: 170px;
    float: left;
    font-family: 'Asap', sans-serif;
    font-weight: 700;
    margin: 15px 10px 10px;
    transition: 0.3s ease-in-out;
    padding: 0 3px;
    outline: none;
}

.matias-navigation__upperMenu ul li img {
    border-radius: 5px;
    max-height: 85px;
    height: 85px;
    width: 100%;
    object-fit: cover;
}

.matias-navigation__upperMenu ul li span {
    position: absolute;
    top: 50%;
    transform: translate(0px , -50%);
    left: 12px;
}

.matias-navigation__upperMenu ul li span a {
    padding: 4px 7px;
    border-radius: 3px;
    background-color: #fff;
    text-transform: uppercase;
    font-size: 12px;
    color: black;
    text-decoration: none;
}


.accordion-content{
    display: none;
    padding: 0 8px;
    flex-direction: column;
    margin: 10px 0 0 0;
}

.accordion-content11{
    display: block;
}

.accordion-row{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100px;
    background-color: #f2f2f2;
    padding-left: 10px;
    min-height: 90px;
    line-height: 90px;
    text-transform: uppercase;
    font-family: 'Asap', sans-serif;
    font-weight: 700;
    color: #000;
    border-radius: 3px;
    margin-bottom: 6px;
}

.accordion-row img {
    max-height: 100px;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
}

.animate__animated.animate__fadeInLeft {
    --animate-duration: 0.75s;
}
  
.matias-navigation__upperMenu ul {
    padding-left: 0 !important;
}
 
.shifter-open{
  overflow:hidden;
  display:block;
}`;

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;
namespace XBMCRPC.List.Filter
{
   public class MusicVideosAnd
   {
       public global::System.Collections.Generic.List<object> and { get; set; }
    }
}

# File upload modal component

The file upload modal is a component that allows users to upload, browse, and modify files. When a save is triggered, the files are then uploaded to the database. The uploaded and/or selected files are returned in an object when the modal is closed.

A common approach to using the File Upload Modal component is within a form, giving users the chance to select files to be attached to a Project, for example. Such an implementation would go as follows:

1. Put a button within the form of the Project edit screen.
2. In your button press handler, specify options for the file-upload-modal, then launch it. See below for more details.
3. When the modal is saved by the user, the files will be uploaded. The file-upload-modal will return the ObjectID of each selected image. You can save these ObjectIDs in your form.

## Setting modal options and launching

The modal technology used with is [NGX Smart modal](https://github.com/maximelafarie/ngx-smart-modal). To set the file-upload-modal data, import the ngxSmartModalService in your component, then call the `setModalData` method:

```
this.ngxSmartModalService.setModalData({
  ...yourOptions
}, 'file-upload-modal', true);
```
After setting the data, use the `open` method to launch the modal:

```
this.ngxSmartModalService.open('file-upload-modal');
```

## Options API

All options are optional except for projectID, which is needed to make sure files are saved to a particular project.

#### __title__ _String_
The title of the modal window. Example: "Select project logo(s)."
### __projectID__ _String_
Should be the project the modal is being launched from. Files will be saved with this project ID.
#### __fileExt__ _String_
A string of accepted file types separated by commas. Example: 'jpg, jpeg, png'
#### __altRequired__ _Boolean_
Whether or not the selected files must each have alt tags specified. Used when specifying image files.
#### __fileNum__ _Number_
Maximum number of files the user can select. If -1 is entered, there is no limit.
#### __returnedFiles__ _Document[]_
An array of document objects returned from the files having been saved. It's not recommended that you set this manually. The File Upload Modal uses this to return files
after they've been saved and the modal has been closed.

## Accessing the returned files

Set up an event listener to check if the File Upload Modal has closed for any reason.
It's recommended you do this in the AfterViewInit lifecycle method.

```
ngAfterViewInit(): void {
  this.ngxSmartModalService.getModal('file-upload-modal').onAnyCloseEventFinished.subscribe((modal: NgxSmartModalComponent) => {
    console.log('The returned data:', modal.getData());
  });
}
```

If the files were successfully saved, you should get an object with a `returnedFiles` containing an array of documents.

#! /usr/bin/env python

from openturns import *

TESTPREAMBLE()

try :

    center = NumericalPoint(4, 0.0)
    center.setName("center")
    center[0] = 0.5
    center[1] = 1.5
    center[2] = 2.5
    center[3] = 3.5
    levels = NumericalPoint(3, 0.0)
    levels.setName("levels")
    levels[0] = 4
    levels[1] = 8
    levels[2] = 16
    myPlane = Factorial(center, levels)
    print "myPlane = " , myPlane
    sample = myPlane.generate()
    print "sample = " , repr(sample)

except :
    import sys
    print "t_Factorial_std.py", sys.exc_type, sys.exc_value

package api

import (
	"net/http"

	"db"
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"gopkg.in/mgo.v2/bson"
	"io/ioutil"
	"time"
	// "strconv"
)

// Input failed validation.
// swagger:response validationError
type ValidationError struct {
	// The error message
	// in: body
	Body struct {
		Code    int32  `json:"code"`
		Message string `json:"message"`
		Field   string `json:"field"`
	} `json:"body"`
}

// Success Answer
// swagger:response successAnswer
type successAnswer struct {
	// The error message
	// in: body
	Body struct {
		Code    int32  `json:"code"`
		Message string `json:"message"`
		Field   string `json:"field"`
	} `json:"body"`
}

// Server id
// swagger:parameters deleteServer getServerById updateServer
type id struct {
	// id Server Generated
	//
	// in: path
	// required: true
	ID int64 `json:"id"`
}

// Server Param
// swagger:parameters createServer updateServer
type myServerBodyParams struct {
	// Server to submit
	//
	// in: body
	// required: true
	Server *db.Server `json:"server"`
}

// Server Multi
// swagger:parameters  importServer
type myMultipleServerBodyParams struct {
	// Server to submit
	//
	// in: body
	// required: true
	Server *[]db.Server `json:"multiserver"`
}

// swagger:route GET /servers servers listServer
//
// Lists servers
//
// This will show all available asset by default.
//
//
//     Responses:
//       default: validationError
//       200: []server
func GetAllItems(w http.ResponseWriter, req *http.Request) {
	rs, err := db.GetAll()
	if err != nil {
		handleError(err, "Failed to load database items: %v", w)
		return
	}
	bs, err := json.MarshalIndent(rs, "", "    ")
	if err != nil {
		handleError(err, "Failed to load marshal data: %v", w)
		return
	}
	w.Write(bs)
}

func handleError(err error, message string, w http.ResponseWriter) {
	w.WriteHeader(http.StatusInternalServerError)
	w.Write([]byte(fmt.Sprintf(message, err)))
}

// swagger:route POST /servers servers createServer
//
// Add a server
//
// This will register asset.
//
//     Responses:
//       default: validationError
//       200: successAnswer
func PostItem(w http.ResponseWriter, req *http.Request) {
	var server db.Server

	decoder := json.NewDecoder(req.Body)

	// debug, err := json.MarshalIndent(decoder, "", "    ")
	// fmt.Println(" debug", debug)
	// fmt.Println(" err", err)

	errjson := decoder.Decode(&server)

	if errjson != nil {
		fmt.Println("Incorrect body")
		fmt.Println(errjson)
		return
	}
	// fmt.Println(server)

	id := bson.NewObjectId()
	ref := id.Hex()
	Name := server.CMDBName
	Function := server.Function
	SerialNumber := server.SerialNumber
	AssetCode := server.AssetCode
	Model := server.HardwareDefinition.Model
	CPU := server.HardwareDefinition.CPU
	RAM := server.HardwareDefinition.RAM
	Room := server.Localisation.Room
	Building := server.Localisation.Building
	Rack := server.Localisation.Rack
	Remarks := server.Remarks
	Status := server.Status
	UpdateTime := time.Now()
	InsertTime := time.Now()

	fmt.Println(UpdateTime)
	fmt.Println(InsertTime)

	// IpAddr := server.Networking[0].IpAddr
	// PatchPanel := server.Networking[0].PatchPanel
	// ServerPort := server.Networking[0].ServerPort
	// Switch := server.Networking[0].Switch
	// Vlan := server.Networking[0].Vlan
	// MAC := server.Networking[0].MAC

	// item := db.Server{ID: id, CMDBName: Name, Networking: []db.Networks{{IpAddr: IpAddr, PatchPanel: PatchPanel, ServerPort: ServerPort, Switch: Switch, Vlan: Vlan, MAC: MAC}}}

	item := db.Server{ID: id, CMDBName: Name, Function: Function, SerialNumber: SerialNumber, AssetCode: AssetCode, HardwareDefinition: db.HardwareDefinition{Model: Model, CPU: CPU, RAM: RAM}, Localisation: db.Localisation{Room: Room, Building: Building, Rack: Rack}, Remarks: Remarks, Status: Status, UpdateTime: UpdateTime, InsertTime: InsertTime}
	if err := db.Save(item); err != nil {
		handleError(err, "Failed to save data: %v", w)
		return
	}

	// Idea is add static field and use loop for update array of networks
	// Networking: []db.Networks{{IpAddr: IpAddr, PatchPanel: PatchPanel, ServerPort: ServerPort, Switch: Switch, Vlan: Vlan, MAC: MAC}},
	var collec string
	collec = "networking"
	fmt.Println(server.Networking)

	for _, net := range server.Networking {
		fmt.Println(net)
		// Launch update with id = id
		if err := db.Update(ref, collec, net); err != nil {
			handleError(err, "Failed to save data: %v", w)
			return
		}
	}
	w.Write([]byte("OK"))
}

// swagger:route DELETE /servers/{id} servers deleteServer
//
// Delete servers
//
// This will delete asset.
//
//     Responses:
//       default: validationError
//       200: successAnswer
func DeleteItem(w http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	id := vars["id"]

	if err := db.Remove(id); err != nil {
		handleError(err, "Failed to remove item: %v", w)
		return
	}
	w.Write([]byte("OK"))
}

// swagger:route GET /servers/{id} servers getServerById
//
// Lists specific server
//
// This will list details for specific server.
//
//     Responses:
//       default: validationError
//       200: server
func GetItem(w http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	id := vars["id"]
	fmt.Println("id", id)

	rs, err := db.GetOne(id)
	// fmt.Println("rs", rs)
	// fmt.Println("err", err)

	if err != nil {
		handleError(err, "Failed to read database: %v", w)
		return
	}

	bs, err := json.Marshal(rs)
	if err != nil {
		handleError(err, "Failed to marshal data: %v", w)
		return
	}
	w.Write(bs)
}

// swagger:route PATCH /servers/{id} servers updateServer
//
// Update specific server
//
// This will update details for specific server.
//
//     Responses:
//       default: validationError
//       200: successAnswer
func UpdateItem(w http.ResponseWriter, req *http.Request) {
	// fmt.Println("Im in update api")
	vars := mux.Vars(req)
	id := vars["id"]
	// fmt.Println("id", id)

	var server db.Server

	decoder := json.NewDecoder(req.Body)

	errjson := decoder.Decode(&server)

	if errjson != nil {
		fmt.Println("Incorrect body")
		fmt.Println(errjson)
		return
	}

	if erro, err := db.Updatemain(id, server); err != nil && erro != nil {
		handleError(err, "Failed to save data: %v", w)
		return
	}
	w.Write([]byte("OK"))
}

// swagger:route POST /servers/import servers importServer
//
// Import / Add multiple Servers
//
// This will insert multiple servers.
//
//     Responses:
//       default: validationError
//       200: successAnswer
func PostMultipleItems(w http.ResponseWriter, req *http.Request) {
	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		panic(err)
	}
	var server []db.Server
	err = json.Unmarshal(body, &server)
	// fmt.Println("Body:", body)
	if err != nil {
		//handle error
	}
	// Loop for multiple of server included in JSON
	for i := range server {
		fmt.Println(server[i].CMDBName)
		fmt.Println(server[i])
		if err := db.Save(server[i]); err != nil {
			handleError(err, "Failed to save data: %v", w)
			return
		}

	}
}
const glob = require('glob');
const { stat, readFile } = require('fs/promises');

const { consoleError } = require('./constants');

function getFilesList(paths = []) {
  if (!Array.isArray(paths)) {
    throw new TypeError(`${consoleError}: Argument "paths" should be an array!`);
  }

  let filesList = [];

  for (const path of paths) {
    const files = glob.sync(path);

    filesList = filesList.concat(files);
  }

  return filesList;
}

async function getFileData(filePath) {
  try {
    if (!filePath || typeof filePath !== 'string') {
      throw new TypeError('filePath must be a string!');
    }

    const fileStat = await stat(filePath);
    const fileData = await readFile(filePath, 'utf8');

    return { fileStat, fileData };
  } catch (error) {
    throw new Error(`${consoleError}: ${error}`);
  }
}

async function startPlugins(filePath, config) {
  try {
    const { fileStat, fileData } = await getFileData(filePath);

    for (const plugin of config.plugins) {
      plugin({ fileData, fileStat }, config);
    }
  } catch (error) {
    throw new Error(`${consoleError}: ${error}`);
  }
}

module.exports = { getFilesList, getFileData, startPlugins };

package io.rsocket.transport.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import io.netty.util.CharsetUtil;

public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

  private final WebSocketClientHandshaker handshaker;
  private ChannelPromise handshakeFuture;

  public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
    this.handshaker = handshaker;
  }

  public ChannelFuture handshakeFuture() {
    return handshakeFuture;
  }

  @Override
  public void handlerAdded(ChannelHandlerContext ctx) {
    handshakeFuture = ctx.newPromise();
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) {
    handshaker.handshake(ctx.channel());
  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) {
    System.out.println("WebSocket Client disconnected!");
  }

  @Override
  public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
      try {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
      } catch (WebSocketHandshakeException e) {
        System.out.println("WebSocket Client failed to connect");
        handshakeFuture.setFailure(e);
      }
      return;
    }

    if (msg instanceof FullHttpResponse) {
      FullHttpResponse response = (FullHttpResponse) msg;
      throw new IllegalStateException(
          "Unexpected FullHttpResponse (getStatus="
              + response.status()
              + ", content="
              + response.content().toString(CharsetUtil.UTF_8)
              + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
      TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
      System.out.println("WebSocket Client received message: " + textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
      System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
      System.out.println("WebSocket Client received closing");
      ch.close();
    }
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    if (!handshakeFuture.isDone()) {
      handshakeFuture.setFailure(cause);
    }
    ctx.close();
  }
}

import 'dotenv/config';
import express from 'express';
import UserController from './app/controllers/UserController';
import BullBoard from 'bull-board';
import Queue from './app/lib/Queue';

const app = express();
BullBoard.setQueues(Queue.queues.map(queue => queue.bull));

app.use(express.json());
app.post('/users', UserController.store);

app.use('/admin/queues', BullBoard.UI);

app.listen(3333, () => {
  console.log('Server running on localhost:3333');
});
module.exports = function getZerosCount(number, base) {
//next function is the sieve of Eratosfen
  function sieve(upper_bound){
    let grains = [0, 0];
    for (let i = 2; i <= upper_bound; i++)
      grains.push(i);
    for (let i = 2; i < Math.sqrt(upper_bound); i++)
      for (let j = i*i; j <= upper_bound; j+=i)
        if (grains[j] != 0) grains[j] = 0;
    return grains.filter(function(x) {return x != 0});
  }

//next function find prime factorization of base (array of couples: prime and its degree)
  function factorization(base_number_system, prime_numbers) {
  let prime_dividers = [];
  for (let i = 0; prime_numbers[i] <= base; i++) {
    let p = prime_numbers[i], count = 0;
    while ((base_number_system >= prime_numbers[i]) && (base_number_system % prime_numbers[i] == 0)) {
      base_number_system = base_number_system / prime_numbers[i];
      p = prime_numbers[i];  
      count++;
    }
    if (count)
      prime_dividers.push([p, count]);
    }
  return prime_dividers;
  }

// Next function find how many zeros in the end of number, which is factorial of `number` in `prime_base` base system
  function getZerosForPrimeBase(number, prime_base) {
    let zeros = 0;
    for (let i = 1; Math.pow(prime_base, i) <= number; i++)
      zeros += Math.floor(number / Math.pow(prime_base, i));
    return zeros;
  }

//let's do it
//first, we seek prime numbers
prime_numbers_before_base = sieve(base);

//second, we add number of zeros to our array of couples and get array of trios: [prime, its degree, zeros]
  candidates = factorization(base, prime_numbers_before_base);
  for (let i = 0; i < candidates.length; i++) 
    candidates[i].push(getZerosForPrimeBase(number, candidates[i][0]));

//and finally, we will chose THE ONE (just believe me, Neo)
  neo = candidates.reduce(function(x, y) {return ((x[2] / x[1]) < (y[2] / y[1]))?x:y;});
  return Math.floor(neo[2] / neo[1]);
} 
/*******************************************************************************
 * Copyright (C) 2021 Mohd Hariz Afiq Bin Abdul Rahman
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ******************************************************************************/
package com.harix.VoucherSystem.SpecialOffer;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping(value = "/api/specialoffer")
public class SpecialOfferController {

	@Autowired
	private SpecialOfferService spOfferService;
	
	@PostMapping(value = "/create")
	public Optional<SpecialOffer> createNewSpecialOffer(@Validated @RequestBody SpecialOffer spOffer) {
		return spOfferService.createNewSpecialOffer(spOffer);
	}
	
	@GetMapping(value = "/list")
	public List<SpecialOffer> retrieveAllSpecialOffer(){
		return spOfferService.listSpecialOffer();
	}
	
	@DeleteMapping(value = "/delete/{id}")
	public void deleteSpecialOffer(@PathVariable(value = "id") int spOfferId) {
		spOfferService.deleteSpecialOffer(spOfferId);
	}
}

package cn.xishan.oftenporter.demo.oftendb.base;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import cn.xishan.oftenporter.oftendb.data.impl.MysqlSource;
import cn.xishan.oftenporter.oftendb.db.DBException;
import cn.xishan.oftenporter.oftendb.db.DBHandle;
import cn.xishan.oftenporter.oftendb.db.mysql.SqlHandle;
import cn.xishan.oftenporter.porter.core.util.WPTool;

public class SqlDBSource extends MysqlSource
{

    public SqlDBSource()
    {
        super((wObject, configed, configing) -> configing.setCollectionName("test1"));
        Connection connection = null;
        Statement statement = null;
        try
        {
            String initSql =
                    "CREATE TABLE IF NOT EXISTS `test1` (\n" + "  `_id` char(32) NOT NULL,\n"
                            + "  `name` varchar(35) NOT NULL,\n"
                            + "  `age` int(11) NOT NULL,\n"
                            + "  `sex` varchar(2) NOT NULL,\n"
                            + "  `time` datetime NOT NULL,\n"
                            + "  PRIMARY KEY (`_id`)\n"
                            + ") ENGINE=InnoDB DEFAULT CHARSET=utf8";
            connection = getConn();
             statement = connection.createStatement();
            statement.execute(initSql);
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            WPTool.close(statement);
            WPTool.close(connection);
        }
    }

    @Override
    public Connection getConnection()
    {
        return getConn();
    }

    private Connection getConn()
    {

        try
        {
            Class.forName("org.h2.Driver");
            Connection conn = DriverManager.getConnection(
                    "jdbc:h2:~/PorterDemo/oftendb;MODE=MySQL", "sa", "");
            return conn;
        } catch (Exception e)
        {
            throw new DBException(e);
        }

    }

    @Override
    public DBHandle getDBHandle()
            throws DBException
    {
        SqlHandle sqlHandle = new SqlHandle(getConn());
        return sqlHandle;
    }

}

package com.githup.hicoincom.exception;

/**
 * @author ZPZ
 */
public class ArgsNullException extends RuntimeException{
    public ArgsNullException(){ super();}
    public ArgsNullException(String msg){super(msg);}
}

/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE126_Buffer_Overread__new_char_loop_83_goodG2B.cpp
Label Definition File: CWE126_Buffer_Overread__new.label.xml
Template File: sources-sink-83_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 126 Buffer Over-read
 * BadSource:  Use a small buffer
 * GoodSource: Use a large buffer
 * Sinks: loop
 *    BadSink : Copy data to string using a loop
 * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE126_Buffer_Overread__new_char_loop_83.h"

namespace CWE126_Buffer_Overread__new_char_loop_83
{
CWE126_Buffer_Overread__new_char_loop_83_goodG2B::CWE126_Buffer_Overread__new_char_loop_83_goodG2B(char * dataCopy)
{
    data = dataCopy;
    /* FIX: Use a large buffer */
    data = new char[100];
    memset(data, 'A', 100-1); /* fill with 'A's */
    data[100-1] = '\0'; /* null terminate */
}

CWE126_Buffer_Overread__new_char_loop_83_goodG2B::~CWE126_Buffer_Overread__new_char_loop_83_goodG2B()
{
    {
        size_t i, destLen;
        char dest[100];
        memset(dest, 'C', 100-1);
        dest[100-1] = '\0'; /* null terminate */
        destLen = strlen(dest);
        /* POTENTIAL FLAW: using length of the dest where data
         * could be smaller than dest causing buffer overread */
        for (i = 0; i < destLen; i++)
        {
            dest[i] = data[i];
        }
        dest[100-1] = '\0';
        printLine(dest);
        delete [] data;
    }
}
}
#endif /* OMITGOOD */

package com.fich.wafproject.dao;
 
import com.fich.wafproject.model.Event;
import java.util.List;
 
public interface EventDao {
 
    void saveEvent(Event event);
    
    Event findByTransactionId(String transactionId);
    
    List<Event> findAllEvent(int pageNumber, String[] targets, String[] names, String[] values, boolean pagination);
    
    List<Event> findAllEvent();
    
    Event findById(Integer id);
    
    List<Event> findEventsByProperties(String[] properties, String[] values);
    
    public void delete(Integer id);
    
    public void deletAll();
     
}
#include "../../non_core/joypad.h"

#if defined(_WIN32) || defined(_MSC_VER) || defined(__ANDROID__)
#include "SDL.h"
#else 
#include <SDL2/SDL.h>
#endif

#if defined(__ANDROID__) 
#include <jni.h>
#endif

#ifdef PSVITA
#include <psp2/ctrl.h>
#endif

#include "stdlib.h"
#include "../../core/mmu/mbc.h"
#include "../../non_core/logger.h"

SDL_Joystick *joystick;

typedef struct {
    int x;
    int y;
    int w;
    int h;
} b_rect;

typedef struct {
    int key_code; // Key code on the keyboard which
                       // maps to the given gameboy button
    int state; // 1 pressed, 0 unpressed
    b_rect rect;
} button_state;


enum {UP = 0, DOWN, LEFT, RIGHT, A, B, START, SELECT};

#if defined(__SWITCH__)
#define JOY_A     0
#define JOY_B     1
#define JOY_X     2
#define JOY_Y     3
#define JOY_PLUS  10
#define JOY_MINUS 11
#define JOY_LEFT  12
#define JOY_UP    13
#define JOY_RIGHT 14
#define JOY_DOWN  15

int button_config[] = {JOY_UP, JOY_DOWN, JOY_LEFT, JOY_RIGHT, JOY_A, JOY_B, JOY_PLUS, JOY_MINUS};

#elif defined(PSVITA)

#define SDLK_VITA_TRIANGLE 0
#define SDLK_VITA_CIRCLE 1 
#define SDLK_VITA_CROSS 2
#define SDLK_VITA_SQUARE 3

#define SDLK_VITA_LTRIGGER 4
#define SDLK_VITA_RTRIGGER 5

#define SDLK_VITA_DOWN 6
#define SDLK_VITA_LEFT 7
#define SDLK_VITA_UP 8
#define SDLK_VITA_RIGHT 9

#define SDLK_VITA_SELECT 10
#define SDLK_VITA_START 11

int button_config[] = {SDLK_VITA_UP, SDLK_VITA_DOWN, SDLK_VITA_LEFT, SDLK_VITA_RIGHT
    , SDLK_VITA_CROSS, SDLK_VITA_CIRCLE, SDLK_VITA_START, SDLK_VITA_SELECT};

#else

int button_config[] = {SDLK_UP, SDLK_DOWN, SDLK_LEFT, SDLK_RIGHT, SDLK_a, SDLK_s, SDLK_RETURN, SDLK_SPACE};

#endif

button_state buttons[8];

#define TOTAL_BUTTONS (sizeof(buttons)/sizeof(buttons[0]))

static SDL_DisplayMode current;
static SDL_Haptic *haptic;
static int rumble_on = 0; // If rumble is activated

#if defined(__ANDROID__) 
static void vibrate() {

    // Retrieve the JNI environment
    JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();

    // retrieve the Java instance of the SDL Activity
    jobject activity = (jobject)SDL_AndroidGetActivity();

    // find the Java class of the activity. It should be SDLActivity or a subclass of it.
    jclass c = (*env)->GetObjectClass(env, activity);
    if (c == 0) {
        log_message(LOG_ERROR, "JNI: Unable to find the \"PlutoboyActivity\" class\n");
        return ; 
    }

    // Get the Vibrate method id
    jmethodID mid = (*env)->GetMethodID(env, c, "vibrate", "()V");
    if (mid == 0) {
        log_message(LOG_ERROR, "JNI: Unable to find the \"vibrate\" method id\n");
        return ; 
    }
    
    (*env)->CallVoidMethod(env, activity, mid); 

    // clean up the local references.
    (*env)->DeleteLocalRef(env, activity);
    (*env)->DeleteLocalRef(env, c);
}
#endif


static int isValidEvent(void * userdata, SDL_Event* event)
{
    return event->type == SDL_QUIT ||
           event->type == SDL_KEYDOWN || 
           event->type == SDL_KEYUP || 
           event->type == SDL_JOYBUTTONDOWN || 
           event->type == SDL_JOYBUTTONUP || 
           event->type == SDL_FINGERUP || 
           event->type == SDL_FINGERDOWN || 
           event->type == SDL_FINGERMOTION; 
}

/*  Intialize the joypad, should be called before any other
 *  joypad functions */
void init_joypad() { 

    #if defined(__ANDROID__)   
    rumble_on = 1;
    #else
    rumble_on = 0;
    #endif

    joystick = 0;
    if (SDL_NumJoysticks() > 0) {
        joystick = SDL_JoystickOpen(0);
    }

#ifndef PSVITA 
    // Attempt to setup Haptic Feedback
    haptic = SDL_HapticOpen(0);
    if (haptic == NULL) {
        log_message(LOG_WARN, "Unable to open haptic device %s\n", SDL_GetError());
    } else {
        if (haptic != NULL && SDL_HapticRumbleInit(haptic) != 0) {
            rumble_on = 1;
        } else {
            log_message(LOG_WARN, "Unable to initialize rumble %s\n", SDL_GetError());
        }
    } 
#endif
    // Setup buttons 
    SDL_GetCurrentDisplayMode(0, &current);    
     
    buttons[UP].state = 0;
    buttons[UP].key_code = button_config[UP];
    b_rect rect_u = {DPAD_UP_X, DPAD_UP_Y(current.h), DPAD_UP_W, DPAD_UP_H};
    buttons[UP].rect = rect_u;

    buttons[DOWN].state = 0;
    buttons[DOWN].key_code = button_config[DOWN];
    b_rect rect_d = {DPAD_DOWN_X, DPAD_DOWN_Y(current.h), DPAD_DOWN_W, DPAD_DOWN_H};
    buttons[DOWN].rect = rect_d; 

    buttons[LEFT].state = 0;
    buttons[LEFT].key_code = button_config[LEFT];
    b_rect rect_l = {DPAD_LEFT_X, DPAD_LEFT_Y(current.h), DPAD_LEFT_W, DPAD_LEFT_H};
    buttons[LEFT].rect = rect_l; 

    buttons[RIGHT].state = 0;
    buttons[RIGHT].key_code = button_config[RIGHT];
    b_rect rect_r = {DPAD_RIGHT_X, DPAD_RIGHT_Y(current.h), DPAD_RIGHT_W, DPAD_RIGHT_H};
    buttons[RIGHT].rect = rect_r; 

    buttons[A].state = 0;
    buttons[A].key_code = button_config[A];
    b_rect rect_a = {A_X(current.w), A_Y(current.h), A_W, A_H};
    buttons[A].rect = rect_a; 

    buttons[B].state = 0;
    buttons[B].key_code = button_config[B];
    b_rect rect_b = {B_X(current.w), B_Y(current.h), B_W, B_H};
    buttons[B].rect = rect_b; 

    buttons[START].state = 0;
    buttons[START].key_code = button_config[START];
    b_rect rect_st = {START_X, START_Y(current.h), START_W, START_H};
    buttons[START].rect = rect_st; 
   
    buttons[SELECT].state = 0;
    buttons[SELECT].key_code = button_config[SELECT];
    b_rect rect_se = {SELECT_X, SELECT_Y(current.h), SELECT_W, SELECT_H};
    buttons[SELECT].rect = rect_se; 

    SDL_SetEventFilter(isValidEvent, NULL);
}

/* Check each individual GameBoy key. Returns 1 if
 * the specified key is being held down, 0 otherwise */
int down_pressed()   { return buttons[DOWN].state;  }  
int up_pressed()     { return buttons[UP].state; }
int left_pressed()   { return buttons[LEFT].state;}
int right_pressed()  { return buttons[RIGHT].state;} 
int a_pressed()      { return buttons[A].state; }
int b_pressed()      { return buttons[B].state;}
int start_pressed()  { return buttons[START].state; }
int select_pressed() { return buttons[SELECT].state; } 

/* Returns 1 if any of the 8 GameBoy keys are being held down,
 * 0 otherwise */
int key_pressed() {

    return down_pressed() || up_pressed() || left_pressed() || right_pressed()
    || a_pressed() || b_pressed() || start_pressed() || select_pressed();
}


// Given relative screen x and y positions and an on/off state
// sets any buttons those co-ordinates are in to the given state.
void check_keys_pressed(float x, float y, int state) {
    float p_x = x * current.w;
    float p_y = y * current.h;
   
     for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
        if (p_x >= buttons[i].rect.x && 
                p_x <= buttons[i].rect.x + buttons[i].rect.w &&
                p_y >= buttons[i].rect.y &&
                p_y <= buttons[i].rect.y + buttons[i].rect.h) {
            
            // If activating button, send rumble feedback
            if (rumble_on && !buttons[i].state && state) {
               // SDL_HapticRumblePlay(haptic, 0.5, 100);
               #if defined(__ANDROID__)
                  vibrate();
               #endif
            }
            buttons[i].state = state;
            
         }
    }
}

// Given new x/y relative screen positions and x/y movement 
// determines which keys are now pressed
void check_keys_moved(float x, float y, float mv_x, float mv_y) {
    // Pixel positions after movement
    float p_x = x * current.w;
    float p_y = y * current.h;

    // Pixel positions before movement
    float old_p_x = (x - mv_x) * current.w;
    float old_p_y = (y - mv_y) * current.h;
   
    int activated = 0;

     for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
        int was_on = (old_p_x >= buttons[i].rect.x) &&
                     (old_p_x <= buttons[i].rect.x + buttons[i].rect.w) &&
                     (old_p_y >= buttons[i].rect.y) &&
                     (old_p_y <= buttons[i].rect.y + buttons[i].rect.h);

        int is_on = (p_x >= buttons[i].rect.x) && 
                    (p_x <= buttons[i].rect.x + buttons[i].rect.w) &&
                    (p_y >= buttons[i].rect.y) &&
                    (p_y <= buttons[i].rect.y + buttons[i].rect.h);
            
        if (!was_on && is_on) {
            activated = 1;
            buttons[i].state = 1;           
        }

        if (was_on && !is_on) {
            buttons[i].state = 0;
        }    
    } 

         
    // If activating button, send rumble feedback
    if (rumble_on && activated) {
        // SDL_HapticRumblePlay(haptic, 0.5, 100);
        #if defined(__ANDROID__)
        vibrate();
        #endif
    }
}


void unset_keys() {
    for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
        buttons[i].state = 0;
    }
}


/* Update current state of GameBoy keys as well as control
 * other external actions for the emulator */
int update_keys() {
        SDL_Event event;

        if (SDL_PollEvent(&event)) {

            switch (event.type) {
                    // exit if the window is closed
                case SDL_QUIT:
                            write_SRAM();
                            return 1;
                            break;

#if !defined(PSVITA) && !defined(__SWITCH__)
                case SDL_KEYDOWN: // Key pressed
                    if (event.key.keysym.sym == SDLK_ESCAPE) {
                        write_SRAM();
                        return 1;
                    }

                    for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
                            if (buttons[i].key_code == event.key.keysym.sym) {
                                buttons[i].state = 1;
                                break;
                            }
                        }
                        break;

                case SDL_KEYUP: //Key released
                    for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
                            if (buttons[i].key_code == event.key.keysym.sym) {
                                buttons[i].state = 0;
                                break;
                            }
                        }
                    break;

#else
                case SDL_JOYBUTTONDOWN:
                case SDL_JOYBUTTONUP:
                    for (size_t i = 0; i < TOTAL_BUTTONS; i++) {
                        if (buttons[i].key_code == event.jbutton.button) {
                            buttons[i].state = (event.jbutton.state == SDL_PRESSED);
                            break;
                        }
                    }
                break;

#endif
#ifndef PSVITA          
                case SDL_FINGERDOWN:
                    check_keys_pressed(event.tfinger.x, event.tfinger.y, 1);
                    break;

                case SDL_FINGERUP:
                    check_keys_pressed(event.tfinger.x, event.tfinger.y, 0);
                    break;

                // Assume only one finger can be on a button at a time considering
                // the size of the buttons. It would be more accurate in the future
                // to keep track of finger ids for each button 
                case SDL_FINGERMOTION:
                    check_keys_moved(event.tfinger.x, event.tfinger.y,
                                     event.tfinger.dx, event.tfinger.dy);
                    break;
                default: 
                    printf("%d\n",  event.type);
                    
#endif
            }                   
        }
    return 0;
}

<?php

/**
 * Module: SmartFAQ
 * Author: The SmartFactory <www.smartfactory.ca>
 * Licence: GNU
 */

use XoopsModules\Smartfaq;

global $xoopsTpl, $xoopsModule;

$uid     = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
$isAdmin = (Smartfaq\Utility::userIsAdmin() || Smartfaq\Utility::hasModerator());

/** @var Smartfaq\Helper $helper */
$helper = Smartfaq\Helper::getInstance();

$xoopsTpl->assign('sf_adminpage', "<a href='" . XOOPS_URL . "/modules/smartfaq/admin/index.php'>" . _MD_SF_ADMIN_PAGE . '</a>');
$xoopsTpl->assign('isAdmin', $isAdmin);

$xoopsTpl->assign(
    [
        'lang_on'       => _MD_SF_ON,
        'lang_postedby' => _MD_SF_POSTEDBY,
        'lang_faq'      => _MD_SF_QUESTION,
        'lang_datesub'  => _MD_SF_DATESUB,
        'lang_hits'     => _MD_SF_HITS,
    ]
);
$xoopsTpl->assign('sectionname', $myts->displayTarea($xoopsModule->getVar('name')));

$xoopsTpl->assign('modulename', $xoopsModule->dirname());
$xoopsTpl->assign('displaylastfaq', $helper->getConfig('displaylastfaq'));
$xoopsTpl->assign('displaysubcatdsc', $helper->getConfig('displaysubcatdsc'));
$xoopsTpl->assign('displaycollaps', $helper->getConfig('displaycollaps'));
$xoopsTpl->assign('display_date_col', $helper->getConfig('display_date_col'));
$xoopsTpl->assign('display_hits_col', $helper->getConfig('display_hits_col'));

$xoopsTpl->assign('displaytopcatdsc', $helper->getConfig('displaytopcatdsc'));

$xoopsTpl->assign('ref_smartfaq', 'SmartFAQ is developed by The SmartFactory (http://www.smartfactory.ca), a division of InBox Solutions (http://www.inboxsolutions.net)');

$xoopsTpl->assign('xoops_module_header', "<link rel='stylesheet' type='text/css' href='" . XOOPS_URL . "/modules/smartfaq/assets/css/smartfaq.css'>");

package com.codepath.apps.restclienttemplate.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.codepath.apps.restclienttemplate.TwitterApp;
import com.codepath.apps.restclienttemplate.TwitterClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Arielle on 03-Mar-18.
 */

public class UserTimelineFragment extends TweetsListFragment {
    TwitterClient client;
    public static UserTimelineFragment newInstance(String  screenName){
       UserTimelineFragment userTimelineFragment = new UserTimelineFragment();
       Bundle args= new Bundle();
       args.putString("screen_name", screenName);
       userTimelineFragment.setArguments(args);
       return userTimelineFragment;


    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        client = TwitterApp.getRestClient();
        populateTimeLine();
    }

    private void populateTimeLine() {
        //comes from the activity
        String screenName = getArguments().getString("screen_name");

        client.getUserTimeline(screenName, new JsonHttpResponseHandler() {
                                   @Override
                                   public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                       Log.d("TwitterClient", response.toString());

                                   }

                                   @Override
                                   public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                                       addItems(response);
                                       //    Log.d("TwitterClient",response.toString());

                                       //iterate trought the JSON array
                                       //for each entry, deserialyze the JSON object
                                       for (int i = 0; i < response.length(); i++) {
                                           //convert each object to a Tweet model
                                           //add that tweet model to our data source
                                           //notify the adapter that we've added an item


                                       }
                                   }

                                   @Override
                                   public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                       Log.d("TwitterClient", responseString);
                                       throwable.printStackTrace();
                                   }

                                   @Override
                                   public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                                       Log.d("TwitterClient", errorResponse.toString());
                                       throwable.printStackTrace();
                                   }

                                   @Override
                                   public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                                       Log.d("TwitterClient", errorResponse.toString());
                                       throwable.printStackTrace();
                                   }


                                           //         Log.d("TwitterClient",response.toString());
            //iterate trought the JSON array
            //for each entry, deserialize the JSON object


        });
}}

package org.apache.kyuubi.engine.spark

import org.apache.curator.framework.CuratorFramework

import org.apache.kyuubi.Utils
import org.apache.kyuubi.config.KyuubiConf
import org.apache.kyuubi.ha.HighAvailabilityConf.{HA_ZK_AUTH_TYPE, HA_ZK_NAMESPACE, HA_ZK_QUORUM}
import org.apache.kyuubi.ha.client.{ZooKeeperAuthTypes, ZooKeeperClientProvider}
import org.apache.kyuubi.zookeeper.{EmbeddedZookeeper, ZookeeperConf}

trait WithDiscoverySparkSQLEngine extends WithSparkSQLEngine {
  private var zkServer: EmbeddedZookeeper = _
  def namespace: String
  override def withKyuubiConf: Map[String, String] = {
    assert(zkServer != null)
    Map(
      HA_ZK_QUORUM.key -> zkServer.getConnectString,
      HA_ZK_AUTH_TYPE.key -> ZooKeeperAuthTypes.NONE.toString,
      HA_ZK_NAMESPACE.key -> namespace)
  }

  override def beforeAll(): Unit = {
    zkServer = new EmbeddedZookeeper()
    val zkData = Utils.createTempDir()
    val tmpConf = KyuubiConf()
    tmpConf.set(ZookeeperConf.ZK_CLIENT_PORT, 0)
    tmpConf.set(ZookeeperConf.ZK_DATA_DIR, zkData.toString)
    zkServer.initialize(tmpConf)
    zkServer.start()
  }

  override def afterAll(): Unit = {
    if (zkServer != null) {
      zkServer.stop()
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    startSparkEngine()
  }

  override protected def afterEach(): Unit = {
    super.afterEach()
    stopSparkEngine()
  }

  def withZkClient(f: CuratorFramework => Unit): Unit = {
    ZooKeeperClientProvider.withZkClient(kyuubiConf)(f)
  }

  protected def getDiscoveryConnectionString: String = {
    if (zkServer == null) {
      ""
    } else {
      zkServer.getConnectString
    }
  }
}
---
title: "Recitation 3 Note"
author: "Yiming Gong"
date: "2021-07-22T02:56:26Z"
link: "https://bookdown.org/yg484/rec_3_note/"
length_weight: "7.8%"
pinned: false
---

This is class note for recitation 3 on July 22th. [...] restrict the time scale to two instants only: The price of one share at time \(t\) will be denoted by \(S(t)\). The
current stock price \(S(0)\) is known to all investors \(A(t)\) and \(A(0)\) \[
S(t)-S(0)
\] The return is defined as: \[
K_S = \frac{S(t)-S(0)}{S(0)}, t= 1
\] Is the return \(K_S\) a fixed value or a random value? Similar for return of bond: \[
K_A = \frac{A(t)-A(0)}{A(0)}, t = 1
\] Is the return \(K_A\) a fixed value or a random value? The future stock price \(S(1)\) is a random variable with at least two
different ...

'use strict';

var memo = require('./');

/**
 * When a string is passed, a function is returned
 */

var cwd = memo(process.cwd());

// use `cwd`
var foo = cwd('foo');
var bar = cwd('bar');
var baz = cwd('baz');

// use `foo`
var qux = foo('a/b/c');
// use `qux`
var fez = qux('x/y/z');

/**
 * Get a memoized path by calling the function
 */

console.log(cwd());
//=> /User/dev/memo-path
console.log(foo());
//=> /User/dev/memo-path/foo
console.log(bar());
//=> /User/dev/memo-path/bar
console.log(baz());
//=> /User/dev/memo-path/baz
console.log(qux());
//=> /User/dev/memo-path/foo/a/b/c
console.log(fez());
//=> /User/dev/memo-path/foo/a/b/c/x/y/z


/**
 * The memoized path is also exposed on the function's `.path` property
 */

console.log(cwd.path);
//=> /User/dev/memo-path
console.log(foo.path);
//=> /User/dev/memo-path/foo
console.log(bar.path);
//=> /User/dev/memo-path/bar
console.log(baz.path);
//=> /User/dev/memo-path/baz
console.log(qux.path);
//=> /User/dev/memo-path/foo/a/b/c
console.log(fez.path);
//=> /User/dev/memo-path/foo/a/b/c/x/y/z

<?php 
namespace App\Http\Controllers;

use App\Language;
    use App\Film;

     
class LanguageController extends Controller {

    /**
    * Display a listing of the resource.
    *
    * @return  Response
    */
    public function index()
    {
        request()->session()->forget("keyword");
        request()->session()->forget("clear");
        request()->session()->forget("defaultSelect");
        session(["mutate" => '1']);


        return view('language_show', ['languages' => Language::paginate(20)]);
    }

    /**
    * Show the form for creating a new resource.
    *
    * @return  Response
    */
    public function create()
    {
        return view('language');
    }

    /**
    * Store a newly created resource in storage.
    *
    * @return  Response
    */
    public function store()
    {
            $data = request()->all();

    $language = Language::create([
             "name" => $data["name"],
          ]);

      
        return redirect('/language');;
    }

    /**
    * Display the specified resource.
    *
    * @param    Mixed
    * @return  Response
    */
    public function show(Language $language )
    {
        request()->session()->forget("mutate");
        $language->load(array("film",));
        return view('language_display', compact('language'));        }

    /**
    * Show the form for editing the specified resource.
    *
    * @param    Mixed
    * @return  Response
    */
    public function edit(Language $language )
    {
        request()->session()->forget("mutate");
        $language->load(array("film",));
        return view('language_edit', compact('language'));
    }

    /**
    * Update the specified resource in storage.
    *
    * @param    Mixed
    * @return  Response
    */
    public function update(Language $language )
    {
            $language->update(request()->all());

        return back();
    }

    /**
    * Remove the specified resource from storage.
    *
    * @param    Mixed
    * @return  Response
    */
    public function destroy(Language $language )
    {
            $language->delete();
        return back();
    }

    /**
    * Load and display related tables.
    * @param    Mixed
    * @return  Response
    */
    public function related(Language $language ){

        session(["mutate" => '1']);
        if(request()->exists('cs')){
            request()->session()->forget("keyword");
            return back();
        }

        if(request()->exists('tab') && session("clear", "none") != request()->get('tab')){
            request()->session()->forget("keyword");
            session(["clear" => request()->get('tab')]);
        }

        $table = request()->get('tab');
        $language->load(array("film",));
return view('language_related', compact(['language', 'table']));
    }

    /**
    * Search Table element By keyword
    * @return  Response
    */
    public function search(){
        $keyword = request()->get('keyword');

        if(request()->exists('tab')){
            session(['keyword' => $keyword]);
            return back();
        }

        session(["keyword" => $keyword]);

        $keyword = '%'.$keyword.'%';

        $languages = Language::where('language_id', 'like', $keyword)
         ->orWhere('language_id', 'like', $keyword)

         ->orWhere('name', 'like', $keyword)

         ->orWhere('last_update', 'like', $keyword)

        ->paginate(20);
    $languages->setPath("search?keyword=$keyword");
    return view('language_show', compact('languages'));
    }

    /**
    * Sort Table element
    * @return  Response
    */
    public function sort(){
        $path = "";

            request()->session()->forget("sortKey");
    request()->session()->forget("sortOrder");
    if(!request()->exists('tab')){
$languages = Language::query();
         if(request()->exists('name')){
            $languages = $languages->orderBy('name', $this->getOrder('name'));
            $path = "name";
        }else{
            request()->session()->forget("name");
        }
          $languages = $languages->paginate(20);
        $languages->setPath("sort?$path");
        return view('language_show', compact('languages'));

    }else{

    if(request()->exists('tab') == 'film'){

                  if(request()->exists('title')){
             session(['sortOrder' => $this->getOrder('title')]);
             session(['sortKey' => 'title']);
        }else{
            request()->session()->forget("title");
        }

                 if(request()->exists('description')){
             session(['sortOrder' => $this->getOrder('description')]);
             session(['sortKey' => 'description']);
        }else{
            request()->session()->forget("description");
        }

                 if(request()->exists('release_year')){
             session(['sortOrder' => $this->getOrder('release_year')]);
             session(['sortKey' => 'release_year']);
        }else{
            request()->session()->forget("release_year");
        }

                  if(request()->exists('rental_duration')){
             session(['sortOrder' => $this->getOrder('rental_duration')]);
             session(['sortKey' => 'rental_duration']);
        }else{
            request()->session()->forget("rental_duration");
        }

                 if(request()->exists('rental_rate')){
             session(['sortOrder' => $this->getOrder('rental_rate')]);
             session(['sortKey' => 'rental_rate']);
        }else{
            request()->session()->forget("rental_rate");
        }

                 if(request()->exists('length')){
             session(['sortOrder' => $this->getOrder('length')]);
             session(['sortKey' => 'length']);
        }else{
            request()->session()->forget("length");
        }

                 if(request()->exists('replacement_cost')){
             session(['sortOrder' => $this->getOrder('replacement_cost')]);
             session(['sortKey' => 'replacement_cost']);
        }else{
            request()->session()->forget("replacement_cost");
        }

                    }
             return back();
    }
    }

    /**
    * Clear Search Pattern
    *
    */
    public function clearSearch(){
        request()->session()->forget("keyword");
        return back();
    }



    function addFilm(Language $language ){
    $language->film()->sync(request()->get('film'));
    return back();
}
 
    private function getOrder($param){
        if(session($param, "none") != "none"){
            session([$param => session($param, 'asc') == 'asc' ? 'desc':'asc']);
        }else{
            session([$param => 'asc']);
        }
        return session($param);
    }



}


package ru.rsmu.olympreg.utils.restconnector.examsapimodel;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;

/**
 * @author leonid.
 */
@XmlRootElement( name = "exam" )
public class ExamFacade {
    private long id;
    private String subject;
    private String eventType;
    private String name;
    private Date date;


    public long getId() {
        return id;
    }

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

    public String getSubject() {
        return subject;
    }

    public void setSubject( String subject ) {
        this.subject = subject;
    }

    public String getEventType() {
        return eventType;
    }

    public void setEventType( String eventType ) {
        this.eventType = eventType;
    }

    public String getName() {
        return name;
    }

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

    public Date getDate() {
        return date;
    }

    public void setDate( Date date ) {
        this.date = date;
    }
}

require "application_system_test_case"

class InstitutionsTest < ApplicationSystemTestCase
  setup do
    @institution = institutions(:one)
  end

  test "visiting the index" do
    visit institutions_url
    assert_selector "h1", text: "Institutions"
  end

  test "creating a Institution" do
    visit institutions_url
    click_on "New Institution"

    fill_in "Description", with: @institution.description
    fill_in "Name", with: @institution.name
    click_on "Create Institution"

    assert_text "Institution was successfully created"
    click_on "Back"
  end

  test "updating a Institution" do
    visit institutions_url
    click_on "Edit", match: :first

    fill_in "Description", with: @institution.description
    fill_in "Name", with: @institution.name
    click_on "Update Institution"

    assert_text "Institution was successfully updated"
    click_on "Back"
  end

  test "destroying a Institution" do
    visit institutions_url
    page.accept_confirm do
      click_on "Destroy", match: :first
    end

    assert_text "Institution was successfully destroyed"
  end
end

import axiosWithAuth from "../../utils/axiosWithAuth.js";

export const LOADING_START = "LOADING_START";
export const LOADING_DONE = "LOADING_DONE";
export const LOGIN_FAILED = "LOGIN_FAILED";
export const LOGOUT = "LOGOUT";
export const SET_CURRENT_USER = "SET_CURRENT_USER";
export const SET_OTHER_USER = "SET_OTHER_USER";
export const WIPE_OTHER_USER = "WIPE_OTHER_USER";
export const SAVED_JOBS = "SAVED_JOBS";
export const DELETE_JOBS = "DELETE_JOBS";
export const DELETE_APPLIED = "DELETE_APPLIED";
export const GET_SAVED_APPLIED_JOBS = "GET_SAVED_APPLIED_JOBS";
export const APPLIED_JOBS = "APPLIED_JOBS";

// export const loadingStart = () =>{
//     return { type: LOADING_START, payload: null };
// }
export const loadingDone = () => {
  return { type: LOADING_DONE, payload: null };
};
export const login = (user) => {
  return { type: SET_CURRENT_USER, payload: user };
};
export const logout = () => {
  return { type: LOGOUT, payload: null };
};
export const getCurrentUser = () => (dispatch) => {
  axiosWithAuth()
    .get("/users/user")
    .then((res) => {
      dispatch({ type: SET_CURRENT_USER, payload: res.data });
    })
    .catch((err) => {
      dispatch({ type: LOGIN_FAILED, payload: err });
      console.log("GetCurrentUser CATCH ERROR: ", err.response.data.message);
    });
  return null;
};

export const updateUser = (userObj, setLoading) => (dispatch) => {
  axiosWithAuth()
    .put(`/users/user`, userObj)
    .then((res) => {
      console.log("update user", res);
      dispatch({ type: SET_CURRENT_USER, payload: res.data });
      dispatch({ type: SET_OTHER_USER, payload: res.data });
    })
    .catch((err) => {
      setLoading(false);
      console.log("updateUser CATCH ERROR: ", err.response.data.message);
      alert(err.response.data.message);
    });
  return null;
};

export const updateProfilePicture = (formData, setPictureLoading) => (
  dispatch
) => {
  // console.log('updateProfilePicture firing', formData);
  axiosWithAuth()
    .put("/users/user/picture", formData)
    .then((res) => {
      console.log("updateProfilePicture res: ", res);
      dispatch({ type: SET_CURRENT_USER, payload: res.data });
      setPictureLoading(false);
    })
    .catch((err) => {
      console.log(
        "updateProfilePicture CATCH ERROR: ",
        err.response.data.message
      );
      alert(err.response.data.message);
      setPictureLoading(false);
    });
  return null;
};
export const deleteProfilePicture = (setPictureLoading) => (dispatch) => {
  console.log("deleteProfilePicture firing");
  axiosWithAuth()
    .delete("/users/user/picture")
    .then((res) => {
      dispatch({ type: SET_CURRENT_USER, payload: { profile_img: "" } });
      setPictureLoading(false);
    })
    .catch((err) => {
      console.log(
        "deleteProfilePicture CATCH ERROR: ",
        err.response.data.message
      );
      alert(err.response.data.message);
      setPictureLoading(false);
    });
  return null;
};

export const updateSaved = (saved, user_id) => (dispatch) => {
  axiosWithAuth()
    .post("/saved/", saved)
    .then((res) => {
      axiosWithAuth()
        .get(`/saved/${user_id}`)
        .then((res) => {
          dispatch({ type: SAVED_JOBS, payload: res.data });
        })
        .catch((error) => {
          console.error(error.message);
        });
    })
    .catch((err) => {
      console.log(err);
    });
  return null;
};

export const deleteSaved = (job_id) => (dispatch) => {
  axiosWithAuth()
    .delete(`/saved/${job_id}`)
    .then((res) => {
      dispatch({ type: DELETE_JOBS, payload: job_id });
    })
    .catch((err) => {
      console.log(err);
    });
  return null;
};

export const deleteApplied = (job_id) => (dispatch) => {
  axiosWithAuth()
    .delete(`/saved/${job_id}`)
    .then((res) => {
      dispatch({ type: DELETE_APPLIED, payload: job_id });
    })
    .catch((err) => {
      console.log(err);
    });
  return null;
};

export const getSavedAppliedJobs = (user_id) => (dispatch) => {
  axiosWithAuth()
    .get(`/saved/${user_id}`)
    .then((res) => {
      dispatch({ type: GET_SAVED_APPLIED_JOBS, payload: res.data });
    })
    .catch((error) => {
      console.error(error.message);
    });
};

export const updateApplied = (applied, user_id) => (dispatch) => {
  axiosWithAuth()
    .post("/saved/", applied)
    .then((res) => {
      axiosWithAuth()
        .get(`/saved/${user_id}`)
        .then((res) => {
          dispatch({ type: APPLIED_JOBS, payload: res.data });
        })
        .catch((error) => {
          console.error(error.message);
        });
    })
    .catch((err) => {
      console.log(err);
    });
};

<?php
/* @var $this InvoiceHeaderController */
/* @var $model InvoiceHeader */

$this->breadcrumbs = array(
    'Invoice Headers' => array('admin'),
    'Manage',
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
    $('.search-form').slideToggle(600);
    $('.bulk-action').toggle();
    $(this).toggleClass('active');
    if ($(this).hasClass('active')) {
            $(this).text('');
    } else {
            $(this).text('Advanced Search');
    }
    return false;
});

$('#invoiceSearch').submit(function(){
    $('#invoice-header-grid').yiiGridView('update', {
        data: $(this).serialize()
    });
    return false;
});
");
?>

<div id="maincontent">
    <div class="row">
        <div class="small-12 columns">
            <div class="clearfix page-action">
                <!-- <a class="button success right" href="<?php //echo Yii::app()->baseUrl.'/transaction/invoiceHeader/create'; ?>"><span class="fa fa-plus"></span>Create Invoice Headers</a> -->
                <h2>Manage Invoice Headers</h2>
            </div>

            <div class="search-bar">
                <div class="clearfix button-bar">
                    <div class="form">
                        <?php $form = $this->beginWidget('CActiveForm', array(
                            'action' => Yii::app()->createUrl($this->route),
                            'method' => 'get',
                            'id' => 'invoiceSearch',
                        )); ?>

                        <div class="row">
                            <div class="medium-6 columns">
                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <?php echo $form->label($model, 'customer_name', array('class' => 'prefix')); ?>
                                        </div>
                                        <div class="small-8 columns">
                                            <?php echo $form->textField($model, 'customer_name'); ?>
                                        </div>
                                    </div>
                                </div>	
                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <?php echo $form->label($model, 'customer_type', array('class' => 'prefix')); ?>
                                        </div>
                                        <div class="small-8 columns">
                                            <?php echo $form->dropDownList($model, 'customer_type', array('Individual' => 'Individual', 'Company' => 'Company',), array('prompt' => 'Select',)); ?>
                                        </div>
                                    </div>
                                </div>

                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <label class="prefix"><?php echo $form->labelEx($model, 'invoice_date'); ?></label>
                                        </div>
                                        <div class="small-8 columns">
                                            <div class="row">
                                                <div class="medium-5 columns">
                                                    <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                                        'model' => $model,
                                                        'attribute' => "invoice_date",
                                                        // additional javascript options for the date picker plugin
                                                        'options' => array(
                                                            'dateFormat' => 'yy-mm-dd',
                                                        //'changeMonth'=>true,
                                                        // 'changeYear'=>true,
                                                        // 'yearRange'=>'1900:2020'
                                                        ),
                                                        'htmlOptions' => array(),
                                                    )); ?>
                                                    <?php echo $form->error($model, 'invoice_date'); ?>

                                                </div>
                                                <div class="medium-7 columns">
                                                    <div class="field">
                                                        <div class="row collapse">
                                                            <div class="small-4 columns">
                                                                <label class="prefix">To</label>
                                                            </div>
                                                            <div class="small-8 columns">
                                                                <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                                                    'model' => $model,
                                                                    'attribute' => "invoice_date_to",
                                                                    // additional javascript options for the date picker plugin
                                                                    'options' => array(
                                                                        'dateFormat' => 'yy-mm-dd',
                                                                    //             'changeMonth'=>true,
                                                                    // 'changeYear'=>true,
                                                                    // 'yearRange'=>'1900:2020'
                                                                    ),
                                                                    'htmlOptions' => array(),
                                                                )); ?>
                                                            </div>
                                                        </div>
                                                    </div>

                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>	

                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <label class="prefix"><?php echo $form->labelEx($model, 'due_date'); ?></label>
                                        </div>
                                        <div class="small-8 columns">
                                            <div class="row">
                                                <div class="medium-5 columns">
                                                    <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                                        'model' => $model,
                                                        'attribute' => "due_date",
                                                        // additional javascript options for the date picker plugin
                                                        'options' => array(
                                                            'dateFormat' => 'yy-mm-dd',
                                                        //             'changeMonth'=>true,
                                                        // 'changeYear'=>true,
                                                        // 'yearRange'=>'1900:2020'
                                                        ),
                                                        'htmlOptions' => array(),
                                                    )); ?>
                                                    <?php echo $form->error($model, 'due_date'); ?>
                                                </div>
                                                <div class="medium-7 columns">
                                                    <div class="field">
                                                        <div class="row collapse">
                                                            <div class="small-4 columns">
                                                                <label class="prefix">To</label>
                                                            </div>
                                                            <div class="small-8 columns">
                                                                <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                                                    'model' => $model,
                                                                    'attribute' => "due_date_to",
                                                                    // additional javascript options for the date picker plugin
                                                                    'options' => array(
                                                                        'dateFormat' => 'yy-mm-dd',
                                                                    //             'changeMonth'=>true,
                                                                    // 'changeYear'=>true,
                                                                    // 'yearRange'=>'1900:2020'
                                                                    ),
                                                                    'htmlOptions' => array(),
                                                                )); ?>
                                                                <?php echo $form->error($model, 'due_date_to'); ?>
                                                            </div>
                                                        </div>
                                                    </div>															
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>	
                            </div>	
                            <div class="medium-6 columns">

                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <?php echo $form->label($model, 'invoice_number', array('class' => 'prefix')); ?>
                                        </div>
                                        <div class="small-8 columns">
                                            <?php echo $form->textField($model, 'invoice_number'); ?>
                                        </div>
                                    </div>
                                </div>	

                                <div class="field">
                                    <div class="row collapse">
                                        <div class="small-4 columns">
                                            <?php echo $form->label($model, 'status', array('class' => 'prefix')); ?>
                                        </div>
                                        <div class="small-8 columns">						
                                            <?php echo $form->dropDownList($model, 'status', array('PAID' => 'PAID', 'NOT PAID' => 'NOT PAID',), array('prompt' => 'Select',)); ?>
                                        </div>
                                    </div>
                                </div>	

                                <div class="buttons text-right">
                                    <?php echo CHtml::submitButton('Search', array('class' => 'button cbutton')); ?>
                                </div>

                            </div>
                        </div>

                        <?php $this->endWidget(); ?>
                    </div>
                </div>
            </div>

            <div class="grid-view">
                <?php $this->widget('zii.widgets.grid.CGridView', array(
                    'id' => 'invoice-header-grid',
                    'dataProvider' => $model->search(),
                    'filter' => $model,
                    // 'summaryText'=>'',
                    'rowCssClassExpression' => '(($data->status == "PAID")?"hijau":"merah")',
                    'template' => '{items}<!--<div class="clearfix">{summary}{pager}</div>-->',
                    'pager' => array(
                        'cssFile' => false,
                        'header' => '',
                    ),
                    'columns' => array(
                        array(
                            'class' => 'CCheckBoxColumn', //CHECKBOX COLUMN ADDED.
                            'selectableRows' => 2, //MULTIPLE ROWS CAN BE SELECTED.
                            'checked' => function($data) use($prChecked) {
                                return in_array($data->id, $prChecked);
                            },
                        ),
                        array(
                            'name' => 'invoice_number', 
                            'value' => 'CHtml::link($data->invoice_number, array("view", "id"=>$data->id))', 
                            'type' => 'raw'
                        ),
                        'invoice_date',
                        'due_date',
                        array(
                            'name' => 'reference_type', 
                            'value' => '$data->reference_type == 1 ? "Sales Order" : "Retail Sales"'
                        ),
                        array(
                            'name' => 'sales_order_id', 
                            'value' => '$data->sales_order_id != null ? $data->salesOrder->sale_order_no : CHtml::link($data->registrationTransaction->sales_order_number, array("/frontDesk/registrationTransaction/view", "id"=>$data->registration_transaction_id))',
                            'type' => 'raw'
                        ),
                        array(
                            'header' => 'WO #', 
                            'value' => '$data->sales_order_id != null ? "" : $data->registrationTransaction->work_order_number'
                        ),
                        array(
                            'name' => 'customer_id', 
                            'value' => '$data->customer_id != null ? $data->customer->name : ""'
                        ),
                        array(
                            'name' => 'customer_type', 
                            'value' => '$data->customer_id != null ? $data->customer->customer_type : ""'
                        ),
                        'status',
                    ),
                )); ?>

                <div class="button-group">
                    <?php if (Yii::app()->user->checkAccess("saleInvoiceEdit")): ?>
                        <?php echo CHtml::button("View Invoice", array("id" => "btnProses", 'class' => 'button cbutton')); ?>
                    <?php endif; ?>
                    <?php if (Yii::app()->user->checkAccess("saleInvoiceEdit")): ?>
                        <?php echo CHtml::button("Export PDF", array("id" => "btnProsesPdf", 'class' => 'button cbutton')); ?>
                    <?php endif; ?>

                    <?php echo CHtml::button("Clear Selected", array("id" => "btnClear", 'class' => 'button cbutton')); ?>
                </div>
            </div>
        </div>
    </div> <!-- end row -->
</div> <!-- end maintenance -->

<?php Yii::app()->clientScript->registerScript('centang', '
	$("#btnProses").click(function(){
        var checked=$("#invoice-header-grid").yiiGridView("getChecked","invoice-header-grid_c0");
        var count=checked.length;
        if (count>0){
            $.ajax({
                    data:{checked:checked},
                    url:"' . CHtml::normalizeUrl(array('invoiceHeader/prTemp')) . '",
                    success:function(data){
                    	$("#invoice-header-grid").yiiGridView("update",{});
                    	window.location.href = "' . CHtml::normalizeUrl(array('invoiceHeader/viewInvoices')) . '";
                    },              
            });
        } else {
            console.log("No Invoice items selected");
            alert("No Invoice items selected");
        }
    });

    $("#btnProsesPdf").click(function(){
        var checked=$("#invoice-header-grid").yiiGridView("getChecked","invoice-header-grid_c0");
        var count=checked.length;
        if (count > 0){
            $.ajax({
                data:{checked:checked},
                url:"' . CHtml::normalizeUrl(array('invoiceHeader/prTemp')) . '",
                success:function(data){
                    $("#invoice-header-grid").yiiGridView("update",{});
                    window.location.href = "' . CHtml::normalizeUrl(array('invoiceHeader/pdfAll')) . '";
                },              
            });
        } else {
            console.log("No Invoice items selected");
            alert("No Invoice items selected");
        }
    });

    $("#btnClear").click(function(){
        var checked="clear";
        $.ajax({
            data:{checked:checked},
            url:"' . CHtml::normalizeUrl(array('invoiceHeader/prTemp')) . '",
            success:function(data){
                $("#invoice-header-grid").yiiGridView("update",{});
            },              
        });
    });
'); ?>

/*
 <codex>
 <abstract>Simple 4x4 matrix computations</abstract>
 </codex>
 */

#ifndef MATRIX_H
#define MATRIX_H

void mat4f_LoadIdentity(float* m);
void mat4f_LoadScale(float* s, float* m);

void mat4f_LoadXRotation(float radians, float* mout);
void mat4f_LoadYRotation(float radians, float* mout);
void mat4f_LoadZRotation(float radians, float* mout);

void mat4f_LoadTranslation(float* t, float* mout);

void mat4f_LoadPerspective(float fov_radians, float aspect, float zNear, float zFar, float* mout);
void mat4f_LoadOrtho(float left, float right, float bottom, float top, float near, float far, float* mout);

void mat4f_MultiplyMat4f(const float* a, const float* b, float* mout);

#endif /* MATRIX_H */

<template>
  <div class="pay">
    <div class="pay-type">
      <span>交易方式:</span>
      <div :class="payType === 'union' ? 'unionSelected' : 'union'"
        @click="changePayType('union')"></div>
      <div :class="payType === 'deposit' ? 'depositSelected' : 'deposit'"
        @click="changePayType('deposit')"></div>
      <div :class="payType === 'alipay' ? 'alipaySelected' : 'alipay'"
        @click="changePayType('alipay')"></div>
      <div :class="payType === 'wepay' ? 'wepaySelected' : 'wepay'"
        @click="changePayType('wepay')"></div>
    </div>
    <!-- <div class="pay-total">
      <div class="pt-count">
        总计:
        <span>货品种类:{{od.total_type}}类</span>
        <span>数量总计:{{od.total_quantity}}件</span>
      </div>
      <div class="pt-pay">
        <span>运费共计:<span class="money">{{od.total_carriage}}</span></span>
        <span>货品总金额:<span class="money">¥{{od.total_money}}</span></span>
        <span class="ptp-total">应付总额(不含运费):<span class="money">¥{{od.total_money}}</span></span>
      </div>
    </div> -->
  </div>
</template>

<script>
export default {
  props: ['od', 'payType'],
  methods: {
    changePayType(type) {
      if(type === 'alipay' || type === 'wepay') this.$emit('updatePayType', {type})
      else this.$message('功能暂未开通...')
    }
  }
}
</script>

<style scoped lang="less">
.pay {
  width: 1024px;
  // height: 192px;

  @eColor: #ec6337;

  .p-box {
    display: flex;
    align-items: center;
    height: 112px;
    width: 1024px;
    padding: 0 10px;
    margin-bottom: 10px;
    font-size: 14px;
    color: #666;
    background-color: white;
  }

  .pay-type {
    .p-box;
    align-items: center;

    div {
      margin-left: 10px;
      width: 140px;
      height: 40px;
      box-sizing: border-box;
      cursor: pointer;
      border-radius: 4px;
    }

    .union {
      background: url(/static/img/p_union.png) 0 0 ~'/' 140px auto no-repeat;
      cursor: not-allowed;
    }

    .unionSelected {
      border: 1px solid @eColor;
      background: url(/static/img/p_union_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }

    .deposit {
      background: url(/static/img/p_deposit.png) 0 0 ~'/' 140px auto no-repeat;
      cursor: not-allowed;
    }

    .depositSelected {
      border: 1px solid @eColor;
      background: url(/static/img/p_deposit_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }

    .alipay {
      border: 1px solid #d8d8d8;
      background: url(/static/img/p_alipay_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }

    .alipaySelected {
      border: 1px solid @eColor;
      background: url(/static/img/p_alipay_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }

    .wepay {
      border: 1px solid #d8d8d8;
      background: url(/static/img/p_wepay_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }

    .wepaySelected {
      border: 1px solid @eColor;
      background: url(/static/img/p_wepay_selected.png) 0 0 ~'/' 140px auto no-repeat;
    }
  }

  // .pay-total {
  //   .p-box;
  //   justify-content: space-between;

  //   .pt-count {

  //   }

  //   .pt-pay {
  //     display: flex;
  //     flex-direction: column;
  //     align-items: flex-end;
  //     font-size: 12px;

  //     .ptp-total {
  //       font-size: 14px;
  //     }

  //     .money {
  //       color: #ec6337;
  //       margin-left: 4px;
  //     }
  //   }
  // }
}
</style>

<!DOCTYPE html>
<html lang="en">

<head>

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

  <title><?= $title ?></title>

  <!-- Custom fonts for this template-->
  <link href="<?= base_url(); ?>assets/sbadmin/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

  <!-- Custom styles for this template-->
  <link href="<?= base_url(); ?>assets/sbadmin/css/sb-admin-2.min.css" rel="stylesheet">
  <style>
    html { 
      background: url(<?= base_url(); ?>assets/img/backgroundpnp.jpeg) no-repeat center center fixed; 
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
    }
    body {
      background-color: transparent;
    }
    .special-card {
      background-color: rgba(245, 245, 245, 1);
      opacity: .91;
    }
  </style>

</head>

<body>
const axios = require("../connectionService").axios
const { JSDOM } = require("jsdom");
const unwanted = JSON.parse(process.env.unwanted)
const banList = JSON.parse(process.env.banList)
const extraStrategy = require('./extraStrategy')
async function getBestPriceForCard(dom, edition, extras){
    extraStrategy.removeUselessExtras(extras)
    const cheapestStorePdp = getCheapestOptionURL(dom, edition, extras)
    return await getPriceFromCheapestStore(cheapestStorePdp, edition, extras)
}

function getCheapestOptionURL(dom, edition, extras){
    const availableOptions = [...dom.window.document.querySelectorAll("#aba-cards>.estoque-linha")]
    let rightEdition = availableOptions.filter(item => item.querySelector(".ed-simb") && 
        item.querySelector(".ed-simb").href.endsWith(`=${edition}`))
    if(extras.length)
      rightEdition = filterExtras(rightEdition, extras)
    rightEdition = removeUnwantedQualityGrades(rightEdition)
    rightEdition = removeStoresFromBanlist(rightEdition)
    const url = "https://www.ligamagic.com.br/" +rightEdition[0].querySelector(".goto").href
    const selectedGrade =  rightEdition[0].querySelector(".e-col4>font").innerHTML
    return {url, selectedGrade}
}

function removeStoresFromBanlist(rightEdition){
    return rightEdition.filter(item => {
        const img = item.querySelector(".e-col1 img").title;
        return !banList.some(store => img.includes(store))
    })
}

function filterExtras(rightEdition, extras){
    return rightEdition.filter(
        item => item.querySelector("p.extras") 
        && extras.every(
            extra => item.querySelector("p.extras").innerHTML.split(", ").includes(extra)
            )
        )
}

function removeUnwantedQualityGrades(rightEdition){
    return rightEdition.filter(item => 
        {
            const quality = item.querySelector(".e-col4>font")
            return !unwanted.some(qlty =>
                quality && quality.innerHTML.includes(qlty)) 
        })
}

async function getPriceFromCheapestStore(cheapestStorePdp, edition, extras){
    const page = await(axios.get(cheapestStorePdp.url))
    const dom = new JSDOM(page.data)
    let options = [...dom.window.document.querySelectorAll(".itemMain table table:last-child tbody tr")].slice(1)
    options = options.filter(item => filterFoils(item, extras)).filter(filterOutOfStock)
    const selected = options.filter(item => 
        item.querySelector(".very2Small") &&
        item.querySelector(".very2Small").innerHTML.includes(cheapestStorePdp.selectedGrade)
        && item.querySelector("img").src.toLowerCase().includes(`/${edition.toLowerCase()}_`))[0]
    if(selected.querySelector(".itemPreco").childElementCount > 0)
        return selected.querySelector(".itemPreco").lastElementChild.innerHTML
    else
        return selected.querySelector(".itemPreco").innerHTML
}

function filterOutOfStock(item){
    return item.querySelector(".hmin30:nth-child(5)").innerHTML !== "0 unid.";
}

function filterFoils(item, extras){
    const inner = (auction) => {
        return auction.querySelector(".hmin30:nth-child(4)")
            && extraStrategy.containsAllExtras(auction.querySelector(".hmin30:nth-child(4)"), extras)
    }

    return extras ? inner(item) : !inner(item)

}



exports.getBestPriceForCard = getBestPriceForCard;
import Foundation
import ExecutionContext
import Future
import Result

public protocol TransactionType : DataConsumerType {
    func tryConsume(content:ContentType) -> Bool
    
    var action:Future<AbstractActionType> {get}
    
    func selfProcess()
}

class Transaction<RequestContent : ConstructableContentType, ResponseContent : FlushableContentType> : TransactionType {
    let app:Express
    let routeId:String
    let out:DataConsumerType
    let head:RequestHeadType
    let factory:RequestContent.Factory
    let content:Future<RequestContent.Factory.Content>
    let actionPromise:Promise<AbstractActionType>
    let action:Future<AbstractActionType>
    let request:Promise<Request<RequestContent>>
    
    internal required init(app:Express, routeId:String, head:RequestHeadType, out:DataConsumerType) {
        self.app = app
        self.routeId = routeId
        self.out = out
        self.head = head
        self.factory = RequestContent.Factory(response: head)
        self.content = factory.content()
        self.actionPromise = Promise()
        self.action = actionPromise.future
        self.request = Promise<Request<RequestContent>>()
        content.settle(in: ExecutionContext.user).onSuccess() { content in
            let request = Request<RequestContent>(app: app, head: head, body: content as? RequestContent)
            self.request.trySuccess(value: request)
        }
        content.onFailure { e in
            self.actionPromise.tryFail(error: e)
        }
    }
    
    convenience init(app:Express, routeId:String, head:RequestHeadType, out:DataConsumerType, handler:@escaping (Request<RequestContent>) -> Future<Action<ResponseContent>>) {
        self.init(app: app, routeId: routeId, head: head, out: out)
        request.future.onSuccess { request in
            let action = handler(request)
            action.onSuccess { action in
                self.actionPromise.trySuccess(value: action)
            }
            action.onFailure { e in
                self.failAction(e: e)
            }
        }
    }
    
    func failAction(e:Error) {
        self.actionPromise.tryFail(error: e)
    }
    
    func handleActionWithRequest<C : ConstructableContentType>(actionAndRequest:Future<(AbstractActionType, Request<C>?)>) {
        actionAndRequest.onComplete { result in
            let action = Future(result: result.map {$0.0})
            self.handleAction(action: action, request: result.value?.1)
        }
    }
    
    func handleAction<C : ConstructableContentType>(action:Future<AbstractActionType>, request:Request<C>?) {
        action.settle(in:ExecutionContext.action ).onSuccess{ action in
            if let request = request {
                self.processAction(action: action, request: request)
            } else {
                //yes we certainly have request here
                
                self.request.future.onSuccess{value in
                    self.processAction(action: action, request: value)
                }
            }
        }
        action.onFailure { e in
            //yes, we always have at least the default error handler
            let next = self.app.errorHandler.handle(e: e)!
            
            if let request = request {
                self.processAction(action: next, request: request)
            } else {
                self.request.future.onSuccess { request in
                    self.processAction(action: next, request: request)
                }
            }
        }
    }
    
    func selfProcess() {
        handleAction(action: action, request: Optional<Request<RequestContent>>.none)
    }
    
    func processAction<C : ConstructableContentType>(action:AbstractActionType, request:Request<C>) {
        switch action {
            case let flushableAction as FlushableAction: flushableAction.flushTo(out: out)
            case let intermediateAction as IntermediateActionType:
                let actAndReq = intermediateAction.nextAction(request: request)
                handleActionWithRequest(actionAndRequest: actAndReq)
            case let selfSufficientAction as SelfSufficientActionType:
                selfSufficientAction.handle(app: app, routeId: routeId, request: request, out: out).onFailure { e in
                    let action = Future<AbstractActionType>(error: e)
                    self.handleAction(action: action, request: request)
                }
            default:
                //TODO: handle server error
                print("wierd action... can do nothing with it")
        }
    }
    
    func tryConsume(content:ContentType) -> Bool {
        return factory.tryConsume(content: content)
    }
    
    func consume(data:Array<UInt8>) -> Future<Void> {
        return factory.consume(data: data)
    }
    
    func dataEnd() throws {
        try factory.dataEnd()
    }
}

typealias TransactionFactory = (RequestHeadType, DataConsumerType)->TransactionType
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;

import { IController } from "../interfaces/IController.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title IntegrationRegistry
 * @author Set Protocol
 *
 * The IntegrationRegistry holds state relating to the Modules and the integrations they are connected with.
 * The state is combined into a single Registry to allow governance updates to be aggregated to one contract.
 */
contract IntegrationRegistry is Ownable {

    /* ============ Events ============ */

    event IntegrationAdded(address indexed _module, address indexed _adapter, string _integrationName);
    event IntegrationRemoved(address indexed _module, address indexed _adapter, string _integrationName);
    event IntegrationEdited(
        address indexed _module,
        address _newAdapter,
        string _integrationName
    );

    /* ============ State Variables ============ */

    // Address of the Controller contract
    IController public controller;

    // Mapping of module => integration identifier => adapter address
    mapping(address => mapping(bytes32 => address)) private integrations;

    /* ============ Constructor ============ */

    /**
     * Initializes the controller
     *
     * @param _controller          Instance of the controller
     */
    constructor(IController _controller) public {
        controller = _controller;
    }

    /* ============ External Functions ============ */

    /**
     * GOVERNANCE FUNCTION: Add a new integration to the registry
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _name         Human readable string identifying the integration
     * @param  _adapter      Address of the adapter contract to add
     */
    function addIntegration(
        address _module,
        string memory _name,
        address _adapter
    )
        public
        onlyOwner
    {
        bytes32 hashedName = _nameHash(_name);
        require(controller.isModule(_module), "Must be valid module.");
        require(integrations[_module][hashedName] == address(0), "Integration exists already.");
        require(_adapter != address(0), "Adapter address must exist.");

        integrations[_module][hashedName] = _adapter;

        emit IntegrationAdded(_module, _adapter, _name);
    }

    /**
     * GOVERNANCE FUNCTION: Batch add new adapters. Reverts if exists on any module and name
     *
     * @param  _modules      Array of addresses of the modules associated with integration
     * @param  _names        Array of human readable strings identifying the integration
     * @param  _adapters     Array of addresses of the adapter contracts to add
     */
    function batchAddIntegration(
        address[] memory _modules,
        string[] memory _names,
        address[] memory _adapters
    )
        external
        onlyOwner
    {
        // Storing modules count to local variable to save on invocation
        uint256 modulesCount = _modules.length;

        require(modulesCount > 0, "Modules must not be empty");
        require(modulesCount == _names.length, "Module and name lengths mismatch");
        require(modulesCount == _adapters.length, "Module and adapter lengths mismatch");

        for (uint256 i = 0; i < modulesCount; i++) {
            // Add integrations to the specified module. Will revert if module and name combination exists
            addIntegration(
                _modules[i],
                _names[i],
                _adapters[i]
            );
        }
    }

    /**
     * GOVERNANCE FUNCTION: Edit an existing integration on the registry
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _name         Human readable string identifying the integration
     * @param  _adapter      Address of the adapter contract to edit
     */
    function editIntegration(
        address _module,
        string memory _name,
        address _adapter
    )
        public
        onlyOwner
    {
        bytes32 hashedName = _nameHash(_name);

        require(controller.isModule(_module), "Must be valid module.");
        require(integrations[_module][hashedName] != address(0), "Integration does not exist.");
        require(_adapter != address(0), "Adapter address must exist.");

        integrations[_module][hashedName] = _adapter;

        emit IntegrationEdited(_module, _adapter, _name);
    }

    /**
     * GOVERNANCE FUNCTION: Batch edit adapters for modules. Reverts if module and
     * adapter name don't map to an adapter address
     *
     * @param  _modules      Array of addresses of the modules associated with integration
     * @param  _names        Array of human readable strings identifying the integration
     * @param  _adapters     Array of addresses of the adapter contracts to add
     */
    function batchEditIntegration(
        address[] memory _modules,
        string[] memory _names,
        address[] memory _adapters
    )
        external
        onlyOwner
    {
        // Storing name count to local variable to save on invocation
        uint256 modulesCount = _modules.length;

        require(modulesCount > 0, "Modules must not be empty");
        require(modulesCount == _names.length, "Module and name lengths mismatch");
        require(modulesCount == _adapters.length, "Module and adapter lengths mismatch");

        for (uint256 i = 0; i < modulesCount; i++) {
            // Edits integrations to the specified module. Will revert if module and name combination does not exist
            editIntegration(
                _modules[i],
                _names[i],
                _adapters[i]
            );
        }
    }

    /**
     * GOVERNANCE FUNCTION: Remove an existing integration on the registry
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _name         Human readable string identifying the integration
     */
    function removeIntegration(address _module, string memory _name) external onlyOwner {
        bytes32 hashedName = _nameHash(_name);
        require(integrations[_module][hashedName] != address(0), "Integration does not exist.");

        address oldAdapter = integrations[_module][hashedName];
        delete integrations[_module][hashedName];

        emit IntegrationRemoved(_module, oldAdapter, _name);
    }

    /* ============ External Getter Functions ============ */

    /**
     * Get integration adapter address associated with passed human readable name
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _name         Human readable adapter name
     *
     * @return               Address of adapter
     */
    function getIntegrationAdapter(address _module, string memory _name) external view returns (address) {
        return integrations[_module][_nameHash(_name)];
    }

    /**
     * Get integration adapter address associated with passed hashed name
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _nameHash     Hash of human readable adapter name
     *
     * @return               Address of adapter
     */
    function getIntegrationAdapterWithHash(address _module, bytes32 _nameHash) external view returns (address) {
        return integrations[_module][_nameHash];
    }

    /**
     * Check if adapter name is valid
     *
     * @param  _module       The address of the module associated with the integration
     * @param  _name         Human readable string identifying the integration
     *
     * @return               Boolean indicating if valid
     */
    function isValidIntegration(address _module, string memory _name) external view returns (bool) {
        return integrations[_module][_nameHash(_name)] != address(0);
    }

    /* ============ Internal Functions ============ */

    /**
     * Hashes the string and returns a bytes32 value
     */
    function _nameHash(string memory _name) internal pure returns(bytes32) {
        return keccak256(bytes(_name));
    }
}
import React from 'react';
import styled from 'styled-components/native';

export const Container = styled.SafeAreaView`
    flex: 1;
    justify-content:center;
    width:100%;
    /* background-color:#F2F6F8; */
    background-color:${props=>props.theme.background};
    padding:20px 20px 0 20px;
    
`;

export const Scroler = styled.ScrollView`
    flex: 1;
`;
export const Loading = styled.ActivityIndicator`
    margin:20px 0;
    color:${props=>props.theme.color};
`;
export const DadosCovid = styled.View`
`;

export const Graficos = styled.View`
    
`;

export const GraficosView = styled.View`
    margin:1px;
`;

export const Texto = styled.Text`

`;
export const Angola = styled.View`
    margin:1px;
    
    
    
    
`;
export const DadosAngola = styled.View`
    flex-direction:row;
    justify-content:space-between;
    flex:1;
    
   
`;

export const Dados = styled.View`
    background-color:${props=>props.theme.container};
    width:49%;
    padding:10px;
    overflow:hidden;
    border-radius:12px;
    elevation:2;
    margin-bottom:10px;
    height:90px;
    
`;

export const DadosCont = styled.View`
`;

export const TextoCont = styled.View`
    flex-direction:row;
    justify-content:space-between;
    align-items:center;
    margin-top:20px;
`;
export const TituloDado = styled.Text`
    font-family:"Poppins-Bold";
    letter-spacing:1px;
    font-size:18px;
    text-align:right;
    color:${props=>props.theme.color};
`;

export const TituloDadoNew = styled.Text`
    font-family:"Poppins-Bold";
    letter-spacing:1px;
    font-size:10px;
    text-align:right;
    margin-right:6px;
    color:${props=>props.theme.color};
    
`;
export const TituloDadoCritico = styled.Text`

    font-family:"Poppins-Bold";
    letter-spacing:1px;
    font-size:14px;
    color:${props=>props.theme.color};
`;
export const DadosCovidAngola = styled.View`

`;

export const DadosPais = styled.View`
    
    /* position:absolute; */
    /* top:-10px; */
`;
/* export const Texto = styled.Text`
font-size:16px;
    font-family:"Poppins-Bold";
    color:${props=>props.theme.color};
    margin-left:4px;
    background-color:${props=>props.theme.container};;
`; */

export const Titulo = styled.View`
    flex-direction:row;
    align-items:center;
    justify-content:space-between;
`;
export const TextoPais = styled.Text`
    font-size:18px;
    font-family:"Poppins-Bold";
    color:${props=>props.theme.color};
    margin-left:4px;
`;
export const Flag = styled.Image`
`;
export const TextoContinente = styled.View`
    flex-direction:row;
    margin-top:20px;
`;
export const TextoContinenteTexto = styled.Text`
    font-size:12px;
    font-family:"Poppins-Medium";
    color:${props=>props.theme.color};
`;
export const DadosDetalhes = styled.View`
    width:100%;
    margin:1px 1px 20px 1px;
    background-color:${props=>props.theme.container};;
    elevation:2;
    border-radius:8px;
    padding:10px;
    margin-top: 20px;
`;
export const MapaContainer = styled.View`
    margin-top:20px;
    width:100%;
`;
export const Botao = styled.TouchableOpacity`
    justify-content:center;
    width:100%;
    align-items:center;
`;
export const BotaoText = styled.Text`
    font-family:"Poppins-Bold";
    font-size:12px;
    color:${props=>props.theme.background};
    background-color:${props=>props.theme.color};
    padding:4px 30px;
    border-radius:4px;
    letter-spacing:1px;
`;
/**
 * Created by terminator10 on 2/11/15.
 */

//Create variables Global
var contador = 1;
//End Variables Global
function main () {
    $('.menu_bar').click(function(){
        if (contador == 1) {
            $('nav').animate({
                left: '0'
            });
            $('.menu_bar span').css({
               'background':'rgb(248,248,248)',
            });
            contador = 0;
        } else {
            $('.menu_bar span').css({
                'background':'#fff'
            });
            contador = 1;
            $('nav').animate({
                left: '100%'
            });

        }
    });
    // Mostramos y ocultamos submenus
    $('.submenu').click(function(){
        $(this).children('.children').slideToggle();
    });
}
/*Funciones para validar usuarios y email*/
function Validador(email){
    var tester = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z0-9]{2,4})+$/;
    return tester.test(email);
}
function caracter(username){
    var caract = /^([a-zA-Z0-9_-])/;
    return caract.test(username)
}
function pass(password){
    var pass = /(^(?=.*[a-z])(?=.*[A-Z])(?=.*\d){7,20}.+$)/;
    return pass.test(password)
}

$(document).ready(function(){
    main();
    /*Verificacion de usurios   $(document).ready(main);*/
    /*Validacion el password*/
   document.getElementById('password').addEventListener('blur',function(){
        var password = document.getElementById('password').value;
        if(pass(password) == false){
            $('.password-validate').css({
                'color': '#fff'
            });
            $('.validate-pass').html('<i class="icon-warning"></i>').show();
            $('.validate-pass').css({
                'color': '#b20000'
            });
            return false;
        }else{
            $('.password-validate').css({
                'color': '#8c8c8c'
            });
            $('.validate-pass').html('<i class="icon-checkmark"></i>').show();
            $('.validate-pass').css({
                'color': 'rgba(72, 130, 255, 1)'
            });
        }
    });
    document.getElementById('username').addEventListener('blur',function(){
        var username = document.getElementById('username').value;
        if (username.length > 0) {
            if (caracter(username) == false) {
                $('.loader').html("<i class='icon-user'></i> Nombre de usuario no es válido o ya adoptadas.").show().delay(2000).hide(200);
                $('.validate-user').css({
                    'color': '#b20000'
                });
                $('.validate-user').html('<i class="icon-warning"></i>').show();
                return false;
            }else {
                $('.loader').html('').hide();
                $.ajax({
                    type:'POST',
                    url:'server/app_server_whereis.php',
                    data:{username:username, wis:'verify_user'},
                    success: function (data) {
                        if (data == 0) {
                            $('.validate-user').css({
                                'color': '#b20000'
                            });
                            $('.validate-user').html('<i class="icon-warning"></i>').show();
                            $('.loader').html("<i class='icon-user'></i> Nombre de usuario no es válido o ya adoptadas.").show().delay(2000).hide(200);
                        } else if (data == 1) {
                            $('.validate-user').css({
                                'color': 'rgba(72, 130, 255, 1)'
                            });
                            $('.validate-user').html('<i class="icon-checkmark"></i>').show();
                        }
                    }
                });
            }
        }
    });
    document.getElementById('email').addEventListener('blur',function(){
        var email = document.getElementById('email').value;
        if (email.length > 0) {
            if (Validador(email) == false) {
                $('.loader').html("<i class='icon-mail2'></i> Correo electronico no es válido o ya adoptadas.").show().delay(2000).hide(200);
                $('.validate-email').css({
                    'color': '#b20000'
                });
                $('.validate-email').html('<i class="icon-warning"></i>').show();
                return false;
            } else {
                $('.loader').html('').hide();
                $.ajax({
                    type: 'POST',
                    url: 'server/app_server_whereis.php',
                    data: {email: email, wis: 'verify_email'},
                    success: function (data) {

                        if (data == 0) {
                            $('.validate-email').css({
                                'color': '#b20000'
                            });
                            $('.validate-email').html('<i class="icon-warning"></i>').show();
                            $('.loader').html("<i class='icon-mail2'></i> Correo electronico no es válido o ya adoptadas.").show().delay(2000).hide(200);
                        }else if (data == 1) {
                            $('.validate-email').css({
                                'color': 'rgba(72, 130, 255, 1)'
                            });
                            $('.validate-email').html('<i class="icon-checkmark"></i>').show();
                        }
                    }
                });

            }
        }
    });
});

function login_data_user(){
    var username = document.getElementById('username').value;
    var email = document.getElementById('email').value;
    var password = document.getElementById('password').value;
    var len = username.length * email.length * password.length;
    if(len == "" && Validador(email) == false && caracter(username) == false && pass(password) == false){
        $('.loader').html('<i class="icon-warning"></i> Ohh! Datos introducidos incorrectos o campos estan vacios.').show().delay(2000).hide(200);
        return false;
    }else {
        $.ajax({
            type: 'POST',
            url: 'server/app_server_whereis.php',
            data: {username: username, email: email, password: password, wis: 'login_whereis'},
            success: function (data) {
                if (data == 1) {
                    $('.register-button').html("Creando su cuenta").show();
                    $('.loader').html('<div class="loader-inner ball-pulse-sync"><div></div><div></div><div></div></div>').show();
                    setTimeout(function () {
                        window.location = "inicio";
                    }, 3000);
                } else if (data == 2) {
                    $('.loader').html('<i class="icon-shocked"></i> Ohh! Hubo problemas para crear tu cuenta o datos ya adoptados. ').show().delay(2000).hide(200);
                } else if (data == 3) {
                    $('.loader').html('<i class="icon-sad"></i> Ohh! Asegurate de que tu usuario y email son correctos.').show().delay(2000).hide(200);
                }
            }
        });
    }
}







﻿// License
// --------------------------------------------------------------------------------------------------------------------
// (C) Copyright 2021 Cato Léan Trütschel and contributors
// (github.com/CatoLeanTruetschel/AsyncQueryableAdapterPrototype)
//
// 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
//
//      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.
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncQueryableAdapter.Sample
{
    internal static class Program
    {
        private static Repository Repository { get; } = new Repository();

#pragma warning disable CS1998, IDE0060
        private static async Task Main(string[] args)
#pragma warning restore CS1998, IDE0060
        {
            var lastNamesSync = from person in Repository.People
                                where person.Age > 25 && person.LastName != "Adams" && person.Gender != Gender.Unknown
                                select person.LastName;

            lastNamesSync = lastNamesSync.Where(p => p.Length > 6);

            Console.WriteLine("Last names: " + string.Join(", ", lastNamesSync));

            var lastNamesAsync = from person in Repository.QueryAdapter.GetAsyncQueryable<Person>()
                                 where person.Age > 25 && person.LastName != "Adams" && person.Gender != Gender.Unknown
                                 select person.LastName;

            var lastNames = await lastNamesAsync.WhereAwait(p => new ValueTask<bool>(p.Length > 6)).ToArrayAsync();

            Console.WriteLine("Last names: " + string.Join(", ", lastNames));
            Console.WriteLine("Last names count: " + await lastNamesAsync.CountAsync());
            Console.WriteLine("Last names max length: " + await lastNamesAsync.Select(p => p.Length).MaxAsync());
        }
    }

    internal sealed class Repository
    {
        private readonly List<Person> _people;
        private readonly List<Relationship> _relationships;

        public Repository()
        {
            QueryAdapter = new RepositoryQueryAdapter(this);
            (_people, _relationships) = SeedData();
        }

        private static (List<Person> people, List<Relationship> relationships) SeedData()
        {
            var relationships = new List<Relationship>();

            var christopherWagner = new Person("Christopher", "Wagner", 22, Gender.Male);
            var juanaMartinez = new Person("Juana", "Martinez", 30);
            var davidEstes = new Person("David", "Estes", 53, Gender.Male);
            var ashSapp = new Person("Ash", "Sapp", 21, Gender.Diverse);

            var jasonRandolph = new Person("Jason", "Randolph", 46, Gender.Male);
            var patriciaStone = new Person("Patricia", "Stone", 48, Gender.Female);
            relationships.Add(new Relationship(jasonRandolph, patriciaStone));

            var julieDaniels = new Person("Julie", "Daniels", 29, Gender.Female);
            var deborahFerguson = new Person("Deborah", "Ferguson", 31, Gender.Female);
            relationships.Add(new Relationship(julieDaniels, deborahFerguson));

            var lewisAdams = new Person("Lewis", "Adams", 46, Gender.Male);
            var rondaBelle = new Person("Ronda", "Belle", 41, Gender.Diverse);
            relationships.Add(new Relationship(lewisAdams, rondaBelle));

            var robertPhillips = new Person("Robert", "Phillips", 36, Gender.Male);
            var meghanPhillips = new Person("Meghan", "Phillips", 34, Gender.Female);
            relationships.Add(new Relationship(robertPhillips, meghanPhillips));

            var people = new List<Person>
            {
                christopherWagner,
                juanaMartinez,
                davidEstes,
                ashSapp,
                jasonRandolph,
                patriciaStone,
                julieDaniels,
                deborahFerguson,
                lewisAdams,
                rondaBelle,
                robertPhillips,
                meghanPhillips
            };

            return (people, relationships);
        }

        public IQueryable<Person> People => _people.AsQueryable();
        public IQueryable<Relationship> Relationships => _relationships.AsQueryable();

        public RepositoryQueryAdapter QueryAdapter { get; }
    }

    internal sealed class RepositoryQueryAdapter : QueryAdapterBase
    {
        private readonly Repository _repository;

        public RepositoryQueryAdapter(Repository repository)
            : base(Microsoft.Extensions.Options.Options.Create(new AsyncQueryableOptions()))
        {
            if (repository is null)
                throw new ArgumentNullException(nameof(repository));

            _repository = repository;
        }

        protected override IQueryable<T> GetQueryable<T>()
        {
            if (typeof(T) == typeof(Person))
            {
                return (IQueryable<T>)_repository.People;
            }

            if (typeof(T) == typeof(Relationship))
            {
                return (IQueryable<T>)_repository.Relationships;
            }

            return Enumerable.Empty<T>().AsQueryable();
        }

        protected override IAsyncEnumerable<T> EvaluateAsync<T>(
            IQueryable<T> queryable,
            CancellationToken cancellation)
        {
            return queryable.ToAsyncEnumerable();
        }
    }

    internal record Person(string FirstName, string LastName, int Age, Gender Gender = Gender.Unknown);

    internal record Relationship(Person Partner1, Person Pertner2);

    internal enum Gender
    {
        Unknown,
        Female,
        Male,
        Diverse,
        Other,
        None
    }
}

from core.terraform.resources import BaseTerraformVariable, TerraformData, TerraformResource
from core.config import Settings
from core.terraform.utils import get_terraform_resource_path, get_terraform_latest_output_file, get_terraform_status_file
from core.log import SysLog
from core import constants as K
from core.lib.python_terraform import *
from datetime import datetime
from core.utils import exists_teraform_lock
import inspect
import json


class PyTerraform():
    log_obj = SysLog()

    def terraform_init(self):
        if exists_teraform_lock():
            raise Exception(K.ANOTHER_PROCESS_RUNNING)

        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
        )
        self.log_obj.write_debug_log(K.TERRAFORM_INIT_STARTED)
        response = terraform.init()

        if response[0] == 1:
            self.log_obj.write_debug_log(K.TERRAFORM_INIT_ERROR)
            raise Exception(response[2])

        self.log_obj.write_terraform_init_log(response)

        return response

    def terraform_plan(self, resources=None):
        if exists_teraform_lock():
            raise Exception(K.ANOTHER_PROCESS_RUNNING)

        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
            targets=self.get_target_resources(resources)
        )

        self.log_obj.write_debug_log(K.TERRAFORM_PLAN_STARTED)
        response = terraform.plan()

        if response[0] == 1:
            self.log_obj.write_debug_log(K.TERRAFORM_PLAN_ERROR)
            raise Exception(response[2])

        self.log_obj.write_terraform_plan_log(response)

        return response

    def terraform_apply(self, resources=None):
        if exists_teraform_lock():
            raise Exception(K.ANOTHER_PROCESS_RUNNING)

        CMD = Settings.get('running_command', "Terraform Apply")
        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
            targets=self.get_target_resources(resources),
            stdout_log_file=self.log_obj.get_terraform_install_log_file()
        )

        self.log_obj.write_terraform_apply_log_header()
        # In order to -auto-approve we need to pass skip_plan=True for python3
        response = terraform.apply(skip_plan=True)

        if response[0] == 1:
            self.log_obj.write_debug_log(K.TERRAFORM_APPLY_ERROR)
            self.write_current_status(CMD, K.APPLY_STATUS_ERROR, response[2])
            raise Exception(response[2])

        self.write_current_status(CMD, K.APPLY_STATUS_COMPLETED, K.TERRAFORM_APPLY_COMPLETED)
        return response

    def terraform_destroy(self, resources=None):
        if exists_teraform_lock():
            raise Exception(K.ANOTHER_PROCESS_RUNNING)

        CMD = Settings.get('running_command', "Terraform Destroy")
        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
            targets=self.get_target_resources(resources),
            stdout_log_file=self.log_obj.get_terraform_destroy_log_file()
        )

        self.log_obj.write_terraform_destroy_log_header()
        kwargs = {"auto_approve": True}
        response = terraform.destroy(**kwargs)

        if response[0] == 1:
            self.log_obj.write_debug_log(K.TERRAFORM_DESTROY_ERROR)
            self.write_current_status(CMD, K.DESTROY_STATUS_ERROR, response[2])
            raise Exception(response[2])

        self.write_current_status(CMD, K.DESTROY_STATUS_COMPLETED, K.TERRAFORM_DESTROY_COMPLETED)
        return response

    def process_destroy_result(self, p):
        response = Terraform().return_process_result(p)
        CMD = Settings.get('running_command', "Terraform Destroy")

        if response[0] == 1:
            self.log_obj.write_debug_log(K.TERRAFORM_DESTROY_ERROR)
            self.write_current_status(CMD, K.DESTROY_STATUS_ERROR, response[2])
            raise Exception(response[2])

        self.write_current_status(CMD, K.DESTROY_STATUS_COMPLETED, K.TERRAFORM_DESTROY_COMPLETED)

    def terraform_taint(self, resources):
        if exists_teraform_lock():
            raise Exception(K.ANOTHER_PROCESS_RUNNING)

        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
        )

        taint_resources = self.get_taint_resources(resources)

        self.log_obj.write_debug_log(K.TERRAFORM_TAINT_STARTED)

        for resource_name in taint_resources:
            response = terraform.cmd("taint", resource_name)
            if response[0] == 1:
                self.log_obj.write_debug_log(K.TERRAFORM_TAINT_ERROR)
                raise Exception(response[2])

        self.log_obj.write_debug_log(K.TERRAFORM_TAINT_COMPLETED)

        return response

    def get_target_resources(self, resources):
        if resources:
            targets = []
            for resource in resources:
                # DO NOT process this resource as its definiiton asked to skip
                if resource.PROCESS is False:
                    continue

                if BaseTerraformVariable not in inspect.getmro(resource.__class__) and TerraformData not in inspect.getmro(resource.__class__):
                    targets.append(get_terraform_resource_path(resource))

            return targets

        return None

    def get_taint_resources(self, resources):
        taint_resources = []
        for resource in resources:
            if TerraformResource in inspect.getmro(resource.__class__):
                taint_resources.append(get_terraform_resource_path(resource))

        return taint_resources

    @classmethod
    def save_terraform_output(cls):
        tf_output_file = get_terraform_latest_output_file()
        output_dict = cls.load_terraform_output()

        with open(tf_output_file, 'w') as jsonfile:
            json.dump(output_dict, jsonfile, indent=4)
        cls.log_obj.write_debug_log(K.TERRAFORM_OUTPUT_STORED)

        return output_dict

    @classmethod
    def load_terraform_output(cls):
        output_dict = {}

        terraform = Terraform(
            working_dir=Settings.TERRAFORM_DIR,
        )
        response = terraform.output()
        if response:
            for key, item in response.items():
                key_splitted = key.split('-')
                resource_key = '-'.join(key_splitted[0:-1])

                if resource_key in output_dict:
                    output_dict[resource_key][key_splitted[-1]] = item['value']
                else:
                    output_dict[resource_key] = {key_splitted[-1]: item['value']}

        return output_dict

    @classmethod
    def load_terraform_output_from_json_file(cls):
        tf_output_file = get_terraform_latest_output_file()
        output_dict = {}
        if os.path.exists(tf_output_file):
            with open(tf_output_file) as jsonfile:
                output_dict = json.load(jsonfile)

        return output_dict

    def write_current_status(self, command, status_code, description=""):
        current_status = self.get_current_status()
        prev_status = None

        if current_status:
            prev_status = {
                'status_code': current_status['status_code'],
                'description': current_status['description'],
                'last_exec_command': current_status['last_exec_command'],
                'executed_time': current_status['executed_time']
            }

        current_status['status_code'] = status_code
        current_status['description'] = description
        current_status['last_exec_command'] = command
        current_status['executed_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        if prev_status:  # FIrst time previous status won't be available
            current_status[prev_status['executed_time']] = prev_status

        status_file = get_terraform_status_file()
        with open(status_file, 'w') as jsonfile:
            json.dump(current_status, jsonfile, indent=4)

    @classmethod
    def get_current_status(self):
        status_file = get_terraform_status_file()
        status_dict = {}
        if os.path.exists(status_file):
            with open(status_file) as jsonfile:
                status_dict = json.load(jsonfile)

        return status_dict

import UIKit

class HSUserProtocalController: UIViewController {
    
      let  webView : UIWebView = UIWebView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height-64));

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.init(red: 0xf3/255.0, green: 0xf3/255.0, blue: 0xf3/255.0, alpha: 1.0);
        self.title = "用户许可协议";
        self.webView.scalesPageToFit = true;
        self.view.addSubview(self.webView);
        
        let url = NSURL.init(string: "http://www.elitez.cn/html/user_agreement");
        let request = NSURLRequest.init(URL: url!);
        self.webView.loadRequest(request);
    }
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
---
title: 基于报表生成数据馈送（报表生成器和 SSRS）| Microsoft Docs
ms.custom: ''
ms.date: 05/30/2017
ms.prod: reporting-services
ms.prod_service: reporting-services-sharepoint, reporting-services-native
ms.component: report-builder
ms.reviewer: ''
ms.suite: pro-bi
ms.technology: ''
ms.tgt_pltfrm: ''
ms.topic: conceptual
ms.assetid: 4e00789f-6967-42e5-b2b4-03181fdb1e2c
caps.latest.revision: 12
author: maggiesMSFT
ms.author: maggies
manager: kfile
ms.openlocfilehash: 394a6ddd55d78615894b42a983f523827bafa27b
ms.sourcegitcommit: 1740f3090b168c0e809611a7aa6fd514075616bf
ms.translationtype: HT
ms.contentlocale: zh-CN
ms.lasthandoff: 05/03/2018
---
# <a name="generating-data-feeds-from-reports-report-builder-and-ssrs"></a>基于报表生成数据馈送（报表生成器和 SSRS）

  [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] Atom 呈现扩展插件可生成 Atom 服务文档，该文档列出分页报表中可用的数据馈送以及来自报表中的数据区域的数据馈送。 使用此扩展插件生成与 Atom 兼容的数据馈送，这些馈送是可读的，并可以与使用从报表生成的数据馈送的应用程序进行交换。 例如，可以使用 Atom 呈现扩展插件生成随后可用在 Power Pivot 或 Power BI 中的数据馈送。  
  
 Atom 服务文档为报表中的每个数据区域至少列出一个数据馈送。 根据数据区域的类型以及数据区域显示的数据， [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] 可以自数据区域生成多个数据馈送。 例如，矩阵或图表可以提供多个数据馈送。 Atom 呈现扩展插件创建 Atom 服务文档时，将为每个数据馈送创建一个唯一标识符，在 URL 中使用该标识符可以访问数据馈送的内容。  
  
 Atom 呈现扩展插件为数据馈送生成数据的方式类似于逗号分隔值 (CSV) 呈现扩展插件将数据呈现到 CSV 文件的方式。 类似于 CSV 文件，数据馈送是报表数据的平展表示形式。 例如，表中有一个行组对某组中的销售额进行加总时，会对每个数据行重复加总，并没有单独的行仅包含总和。  
  
 可以使用 [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] Web 门户、Report Server 或与 [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)]集成的 SharePoint 站点来生成 Atom 服务文档和数据馈送。  
  
 Atom 应用于一对相关标准。 Atom 服务文档符合 RFC 5023 Atom 发布协议规范，数据馈送符合 RFC 4287 Atom 联合格式协议规范。  
  
 以下各节提供有关如何使用 Atom 呈现扩展插件的附加信息：  
  
 [!INCLUDE[ssRBRDDup](../../includes/ssrbrddup-md.md)]  
  
##  <a name="ReportDataAsDataFeeds"></a> 作为数据馈送的报表  
 可以将生产报表作为数据馈送导出，或者可以创建主要目的是以数据馈送的形式向应用程序提供数据的报表。 将报表用作数据馈送为您在以下情况下提供了另一种向应用程序提供数据的方式：当数据不易通过客户端数据访问接口访问时，或者您更喜欢隐藏数据源的复杂性以使数据的使用更为简便时。 还可以使用 [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] 功能（如安全、计划和报表快照）管理用来提供数据馈送的报表，这是将报表用作数据馈送的另一个优点。  
  
 若要充分利用 Atom 呈现扩展插件，您应该理解报表是如何呈现到数据馈送中的。 如果使用现有报表，则若能预测这些报表能够生成的数据馈送将很有用；如果编写报表的目的是专门用作数据馈送，则重要的是能够包括数据并优化报表布局以充分利用数据馈送。  
  
 有关详细信息，请参阅[从报表生成数据馈送（报表生成器和 SSRS）](../../reporting-services/report-builder/generate-data-feeds-from-a-report-report-builder-and-ssrs.md)。  
  
  
##  <a name="AtomServiceDocument"></a> Atom 服务文档（.atomsvc 文件）  
 Atom 服务文档指定针对一个或多个数据馈送的连接。 该连接至少是指向生成馈送的数据服务的简单 URL。  
  
 使用 Atom 呈现扩展插件呈现报表数据时，Atom 服务文档将列出可用于报表的数据馈送。 该文档为报表中的每个数据区域至少列出一个数据馈送。 表和仪表都只生成一个数据馈送；但矩阵、列表和图表可能生成多个数据馈送，具体取决于它们所显示的数据。  
  
 下图显示了使用两个表和一个图表的报表。  
  
 ![RS_Atom_TableAndChartDataFeeds](../../reporting-services/report-builder/media/rs-atom-tableandchartdatafeeds.gif "RS_Atom_TableAndChartDataFeeds")  
  
 从此报表生成的 Atom 服务文档包括三个数据馈送：两个表各对应一个数据馈送，图表对应一个数据馈送。  
  
 矩阵数据区域可能包括多个数据馈送，这取决于该矩阵的结构。 下图显示的报表使用生成两个数据馈送的矩阵。  
  
 ![RS_Atom_PeerDynamicColumns](../../reporting-services/report-builder/media/rs-atom-peerdynamiccolumns.gif "RS_Atom_PeerDynamicColumns")  
  
 从此报表生成的 Atom 服务文档包括两个数据馈送：两个动态对等列（Territory 和 Year）各对应一个数据馈送。 下图显示了每个数据馈送的内容。  
  
 ![RS_Atom_PeerDynamicDataFeeds](../../reporting-services/report-builder/media/rs-atom-peerdynamicdatafeeds.gif "RS_Atom_PeerDynamicDataFeeds")  
  
  
##  <a name="DataFeeds"></a> 数据馈送  
 数据馈送是一个 XML 文件，它具有一致的不随时间变化的表格格式，以及在每次运行报表时都可能不同的可变数据。 [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] 生成的数据馈送采用与 ADO.NET Data Services 生成的数据馈送相同的格式。  
  
 数据馈送包含两部分：标题和数据。 Atom 规范中定义了各部分中的元素。 标题包括用于数据馈送的字符编码架构之类的信息。  
  
### <a name="header-section"></a>标题部分  
 以下 XML 代码显示数据馈送的标题部分。  
  
 `<?xml version="1.0" encoding="utf-8" standalone="yes"?><feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">`  
  
 `<title type="text"></title>`  
  
 `<id>uuid:1795992c-a6f3-40ec-9243-fbfd0b1a5be3;id=166321</id>`  
  
 `<updated>2009-05-08T23:09:58Z</updated>`  
  
### <a name="data-section"></a>数据部分  
 数据馈送的数据部分为 Atom 呈现扩展插件生成的平展行集中的每一行都包含一个 \<entry> 元素。  
  
 下图显示了使用组和总计的报表。  
  
 ![RS_Atom_ProductSalesSummaryCircledValues](../../reporting-services/report-builder/media/rs-atom-productsalessummarycircledvalues.gif "RS_Atom_ProductSalesSummaryCircledValues")  
  
 下面的 XML 在数据馈送中显示了来自该报表的 \<entry> 元素。 请注意，\<entry> 元素包含该组的销售和订单的总计以及所有组的销售和订单的总计。 \<entry> 元素包含报表中的所有值。  
  
 `<entry><id>uuid:1795992c-a6f3-40ec-9243-fbfd0b1a5be3;id=166322</id><title type="text"></title><updated>2009-05-08T23:09:58Z</updated><author /><content type="application/xml"><m:properties>`  
  
 `<d:ProductCategory_Value>Accessories</d:ProductCategory_Value>`  
  
 `<d:OrderYear_Value m:type="Edm.Int32">2001</d:OrderYear_Value>`  
  
 `<d:SumLineTotal_Value m:type="Edm.Decimal">20235.364608</d:SumLineTotal_Value>`  
  
 `<d:SumOrderQty_Value m:type="Edm.Int32">1003</d:SumOrderQty_Value>`  
  
 `<d:SumLineTotal_Total_2_1 m:type="Edm.Decimal">1272072.883926</d:SumLineTotal_Total_2_1>`  
  
 `<d:SumOrderQty_Total_2_1 m:type="Edm.Double">61932</d:SumOrderQty_Total_2_1>`  
  
 `<d:SumLineTotal_Total_2_2 m:type="Edm.Decimal">109846381.399888</d:SumLineTotal_Total_2_2>`  
  
 `<d:SumOrderQty_Total_2_2 m:type="Edm.Double">274914</d:SumOrderQty_Total_2_2></m:properties></content>`  
  
 `</entry>`  
  
### <a name="working-with-data-feeds"></a>使用数据馈送  
 由报表生成的所有数据馈送都包括生成数据馈送的数据区域父级范围内的报表项。 集成的 SharePoint 站点来生成 Atom 服务文档和数据馈送。 设想有一个报表包含若干表和一个图表。 报表正文中的文本框提供有关每个数据区域的说明性文本。 该报表生成的每个数据馈送中的每个条目都包括该文本框的值。 例如，如果文本为“Chart displays monthly sales averages by sales region”，则所有三个数据馈送都会在每一行中包括此文本。  
  
 如果报表布局包括分层数据关系，如嵌套数据区域，这些关系将包括在报表数据的平展行集中。  
  
 嵌套数据区域的数据行通常较宽，特别是在嵌套表和矩阵包括组和总计的情况下。 您可能会发现，将报表导出到数据馈送并且查看数据馈送以确定生成的数据就是所需数据，这会很有帮助。  
  
 当 Atom 呈现扩展插件创建 Atom 服务文档时，将为数据馈送创建一个唯一标识符，在 URL 中使用该标识符可以查看数据馈送的内容。 示例 Atom 服务文档（如上所示）包括 URL `http://ServerName/ReportServer?%2fProduct+Sales+Summary&rs%3aCommand=Render&rs%3aFormat=ATOM&rc%3aDataFeed=xAx0x1`。 该 URL 标识报表 (Product Sales Summary)、Atom 呈现格式 (ATOM) 以及数据馈送的名称 (xAx0x1)。  
  
 报表项名称默认为报表项的报表定义语言 (RDL) 元素名称，这些名称经常较为直观或容易记忆。 例如，放入报表的第一个矩阵的默认名称为 Tablix 1。 数据馈送使用这些名称。  
  
 若要令数据馈送易于使用，可以使用数据区域的 DataElementName 属性来提供友好名称。 如果为 DataElementName 提供值，数据馈送子元素 \<d> 将使用该值，而不是使用默认的数据区域名称。 例如，如果数据区域的默认名称为 Tablix1，而 DataElementName 设置为 SalesByTerritoryYear，则数据馈送中的 \<d> 将使用 SalesByTerritoryYear。 如果数据区域具有两个数据馈送（类似上述矩阵报表），则数据馈送中使用的名称为 SalesByTerritoryYear _Territory 和 SalesByTerritoryYear _Year。  
  
 如果对报表显示的数据和数据馈送中的数据进行比较，则可能发现一些差异。 报表经常显示格式化的数值和时间/日期数据，但数据馈送包含非格式化的数据。  
  
 数据馈送用 .atom 文件扩展名保存。 可以使用文本或 XML 编辑器（如记事本或 XML 编辑器）来查看文件结构和内容。  
  
  
##  <a name="FlatteningReportData"></a> 平展报表数据  
 Atom 呈现器将报表数据提供为 XML 格式的平展行集。 用于平展数据表的规则与用于 CSV 呈现器的规则相同，只有以下几点例外：  
  
-   范围中的项平展到详细信息级别。 不同于 CSV 呈现器，顶级文本框显示在写入数据馈送的每个条目中。  
  
-   在输出的每一行上呈现报表参数值。  
  
 分层数据和分组数据必须进行平展才能以与 Atom 兼容的格式表示。 呈现扩展插件可将报表平展为用于表示数据区域中嵌套组的树结构。 要平展报表：  
  
-   行层次结构在列层次结构之前进行平展。  
  
-   行层次结构的成员在列层次结构的成员之前呈现到数据馈送。  
  
-   列按照以下顺序排序：表体中的文本框的顺序为从左到右，从上到下，后面紧跟数据区域，后者顺序为从左到右，从上到下。  
  
-   在数据区域中，列按照以下顺序排序：角成员、行层次结构成员、列层次结构成员，然后是单元。  
  
-   对等数据区域是一些共享一个公共数据区域或动态祖先的数据区域或动态组。 对等数据通过平展后的树的分支进行标识。  
  
 有关详细信息，请参阅 [表、矩阵和列表（报表生成器和 SSRS）](../../reporting-services/report-design/tables-matrices-and-lists-report-builder-and-ssrs.md)。  
  
  
##  <a name="AtomRendering"></a> Atom 呈现规则  
 Atom 呈现扩展插件在呈现数据馈送时忽略以下信息：  
  
-   格式设置和布局  
  
-   页眉  
  
-   页脚  
  
-   自定义报表项  
  
-   矩形  
  
-   线条  
  
-   映像  
  
-   自动小计  
  
 对其余的报表项进行排序，先从上到下排，再从左到右排。 之后，每一项将呈现到一列中。 如果报表有嵌套数据项（如列表或表），则会在每一行中重复它的父项。  
  
 下表说明了呈现报表项时这些报表项的外观：  
  
|项|呈现行为|  
|----------|------------------------|  
|表|呈现方式为扩展该表，在只保留最起码的格式的情况下为每一行和每一列都分别创建行和列。 小计行和小计列没有列标题或行标题。 不支持钻取报表。|  
|矩阵|呈现方式为扩展该矩阵，在只保留最起码的格式的情况下为每一行和每一列都分别创建行和列。 小计行和小计列没有列标题或行标题。|  
|列表|为列表中每一明细行或实例呈现一个记录。|  
|子报表|对于内容的每个实例，都会重复它的父项。|  
|图表|为每个图表值呈现具有所有图表标签的记录。 来自系列和类别的标签采用平展的层次结构，并包含在图表值的行中。|  
|数据条|像图表一样呈现。 通常，数据条并不包括层次结构或标签。|  
|迷你图|像图表一样呈现。 通常，迷你图并不包括层次结构或标签。|  
|测量|作为单个记录呈现，具有线性刻度的最小值和最大值、范围的起始和终止值，以及指针的值。|  
|指示器|作为单个记录呈现，具有活动状态名称、可用状态以及数据值。|  
|地图|为每个地图数据区域生成数据馈送。 如果多个地图层使用相同数据区域，数据馈送将包含所有层的数据。 该数据馈送包含一个记录，该记录包含地图层的每个地图成员的标签和值。|  
  
  
##  <a name="DeviceInfo"></a> 设备信息设置  
 您可以更改此呈现器的某些默认设置，包括要使用的编码架构。 有关详细信息，请参阅 [ATOM Device Information Settings](../../reporting-services/atom-device-information-settings.md)。  

## <a name="next-steps"></a>后续步骤

[导出到 CSV 文件](../../reporting-services/report-builder/exporting-to-a-csv-file-report-builder-and-ssrs.md)   
[导出报表](../../reporting-services/report-builder/export-reports-report-builder-and-ssrs.md)  

更多疑问？ [请访问 Reporting Services 论坛](http://go.microsoft.com/fwlink/?LinkId=620231)

namespace backend\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle {

    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/AdminLTE.min.css',
        'css/font-awesome.min.css',
        'css/skins/_all-skins.min.css',
        'css/bootstrap3-wysihtml5.min.css',
        'css/morris.css',
        'css/css.css',
    ];
    public $js = [
        'js/library/jquery-ui.min.js',
        'js/library/morris.min.js',
        'js/library/jquery.slimscroll.min.js',
        'js/library/popup/ejs.js',
        'js/library/popup/tmpl.js',
        'js/library/popup/popup.js',
        'js/library/popup/ajax.js',
        'js/library/fastclick.min.js',
        'js/library/bootstrap.min.js',
        'js/library/bootstrap3-wysihtml5.all.min.js',
        'js/library/base64.js',
        'js/library/textutils.js',
        'js/layout/app.min.js',
        'js/layout/demo.js',
        'js/dev/administrator.js',
        'js/dev/main.js',
        'js/dev/image.js',
        'js/dev/items.js',
        'js/dev/auth.js',
        'js/dev/itemscate.js',
        'js/dev/property.js',
        'js/dev/hotdeal.js',
        'js/dev/search.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];

}
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import datetime as dt

from main_functions import readFile, getData, plotGraph

gpppath = 'all_daily_model_results'
region = 'WI'
site = 'BRW'
start_date = dt.datetime.strptime('2017-01-01', '%Y-%m-%d')   #2017-01-01
end_date = dt.datetime.strptime('2017-12-29', '%Y-%m-%d')   #2017-12-29

doing_GPP = True    #whether or not we're plotting GPP or one of the other variables

mygpp = pd.read_csv("all_daily_model_results.csv", sep=',', skiprows=[1], parse_dates=['year', 'solar_date'], dtype={'GPP':np.float64, 'GPP_lower':np.float64,
                                                                        'GPP_upper':np.float64, 'ER':np.float64, 'ER_lower':np.float64,
                                                                        'ER_upper':np.float64, 'K600':np.float64, 'K600_lower':np.float64,
                                                                        'K600_upper':np.float64}, na_values=['\\N'])
mygpp = mygpp.loc[(mygpp['region']==region) & (mygpp['site']==site)]
mygpp = mygpp.loc[(mygpp['solar_date'] >= start_date) & (mygpp['solar_date'] <= end_date)]
mygpp = mygpp[['solar_date','GPP']]
mygpp.columns = ['DateTime_UTC','value']
READINGS = len(mygpp['value'])      #number of readings of gpp from river! from OC is 687
FRAMESIZE = 1          #how slow we're going through, when one, we go 1frame/0.1sec
#optimal frame for discharge (lightning and pinknoises) is 20 (1frame/2sec)
#for all others, frame=1 is great

path = region + '_' + site + '_' + "sensorData"
variable = "DO_mgL"

myfile = pd.read_csv('csv_files/' + 'Complete_Sensor_Data/' + path + '.csv', sep=',')
myfile['DateTime_UTC'] = pd.to_datetime(myfile['DateTime_UTC'], format='%Y-%m-%d %H:%M:%S')
myfile['value'] = pd.to_numeric(myfile['value'])
myfile = myfile.loc[(myfile['DateTime_UTC'] >= start_date) & (myfile['DateTime_UTC'] <= end_date)]
myfile = myfile.loc[myfile['variable'] == variable]
myfile = myfile[['DateTime_UTC','value']]

myvalues = pd.DataFrame()
skipby = 1

if(doing_GPP):
    myvalues = mygpp
    variable = 'GPP'
    skipby = 1
else:
    myvalues = myfile
    skipby = myvalues.size / READINGS * FRAMESIZE


title = region + ', ' + site + ', ' + variable
y = np.array(myvalues['value'])
x = np.array(myvalues['DateTime_UTC'])
varplot = pd.DataFrame(y,x)

Writer = animation.writers['ffmpeg']
writer = Writer(fps=10, metadata=dict(artist='Me'), bitrate=1800)

fig = plt.figure(figsize=(10,6))
plt.title(title)
plt.plot_date(x,y)
plt.xlabel(variable)
plt.ylabel('Time Stamp')
plt.title(variable + ' over time', fontsize=22)

#plt.clf()

#def init():
#    scat.set_offsets([])
#    return scat

def animate(i):
    data = myvalues.iloc[:int((i+1) * skipby)] #select data range
    p = sns.lineplot(x=data['DateTime_UTC'], y=data['value'], data=data, color="r")
    p.tick_params(labelsize=17)
    plt.setp(p.lines,linewidth=7)

#def animate(i):
#    data = np.hstack((x[:i,np.newaxis], y[:i, np.newaxis]))
#    scat.set_offsets(data)
#    return scat

#init_func=init,
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=int(READINGS/FRAMESIZE),
                               interval=100, blit=False, repeat=True)

ani.save('mp4_files/' + region + '_' + site + '_' + variable + '_animation.mp4', writer=writer)

# ἐπίνοια -ας, ἡ

<!-- Status: S2=NeedsEdits -->
<!-- Lexica used for edits:   -->

## Word data

* Strongs: G19630

* Alternate spellings:



* Principle Parts: 


* Part of speech: 


* Instances in Scripture: 1

* All Scriptures cited: Yes

## Etymology: 

[ἐπινοέω](), to contrive

* LXX/Hebrew glosses: 


* Time Period/Ancient Authors: 


* Related words: 

* Antonyms for all senses

* Synonyms for all senses: 


## Senses 


### Sense  1.0: 

#### Definition: 

#### Glosses: 

a thought, design; 

#### Explanation: 


#### Citations: 

a thought, design: [Ac 8:22](Act 8:22).†

#include <debug.h>
#include <arch.h>
#include <arch/ops.h>
#include <arch/arm64.h>
#include <arch/arm64/mmu.h>
#include <platform.h>

void arch_early_init(void)
{
    /* set the vector base */
    ARM64_WRITE_SYSREG(VBAR_EL1, (uint64_t)&arm64_exception_base);

    /* switch to EL1 */
    unsigned int current_el = ARM64_READ_SYSREG(CURRENTEL) >> 2;
    if (current_el > 1) {
        arm64_el3_to_el1();
    }

    platform_init_mmu_mappings();
}

void arch_init(void)
{
}

void arch_quiesce(void)
{
}

void arch_idle(void)
{
    __asm__ volatile("wfi");
}

void arch_chain_load(void *entry, ulong arg0, ulong arg1, ulong arg2, ulong arg3)
{
    PANIC_UNIMPLEMENTED;
}
<!DOCTYPE HTML>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>

<html lang="en" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#"><head>

	<!-- common -->
	<title>Heatbud | Social Blogging for Bloggers and Businesses</title>
	<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
	<link rel="alternate" type="application/rss+xml" href="https://www.heatbud.com/do/rss" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />

	<!-- icons -->
	<link rel="shortcut icon" href="/resources/images/favicon.ico" type="image/x-icon"/>
    <link rel="apple-touch-icon" href="/resources/images/apple-touch-icon.png"/>
	<link rel="apple-touch-icon" sizes="152x152" href="/resources/images/apple-touch-icon-152x152.png"/>
	<link rel="apple-touch-icon" sizes="144x144" href="/resources/images/apple-touch-icon-144x144.png"/>
	<link rel="apple-touch-icon" sizes="120x120" href="/resources/images/apple-touch-icon-120x120.png"/>
	<link rel="apple-touch-icon" sizes="114x114" href="/resources/images/apple-touch-icon-114x114.png"/>
	<link rel="apple-touch-icon" sizes="76x76" href="/resources/images/apple-touch-icon-76x76.png"/>
	<link rel="apple-touch-icon" sizes="72x72" href="/resources/images/apple-touch-icon-72x72.png"/>
	<link rel="apple-touch-icon" sizes="57x57" href="/resources/images/apple-touch-icon-57x57.png"/>
    <link rel="apple-touch-icon-precomposed" href="/resources/images/apple-touch-icon-76x76.png">
    <link rel="icon" sizes="32x32" href="/resources/images/favicon.ico">
    <meta name="msapplication-TileColor" content="#d3ede7">
	<meta name="msapplication-TileImage" content="/resources/images/apple-touch-icon-114x114.png">

	<!-- for Open Graph (facebook) -->
	<meta property="og:type" content="website"/>
	<meta property="og:title" content="Heatbud | Social Blogging for Businesses"/>
    <meta property="og:description" content="Create Social Blog for your business starting $29 a month. OR, Add Social Blogging to your Business starting $29 a month!"/>
	<meta property="og:url" content="https://www.heatbud.com/top/posts-trending-now"/>
	<meta property="og:image" content="https://www.heatbud.com/resources/images/fb-share-picture.png"/>
	<meta property="og:site_name" content="Heatbud"/>
	<meta property="fb:app_id" content="1444142922465514"/>

	<!-- for Google -->
    <meta name="description" content="Heatbud helps you write sophisticated posts and share them with the world instantly."/>
    <meta name="keywords" content="Social Blogging, Blogging, Business Website, Business, Website, Business Traffic, Traffic"/>
	<meta name="application-name" content="Heatbud"/>
	<link rel="publisher" href="https://plus.google.com/+Heatbud"/>
	<link rel="canonical" href="https://www.heatbud.com/top/posts-trending-now"/>

	<!-- JS includes -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<script src="/resources/js/heatbud-top-charts-min.js?20180530"></script>

    <!-- CSS includes -->
	<link type='text/css' rel='stylesheet' href="https://fonts.googleapis.com/css?family=Arvo%7CDroid+Sans+Mono%7CFauna+One%7CImprima%7CLato%7CMarvel%7COffside%7COpen+Sans%7COxygen+Mono%7CPermanent+Marker%7CRaleway%7CRoboto+Mono%7CScope+One%7CText+Me+One%7CUbuntu">
	<link type="text/css" href="/resources/css/main-min.css?20180530" media="screen" rel="stylesheet"/>

</head><body style="position:relative; background-color:rgb(248, 250, 252)">

	<%-- Begin pretty number --%>
	<script>
	function prettyNumber(n) {
		if ( n < 1000 ) {
			return n;
		} else if ( n >= 1000 && n < 1000000 ) {
			return Math.round(n*10/1000)/10+'k';
		} else {
			return Math.round(n*10/1000000)/10+'m';
		}
	}
	</script>
	<%-- End pretty number --%>

	<%-- Begin header --%>
	<table class="header"><tr style="width:100%">
		<td style="float:left">
			<a href="/"><img alt="Heatbud logo" style="width:140px; padding-top:2px; margin-left:20px; border:none" src="/resources/images/heatbud-logo.png"/></a>
		</td>
		<td style="float:right; font-size:13px; padding-top:14px; padding-bottom:6px">
			<div style="float:left; margin-right:8px"><a href="/top/posts-trending-now" class="mainSelection">TOP CHARTS</a></div>
			<div style="float:left; margin-right:8px"><a href="/post/singing-bowls-singing-bowls-and-chakras" class="mainSelection">BLOG POSTS</a></div>
			<div style="float:left; margin-right:8px"><a href="/do/search" class="mainSelection">SEARCH</a></div>
			<div style="float:left; margin-right:8px"><a href="/do/help" class="mainSelection">HELP CENTER</a></div>
			<sec:authorize access="!isAuthenticated()">
				<div style="float:left"><a href="/do/login" class="mainSelection">LOGIN / SIGNUP</a></div>
			</sec:authorize>
			<sec:authorize access="isAuthenticated()">
				<div style="float:left; font-size:16px">
					<ul id="nav" style="margin-top:0px; margin-bottom:0px">
						<li>
							<span style="color:#ffffff; letter-spacing:1.5px"><sec:authentication property="principal.firstName"/> <sec:authentication property="principal.lastName"/> <img src="/resources/images/menu_header.png" style="padding-left:5px; height:15px"></span>
							<ul>
								<li><a href="/<sec:authentication property="principal.userId"/>" style="margin-top:10px; padding-top:10px">Profile</a></li>
								<li><a href="/user/settings" style="padding-top:10px">Settings</a></li>
								<li><a href="/user/notifications" style="padding-top:10px">Notifications</a></li>
								<li><a href="/user/pages" style="padding-top:10px">Page Manager</a></li>
								<li><a href="/user/orders" style="padding-top:10px">Orders</a></li>
								<li><a href="/user/images" style="padding-top:10px">Images</a></li>
								<li><a href="/user/posts" style="padding-top:10px">Unpublished Posts</a></li>
								<li><a href="<c:url value="/do/logout"/>" style="padding-top:10px">Logout</a></li>
								<li><a href="/user/drop" style="padding-top:10px; padding-bottom:30px">Drop Account</a></li>
							</ul>
						</li>
					</ul>
				</div>
			</sec:authorize>
		</td>
	</tr></table>
	<div style="clear:both"></div>
	<%-- End header --%>

	<%-- Begin page content --%>
	<input id=topChartsNameHidden type=hidden value="${topChartsName}">
	<input id=generateTopChartsJobPeriodHidden type=hidden value="${generateTopChartsJobPeriod}">

	<table style="border-spacing:2px; width:96%; padding-top:60px; margin-left:4%">

	<tr><td colspan="2">
		<%-- Social Blogging revolution --%>
		<div style="width:70%; background-color:#87bdd8; border-radius:4px; padding:10px 30px; margin:0 auto">
			<div style="color:yellow; font-size:1.8em">Join the Social Blogging revolution!</div>
			<div style="width:38%; float:left; color:white; font-size:1.6em">
				<div>For Bloggers</div>
				<div style="font-size:0.7em"><a style="color:white" href="/do/help/main/pricing">&bull; I want to earn followers</a></div>
				<div style="font-size:0.7em"><a style="color:white" href="/do/help/main/pricing">&bull; I want to earn money</a></div>
			</div>
			<div style="width:60%; float:left; color:white; font-size:1.6em">
				<div>For Businesses</div>
				<div style="font-size:0.7em"><a style="color:white" href="/do/help/main/why-1">&bull; I want to create a new website</a></div>
				<div style="font-size:0.7em"><a style="color:white" href="/do/help/main/why-1">&bull; I want to add Social Blog to my existing website</a></div>
			</div>
			<div style="clear:both"></div>
		</div>
	</td></tr>

	<tr><td style="width:65%; vertical-align:top">

		<%-- Page Title --%>
		<div style="float:right">
			<ul id="nav" style="z-index:3">
				<li>
					<div style="font-family:Calibri, Arial, Sans-serif; font-weight:bold; font-size:1.5em; background-color:#FD8A33; color:white; letter-spacing:3px; padding:3px 13px 7px 20px; border-radius:5px">
						<span>${pageTitle}</span>
						<span><img alt="top charts menu" src="/resources/images/menu.png" style="padding-left:8px; height:24px"></span>
					</div>
					<ul style="width:160px">
						<li style="padding-top:6px; padding-left:6px; font-weight:bold; color:#333333; margin-top:15px">TRENDING NOW</li>
						<li><div onclick="switchChart('posts-trending-now')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">POSTS</div></li>
						<li><div onclick="switchChart('zones-trending-now')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">ZONES</div></li>
						<li><div onclick="switchChart('bloggers-trending-now')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">BLOGGERS</div></li>
						<li><div onclick="switchChart('pages-trending-now')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">PAGES</div></li>
						<li style="padding-top:6px; padding-left:6px; font-weight:bold; color:#333333; margin-top:6px">ALL TIME</li>
						<li><div onclick="switchChart('posts-all-time')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">POSTS</div></li>
						<li><div onclick="switchChart('bloggers-all-time')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">BLOGGERS</div></li>
						<li><div onclick="switchChart('pages-all-time')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; cursor:pointer">PAGES</div></li>
						<li style="padding-top:6px; padding-left:6px; font-weight:bold; color:#333333; margin-top:6px">JUST PUBLISHED</li>
						<li><div onclick="switchChart('posts-just-published')" style="color:#0E8D9E; padding-top:6px; padding-left:12px; margin-bottom:40px; cursor:pointer">POSTS</div></li>
					</ul>
				</li>
			</ul>
		</div>
		<div style="clear:both"></div>
	</td><td style="width:28%; vertical-align:top"></td></tr>

	<tr>
		<td style="width:65%; vertical-align:top; padding-right:11px">

			<div id="topChartsDiv">

				<%-- Top Charts for Posts --%>
				<c:if test="${fn:contains(topChartsName,'post')}">
					<c:forEach var="post" items="${topChartsList}" varStatus="loopStatus">
						<div class="topChartsElement" style="float:right">
							<div style="font-size:18px; font-weight:bold; padding:10px 20px">
								<a href="/post/${post.postId}">${post.postTitle}</a>
							</div>
							<div onclick="location.href='/post/${post.postId}'" class="topChartsThumb grow" style="margin:0 auto; background-image:url(${post.postHeadshot})"></div>
							<div style="font-size:15px; padding:10px 20px">
								<span style="font-size:13px; color:rgb(144, 144, 144)"> By </span>
								<span><a href="/${post.bloggerId}">${post.bloggerName}</a></span>
								<span style="font-size:13px; color:rgb(144, 144, 144)"> Zone </span>
								<span><a href="/zone/${post.zoneId}">${fn:escapeXml(post.zoneName)}</a></span>
							</div>
							<c:if test="${fn:contains(topChartsName,'just')}">
								<div style="padding:3px 20px; color:#8A8C8E"><script>document.write(new Date(${post.updateDate}).toLocaleString());</script></div>
							</c:if>
							<div style="padding:3px 20px">${post.postSummary}</div>
							<div style="padding:5px 20px">
								<img alt="Overall Heat Index" title="Overall Heat Index" style="width:14px; height:18px; border:none" src="/resources/images/favicon.ico"/>
								<span title="Overall Heat Index" style="color:#7A7C7E; font-size:17px"><script>document.write(prettyNumber(${post.hi}));</script></span>
								<c:if test="${fn:contains(topChartsName,'trending')}">
									<c:if test="${post.hiTrending >= 0}">
										<span><img alt="This week's change" title="This week's change" style="width:8px; height:8px; border:none; margin-left:10px" src="/resources/images/trending-up.png"></span>
										<span title="This week's change" style="color:#8A8C8E; font-size:10px">${post.hiTrending}</span>
									</c:if>
									<c:if test="${post.hiTrending < 0}">
										<span><img alt="This week's change" title="This week's change" style="width:8px; height:8px; border:none; margin-left:10px" src="/resources/images/trending-down.png"></span>
										<span title="This week's change" style="color:#8A8C8E; font-size:10px">${-post.hiTrending}</span>
									</c:if>
								</c:if>
							</div>
						</div>
						<c:if test="${loopStatus.index % 2 == 1}">
							<div style="clear:both"></div>
						</c:if>
					</c:forEach>
				</c:if>

				<%-- Top Charts for Zones --%>
				<c:if test="${fn:contains(topChartsName,'zone')}">
					<c:forEach var="zone" items="${topChartsList}" varStatus="loopStatus">
						<div class="topChartsElement" style="float:right">
							<div style="font-size:18px; font-weight:bold; padding:10px 20px">
								<a href="/zone/${zone.zoneId}">${zone.zoneName}</a>
							</div>
							<div onclick="location.href='/zone/${zone.zoneId}'" class="topChartsThumb grow" style="margin:0 auto; background-image:url(${zone.zoneHeadshot})"></div>
							<div style="padding:3px 20px">${zone.zoneDesc}</div>
							<div style="font-size:12px; color:#909090; padding:5px 20px">
								<span>${zone.posts} posts</span>
								<span style="font-weight:bold; color:rgb(144, 144, 144)">&nbsp;.&nbsp;</span>
								<span>${zone.comments} comments</span>
							</div>
						</div>
						<c:if test="${loopStatus.index % 2 == 1}">
							<div style="clear:both"></div>
						</c:if>
					</c:forEach>
				</c:if>

				<%-- Top Charts for entities (bloggers and pages) --%>
				<c:if test="${fn:contains(topChartsName,'blogger') || fn:contains(topChartsName,'page')}">
					<c:forEach var="entity" items="${topChartsList}"  varStatus="loopStatus">
						<div class="topChartsElement" style="float:right">
							<div style="font-size:18px; padding:10px 20px; font-weight:bold">
								<a href="/${entity.entityId}">${entity.entityName}</a>
							</div>
							<c:if test="${empty entity.profilePhoto}">
								<c:if test="${fn:contains(topChartsName,'blogger')}">
									<div onclick="location.href='/${entity.entityId}'" class="topChartsThumb grow" style="margin:0 auto; background-image:url('/resources/images/def-blogger-photo.jpg')"></div>
								</c:if>
								<c:if test="${fn:contains(topChartsName,'page')}">
									<div onclick="location.href='/${entity.entityId}'" class="topChartsThumb grow" style="margin:0 auto; background-image:url('/resources/images/def-page-photo.jpg')"></div>
								</c:if>
							</c:if>
							<c:if test="${not empty entity.profilePhoto}">
								<div onclick="location.href='/${entity.entityId}'" class="topChartsThumb grow" style="margin:0 auto; background-image:url('${entity.profilePhoto}')"></div>
							</c:if>
							<div style="padding:3px 20px; white-space:pre-line">${entity.about}</div>
							<div style="padding:3px 20px">
								<img alt="Overall Heat Index" title="Overall Heat Index" style="width:14px; height:18px; border:none" src="/resources/images/favicon.ico"/>
								<span title="Overall Heat Index" style="color:#7A7C7E; font-size:17px"><script>document.write(prettyNumber(${entity.hi}));</script></span>
								<c:if test="${fn:contains(topChartsName,'trending')}">
									<c:if test="${entity.hiTrending >= 0}">
										<span><img alt="This week's change" title="This week's change" style="width:8px; height:8px; border:none; margin-left:10px" src="/resources/images/trending-up.png"></span>
										<span title="This week's change" style="color:#8A8C8E; font-size:10px">${entity.hiTrending}</span>
									</c:if>
									<c:if test="${entity.hiTrending < 0}">
										<span><img alt="This week's change" title="This week's change" style="width:8px; height:8px; border:none; margin-left:10px" src="/resources/images/trending-down.png"></span>
										<span title="This week's change" style="color:#8A8C8E; font-size:10px">${-entity.hiTrending}</span>
									</c:if>
								</c:if>
							</div>
							<div style="font-size:12px; color:#909090; padding:5px 20px">
								<span>${entity.posts} posts</span>
								<span style="font-weight:bold; color:rgb(144, 144, 144)">&nbsp;.&nbsp;</span>
								<span>${entity.votes} votes</span>
								<span style="font-weight:bold; color:rgb(144, 144, 144)">&nbsp;.&nbsp;</span>
								<span>${entity.comments} comments</span>
							</div>
						</div>
						<c:if test="${loopStatus.index % 2 == 1}">
							<div style="clear:both"></div>
						</c:if>
					</c:forEach>
				</c:if>
			</div>

			<%-- Top Charts navigation --%>
			<div id="topChartsNavigation">
				<%-- previous page link will be hidden on the first page --%>
				<input type=hidden id=topChartsKeyPrevIdHidden value="NULL">
				<input type=hidden id=topChartsKeyPrevHIHidden value="NULL">
				<div id="getTopChartsPreviousDiv" style="width:45%; margin-top:10px; margin-left:15px; float:left; text-align:left; visibility:hidden">
					<a id="getTopChartsPrevious" class="topNextPrev" href="javascript:">BACK</a>
				</div>
				<%-- next page link will be set to visible if the key is not NULL --%>
				<input type=hidden id=topChartsKeyNextIdHidden value="${topChartsKeyNextId}">
				<input type=hidden id=topChartsKeyNextHIHidden value="${topChartsKeyNextHI}">
				<c:if test="${topChartsKeyNextId != 'NULL'}">
					<div id="getTopChartsNextDiv" style="width:45%; margin-top:10px; margin-right:56px; float:right; text-align:right">
						<a id="getTopChartsNext" class="topNextPrev" href="javascript:">MORE</a>
					</div>
				</c:if>
			</div>
			<div style="clear:both"></div>

		</td>
		<td style="width:28%; vertical-align:top">
			<%-- Facebook --%>
			<div class="friendFacebook" style="float:right">
				<a style="color:white" target="_blank" href="https://www.facebook.com/heatbud">Like us on Facebook</a>
			</div>
			<div style="clear:both"></div>
			<%-- Ticker --%>
			<div style="margin-top:10px; margin-bottom:5px; color:#797979; font-size:15px">Recent activity</div>
			<div style="border:1px solid #d1d1d1; padding:20px 10px 30px 20px; background-color:white">
				<c:forEach var="ticker" items="${tickersList}" varStatus="counter">
					<div style="margin-bottom:25px">
						<span style="color:#8A8C8E">&#9898;</span>
						<span style="color:#8A8C8E"><script>document.write(new Date(${ticker.tickerTime}).toLocaleString());</script></span><br/>
						<span>${ticker.tickerDesc}</span>
					</div>
				</c:forEach>
			</div>
		</td>

	</tr></table>

	<%-- Google Ads Horizontal --%>
	<div style="width:100%; text-align:center; margin-top:30px; margin-bottom:40px">
		<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
		<ins class="adsbygoogle"
		     style="display:inline-block;width:728px;height:90px"
		     data-ad-client="ca-pub-3344897177583439"
		     data-ad-slot="5851386905">
		</ins>
		<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
	</div>

	<%-- Begin footer --%>
	<div class="footer">
		<div style="float: right; margin-right: 40px">
			<a href="/top/posts-trending-now">Home</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/help">Help Center</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/privacy">Privacy &amp; Terms</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/partnerships">Partnerships</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/careers">Careers</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/contact">Contact Us</a>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href="/do/newsletters">Newsletters</a>
		</div>
	</div>
	<%-- End footer --%>

	<!-- Google analytics -->
	<script>
	  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
	  ga('create', 'UA-48436913-1', 'heatbud.com');
	  ga('send', 'pageview');
	</script>

</body></html>
#include <time.h>

typedef int (*timer_gettime_test)(timer_t, struct itimerspec *);

int dummyfcn (void)
{
	timer_gettime_test dummyvar;
	dummyvar = timer_gettime;
	return 0;
}
﻿' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.InvertIf
    <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InvertMultiLineIf), [Shared]>
    Friend NotInheritable Class VisualBasicInvertMultiLineIfCodeRefactoringProvider
        Inherits VisualBasicInvertIfCodeRefactoringProvider(Of MultiLineIfBlockSyntax)

        <ImportingConstructor>
        <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
        Public Sub New()
        End Sub

        Protected Overrides Function IsElseless(ifNode As MultiLineIfBlockSyntax) As Boolean
            Return ifNode.ElseBlock Is Nothing
        End Function

        Protected Overrides Function CanInvert(ifNode As MultiLineIfBlockSyntax) As Boolean
            Return ifNode.ElseIfBlocks.IsEmpty
        End Function

        Protected Overrides Function GetCondition(ifNode As MultiLineIfBlockSyntax) As SyntaxNode
            Return ifNode.IfStatement.Condition
        End Function

        Protected Overrides Function GetIfBody(ifNode As MultiLineIfBlockSyntax) As SyntaxList(Of StatementSyntax)
            Return ifNode.Statements
        End Function

        Protected Overrides Function GetElseBody(ifNode As MultiLineIfBlockSyntax) As SyntaxList(Of StatementSyntax)
            Return ifNode.ElseBlock.Statements
        End Function

        Protected Overrides Function UpdateIf(
                sourceText As SourceText,
                ifNode As MultiLineIfBlockSyntax,
                condition As SyntaxNode,
                trueStatement As SyntaxList(Of StatementSyntax),
                Optional falseStatementOpt As SyntaxList(Of StatementSyntax) = Nothing) As MultiLineIfBlockSyntax

            Dim updatedIf = ifNode _
                .WithIfStatement(ifNode.IfStatement.WithCondition(DirectCast(condition, ExpressionSyntax))) _
                .WithStatements(trueStatement)

            If falseStatementOpt.Count > 0 Then
                updatedIf = updatedIf.WithElseBlock(SyntaxFactory.ElseBlock(falseStatementOpt))
            End If

            Return updatedIf
        End Function
    End Class
End Namespace


;;; orary-rust.el --- Rust support for Orary
;;
;;; Commentary:
;; Maybe rust is nice? I'm unlikely to be able to tell if my editor isn't set up for it ;P
;;; Code:

(require 'orary-braces)
(require 'orary-functions)

(use-package cargo)         ;; Build tool wrapper
(use-package racer)         ;; Symbol completion, introspection
(use-package flycheck-rust) ;; Syntax checking

(defun orary/rust-ret-dwim (arg)
  (interactive "P")

  (cond
   ;; We're in a pair of {}, open them
   ((and (looking-at "}")
         (looking-back "{" (- (point) 2)))
    (orary/braces-open-pair))

   ;; We're opening a match; insert {}, open, then expand a yasnippet
   ((looking-back "match.*" (line-beginning-position))
    (sp-insert-pair "{")
    (orary/braces-open-pair)
    ;; NOTE[rdonaldson|2020-05-31] with LSP mode, it's often more ergonomic to
    ;; use an lsp action to fill in match arms. Reconsidering this; might gate
    ;; it behind C-u.
    ;; (yas-expand-snippet "$1 => $0,")
    )

   ;; We're defining an if/else, while, function, struct, enum, unsafe, or trait; insert {}, then open
   ((looking-back "if.*\\|else.*\\|while.*\\|fn .*\\|\\<impl\\>.*\\|trait.*\\|struct.*\\|enum.*\\|mod.*\\|for.*\\|unsafe.*\\|async.*" (line-beginning-position))
    (sp-insert-pair "{")
    (orary/braces-open-pair))

   ;; We're in a match expression
   ((looking-back "=>.*" (line-beginning-position))
    (end-of-line)
    ;; With a prefix arg, jump out of the match
    (if arg
        (progn
          (re-search-forward "}")
          (newline-and-indent))
      (progn
        (unless (looking-back "," (- (point) 1))
          (insert-char ?,))
        (newline-and-indent)
        (yas-expand-snippet "$1 => $0,"))))

   ;; Default: try to add a ; and newline
   (t
    (unless (eolp)
      (re-search-forward ")"))

    (unless (or (looking-at ";")
                (looking-back ";" (- (point) 1))
                (looking-back "^\\s-+" (line-beginning-position)))
      (insert-char ?\;))
    (end-of-line)
    (newline-and-indent))))

(defun orary/rust-insert-arrow ()
  (interactive)
  (orary/insert-key-seq "-" ">" "<")
  (set-transient-map
   (let ((map (make-sparse-keymap)))
     (define-key map (kbd "-") #'orary/rust-insert-arrow)
     map)))

;; The Business
(use-package rust-mode
  :config
  (setq cargo-process--command-clippy "clippy")
  (add-hook 'rust-mode-hook
            (lambda ()
              (cargo-minor-mode +1)
              (subword-mode +1)
              (lsp)
              (flycheck-add-next-checker 'lsp 'rust-clippy)
              (setq comment-start "//")))

  (add-hook 'racer-mode-hook #'eldoc-mode)
  (add-hook 'racer-mode-hook #'company-mode)

  :bind (:map rust-mode-map
              ("C-c C-c" . #'rust-compile)
              ("<C-return>" . #'orary/rust-ret-dwim)
              ("C-o" . #'orary/braces-open-newline)
              ("-" . #'orary/rust-insert-arrow))
  )

(provide 'orary-rust)
;;; orary-rust.el ends here

<?php

namespace Tg\OkoaBundle\Response;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use RuntimeException;

/**
 * Respond with the contents of a file.
 */
class FileResponse extends Response
{

    protected $disposition;

    protected $filename;

    protected $file;

    public function __construct($file, $attach = false, $filename = null)
    {
        parent::__construct(null, 200, [
            'Content-Type' => 'application/octet-stream'
        ]);
        if ($attach) {
            $this->setDispositionAttachment();
        } else {
            $this->setDispositionInline();
        }
        $this->setFile($file);
        $this->setFilename($filename);
        $this->setPrivate();
    }

    public function setContentType($type)
    {
        $this->headers->set('Content-Type', $type);
    }

    public function setDispositionAttachment()
    {
        $this->disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT;
        $this->updateProps();
    }

    public function setDispositionInline()
    {
        $this->disposition = ResponseHeaderBag::DISPOSITION_INLINE;
        $this->updateProps();
    }

    public function setFilename($name)
    {
        $this->filename = $name;
        $this->updateProps();
    }

    public function getFilesize()
    {
        if (is_string($this->file)) {
            return filesize($this->file);
        } else {
            fseek($this->file, 0, SEEK_END);
            $size = ftell($this->file);
            rewind($this->file);
            return $size;
        }
    }

    public function setFile($file, $determineType = true)
    {
        if (is_string($file)) {
            if (!file_exists($file) || !is_readable($file)) {
                throw new RuntimeException("Could not read file '$file'");
            }
        }
        $this->file = $file;
        if (is_string($file) && $determineType) {
            $this->tryDetermineType();
        }
        $this->updateProps();
    }

    public function tryDetermineType()
    {
        if (is_string($this->file) && strlen($this->file) > 0) {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $this->file);
            if (is_string($mime) && strlen($mime) > 0) {
                $this->setContentType($mime);
            }
            finfo_close($finfo);
        }
    }

    public function sendContent()
    {
        if (is_resource($this->file)) {
            $size = $this->getFilesize();
            rewind($this->file);
            print fread($this->file, $size);
        } else {
            readfile($this->file);
        }
    }

    protected function updateProps()
    {
        if (is_string($this->file) || is_resource($this->file)) {
            $disp = $this->disposition;
            if ($disp !== ResponseHeaderBag::DISPOSITION_INLINE && $this->filename !== null) {
                $disp .= '; filename=' . $this->filename;
            }
            $this->headers->set('Content-Disposition', $disp);
            $this->headers->set('Content-Length', $this->getFilesize());
        } else {
            $this->headers->remove('Content-Disposition');
            $this->headers->remove('Content-Length');
        }
    }
}

#include "includes.h"
#include "lib/util/dlinklist.h"
#include "smb_server/smb_server.h"
#include "smbd/service_stream.h"
#include "ntvfs/ntvfs.h"

struct socket_address *smbsrv_get_my_addr(void *p, TALLOC_CTX *mem_ctx)
{
	struct smbsrv_connection *smb_conn = talloc_get_type(p,
					     struct smbsrv_connection);

	return socket_get_my_addr(smb_conn->connection->socket, mem_ctx);
}

struct socket_address *smbsrv_get_peer_addr(void *p, TALLOC_CTX *mem_ctx)
{
	struct smbsrv_connection *smb_conn = talloc_get_type(p,
					     struct smbsrv_connection);

	return socket_get_peer_addr(smb_conn->connection->socket, mem_ctx);
}

/****************************************************************************
init the tcon structures
****************************************************************************/
static NTSTATUS smbsrv_init_tcons(struct smbsrv_tcons_context *tcons_ctx, TALLOC_CTX *mem_ctx, uint32_t limit)
{
	/* 
	 * the idr_* functions take 'int' as limit,
	 * and only work with a max limit 0x00FFFFFF
	 */
	limit &= 0x00FFFFFF;

	tcons_ctx->idtree_tid	= idr_init(mem_ctx);
	NT_STATUS_HAVE_NO_MEMORY(tcons_ctx->idtree_tid);
	tcons_ctx->idtree_limit	= limit;
	tcons_ctx->list		= NULL;

	return NT_STATUS_OK;
}

NTSTATUS smbsrv_smb_init_tcons(struct smbsrv_connection *smb_conn)
{
	return smbsrv_init_tcons(&smb_conn->smb_tcons, smb_conn, UINT16_MAX);
}

NTSTATUS smbsrv_smb2_init_tcons(struct smbsrv_session *smb_sess)
{
	return smbsrv_init_tcons(&smb_sess->smb2_tcons, smb_sess, UINT32_MAX);
}

/****************************************************************************
find a tcon given a tid for SMB
****************************************************************************/
static struct smbsrv_tcon *smbsrv_tcon_find(struct smbsrv_tcons_context *tcons_ctx,
					    uint32_t tid, struct timeval request_time)
{
	void *p;
	struct smbsrv_tcon *tcon;

	if (tid == 0) return NULL;

	if (tid > tcons_ctx->idtree_limit) return NULL;

	p = idr_find(tcons_ctx->idtree_tid, tid);
	if (!p) return NULL;

	tcon = talloc_get_type(p, struct smbsrv_tcon);
	if (!tcon) return NULL;

	tcon->statistics.last_request_time = request_time;

	return tcon;
}

struct smbsrv_tcon *smbsrv_smb_tcon_find(struct smbsrv_connection *smb_conn,
					 uint32_t tid, struct timeval request_time)
{
	return smbsrv_tcon_find(&smb_conn->smb_tcons, tid, request_time);
}

struct smbsrv_tcon *smbsrv_smb2_tcon_find(struct smbsrv_session *smb_sess,
					  uint32_t tid, struct timeval request_time)
{
	if (!smb_sess) return NULL;
	return smbsrv_tcon_find(&smb_sess->smb2_tcons, tid, request_time);
}

/*
  destroy a connection structure
*/
static int smbsrv_tcon_destructor(struct smbsrv_tcon *tcon)
{
	struct smbsrv_tcons_context *tcons_ctx;
	struct socket_address *client_addr;

	client_addr = socket_get_peer_addr(tcon->smb_conn->connection->socket, tcon);
	DEBUG(3,("%s closed connection to service %s\n",
		 client_addr ? client_addr->addr : "(unknown)",
		 tcon->share_name));

	/* tell the ntvfs backend that we are disconnecting */
	if (tcon->ntvfs) {
		ntvfs_disconnect(tcon->ntvfs);
		tcon->ntvfs = NULL;
	}

	if (tcon->smb2.session) {
		tcons_ctx = &tcon->smb2.session->smb2_tcons;
	} else {
		tcons_ctx = &tcon->smb_conn->smb_tcons;
	}

	idr_remove(tcons_ctx->idtree_tid, tcon->tid);
	DLIST_REMOVE(tcons_ctx->list, tcon);
	return 0;
}

/*
  find first available connection slot
*/
static struct smbsrv_tcon *smbsrv_tcon_new(struct smbsrv_connection *smb_conn,
					   struct smbsrv_session *smb_sess,
					   const char *share_name)
{
	TALLOC_CTX *mem_ctx;
	struct smbsrv_tcons_context *tcons_ctx;
	uint32_t handle_uint_max;
	struct smbsrv_tcon *tcon;
	NTSTATUS status;
	int i;

	if (smb_sess) {
		mem_ctx = smb_sess;
		tcons_ctx = &smb_sess->smb2_tcons;
		handle_uint_max = UINT32_MAX;
	} else {
		mem_ctx = smb_conn;
		tcons_ctx = &smb_conn->smb_tcons;
		handle_uint_max = UINT16_MAX;
	}

	tcon = talloc_zero(mem_ctx, struct smbsrv_tcon);
	if (!tcon) return NULL;
	tcon->smb_conn		= smb_conn;
	tcon->smb2.session	= smb_sess;
	tcon->share_name	= talloc_strdup(tcon, share_name);
	if (!tcon->share_name) goto failed;

	/*
	 * the use -1 here, because we don't want to give away the wildcard
	 * fnum used in SMBflush
	 */
	status = smbsrv_init_handles(tcon, handle_uint_max - 1);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1,("ERROR! failed to init handles: %s\n", nt_errstr(status)));
		goto failed;
	}

	i = idr_get_new_random(tcons_ctx->idtree_tid, tcon, tcons_ctx->idtree_limit);
	if (i == -1) {
		DEBUG(1,("ERROR! Out of connection structures\n"));
		goto failed;
	}
	tcon->tid = i;

	DLIST_ADD(tcons_ctx->list, tcon);
	talloc_set_destructor(tcon, smbsrv_tcon_destructor);

	/* now fill in some statistics */
	tcon->statistics.connect_time = timeval_current();

	return tcon;

failed:
	talloc_free(tcon);
	return NULL;
}

struct smbsrv_tcon *smbsrv_smb_tcon_new(struct smbsrv_connection *smb_conn, const char *share_name)
{
	return smbsrv_tcon_new(smb_conn, NULL, share_name);
}

struct smbsrv_tcon *smbsrv_smb2_tcon_new(struct smbsrv_session *smb_sess, const char *share_name)
{
	return smbsrv_tcon_new(smb_sess->smb_conn, smb_sess, share_name);
}
package fr.adrienbrault.idea.symfony2plugin.tests.intentions.yaml;

import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyLightCodeInsightFixtureTestCase;
import org.jetbrains.yaml.YAMLFileType;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 *
 * @see fr.adrienbrault.idea.symfony2plugin.intentions.yaml.YamlServiceTagIntention
 */
public class YamlServiceTagIntentionTest extends SymfonyLightCodeInsightFixtureTestCase {

    public void setUp() throws Exception {
        super.setUp();
        myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("classes.php"));
    }

    protected String getTestDataPath() {
        return "src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/intentions/yaml/fixtures";
    }

    public void testTagIntentionIsAvailable() {
        assertIntentionIsAvailable(
            YAMLFileType.YML,
            "services:\n" +
                "    foo:\n" +
                "        class: Foo<caret>\\Bar",
            "Symfony: Add Tags"
        );

        assertIntentionIsAvailable(
            YAMLFileType.YML,
            "services:\n" +
                "    foo:\n" +
                "        arguments: [Foo<caret>\\Bar] ",
            "Symfony: Add Tags"
        );
    }
}

/* istanbul ignore file */
/* istanbul ignore file */
import React from 'react';
import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import { Provider } from 'react-redux';
import { ToastProvider } from 'react-toast-notifications';

import Routes from './routes';
import store from "./store";

import Header from './components/Header';
import Footer from './components/Footer';
import GlobalStyles from './assets/styles/global';

function App () {

  const history = createHistory({
    basename: "",
    forceRefresh: false
  });

  return (
    <Provider store={store}>
      <Router history={history}>
        <GlobalStyles />
        <Header />
        <ToastProvider>
          <Routes />
        </ToastProvider>
        <Footer />
      </Router>
    </Provider>
  );
}

export default App;

package org.ping.apache.sqoop.mapreduce.db.rsync;

import java.sql.Timestamp;

public class TimeUtil {
	public static String getNowStamp() {
		Timestamp now = new Timestamp(System.currentTimeMillis());
		return getStamp(now);
	}

	public static String getStamp(Timestamp timestamp) {
		String stamp = timestamp.toString();
		stamp = stamp.replaceAll("-", "");
		stamp = stamp.replaceAll(":", "");
		stamp = stamp.replaceAll("\\.", "");
		stamp = stamp.replaceAll(" ", "");
		return stamp;
	}
}

import operator

import numpy as np
import numpy.core.umath_tests as ut

from utils.Quaternions import Quaternions


class Animation:
    """
    Animation is a numpy-like wrapper for animation data
    
    Animation data consists of several arrays consisting
    of F frames and J joints.
    
    The animation is specified by
    
        rotations : (F, J) Quaternions | Joint Rotations
        positions : (F, J, 3) ndarray  | Joint Positions
    
    The base pose is specified by
    
        orients   : (J) Quaternions    | Joint Orientations
        offsets   : (J, 3) ndarray     | Joint Offsets
        
    And the skeletal structure is specified by
        
        parents   : (J) ndarray        | Joint Parents
    """
    
    def __init__(self, rotations, positions, orients, offsets, parents):
        
        self.rotations = rotations
        self.positions = positions
        self.orients   = orients
        self.offsets   = offsets
        self.parents   = parents
    
    def __op__(self, op, other):
        return Animation(
            op(self.rotations, other.rotations),
            op(self.positions, other.positions),
            op(self.orients, other.orients),
            op(self.offsets, other.offsets),
            op(self.parents, other.parents))

    def __iop__(self, op, other):
        self.rotations = op(self.roations, other.rotations)
        self.positions = op(self.roations, other.positions)
        self.orients   = op(self.orients, other.orients)
        self.offsets   = op(self.offsets, other.offsets)
        self.parents   = op(self.parents, other.parents)
        return self
    
    def __sop__(self, op):
        return Animation(
            op(self.rotations),
            op(self.positions),
            op(self.orients),
            op(self.offsets),
            op(self.parents))
    
    def __add__(self, other): return self.__op__(operator.add, other)
    def __sub__(self, other): return self.__op__(operator.sub, other)
    def __mul__(self, other): return self.__op__(operator.mul, other)
    def __div__(self, other): return self.__op__(operator.div, other)
    
    def __abs__(self): return self.__sop__(operator.abs)
    def __neg__(self): return self.__sop__(operator.neg)
    
    def __iadd__(self, other): return self.__iop__(operator.iadd, other)
    def __isub__(self, other): return self.__iop__(operator.isub, other)
    def __imul__(self, other): return self.__iop__(operator.imul, other)
    def __idiv__(self, other): return self.__iop__(operator.idiv, other)
    
    def __len__(self): return len(self.rotations)
    
    def __getitem__(self, k):
        if isinstance(k, tuple):
            return Animation(
                self.rotations[k],
                self.positions[k],
                self.orients[k[1:]],
                self.offsets[k[1:]],
                self.parents[k[1:]]) 
        else:
            return Animation(
                self.rotations[k],
                self.positions[k],
                self.orients,
                self.offsets,
                self.parents) 
        
    def __setitem__(self, k, v): 
        if isinstance(k, tuple):
            self.rotations.__setitem__(k, v.rotations)
            self.positions.__setitem__(k, v.positions)
            self.orients.__setitem__(k[1:], v.orients)
            self.offsets.__setitem__(k[1:], v.offsets)
            self.parents.__setitem__(k[1:], v.parents)
        else:
            self.rotations.__setitem__(k, v.rotations)
            self.positions.__setitem__(k, v.positions)
            self.orients.__setitem__(k, v.orients)
            self.offsets.__setitem__(k, v.offsets)
            self.parents.__setitem__(k, v.parents)
        
    @property
    def shape(self): return (self.rotations.shape[0], self.rotations.shape[1])
            
    def copy(self): return Animation(
        self.rotations.copy(), self.positions.copy(), 
        self.orients.copy(), self.offsets.copy(), 
        self.parents.copy())
    
    def repeat(self, *args, **kw):
        return Animation(
            self.rotations.repeat(*args, **kw),
            self.positions.repeat(*args, **kw),
            self.orients, self.offsets, self.parents)
        
    def ravel(self):
        return np.hstack([
            self.rotations.log().ravel(),
            self.positions.ravel(),
            self.orients.log().ravel(),
            self.offsets.ravel()])
        
    @classmethod
    def unravel(clas, anim, shape, parents):
        nf, nj = shape
        rotations = anim[nf*nj*0:nf*nj*3]
        positions = anim[nf*nj*3:nf*nj*6]
        orients   = anim[nf*nj*6+nj*0:nf*nj*6+nj*3]
        offsets   = anim[nf*nj*6+nj*3:nf*nj*6+nj*6]
        return cls(
            Quaternions.exp(rotations), positions,
            Quaternions.exp(orients), offsets,
            parents.copy())
    
    
""" Maya Interaction """

def load_to_maya(anim, names=None, radius=0.5):
    """
    Load Animation Object into Maya as Joint Skeleton
    loads each frame as a new keyfame in maya.
    
    If the animation is too slow or too fast perhaps
    the framerate needs adjusting before being loaded
    such that it matches the maya scene framerate.
    
    
    Parameters
    ----------
    
    anim : Animation
        Animation to load into Scene
        
    names : [str]
        Optional list of Joint names for Skeleton
    
    Returns
    -------
    
    List of Maya Joint Nodes loaded into scene
    """
    
    import pymel.core as pm
    
    joints = []
    frames = range(1, len(anim)+1)
    
    if names is None: names = ["joint_" + str(i) for i in range(len(anim.parents))]
    
    for i, offset, orient, parent, name in zip(range(len(anim.offsets)), anim.offsets, anim.orients, anim.parents, names):
    
        if parent < 0:
            pm.select(d=True)
        else:
            pm.select(joints[parent])
        
        joint = pm.joint(n=name, p=offset, relative=True, radius=radius)
        joint.setOrientation([orient[1], orient[2], orient[3], orient[0]])
        
        curvex = pm.nodetypes.AnimCurveTA(n=name + "_rotateX")
        curvey = pm.nodetypes.AnimCurveTA(n=name + "_rotateY")
        curvez = pm.nodetypes.AnimCurveTA(n=name + "_rotateZ")  
        
        jrotations = (-Quaternions(orient[np.newaxis]) * anim.rotations[:,i]).euler()
        curvex.addKeys(frames, jrotations[:,0])
        curvey.addKeys(frames, jrotations[:,1])
        curvez.addKeys(frames, jrotations[:,2])
        
        pm.connectAttr(curvex.output, joint.rotateX)
        pm.connectAttr(curvey.output, joint.rotateY)
        pm.connectAttr(curvez.output, joint.rotateZ)
        
        offsetx = pm.nodetypes.AnimCurveTU(n=name + "_translateX")
        offsety = pm.nodetypes.AnimCurveTU(n=name + "_translateY")
        offsetz = pm.nodetypes.AnimCurveTU(n=name + "_translateZ")
        
        offsetx.addKeys(frames, anim.positions[:,i,0])
        offsety.addKeys(frames, anim.positions[:,i,1])
        offsetz.addKeys(frames, anim.positions[:,i,2])
        
        pm.connectAttr(offsetx.output, joint.translateX)
        pm.connectAttr(offsety.output, joint.translateY)
        pm.connectAttr(offsetz.output, joint.translateZ)
        
        joints.append(joint)
    
    return joints
    
def transforms_local(anim):
    """
    Computes Animation Local Transforms
    
    As well as a number of other uses this can
    be used to compute global joint transforms,
    which in turn can be used to compete global
    joint positions
    
    Parameters
    ----------
    
    anim : Animation
        Input animation
        
    Returns
    -------
    
    transforms : (F, J, 4, 4) ndarray
    
        For each frame F, joint local
        transforms for each joint J
    """
    
    transforms = anim.rotations.transforms()
    transforms = np.concatenate([transforms, np.zeros(transforms.shape[:2] + (3, 1))], axis=-1)
    transforms = np.concatenate([transforms, np.zeros(transforms.shape[:2] + (1, 4))], axis=-2)
    transforms[:,:,0:3,3] = anim.positions
    transforms[:,:,3:4,3] = 1.0
    return transforms

    
def transforms_multiply(t0s, t1s):
    """
    Transforms Multiply
    
    Multiplies two arrays of animation transforms
    
    Parameters
    ----------
    
    t0s, t1s : (F, J, 4, 4) ndarray
        Two arrays of transforms
        for each frame F and each
        joint J
        
    Returns
    -------
    
    transforms : (F, J, 4, 4) ndarray
        Array of transforms for each
        frame F and joint J multiplied
        together
    """
    
    return ut.matrix_multiply(t0s, t1s)
    
def transforms_inv(ts):
    fts = ts.reshape(-1, 4, 4)
    fts = np.array(list(map(lambda x: np.linalg.inv(x), fts)))
    return fts.reshape(ts.shape)
    
def transforms_blank(anim):
    """
    Blank Transforms
    
    Parameters
    ----------
    
    anim : Animation
        Input animation
    
    Returns
    -------
    
    transforms : (F, J, 4, 4) ndarray
        Array of identity transforms for 
        each frame F and joint J
    """

    ts = np.zeros(anim.shape + (4, 4)) 
    ts[:,:,0,0] = 1.0; ts[:,:,1,1] = 1.0;
    ts[:,:,2,2] = 1.0; ts[:,:,3,3] = 1.0;
    return ts
    
def transforms_global(anim):
    """
    Global Animation Transforms
    
    This relies on joint ordering
    being incremental. That means a joint
    J1 must not be a ancestor of J0 if
    J0 appears before J1 in the joint
    ordering.
    
    Parameters
    ----------
    
    anim : Animation
        Input animation
    
    Returns
    ------
    
    transforms : (F, J, 4, 4) ndarray
        Array of global transforms for 
        each frame F and joint J
    """
    
    joints  = np.arange(anim.shape[1])
    parents = np.arange(anim.shape[1])
    locals  = transforms_local(anim)
    globals = transforms_blank(anim)

    globals[:,0] = locals[:,0]

    for i in range(1, anim.shape[1]):
        globals[:,i] = transforms_multiply(globals[:,anim.parents[i]], locals[:,i])

    return globals
    
    
def positions_global(anim):
    """
    Global Joint Positions
    
    Given an animation compute the global joint
    positions at at every frame
    
    Parameters
    ----------
    
    anim : Animation
        Input animation
        
    Returns
    -------
    
    positions : (F, J, 3) ndarray
        Positions for every frame F 
        and joint position J
    """
    
    positions = transforms_global(anim)[:,:,:,3]
    return positions[:,:,:3] / positions[:,:,3,np.newaxis]
    
""" Rotations """
    
def rotations_global(anim):
    """
    Global Animation Rotations
    
    This relies on joint ordering
    being incremental. That means a joint
    J1 must not be a ancestor of J0 if
    J0 appears before J1 in the joint
    ordering.
    
    Parameters
    ----------
    
    anim : Animation
        Input animation
        
    Returns
    -------
    
    points : (F, J) Quaternions
        global rotations for every frame F 
        and joint J
    """

    joints  = np.arange(anim.shape[1])
    parents = np.arange(anim.shape[1])
    locals  = anim.rotations
    globals = Quaternions.id(anim.shape)
    
    globals[:,0] = locals[:,0]
    
    for i in range(1, anim.shape[1]):
        globals[:,i] = globals[:,anim.parents[i]] * locals[:,i]
        
    return globals
    
def rotations_parents_global(anim):
    rotations = rotations_global(anim)
    rotations = rotations[:,anim.parents]
    rotations[:,0] = Quaternions.id(len(anim))
    return rotations
    
def rotations_load_to_maya(rotations, positions, names=None):
    """
    Load Rotations into Maya
    
    Loads a Quaternions array into the scene
    via the representation of axis
    
    Parameters
    ----------
    
    rotations : (F, J) Quaternions 
        array of rotations to load
        into the scene where
            F = number of frames
            J = number of joints
    
    positions : (F, J, 3) ndarray 
        array of positions to load
        rotation axis at where:
            F = number of frames
            J = number of joints
            
    names : [str]
        List of joint names
    
    Returns
    -------
    
    maxies : Group
        Grouped Maya Node of all Axis nodes
    """
    
    import pymel.core as pm

    if names is None: names = ["joint_" + str(i) for i in range(rotations.shape[1])]
    
    maxis = []
    frames = range(1, len(positions)+1)
    for i, name in enumerate(names):
    
        name = name + "_axis"
        axis = pm.group(
             pm.curve(p=[(0,0,0), (1,0,0)], d=1, n=name+'_axis_x'),
             pm.curve(p=[(0,0,0), (0,1,0)], d=1, n=name+'_axis_y'),
             pm.curve(p=[(0,0,0), (0,0,1)], d=1, n=name+'_axis_z'),
             n=name)
        
        axis.rotatePivot.set((0,0,0))
        axis.scalePivot.set((0,0,0))
        axis.childAtIndex(0).overrideEnabled.set(1); axis.childAtIndex(0).overrideColor.set(13)
        axis.childAtIndex(1).overrideEnabled.set(1); axis.childAtIndex(1).overrideColor.set(14)
        axis.childAtIndex(2).overrideEnabled.set(1); axis.childAtIndex(2).overrideColor.set(15)
    
        curvex = pm.nodetypes.AnimCurveTA(n=name + "_rotateX")
        curvey = pm.nodetypes.AnimCurveTA(n=name + "_rotateY")
        curvez = pm.nodetypes.AnimCurveTA(n=name + "_rotateZ")  
        
        arotations = rotations[:,i].euler()
        curvex.addKeys(frames, arotations[:,0])
        curvey.addKeys(frames, arotations[:,1])
        curvez.addKeys(frames, arotations[:,2])
        
        pm.connectAttr(curvex.output, axis.rotateX)
        pm.connectAttr(curvey.output, axis.rotateY)
        pm.connectAttr(curvez.output, axis.rotateZ)
        
        offsetx = pm.nodetypes.AnimCurveTU(n=name + "_translateX")
        offsety = pm.nodetypes.AnimCurveTU(n=name + "_translateY")
        offsetz = pm.nodetypes.AnimCurveTU(n=name + "_translateZ")
        
        offsetx.addKeys(frames, positions[:,i,0])
        offsety.addKeys(frames, positions[:,i,1])
        offsetz.addKeys(frames, positions[:,i,2])
        
        pm.connectAttr(offsetx.output, axis.translateX)
        pm.connectAttr(offsety.output, axis.translateY)
        pm.connectAttr(offsetz.output, axis.translateZ)
    
        maxis.append(axis)
        
    return pm.group(*maxis, n='RotationAnimation')   
    
""" Offsets & Orients """

def orients_global(anim):

    joints  = np.arange(anim.shape[1])
    parents = np.arange(anim.shape[1])
    locals  = anim.orients
    globals = Quaternions.id(anim.shape[1])
    
    globals[:,0] = locals[:,0]
    
    for i in range(1, anim.shape[1]):
        globals[:,i] = globals[:,anim.parents[i]] * locals[:,i]
        
    return globals

    
def offsets_transforms_local(anim):
    
    transforms = anim.orients[np.newaxis].transforms()
    transforms = np.concatenate([transforms, np.zeros(transforms.shape[:2] + (3, 1))], axis=-1)
    transforms = np.concatenate([transforms, np.zeros(transforms.shape[:2] + (1, 4))], axis=-2)
    transforms[:,:,0:3,3] = anim.offsets[np.newaxis]
    transforms[:,:,3:4,3] = 1.0
    return transforms
    
    
def offsets_transforms_global(anim):
    
    joints  = np.arange(anim.shape[1])
    parents = np.arange(anim.shape[1])
    locals  = offsets_transforms_local(anim)
    globals = transforms_blank(anim)

    globals[:,0] = locals[:,0]
    
    for i in range(1, anim.shape[1]):
        globals[:,i] = transforms_multiply(globals[:,anim.parents[i]], locals[:,i])
        
    return globals
    
def offsets_global(anim):
    offsets = offsets_transforms_global(anim)[:,:,:,3]
    return offsets[0,:,:3] / offsets[0,:,3,np.newaxis]
    
""" Lengths """

def offset_lengths(anim):
    return np.sum(anim.offsets[1:]**2.0, axis=1)**0.5
    
    
def position_lengths(anim):
    return np.sum(anim.positions[:,1:]**2.0, axis=2)**0.5
    
    
""" Skinning """
def skin(anim, rest, weights, mesh, maxjoints=4):
    full_transforms = transforms_multiply(
        transforms_global(anim), 
        transforms_inv(transforms_global(rest[0:1])))
    
    weightids = np.argsort(-weights, axis=1)[:,:maxjoints]
    weightvls = np.array(list(map(lambda w, i: w[i], weights, weightids)))
    weightvls = weightvls / weightvls.sum(axis=1)[...,np.newaxis]
    
    verts = np.hstack([mesh, np.ones((len(mesh), 1))])
    verts = verts[np.newaxis,:,np.newaxis,:,np.newaxis]
    verts = transforms_multiply(full_transforms[:,weightids], verts)    
    verts = (verts[:,:,:,:3] / verts[:,:,:,3:4])[:,:,:,:,0]

    return np.sum(weightvls[np.newaxis,:,:,np.newaxis] * verts, axis=2)


def load_from_network(translation, rotations, length, third_dimension=1, average_length=5, tanslation_scale=3):
    rotations = rotations.reshape((-1, 17, 4))
    length = length[0]
    rotations = rotations / np.repeat(np.expand_dims(np.sqrt(np.sum(np.square(rotations), axis=-1)), axis=-1), 4, axis=-1)
    rotations = Quaternions(rotations)
    scaling_factor = np.mean(length) / average_length
    length = length / scaling_factor
    translation = translation / scaling_factor / tanslation_scale
    positions = np.expand_dims(translation, axis=1)
    parents = [-1, 0, 1, 2, 0, 4, 5, 0, 7, 8, 9, 8, 11, 12, 8, 14, 15]
    offsets = np.zeros((17, 3))
    offsets[1, 0] = -length[0]
    offsets[4, 0] = length[0]
    offsets[2, third_dimension] = -length[1]
    offsets[5, third_dimension] = -length[1]
    offsets[3, third_dimension] = -length[2]
    offsets[6, third_dimension] = -length[2]
    offsets[7, third_dimension] = length[3]
    offsets[8, third_dimension] = length[4]
    offsets[9, third_dimension] = length[5]
    offsets[10, third_dimension] = length[6]    
    offsets[11, 0] = length[7]
    offsets[12, 0] = length[8]
    offsets[13, 0] = length[9]
    offsets[14, 0] = -length[7]
    offsets[15, 0] = -length[8]
    offsets[16, 0] = -length[9]
    return Animation(rotations, positions, Quaternions.id(0), offsets, np.array(parents))

---
date: '2018-01-26T19:28:52.259Z'
user_id: 865
user_name: OverthrowCPC
user_intro: |-
    打倒加拿大保守党
    ————
    名字含义：Overthrow 为“打倒”，CPC 为“加拿大保守党”（Conservative Party of Canada）。
    本人是个文盲，所有帖子均为软件随机生成，可随便转载不必署名，谢绝各种跨省、跨国、跨球行动。
user_avatar: >-
    /static/upload/thumb/small50-u-thumb-8652ad06054ab4de2b630c1433bcf39da043b3e0921.png
upvote: 36
downvote: 0
comments:
    - ''
    - ''
    - ''
    - ''
    - ''
    - ''
    - ''
    - ''
    - ''
    - ''
---

很多人意想不到的是：**中共自己安插在国府中的鼹鼠，大都是低级别的，真正高级别的鼹鼠，都是苏共安插进去的。当时国府的老大哥美国自己就浑身挂满苏联木马，国府中的苏共间谍，很多是美国推荐给国府的。**

（本文无意于给历史翻案，或者给国府的溃败寻找外在理由，目的在于提醒诸位历史爱好者，在美苏谍对于内战局势的影响是不可忽略的）

  

  

先偷懒搬运下我的另一个回答[《如何评价“麦卡锡主义”？》](https://pin-cong.com/p/25952/?s=26471)：  

上世纪 30 年代到 50 年初，美国政府被苏联红色间谍渗透得千疮百孔，就是 CIA ， FBI 这些组织都不能幸免。美国政府财政部、军工部门的高管，充斥着苏联间谍。甚至曼哈顿绝密工程，斯大林比杜鲁门了解的更清楚。这些在美苏谍极大影响了 40 年代美国的对华政策

一方面，早在二战期间，在美苏谍就在暗中破坏美国的对华（中华民国）援助。当时，美国国会通过的对华援助方案，被财政部的苏联间谍怀特（Harry Dexter White）暗中脱后腿。甚至后来内战期间滥发法币的始作俑者冀朝鼎，也是怀特推荐给国府的。

另一方面，内战期间的中共与苏联联手作戏表演给美国左派，营造一种苏联没有支援中共的假象。当时美国主政的是左派的民主党，只是简单的认为中国的内战不过是一次普通的改朝换代，并没有意识到苏联在背后的作用。来华调停的马歇尔甚至天真的认为美国对华（中华民国）援助导致了对中共的不公平，引起了中国人的反美情绪。如此种种，导致杜鲁门当局在 1946 年 8 月出台了对华武器禁运政策，虽然禁用政策在一年后被解除，但由于在美苏谍暗中作梗，直到国府迁台前美援并未起到太大作用。

直到中国大陆易手之后，当时左派掌握话语权的美国仍然没有对此事予以充分重视，杜鲁门当局屡屡以国府贪腐为借口来掩盖自己援华不力外加防共无能的事实，甚至已经准备放弃迁台后的国府。

韩战爆发之后，参议员麦卡锡重提苏谍渗透问题，美国左派才意识到之前的对华政策可能被苏联间谍误导了，FBI 局长胡佛之前曾警告的问题也得以被摆到国会议程上，但为时已晚。此时，FBI 凭借“维诺那计划”（Venona Project）之前已经查到的线索确定当初在政界破坏美国援华的那些高级官员是奉命行事的苏联间谍，白宫才终于把中国大陆内战爆发以来的事情和韩战整合在一起。

  

关于在美苏谍误导美国对华政策的话题，详见[《美国为何没在国共内战的时候全力支持国民政府？ - 知乎》](https://www.zhihu.com/question/20255728/answer/178205685)（[防删备份](https://archive.is/tSFXe)）。

关于苏联在中国内战期间起的作用，推荐阅读：

《大棋局中的国共关系》社科院的吕迅著，此书为近年来研究国共内战的新作（2015出版），基于最新解密档案写成的（顺便跪求该书的电子版）。

《朝鲜支援东北解放战争纪实》中国学者吕明辉著。

  

**（未完待续，关于国府中苏联间谍的情况，需要查很多资料，有时间我会慢慢补充）**

/// <reference types="react" />
declare const MessageBoxUI_base: (new (..._: any[]) => import("react-vextensions").BaseComponent<{
    id: number;
}, {
    offset: {
        x: number;
        y: number;
    };
}, unknown>) & {
    renderCount: number;
    lastRenderTime: number;
};
export declare class MessageBoxUI extends MessageBoxUI_base {
    moveBar_drag_origOffset: {
        x: number;
        y: number;
    } | n;
    moveBar_drag_mouseDownPos: {
        x: number;
        y: number;
    } | n;
    moveBar_drag_mouseMoveListener: EventListener | n;
    moveBar_drag_mouseUpListener: EventListener | n;
    render(): JSX.Element;
}
export {};

import { K8SContext, ResourceWithActions, ResourceWithActionsAndDocs } from "../core/models";
import { NetworkLayout, ResourceVisibility } from "./ui-enums";

export type Node = { id: string; label: string; group: string; shape?: string; image?: string };
export type Edge = { from: string; to: string; dashes?: number[] };

export type DisplaySettings = {
  SettingsVersion: number;
  Layout: NetworkLayout;
  Resources: { [kind: string]: ResourceVisibility };
  // this is just a map of the Resource field (maps are not correctly serialized when saved to local storage)
  ResourcesMap: Map<string, ResourceVisibility>;
  Context: {
    currentContext: string;
    contexts: K8SContext[];
  };
};

export type ResourceUIModel = ResourceWithActionsAndDocs & {
  ui: {
    location: {
      x: number;
      y: number;
    };
    font?: {
      size: number;
      bold: boolean;
    };
    size?: {
      height: number;
      width: number;
    };
  };
  isGroup: boolean;
};

export type MongodbDeploymentUIModel = {
  resources: ResourceUIModel[];
  resourceGroups: Map<string, ResourceUIModel[]>;
};

---
title: Feature Set and Roadmap
author: ashish161
date: 2021-03-24
category: features
layout: post
---

#PikReview
    
    Quick, hassle free and privcay centric  store front for your business and your data 


## Store Settings
 - Setup your store link, currency, payment instructions.
 - Order and shipping settings 
 - Store communication details 
 - Payment options 
 
## Inventory  management
 Easy inventory setup and ability to customize your products    
 - Description
 - Pricing
 - Variants : Size and Colors
 - Taxes 
 - Shipping 
 - Category 
 - Bulk products using excel for quick on-boarding 

## Order Management 
Fulfill orders from your mobile / desktop and never miss updating your customers 
 - Accept orders and send quick updates to your customers using whatsapp 
 - Get insights of high value and repeat customers
 - Dashboard of pending / shipping and shipped order and revenue  
 - Bulk products using excel for quick on-boarding 

## Roadmap 
- Support for local languages 
- Support for international currencies 
- Payment gateway integration 
- Setup on custom domain 
- Reseller management
- Tie up with shipping and logistic partners   
import os
import platform
import shelve
from logic.utils import clear_folder
from collections import OrderedDict


class Round:

    def __init__(self, name, teams=[], max_points=100):
        self.round_name = name
        self.max_points = max_points
        self.teams = OrderedDict()
        for team in teams:
            self.teams[team["name"]] = team
            self.teams[team["name"]]["score"] = 0

    def __str__(self):
        return str(self.teams)

    def create_self(self):
        # first delete all other files
        clear_folder(os.path.join(os.getcwd(), "data", "*"))
        self.write_to_db()

    def write_to_db(self):
        db_path = os.path.join(os.getcwd(), "data", self.round_name)
        db = shelve.open(db_path)
        for k in self.teams.keys():
            db[k] = self.teams[k]
        db.close()

    def exists(self):
        if platform.system() != "Linux":
            db_path = os.path.join(os.getcwd(), "data", self.round_name + '.dat')
        else:
            db_path = os.path.join(os.getcwd(), "data", self.round_name)
        return os.path.exists(db_path)

    def open_existing(self):
        # expects that round_name already exists
        db_path = os.path.join(os.getcwd(), "data", self.round_name)
        db = shelve.open(db_path)
        db_keys = list(db.keys())
        db_keys.sort()
        for k in db_keys:
            self.teams[k] = db[k]
        db.close()

    def update_from_dict(self, d):
        for k in d.keys():
            if k in self.teams:
                val = int(d[k])
                if val < 0:
                    self.teams[k]["score"] = 0
                else:
                    self.teams[k]["score"] = val if val <= self.max_points else self.max_points
        self.write_to_db()



var config = {}

config.redis = {};
config.http = {};
config.cookie = {};
config.log = {};
config.ubersmith = {};
config.ubersmith.warm_cache = false;
config.log.access_log = './access.log';
config.log.directory = process.env.LOG_DIR || './';

config.redis.uri = process.env.REDIS_URI;
config.redis.host = process.env.REDIS_HOST || 'localhost';
config.redis.port = process.env.REDIS_PORT || 6379;
config.redis.db = process.env.REDIS_DB || 1;

config.http.port = process.env.PORT || 3005;
config.cookie.secret = 'securit3333!!';

module.exports = config;

<?php

namespace App\Http\Controllers\Auth;

use App\Custodian;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use JWTAuth;
use App\UserType;
use App\Department;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    public function userAuth(Request $request){
        $credentials = $request->only('email','password');
        $token = null;

        try{
            if(!$token = JWTAuth::attempt($credentials)){ 
                return response()->json(['error' => 'invalid_credentials'], 404);
            }
        }catch(JWTException $ex){
            return response()->json(['error' => 'something_went_wrong'], 500);
        }

        return response()->json(compact('token'));

        
    }

    public function getAuthenticatedUser(){
        
        try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {
                return response()->json(['user_not_found'], 404);
            }

        } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

            return response()->json(['token_expired'], $e->getStatusCode());

        } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

            return response()->json(['token_invalid'], $e->getStatusCode());

        } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

            return response()->json(['token_absent'], $e->getStatusCode());
        }

        $user_type_name = Usertype::find($user->user_type_id)->role;
        $user->user_type_name =  $user_type_name;

        $user_department_name = Department::find($user->department_id)->name;
        $user->user_department_name =  $user_department_name;

        $data = [];
            $data = [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'position' => $user->position,
                'contact_number' => $user->contact_number,
                'employee_id' => $user->employee_id,
                'user_type_id' => $user->user_type_id,
                'department_id' => $user->department_id,
                'user_type_name' => $user->user_type_name,
                'user_department_name' => $user->user_department_name
            ];
        
        // the token is valid and we have found the user via the sub claim
        return response()->json(compact('data'));
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return Custodian::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

#include "mini_uart.h"
#include "uint.h"
#include "priority_queue.h"
#include "queue.h"
#include "scheduler.h"
#include "task.h"

uint64 freq_thread = 31;

void core_timer_init(){
    uint64 tmp;
    asm volatile("mrs %0, cntkctl_el1" : "=r"(tmp));
    tmp |= 1;
    asm volatile("msr cntkctl_el1, %0" : : "r"(tmp));
    core_timer_disable();
}

void arm_core_timer_intr_handler() {
    core_timer_handler();
}

void core_timer_handler(){
    struct node* node = delete_first_node();
    if(node->next == NULL){
        asm volatile("mrs x0, cntfrq_el0\n"
                     "ldr x1, =10\n"
                     "mul x0, x0, x1\n"
                     "msr cntp_tval_el0, x0\n");
        core_timer_disable();
    }else{
        core_timer_enable();
        uint64 interval = node->next->time_to_ring;
        asm volatile("msr cntp_tval_el0, %[output0]\n"
                     ::[output0] "r" (interval));
    }
    free(node);
    node->todo(node->arguments);
}

void add_timer(void (*callback_f)(void*),void *argu_for_call,int times){
    uint64 clock_hz,now_time,interval;
    asm volatile("mrs %[input0], cntfrq_el0\n"
                 "mrs %[input2], cntp_tval_el0\n"
                 :[input0] "=r" (clock_hz),
                  [input2] "=r" (interval));
    uint64 time_to_ring = add_node(callback_f, argu_for_call, clock_hz / 1000 * times, interval);
    core_timer_enable();
    asm volatile("msr cntp_tval_el0, %[output0]\n"
                 ::[output0] "r" (time_to_ring));
}

void *wakeup(void *p){
    uart_printf("Timeout!!\n");
}

void sleep(int duration){
    add_timer(wakeup,NULL,duration);
    uart_printf("Timer is set...\n");
}

void delay(int duration){
    irq_disable();
    void *argu = get_current();
    add_timer(wakeup_queue,argu,duration);
    irq_enable();
    schedule();
}

void thread_timer_handler(){
    void *t = get_current();
    struct thread *s = t;
    PushToReadyList(s->tid);
    thread_timer();
    task_schedule(t);
}

void thread_timer(){
    while(delete_first_node() != NULL);
    add_timer(thread_timer_handler,NULL,freq_thread);
}

/* eslint-disable @typescript-eslint/no-unused-vars,@typescript-eslint/no-empty-interface,@typescript-eslint/no-explicit-any */
import Vue, { VNode, RenderContext } from 'vue';
import { DefaultProps } from 'vue/types/options';

declare global {
  namespace JSX {
    interface Element extends VNode {}
    interface ElementClass extends Vue {}
    interface IntrinsicElements {
      [elem: string]: any;
    }
  }
}

declare module 'vue/types/index' {
  type FunctionalComponent<Props = DefaultProps> = (
    context: RenderContext<Props>,
  ) => VNode;
}

---
layout: "fluid/docs_base"
version: "3.6.1"
versionHref: "/docs/v3/3.6.1"
path: ""
category: api
id: "app"
title: "App"
header_sub_title: "Ionic API Documentation"
doc: "App"
docType: "class"

---









<h1 class="api-title">
<a class="anchor" name="app" href="#app"></a>

App





</h1>

<a class="improve-v2-docs" href="http://github.com/ionic-team/ionic/edit/v3/src/components/app/app.ts#L16">
Improve this doc
</a>






<p>App is a utility class used in Ionic to get information about various aspects of an app</p>




<!-- @usage tag -->


<!-- @property tags -->



<!-- instance methods on the class -->

<h2><a class="anchor" name="instance-members" href="#instance-members">Instance Members</a></h2>

<div id="getActiveNav"></div>

<h3>
<a class="anchor" name="getActiveNav" href="#getActiveNav">
<code>getActiveNav()</code>


</a>
</h3>








<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>NavController</code> <p>Returns the first Active Nav Controller from the list. This method is deprecated</p>


</div>




<div id="getActiveNavContainers"></div>

<h3>
<a class="anchor" name="getActiveNavContainers" href="#getActiveNavContainers">
<code>getActiveNavContainers()</code>


</a>
</h3>











<div id="getActiveNavs"></div>

<h3>
<a class="anchor" name="getActiveNavs" href="#getActiveNavs">
<code>getActiveNavs()</code>


</a>
</h3>








<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>NavController[]</code> <p>Returns the active NavControllers. Using this method is preferred when we need access to the top-level navigation controller while on the outside views and handlers like <code>registerBackButtonAction()</code></p>


</div>




<div id="getNavByIdOrName"></div>

<h3>
<a class="anchor" name="getNavByIdOrName" href="#getNavByIdOrName">
<code>getNavByIdOrName()</code>


</a>
</h3>











<div id="getRootNav"></div>

<h3>
<a class="anchor" name="getRootNav" href="#getRootNav">
<code>getRootNav()</code>


</a>
</h3>











<div id="getRootNavById"></div>

<h3>
<a class="anchor" name="getRootNavById" href="#getRootNavById">
<code>getRootNavById()</code>


</a>
</h3>








<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>NavController</code> <p>Returns the root NavController</p>


</div>




<div id="getRootNavs"></div>

<h3>
<a class="anchor" name="getRootNavs" href="#getRootNavs">
<code>getRootNavs()</code>


</a>
</h3>











<div id="isScrolling"></div>

<h3>
<a class="anchor" name="isScrolling" href="#isScrolling">
<code>isScrolling()</code>


</a>
</h3>

Boolean if the app is actively scrolling or not.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>boolean</code> <p>returns true or false</p>


</div>




<div id="setTitle"></div>

<h3>
<a class="anchor" name="setTitle" href="#setTitle">
<code>setTitle(val)</code>


</a>
</h3>

Sets the document title.


<table class="table param-table" style="margin:0;">
  <thead>
    <tr>
      <th>Param</th>
      <th>Type</th>
      <th>Details</th>
    </tr>
  </thead>
  <tbody>

    <tr>
      <td>
        val


      </td>
      <td>

  <code>string</code>
      </td>
      <td>
        <p>Value to set the document title to.</p>


      </td>
    </tr>

  </tbody>
</table>








<div id="viewDidEnter"></div>

<h3>
<a class="anchor" name="viewDidEnter" href="#viewDidEnter">
<code>viewDidEnter</code>


</a>
</h3>

Observable that emits after any view is entered in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>




<div id="viewDidLeave"></div>

<h3>
<a class="anchor" name="viewDidLeave" href="#viewDidLeave">
<code>viewDidLeave</code>


</a>
</h3>

Observable that emits after any view is exited in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>




<div id="viewDidLoad"></div>

<h3>
<a class="anchor" name="viewDidLoad" href="#viewDidLoad">
<code>viewDidLoad</code>


</a>
</h3>

Observable that emits whenever a view loads in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>




<div id="viewWillEnter"></div>

<h3>
<a class="anchor" name="viewWillEnter" href="#viewWillEnter">
<code>viewWillEnter</code>


</a>
</h3>

Observable that emits before any view is entered in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>




<div id="viewWillLeave"></div>

<h3>
<a class="anchor" name="viewWillLeave" href="#viewWillLeave">
<code>viewWillLeave</code>


</a>
</h3>

Observable that emits before any view is exited in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>




<div id="viewWillUnload"></div>

<h3>
<a class="anchor" name="viewWillUnload" href="#viewWillUnload">
<code>viewWillUnload</code>


</a>
</h3>

Observable that emits before any view unloads in the app.






<div class="return-value">
<i class="icon ion-arrow-return-left"></i>
<b>Returns:</b>
  <code>Observable</code> <p>Returns an observable</p>


</div>





  <h2 id="sass-variable-header"><a class="anchor" name="sass-variables" href="#sass-variables">Sass Variables</a></h2>
  <div id="sass-variables" ng-controller="SassToggleCtrl">
  <div class="sass-platform-toggle">

    <h3 ng-init="setSassPlatform('base')">All</h3>

  </div>



  <table ng-show="active === 'base'" id="sass-base" class="table param-table" style="margin:0;">
    <thead>
      <tr>
        <th>Property</th>
        <th>Default</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>

      <tr>
        <td><code>$font-size-root</code></td>

          <td><code>62.5%</code></td>

        <td><p>Font size of the root html</p>
</td>
      </tr>

      <tr>
        <td><code>$headings-font-weight</code></td>

          <td><code>500</code></td>

        <td><p>Font weight of all headings</p>
</td>
      </tr>

      <tr>
        <td><code>$headings-line-height</code></td>

          <td><code>1.2</code></td>

        <td><p>Line height of all headings</p>
</td>
      </tr>

      <tr>
        <td><code>$h1-font-size</code></td>

          <td><code>2.6rem</code></td>

        <td><p>Font size of heading level 1</p>
</td>
      </tr>

      <tr>
        <td><code>$h2-font-size</code></td>

          <td><code>2.4rem</code></td>

        <td><p>Font size of heading level 2</p>
</td>
      </tr>

      <tr>
        <td><code>$h3-font-size</code></td>

          <td><code>2.2rem</code></td>

        <td><p>Font size of heading level 3</p>
</td>
      </tr>

      <tr>
        <td><code>$h4-font-size</code></td>

          <td><code>2rem</code></td>

        <td><p>Font size of heading level 4</p>
</td>
      </tr>

      <tr>
        <td><code>$h5-font-size</code></td>

          <td><code>1.8rem</code></td>

        <td><p>Font size of heading level 5</p>
</td>
      </tr>

      <tr>
        <td><code>$h6-font-size</code></td>

          <td><code>1.6rem</code></td>

        <td><p>Font size of heading level 6</p>
</td>
      </tr>

      <tr>
        <td><code>$include-responsive-utilities</code></td>

          <td><code>true</code></td>

        <td><p>Whether to include all of the responsive utility attributes</p>
</td>
      </tr>

      <tr>
        <td><code>$include-text-alignment-utilities</code></td>

          <td><code>$include-responsive-utilities</code></td>

        <td><p>Whether to include all of the responsive text alignment attributes</p>
</td>
      </tr>

      <tr>
        <td><code>$include-text-transform-utilities</code></td>

          <td><code>$include-responsive-utilities</code></td>

        <td><p>Whether to include all of the responsive text transform attributes</p>
</td>
      </tr>

      <tr>
        <td><code>$include-float-element-utilities</code></td>

          <td><code>$include-responsive-utilities</code></td>

        <td><p>Whether to include all of the responsive float attributes</p>
</td>
      </tr>

      <tr>
        <td><code>$screen-breakpoints</code></td>

          <td><code>(&#10;  xs: 0,&#10;  sm: 576px,&#10;  md: 768px,&#10;  lg: 992px,&#10;  xl: 1200px&#10;)</code></td>

        <td><p>The minimum dimensions at which your layout will change,
adapting to different screen sizes, for use in media queries</p>
</td>
      </tr>

    </tbody>
  </table>

</div>



<!-- related link --><!-- end content block -->


<!-- end body block -->


import __SInterface from '@coffeekraken/s-interface';
import __SugarConfig from '@coffeekraken/s-sugar-config';
import __flatten from '@coffeekraken/sugar/shared/object/flatten';
import __postCss from 'postcss';
import __deepMerge from '@coffeekraken/sugar/shared/object/deepMerge';
import __postcss from 'postcss';
import __theme from '../../utils/theme';

class postcssSugarPluginMediaMixinInterface extends __SInterface {
  static definition = {
    query1: {
      type: 'String',
      required: true
    },
    query2: {
      type: 'String'
    },
    query3: {
      type: 'String'
    },
    query4: {
      type: 'String'
    },
    query5: {
      type: 'String'
    },
    query6: {
      type: 'String'
    },
    query7: {
      type: 'String'
    }
  };
}
export { postcssSugarPluginMediaMixinInterface as interface };

/**
 * @name           media
 * @namespace      mixins
 * @type           Mixin
 * @platform      css
 * @status        beta
 *
 * This mixin allows you to apply any media queries that are defined
 * in the config.theme.media.queries configuration stack like "tablet", "mobile", etc...
 *
 * @param       {String}        query       The query string like ">tablet", "<=desktop", etc...
 * @return      {Css}         The generated css
 * 
 * @example         postcss
 * \@sugar.media >=desktop {
 *      // ...
 * }
 * \@sugar.media tablet {
 *      // ...
 * }
 *
 * @since       2.0.0
 * @author         Olivier Bossel <olivier.bossel@gmail.com> (https://olivierbossel.com)
 */
export default function ({
  params,
  atRule,
  postcssApi
}: {
  params: any;
  atRule: any;
  postcssApi: any;
}) {
  const mediaConfig = __theme().config('media');

  const queries: string[] = [];

  Object.keys(params).forEach(queryId => {
    const query = params[queryId].trim();
    query.split(',').forEach(q => {
      queries.push(q.trim());
    });
  });

  // const queries = params.query.split(',').map(l => l.trim());
  const fullQueriesList: string[] = [];

  queries.forEach(query => {

    // const mediasArray: string[] = [];
    // let currentQuery = '';
    // query.replace(/\sand\s/gm, ' , ').replace(/\sor\s/gm, ' _ ').split('').forEach(char => {
    //   if (char === '_') {
    //     mediasArray.push(currentQuery.trim());
    //     mediasArray.push('or');
    //     currentQuery = '';
    //   } else if (char === ',') {
    //     mediasArray.push(currentQuery.trim());
    //     mediasArray.push('and');
    //     currentQuery = '';
    //   } else {
    //     currentQuery += char;
    //   }
    // });
    // mediasArray.push(currentQuery.trim());

    const currentQueryList: string[] = [mediaConfig.defaultQuery, 'and'];

    // mediasArray.forEach((query) => {

      if (query === 'and' || query === 'or') {
        currentQueryList.push(query); 
        return;
      }

      const firstChar = query.slice(0, 1);
      const firstTwoChar = query.slice(0, 2);
      const lastChar = query.slice(-1);
      let action = mediaConfig.defaultAction;
      let mediaName = query;

      if (lastChar === '-' || lastChar === '|')
        mediaName = mediaName.slice(0, -1);

      if (
        firstTwoChar === '>=' ||
        firstTwoChar === '<=' ||
        firstTwoChar === '=='
      ) {
        mediaName = mediaName.slice(2);
        action = firstTwoChar;
      } else if (firstChar === '<' || firstChar === '>' || firstChar === '=') {
        mediaName = mediaName.slice(1);
        action = firstChar;
      }

      const mediaQueryConfig = mediaConfig.queries[mediaName];
      if (!mediaQueryConfig)
        throw new Error(
          `<red>[postcssSugarPlugin.media]</red> Sorry but the requested media "<yellow>${mediaName}</yellow>" does not exists in the config. Here's the available medias: ${Object.keys(
            mediaConfig.queries
          )
            .map((l) => `<green>${l}</green>`)
            .join(',')}`
        );

      const queryList: string[] = [];

      Object.keys(mediaQueryConfig).forEach((prop) => {
        const value = mediaQueryConfig[prop];
        if (!value) return;

        if (
          [
            'min-width',
            'max-width',
            'min-device-width',
            'max-device-width'
          ].indexOf(prop) !== -1
        ) {
          if (action === '>') {
            if (prop === 'max-width' || prop === 'max-device-width') {
              let argName = 'min-width';
              if (prop.includes('-device')) argName = 'min-device-width';
              queryList.push(`(${argName}: ${value + 1}px)`);
            }
          } else if (action === '<') {
            if (prop === 'min-width' || prop === 'min-device-width') {
              let argName = 'max-width';
              if (prop.includes('-device')) argName = 'max-device-width';
              queryList.push(`(${argName}: ${value}px)`);
            }
          } else if (action === '=') {
            queryList.push(`(${prop}: ${value}px)`);
          } else if (action === '>=') {
            if (prop === 'min-width' || prop === 'min-device-width') {
              queryList.push(`(${prop}: ${value}px)`);
            }
          } else if (action === '<=') {
            if (prop === 'max-width' || prop === 'max-device-width') {
              queryList.push(`(${prop}: ${value}px)`);
            }
          } else {
            queryList.push(`(${prop}: ${value}px)`);
          }
        } else {
          queryList.push(`(${prop}: ${value}px)`);
        }
      });

      if (lastChar === '-') {
        queryList.push('(orientation: landscape)');
      } else if (lastChar === '|') {
        queryList.push('(orientation: portrait)');
      }

      currentQueryList.push(queryList.join(' and '));
    // });

    fullQueriesList.push(currentQueryList.join(' '));

  });
  
  const mediaRule = new postcssApi.AtRule({
    name: 'media',
    params: fullQueriesList.join(' ')
  });

  // const AST = __postcss.parse(`@media ${fullQueriesList.join(' ')} {}`);

  // @ts-ignore
  atRule.nodes.forEach(node => {
    mediaRule.append(node);
  });

  atRule.replaceWith(mediaRule);
}

package org.honeysoft.akka.di;

import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Field;

import static org.fest.reflect.util.Accessibles.setAccessible;
import static org.fest.reflect.util.Accessibles.setAccessibleIgnoringExceptions;

public class SpringUntypedActorFactory implements UntypedActorFactory {

    private final DependencyInjectionFactory dependencyInjectionFactory;

    private final ApplicationContext applicationContext;

    public SpringUntypedActorFactory(Class<?> actorClass, ApplicationContext applicationContext) {
        this.dependencyInjectionFactory = new DefaultUntypedActorFactory(actorClass);
        this.applicationContext = applicationContext;
    }

    public SpringUntypedActorFactory(UntypedActorFactory customFactory, ApplicationContext applicationContext) {
        this.dependencyInjectionFactory = new SpecificUntypedActorFactory(customFactory);
        this.applicationContext = applicationContext;
    }

    private interface DependencyInjectionFactory {
        UntypedActor createAndInject();
    }


    private abstract class AbstractUntypedActorFactory implements DependencyInjectionFactory {

        @Override
        public final UntypedActor createAndInject() {
            try {
                UntypedActor untypedActor = create();

                Class<?> aClass = getActorClass();
                for (Field field : aClass.getDeclaredFields()) {

                    if (field.getAnnotation(Autowired.class) != null) {
                        boolean accessible = field.isAccessible();
                        try {
                            setAccessible(field, true);
                            field.set(untypedActor, applicationContext.getBean(field.getType()));
                        } catch (IllegalAccessException e) {
                            throw new IllegalStateException("Unable to create actor instance", e);
                        } finally {
                            setAccessibleIgnoringExceptions(field, accessible);
                        }
                    }
                }
                return untypedActor;

            } catch (Exception e) {
                throw new IllegalStateException("Unable to create actor instance", e);
            }

        }

        protected abstract Class<?> getActorClass();

        protected abstract UntypedActor create() throws Exception;

    }

    private final class SpecificUntypedActorFactory extends AbstractUntypedActorFactory {

        private final UntypedActorFactory specificFactory;
        private volatile Class<?> actorClass;

        private SpecificUntypedActorFactory(UntypedActorFactory specificFactory) {
            this.specificFactory = specificFactory;
        }

        @Override
        protected Class<?> getActorClass() {
            return actorClass;
        }

        @Override
        protected UntypedActor create() throws Exception {
            UntypedActor untypedActor = (UntypedActor) specificFactory.create();
            actorClass = untypedActor.getClass();
            return untypedActor;
        }
    }

    private final class DefaultUntypedActorFactory extends AbstractUntypedActorFactory {
        private final Class<?> actorClass;

        public DefaultUntypedActorFactory(Class<?> actorClass) {
            this.actorClass = actorClass;
        }

        @Override
        protected Class<?> getActorClass() {
            return actorClass;
        }

        @Override
        protected UntypedActor create() throws InstantiationException, IllegalAccessException {
            return (UntypedActor) actorClass.newInstance();
        }
    }

    /**
     * This method must return a different instance upon every call.
     */
    @Override
    public UntypedActor create() {
        return dependencyInjectionFactory.createAndInject();
    }


}
package channel

import (
	"bytes"
)

/**
 * 通道支付完整单据
 */

// 通道链支付票据
type ChannelPayCompleteDocuments struct {
	// 对账票据表
	ProveBodys *ChannelPayProveBodyList
	// 支付签名票据
	ChainPayment *OffChainFormPaymentChannelTransfer
}

func (c ChannelPayCompleteDocuments) Size() uint32 {
	return c.ProveBodys.Size() + c.ChainPayment.Size()
}

func (c ChannelPayCompleteDocuments) Serialize() ([]byte, error) {
	var buffer bytes.Buffer
	var bt1, _ = c.ProveBodys.Serialize()
	buffer.Write(bt1)
	var bt2, _ = c.ChainPayment.Serialize()
	buffer.Write(bt2)
	return buffer.Bytes(), nil
}

func (c *ChannelPayCompleteDocuments) Parse(buf []byte, seek uint32) (uint32, error) {
	var e error
	// 通道
	c.ProveBodys = &ChannelPayProveBodyList{}
	seek, e = c.ProveBodys.Parse(buf, seek)
	if e != nil {
		return 0, e
	}
	c.ChainPayment = &OffChainFormPaymentChannelTransfer{}
	seek, e = c.ChainPayment.Parse(buf, seek)
	if e != nil {
		return 0, e
	}
	return seek, nil
}

import React, { Fragment, Component } from "react";
import LinearProgress from "@material-ui/core/LinearProgress";
import Snackbar from "../../organisms/Snackbar";

export default class FileUpload extends Component {
  constructor(props) {
    super(props);
    this.state = {
      url: props.url || "/upload/image",
      showStatus: true, //props.showStatus,
      showSnackbar: false,
      snackbarSeverity: "error",
      snackbarDuration: 5000,
      snackbarMessage: "",
    };

    this.uploadId = Math.round(Math.random() * 1e9);
    this.fileInput = React.createRef();
  }

  uploadFile = async (e) => {
    if (this.fileInput.current.files[0]) {
      const formData = new FormData();
      let json;
      try {
        formData.append("image", this.fileInput.current.files[0]);
        const response = await fetch(this.state.url, {
          method: "POST",
          body: formData,
        });
        json = await response.json();

        if (this.props.afterUpload) {
          this.props.afterUpload(json);
        }
        this.setState({
          showSnackbar: true,
          snackbarSeverity: "success",
          snackbarMessage: "Upload success.",
        });
      } catch (e) {
        this.setState({
          showSnackbar: true,
          snackbarSeverity: "error",
          snackbarMessage: "Upload failed.",
        });
      }

      this.fileInput.current.value = "";
    }
  };

  render() {
    const {
      showSnackbar,
      snackbarSeverity,
      snackbarDuration,
      snackbarMessage,
    } = this.state;
    return (
      <Fragment>
        <Snackbar
          open={showSnackbar}
          severity={snackbarSeverity}
          duration={snackbarDuration}
          message={snackbarMessage}
          onClose={() => {
            this.setState({ showSnackbar: false });
          }}
        />
        <input
          accept="image/*"
          id={this.uploadId}
          multiple
          type="file"
          onChange={this.uploadFile}
          onBlur={() => {}}
          ref={this.fileInput}
          style={{ display: "none" }}
        />
        <div
          style={{ cursor: "pointer", display: "inline-block" }}
          onClick={(e) => {
            if (!this.fileInput.current.value === "" || this.props.disabled) {
              return;
            }

            document.getElementById(`${this.uploadId}`).click();
          }}
        >
          {this.fileInput &&
          this.fileInput.current &&
          !this.fileInput.current.value === "" &&
          this.state.showStatus ? (
            <LinearProgress style={{ marginTop: "3em" }} />
          ) : (
            this.props.children
          )}
        </div>
      </Fragment>
    );
  }
}

import FontPainter, { FontParserSVG, RenderEngineSVG, RenderBoundsElementWidth } from 'fontpainter';
import './example-simple.scss';

export class Demo {
	immediate = true;

	constructor() {
		this.container = document.querySelector('.example-simple');
		this.painter = new FontPainter();
		this.engine = new RenderEngineSVG();
		this.painter.setEngine(this.engine);
		this.painter.fontSize = 45;
		this.painter.bounds = new RenderBoundsElementWidth(this.container);
	}

	render(copy = '', fontPath) {
		this.painter.loadFont(fontPath, FontParserSVG);
		this.painter.getFont().then(() => {
			this.painter.paint(copy);
			this.container.appendChild(this.engine.svgElement);
		});
	}

	dispose() {
		this.painter.dispose();
	}
}

export const menuName = 'Simple SVG';

export const defaultText = 'The quick brown fox jumps over the lazy dog';

export { default as template } from 'raw-loader!./template.html';


module BestPractices::Scopes
  extend ActiveSupport::Concern

  included do
    scope :ordered, -> { order obsolete: :asc, name: :asc }
  end

  module ClassMethods
    def visible
      setting                      = Current.organization.settings.find_by name: 'hide_obsolete_best_practices'
      hide_obsolete_best_practices = DEFAULT_SETTINGS[:hide_obsolete_best_practices][:value]

      if (setting ? setting.value : hide_obsolete_best_practices) == '0'
        all
      else
        where(obsolete: false)
      end
    end
  end
end

pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;

import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";

import "../interfaces/helpers/IPriceFeed.sol";

import "../abstract/AbstractDependant.sol";

contract PriceFeed is IPriceFeed, AbstractDependant {
    IUniswapV2Router02 public ammRouter;

    address public wrappedToken;
    address public bmiToken;
    address public usdtToken;

    function setDependencies(IContractsRegistry _contractsRegistry)
        external
        override
        onlyInjectorOrZero
    {
        ammRouter = IUniswapV2Router02(_contractsRegistry.getAMMRouterContract());
        wrappedToken = _contractsRegistry.getWrappedTokenContract();
        bmiToken = _contractsRegistry.getBMIContract();
        usdtToken = _contractsRegistry.getUSDTContract();
    }

    function howManyBMIsInUSDT(uint256 usdtAmount) external view override returns (uint256) {
        if (usdtAmount == 0) {
            return 0;
        }

        address[] memory pairs = new address[](3);
        pairs[0] = usdtToken;
        pairs[1] = wrappedToken;
        pairs[2] = bmiToken;

        uint256[] memory amounts = ammRouter.getAmountsOut(usdtAmount, pairs);

        return amounts[amounts.length - 1];
    }

    function howManyUSDTsInBMI(uint256 bmiAmount) external view override returns (uint256) {
        if (bmiAmount == 0) {
            return 0;
        }

        address[] memory pairs = new address[](3);
        pairs[0] = bmiToken;
        pairs[1] = wrappedToken;
        pairs[2] = usdtToken;

        uint256[] memory amounts = ammRouter.getAmountsOut(bmiAmount, pairs);

        return amounts[amounts.length - 1];
    }
}
import fs from 'fs';
import sinon from 'sinon';
import test from 'tape';

import { mockParsedMarkdown } from './_fixtures';

import { DIRECTORIES } from './config/constants';
import { MarkdownParser } from './MarkdownParser';
import { Renderer } from './Renderer';
import { parseContent } from './parseContent';

import type { ParsedContentType } from './parseContent';

type MockDirentProps = {
  isDirectory?: true;
  isFile?: true;
  name: string;
};

const mockDirent = (props: MockDirentProps): fs.Dirent => {
  const { isDirectory, isFile, name } = props;

  return {
    isBlockDevice: () => false,
    isCharacterDevice: () => false,
    isDirectory: () => isDirectory || false,
    isFIFO: () => false,
    isFile: () => isFile || false,
    isSocket: () => false,
    isSymbolicLink: () => false,
    name,
  };
};

test('`parseContent`', async (t: test.Test) => {
  const readdirStub = sinon.stub(fs.promises, 'readdir');
  const readFileStub = sinon.stub(fs.promises, 'readFile');

  readdirStub
    .withArgs('./content/', { withFileTypes: true })
    .resolves([
      mockDirent({ isFile: true, name: 'index.md' }),
      mockDirent({ isFile: true, name: 'draft.md' }),
      mockDirent({ isFile: true, name: 'page.md' }),
      mockDirent({ isFile: true, name: 'asset.jpg' }),
      mockDirent({ isFile: true, name: '_data.json' }),
      mockDirent({ isDirectory: true, name: 'directory' }),
    ]);

  readdirStub
    .withArgs('./content/directory/', { withFileTypes: true })
    .resolves([
      mockDirent({ isFile: true, name: '_index.md' }),
      mockDirent({ isFile: true, name: 'draft.md' }),
      mockDirent({ isFile: true, name: 'page.md' }),
      mockDirent({ isFile: true, name: 'asset.jpg' }),
      mockDirent({ isFile: true, name: '_data.json' }),
      mockDirent({ isDirectory: true, name: 'nested' }),
    ]);

  readdirStub
    .withArgs('./content/directory/nested/', { withFileTypes: true })
    .resolves([
      mockDirent({ isFile: true, name: 'index.md' }),
      mockDirent({ isFile: true, name: 'draft.md' }),
      mockDirent({ isFile: true, name: 'page.md' }),
      mockDirent({ isFile: true, name: 'asset.jpg' }),
      mockDirent({ isFile: true, name: '_data.json' }),
    ]);

  readFileStub.withArgs(sinon.match(/\.md$/)).resolves('Markdown');
  readFileStub
    .withArgs(sinon.match(/draft.md$/))
    .resolves('+++\ndraft = true\n+++\n\nMarkdown');
  readFileStub
    .withArgs(sinon.match(/_data.json$/))
    .resolves('{ "key": "value" }');

  const renderer = new Renderer({ baseTemplate: '', config: {}, partials: {} });
  const markdownParser = new MarkdownParser(renderer, []);

  const content = await parseContent({
    directory: DIRECTORIES.CONTENT,
    markdownParser,
    renderer,
  });

  t.deepEqual(
    content,
    {
      assets: [{ filePath: './content/asset.jpg' }],
      children: {
        directory: {
          assets: [{ filePath: './content/directory/asset.jpg' }],
          children: {
            nested: {
              assets: [{ filePath: './content/directory/nested/asset.jpg' }],
              children: null,
              data: {
                json: { key: 'value' },
                filePath: './content/directory/nested/_data.json',
              },
              pages: [
                {
                  filePath: './content/directory/nested/index.md',
                  markdown: mockParsedMarkdown,
                  name: 'index.md',
                },
                {
                  filePath: './content/directory/nested/page.md',
                  markdown: mockParsedMarkdown,
                  name: 'page.md',
                },
              ],
              section: null,
            },
          },
          data: {
            json: { key: 'value' },
            filePath: './content/directory/_data.json',
          },
          pages: [
            {
              filePath: './content/directory/page.md',
              markdown: mockParsedMarkdown,
              name: 'page.md',
            },
          ],
          section: {
            filePath: './content/directory/_index.md',
            markdown: mockParsedMarkdown,
            name: '_index.md',
          },
        },
      },
      data: { json: { key: 'value' }, filePath: './content/_data.json' },
      pages: [
        {
          filePath: './content/index.md',
          markdown: mockParsedMarkdown,
          name: 'index.md',
        },
        {
          filePath: './content/page.md',
          markdown: mockParsedMarkdown,
          name: 'page.md',
        },
      ],
      section: null,
    } as ParsedContentType,
    'parses all files within the given directory and returns a formatted object'
  );

  readdirStub.restore();
  readFileStub.restore();
  t.end();
});

@extends('errors::layout')

@section('title', 'Error')

{{--@section('message', 'Whoops, looks like something went wrong.')--}}

@section('message')
    500
    <br/><br/>
    服务器出错，请联系您的管理员
@stop

package com.pixelw.net.netty;

import com.pixelw.entity.Client;
import com.pixelw.net.ServerCore;
import com.pixelw.net.ServerListener;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

import java.util.Map;

/**
 * @author Carl Su
 * @date 2020/5/1
 */
public class NettyCore extends ServerCore {

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    public NettyCore(ServerListener listener, int port) {
        super(listener, port);
    }

    @Override
    public void run() {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                bossGroup = new NioEventLoopGroup();
                workerGroup = new NioEventLoopGroup();
                try {
                    ServerBootstrap bootstrap = new ServerBootstrap();
                    bootstrap.group(bossGroup, workerGroup)
                            .channel(NioServerSocketChannel.class)
                            .childHandler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel socketChannel) {
                                    socketChannel.pipeline().addLast(new ServerHandler(listener, NettyCore.this));
                                }
                            })
                            .option(ChannelOption.SO_BACKLOG, 128)
                            .childOption(ChannelOption.SO_KEEPALIVE, true);
                    ChannelFuture future = bootstrap.bind(port).sync();
                    future.channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void sendTextMsg(String msg, Client client) {
        Channel channel = client.getChannel();
        if (channel != null) {
            System.out.println("sendto:" + client.getInetAddress());
            //client is based on stream reader, append a line
            String string = msg + "\n";
            byte[] bytes = string.getBytes(CharsetUtil.UTF_8);
            ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes);
            channel.writeAndFlush(byteBuf);
        }
    }

    @Override
    public void shutdown(Map<String, Client> map) {
        //foreach 或者Iterator
        try {
            if (map.size() > 0) {
                for (String strUserID : map.keySet()) {
                    Client client = map.get(strUserID);
                    client.getChannel().writeAndFlush(CONTROL_TOKEN);
                    client.getChannel().close();
                }
            } else {
                System.out.println("no opened sockets");
            }
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            listener.onClosed(this);
        }

    }
}

import React, {Component} from 'react';
import FailureView from '../views/FailureView';
import PropTypes from 'prop-types';

class Failure extends Component {
  showLogin() {
    const {emitter} = this.props.services;
    emitter.emit('setView', 'Login');
  }

  render() {
    const {error} = this.props.viewParameters;
    return (
      <FailureView
        errorMessage={error}
        onBackClick={this.showLogin.bind(this)}
      />
    );
  }
}

Failure.propTypes = {
  services: PropTypes.object,
  viewParameters: PropTypes.object
};

export default Failure;

package org.lwjgl.opengl;

/**
 * Native bindings to the <a target="_blank" href="https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_gpu_shader_half_float.txt">AMD_gpu_shader_half_float</a> extension.
 * 
 * <p>This extension was developed based on the {@link NVGPUShader5 NV_gpu_shader5} extension to allow implementations supporting half float in shader and expose the
 * feature without the additional requirements that are present in {@code NV_gpu_shader5}.</p>
 * 
 * <p>The extension introduces the following features for all shader types:</p>
 * 
 * <ul>
 * <li>support for half float scalar, vector and matrix data types in shader;</li>
 * <li>new built-in functions to pack and unpack half float types into a 32-bit integer vector;</li>
 * <li>half float support for all existing single float built-in functions, including angle functions, exponential functions, common functions, geometric
 * functions, matrix functions and etc.;</li>
 * </ul>
 * 
 * <p>This extension is designed to be a functional superset of the half-precision floating-point support from NV_gpu_shader5 and to keep source code
 * compatible with that, thus the new procedures, functions, and tokens are identical to those found in that extension.</p>
 * 
 * <p>Requires {@link GL40 OpenGL 4.0} and GLSL 4.00.</p>
 */
public final class AMDGPUShaderHalfFloat {

    /** Returned by the {@code type} parameter of GetActiveAttrib, GetActiveUniform, and GetTransformFeedbackVarying. */
    public static final int
        GL_FLOAT16_MAT2_AMD   = 0x91C5,
        GL_FLOAT16_MAT3_AMD   = 0x91C6,
        GL_FLOAT16_MAT4_AMD   = 0x91C7,
        GL_FLOAT16_MAT2x3_AMD = 0x91C8,
        GL_FLOAT16_MAT2x4_AMD = 0x91C9,
        GL_FLOAT16_MAT3x2_AMD = 0x91CA,
        GL_FLOAT16_MAT3x4_AMD = 0x91CB,
        GL_FLOAT16_MAT4x2_AMD = 0x91CC,
        GL_FLOAT16_MAT4x3_AMD = 0x91CD;

    private AMDGPUShaderHalfFloat() {}

}
package pipelineexecution

import (
	"context"
	"github.com/rancher/norman/controller"
	"github.com/rancher/rancher/pkg/controllers/user/pipeline/engine"
	"github.com/rancher/rancher/pkg/controllers/user/pipeline/utils"
	"github.com/rancher/rancher/pkg/ticker"
	"github.com/rancher/types/apis/management.cattle.io/v3"
	"github.com/sirupsen/logrus"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	"time"
)

const (
	syncStateInterval = 5 * time.Second
)

//ExecutionStateSyncer is responsible for updating pipeline execution states
//by syncing with the pipeline engine
type ExecutionStateSyncer struct {
	clusterName           string
	clusterPipelineLister v3.ClusterPipelineLister

	pipelineLister          v3.PipelineLister
	pipelines               v3.PipelineInterface
	pipelineExecutionLister v3.PipelineExecutionLister
	pipelineExecutions      v3.PipelineExecutionInterface
	pipelineEngine          engine.PipelineEngine
}

func (s *ExecutionStateSyncer) sync(ctx context.Context, syncInterval time.Duration) {
	for range ticker.Context(ctx, syncInterval) {
		s.syncState()
	}

}

func (s *ExecutionStateSyncer) syncState() {
	if !utils.IsPipelineDeploy(s.clusterPipelineLister, s.clusterName) {
		return
	}

	set := labels.Set(map[string]string{utils.PipelineFinishLabel: "false"})
	allExecutions, err := s.pipelineExecutionLister.List("", set.AsSelector())
	if err != nil {
		logrus.Errorf("Error listing PipelineExecutions - %v", err)
		return
	}
	executions := []*v3.PipelineExecution{}
	for _, e := range allExecutions {
		if controller.ObjectInCluster(s.clusterName, e) {
			executions = append(executions, e)
		}
	}
	if len(executions) < 1 {
		return
	}
	if err := s.pipelineEngine.PreCheck(); err != nil {
		//fail to connect engine, mark the remaining executions as failed
		logrus.Errorf("Error get Jenkins engine - %v", err)
		for _, e := range executions {
			e.Status.ExecutionState = utils.StateFail
			v3.PipelineExecutionConditonProvisioned.False(e)
			v3.PipelineExecutionConditonProvisioned.ReasonAndMessageFromError(e, err)
			if err := s.updateExecutionAndLastRunState(e); err != nil {
				logrus.Errorf("Error update pipeline execution - %v", err)
				return
			}
		}
		return
	}
	for _, e := range executions {
		if e.Status.ExecutionState == utils.StateWaiting || e.Status.ExecutionState == utils.StateBuilding {
			updated, err := s.pipelineEngine.SyncExecution(e)
			if err != nil {
				logrus.Errorf("Error sync pipeline execution - %v", err)
				e.Status.ExecutionState = utils.StateFail
				v3.PipelineExecutionConditonProvisioned.False(e)
				v3.PipelineExecutionConditonProvisioned.ReasonAndMessageFromError(e, err)
				updated = true
			}
			if updated {
				if err := s.updateExecutionAndLastRunState(e); err != nil {
					logrus.Errorf("Error update pipeline execution - %v", err)
					return
				}
			}
		} else {
			if err := s.updateExecutionAndLastRunState(e); err != nil {
				logrus.Errorf("Error update pipeline execution - %v", err)
				return
			}
		}
	}
	logrus.Debugf("Sync pipeline execution state complete")
}

func (s *ExecutionStateSyncer) updateExecutionAndLastRunState(execution *v3.PipelineExecution) error {
	if execution.Status.ExecutionState != utils.StateWaiting && execution.Status.ExecutionState != utils.StateBuilding {
		execution.Labels[utils.PipelineFinishLabel] = "true"
	}
	if _, err := s.pipelineExecutions.Update(execution); err != nil {
		return err
	}

	//check and update lastrunstate of the pipeline when necessary
	p, err := s.pipelineLister.Get(execution.Spec.Pipeline.Namespace, execution.Spec.Pipeline.Name)
	if apierrors.IsNotFound(err) {
		logrus.Warningf("pipeline of execution '%s' is not found", execution.Name)
		return nil
	} else if err != nil {
		return err
	}

	if p.Status.LastExecutionID == execution.Namespace+":"+execution.Name &&
		p.Status.LastRunState != execution.Status.ExecutionState {
		p.Status.LastRunState = execution.Status.ExecutionState
		if _, err := s.pipelines.Update(p); err != nil {
			return err
		}
	}
	return nil
}

### [CVE-2006-4327](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-4327)
![](https://img.shields.io/static/v1?label=Product&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Version&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Vulnerability&message=n%2Fa&color=brighgreen)

### Description

Multiple cross-site scripting (XSS) vulnerabilities in add_url.php in CloudNine Interactive Links Manager 2006-06-12 allow remote attackers to inject arbitrary web script or HTML via the (1) title, (2) description, or (3) keywords parameters.

### POC

#### Reference
- http://evuln.com/vulns/136/description.html

#### Github
No PoCs found on GitHub currently.


package io.github.yannici.bedwars.Listener;

import java.util.List;

import io.github.yannici.bedwars.Main;
import io.github.yannici.bedwars.Game.Game;
import io.github.yannici.bedwars.Game.GameState;

import org.bukkit.event.EventHandler;
import org.bukkit.event.weather.WeatherChangeEvent;

public class WeatherListener extends BaseListener {

	public WeatherListener() {
		super();
	}

	@EventHandler
	public void onWeatherEvent(WeatherChangeEvent we) {
	    if(we.isCancelled()) {
	        return;
	    }
	    
	    List<Game> games = Main.getInstance().getGameManager().getGamesByWorld(we.getWorld());
	    
	    if(games.size() == 0) {
	        return;
	    }
	    
	    for(Game game : games) {
	    	if(game.getState() == GameState.STOPPED) {
		        continue;
		    }
	    	
	    	we.setCancelled(true);
	    	return;
	    }
	}

}

package uoc.cbonache.tfg.ui.shippingMap

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.os.Build
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.drawable.DrawableCompat
import android.view.ViewGroup
import uoc.cbonache.tfg.R
import uoc.cbonache.tfg.ui.ManagePermissions
import uoc.cbonache.tfg.ui.Navigator
import uoc.cbonache.tfg.ui.base.BaseActivity
import uoc.cbonache.tfg.ui.model.ShippingViewEntity
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.MapFragment
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.PolylineOptions
import org.jetbrains.anko.contentView
import javax.inject.Inject

/**
 * @author cbonache
 */
class ShippingMapActivity: BaseActivity(), ShippingMapView, OnMapReadyCallback {


    companion object {

        const val CODE = "code"
        @JvmStatic
        fun getIntent(context: Context): Intent {
            return Intent(context, ShippingMapActivity::class.java)
        }
    }

    @Inject lateinit var presenter: ShippingMapPresenter
    @Inject lateinit var managePermissions: ManagePermissions
    @Inject lateinit var navigator: Navigator
    lateinit var locationManager: LocationManager
    lateinit var mapFragment: MapFragment
    lateinit var googleMap: GoogleMap
    lateinit var geocoder: Geocoder
    lateinit var shippingDestination: String

    override fun onRequestLayout(): Int {
        return R.layout.activity_shipping_map
    }

    override fun onViewLoaded() {
        val code = intent.extras.get(CODE) as String
        setUpActionBar()
        presenter.onStart(code)
    }

    override fun showMap() {

        if (googleServicesAvailable()) {
            mapFragment = fragmentManager.findFragmentById(R.id.frame_map) as MapFragment
            mapFragment.getMapAsync(this)
        }
    }

    override fun drawPolyline(polyOptions: PolylineOptions) {

        googleMap.addPolyline(polyOptions)

        setUpMapClick()
    }

    private fun setUpMapClick() {

        googleMap.setOnMapLongClickListener {
            presenter.onClickMap()
        }
    }

    @SuppressLint("MissingPermission")
    override fun getCurrentLocation(): Location? {
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
    }

    override fun getDestination(): String {
        return shippingDestination
    }

    override fun navigateToGoogleMaps() {

        navigator.navigateToGoogleMapsApps(this, shippingDestination)
    }

    private fun googleServicesAvailable(): Boolean {

        val api = GoogleApiAvailability.getInstance()
        val isAvailable = api.isGooglePlayServicesAvailable(this)
        return isAvailable == ConnectionResult.SUCCESS
    }


    private fun setUpActionBar() {

        supportActionBar?.apply {
            title = getString(R.string.shipping_map)
            setDisplayHomeAsUpEnabled(true)
            setDisplayShowHomeEnabled(true)
        }
    }

    override fun showShippingInfo(shippingViewEntity: ShippingViewEntity) {
        shippingDestination = shippingViewEntity.address + " " + shippingViewEntity.cp + " " + shippingViewEntity.city + " " + shippingViewEntity.country
    }

    override fun requestLocationPermission() {

        val permissionsMessage = getString(R.string.permissions_location_message)
        val listener =
                managePermissions.setAllPermissionsListener(this,
                        contentView as ViewGroup, permissionsMessage, { presenter.onLocationPermissionGranted() })
        managePermissions.setRequestPermissions(this, arrayListOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), listener)
    }

    override fun onMapReady(googleMap: GoogleMap) {

        this.googleMap = googleMap
        geocoder = Geocoder(this)
        goToLocation(15f)
        presenter.onMapReady(this)

    }


    private fun goToLocation(zoom: Float) {

        val address = geocoder.getFromLocationName(shippingDestination, 1)
        val it = address.first()
        val ll = LatLng(it.latitude, it.longitude)
        val updateCamera = CameraUpdateFactory.newLatLngZoom(ll, zoom)

        googleMap.moveCamera(updateCamera)
        googleMap.addMarker(MarkerOptions().position(ll))
    }

    override fun showLocation(currentLocation: Location?) {

        currentLocation?.let {
            val latlng = LatLng(currentLocation.latitude, currentLocation.longitude)

            val bitmap = getBitmapFromVectorDrawable(this, R.drawable.ic_noun_814594_cc)
            googleMap.addMarker(MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(bitmap)))
        }
    }

    private fun getBitmapFromVectorDrawable(context: Context, drawableId: Int): Bitmap {
        var drawable = ContextCompat.getDrawable(context, drawableId)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            drawable = DrawableCompat.wrap(drawable).mutate()
        }

        val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth,
                drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)

        return bitmap
    }
}

package net.thinksquared.lilldep.struts;

/*******************************************************
* Creates a new Collection.
* author: Arnold Doray
* date: 19 Mar 2005
* version: 0.0
* Copyright 2005 Arnold Doray   
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
********************************************************/

import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import net.thinksquared.lilldep.database.*;

public final class NewCollectionAction extends Action implements JSPConstants{

    private final String QUERY_PREFIX = "SELECT CONTACT.CONTACT_ID,CONTACT.NAME,CONTACT.DESIGNATION,CONTACT.DEPARTMENT,CONTACT.EMAIL,CONTACT.TEL,CONTACT.FAX,CONTACT.COMPANY,CONTACT.ADDRESS,CONTACT.POSTCODE,CONTACT.COUNTRY,CONTACT.WEBSITE,CONTACT.ACTIVITY,CONTACT.CLASSIFICATION,CONTACT.MEMO, UPPER(CONTACT.COMPANY) AS UCOMPANY FROM CONTACT WHERE ";
    private final String QUERY_SUFFIX = " ORDER BY UCOMPANY";

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
    throws Exception{

            //YOUR IMPLEMENTATION HERE.

            //NOTE: The query passed to ContactPeer's doSelect()
            //      should be QUERY_PREFIX + query + QUERY_SUFFIX

            return null;//REMOVE!
        
    }

}



package org.imagearchive.lsm.toolbox;

import ij.IJ;
import ij.ImagePlus;
import ij.text.TextWindow;

import org.imagearchive.lsm.reader.info.ImageDirectory;
import org.imagearchive.lsm.reader.info.LSMFileInfo;
import org.imagearchive.lsm.toolbox.info.CZLSMInfoExtended;
import org.imagearchive.lsm.toolbox.info.EventList;
import org.imagearchive.lsm.toolbox.info.scaninfo.Recording;

public class StampUtils {
	public static String getTStamps(Reader reader, ImagePlus imp) {
		reader.updateMetadata(imp);
		LSMFileInfo openLSM = (LSMFileInfo) imp.getOriginalFileInfo();
		CZLSMInfoExtended cz = (CZLSMInfoExtended) ((ImageDirectory) openLSM.imageDirectories
				.get(0)).TIF_CZ_LSMINFO;
		int n = new Long(cz.timeStamps.NumberTimeStamps).intValue();
		String[] stamps = new String[n];
		for (int k = 0; k < n; k++)
			stamps[k] = Double.toString(cz.timeStamps.TimeStamps[k]);
		return implode(stamps);
	}

	public static String getZStamps(Reader reader, ImagePlus imp) {
		reader.updateMetadata(imp);
		LSMFileInfo openLSM = (LSMFileInfo) imp.getOriginalFileInfo();
		CZLSMInfoExtended cz = (CZLSMInfoExtended) ((ImageDirectory) openLSM.imageDirectories
				.get(0)).TIF_CZ_LSMINFO;
		Recording r = (Recording) cz.scanInfo.recordings.get(0);
		double planeSpacing = ((Double) r.records.get("PLANE_SPACING")).doubleValue();
		double ps = 0;
		String[] stamps = new String[(int) cz.DimensionZ];
		for (int k = 0; k < cz.DimensionZ; k++){
			stamps[k] = IJ.d2s(ps, 2) + " "+ MasterModel.micrometer;
			ps += planeSpacing;
		}
		return implode(stamps);
	}

	public static String getLStamps(Reader reader, ImagePlus imp) {
		reader.updateMetadata(imp);
		LSMFileInfo openLSM = (LSMFileInfo) imp.getOriginalFileInfo();
		CZLSMInfoExtended cz = (CZLSMInfoExtended) ((ImageDirectory) openLSM.imageDirectories
				.get(0)).TIF_CZ_LSMINFO;
		if (cz.SpectralScan != 1) {
			IJ
					.error("Image not issued from spectral scan. Lambda stamp obsolete!");
			return null;
		}
		String[] stamps = new String[(int) cz.channelWavelength.Channels];
		for (int k = 0; k < cz.channelWavelength.Channels; k++){
			stamps[k] = IJ.d2s(cz.channelWavelength.LambdaStamps[k], 2);

		}
		return implode(stamps);
	}

	public static String getEvents(Reader reader, ImagePlus imp) {
		reader.updateMetadata(imp);
		LSMFileInfo openLSM = (LSMFileInfo) imp.getOriginalFileInfo();
		CZLSMInfoExtended cz = (CZLSMInfoExtended) ((ImageDirectory) openLSM.imageDirectories
				.get(0)).TIF_CZ_LSMINFO;

		EventList events = cz.eventList;
		StringBuffer buffer = new StringBuffer();
		if (events != null) {
			buffer.append("Time (sec) \tEvent Type \tEvent Description");
			buffer.append(events.Description);
		}
		return buffer.toString();
	}

	private static String implode(String[] input) {
		String result;
		if (input.length == 0) {
			result = "";
		} else {
			StringBuffer sb = new StringBuffer();
			sb.append(input[0]);
			for (int i = 1; i < input.length; i++) {
				sb.append(",");
				sb.append(input[i]);
			}
			result = sb.toString();
		}
		return result;
	}


}
var jQuery = function(selector) {
    /* BEGIN arguments unpacking */
    /* END arguments unpacking */
    /* BEGIN function */
    var call_arguments0 = [jstype, selector];
    var call_arguments1 = [$, pythonium_call.apply(undefined, call_arguments0)];
    return pythonium_call.apply(undefined, call_arguments1);
    return __NONE;
};

var call_arguments2 = [jQuery, pythonium_call(str, '[type="text"]')];
input = pythonium_call.apply(undefined, call_arguments2);
var call_arguments3 = [jQuery, pythonium_call(str, '[type="submit"]')];
button = pythonium_call.apply(undefined, call_arguments3);
var call_arguments4 = [jQuery, pythonium_call(str, "#todos")];
todos = pythonium_call.apply(undefined, call_arguments4);
var add_todo = function(text) {
    /* BEGIN arguments unpacking */
    /* END arguments unpacking */
    var li;
    /* BEGIN function */
    li = (pythonium_call(pythonium_get_attribute((pythonium_call(pythonium_get_attribute(pythonium_call(str, "<li>"), "__add__"), text)), "__add__"), pythonium_call(str, "</li>")));
    var call_arguments5 = [jstype, li];
    li = pythonium_call.apply(undefined, call_arguments5);
    var call_arguments6 = [pythonium_get_attribute(todos, "append"), li];
    pythonium_call.apply(undefined, call_arguments6);
};

var on_click = function(event) {
    /* BEGIN arguments unpacking */
    /* END arguments unpacking */
    var text;
    /* BEGIN function */
    var call_arguments7 = [pythonium_get_attribute(input, "val")];
    var call_arguments8 = [str, pythonium_call.apply(undefined, call_arguments7)];
    text = pythonium_call.apply(undefined, call_arguments8);
    var call_arguments9 = [len, text];
    if (pythonium_is_true(pythonium_call.apply(undefined, call_arguments9))) {
        var call_arguments10 = [add_todo, text];
        pythonium_call.apply(undefined, call_arguments10);
    }
};

var call_arguments11 = [pythonium_get_attribute(button, "click"), on_click];
pythonium_call.apply(undefined, call_arguments11);

(defproject coldnew/best5 "0.1.0-SNAPSHOT"
  :description "Get the Taiwan's stock best5 data"
  :url "https://github.com/coldnew/twstock-best5.clj"
  :author "Yen-Chin, Lee"
  :license {:name "MIT License"
            :url "https://github.com/coldnew/twstock-best5.clj/blob/master/LICENSE"}
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [clj-http "3.7.0"]
                 [cheshire "5.8.0"]
                 [http-kit "2.3.0"]
                 [hickory "0.7.1"]
                 [clj-time "0.14.2"]
                 [datascript "0.16.3"]
                 [datascript-transit "0.2.2"]
                 [toucan "1.1.4"]
                 [yesql "0.5.3"]
                 [org.xerial/sqlite-jdbc "3.14.2.1"]
                 [com.layerware/hugsql "0.4.8"]]

  :source-paths ["src"]
  :test-paths ["test"]

  :main coldnew.best5.core
  :jvm-opts ["-Dclojure.compiler.direct-linking=true"
             "-XX:MaxDirectMemorySize=16g" "-XX:+UseLargePages"]

  :profiles {:uberjar
             {:source-paths ["src/clj"]
              :omit-source true
              :aot :all}})

﻿/*
 * Licensed to the SkyAPM under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The SkyAPM licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

using SkyApm.Tracing.Segments;

namespace SkyApm.Tracing
{
    public class CrossThreadCarrier : SegmentReference, ICarrier
    {
        public bool HasValue => true;

        public bool? Sampled { get; set; }
    }
}

import { _SystemTemplateFilter } from "./_SystemTemplateFilter";
import { NodeHttpOptions as __HttpOptions__ } from "@aws-sdk/types";
import * as __aws_sdk_types from "@aws-sdk/types";

/**
 * SearchSystemTemplatesInput shape
 */
export interface SearchSystemTemplatesInput {
  /**
   * <p>An array of filters that limit the result set. The only valid filter is <code>FLOW_TEMPLATE_ID</code>.</p>
   */
  filters?: Array<_SystemTemplateFilter> | Iterable<_SystemTemplateFilter>;

  /**
   * <p>The string that specifies the next page of results. Use this when you're paginating results.</p>
   */
  nextToken?: string;

  /**
   * <p>The maximum number of results to return in the response.</p>
   */
  maxResults?: number;

  /**
   * The maximum number of times this operation should be retried. If set, this value will override the `maxRetries` configuration set on the client for this command.
   */
  $maxRetries?: number;

  /**
   * An object that may be queried to determine if the underlying operation has been aborted.
   *
   * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
   */
  $abortSignal?: __aws_sdk_types.AbortSignal;

  /**
   * Per-request HTTP configuration options. If set, any options specified will override the corresponding HTTP option set on the client for this command.
   */
  $httpOptions?: __HttpOptions__;
}

#! /usr/bin/env python

"""
 *******************************************************************************
 * 
 * $Id: SecureDocXMLRPCServer.py 4 2008-06-04 18:44:13Z yingera $
 * $URL: https://xxxxxx/repos/utils/trunk/tools/SVNRPCServer.py $
 *
 * $Date: 2008-06-04 13:44:13 -0500 (Wed, 04 Jun 2008) $
 * $Author: yingera $
 *
 * Authors: Laszlo Nagy, Andrew Yinger
 *
 * Description: Threaded, Documenting SecureDocXMLRPCServer.py - over HTTPS.
 *
 *  requires pyOpenSSL: http://sourceforge.net/project/showfiles.php?group_id=31249
 *   ...and open SSL certs installed.
 *
 * Based on this article: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549
 *
 *******************************************************************************
"""

import SocketServer
import BaseHTTPServer
import SimpleHTTPServer
import SimpleXMLRPCServer

import socket, os
from OpenSSL import SSL
from threading import Event, currentThread, Thread, Condition
from thread import start_new_thread as start
from DocXMLRPCServer import DocXMLRPCServer, DocXMLRPCRequestHandler

# static stuff
DEFAULTKEYFILE='key.pem'    # Replace with your PEM formatted key file
DEFAULTCERTFILE='certificate.crt'  # Replace with your PEM formatted certificate file


class SecureDocXMLRpcRequestHandler(DocXMLRPCRequestHandler):
    """Secure Doc XML-RPC request handler class.
    It it very similar to DocXMLRPCRequestHandler but it uses HTTPS for transporting XML data.
    """
    def setup(self):
        self.connection = self.request
        self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
        self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)

    def address_string(self):
        "getting 'FQDN' from host seems to stall on some ip addresses, so... just (quickly!) return raw host address"
        host, port = self.client_address
        #return socket.getfqdn(host)
        return host

    def do_POST(self):
        """Handles the HTTPS POST request.
        It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
        """
        try:
            # get arguments
            data = self.rfile.read(int(self.headers["content-length"]))
            # In previous versions of SimpleXMLRPCServer, _dispatch
            # could be overridden in this class, instead of in
            # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
            # check to see if a subclass implements _dispatch and dispatch
            # using that method if present.
            response = self.server._marshaled_dispatch(data, getattr(self, '_dispatch', None))
        except: # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            self.send_response(500)
            self.end_headers()
        else:
            # got a valid XML RPC response
            self.send_response(200)
            self.send_header("Content-type", "text/xml")
            self.send_header("Content-length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)

            # shut down the connection
            self.wfile.flush()
            self.connection.shutdown() # Modified here!

    def do_GET(self):
        """Handles the HTTP GET request.

        Interpret all HTTP GET requests as requests for server
        documentation.
        """
        # Check that the path is legal
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        response = self.server.generate_html_documentation()
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)

        # shut down the connection
        self.wfile.flush()
        self.connection.shutdown() # Modified here!

    def report_404 (self):
        # Report a 404 error
        self.send_response(404)
        response = 'No such page'
        self.send_header("Content-type", "text/plain")
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)
        # shut down the connection
        self.wfile.flush()
        self.connection.shutdown() # Modified here!



class CustomThreadingMixIn:
    """Mix-in class to handle each request in a new thread."""
    # Decides how threads will act upon termination of the main process
    daemon_threads = True

    def process_request_thread(self, request, client_address):
        """Same as in BaseServer but as a thread.
        In addition, exception handling is done here.
        """
        try:
            self.finish_request(request, client_address)
            self.close_request(request)
        except (socket.error, SSL.SysCallError), why:
            print 'socket.error finishing request from "%s"; Error: %s' % (client_address, str(why))
            self.close_request(request)
        except:
            self.handle_error(request, client_address)
            self.close_request(request)

    def process_request(self, request, client_address):
        """Start a new thread to process the request."""
        t = Thread(target = self.process_request_thread, args = (request, client_address))
        if self.daemon_threads:
            t.setDaemon(1)
        t.start()



class SecureDocXMLRPCServer(CustomThreadingMixIn, DocXMLRPCServer):
    def __init__(self, registerInstance, server_address, keyFile=DEFAULTKEYFILE, certFile=DEFAULTCERTFILE, logRequests=True):
        """Secure Documenting XML-RPC server.
        It it very similar to DocXMLRPCServer but it uses HTTPS for transporting XML data.
        """
        DocXMLRPCServer.__init__(self, server_address, SecureDocXMLRpcRequestHandler, logRequests)
        self.logRequests = logRequests

        # stuff for doc server
        try: self.set_server_title(registerInstance.title)
        except AttributeError: self.set_server_title('default title')
        try: self.set_server_name(registerInstance.name)
        except AttributeError: self.set_server_name('default name')
        if registerInstance.__doc__: self.set_server_documentation(registerInstance.__doc__)
        else: self.set_server_documentation('default documentation')
        self.register_introspection_functions()

        # init stuff, handle different versions:
        try:
            SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self)
        except TypeError:
            # An exception is raised in Python 2.5 as the prototype of the __init__
            # method has changed and now has 3 arguments (self, allow_none, encoding)
            SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self, False, None)
        SocketServer.BaseServer.__init__(self, server_address, SecureDocXMLRpcRequestHandler)
        self.register_instance(registerInstance) # for some reason, have to register instance down here!

        # SSL socket stuff
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file(keyFile)
        ctx.use_certificate_file(certFile)
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
        self.server_bind()
        self.server_activate()

        # requests count and condition, to allow for keyboard quit via CTL-C
        self.requests = 0
        self.rCondition = Condition()


    def startup(self):
        'run until quit signaled from keyboard...'
        print 'server starting; hit CTRL-C to quit...'
        while True:
            try:
                self.rCondition.acquire()
                start(self.handle_request, ()) # we do this async, because handle_request blocks!
                while not self.requests:
                    self.rCondition.wait(timeout=3.0)
                if self.requests: self.requests -= 1
                self.rCondition.release()
            except KeyboardInterrupt:
                print "quit signaled, i'm done."
                return

    def get_request(self):
        request, client_address = self.socket.accept()
        self.rCondition.acquire()
        self.requests += 1
        self.rCondition.notifyAll()
        self.rCondition.release()
        return (request, client_address)

    def listMethods(self):
        'return list of method names (strings)'
        methodNames = self.funcs.keys()
        methodNames.sort()
        return methodNames

    def methodHelp(self, methodName):
        'method help'
        if methodName in self.funcs:
            return self.funcs[methodName].__doc__
        else:
            raise Exception('method "%s" is not supported' % methodName)



def TestSampleServer():
    """Test xml rpc over https server"""
    class ExampleRegisters:
        '''just some test methods to try out new secure doc xml-rpc server...'''
        title = 'test server methods'
        name = 'test server'
        def __init__(self):
            import string
            self.python_string = string
            
        def add(self, x, y):
            return x + y
    
        def mult(self,x,y):
            return x*y
    
        def div(self,x,y):
            return x//y

        def poop(self): return 'poop'
        
    server_address = (socket.gethostname(), 9779) # (address, port)
    server = SecureDocXMLRPCServer(ExampleRegisters(), server_address, DEFAULTKEYFILE, DEFAULTCERTFILE)    
    sa = server.socket.getsockname()
    print "Serving HTTPS on", sa[0], "port", sa[1]
    server.startup()


if __name__ == '__main__':
    TestSampleServer()


# Here is an xmlrpc client for testing:
"""
import xmlrpclib

server = xmlrpclib.Server('https://localhost:9777')
print server.add(1,2)
print server.div(10,4)
"""

const salaryInformation = [
  {
    type: 'select',
    name: 'currency_typeSalary',
    label: 'Salary Amount',
    placeholder: '',
    twocol: false,
    colWidth: '0 1 118px',

    options: [{ value: 'RM', label: 'RM' }],
  },
  {
    type: 'input',
    name: 'salary_amount',
    label: '',
    placeholder: 'Amount',
    twocol: false,
    req: true,
    reqmessage: 'Please enter amount',
    colWidth: '1 0 180px',
  },
  {
    type: 'select',
    name: 'payment_method',
    label: 'Payment Method',
    placeholder: 'Select Payment Method',
    twocol: true,
    req: true,
    reqmessage: 'Payment method required',
    options: [
      { value: 'Automatic Payment System (APS)', label: 'Automatic Payment System (APS)' },
      { value: 'Cash', label: 'Cash' },
      { value: 'Cheque', label: 'Cheque' },
    ],
  },
  {
    type: 'select',
    name: 'payment_frequency',
    label: 'Payment Frequency',
    placeholder: '',
    twocol: true,
    req: true,
    reqmessage: 'Payment frequency required',
    options: [
      { value: 'Daily', label: 'Daily' },
      { value: 'Weekly', label: 'Weekly' },
      { value: 'Biweekly', label: 'Biweekly' },
      { value: 'Monthly', label: 'Monthly' },
      { value: 'Quarterly', label: 'Quarterly' },
      { value: 'Annually', label: 'Annually' },
    ],
  },
  {
    type: 'select',
    name: 'payment_type',
    label: 'Payment Type',
    placeholder: '',
    twocol: true,
    options: [
      { value: 'Recurring', label: 'Recurring' },
      { value: 'Once', label: 'Once' },
    ],
  },
  {
    type: 'date',
    name: 'effective_date',
    label: 'Effective Date',
    placeholder: 'Please Select',
    twocol: true,
  },
  {
    type: 'select',
    name: 'tax_currency_type',
    label: 'Tax Ammount',
    placeholder: '',
    twocol: false,
    colWidth: '0 1 118px',
    options: [{ value: 'RM', label: 'RM' }],
  },
  {
    type: 'input',
    name: 'tax_amount',
    label: '',
    placeholder: '',
    twocol: false,
    colWidth: '1 0 180px',
  },
];

export { salaryInformation };

---
title: "ETW Tracing"
ms.date: "03/30/2017"
ms.assetid: ac99a063-e2d2-40cc-b659-d23c2f783f92
---
# ETW Tracing
This sample demonstrates how to implement End-to-End (E2E) tracing using Event Tracing for Windows (ETW) and the `ETWTraceListener` that is provided with this sample. The sample is based on the [Getting Started](../../../../docs/framework/wcf/samples/getting-started-sample.md) and includes ETW tracing.  
  
> [!NOTE]
> The set-up procedure and build instructions for this sample are located at the end of this topic.  
  
 This sample assumes that you are familiar with [Tracing and Message Logging](../../../../docs/framework/wcf/samples/tracing-and-message-logging.md).  
  
 Each trace source in the <xref:System.Diagnostics> tracing model can have multiple trace listeners that determine where and how the data is traced. The type of listener defines the format in which trace data is logged. The following code sample shows how to add the listener to configuration.  
  
```xml  
<system.diagnostics>  
    <sources>  
        <source name="System.ServiceModel"   
             switchValue="Verbose,ActivityTracing"  
             propagateActivity="true">  
            <listeners>  
                <add type=  
                   "System.Diagnostics.DefaultTraceListener"  
                   name="Default">  
                   <filter type="" />  
                </add>  
                <add name="ETW">  
                    <filter type="" />  
                </add>  
            </listeners>  
        </source>  
    </sources>  
    <sharedListeners>  
        <add type=  
            "Microsoft.ServiceModel.Samples.EtwTraceListener, ETWTraceListener"  
            name="ETW" traceOutputOptions="Timestamp">  
            <filter type="" />  
       </add>  
    </sharedListeners>  
</system.diagnostics>  
```  
  
 Before using this listener, an ETW Trace Session must be started. This session can be started by using Logman.exe or Tracelog.exe. A SetupETW.bat file is included with this sample so that you can set up the ETW Trace Session along with a CleanupETW.bat file for closing the session and completing the log file.  
  
> [!NOTE]
> The setup procedure and build instructions for this sample are located at the end of this topic. For more information about these tools, see <https://go.microsoft.com/fwlink/?LinkId=56580>  
  
 When using the ETWTraceListener, traces are logged in binary .etl files. With ServiceModel tracing turned on, all generated traces appear in the same file. Use [Service Trace Viewer Tool (SvcTraceViewer.exe)](../../../../docs/framework/wcf/service-trace-viewer-tool-svctraceviewer-exe.md) for viewing .etl and .svclog log files. The viewer creates an end-to-end view of the system that makes it possible to trace a message from its source to its destination and point of consumption.  
  
 The ETW Trace Listener supports circular logging. To enable this feature, go to **Start**, **Run** and type `cmd` to start a command console. In the following command, replace the `<logfilename>` parameter with the name of your log file.  
  
```console  
logman create trace Wcf -o <logfilename> -p "{411a0819-c24b-428c-83e2-26b41091702e}" -f bincirc -max 1000  
```  
  
 The `-f` and `-max` switches are optional. They specify the binary circular format and max log size of 1000MB respectively. The `-p` switch is used to specify the trace provider. In our example, `"{411a0819-c24b-428c-83e2-26b41091702e}"` is the GUID for "XML ETW Sample Provider".  
  
 To start the session, type in the following command.  
  
```console  
logman start Wcf  
```  
  
 After you have finished logging, you can stop the session with the following command.  
  
```console  
logman stop Wcf  
```  
  
 This process generates binary circular logs that you can process with your tool of choice, including [Service Trace Viewer Tool (SvcTraceViewer.exe)](../../../../docs/framework/wcf/service-trace-viewer-tool-svctraceviewer-exe.md) or Tracerpt.  
  
 You can also review the [Circular Tracing](../../../../docs/framework/wcf/samples/circular-tracing.md) sample for more information on an alternative listener to perform circular logging.  
  
### To set up, build, and run the sample  
  
1. Be sure you have performed the [One-Time Setup Procedure for the Windows Communication Foundation Samples](../../../../docs/framework/wcf/samples/one-time-setup-procedure-for-the-wcf-samples.md).  
  
2. To build the solution, follow the instructions in [Building the Windows Communication Foundation Samples](../../../../docs/framework/wcf/samples/building-the-samples.md).  
  
    > [!NOTE]
    > To use the RegisterProvider.bat, SetupETW.bat and CleanupETW.bat commands, you must run under a local administrator account. If you are using [!INCLUDE[wv](../../../../includes/wv-md.md)] or later, you must also run the command prompt with elevated privileges. To do so, right-click the command prompt icon, then click **Run as administrator**.  
  
3. Before running the sample, run RegisterProvider.bat on the client and server. This sets up the resulting ETWTracingSampleLog.etl file to generate traces that can be read by the Service Trace Viewer. This file can be found in the C:\logs folder. If this folder does not exist, it must be created or no traces are generated. Then, run SetupETW.bat on the client and server computers to begin the ETW Trace Session. The SetupETW.bat file can be found under the CS\Client folder.  
  
4. To run the sample in a single- or cross-computer configuration, follow the instructions in [Running the Windows Communication Foundation Samples](../../../../docs/framework/wcf/samples/running-the-samples.md).  
  
5. When the sample is completed, run CleanupETW.bat to complete the creation of the ETWTracingSampleLog.etl file.  
  
6. Open the ETWTracingSampleLog.etl file from within the Service Trace Viewer. You will be prompted to save the binary formatted file as a .svclog file.  
  
7. Open the newly created .svclog file from within the Service Trace Viewer to view the ETW and ServiceModel traces.  
  
> [!IMPORTANT]
> The samples may already be installed on your computer. Check for the following (default) directory before continuing.  
>   
> `<InstallDrive>:\WF_WCF_Samples`  
>   
> If this directory does not exist, go to [Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4](https://go.microsoft.com/fwlink/?LinkId=150780) to download all Windows Communication Foundation (WCF) and [!INCLUDE[wf1](../../../../includes/wf1-md.md)] samples. This sample is located in the following directory.  
>   
> `<InstallDrive>:\WF_WCF_Samples\WCF\Basic\Management\AnalyticTrace`  
  
## See also

- [AppFabric Monitoring Samples](https://go.microsoft.com/fwlink/?LinkId=193959)

﻿// <Snippet1>
using System;
using System.Reflection;

class Class1
{
    public static void Main()
    {
        // You must supply a valid fully qualified assembly name.
        Assembly SampleAssembly = Assembly.Load
		    ("SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3");
        // Display all the types contained in the specified assembly.
		foreach (Type oType in SampleAssembly.GetTypes()) {
            Console.WriteLine(oType.Name);
        }
    }
}
// </Snippet1>
""" PostProcessorBase.py

Base class for the post processor classes """

# Imports
import xlsxwriter

class PostProcessorBase:
    def __init__(self, inputFileName, outputFileName, logDate):
        """Constructor"""
        # Initialize variables
        self.inputFile = open(inputFileName, "r")
        self.outputFile = xlsxwriter.Workbook(outputFileName)
        self.logDate = logDate
    
    def DetermineChartRows(self, hourOffsets, startHour, endHour):
        """Determine the chart rows that correspond to the hour span"""
        startRow = -1
        endRow = -1
        for hour in range(startHour, endHour):
            if hourOffsets[hour] != -1:
                if hour < (endHour - 1):
                    if startRow == -1:
                        startRow = hourOffsets[hour]
                    endRow = hourOffsets[hour]
                else:
                    endRow = hourOffsets[hour] - 1
        return (startRow, endRow)
    
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AjaxCallController extends BaseController
{
    public function TextBox(Request $request){
        $number = $request->number;

        $html = "<table>";
        for($i = 1; $i <= $number; $i++) {
            $html .= '<tr style="padding:5px;"><td><input type="text" id="'.($i+$i).'" placeholder="Enter left value"> &nbsp;&nbsp;<input type="text" id="'.($i+$i+$i).'" placeholder="Enter right value"> &nbsp;&nbsp;<button class="btn btn-success" onclick="function_'.$i.'($(this))">Submit</button></td>&nbsp;&nbsp;&nbsp;&nbsp;<td><span style="
    padding: 37px;font-weight:bold;font-size:25px;
" id="'.($i+$i+$i+$i+$i).'"></span></td></tr>';  
        }
        $html .= "</table><script>";

        for($j = 1; $j <= $number; $j++) {
            $tot = ($j+$j+$j);
            $tot1 = ($j+$j);
            $tot2 = ($j+$j+$j+$j+$j);
            // $attr = "input[]";
            $html .= "function function_$j(This){ 
                var lowerNumber = $('#$tot1').val(); 
                var higherNumber = $('#$tot').val(); 
                var primenumber = [];
                var pushprin = [];
                for (let i = lowerNumber; i <= higherNumber; i++) {
                    let flag = 0;
                    for (let j = 2; j < i; j++) {
                        if (i % j == 0) {
                            flag = 1;
                            break;
                        }
                    }
                    if (i > 1 && flag == 0) {
                        primenumber.push(i);
                    }
                }

                var number1 = 0; 
                var number2 = 0; 
                $.each(primenumber, function(index, value){
                    if(index == 0){
                        number1 = value;
                    }
                    number2 = value;

                });
                var num3 = number2 - number1;
                $('#$tot2').html(num3);
            }";
        }
        $html .= "</script>";
        return response()->json($html,200);

    }
}

% simpleConeReflectanceModel  Compute reflectance versus time for a swelling cone
%
% Description:
%   Very simple calculation of how light reflected from a cone varies with
%   cone length, taking into account both incoherent reflection and
%   interference between coherent component of light.
%
%   Based on a very simple model where there are two reflecting surfaces.  Light
%   reflects from each surface and interferes at the source side of the first surface.
%
%   The fraction of coherent (interfering) versus incoherent light is simply specified,
%   not computed.  Adding this computation would be a good extension.
%
%   The model has a number of parameters that have physical analogs. These
%   are set and commented in the code below.
%
% Notes:
% * [NOTE: DHB - I tried to understand coherence length from the web. In some places it
%   is defined a length at which phase is totally random.  In others, a
%   more graded definition is used.  We need to understand which the one we
%   calculate represents, if we are to add coherence length into this
%   cacluation.]
%

% History:
%   10/28/17  dhb  Wrote it.

%% Clear
clear; close all;

%% Parameters
%
% Imaging light wavelength
firstLightWavelengthNm = 720;
secondLightWavelengthNm = 1.25*firstLightWavelengthNm; % 850;
refractiveIndex1 = 1.331;
refractiveIndex2 = 1.328;

% Number of cones to simulate
nCones = 400;

% Length between reflecting surfaces
reflectingSurfaceDifferenceNm1 = 10*1e3;
reflectingSurfaceDifferenceNm2 = 7*1e3;

% How much variation in the starting length between surfces is there
% across cones (or trials within measurements for one cone), experessed as a
% fraction of the length between the two reflecting surfaces.
reflectingSurfaceRandomizationFraction = 0.1;

% Maximum length change between reflecting surfaces,
% in response to stimulus.
maxDeltaLengthNm = 150;

% What fraction of a full half sinusoid does length vary over
% in response to a stimulus, and how much trial-to-trial jitter
% is there in that fraction.
%
% Set the fraction to 1 if you think what happens is that the cone
% swells and then contracts to about its original length.  Set the
% fraction to 0.5 if you think it swells and then sits at the swollen
% length over the relevant time frame of the experiment.
%
% The randomization is also expressed as a fraction of the full half
% sinusoid
halfSinusoidFraction = 0.8;
halfSinusoidFractionRandomizationFraction = 0.5;

% Time in seconds for stimulus to have its effect. This just puts
% a time axis on the plots.
stimEffectTimeSecs = 4;

% Number sampling timepoints for simulation of what happens on a trial
nDeltaLengths = 100;
theDeltaTimesSecs = linspace(0,stimEffectTimeSecs,nDeltaLengths);

% Fraction of light reflected from the first and second surfaces.  Model below
% assumes that light not reflected from first surface is transmitted, and
% that light reflected from the second surface passes through the first
% surface both on the way in and on the way out.
firstSurfaceReflectance = 0.2;
secondSurfaceReflectance = 0.4;
thirdSurfaceReflectance = 0.4;

% Coherent fraction
%
% This depends on coherence length relative relative to distance between
% reflecting surfaces Here just making it up, because I don't really
% understand coherence length.
coherentFraction = 0.5;

%% Get intensities of light coming back from each surface
%
% This is calculated at the source side of the first surface; the light
% from the second surface goes through the first surface twice.
firstSurfaceIntensity = firstSurfaceReflectance;
secondSurfaceIntensity = (1-firstSurfaceReflectance)^2*secondSurfaceReflectance;

%% Different starting lengths, drawn at random from a uniform distribution
%
% Distribution is centered on the assumed length
randValues = rand(1,nCones);
theStartingDeltas = reflectingSurfaceRandomizationFraction*reflectingSurfaceDifferenceNm1*(randValues-0.5);

%% Set first phase to 0 without loss of generality
phase0 = 0;

%% Loop over cones/trials
for jj = 1:nCones
    % For each, we choose a random starting length and compute the
    % interferece effect. We also choose a random excursion, jittered
    % around a half sinusoid
    %
    % Get delta lengths as a function of time.
    theDeltaLengthsNm{jj} = maxDeltaLengthNm*sin(halfSinusoidFraction*(1+halfSinusoidFractionRandomizationFraction*(rand(1,1)-0.5))*pi*(0:nDeltaLengths-1)/nDeltaLengths);
    for ii = 1:nDeltaLengths
        
        % Get starting distance between surfaces for this cone, and compute phase of
        % second light at the point of interference.
        distanceNm1(jj,ii) = reflectingSurfaceDifferenceNm1 + theStartingDeltas(jj) + theDeltaLengthsNm{jj}(ii);
        distanceNm2(jj,ii) = reflectingSurfaceDifferenceNm2 + theStartingDeltas(jj) + theDeltaLengthsNm{jj}(ii);

        phaseWl1Sur1(jj,ii) = 2*pi*(2*distanceNm1(jj,ii))*refractiveIndex1/firstLightWavelengthNm;
        phaseWl2Sur1(jj,ii) = 2*pi*(2*distanceNm1(jj,ii))*refractiveIndex2/secondLightWavelengthNm;
        
        phaseWl1Sur2(jj,ii) = 2*pi*(2*distanceNm2(jj,ii))*refractiveIndex1/firstLightWavelengthNm;
        phaseWl2Sur2(jj,ii) = 2*pi*(2*distanceNm2(jj,ii))*refractiveIndex2/secondLightWavelengthNm;
        
        % Get amplitude of coherent component of reflected light, taking interference
        % into account.
        %
        % Formula from Hecht, Optics, 3rd ed, p. 291
        coherentAmplitude1(jj,ii) = sqrt(...
            firstSurfaceIntensity^2 + secondSurfaceIntensity^2 + ...
            2*firstSurfaceIntensity*secondSurfaceIntensity*cos(phase0-phaseWl1Sur1(jj,ii)));
        coherentAmplitude2(jj,ii) = sqrt(...
            firstSurfaceIntensity^2 + secondSurfaceIntensity^2 + ...
            2*firstSurfaceIntensity*secondSurfaceIntensity*cos(phase0-phaseWl2Sur1(jj,ii)));
        
        % Put together coherent and incoherent reflected light to get
        % intensity of total reflected light.  This is a model of what
        % we measure.
        totalAmplitude1(jj,ii) = coherentFraction*coherentAmplitude1(jj,ii) + (1-coherentFraction)*(firstSurfaceIntensity + secondSurfaceIntensity);
        totalAmplitude2(jj,ii) = coherentFraction*coherentAmplitude2(jj,ii) + (1-coherentFraction)*(firstSurfaceIntensity + secondSurfaceIntensity);
        
        
    end
    
    % Get initial slope of responses at both wavelengths
    nTimes = 50;
    initialSlope1(jj) = (totalAmplitude1(jj,nTimes+1)-totalAmplitude1(jj,1))/(theDeltaTimesSecs(nTimes+1)-theDeltaTimesSecs(1));
    initialSlope2(jj) = (totalAmplitude2(jj,nTimes+1)-totalAmplitude2(jj,1))/(theDeltaTimesSecs(nTimes+1)-theDeltaTimesSecs(1));
    
end

%% Make a plot of responses
nConesToPlot = 9;
theColors = ['r' 'g' 'b' 'k' 'y' 'c'];
nColors = length(theColors);
responseFig1 = figure; clf; hold on
responseFig2 = figure; clf; hold on
correlationFig = figure; clf; hold on
whichColor = 1;
for jj = 1:nConesToPlot
    figure(responseFig1);
    plot(theDeltaTimesSecs,totalAmplitude1(jj,:),theColors(whichColor),'LineWidth',3);
    
    figure(responseFig2);
    plot(theDeltaTimesSecs,totalAmplitude2(jj,:),theColors(whichColor),'LineWidth',3);

    figure(correlationFig);
    plot(totalAmplitude1(jj,:),totalAmplitude2(jj,:),'o','Color',theColors(whichColor),'MarkerFaceColor',theColors(whichColor), ...
        'MarkerSize',8);
    
    whichColor = whichColor + 1;
    if (whichColor > nColors)
        whichColor = 1;
    end
end
figure(responseFig1);
set(gca,'YTick',[0.2 0.3 0.4 0.5]);
set(gca,'FontName','Helvetica','FontSize', 16);
xlabel('Time','FontName','Helvetica','FontSize',18);
ylabel('Reflectance','FontName','Helvetica','FontSize',18);
xlim([0 2]);
ylim([0.2 0.5]);
set(gca,'XTickLabel',''); set(gca,'YTickLabel','');
FigureSave('ExampleResponses',responseFig1,'tif');
figure(responseFig2);
xlabel('Time (secs)');
ylabel('Reflectance');
ylim([0.2 0.6]);
figure(correlationFig);
set(gca,'FontName','Helvetica','FontSize', 16);
xlabel(sprintf('Standardized Reflectance %d nm',firstLightWavelengthNm),'FontName','Helvetica','FontSize',18);
ylabel(sprintf('Standardized Reflectance %d nm',secondLightWavelengthNm),'FontName','Helvetica','FontSize',18);
axis('square');
xlim([0.2 0.5]);
set(gca,'XTick',[0.2 0.3 0.4 0.5]);
set(gca,'YTick',[0.2 0.3 0.4 0.5]);
ylim([0.2 0.5]);
FigureSave('TwoWavelengthCompare',correlationFig,'tif');

%% Make a plot of initial slopes at two wavelengths
slopeFig = figure; clf;
plot(initialSlope1,initialSlope2,'ro','MarkerFaceColor','r','MarkerSize',14);
xlabel(sprintf('Initial response slope (%d nm)',firstLightWavelengthNm));
ylabel(sprintf('Initial response slope (%d nm)',secondLightWavelengthNm));
xlim([-0.3 0.3]); ylim([-0.3 0.3]); axis('square');

%% Make a plot of reflectance versus reflectance
slopeFig1 = figure; clf; hold on;
plot(totalAmplitude1(:,1),initialSlope1,'ro','MarkerFaceColor','r','MarkerSize',8);
plot(totalAmplitude2(:,1),initialSlope2,'bo','MarkerFaceColor','b','MarkerSize',8);
xlabel(sprintf('Initial reflectance amplitude',firstLightWavelengthNm));
ylabel(sprintf('Initial response slope',secondLightWavelengthNm));
xlim([0.2 0.6]); ylim([-0.3 0.3]); 
legend({sprintf('%d nm',round(firstLightWavelengthNm)),sprintf('%d nm',round(secondLightWavelengthNm))},'Location','NorthEast')


<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title ></title>
      <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
      <script src="https://cdn.jsdelivr.net/npm/gijgo@1.9.9/js/gijgo.min.js" type="text/javascript"></script>
      <link href="https://cdn.jsdelivr.net/npm/gijgo@1.9.9/css/gijgo.min.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
 <br><br>
<form class="" action="index.html" method="post">
  <div class="container">
      <div class="row justify-content-md-center">
          <h3>ประวัติ</h3><br><br>
      </div>
      <div class="form-group">
        <label for="inputAddress">ชื่อ-นามสกุล :</label>
        <input type="text" class="form-control" required placeholder="ชื่อ-นามสกุล">
      </div>
      <div class="form-row">
        <div class="form-group col-md-5">
          <label for="inputState">เพศ :</label>
          <select id="inputState" class="form-control">
            <option selected>เพศ</option>
            <option>ชาย</option>
            <option>หญิง</option>
          </select>
        </div>
        <div class="form-group col-md-7">
          <label for="inputState">สถานะภาพ :</label>
          <select id="inputState" class="form-control">
            <option selected>สถานะภาพ</option>
            <option>โสด</option>
            <option>สมรส</option>
            <option>หย่า</option>
            <option>หม้าย</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label for="inputAddress">ศาสนา :</label>
        <input type="text" class="form-control" required placeholder="ศาสนา">
      </div>
      <div class="form-group">
        <label for="inputAddress">วัน/เดือน/ปี เกิด :</label>
        <input id="datepicker" width="276">
      </div>
      <div class="form-group">
        <label for="inputAddress">ที่อยู่ :</label>
        <textarea name="address" class="form-control" required rows="4" cols="80"></textarea>
      </div>
      <div class="form-group">
        <label for="inputAddress">เบอร์โทร :</label>
        <input type="number" class="form-control" required  placeholder="เบอร์โทร">
      </div>
      <div class="form-group">
        <label for="inputAddress">จบจาก :</label>
        <input type="text" class="form-control" required placeholder="จบจาก">
      </div>
      <div class="form-group">
        <label for="inputAddress">สาขาวิชาชีพ :</label>
        <input type="text" class="form-control" required placeholder="สาขาวิชาชีพ">
      </div>
      <div class="row justify-content-md-center">
        <button type="submit" class="btn btn-primary">บันทึก</button>
      </div>
  </div>{{-- end container --}}
</form>
<br><br><br><br><br><br>


<script>
        $('#datepicker').datepicker({
            uiLibrary: 'bootstrap4'
        });
    </script>
  </body>
</html>

<?php
	require_once("connect.inc");

	/*** test mysqli_connect 127.0.0.1 ***/
	$mysql = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket);

	$mysql->select_db($db);
	$mysql->query("DROP TABLE IF EXISTS test_048_table_1");

	$mysql->query("CREATE TABLE test_048_table_1(col1 tinyint, col2 smallint,
		col3 int, col4 bigint,
		col5 float, col6 double,
		col7 date, col8 time,
		col9 varbinary(10),
		col10 varchar(50),
		col11 char(20)) ENGINE=" . $engine);

	$mysql->query("INSERT INTO test_048_table_1(col1,col10, col11) VALUES(1,'foo1', 1000),(2,'foo2', 88),(3,'foo3', 389789)");

	$stmt = $mysql->prepare("SELECT col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11 from test_048_table_1");
	$stmt->bind_result($c1, $c2, $c3, $c4, $c5, $c6, $c7, $c8, $c9, $c10, $c11);
	$stmt->execute();

	$stmt->fetch();

	$test = array($c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$c10,$c11);

	var_dump($test);

	$stmt->close();
	$mysql->query("DROP TABLE IF EXISTS test_048_table_1");
	$mysql->close();
	print "done!";
?>
<?php error_reporting(0); ?>
<?php
require_once("connect.inc");
if (!$link = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket))
   printf("[c001] [%d] %s\n", mysqli_connect_errno(), mysqli_connect_error());

if (!mysqli_query($link, "DROP TABLE IF EXISTS test_048_table_1"))
	printf("[c002] Cannot drop table, [%d] %s\n", mysqli_errno($link), mysqli_error($link));

mysqli_close($link);
?>
module.exports = async d =>{
let code = d.command.code 
let inside = d.unpack()
let err = d.inside(inside) 
if(err) return d.error(err) 
let [query,type = "equal", separator = ","] = inside.splits 

if(!["equal","starts","ends","includes"].includes(type)) return d.error(`Invalid Typr Provided in $filterTextSplitElement${inside}`) 

let res;
    switch (type){
      case "equal" :
            res = d.array.filter(x=>x === query)
            break;
            case "starts":
            res = d.array.filter(x=>x.startsWith(query))
            break;
            case "ends" :
            res = d.array.filter(x=>x.endsWith(query)) 
            break;
            case "includes":
            res = d.array.filter(x=>x.includes(query))
            break;
            
            }
   return {
       code: code.replaceLast(`$filterTextSplitElement${inside}`,res.join(separator))
       }
}

from __future__ import print_function
import re
import sys
import ctypes

VALUE_t =  gdb.lookup_type('VALUE')
control_frame_t = gdb.lookup_type('rb_control_frame_t')
RString_t = gdb.lookup_type('struct RString')
RArray_t = gdb.lookup_type('struct RArray')
RBasic_t = gdb.lookup_type('struct RBasic')
RHash_t = gdb.lookup_type('struct RHash')
RObject_t = gdb.lookup_type('struct RObject')
RClass_t = gdb.lookup_type('struct RClass')
global_entry_t = gdb.lookup_type('struct rb_global_entry')
rb_thread_struct_t = gdb.lookup_type('struct rb_thread_struct')

try:
    ID_ENTRY_STR = gdb.parse_and_eval('ID_ENTRY_STR')
    ID_ENTRY_SYM = gdb.parse_and_eval('ID_ENTRY_SYM')
    ID_ENTRY_SIZE = gdb.parse_and_eval('ID_ENTRY_SIZE')
    ID_ENTRY_UNIT = gdb.parse_and_eval('ID_ENTRY_UNIT')
except:
    ID_ENTRY_STR = 0
    ID_ENTRY_SYM = 1
    ID_ENTRY_SIZE = 2
    ID_ENTRY_UNIT =512

try:
    RUBY_FL_USHIFT = gdb.parse_and_eval('RUBY_FL_USHIFT')
    RUBY_FL_USER0  = gdb.parse_and_eval('RUBY_FL_USER0')
    RUBY_FL_USER1  = gdb.parse_and_eval('RUBY_FL_USER1')
    RUBY_FL_USER2  = gdb.parse_and_eval('RUBY_FL_USER2')
    RUBY_FL_USER3  = gdb.parse_and_eval('RUBY_FL_USER3')
    RUBY_FL_USER4  = gdb.parse_and_eval('RUBY_FL_USER4')
    RUBY_FL_USER5  = gdb.parse_and_eval('RUBY_FL_USER5')
    RUBY_FL_USER6  = gdb.parse_and_eval('RUBY_FL_USER6')
    RUBY_FL_USER7  = gdb.parse_and_eval('RUBY_FL_USER7')
    RUBY_FL_USER8  = gdb.parse_and_eval('RUBY_FL_USER8')
    RUBY_FL_USER9  = gdb.parse_and_eval('RUBY_FL_USER9')
    RUBY_FL_USER10 = gdb.parse_and_eval('RUBY_FL_USER10')
    RUBY_FL_USER11 = gdb.parse_and_eval('RUBY_FL_USER11')
    RUBY_FL_USER12 = gdb.parse_and_eval('RUBY_FL_USER12')
    RUBY_FL_USER13 = gdb.parse_and_eval('RUBY_FL_USER13')
    RUBY_FL_USER14 = gdb.parse_and_eval('RUBY_FL_USER14')
    RUBY_FL_USER15 = gdb.parse_and_eval('RUBY_FL_USER15')
    RUBY_FL_USER16 = gdb.parse_and_eval('RUBY_FL_USER16')
    RUBY_FL_USER17 = gdb.parse_and_eval('RUBY_FL_USER17')
    RUBY_FL_USER18 = gdb.parse_and_eval('RUBY_FL_USER18')
    RUBY_FL_USER19 = gdb.parse_and_eval('RUBY_FL_USER19')
    RUBY_FL_SINGLETON = gdb.parse_and_eval('RUBY_FL_SINGLETON')
except:
    RUBY_FL_USHIFT = 12
    RUBY_FL_USER0 = (1<<RUBY_FL_USHIFT+0)
    RUBY_FL_USER1 = (1<<RUBY_FL_USHIFT+1)
    RUBY_FL_USER2 = (1<<RUBY_FL_USHIFT+2)
    RUBY_FL_USER3 = (1<<RUBY_FL_USHIFT+3)
    RUBY_FL_USER4 = (1<<RUBY_FL_USHIFT+4)
    RUBY_FL_USER5 = (1<<RUBY_FL_USHIFT+5)
    RUBY_FL_USER6 = (1<<RUBY_FL_USHIFT+6)
    RUBY_FL_USER7 = (1<<RUBY_FL_USHIFT+7)
    RUBY_FL_USER8 = (1<<RUBY_FL_USHIFT+8)
    RUBY_FL_USER9 = (1<<RUBY_FL_USHIFT+9)
    RUBY_FL_USER10 = (1<<RUBY_FL_USHIFT+10)
    RUBY_FL_USER11 = (1<<RUBY_FL_USHIFT+11)
    RUBY_FL_USER12 = (1<<RUBY_FL_USHIFT+12)
    RUBY_FL_USER13 = (1<<RUBY_FL_USHIFT+13)
    RUBY_FL_USER14 = (1<<RUBY_FL_USHIFT+14)
    RUBY_FL_USER15 = (1<<RUBY_FL_USHIFT+15)
    RUBY_FL_USER16 = (1<<RUBY_FL_USHIFT+16)
    RUBY_FL_USER17 = (1<<RUBY_FL_USHIFT+17)
    RUBY_FL_USER18 = (1<<RUBY_FL_USHIFT+18)
    RUBY_FL_USER19 = (1<<RUBY_FL_USHIFT+19)
    RUBY_FL_SINGLETON = RUBY_FL_USER0

RARRAY_EMBED_FLAG = RUBY_FL_USER1
RARRAY_EMBED_LEN_SHIFT = RUBY_FL_USHIFT+3
RARRAY_EMBED_LEN_MASK = (RUBY_FL_USER4|RUBY_FL_USER3)

tLAST_OP_ID = gdb.parse_and_eval('tLAST_OP_ID')

try:
    ID_SCOPE_SHIFT = gdb.parse_and_eval('RUBY_ID_SCOPE_SHIFT')
except:
    ID_SCOPE_SHIFT = 4

RUBY_Qfalse = gdb.parse_and_eval('RUBY_Qfalse')
RUBY_Qtrue = gdb.parse_and_eval('RUBY_Qtrue')
RUBY_Qnil = gdb.parse_and_eval('RUBY_Qnil')
RUBY_Qundef = gdb.parse_and_eval('RUBY_Qundef')

RUBY_FIXNUM_FLAG = gdb.parse_and_eval('RUBY_FIXNUM_FLAG')
RUBY_SYMBOL_FLAG = gdb.parse_and_eval('RUBY_SYMBOL_FLAG')

RUBY_FLONUM_MASK = gdb.parse_and_eval('RUBY_FLONUM_MASK')
RUBY_FLONUM_FLAG = gdb.parse_and_eval('RUBY_FLONUM_FLAG')

RUBY_SPECIAL_SHIFT = gdb.parse_and_eval('RUBY_SPECIAL_SHIFT')
RUBY_IMMEDIATE_MASK = gdb.parse_and_eval('RUBY_IMMEDIATE_MASK')
RUBY_T_MASK = gdb.parse_and_eval('RUBY_T_MASK')
RUBY_T_NONE = gdb.parse_and_eval('RUBY_T_NONE')
RUBY_T_NIL = gdb.parse_and_eval('RUBY_T_NIL')
RUBY_T_OBJECT = gdb.parse_and_eval('RUBY_T_OBJECT')
RUBY_T_CLASS = gdb.parse_and_eval('RUBY_T_CLASS')
RUBY_T_ICLASS = gdb.parse_and_eval('RUBY_T_ICLASS')
RUBY_T_MODULE = gdb.parse_and_eval('RUBY_T_MODULE')
RUBY_T_FLOAT = gdb.parse_and_eval('RUBY_T_FLOAT')
RUBY_T_STRING = gdb.parse_and_eval('RUBY_T_STRING')
RUBY_T_REGEXP = gdb.parse_and_eval('RUBY_T_REGEXP')
RUBY_T_FIXNUM = gdb.parse_and_eval('RUBY_T_FIXNUM')
RUBY_T_ARRAY = gdb.parse_and_eval('RUBY_T_ARRAY')
RUBY_T_HASH = gdb.parse_and_eval('RUBY_T_HASH')
RUBY_T_STRUCT = gdb.parse_and_eval('RUBY_T_STRUCT')
RUBY_T_BIGNUM = gdb.parse_and_eval('RUBY_T_BIGNUM')
RUBY_T_RATIONAL = gdb.parse_and_eval('RUBY_T_RATIONAL')
RUBY_T_COMPLEX = gdb.parse_and_eval('RUBY_T_COMPLEX')
RUBY_T_FILE = gdb.parse_and_eval('RUBY_T_FILE')
RUBY_T_TRUE = gdb.parse_and_eval('RUBY_T_TRUE')
RUBY_T_FALSE = gdb.parse_and_eval('RUBY_T_FALSE')
RUBY_T_DATA = gdb.parse_and_eval('RUBY_T_MATCH')
RUBY_T_SYMBOL = gdb.parse_and_eval('RUBY_T_SYMBOL')
RUBY_T_UNDEF = gdb.parse_and_eval('RUBY_T_UNDEF')
RUBY_T_NODE = gdb.parse_and_eval('RUBY_T_NODE')
RUBY_T_ZOMBIE = gdb.parse_and_eval('RUBY_T_ZOMBIE')
RUBY_T_NIL = gdb.parse_and_eval('RUBY_T_NIL')

def _rb_id2str(id):
    str = _lookup_id_str(id)
    return str

def _lookup_id_str(id):
    return _get_id_entry(_id_to_serial(id), ID_ENTRY_STR);

def _id_to_serial(id):
    if _is_notop_id(id):
        return id >> ID_SCOPE_SHIFT
    else:
        return id

def _is_notop_id(id):
    return id > tLAST_OP_ID

def _get_id_entry(num, id_entry_type):
    global_symbols = gdb.parse_and_eval('global_symbols')
    if (num != 0 and num <= global_symbols['last_id']):
        idx = num / ID_ENTRY_UNIT
        ids = global_symbols['ids']
        ary = _rb_ary_entry(ids, idx)
        if (idx < _RARRAY_LEN(ids) and (ary != RUBY_Qnil)):
            ary = _rb_ary_entry(ary, (num % ID_ENTRY_UNIT) * ID_ENTRY_SIZE + id_entry_type)
            if (ary != RUBY_Qnil):
                return ary

    return None

def _RARRAY_LEN(ary):
    a = ary.cast(RArray_t.pointer())
    if a['basic']['flags'] & RARRAY_EMBED_FLAG:
        return (a['basic']['flags'] >> RARRAY_EMBED_LEN_SHIFT) & (RARRAY_EMBED_LEN_MASK >> RARRAY_EMBED_LEN_SHIFT)
    else:
        return a['as']['heap']['len']

def _rb_ary_entry(ary, offset):
    if (offset < 0):
        offset += _RARRAY_LEN(ary)

    return _rb_ary_elt(ary, offset)


def _rb_ary_elt(ary, offset):
    len = _RARRAY_LEN(ary)
    if len == 0:
        return None
    if offset < 0 or len <= offset:
        return None

    return _RARRAY_AREF(ary, offset);

def _RARRAY_AREF(a, i):
    return _RARRAY_CONST_PTR(a)[i]

def _RARRAY_CONST_PTR(ary):
    a = ary.cast(RArray_t.pointer())
    if a['basic']['flags'] & RARRAY_EMBED_FLAG:
        return a['as']['ary']
    else:
        return a['as']['heap']['ptr']

def print_ruby_id(v):
    l = _rb_id2str(v)
    if l is not None:
        sys.stdout.write(get_rstring(l))

def print_ruby_class(v):
    print("Class value print not yet supported")

def print_ruby_array(v):
    len = _RARRAY_LEN(v)
    for i in range(0, int(len)):
        print_ruby_value(_rb_ary_entry(v, i))
        sys.stdout.write(" ")

def PACKED_BINS(table):
    return table['as']['packed']['entries']

def PACKED_ENT(table, i):
    return PACKED_BINS(table)[i]

def PKEY(table, i):
    return PACKED_ENT(table, (i))['key']

def PVAL(table, i):
    return PACKED_ENT(table, (i))['val']

def PHASH(table, i):
    return PACKED_ENT(table, (i))['hash']

# Walk through the ruby hashtable and callback the lambda for each key,value
# pair
def st_foreach(table, callback, *args):
    if table == 0:
        return

    if table['entries_packed']:
        for i in range(0, int(table['as']['packed']['real_entries'])):
            key = PKEY(table, i)
            val = PVAL(table, i)
            callback(key, val, *args)
    else:
        ptr = table['as']['big']['head']

        while ptr != 0 and table['as']['big']['head'] != 0:
            key = ptr['key']
            val = ptr['record']
            callback(key, val, *args)
            ptr = ptr['fore']

    return

def print_ruby_hash(v):
    h = v.cast(RHash_t.pointer())
    sys.stdout.write("{ ")
    if h['ntbl']:
        f = lambda key,val: [print_ruby_value(key), sys.stdout.write(" => "), print_ruby_value(val), sys.stdout.write(", ")]
        st_foreach(h['ntbl'], f)
    sys.stdout.write("}")

ROBJECT_EMBED_LEN_MAX = 3

def ROBJECT_NUMIV(o):
    if (o['basic']['flags'] & RUBY_FL_USER1):
        return ROBJECT_EMBED_LEN_MAX
    else:
        return o['as']['heap']['numiv']

def ROBJECT_IVPTR(o):
    if (o['basic']['flags'] & RUBY_FL_USER1):
        return o['as']['ary']
    else:
        return o['as']['heap']['ivptr']

def ROBJECT_IV_INDEX_TBL(o):
    if (o['basic']['flags'] & RUBY_FL_USER1):
        return RCLASS_IV_INDEX_TBL(rb_obj_class(o))
    else:
        return o['as']['heap']['iv_index_tbl']

def RCLASS_IV_INDEX_TBL(c):
    return (RCLASS_EXT(c)['iv_index_tbl'])

def RCLASS_EXT(c):
    return c['ptr']

def RCLASS_IV_TBL(c):
    return RCLASS_EXT(c)['iv_tbl']

def RCLASS_CONST_TBL(c):
    return RCLASS_EXT(c)['const_tbl']

def rb_obj_class(o):
    return rb_class_real(CLASS_OF(o))

def CLASS_OF(v):
    return rb_class_of(v)

def IMMEDIATE_P(x):
    return (x & RUBY_IMMEDIATE_MASK)

def rb_class_of(obj):
    return obj['basic']['klass']
#    if (IMMEDIATE_P(obj)):
#       if (FIXNUM_P(obj)) return rb_cFixnum;
#       if (FLONUM_P(obj)) return rb_cFloat;
#       if (obj == Qtrue)  return rb_cTrueClass;
#       if (STATIC_SYM_P(obj)) return rb_cSymbol;
#     }
#     else if (!RTEST(obj)) {
#       if (obj == Qnil)   return rb_cNilClass;
#       if (obj == Qfalse) return rb_cFalseClass;
#     }
#     return RBASIC(obj)->klass;
# }

def rb_class_real(cl):
    cl = cl.cast(RClass_t.pointer())
    while ((cl != 0) and
           ((cl['basic']['flags'] & RUBY_FL_SINGLETON) or (cl['basic']['flags'] & RUBY_T_MASK) == RUBY_T_ICLASS)):
        cl = cl['super']

    return cl

# Print a ruby object's variables
def print_ruby_object(v):
    obj = v.cast(RObject_t.pointer())
    len = ROBJECT_NUMIV(obj)
    ptr = ROBJECT_IVPTR(obj)
    num = 0;

    # Print instance variables.
    #
    # The instance variable values are stored inside the RObject itself but
    # the names are in class's rb_classext_struct.iv_index_tbl variable. So
    # we will iterate that hash table and print key from it and value from
    # this object's variable
    sys.stdout.write("{{ ")
    f = lambda key,val: [ print_ruby_id(key), sys.stdout.write(" => "),
                          print_ruby_value(ptr[val]), sys.stdout.write(", ")]
    st_foreach(ROBJECT_IV_INDEX_TBL(obj), f)

    # Print class variable (@@myvar).
    f = lambda key,val: [ print_ruby_id(key), sys.stdout.write(" => "),
                          print_ruby_value(val), sys.stdout.write(", ")]
    st_foreach(RCLASS_IV_TBL(rb_obj_class(obj)), f)

    # Print the constants in this object
    st_foreach(RCLASS_CONST_TBL(rb_obj_class(obj)), f)
    sys.stdout.write("}}")

class FLONUM(ctypes.Union):
    _fields_ = [("d", ctypes.c_double),
                ("v", ctypes.c_ulong)]

def print_ruby_value(v):
    if ((v & ~((~0)<<RUBY_SPECIAL_SHIFT)) == RUBY_SYMBOL_FLAG):
        print_ruby_id(v >> RUBY_SPECIAL_SHIFT)
        return

    if v & RUBY_FIXNUM_FLAG:
        sys.stdout.write("%ld" % (v >> 1))
        flags = v.cast(RBasic_t.pointer())['flags']
        return

    if v == RUBY_Qfalse:
        sys.stdout.write("false")
        return

    if v == RUBY_Qtrue:
        sys.stdout.write("true")
        return

    if v == RUBY_Qnil:
        sys.stdout.write("nil")
        return

    if v == RUBY_Qundef:
        sys.stdout.write("undef")
        return

    if (v & RUBY_IMMEDIATE_MASK):
        if (v & RUBY_FLONUM_MASK == RUBY_FLONUM_FLAG):
            if (v != 0x8000000000000002):
                b63 = (v >> 63)
                nv = (2 - b63) | (v & ~0x03)
                nv = ((nv >> 3) | (nv << (8 * 8) - 3))
                f = FLONUM(v=nv)
                sys.stdout.write("%s" % f.d)
        else:
            sys.stdout.write("immediate")
        return

    flags = v.cast(RBasic_t.pointer())['flags']

    if flags & RUBY_T_MASK == RUBY_T_NONE:
        sys.stdout.write("T_NONE : (struct RBasic *)%s" % v)
        return

    if flags & RUBY_T_MASK == RUBY_T_NIL:
        sys.stdout.write("T_NIL : (struct RBasic *)%s" % v)
        return

    if flags & RUBY_T_MASK == RUBY_T_OBJECT:
        #sys.stdout.write("T_OBJECT : (struct RObject *)%s TODO" % v)
        print_ruby_object(v)
        return

    if flags & RUBY_T_MASK == RUBY_T_CLASS:
        s = "*" if (flags & RUBY_FL_SINGLETON) else ""
        sys.stdout.write("T_CLASS %s : (struct RObject *)%s  TODO" % (s, v))
        return

    if flags & RUBY_T_MASK == RUBY_T_ICLASS:
        sys.stdout.write("T_ICLASS : TODO ")
        print_ruby_class(v)
        return

    if flags & RUBY_T_MASK == RUBY_T_MODULE:
        sys.stdout.write("T_MODULE : TODO")
        print_ruby_class(v)
        return

    if flags & RUBY_T_MASK == RUBY_T_FLOAT:
        v.cast(RFloat_t.pointer())['float_value']
        sys.stdout.write("T_FLOAT : %f (struct RFloat *)%s" % (v))
        return

    if flags & RUBY_T_MASK == RUBY_T_STRING:
        sys.stdout.write("\"" + get_rstring(v) + "\"")
        return

    if flags & RUBY_T_MASK == RUBY_T_REGEXP:
        sys.stdout.write("T_REGEX : (struct RRegex *)%s  TODO" % v)
        return

    if flags & RUBY_T_MASK == RUBY_T_ARRAY:
        print_ruby_array(v)
        return

    if flags & RUBY_T_MASK == RUBY_T_HASH:
        print_ruby_hash(v)
        return

    sys.stdout.write("unknown (struct RBasic *)%s" % v)
    # gdb.execute("rp %s" % v)

def try_print_variable(key, val):
    # TODO: fix it
    try:
        global_entry = val.cast(global_entry_t.pointer())
        v = (global_entry['var']['data']).cast(VALUE_t)
        print_ruby_id(key)
        sys.stdout.write(" = ")
        print_ruby_value(v)
    except:
        return
    finally:
        sys.stdout.write("\n")

def print_global_variables():
    rb_global_tbl = gdb.parse_and_eval('rb_global_tbl')
    st_foreach(rb_global_tbl, try_print_variable)

def get_ruby_localvariables(th=None, varname=None):
  if th == None:
      th = gdb.parse_and_eval('ruby_current_thread')
  else:
      th = gdb.parse_and_eval('(rb_thread_t *) %s' % th)

  last_cfp = th['cfp']
  start_cfp = (th['stack'] + th['stack_size']).cast(control_frame_t.pointer()) - 2
  size = start_cfp - last_cfp + 1
  cfp = start_cfp
  call_stack = []
  for i in range(0, int(size)):
      if cfp['iseq'].dereference().address != 0:
          if cfp['pc'].dereference().address != 0:
              call_stack.append(cfp)
      cfp -= 1

  for cfp in reversed(call_stack):
      print(get_func_info(cfp))
      local_table = get_local_table(cfp)
      local_table_size = get_local_table_size(cfp)
      print("local table size = %s" % local_table_size)
      for j in range(0, int(local_table_size)):
          id = local_table[j]
          l = _rb_id2str(id)
          if varname is not None:
              if l is not None or varname is get_rstring(l):
                  continue

          if l is not None:
              sys.stdout.write("%s = " % get_rstring(l))
              v = cfp['ep'] - (local_table_size - j - 1 + 2)
              try:
                  print_ruby_value(v.dereference())
              except:
                  continue
              finally:
                  sys.stdout.write("\n")

def get_rstring(addr):
  if addr is None:
    return None

  s = addr.cast(RString_t.pointer())
  if s['basic']['flags'] & (1 << 13):
    return s['as']['heap']['ptr'].string()
  else:
    return s['as']['ary'].string()

def get_lineno(iseq, pos):
  if pos != 0:
    pos -= 1

  try:
      t = iseq['body']['line_info_table']
      t_size = iseq['body']['line_info_size']
  except:
      t = iseq['line_info_table']
      t_size = iseq['line_info_size']

  if t_size == 0:
    return 0
  elif t_size == 1:
    return t[0]['line_no']

  for i in range(0, int(t_size)):
    if pos == t[i]['position']:
      return t[i]['line_no']
    elif t[i]['position'] > pos:
      return t[i-1]['line_no']

  return t[t_size-1]['line_no']

def get_func_info(cfp):
    try:
        path = get_rstring(cfp['iseq']['location']['path'])
        label = get_rstring(cfp['iseq']['location']['label'])
        lineno = get_lineno(cfp['iseq'], cfp['pc'] - cfp['iseq']['iseq_encoded'])
    except:
        # Ruby 2.3+
        path = get_rstring(cfp['iseq']['body']['location']['path'])
        label = get_rstring(cfp['iseq']['body']['location']['label'])
        lineno = get_lineno(cfp['iseq'], cfp['pc'] - cfp['iseq']['body']['iseq_encoded'])

    return "{}:{}:in `{}'".format(path, lineno, label)

def get_local_table(cfp):
    try:
        local_table = (cfp['iseq']['local_table'])
    except:
        local_table = (cfp['iseq']['body']['local_table'])
    return local_table

def get_local_table_size(cfp):
    try:
        local_table_size = (cfp['iseq']['local_table_size'])
    except:
        local_table_size = (cfp['iseq']['body']['local_table_size'])
    return local_table_size

def get_ruby_stacktrace(th=None, folded=False):
    if th == None:
        th = gdb.parse_and_eval('ruby_current_thread')
    else:
        th = gdb.parse_and_eval('(rb_thread_t *) %s' % th)

    last_cfp = th['cfp']
    start_cfp = (th['stack'] + th['stack_size']).cast(control_frame_t.pointer()) - 2
    size = start_cfp - last_cfp + 1
    cfp = start_cfp
    call_stack = []
    for i in range(0, int(size)):
        if cfp['iseq'].dereference().address != 0:
            if cfp['pc'].dereference().address != 0:
                call_stack.append(get_func_info(cfp))
        cfp -= 1

    for i in reversed(call_stack):
        if folded:
            sys.stdout.write("%s;" % i)
        else:
            print(i)

    if folded:
        print()

def get_rb_thread_for_current_thread():
    # We will get the current thread id from gdb, iterate over all ruby
    # threads and find the corresponding rb_thread_t

    # TODO: Can't we directly pull the thread id out of gdb.selected_thread()?
    t = gdb.selected_thread()
    if t is None:
        print("No current thread")
        return None

    gdb_th_num = t.num
    curr_th_id = re.search('Thread ([0-9a-zx]+)', gdb.execute('info thread %d' % gdb_th_num, to_string=True)).group(1);
    curr_th_id = int(curr_th_id, 16)
    #curr_th_id=gdb.parse_and_eval('(pthread_t)pthread_self()')

    head = gdb.parse_and_eval('&ruby_current_thread->vm->living_threads.n')
    t = gdb.parse_and_eval('ruby_current_thread->vm->living_threads.n.next')
    while (t != head):
        ti = t.cast(rb_thread_struct_t.pointer())
        if ti['thread_id'] == curr_th_id:
            #print("found matching ruby thread")
            return ti
        t = t['next']

    print("Thread {0} (0x{1:x}) is not a ruby thread!".format(gdb_th_num,curr_th_id))

    return None

class AnalyzeSegFaultCmd(gdb.Command):
    "Analyze ruby segfault info"

    def __init__(self):
        gdb.Command.__init__(self, "analyze_ruby_fault", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        for i,inferior in enumerate(gdb.inferiors()):
            if not inferior.is_valid():
                continue

            found_segfault = False

            for j,thread in enumerate(inferior.threads()):
                thread.switch()
                #print("Processing thread %s" % thread.ptid[1])
                frame = gdb.selected_frame()
                while ((frame is not None) and (frame.type() != gdb.SIGTRAMP_FRAME)):
                    frame = frame.older()

                if frame is None:
                    continue

                sigsegv_frame = frame.newer()
                if (sigsegv_frame is None) or sigsegv_frame.name() != "sigsegv":
                    continue

                found_segfault = True
                print("Found segfault frame for pid %s" % inferior.pid)
                sigsegv_frame.select()

                fault_addr = gdb.parse_and_eval("info->si_addr")
                reg_err = gdb.parse_and_eval("((ucontext_t *)ctx)->uc_mcontext.gregs[REG_ERR]")
                reg_err = reg_err.cast(gdb.lookup_type('long long'))

                print("Faulting address : %s" % fault_addr)
                sys.stdout.write("Fault reason : %s (" % hex(int(reg_err)))
                if reg_err & 0x1:
                    sys.stdout.write("ProtectionFault")
                else:
                    sys.stdout.write("NoPageFound")

                if reg_err & 0x2:
                    sys.stdout.write(" WriteAccess")
                else:
                    sys.stdout.write(" ReadAccess")

                if reg_err & 0x4:
                    sys.stdout.write(" UserMode")
                else:
                    sys.stdout.write(" KernelMode")
                print(")")

            if not found_segfault:
                print("Couldn't find segfault frame for pid %s" % inferior.pid)

class RubyStackTraceCmd(gdb.Command):
    "Print Ruby callstack of current GDB thread (which may/may not be current Ruby thread holding GVL)"

    def __init__(self):
        gdb.Command.__init__(self, "ruby_bt", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        ti = get_rb_thread_for_current_thread()
        if ti is None:
            print("Could not find ruby thread info for current gdb thread")
            return

        argv = gdb.string_to_argv(arg)
        folded = False
        if len(argv) > 0 and argv[0] == 'folded':
            folded = True
        get_ruby_stacktrace(th=ti, folded=folded)

class RubyStackTraceCurrCmd(gdb.Command):
    "Print stacktrace of current Ruby thread (which may/may not be current GDB thread)"

    def __init__(self):
        gdb.Command.__init__(self, "ruby_bt_curr", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        get_ruby_stacktrace()

class RubyLocalVariablesCmd(gdb.Command):
    "Print Ruby local variables, by walking current GDB thread's Ruby stack. Pass variable name to filter"

    def __init__(self):
        gdb.Command.__init__(self, "ruby_locals", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        ti = get_rb_thread_for_current_thread()
        if ti is None:
            print("Could not find ruby thread info for current gdb thread")
            return

        argv = gdb.string_to_argv(arg)
        varname = None
        if len(argv) > 0:
            varname = argv[0]

        get_ruby_localvariables(th=ti, varname=varname)

class RubyLocalVariablesCurrCmd(gdb.Command):
    "Print Ruby local variables, by walking current (holding GVL) Ruby thread's stack. Pass variable name to filter"

    def __init__(self):
        gdb.Command.__init__(self, "ruby_locals_curr", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        argv = gdb.string_to_argv(arg)
        varname = None
        if len(argv) > 0:
            varname = argv[0]

        get_ruby_localvariables(varname=varname)

class RubyGlovalVariablesCmd(gdb.Command):
    "Print Ruby global variables"

    def __init__(self):
        gdb.Command.__init__(self, "ruby_globals", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL)

    def invoke(self, arg, _from_tty):
        print_global_variables()

AnalyzeSegFaultCmd()
RubyStackTraceCmd()
RubyStackTraceCurrCmd()
RubyLocalVariablesCmd()
RubyLocalVariablesCurrCmd()
RubyGlovalVariablesCmd()

/*---
es5id: 15.2.3.5-4-251
description: >
    Object.create - one property in 'Properties' is the Math object
    that uses Object's [[Get]] method to access the 'get' property
    (8.10.5 step 7.a)
---*/

            Math.get = function () {
                return "VerifyMathObject";
            };

            var newObj = Object.create({}, {
                prop: Math 
            });

assert.sameValue(newObj.prop, "VerifyMathObject", 'newObj.prop');
package com.serotonin.mango.web.mvc.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ParameterizableViewController;

import com.serotonin.mango.Common;
import com.serotonin.mango.db.dao.ViewDao;
import com.serotonin.mango.view.ShareUser;
import com.serotonin.mango.view.View;

/**
 * @author Matthew Lohbihler
 */
public class PublicViewController extends ParameterizableViewController {
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
        ViewDao viewDao = new ViewDao();

        // Get the view by id.
        String vid = request.getParameter("viewId");
        View view = null;
        if (vid != null) {
            try {
                view = viewDao.getView(Integer.parseInt(vid));
            }
            catch (NumberFormatException e) { /* no op */
            }
        }
        else {
            String name = request.getParameter("viewName");
            if (name != null)
                view = viewDao.getView(name);
            else {
                String xid = request.getParameter("viewXid");
                if (xid != null)
                    view = viewDao.getViewByXid(xid);
            }
        }

        Map<String, Object> model = new HashMap<String, Object>();

        // Ensure the view has anonymously accessible.
        if (view != null && view.getAnonymousAccess() == ShareUser.ACCESS_NONE)
            view = null;

        if (view != null) {
            model.put("view", view);
            view.validateViewComponents(view.getAnonymousAccess() == ShareUser.ACCESS_READ);
            Common.addAnonymousView(request, view);
        }

        return new ModelAndView(getViewName(), model);
    }
}
require 'rails_helper'

RSpec.describe Companies::DestroyCompany do
  include ServiceStubHelpers::Cruncher

  describe '#call' do
    let(:company) { double }
    let(:company_query_stub) { double }
    let(:job_application_query) { double }
    let(:reject_iterator) { double(JobApplications::Reject) }
    let(:subject) do
      Companies::DestroyCompany.new(
        double, company_query_stub, job_application_query, reject_iterator
      )
    end
    context 'cannot find company' do
      before(:each) do
        allow(subject.query).to receive(:find_by_id)
          .and_raise(ActiveRecord::RecordNotFound)
      end

      it 'raises ActiveRecord Exception' do
        expect(subject.query).not_to receive(:destroy)
        expect { subject.call(1) }.to raise_error(ActiveRecord::RecordNotFound)
      end
    end

    context 'user not authorized to delete a company' do
      let(:agency) { FactoryBot.build(:agency) }
      let(:company_with_jobs) do
        job = FactoryBot.build(:job)
        job.id = 1
        company = FactoryBot.build(:company, agencies: [agency], jobs: [job])
        allow(company.jobs).to receive(:exists?).and_return true
        company
      end

      before(:each) do
        expect(subject).to receive(:authorized!)
          .with(company_with_jobs, 'destroy')
          .and_raise(Authorization::NotAuthorizedError)
        company_with_jobs.id = 1
        allow(subject.query).to receive(:find_by_id).and_return(company_with_jobs)
      end

      it 'does not delete the company' do
        expect(subject.query).not_to receive(:destroy)
        expect { subject.call(1) }.to raise_error(Authorization::NotAuthorizedError)
      end
    end

    context 'company with jobs' do
      let(:agency) { FactoryBot.build(:agency) }
      let(:company_with_jobs) do
        job = FactoryBot.build(:job)
        job.id = 1
        company = FactoryBot.build(:company, agencies: [agency], jobs: [job])
        allow(company.jobs).to receive(:exists?).and_return true
        company
      end

      before(:each) do
        stub_cruncher_authenticate
        stub_cruncher_job_create
      end

      context 'no job applications' do
        before(:each) do
          expect(subject).to receive(:authorized!)
            .with(company_with_jobs, 'destroy')
          expect(job_application_query).to receive(:find_by_company)
            .and_return([])
          company_with_jobs.id = 1
          allow(subject.query).to receive(:find_by_id).and_return(company_with_jobs)
          expect(reject_iterator).not_to receive(:call)
        end

        it 'does update the company status to inactive' do
          expect(company_with_jobs).to receive(:inactive)
          result = subject.call(1)
          expect(result).to eq(company_with_jobs)
        end
      end

      context 'a job as application' do
        let(:job_application) do
          FactoryBot.build(:job_application)
        end

        before(:each) do
          expect(subject).to receive(:authorized!)
            .with(company_with_jobs, 'destroy')
          expect(job_application_query).to receive(:find_by_company)
            .and_return([job_application])

          company_with_jobs.id = 1
          allow(subject.query).to receive(:find_by_id).and_return(company_with_jobs)
          expect(reject_iterator).to receive(:call)
            .with(job_application, 'Company removed from the system')
        end

        it 'does update the company status to inactive' do
          expect(company_with_jobs).to receive(:inactive)
          result = subject.call(1)
          expect(result).to eq(company_with_jobs)
        end

        it 'calls the job application rejection iterator' do
          expect(company_with_jobs).to receive(:inactive)
          result = subject.call(10)
          expect(result).to eq(company_with_jobs)
        end
      end
    end

    context 'company without jobs' do
      let(:agency) { FactoryBot.build(:agency) }
      let(:company) do
        FactoryBot.build(:company, agencies: [agency])
      end

      before(:each) do
        expect(subject).to receive(:authorized!)
          .with(company, 'destroy')
        allow(subject.query).to receive(:find_by_id).and_return(company)
        allow(job_application_query).to receive(:find_by_company)
          .and_return([])
      end

      it 'does udpdate the company status to inactive' do
        expect(company).to receive(:inactive)
        result = subject.call(1)
        expect(result).to eq(company)
      end
    end
  end
end

CXX = g++
CXXFLAGS = -std=c++11 -Wall
RM = rm -rf

OBJ = $(patsubst %.cpp,%.o,$(wildcard *.cpp))

.PHONY: all
all: test_all
test_all : $(OBJ)
	$(CXX) $(CXXFLAGS) $^ -o $@
%.o: %.cpp test_tool.h
	$(CXX) $(CXXFLAGS) -c $< -o $@

.PHONY: clean
clean:
	$(RM) $(OBJ) test_all
.PHONY: distclean
distclean: clean

open! IStd

(** visibility of the issue type *)
type visibility =
  | User  (** always add to error log *)
  | Developer  (** only add to error log in some debug modes *)
  | Silent  (** never add to error log *)
[@@deriving compare, equal]

(** severity of the report *)
type severity = Like | Info | Advice | Warning | Error [@@deriving compare, equal, enumerate]

val string_of_severity : severity -> string

type t = private
  { unique_id: string
  ; checker: Checker.t
  ; visibility: visibility
  ; mutable default_severity: severity
        (** used for documentation but can be overriden at report time *)
  ; mutable enabled: bool
  ; mutable hum: string
  ; mutable doc_url: string option
  ; mutable linters_def_file: string option }
[@@deriving compare]

val equal : t -> t -> bool

val all_issues : unit -> t list
(** all the issues declared so far *)

val pp : Format.formatter -> t -> unit
(** pretty print a localised string *)

val find_from_string : id:string -> t option
(** return the issue type if it was previously registered *)

val register_from_string :
     ?enabled:bool
  -> ?hum:string
  -> ?doc_url:string
  -> ?linters_def_file:string
  -> id:string
  -> ?visibility:visibility
  -> severity
  -> Checker.t
  -> t
(** Create a new issue and register it in the list of all issues. NOTE: if the issue with the same
    string id is already registered, overrides `hum`, `doc_url`, and `linters_def_file`, but DOES
    NOT override `enabled`. This trick allows to deal with disabling/enabling dynamic AL issues from
    the config, when we don't know all params yet. Thus, the human-readable description can be
    updated when we encounter the definition of the issue type, eg in AL. *)

val checker_can_report : Checker.t -> t -> bool
(** Whether the issue was registered as coming from the given checker. Important to call this before
    reporting to keep documentation accurate. *)

val set_enabled : t -> bool -> unit

val abduction_case_not_implemented : t

val array_of_pointsto : t

val array_out_of_bounds_l1 : t

val array_out_of_bounds_l2 : t

val array_out_of_bounds_l3 : t

val assert_failure : t

val bad_footprint : t

val biabduction_analysis_stops : t

val biabd_condition_always_false : t

val biabd_condition_always_true : t

val biabd_registered_observer_being_deallocated : t

val biabd_stack_variable_address_escape : t

val biabd_use_after_free : t

val buffer_overrun_l1 : t

val buffer_overrun_l2 : t

val buffer_overrun_l3 : t

val buffer_overrun_l4 : t

val buffer_overrun_l5 : t

val buffer_overrun_r2 : t

val buffer_overrun_s2 : t

val buffer_overrun_t1 : t
(** Tainted values is used in array accesses, causing buffer over/underruns *)

val buffer_overrun_u5 : t

val cannot_star : t

val captured_strong_self : t

val checkers_allocates_memory : t
(** Warning name when a performance critical method directly or indirectly calls a method allocating
    memory *)

val checkers_annotation_reachability_error : t

val checkers_calls_expensive_method : t
(** Warning name when a performance critical method directly or indirectly calls a method annotatd
    as expensive *)

val checkers_expensive_overrides_unexpensive : t
(** Warning name for the subtyping rule: method not annotated as expensive cannot be overridden by a
    method annotated as expensive *)

val checkers_fragment_retain_view : t

val checkers_immutable_cast : t

val checkers_printf_args : t

val class_cast_exception : t

val class_load : t

val complexity_increase : kind:CostKind.t -> is_on_ui_thread:bool -> t

val component_factory_function : t

val component_file_cyclomatic_complexity : t

val component_file_line_count : t

val component_initializer_with_side_effects : t

val component_with_multiple_factory_methods : t

val component_with_unconventional_superclass : t

val condition_always_false : t

val condition_always_true : t

val constant_address_dereference : t

val create_intent_from_uri : t

val cross_site_scripting : t

val dangling_pointer_dereference : t

val dangling_pointer_dereference_maybe : t

val dead_store : t

val deadlock : t

val deallocate_stack_variable : t

val deallocate_static_memory : t

val deallocation_mismatch : t

val divide_by_zero : t

val do_not_report : t
(** an issue type that should never be reported *)

val empty_vector_access : t

val eradicate_condition_redundant : t

val eradicate_field_not_initialized : t

val eradicate_field_not_nullable : t

val eradicate_field_over_annotated : t

val eradicate_inconsistent_subclass_parameter_annotation : t

val eradicate_inconsistent_subclass_return_annotation : t

val eradicate_redundant_nested_class_annotation : t

val eradicate_bad_nested_class_annotation : t

val eradicate_nullable_dereference : t

val eradicate_parameter_not_nullable : t

val eradicate_return_not_nullable : t

val eradicate_return_over_annotated : t

val eradicate_unvetted_third_party_in_nullsafe : t

val eradicate_unchecked_usage_in_nullsafe : t

val eradicate_meta_class_can_be_nullsafe : t

val eradicate_meta_class_needs_improvement : t

val eradicate_meta_class_is_nullsafe : t

val exposed_insecure_intent_handling : t

val failure_exe : t

val field_not_null_checked : t

val guardedby_violation_racerd : t

val impure_function : t

val inefficient_keyset_iterator : t

val inferbo_alloc_is_big : t

val inferbo_alloc_is_negative : t

val inferbo_alloc_is_zero : t

val inferbo_alloc_may_be_big : t

val inferbo_alloc_may_be_negative : t

val inferbo_alloc_may_be_tainted : t

val infinite_cost_call : kind:CostKind.t -> t

val inherently_dangerous_function : t

val insecure_intent_handling : t

val integer_overflow_l1 : t

val integer_overflow_l2 : t

val integer_overflow_l5 : t

val integer_overflow_r2 : t

val integer_overflow_u5 : t

val interface_not_thread_safe : t

val internal_error : t

val invariant_call : t

val javascript_injection : t

val lab_resource_leak : t

val leak_after_array_abstraction : t

val leak_in_footprint : t

val leak_unknown_origin : t

val lockless_violation : t

val lock_consistency_violation : t

val logging_private_data : t

val expensive_loop_invariant_call : t

val memory_leak : t

val missing_fld : t

val missing_required_prop : t

val mixed_self_weakself : t

val multiple_weakself : t

val mutable_local_variable_in_component_file : t

val null_dereference : t

val null_test_after_dereference : t

val nullptr_dereference : t

val parameter_not_null_checked : t

val pointer_size_mismatch : t

val precondition_not_found : t

val precondition_not_met : t

val premature_nil_termination : t

val pulse_memory_leak : t

val pure_function : t

val quandary_taint_error : t

val resource_leak : t

val retain_cycle : t

val skip_function : t

val skip_pointer_dereference : t

val shell_injection : t

val shell_injection_risk : t

val sql_injection : t

val sql_injection_risk : t

val stack_variable_address_escape : t

val starvation : t

val static_initialization_order_fiasco : t

val strict_mode_violation : t

val strong_self_not_checked : t

val symexec_memory_error : t

val thread_safety_violation : t

val topl_error : t

val unary_minus_applied_to_unsigned_expression : t

val uninitialized_value : t

val unreachable_code_after : t

val use_after_delete : t

val use_after_free : t

val use_after_lifetime : t

val untrusted_buffer_access : t

val untrusted_deserialization : t

val untrusted_deserialization_risk : t

val untrusted_file : t

val untrusted_file_risk : t

val untrusted_heap_allocation : t

val untrusted_intent_creation : t

val untrusted_url_risk : t

val untrusted_environment_change_risk : t

val untrusted_variable_length_array : t

val user_controlled_sql_risk : t

val vector_invalidation : t

val weak_self_in_noescape_block : t

val wrong_argument_number : t

val unreachable_cost_call : kind:CostKind.t -> t
public class MessageC2SLoginSendNonceNameAndPassword extends MessageSendByteArray {

	private String username;

	private byte[] password;

	/** Constructor for allowing creation of an empty message */
	public MessageC2SLoginSendNonceNameAndPassword() {
		super(MessageType.C2S_LOGIN_SENDNONCENAMEANDPASSWORD);
	}

	/**
	 * Constructor with a TCP/IP source/destination of the message and the name
	 * of the choosen character.
	 *
	 * @param source
	 *            The TCP/IP address associated to this message
	 * @param nonce
	 *            random number to prevent replay attacks
	 * @param username
	 *            the username of the user that wants to login
	 * @param password
	 *            the plain password of the user that wants to login
	 */
	public MessageC2SLoginSendNonceNameAndPassword(Channel source, byte[] nonce,
	        String username, byte[] password) {
		super(MessageType.C2S_LOGIN_SENDNONCENAMEANDPASSWORD, source, nonce);
		this.username = username;
		this.password = Utility.copy(password);
	}

	/**
	 * This method returns the username
	 *
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * This method returns the encoded password
	 *
	 * @return the password
	 */
	public byte[] getPassword() {
		return Utility.copy(password);

	}

	/**
	 * This method returns a String that represent the object
	 *
	 * @return a string representing the object.
	 */
	@Override
	public String toString() {
		return "Message (C2S Login) from (" + getAddress() + ") CONTENTS: (nonce:"
		        + Hash.toHexString(hash) + "\tusername:" + username + ")";
	}

	@Override
	public void writeObject(OutputSerializer out) throws IOException {
		super.writeObject(out);
		out.write(username);
		out.write(password);
	}

	@Override
	public void readObject(InputSerializer in) throws IOException {
		super.readObject(in);
		username = in.readString();
		password = in.readByteArray();
		if (type != MessageType.C2S_LOGIN_SENDNONCENAMEANDPASSWORD) {
			throw new IOException();
		}
	}
}
export default {
init: function () {
const AK = 'vcM72RPfaB2Wqcqq7QBli94s4GUyOiWY'
const BMapURL = 'https://api.map.baidu.com/api?v=3.0&ak=' + AK + '&s=1&callback=onBMapCallback'
return new Promise((resolve, reject) => {
// 如果已加载直接返回
// if (typeof BMap !== 'undefined') {
// resolve(BMap)
// return true
// }
// 百度地图异步加载回调处理
window.onBMapCallback = function () {
console.log('百度地图脚本初始化成功...')
// eslint-disable-next-line
resolve(BMap)
}

// 插入script脚本
let scriptNode = document.createElement('script')
scriptNode.setAttribute('type', 'text/javascript')
scriptNode.setAttribute('src', BMapURL)
document.body.appendChild(scriptNode)
})
}
}

BOSH Release for PostgreSQL in Docker container
===============================================

This BOSH release has three use cases:

-	run a single Docker container of a PostgreSQL Docker image on a single BOSH VM
-	run a Cloud Foundry service broker that itself runs containers of PostgreSQL Docker image on a BOSH VM based on user requests
-	embedded PostgreSQL Docker image that could be used by another BOSH release

As a Cloud Foundry service broker, there are two version of PostgreSQL that can be offered:

```
$ cf marketplace
Getting services from marketplace in org system / space dev as admin...
OK

service        plans   description
postgresql93   free    postgresql 9.3 service for application development and testing
postgresql94   free    postgresql 9.4 service for application development and testing
```

NOTE: if you're deploying the broker for the first time, it is suggested to only offer the latest database to minimize the operations upset of deprecating and disabling the older one in the future.

The PostgreSQL image can be referenced either:

-	from an embebbed/bundled image stored with each BOSH release version
-	from upstream and/or private registries

Spiff deployment templates are included for:

-	bosh-lite/garden
-	bosh-lite/warden (older bosh-lites, deprecated)
-	bosh/aws

[Learn more](https://blog.starkandwayne.com/2015/04/28/embed-docker-into-bosh-releases/) about embedding Docker images in BOSH releases.

Installation
------------

To use this BOSH release, first upload it to your bosh and the `docker` release

```
bosh upload release https://bosh.io/d/github.com/cf-platform-eng/docker-boshrelease
bosh upload release https://bosh.io/d/github.com/cloudfoundry-community/postgresql-docker-boshrelease
```

For the various Usage cases below you will need this git repo's `templates` folder:

```
git clone https://github.com/cloudfoundry-community/postgresql-docker-boshrelease.git
cd postgresql-docker-boshrelease
```

Usage
-----

### Run a single container of PostgreSQL

For [bosh-lite](https://github.com/cloudfoundry/bosh-lite), you can quickly create a deployment manifest & deploy a single VM:

```
templates/make_manifest warden container embedded
bosh -n deploy
```

This deployment will look like:

```
$ bosh vms postgresql-docker-warden
+------------------------+---------+---------------+--------------+
| Job/index              | State   | Resource Pool | IPs          |
+------------------------+---------+---------------+--------------+
| postgresql_docker_z1/0 | running | small_z1      | 10.244.20.6  |
+------------------------+---------+---------------+--------------+
```

If you want to use the upstream version of the Docker image, reconfigure the deployment manifest:

```
templates/make_manifest warden container upstream
bosh -n deploy
```

To register your Logstash with a Cloud Foundry application on bosh-lite/warden:

```
cf cups postgresql -l syslog://10.244.20.6:514
```

Now bind it to your applications and their STDOUT/STDERR logs will automatically stream to your PostgreSQL.

```
cf bs my-app postgresql
```

### Run a Cloud Foundry service broker for PostgreSQL

For [bosh-lite](https://github.com/cloudfoundry/bosh-lite), you can quickly create a deployment manifest & deploy a single VM that also includes a service broker for Cloud Foundry

```
templates/make_manifest warden broker embedded
bosh -n deploy
```

This deployment will also look like:

```
$ bosh vms postgresql-docker-warden
+------------------------+---------+---------------+--------------+
| Job/index              | State   | Resource Pool | IPs          |
+------------------------+---------+---------------+--------------+
| postgresql_docker_z1/0 | running | small_z1      | 10.244.20.6 |
+------------------------+---------+---------------+--------------+
```

As a Cloud Foundry admin, you can register the broker and the service it provides:

```
cf create-service-broker postgresql-docker containers containers http://10.244.20.6
cf enable-service-access postgresql93
cf marketplace
```

If you want to use the upstream version of the Docker image, reconfigure the deployment manifest:

```
templates/make_manifest warden container upstream
bosh -n deploy
```

### Using Cloud Foundry Service Broker

Users can now provision PostgreSQL services and bind them to their apps.

```
cf cs postgresql93 free my-pg
cf bs my-app my-pg
```

### Versions & configuration

The version of PostgreSQL is determined by the Docker image bundled with the release being used. The source for building the Docker images is in the `images/` folders of this repo. See below for instructions.

### Development of postgresql configuration

To push new ideas/new PostgreSQL versions to an alternate Docker Hub image name:

```
cd images/postgresql95
export DOCKER_USER=<your user>
docker build -t $DOCKER_USER/postgresql .
docker push $DOCKER_USER/postgresql:9.5
```

This will create a new Docker image, based upon the upstream `cfcommunity/postgresql-base:9.5`.

Create an override YAML file, say `my-docker-image.yml`

```yaml
---
meta:
  postgresql_images:
    image: USERNAME/postgresql
    tag: 9.5
```

To deploy this change into BOSH, add the `my-docker-image.yml` file to the end of the `make_manifest` command:

```
./templates/make_manifest warden container upstream my-docker-image.yml
bosh deploy
```

import {Route, RouterModule} from '@angular/router';
import {PlayerComponent} from './player.component';
import {MapComponent} from './map/map.component';
import {AuthGuard} from '../shared/guards/auth.guard';
import {ProfileComponent} from './profile/profile.component';
import {CharacterComponent} from './character/character.component';

/**
 * Routes players are actived when module is lazy loaded.
 * Give access to map, character, forum, ranks, profile
 */
const GAME_ROUTES: Route[] = [
  {path: '', component : PlayerComponent, canActivate: [AuthGuard], children : [
      {path : 'map', component: MapComponent},
      {path : 'character', component: CharacterComponent},
      {path : 'profile', component: ProfileComponent},
      {path : '**', redirectTo : 'map', pathMatch: 'full'}
    ]},
];

export const PlayerRouting = RouterModule.forChild(GAME_ROUTES);

package com.norconex.collector.http.fetch.impl;

import org.junit.jupiter.api.Test;

import com.norconex.commons.lang.xml.XML;

public class GenericHttpFetcherTest  {

    @Test
    public void testWriteRead() {
        GenericHttpFetcherConfig cfg = new GenericHttpFetcherConfig();
        cfg.setValidStatusCodes(200, 201, 202);
        cfg.setNotFoundStatusCodes(404, 405);
        cfg.setHeadersPrefix("blah");
        cfg.setForceCharsetDetection(true);
        cfg.setForceContentTypeDetection(true);

        GenericHttpFetcher f = new GenericHttpFetcher(cfg);
        XML.assertWriteRead(f, "fetcher");
    }
}
package com.handsome.robot.Activity;

import android.content.Context;
import android.opengl.GLSurfaceView;

/**
 * Created by Joern on 2017/08/16.
 */

public class MyGLSurfaceView extends GLSurfaceView {

    private MyPlaneGLRenderer mRenderer;

    public MyGLSurfaceView(Context context) {
        super(context);
       /* // 创建一个OpenGL ES 2.0 context
        setEGLContextClientVersion(2);

        // Set the Renderer for drawing on the GLSurfaceView
        mRenderer = new MyPlaneGLRenderer();
        setRenderer(mRenderer);

        // Render the view only when there is a change in the drawing data
        setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);*/
    }
}

---
title: "Installation des Postfix-Dogu"
---

# Installation des Postfix-Dogu

## Voraussetzung

Für eine erfolgreiche Installation von Postfix muss im etcd vom CES ein Wert für den Relay-Host von Postfix konfiguriert
sein. Dieser wird in der Regel bereits beim Setup des CES gesetzt. Allerdings wird dieser Wert beim Entfernen des Dogus
über den Purge Befehl gelöscht. Der Wert muss dann vor der erneuten Installation vom Postfix neu gesetzt werden. Dies
kann über folgenden Befehl erfolgen:

``` 
etcdctl set /config/postfix/relayhost <Wert für den Relay-Host>
```

## Installation

Postfix can be easily installed via `cesapp` like all other dogus:

```
cesapp install official/postfix
```

/**
 * Logical event-driven API.
 */
export interface IGsLogicalHandler {

	/**
	 * Notify the start of a node.
	 *
	 * @param node Node with its head attributes, his holder property (if it is declared in a map) and its ancestors.
	 *   For empty keys in a map <pre>{key}</pre>, the node type is simple ('') and the body type is empty (''),
	 *   ie a node that has no serialized representation, but a node.holderProp specified.
	 * @param bodyText Must be specified only if node.bodyType==='"', ie a text body node ('"').
	 */
	startNode(node: IGsEventNode, bodyText?: IGsText): void

	/**
	 * Notify the end of a node.
	 * Each startNode() call has it corresponding endNode() call, even for an empty node or an empty key in a map.
	 *
	 * @param node Node with its head and tail attributes and its ancestors
	 */
	endNode(node: IGsEventNode): void
}

/**
 * Low level flat stream event-driven API for whitespaces handling.
 */
export interface IGsStreamHandler {
	headNode(name: IGsName, specialType?: gsSpecialType | null): void

	attribute(name: IGsName, value: IGsValue, specialType?: gsSpecialType | null, spBeforeEq?: string, spAfterEq?: string): void

	text(text: IGsText, inBodyMixed?: boolean): void

	startBody(bodyType: '[' | '{' | '`' | '~`'): void

	property(name: IGsName, isNull: boolean, spBeforeEq?: string): void

	endBody(bodyType: '[' | '{' | '`' | '~`'): void

	tailNode(): void

	whiteSpaces(spaces: string): void
}

/**
 * Serialization strategies and options.
 * - minified: minimize siz but less human readable, elimnating whitespaces when not necessary: <tag att='1'att2='2'>
 * - pretty: spaces are inserted for human readability: <tag att='1' att2='2'>
 * - indented: indentation is added for imbricated nodes.
 * - formatted: nodes are indented, text nodes and attribute values are formatted based on line width.
 */
export type IGsSerializeOptions = {
	method: 'minified'
	unformat?: boolean
} | {
	method: 'pretty'
	unformat?: boolean
} | {
	method: 'indented'
	unformat?: boolean
	indent?: gsIndent
} | {
	method: 'formatted'
	indent?: gsIndent
	lineWidth?: number
};

export type gsIndent = "" | "\t" | " " | "  " | "   " | "    " | "     "

/** Name for a node or an attribute with its escaping rule. */
export interface IGsName {
	name: string;
	nameEsc: gsEscapingStr;
}

/** Attribute value with its escaping rule and its formattable flag. */
export interface IGsValue {
	value: null | string
	valueEsc: gsEscapingValue
	valueFormattable: boolean
}

/**
 * Body Text
 */
export interface IGsText {
	value: string
	valueEsc: gsEscapingText
	valueFormattable: boolean
}

/**
 * Partial node definition used in IGsLogicalHandler
 */
export interface IGsEventNode extends IGsName {
	/** Parent node. */
	readonly parent: IGsEventNode | null

	/** Holder property when the node is declared in a map. */
	readonly holderProp: IGsName | undefined

	/** Depth of this node, ie count of non null parents. */
	readonly depth: number

	/** Node type : standard (null), simple('') or special type('#', '&', '?' or '%').*/
	readonly nodeType: gsNodeType

	/** Name of the node. */
	readonly name: string

	/** Escaping rule for the node. */
	readonly nameEsc: gsEscapingStr

	/** First tail attribute. */
	readonly firstAtt: IGsEventAtt | null

	/** Body type of the node: list ('['), map ('{'), text ('"'), empty (''), mixed ('`') or mixed formattable ('~`'). */
	readonly bodyType: gsEventBodyType

	/** Helper to know if the body type node is mixed or mixed formattable ('`' or '~`'). */
	readonly isBodyMixed: boolean;

	/** Attributes in tail node: only available in IGsLogicalHandler.endNode() and not in IGsLogicalHandler.startNode() */
	readonly firstTailAtt: IGsEventAtt | null

	/**
	 * Get the first attribute with this name and type.
	 * @return the attribute or null if not found.
	 */
	getAttribute(name: string, specialType?: gsSpecialType | null, after?: IGsEventAtt): IGsEventAtt | null

	/**
	 * Get the value of the first attribute with this name and type.
	 * @return null if the attribute exist with no value, undefined if the attribute does not exist.
	 */
	getAttr(name: string, specialType?: gsSpecialType | null): string | null | undefined

	/**
	 * Build a path from the root for retrieving this node. Useful for test and debug.
	 * Path format:
	 * - each anonymous node: {offset} //TODO add offset in IGsEventNode
	 * - each named node: {offset} '~' {name}
	 * - each prop: {name} '='
	 * - node separator: '>'
	 *
	 * Names use the same escaping rules as in GS (raw, quoted or bounded).
	 */
	toPath(): string;
}

/**
 * Attribute definition used in IGsLogicalHandler
 */
export interface IGsEventAtt extends IGsName, IGsValue {
	readonly attType: gsSpecialType | null
	readonly name: string
	readonly nameEsc: gsEscapingStr
	readonly value: string | null
	readonly valueEsc: gsEscapingValue
	readonly valueFormattable: boolean
	readonly offset: number
	readonly inTail: boolean
	readonly next: IGsEventAtt | null

	/**
	 * Build a path from the root for retrieving this attribute. Useful for test and debug.
	 * Attribute format after the owner path: '@' {offset} '~' {name}
	 */
	toPath(owner: IGsEventNode): string;
}


export type gsEscapingStr = /*raw*/ null | /*quoted*/ "'" |  /*bounded*/ `|${string}'`
export type gsEscapingText = /*quoted*/ '"' |  /*bounded*/ `!${string}"` | /*raw for simple node*/ null //TODO | /*base64*/ '$'
export type gsEscapingValue = gsEscapingStr | gsEscapingText

export type gsSpecialType = /*Comment*/ '#' | /*Meta*/ '&' | /*Instruction*/ '%' |  /*Syntax*/ '?'

export type gsNodeType = gsSpecialType | /*standard node*/ null | /*simple node*/ ''

export type gsBodyType = /*empty*/ '' |  /*list*/'[' | /*map*/ '{' | /*text*/ '"' | /*mixed*/ '`'

export type gsEventBodyType = gsBodyType | /*mixed formattable*/ '~`'

/**
 * Regex for avaluate if a string can be serialized as a rawChars (without escaping)
 * rawchars : minusucle || majuscule || -./0-9: || _
 * cardinality '+' in the regExp because an empty string must be quoted: '' or "".
 */
export const rawChars = /^[a-zA-Z\--:_]+$/;

export const whiteSpaces = /^[ \t\r\n]*$/;
// import React from "react"
// import { graphql } from "gatsby"

// export default function Template({
//   data, // this prop will be injected by the GraphQL query below.
// }) {
//   const { blogsJson } = data // data.blogsJson holds our post data
//   const { frontmatter, html } = blogsJson
//   return (
//     <div className="blog-post-container">
//       <div className="blog-post">
//         <h1>{frontmatter.title}</h1>
//         <h2>{frontmatter.date}</h2>
//         <div
//           className="blog-post-content"
//           dangerouslySetInnerHTML={{ __html: html }}
//         />
//       </div>
//     </div>
//   )
// }

// export const pageQuery = graphql`
//   query($path: String!) {
//     blogsJson(frontmatter: { path: { eq: $path } }) {
//       html
//       frontmatter {
//         date(formatString: "MMMM DD, YYYY")
//         path
//         title
//       }
//     }
//   }
// `



// import React from "react"
// import { graphql } from "gatsby"
// import Layout from "../components/layout"

// export default ({ data }) => {
// 	console.log('data:', data);
//   const post = data.markdownRemark
//   return (
//     <Layout>
//       <div>
//         <h1>{post.frontmatter.title}</h1>
//         <div dangerouslySetInnerHTML={{ __html: post.html }} />
//       </div>
//     </Layout>
//   )
// }

// export const query = graphql`
//   query($slug: String!) {
//     markdownRemark(fields: { slug: { eq: $slug } }) {
//       html
//       frontmatter {
//         title
//       }
//     }
//   }
// `
#include "sequence.hpp"
#include "kmer.hpp"
#include "database.hpp"
#include "kmerdb.hpp"

/**************************************************************************************************/

KmerDB::KmerDB(string fastaFileName, int kSize) : Database(), kmerSize(kSize) {
	try { 
	
		kmerDBName = fastaFileName.substr(0,fastaFileName.find_last_of(".")+1) + char('0'+ kmerSize) + "mer";
		
		int power4s[14] = { 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864 };
		count = 0;
		
		maxKmer = power4s[kmerSize];
		kmerLocations.resize(maxKmer+1);
		
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "KmerDB");
		exit(1);
	}	

}
/**************************************************************************************************/
KmerDB::KmerDB() : Database() {}
/**************************************************************************************************/

KmerDB::~KmerDB(){}

/**************************************************************************************************/

vector<int> KmerDB::findClosestSequences(Sequence* candidateSeq, int num){
	try {
		if (num > numSeqs) { m->mothurOut("[WARNING]: you requested " + toString(num) + " closest sequences, but the template only contains " + toString(numSeqs) + ", adjusting."); m->mothurOutEndLine(); num = numSeqs; }
		
		vector<int> topMatches;
		Kmer kmer(kmerSize);
		searchScore = 0;
		Scores.clear();
		
		vector<int> matches(numSeqs, 0);						//	a record of the sequences with shared kmers
		vector<int> timesKmerFound(kmerLocations.size()+1, 0);	//	a record of the kmers that we have already found
		
		int numKmers = candidateSeq->getNumBases() - kmerSize + 1;	
	
		for(int i=0;i<numKmers;i++){
			int kmerNumber = kmer.getKmerNumber(candidateSeq->getUnaligned(), i);		//	go through the query sequence and get a kmer number
			if(timesKmerFound[kmerNumber] == 0){				//	if we haven't seen it before...
				for(int j=0;j<kmerLocations[kmerNumber].size();j++){//increase the count for each sequence that also has
					matches[kmerLocations[kmerNumber][j]]++;	//	that kmer
				}
			}
			timesKmerFound[kmerNumber] = 1;						//	ok, we've seen the kmer now
		}
		
		if (num != 1) {
			vector<seqMatch> seqMatches; seqMatches.resize(numSeqs);
			for(int i=0;i<numSeqs;i++){		
				seqMatches[i].seq = i;
				seqMatches[i].match = matches[i];
			}
			
			//sorts putting largest matches first
			sort(seqMatches.begin(), seqMatches.end(), compareSeqMatches);
			
			searchScore = seqMatches[0].match;
			searchScore = 100 * searchScore / (float) numKmers;		//	return the Sequence object corresponding to the db
		
			//save top matches
			for (int i = 0; i < num; i++) {
				topMatches.push_back(seqMatches[i].seq);
				float thisScore = 100 * seqMatches[i].match / (float) numKmers;
				Scores.push_back(thisScore);
			}
		}else{
			int bestIndex = 0;
			int bestMatch = -1;
			for(int i=0;i<numSeqs;i++){	
				
				if (matches[i] > bestMatch) {
					bestIndex = i;
					bestMatch = matches[i];
				}
			}
			
			searchScore = bestMatch;
			searchScore = 100 * searchScore / (float) numKmers;		//	return the Sequence object corresponding to the db
			topMatches.push_back(bestIndex);
			Scores.push_back(searchScore);
		}
		return topMatches;		
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "findClosestSequences");
		exit(1);
	}	
}

/**************************************************************************************************/

void KmerDB::generateDB(){
	try {
		
		ofstream kmerFile;										//	once we have the kmerLocations folder print it out
		m->openOutputFile(kmerDBName, kmerFile);					//	to a file
		
		//output version
		kmerFile << "#" << m->getVersion() << endl;
		
		for(int i=0;i<maxKmer;i++){								//	step through all of the possible kmer numbers
			kmerFile << i << ' ' << kmerLocations[i].size();	//	print the kmer number and the number of sequences with
			for(int j=0;j<kmerLocations[i].size();j++){			//	that kmer.  then print out the indices of the sequences
				kmerFile << ' ' << kmerLocations[i][j];			//	with that kmer.
			}
			kmerFile << endl;
		}
		kmerFile.close();
		
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "generateDB");
		exit(1);
	}	
	
}
/**************************************************************************************************/
void KmerDB::addSequence(Sequence seq) {
	try {
		Kmer kmer(kmerSize);
		
		string unaligned = seq.getUnaligned();	//	...take the unaligned sequence...
		int numKmers = unaligned.length() - kmerSize + 1;
			
		vector<int> seenBefore(maxKmer+1,0);
		for(int j=0;j<numKmers;j++){						//	...step though the sequence and get each kmer...
			int kmerNumber = kmer.getKmerNumber(unaligned, j);
			if(seenBefore[kmerNumber] == 0){
				kmerLocations[kmerNumber].push_back(count);		//	...insert the sequence index into kmerLocations for
			}												//	the appropriate kmer number
			seenBefore[kmerNumber] = 1;
		}													
	
		count++;
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "addSequence");
		exit(1);
	}	
}
/**************************************************************************************************/

void KmerDB::readKmerDB(ifstream& kmerDBFile){
	try {
					
		kmerDBFile.seekg(0);									//	start at the beginning of the file
		
		//read version
		string line = m->getline(kmerDBFile); m->gobble(kmerDBFile);
		
		string seqName;
		int seqNumber;

		for(int i=0;i<maxKmer;i++){
			int numValues = 0;	
			kmerDBFile >> seqName >> numValues;
			
			for(int j=0;j<numValues;j++){						//	for each kmer number get the...
				kmerDBFile >> seqNumber;						//		1. number of sequences with the kmer number
				kmerLocations[i].push_back(seqNumber);			//		2. sequence indices
			}
		}
		kmerDBFile.close();
		
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "readKmerDB");
		exit(1);
	}	
}

/**************************************************************************************************/
int KmerDB::getCount(int kmer) {
	try {
		if (kmer < 0) { return 0; }  //if user gives negative number
		else if (kmer > maxKmer) {	return 0;	}  //or a kmer that is bigger than maxkmer
		else {	return kmerLocations[kmer].size();	}  // kmer is in vector range
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "getCount");
		exit(1);
	}	
}
/**************************************************************************************************/
int KmerDB::getReversed(int kmerNumber) {
	try {
		Kmer kmer(kmerSize);
		
		if (kmerNumber < 0) { return 0; }  //if user gives negative number
		else if (kmerNumber > maxKmer) {	return 0;	}  //or a kmer that is bigger than maxkmer
		else {	return kmer.getReverseKmerNumber(kmerNumber);	}  // kmer is in vector range
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "getReversed");
		exit(1);
	}	
}
/**************************************************************************************************/
vector<int> KmerDB::getSequencesWithKmer(int kmer) {
	try {
		
		vector<int> seqs;
	
		if (kmer < 0) { }  //if user gives negative number
		else if (kmer > maxKmer) {	}  //or a kmer that is bigger than maxkmer
		else {	seqs = kmerLocations[kmer];	}
		
		return seqs;
	}
	catch(exception& e) {
		m->errorOut(e, "KmerDB", "getSequencesWithKmer");
		exit(1);
	}	
}
/**************************************************************************************************/


/**************************************************************************************************/
<?php

namespace Drupal\commerce;

/**
 * Holds a reference to the current locale, resolved on demand.
 *
 * @see \Drupal\commerce\LocaleContext
 */
interface LocaleContextInterface {

  /**
   * Gets the locale for the current request.
   *
   * @return \Drupal\commerce\Locale
   *   The locale.
   */
  public function getLocale();

}

from ..utils import ApiUtil
from ..utils.ApiUtil import Url


class BlueprintHistories:
    def __init__(self, code, auth_token, blueprint_id):
        self.code = code
        self.auth_token = auth_token
        self.blueprint_id = blueprint_id
        url = Url.blueprintHistoriesList(self.blueprint_id, Url.url)
        data = {
                'auth_token': self.auth_token,
               }
        self.blueprint_histories = ApiUtil.requestGet(url, self.code, data)

    def get_blueprint_history(self, id):
        for blueprint_history in self:
            if blueprint_history['id'] == id:
                return blueprint_history

    def __iter__(self):
        for blueprint_history in self.blueprint_histories:
            yield(blueprint_history)

﻿// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal sealed partial class OverloadResolution
    {
        public void BinaryOperatorOverloadResolution(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, BinaryOperatorOverloadResolutionResult result, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);
            Debug.Assert(result.Results.Count == 0);

            // SPEC: An operation of the form x&&y or x||y is processed by applying overload resolution
            // SPEC: as if the operation was written x&y or x|y.

            // SPEC VIOLATION: For compatibility with Dev11, do not apply this rule to built-in conversions.

            BinaryOperatorKind underlyingKind = kind & ~BinaryOperatorKind.Logical;

            // We can do a table lookup for well-known problems in overload resolution.

            BinaryOperatorEasyOut(underlyingKind, left, right, result);
            if (result.Results.Count > 0)
            {
                return;
            }

            // The following is a slight rewording of the specification to emphasize that not all
            // operands of a binary operation need to have a type.

            // SPEC: An operation of the form x op y, where op is an overloadable binary operator is processed as follows:
            // SPEC: The set of candidate user-defined operators provided by the types (if any) of x and y for the 
            // SPEC operation operator op(x, y) is determined. 

            bool hadUserDefinedCandidate = GetUserDefinedOperators(underlyingKind, left, right, result.Results, ref useSiteDiagnostics);

            // @t-mawind
            //   Here, we add in the possibility of having access to a concept
            //   witness defining the binary operator.
            if ((_binder.Flags & BinderFlags.InShim) == 0 && !hadUserDefinedCandidate)
            {
                hadUserDefinedCandidate |= GetBinaryConceptOperators(underlyingKind, left, right, result.Results, ref useSiteDiagnostics);
            }

            // SPEC: If the set of candidate user-defined operators is not empty, then this becomes the set of candidate 
            // SPEC: operators for the operation. Otherwise, the predefined binary operator op implementations, including 
            // SPEC: their lifted forms, become the set of candidate operators for the operation. 

            // Note that the native compiler has a bug in its binary operator overload resolution involving 
            // lifted built-in operators.  The spec says that we should add the lifted and unlifted operators
            // to a candidate set, eliminate the inapplicable operators, and then choose the best of what is left.
            // The lifted operator is defined as, say int? + int? --> int?.  That is not what the native compiler
            // does. The native compiler, rather, effectively says that there are *three* lifted operators:
            // int? + int? --> int?, int + int? --> int? and int? + int --> int?, and it chooses the best operator
            // amongst those choices.  
            //
            // This is a subtle difference; most of the time all it means is that we generate better code because we
            // skip an unnecessary operand conversion to int? when adding int to int?. But some of the time it
            // means that a different user-defined conversion is chosen than the one you would expect, if the
            // operand has a user-defined conversion to both int and int?.
            //
            // Roslyn matches the specification and takes the break from the native compiler.

            if (!hadUserDefinedCandidate)
            {
                result.Results.Clear();
                GetAllBuiltInOperators(kind, left, right, result.Results, ref useSiteDiagnostics);
            }

            // SPEC: The overload resolution rules of 7.5.3 are applied to the set of candidate operators to select the best 
            // SPEC: operator with respect to the argument list (x, y), and this operator becomes the result of the overload 
            // SPEC: resolution process. If overload resolution fails to select a single best operator, a binding-time 
            // SPEC: error occurs.

            BinaryOperatorOverloadResolution(left, right, result, ref useSiteDiagnostics);
        }

        /// <summary>
        /// Populates a list of binary operator results with those from any
        /// witness in scope at the operator site.
        /// </summary>
        /// <param name="kind">
        /// The binary operator kind of the expression.
        /// </param>
        /// <param name="left">
        /// The expression on the left-hand side of the expression.
        /// </param>
        /// <param name="right">
        /// The expression on the right-hand side of the expression.
        /// </param>
        /// <param name="results">
        /// The results list to populate.
        /// </param>
        /// <param name="useSiteDiagnostics">
        /// The set of diagnostics to populate with any errors.
        /// </param>
        /// <returns>
        /// True if we managed to find candidate operators from the concept
        /// witnesses in scope; false otherwise.
        /// </returns>
        private bool GetBinaryConceptOperators(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorAnalysisResult> results, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);

            string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
            var args = ArrayBuilder<BoundExpression>.GetInstance();
            args.Add(left);
            args.Add(right);

            var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
            foreach (var method in GetConceptOperators(name, args.ToImmutableAndFree(), ref useSiteDiagnostics))
            {
                // TODO: nullability
                operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | kind, method.ParameterTypes[0], method.ParameterTypes[1], method.ReturnType, method));
            }

            bool hasCandidates = CandidateOperators(operators, left, right, results, ref useSiteDiagnostics);
            operators.Free();
            return hasCandidates;
        }

        private void AddDelegateOperation(BinaryOperatorKind kind, TypeSymbol delegateType,
            ArrayBuilder<BinaryOperatorSignature> operators)
        {
            switch (kind)
            {
                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, Compilation.GetSpecialType(SpecialType.System_Boolean)));
                    break;

                case BinaryOperatorKind.Addition:
                case BinaryOperatorKind.Subtraction:
                default:
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Delegate, delegateType, delegateType, delegateType));
                    break;
            }
        }

        private void GetDelegateOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right,
            ArrayBuilder<BinaryOperatorSignature> operators, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);
            AssertNotChecked(kind);

            switch (kind)
            {
                case BinaryOperatorKind.Multiplication:
                case BinaryOperatorKind.Division:
                case BinaryOperatorKind.Remainder:
                case BinaryOperatorKind.RightShift:
                case BinaryOperatorKind.LeftShift:
                case BinaryOperatorKind.And:
                case BinaryOperatorKind.Or:
                case BinaryOperatorKind.Xor:
                case BinaryOperatorKind.GreaterThan:
                case BinaryOperatorKind.LessThan:
                case BinaryOperatorKind.GreaterThanOrEqual:
                case BinaryOperatorKind.LessThanOrEqual:
                case BinaryOperatorKind.LogicalAnd:
                case BinaryOperatorKind.LogicalOr:
                    return;

                case BinaryOperatorKind.Addition:
                case BinaryOperatorKind.Subtraction:
                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                    break;

                default:
                    // Unhandled bin op kind in get delegate operation
                    throw ExceptionUtilities.UnexpectedValue(kind);
            }

            var leftType = left.Type;
            var leftDelegate = (object)leftType != null && leftType.IsDelegateType();
            var rightType = right.Type;
            var rightDelegate = (object)rightType != null && rightType.IsDelegateType();

            // If no operands have delegate types then add nothing.
            if (!leftDelegate && !rightDelegate)
            {
                // Even though neither left nor right type is a delegate type,
                // both types might have implicit conversions to System.Delegate type.

                // Spec 7.10.8: Delegate equality operators:
                // Every delegate type implicitly provides the following predefined comparison operators:
                //     bool operator ==(System.Delegate x, System.Delegate y)
                //     bool operator !=(System.Delegate x, System.Delegate y)

                switch (OperatorKindExtensions.Operator(kind))
                {
                    case BinaryOperatorKind.Equal:
                    case BinaryOperatorKind.NotEqual:
                        TypeSymbol systemDelegateType = _binder.GetSpecialType(SpecialType.System_Delegate, _binder.Compilation.DeclarationDiagnostics, left.Syntax);

                        if (Conversions.ClassifyImplicitConversionFromExpression(left, systemDelegateType, ref useSiteDiagnostics).IsValid &&
                            Conversions.ClassifyImplicitConversionFromExpression(right, systemDelegateType, ref useSiteDiagnostics).IsValid)
                        {
                            AddDelegateOperation(kind, systemDelegateType, operators);
                        }

                        break;
                }

                return;
            }

            // We might have a situation like
            //
            // Func<string> + Func<object>
            // 
            // in which case overload resolution should consider both 
            //
            // Func<string> + Func<string>
            // Func<object> + Func<object>
            //
            // are candidates (and it will pick Func<object>). Similarly,
            // we might have something like:
            //
            // Func<object> + Func<dynamic>
            // 
            // in which case neither candidate is better than the other,
            // resulting in an error.
            //
            // We could as an optimization say that if you are adding two completely
            // dissimilar delegate types D1 and D2, that neither is added to the candidate
            // set because neither can possibly be applicable, but let's not go there.
            // Let's just add them to the set and let overload resolution (and the 
            // error recovery heuristics) have at the real candidate set.
            //
            // However, we will take a spec violation for this scenario:
            //
            // SPEC VIOLATION:
            //
            // Technically the spec implies that we ought to be able to compare 
            // 
            // Func<int> x = whatever;
            // bool y = x == ()=>1;
            //
            // The native compiler does not allow this. I see no
            // reason why we ought to allow this. However, a good question is whether
            // the violation ought to be here, where we are determining the operator
            // candidate set, or in overload resolution where we are determining applicability.
            // In the native compiler we did it during candidate set determination, 
            // so let's stick with that.

            if (leftDelegate && rightDelegate)
            {
                // They are both delegate types. Add them both if they are different types.
                AddDelegateOperation(kind, leftType, operators);

                // There is no reason why we can't compare instances of delegate types that are identity convertible.
                // We can't perform + or - operation on them since it is not clear what the return type of such operation should be.
                bool useIdentityConversion = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;

                if (!(useIdentityConversion ? Conversions.HasIdentityConversion(leftType, rightType) : leftType.Equals(rightType)))
                {
                    AddDelegateOperation(kind, rightType, operators);
                }

                return;
            }

            // One of them is a delegate, the other is not.
            TypeSymbol delegateType = leftDelegate ? leftType : rightType;
            BoundExpression nonDelegate = leftDelegate ? right : left;

            if ((kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual)
                && nonDelegate.Kind == BoundKind.UnboundLambda)
            {
                return;
            }

            AddDelegateOperation(kind, delegateType, operators);
        }

        private void GetEnumOperation(BinaryOperatorKind kind, TypeSymbol enumType, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorSignature> operators)
        {
            Debug.Assert((object)enumType != null);
            AssertNotChecked(kind);

            if (!enumType.IsValidEnumType())
            {
                return;
            }

            var underlying = enumType.GetEnumUnderlyingType();
            Debug.Assert((object)underlying != null);
            Debug.Assert(underlying.SpecialType != SpecialType.None);

            var nullable = Compilation.GetSpecialType(SpecialType.System_Nullable_T);
            var nullableEnum = nullable.Construct(enumType);
            var nullableUnderlying = nullable.Construct(underlying);

            switch (kind)
            {
                case BinaryOperatorKind.Addition:
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingAddition, enumType, underlying, enumType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumAddition, underlying, enumType, enumType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingAddition, nullableEnum, nullableUnderlying, nullableEnum));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumAddition, nullableUnderlying, nullableEnum, nullableEnum));
                    break;
                case BinaryOperatorKind.Subtraction:
                    if (Strict)
                    {
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, underlying));
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, underlying, enumType));
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, nullableEnum, nullableEnum, nullableUnderlying));
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, nullableEnum, nullableUnderlying, nullableEnum));
                    }
                    else
                    {
                        // SPEC VIOLATION:
                        // The native compiler has bugs in overload resolution involving binary operator- for enums,
                        // which we duplicate by hardcoding Priority values among the operators. When present on both
                        // methods being compared during overload resolution, Priority values are used to decide between
                        // two candidates (instead of the usual language-specified rules).
                        bool isExactSubtraction = right.Type?.StrippedType() == underlying;
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumSubtraction, enumType, enumType, underlying)
                        { Priority = 2 });
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.EnumAndUnderlyingSubtraction, enumType, underlying, enumType)
                        { Priority = isExactSubtraction ? 1 : 3 });
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumSubtraction, nullableEnum, nullableEnum, nullableUnderlying)
                        { Priority = 12 });
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedEnumAndUnderlyingSubtraction, nullableEnum, nullableUnderlying, nullableEnum)
                        { Priority = isExactSubtraction ? 11 : 13 });

                        // Due to a bug, the native compiler allows "underlying - enum", so Roslyn does as well.
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UnderlyingAndEnumSubtraction, underlying, enumType, enumType)
                        { Priority = 4 });
                        operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LiftedUnderlyingAndEnumSubtraction, nullableUnderlying, nullableEnum, nullableEnum)
                        { Priority = 14 });
                    }
                    break;
                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                case BinaryOperatorKind.GreaterThan:
                case BinaryOperatorKind.LessThan:
                case BinaryOperatorKind.GreaterThanOrEqual:
                case BinaryOperatorKind.LessThanOrEqual:
                    var boolean = Compilation.GetSpecialType(SpecialType.System_Boolean);
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, boolean));
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, nullableEnum, nullableEnum, boolean));
                    break;
                case BinaryOperatorKind.And:
                case BinaryOperatorKind.Or:
                case BinaryOperatorKind.Xor:
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Enum, enumType, enumType, enumType));
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Lifted | BinaryOperatorKind.Enum, nullableEnum, nullableEnum, nullableEnum));
                    break;
            }
        }

        private void GetPointerArithmeticOperators(
            BinaryOperatorKind kind,
            PointerTypeSymbol pointerType,
            ArrayBuilder<BinaryOperatorSignature> operators)
        {
            Debug.Assert((object)pointerType != null);
            AssertNotChecked(kind);

            switch (kind)
            {
                case BinaryOperatorKind.Addition:
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongAddition, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.IntAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType, pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UIntAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType, pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.LongAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType, pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.ULongAndPointerAddition, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType, pointerType));
                    break;
                case BinaryOperatorKind.Subtraction:
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndIntSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_Int32), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndUIntSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt32), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndLongSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerAndULongSubtraction, pointerType, Compilation.GetSpecialType(SpecialType.System_UInt64), pointerType));
                    operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.PointerSubtraction, pointerType, pointerType, Compilation.GetSpecialType(SpecialType.System_Int64)));
                    break;
            }
        }

        private void GetPointerComparisonOperators(
            BinaryOperatorKind kind,
            ArrayBuilder<BinaryOperatorSignature> operators)
        {
            switch (kind)
            {
                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                case BinaryOperatorKind.GreaterThan:
                case BinaryOperatorKind.LessThan:
                case BinaryOperatorKind.GreaterThanOrEqual:
                case BinaryOperatorKind.LessThanOrEqual:
                    var voidPointerType = new PointerTypeSymbol(Compilation.GetSpecialType(SpecialType.System_Void));
                    operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Pointer, voidPointerType, voidPointerType, Compilation.GetSpecialType(SpecialType.System_Boolean)));
                    break;
            }
        }

        private void GetEnumOperations(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorSignature> results)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);
            AssertNotChecked(kind);

            // First take some easy outs:
            switch (kind)
            {
                case BinaryOperatorKind.Multiplication:
                case BinaryOperatorKind.Division:
                case BinaryOperatorKind.Remainder:
                case BinaryOperatorKind.RightShift:
                case BinaryOperatorKind.LeftShift:
                case BinaryOperatorKind.LogicalAnd:
                case BinaryOperatorKind.LogicalOr:
                    return;
            }

            var leftType = left.Type;
            if ((object)leftType != null)
            {
                leftType = leftType.StrippedType();
            }

            var rightType = right.Type;
            if ((object)rightType != null)
            {
                rightType = rightType.StrippedType();
            }

            bool useIdentityConversion;
            switch (kind)
            {
                case BinaryOperatorKind.And:
                case BinaryOperatorKind.Or:
                case BinaryOperatorKind.Xor:
                    // These operations are ambiguous on non-equal identity-convertible types - 
                    // it's not clear what the resulting type of the operation should be:
                    //   C<?>.E operator +(C<dynamic>.E x, C<object>.E y)
                    useIdentityConversion = false;
                    break;

                case BinaryOperatorKind.Addition:
                    // Addition only accepts a single enum type, so operations on non-equal identity-convertible types are not ambiguous. 
                    //   E operator +(E x, U y)
                    //   E operator +(U x, E y)
                    useIdentityConversion = true;
                    break;

                case BinaryOperatorKind.Subtraction:
                    // Subtraction either returns underlying type or only accept a single enum type, so operations on non-equal identity-convertible types are not ambiguous. 
                    //   U operator –(E x, E y)
                    //   E operator –(E x, U y)
                    useIdentityConversion = true;
                    break;

                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                case BinaryOperatorKind.GreaterThan:
                case BinaryOperatorKind.LessThan:
                case BinaryOperatorKind.GreaterThanOrEqual:
                case BinaryOperatorKind.LessThanOrEqual:
                    // Relational operations return Boolean, so operations on non-equal identity-convertible types are not ambiguous. 
                    //   Boolean operator op(C<dynamic>.E, C<object>.E)
                    useIdentityConversion = true;
                    break;

                default:
                    // Unhandled bin op kind in get enum operations
                    throw ExceptionUtilities.UnexpectedValue(kind);
            }

            if ((object)leftType != null)
            {
                GetEnumOperation(kind, leftType, left, right, results);
            }

            if ((object)rightType != null && ((object)leftType == null || !(useIdentityConversion ? Conversions.HasIdentityConversion(rightType, leftType) : rightType.Equals(leftType))))
            {
                GetEnumOperation(kind, rightType, left, right, results);
            }
        }

        private void GetPointerOperators(
            BinaryOperatorKind kind,
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorSignature> results)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);
            AssertNotChecked(kind);

            var leftType = left.Type as PointerTypeSymbol;
            var rightType = right.Type as PointerTypeSymbol;

            if ((object)leftType != null)
            {
                GetPointerArithmeticOperators(kind, leftType, results);
            }

            // The only arithmetic operator that is applicable on two distinct pointer types is
            //   long operator –(T* x, T* y)
            // This operator returns long and so it's not ambiguous to apply it on T1 and T2 that are identity convertible to each other.
            if ((object)rightType != null && ((object)leftType == null || !Conversions.HasIdentityConversion(rightType, leftType)))
            {
                GetPointerArithmeticOperators(kind, rightType, results);
            }

            if ((object)leftType != null || (object)rightType != null)
            {
                // The pointer comparison operators are all "void* OP void*".
                GetPointerComparisonOperators(kind, results);
            }
        }

        private void GetAllBuiltInOperators(BinaryOperatorKind kind, BoundExpression left, BoundExpression right, ArrayBuilder<BinaryOperatorAnalysisResult> results, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // Strip the "checked" off; the checked-ness of the context does not affect which built-in operators
            // are applicable.
            kind = kind.OperatorWithLogical();
            var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
            bool isEquality = kind == BinaryOperatorKind.Equal || kind == BinaryOperatorKind.NotEqual;
            if (isEquality && UseOnlyReferenceEquality(left, right, ref useSiteDiagnostics))
            {
                // As a special case, if the reference equality operator is applicable (and it
                // is not a string or delegate) we do not check any other operators.  This patches
                // what is otherwise a flaw in the language specification.  See 11426.
                GetReferenceEquality(kind, operators);
            }
            else
            {
                this.Compilation.builtInOperators.GetSimpleBuiltInOperators(kind, operators);

                // SPEC 7.3.4: For predefined enum and delegate operators, the only operators
                // considered are those defined by an enum or delegate type that is the binding
                //-time type of one of the operands.
                GetDelegateOperations(kind, left, right, operators, ref useSiteDiagnostics);
                GetEnumOperations(kind, left, right, operators);

                // We similarly limit pointer operator candidates considered.
                GetPointerOperators(kind, left, right, operators);
            }

            CandidateOperators(operators, left, right, results, ref useSiteDiagnostics);
            operators.Free();
        }

        private bool UseOnlyReferenceEquality(BoundExpression left, BoundExpression right, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            return
                BuiltInOperators.IsValidObjectEquality(Conversions, left.Type, left.IsLiteralNull(), right.Type, right.IsLiteralNull(), ref useSiteDiagnostics) &&
                ((object)left.Type == null || (!left.Type.IsDelegateType() && left.Type.SpecialType != SpecialType.System_String && left.Type.SpecialType != SpecialType.System_Delegate)) &&
                ((object)right.Type == null || (!right.Type.IsDelegateType() && right.Type.SpecialType != SpecialType.System_String && right.Type.SpecialType != SpecialType.System_Delegate));
        }

        private void GetReferenceEquality(BinaryOperatorKind kind, ArrayBuilder<BinaryOperatorSignature> operators)
        {
            var @object = Compilation.GetSpecialType(SpecialType.System_Object);
            operators.Add(new BinaryOperatorSignature(kind | BinaryOperatorKind.Object, @object, @object, Compilation.GetSpecialType(SpecialType.System_Boolean)));
        }

        private bool CandidateOperators(
            ArrayBuilder<BinaryOperatorSignature> operators,
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorAnalysisResult> results,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            bool hadApplicableCandidate = false;
            foreach (var op in operators)
            {
                var convLeft = Conversions.ClassifyConversionFromExpression(left, op.LeftType, ref useSiteDiagnostics);
                var convRight = Conversions.ClassifyConversionFromExpression(right, op.RightType, ref useSiteDiagnostics);
                if (convLeft.IsImplicit && convRight.IsImplicit)
                {
                    results.Add(BinaryOperatorAnalysisResult.Applicable(op, convLeft, convRight));
                    hadApplicableCandidate = true;
                }
                else
                {
                    results.Add(BinaryOperatorAnalysisResult.Inapplicable(op, convLeft, convRight));
                }
            }
            return hadApplicableCandidate;
        }

        // Returns an analysis of every matching user-defined binary operator, including whether the
        // operator is applicable or not.

        private bool GetUserDefinedOperators(
            BinaryOperatorKind kind,
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorAnalysisResult> results,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);

            // The following is a slight rewording of the specification to emphasize that not all
            // operands of a binary operation need to have a type.

            // TODO (tomat): The spec needs to be updated to use identity conversion instead of type equality.

            // Spec 7.3.4 Binary operator overload resolution:
            //   An operation of the form x op y, where op is an overloadable binary operator is processed as follows:
            //   The set of candidate user-defined operators provided by the types (if any) of x and y for the 
            //   operation operator op(x, y) is determined. The set consists of the union of the candidate operators
            //   provided by the type of x (if any) and the candidate operators provided by the type of y (if any), 
            //   each determined using the rules of 7.3.5. Candidate operators only occur in the combined set once.

            var operators = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
            TypeSymbol leftType = left.Type;
            TypeSymbol strippedLeftType = leftType?.StrippedType();

            bool hadApplicableCandidate = false;

            if ((object)strippedLeftType != null && !OperatorFacts.DefinitelyHasNoUserDefinedOperators(strippedLeftType))
            {
                hadApplicableCandidate = GetUserDefinedOperators(kind, strippedLeftType, left, right, operators, ref useSiteDiagnostics);
                if (!hadApplicableCandidate)
                {
                    operators.Clear();
                }
            }

            TypeSymbol rightType = right.Type;
            TypeSymbol strippedRightType = rightType?.StrippedType();
            if ((object)strippedRightType != null && !strippedRightType.Equals(strippedLeftType) &&
                !OperatorFacts.DefinitelyHasNoUserDefinedOperators(strippedRightType))
            {
                var rightOperators = ArrayBuilder<BinaryOperatorAnalysisResult>.GetInstance();
                hadApplicableCandidate |= GetUserDefinedOperators(kind, strippedRightType, left, right, rightOperators, ref useSiteDiagnostics);
                AddDistinctOperators(operators, rightOperators);
                rightOperators.Free();
            }

            if (hadApplicableCandidate)
            {
                results.AddRange(operators);
            }

            operators.Free();

            return hadApplicableCandidate;
        }

        private static void AddDistinctOperators(ArrayBuilder<BinaryOperatorAnalysisResult> result, ArrayBuilder<BinaryOperatorAnalysisResult> additionalOperators)
        {
            int initialCount = result.Count;

            foreach (var op in additionalOperators)
            {
                bool equivalentToExisting = false;

                for (int i = 0; i < initialCount; i++)
                {
                    var existingSignature = result[i].Signature;

                    Debug.Assert(op.Signature.Kind.Operator() == existingSignature.Kind.Operator());

                    // Return types must match exactly, parameters might match modulo identity conversion.
                    if (op.Signature.Kind == existingSignature.Kind && // Easy out
                        op.Signature.ReturnType.Equals(existingSignature.ReturnType, TypeCompareKind.ConsiderEverything) &&
                        op.Signature.LeftType.Equals(existingSignature.LeftType, TypeCompareKind.IgnoreDynamicAndTupleNames) &&
                        op.Signature.RightType.Equals(existingSignature.RightType, TypeCompareKind.IgnoreDynamicAndTupleNames) &&
                        op.Signature.Method.ContainingType.Equals(existingSignature.Method.ContainingType, TypeCompareKind.IgnoreDynamicAndTupleNames))
                    {
                        equivalentToExisting = true;
                        break;
                    }
                }

                if (!equivalentToExisting)
                {
                    result.Add(op);
                }
            }
        }

        private bool GetUserDefinedOperators(
            BinaryOperatorKind kind,
            TypeSymbol type0,
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorAnalysisResult> results,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // Spec 7.3.5 Candidate user-defined operators
            // SPEC: Given a type T and an operation operator op(A), where op is an overloadable 
            // SPEC: operator and A is an argument list, the set of candidate user-defined operators 
            // SPEC: provided by T for operator op(A) is determined as follows:

            // SPEC: Determine the type T0. If T is a nullable type, T0 is its underlying type, 
            // SPEC: otherwise T0 is equal to T.

            // (The caller has already passed in the stripped type.)

            // SPEC: For all operator op declarations in T0 and all lifted forms of such operators, 
            // SPEC: if at least one operator is applicable (7.5.3.1) with respect to the argument 
            // SPEC: list A, then the set of candidate operators consists of all such applicable 
            // SPEC: operators in T0. Otherwise, if T0 is object, the set of candidate operators is empty.
            // SPEC: Otherwise, the set of candidate operators provided by T0 is the set of candidate 
            // SPEC: operators provided by the direct base class of T0, or the effective base class of
            // SPEC: T0 if T0 is a type parameter.

            string name = OperatorFacts.BinaryOperatorNameFromOperatorKind(kind);
            var operators = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
            bool hadApplicableCandidates = false;

            NamedTypeSymbol current = type0 as NamedTypeSymbol;
            if ((object)current == null)
            {
                current = type0.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
            }

            if ((object)current == null && type0.IsTypeParameter())
            {
                current = ((TypeParameterSymbol)type0).EffectiveBaseClass(ref useSiteDiagnostics);
            }

            for (; (object)current != null; current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
            {
                operators.Clear();
                GetUserDefinedBinaryOperatorsFromType(current, kind, name, operators);
                results.Clear();
                if (CandidateOperators(operators, left, right, results, ref useSiteDiagnostics))
                {
                    hadApplicableCandidates = true;
                    break;
                }
            }

            operators.Free();

            return hadApplicableCandidates;
        }

        private void GetUserDefinedBinaryOperatorsFromType(
            NamedTypeSymbol type,
            BinaryOperatorKind kind,
            string name,
            ArrayBuilder<BinaryOperatorSignature> operators)
        {
            foreach (MethodSymbol op in type.GetOperators(name))
            {
                // If we're in error recovery, we might have bad operators. Just ignore it.
                if (op.ParameterCount != 2 || op.ReturnsVoid)
                {
                    continue;
                }

                TypeSymbol leftOperandType = op.ParameterTypes[0];
                TypeSymbol rightOperandType = op.ParameterTypes[1];
                TypeSymbol resultType = op.ReturnType;

                operators.Add(new BinaryOperatorSignature(BinaryOperatorKind.UserDefined | kind, leftOperandType, rightOperandType, resultType, op));

                LiftingResult lifting = UserDefinedBinaryOperatorCanBeLifted(leftOperandType, rightOperandType, resultType, kind);

                if (lifting == LiftingResult.LiftOperandsAndResult)
                {
                    operators.Add(new BinaryOperatorSignature(
                        BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind,
                        MakeNullable(leftOperandType), MakeNullable(rightOperandType), MakeNullable(resultType), op));
                }
                else if (lifting == LiftingResult.LiftOperandsButNotResult)
                {
                    operators.Add(new BinaryOperatorSignature(
                        BinaryOperatorKind.Lifted | BinaryOperatorKind.UserDefined | kind,
                        MakeNullable(leftOperandType), MakeNullable(rightOperandType), resultType, op));
                }
            }
        }

        private enum LiftingResult
        {
            NotLifted,
            LiftOperandsAndResult,
            LiftOperandsButNotResult
        }

        private static LiftingResult UserDefinedBinaryOperatorCanBeLifted(TypeSymbol left, TypeSymbol right, TypeSymbol result, BinaryOperatorKind kind)
        {
            // SPEC: For the binary operators + - * / % & | ^ << >> a lifted form of the
            // SPEC: operator exists if the operand and result types are all non-nullable
            // SPEC: value types. The lifted form is constructed by adding a single ?
            // SPEC: modifier to each operand and result type. 
            //
            // SPEC: For the equality operators == != a lifted form of the operator exists
            // SPEC: if the operand types are both non-nullable value types and if the 
            // SPEC: result type is bool. The lifted form is constructed by adding
            // SPEC: a single ? modifier to each operand type.
            //
            // SPEC: For the relational operators > < >= <= a lifted form of the 
            // SPEC: operator exists if the operand types are both non-nullable value
            // SPEC: types and if the result type is bool. The lifted form is 
            // SPEC: constructed by adding a single ? modifier to each operand type.

            if (!left.IsValueType ||
                left.IsNullableType() ||
                !right.IsValueType ||
                right.IsNullableType())
            {
                return LiftingResult.NotLifted;
            }

            switch (kind)
            {
                case BinaryOperatorKind.Equal:
                case BinaryOperatorKind.NotEqual:
                    // Spec violation: can't lift unless the types match.
                    // The spec doesn't require this, but dev11 does and it reduces ambiguity in some cases.
                    if (left != right) return LiftingResult.NotLifted;
                    goto case BinaryOperatorKind.GreaterThan;
                case BinaryOperatorKind.GreaterThan:
                case BinaryOperatorKind.GreaterThanOrEqual:
                case BinaryOperatorKind.LessThan:
                case BinaryOperatorKind.LessThanOrEqual:
                    return result.SpecialType == SpecialType.System_Boolean ?
                        LiftingResult.LiftOperandsButNotResult :
                        LiftingResult.NotLifted;
                default:
                    return result.IsValueType && !result.IsNullableType() ?
                        LiftingResult.LiftOperandsAndResult :
                        LiftingResult.NotLifted;
            }
        }

        // Takes a list of candidates and mutates the list to throw out the ones that are worse than
        // another applicable candidate.
        private void BinaryOperatorOverloadResolution(
            BoundExpression left,
            BoundExpression right,
            BinaryOperatorOverloadResolutionResult result,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // SPEC: Given the set of applicable candidate function members, the best function member in that set is located. 
            // SPEC: If the set contains only one function member, then that function member is the best function member. 

            if (result.SingleValid())
            {
                return;
            }

            // SPEC: Otherwise, the best function member is the one function member that is better than all other function 
            // SPEC: members with respect to the given argument list, provided that each function member is compared to all 
            // SPEC: other function members using the rules in 7.5.3.2. If there is not exactly one function member that is 
            // SPEC: better than all other function members, then the function member invocation is ambiguous and a binding-time 
            // SPEC: error occurs.

            var candidates = result.Results;
            // Try to find a single best candidate
            int bestIndex = GetTheBestCandidateIndex(left, right, candidates, ref useSiteDiagnostics);
            if (bestIndex != -1)
            {
                // Mark all other candidates as worse
                for (int index = 0; index < candidates.Count; ++index)
                {
                    if (candidates[index].Kind != OperatorAnalysisResultKind.Inapplicable && index != bestIndex)
                    {
                        candidates[index] = candidates[index].Worse();
                    }
                }

                return;
            }

            for (int i = 1; i < candidates.Count; ++i)
            {
                if (candidates[i].Kind != OperatorAnalysisResultKind.Applicable)
                {
                    continue;
                }

                // Is this applicable operator better than every other applicable method?
                for (int j = 0; j < i; ++j)
                {
                    if (candidates[j].Kind == OperatorAnalysisResultKind.Inapplicable)
                    {
                        continue;
                    }

                    var better = BetterOperator(candidates[i].Signature, candidates[j].Signature, left, right, ref useSiteDiagnostics);
                    if (better == BetterResult.Left)
                    {
                        candidates[j] = candidates[j].Worse();
                    }
                    else if (better == BetterResult.Right)
                    {
                        candidates[i] = candidates[i].Worse();
                    }
                }
            }
        }

        private int GetTheBestCandidateIndex(
            BoundExpression left,
            BoundExpression right,
            ArrayBuilder<BinaryOperatorAnalysisResult> candidates,
            ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            int currentBestIndex = -1;
            for (int index = 0; index < candidates.Count; index++)
            {
                if (candidates[index].Kind != OperatorAnalysisResultKind.Applicable)
                {
                    continue;
                }

                // Assume that the current candidate is the best if we don't have any
                if (currentBestIndex == -1)
                {
                    currentBestIndex = index;
                }
                else
                {
                    var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, left, right, ref useSiteDiagnostics);
                    if (better == BetterResult.Right)
                    {
                        // The current best is worse
                        currentBestIndex = index;
                    }
                    else if (better != BetterResult.Left)
                    {
                        // The current best is not better
                        currentBestIndex = -1;
                    }
                }
            }

            // Make sure that every candidate up to the current best is worse
            for (int index = 0; index < currentBestIndex; index++)
            {
                if (candidates[index].Kind == OperatorAnalysisResultKind.Inapplicable)
                {
                    continue;
                }

                var better = BetterOperator(candidates[currentBestIndex].Signature, candidates[index].Signature, left, right, ref useSiteDiagnostics);
                if (better != BetterResult.Left)
                {
                    // The current best is not better
                    return -1;
                }
            }

            return currentBestIndex;
        }

        private BetterResult BetterOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, BoundExpression left, BoundExpression right, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            // We use Priority as a tie-breaker to help match native compiler bugs.
            Debug.Assert(op1.Priority.HasValue == op2.Priority.HasValue);
            if (op1.Priority.HasValue && op1.Priority.GetValueOrDefault() != op2.Priority.GetValueOrDefault())
            {
                return (op1.Priority.GetValueOrDefault() < op2.Priority.GetValueOrDefault()) ? BetterResult.Left : BetterResult.Right;
            }

            BetterResult leftBetter = BetterConversionFromExpression(left, op1.LeftType, op2.LeftType, ref useSiteDiagnostics);
            BetterResult rightBetter = BetterConversionFromExpression(right, op1.RightType, op2.RightType, ref useSiteDiagnostics);

            // SPEC: Mp is defined to be a better function member than Mq if:
            // SPEC: * For each argument, the implicit conversion from Ex to Qx is not better than
            // SPEC:   the implicit conversion from Ex to Px, and
            // SPEC: * For at least one argument, the conversion from Ex to Px is better than the 
            // SPEC:   conversion from Ex to Qx.

            // If that is hard to follow, consult this handy chart:
            // op1.Left vs op2.Left     op1.Right vs op2.Right    result
            // -----------------------------------------------------------
            // op1 better               op1 better                op1 better
            // op1 better               neither better            op1 better
            // op1 better               op2 better                neither better
            // neither better           op1 better                op1 better
            // neither better           neither better            neither better
            // neither better           op2 better                op2 better
            // op2 better               op1 better                neither better
            // op2 better               neither better            op2 better
            // op2 better               op2 better                op2 better

            if (leftBetter == BetterResult.Left && rightBetter != BetterResult.Right ||
                leftBetter != BetterResult.Right && rightBetter == BetterResult.Left)
            {
                return BetterResult.Left;
            }

            if (leftBetter == BetterResult.Right && rightBetter != BetterResult.Left ||
                leftBetter != BetterResult.Left && rightBetter == BetterResult.Right)
            {
                return BetterResult.Right;
            }

            // There was no better member on the basis of conversions. Go to the tiebreaking round.

            // SPEC: In case the parameter type sequences P1, P2 and Q1, Q2 are equivalent -- that is, every Pi
            // SPEC: has an identity conversion to the corresponding Qi -- the following tie-breaking rules
            // SPEC: are applied:

            if (Conversions.HasIdentityConversion(op1.LeftType, op2.LeftType) &&
                Conversions.HasIdentityConversion(op1.RightType, op2.RightType))
            {
                // NOTE: The native compiler does not follow these rules; effectively, the native 
                // compiler checks for liftedness first, and then for specificity. For example:
                // struct S<T> where T : struct {
                //   public static bool operator +(S<T> x, int y) { return true; }
                //   public static bool? operator +(S<T>? x, int? y) { return false; }
                // }
                // 
                // bool? b = new S<int>?() + new int?();
                //
                // should reason as follows: the two applicable operators are the lifted
                // form of the first operator and the unlifted second operator. The
                // lifted form of the first operator is *more specific* because int?
                // is more specific than T?.  Therefore it should win. In fact the 
                // native compiler chooses the second operator, because it is unlifted.
                // 
                // Roslyn follows the spec rules; if we decide to change the spec to match
                // the native compiler, or decide to change Roslyn to match the native
                // compiler, we should change the order of the checks here.

                // SPEC: If Mp has more specific parameter types than Mq then Mp is better than Mq.
                BetterResult result = MoreSpecificOperator(op1, op2, ref useSiteDiagnostics);
                if (result == BetterResult.Left || result == BetterResult.Right)
                {
                    return result;
                }

                // SPEC: If one member is a non-lifted operator and the other is a lifted operator,
                // SPEC: the non-lifted one is better.

                bool lifted1 = op1.Kind.IsLifted();
                bool lifted2 = op2.Kind.IsLifted();

                if (lifted1 && !lifted2)
                {
                    return BetterResult.Right;
                }
                else if (!lifted1 && lifted2)
                {
                    return BetterResult.Left;
                }
            }

            return BetterResult.Neither;
        }

        private BetterResult MoreSpecificOperator(BinaryOperatorSignature op1, BinaryOperatorSignature op2, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            TypeSymbol op1Left, op1Right, op2Left, op2Right;
            if ((object)op1.Method != null)
            {
                var p = op1.Method.OriginalDefinition.GetParameters();
                op1Left = p[0].Type;
                op1Right = p[1].Type;
                if (op1.Kind.IsLifted())
                {
                    op1Left = MakeNullable(op1Left);
                    op1Right = MakeNullable(op1Right);
                }
            }
            else
            {
                op1Left = op1.LeftType;
                op1Right = op1.RightType;
            }

            if ((object)op2.Method != null)
            {
                var p = op2.Method.OriginalDefinition.GetParameters();
                op2Left = p[0].Type;
                op2Right = p[1].Type;
                if (op2.Kind.IsLifted())
                {
                    op2Left = MakeNullable(op2Left);
                    op2Right = MakeNullable(op2Right);
                }
            }
            else
            {
                op2Left = op2.LeftType;
                op2Right = op2.RightType;
            }

            var uninst1 = ArrayBuilder<TypeSymbol>.GetInstance();
            var uninst2 = ArrayBuilder<TypeSymbol>.GetInstance();

            uninst1.Add(op1Left);
            uninst1.Add(op1Right);

            uninst2.Add(op2Left);
            uninst2.Add(op2Right);

            BetterResult result = MoreSpecificType(uninst1, uninst2, ref useSiteDiagnostics);

            uninst1.Free();
            uninst2.Free();

            return result;
        }

        [Conditional("DEBUG")]
        private static void AssertNotChecked(BinaryOperatorKind kind)
        {
            Debug.Assert((kind & ~BinaryOperatorKind.Checked) == kind, "Did not expect operator to be checked.  Consider using .Operator() to mask.");
        }
    }
}

package extension

import (
	envoy_config_core_v3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
	hcm_filter "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/durationpb"

	extensions "istio.io/api/extensions/v1alpha1"
	"istio.io/istio/pilot/pkg/model"
	"istio.io/istio/pilot/pkg/networking"
	authzmodel "istio.io/istio/pilot/pkg/security/authz/model"
	securitymodel "istio.io/istio/pilot/pkg/security/model"
)

const (
	wasmFilterType  = "envoy.extensions.filters.http.wasm.v3.Wasm"
	statsFilterName = "istio.stats"
)

var defaultConfigSource = &envoy_config_core_v3.ConfigSource{
	ConfigSourceSpecifier: &envoy_config_core_v3.ConfigSource_Ads{
		Ads: &envoy_config_core_v3.AggregatedConfigSource{},
	},
	ResourceApiVersion: envoy_config_core_v3.ApiVersion_V3,
	// we block proxy init until WasmPlugins are loaded because they might be
	// critical for security (e.g. authn/authz)
	InitialFetchTimeout: &durationpb.Duration{Seconds: 0},
}

// AddWasmPluginsToMutableObjects adds WasmPlugins to HTTP filterChains
// Note that the slices in the map must already be ordered by plugin
// priority! This will be the case for maps returned by PushContext.WasmPlugin()
func AddWasmPluginsToMutableObjects(
	mutable *networking.MutableObjects,
	extensionsMap map[extensions.PluginPhase][]*model.WasmPluginWrapper,
) {
	if mutable == nil {
		return
	}

	for fcIndex, fc := range mutable.FilterChains {
		// we currently only support HTTP
		if fc.ListenerProtocol != networking.ListenerProtocolHTTP {
			continue
		}
		mutable.FilterChains[fcIndex].HTTP = injectExtensions(fc.HTTP, extensionsMap)
	}
}

func injectExtensions(filterChain []*hcm_filter.HttpFilter, exts map[extensions.PluginPhase][]*model.WasmPluginWrapper) []*hcm_filter.HttpFilter {
	// copy map as we'll manipulate it in the loop
	extMap := make(map[extensions.PluginPhase][]*model.WasmPluginWrapper)
	for phase, list := range exts {
		extMap[phase] = []*model.WasmPluginWrapper{}
		extMap[phase] = append(extMap[phase], list...)
	}
	newHTTPFilters := make([]*hcm_filter.HttpFilter, 0)
	// The following algorithm tries to make as few assumptions as possible about the filter
	// chain - it might contain any number of filters that will have to retain their ordering.
	// The one assumption we make is about the ordering of the builtin filters. This is used to
	// position WasmPlugins relatively to the builtin filters according to their phase: when
	// we see the Stats filter, we know that all WasmPlugins with phases AUTHN, AUTHZ and STATS
	// must be injected before it. This method allows us to inject WasmPlugins in the right spots
	// while retaining any filters that were unknown at the time of writing this algorithm,
	// in linear time. The assumed ordering of builtin filters is:
	//
	// 1. Istio JWT, 2. Istio AuthN, 3. RBAC, 4. Stats, 5. Metadata Exchange
	//
	// TODO: how to deal with ext-authz? RBAC will be in the chain twice in that case
	for _, httpFilter := range filterChain {
		switch httpFilter.Name {
		case securitymodel.EnvoyJwtFilterName:
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHN)
			newHTTPFilters = append(newHTTPFilters, httpFilter)
		case securitymodel.AuthnFilterName:
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHN)
			newHTTPFilters = append(newHTTPFilters, httpFilter)
		case authzmodel.RBACHTTPFilterName:
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHN)
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHZ)
			newHTTPFilters = append(newHTTPFilters, httpFilter)
		case statsFilterName:
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHN)
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHZ)
			newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_STATS)
			newHTTPFilters = append(newHTTPFilters, httpFilter)
		default:
			newHTTPFilters = append(newHTTPFilters, httpFilter)
		}
	}
	// append all remaining extensions at the end. This is required because not all builtin filters
	// are always present (e.g. RBAC is only present when an AuthorizationPolicy was created), so
	// we might not have emptied all slices in the map.
	newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHN)
	newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_AUTHZ)
	newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_STATS)
	newHTTPFilters = popAppend(newHTTPFilters, extMap, extensions.PluginPhase_UNSPECIFIED_PHASE)
	return newHTTPFilters
}

func popAppend(list []*hcm_filter.HttpFilter,
	filterMap map[extensions.PluginPhase][]*model.WasmPluginWrapper,
	phase extensions.PluginPhase) []*hcm_filter.HttpFilter {
	for _, ext := range filterMap[phase] {
		list = append(list, toEnvoyHTTPFilter(ext))
	}
	filterMap[phase] = []*model.WasmPluginWrapper{}
	return list
}

func toEnvoyHTTPFilter(wasmPlugin *model.WasmPluginWrapper) *hcm_filter.HttpFilter {
	return &hcm_filter.HttpFilter{
		Name: wasmPlugin.Namespace + "." + wasmPlugin.Name,
		ConfigType: &hcm_filter.HttpFilter_ConfigDiscovery{
			ConfigDiscovery: &envoy_config_core_v3.ExtensionConfigSource{
				ConfigSource: defaultConfigSource,
				TypeUrls:     []string{"type.googleapis.com/" + wasmFilterType},
			},
		},
	}
}

// InsertedExtensionConfigurations returns pre-generated extension configurations added via WasmPlugin.
func InsertedExtensionConfigurations(
	wasmPlugins map[extensions.PluginPhase][]*model.WasmPluginWrapper,
	names []string) []*envoy_config_core_v3.TypedExtensionConfig {
	result := make([]*envoy_config_core_v3.TypedExtensionConfig, 0)
	if len(wasmPlugins) == 0 {
		return result
	}
	hasName := make(map[string]bool)
	for _, n := range names {
		hasName[n] = true
	}
	for _, list := range wasmPlugins {
		for _, p := range list {
			if _, ok := hasName[p.Namespace+"."+p.Name]; !ok {
				continue
			}
			result = append(result, proto.Clone(p.ExtensionConfiguration).(*envoy_config_core_v3.TypedExtensionConfig))
		}
	}
	return result
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.frre.library.data;

/**
 *
 * @author justomiguel
 */
public final class DataSource {
    
    public static String apellidos = "Roma\n" +
"Buzón\n" +
"Sanguino\n" +
"Matesanz\n" +
"Del Rosario\n" +
"Igual\n" +
"San Emeterio\n" +
"José\n" +
"Manresa\n" +
"Planells\n" +
"Victoria\n" +
"Ciobanu\n" +
"Lazar\n" +
"Mayol\n" +
"De Souza\n" +
"Bustillo\n" +
"Lorite\n" +
"Orti\n" +
"Recuero\n" +
"Manchón\n" +
"Salva\n" +
"Verges\n" +
"Miñano\n" +
"Gamiz\n" +
"Villalonga\n" +
"Queralt\n" +
"Bañon\n" +
"Bethencourt\n" +
"Tinoco\n" +
"Cancela\n" +
"Montaña\n" +
"Vivar\n" +
"Ji\n" +
"Espínola\n" +
"Cabanes\n" +
"Arriaga\n" +
"Herrador\n" +
"Limón\n" +
"Mozo\n" +
"Ilie\n" +
"Cara\n" +
"Dolz\n" +
"Pariente\n" +
"Artola\n" +
"Arrizabalaga\n" +
"Fortuny\n" +
"Barquín\n" +
"Vasco\n" +
"Claros\n" +
"Estruch\n" +
"Chinea\n" +
"Benet\n" +
"Villalta\n" +
"Domene\n" +
"Ezquerro\n" +
"Pares\n" +
"Rojano\n" +
"Gras\n" +
"Bohórquez\n" +
"Piris\n" +
"Tendero\n" +
"Bruno\n" +
"Estrella\n" +
"Suero\n" +
"Valenciano\n" +
"Godino\n" +
"Campuzano\n" +
"Garrigós\n" +
"Ligero\n" +
"Humanes\n" +
"Garijo\n" +
"Santacruz\n" +
"Gallart\n" +
"Ollé\n" +
"Santander\n" +
"Isla\n" +
"Comino\n" +
"Rufo\n" +
"Cubillo\n" +
"Llabres\n" +
"Jaume\n" +
"Barrul\n" +
"Ospina\n" +
"Cava\n" +
"Santaella\n" +
"Brown\n" +
"Zapatero\n" +
"Doval\n" +
"Sanjurjo\n" +
"Corredera\n" +
"Gaona\n" +
"Cerón\n" +
"Madariaga\n" +
"Gibert\n" +
"Muller\n" +
"Matute\n" +
"Salgueiro\n" +
"Sillero\n" +
"Villarroya\n" +
"Molto\n" +
"Colas\n" +
"Cárceles\n" +
"Sesma\n" +
"Montaner\n" +
"Carril\n" +
"Dopico\n" +
"Camarasa\n" +
"Olalla\n" +
"Oliveros\n" +
"Londoño\n" +
"Poyatos\n" +
"Villarejo\n" +
"Risco\n" +
"Sarria\n" +
"Callejón\n" +
"Abarca\n" +
"Nava\n" +
"Etxebarria\n" +
"Ulloa\n" +
"Odriozola\n" +
"Marfil\n" +
"Taylor\n" +
"Pol\n" +
"Pernas\n" +
"Arco\n" +
"Rusu\n" +
"Gay\n" +
"Menacho\n" +
"Paños\n" +
"Peñaranda\n" +
"Polanco\n" +
"Palmer\n" +
"Granell\n" +
"Armendáriz\n" +
"Pires\n" +
"Calvet\n" +
"Lama\n" +
"Allende\n" +
"Feito\n" +
"Sureda\n" +
"Arguello\n" +
"Platero\n" +
"Bataller\n" +
"Melchor\n" +
"Tarín\n" +
"Lugo\n" +
"Rubia\n" +
"De los Ríos\n" +
"Serban\n" +
"Olive\n" +
"Cuello\n" +
"Arrebola\n" +
"Cabaleiro\n" +
"Teixidó\n" +
"Balde\n" +
"Riesco\n" +
"Elizalde\n" +
"Stefan\n" +
"Astorga\n" +
"Castelo\n" +
"Pedreira\n" +
"Bocanegra\n" +
"Caño\n" +
"Bel\n" +
"Fariñas\n" +
"Arredondo\n" +
"Juez\n" +
"Orgaz\n" +
"Riba\n" +
"Torrens\n" +
"Gordon\n" +
"Gala\n" +
"Ezquerra\n" +
"Magaña\n" +
"Doblas\n" +
"Adrian\n" +
"Corredor\n" +
"Llamazares\n" +
"Presa\n" +
"Oñate\n" +
"Mestres\n" +
"Cabral\n" +
"Capel\n" +
"Gaya\n" +
"Cuadra\n" +
"Crespi\n" +
"Carazo\n" +
"Ovejero\n" +
"Mamani\n" +
"Clavería\n" +
"Falco\n" +
"Sebastia\n" +
"Cantarero\n" +
"Vigil\n" +
"Solorzano\n" +
"Cavero\n" +
"Salom\n" +
"Alejo\n" +
"Rubiales\n" +
"Pintos\n" +
"Albarracín\n" +
"Malo\n" +
"Larios\n" +
"Almodóvar\n" +
"Justicia\n" +
"Soares\n" +
"Molins\n" +
"Doncel\n" +
"Holguín\n" +
"Moraga\n" +
"Lanza\n" +
"Nogués\n" +
"Escalera\n" +
"Calviño\n" +
"Orihuela\n" +
"Arnedo\n" +
"Palenzuela\n" +
"Armero\n" +
"Monserrat\n" +
"Bonillo\n" +
"Cacho\n" +
"Guedes\n" +
"Barber\n" +
"Ariño\n" +
"Troya\n" +
"Gual\n" +
"Hortelano\n" +
"Gavira\n" +
"Rayo\n" +
"Corominas\n" +
"Williams\n" +
"Dimitrova\n" +
"Gomáriz\n" +
"Lechuga\n" +
"Puebla\n" +
"Mula\n" +
"Augusto\n" +
"Terol\n" +
"Traore\n" +
"Magdaleno\n" +
"Illescas\n" +
"Etxeberria\n" +
"Cremades\n" +
"Marzo\n" +
"Gomila\n" +
"Gregori\n" +
"Montañez\n" +
"Adrover\n" +
"Marchante\n" +
"Zapico\n" +
"Carrascal\n" +
"Elena\n" +
"Villalón\n" +
"Ortín\n" +
"Feliz\n" +
"Lemos\n" +
"Matei\n" +
"Aldea\n" +
"Elorza\n" +
"Adame\n" +
"Garate\n" +
"Fornes\n" +
"Vilaplana\n" +
"Insua\n" +
"Obregón\n" +
"Escolar\n" +
"Llobet\n" +
"Adell\n" +
"Guaman\n" +
"Illán\n" +
"Bouza\n" +
"Castellón\n" +
"Boluda\n" +
"Rioja\n" +
"Portilla\n" +
"Pallas\n" +
"Hu\n" +
"Enrique\n" +
"Trueba\n" +
"Junquera\n" +
"Mayordomo\n" +
"Padin\n" +
"Fandiño\n" +
"Folch\n" +
"Munuera\n" +
"Agustín\n" +
"Góngora\n" +
"Baz\n" +
"Muela\n" +
"Melgarejo\n" +
"Benedicto\n" +
"Laborda\n" +
"Zabaleta\n" +
"Cea\n" +
"Boada\n" +
"Leyva\n" +
"Aranguren\n" +
"Teijeiro\n" +
"Puentes\n" +
"Castellá\n" +
"Salvado\n" +
"Morant\n" +
"Tejeda\n" +
"Antonio\n" +
"Madueño\n" +
"Lasheras\n" +
"Utrilla\n" +
"Cubas\n" +
"Vinuesa\n" +
"Ivars\n" +
"Ricart\n" +
"Viña\n" +
"Darias\n" +
"Verde\n" +
"Gallegos\n" +
"Galdeano\n" +
"David\n" +
"Corona\n" +
"Berbel\n" +
"Escobedo\n" +
"Mendieta\n" +
"Uría\n" +
"Restrepo\n" +
"Ciudad\n" +
"Malló\n" +
"Espí\n" +
"Candel\n" +
"Ledo\n" +
"Alcañiz\n" +
"Piera\n" +
"Varas\n" +
"Jove\n" +
"Palacín\n" +
"Camarena\n" +
"Galdón\n" +
"Belenguer\n" +
"Reverte\n" +
"Pont\n" +
"Lopera\n" +
"Fábregas\n" +
"Roura\n" +
"Collazo\n" +
"De Sousa\n" +
"Canosa\n" +
"Berrio\n" +
"Montserrat\n" +
"Urbina\n" +
"Magro\n" +
"Estepa\n" +
"Miñana\n" +
"Batalla\n" +
"Bouzas\n" +
"Pimentel\n" +
"Vaz\n" +
"Mesas\n" +
"Cruzado\n" +
"Regueira\n" +
"Hermosilla\n" +
"Armenteros\n" +
"Flor\n" +
"Azcona\n" +
"Días\n" +
"Goncalves\n" +
"Troncoso\n" +
"Collantes\n" +
"Sicilia\n" +
"Jiang\n" +
"Novillo\n" +
"Hernán\n" +
"Molano\n" +
"Georgieva\n" +
"Córdova\n" +
"Vilalta\n" +
"Oliveras\n" +
"Larrosa\n" +
"Del Hoyo\n" +
"Machuca\n" +
"Quijada\n" +
"Lerma\n" +
"Del Cerro\n" +
"Mayorga\n" +
"Girona\n" +
"Cañellas\n" +
"Brenes\n" +
"Lumbreras\n" +
"Brotons\n" +
"Chamizo\n" +
"Dios\n" +
"Malagón\n" +
"Moscoso\n" +
"Gamarra\n" +
"Mancera\n" +
"Rodas\n" +
"Llacer\n" +
"Gascó\n" +
"Marquina\n" +
"Zarco\n" +
"Villaescusa\n" +
"Boza\n" +
"Seijo\n" +
"Cabrerizo\n" +
"Torralbo\n" +
"Comesaña\n" +
"Tamarit\n" +
"Gelabert\n" +
"Piquer\n" +
"Pelegrín\n" +
"Hussain\n" +
"Trejo\n" +
"Del Toro\n" +
"Fabra\n" +
"Agustí\n" +
"Callejas\n" +
"Cejudo\n" +
"Perona\n" +
"Balboa\n" +
"Marchena\n" +
"Llop\n" +
"Prades\n" +
"Magán\n" +
"Requejo\n" +
"Hernanz\n" +
"Jareño\n" +
"Moure\n" +
"Cedeño\n" +
"Toral\n" +
"Vivo\n" +
"Bernat\n" +
"Ocampo\n" +
"Gargallo\n" +
"Amengual\n" +
"Alegría\n" +
"Batlle\n" +
"Rodero\n" +
"Gamboa\n" +
"Bárcena\n" +
"Tortajada\n" +
"Pou\n" +
"Callejo\n" +
"Monedero\n" +
"Aracil\n" +
"Gándara\n" +
"Hevia\n" +
"Coloma\n" +
"Hueso\n" +
"Barrado\n" +
"Maeso\n" +
"Dimitrov\n" +
"Galeano\n" +
"Azorín\n" +
"Somoza\n" +
"Asensi\n" +
"Trigueros\n" +
"Borreguero\n" +
"Borrell\n" +
"Baro\n" +
"Bauza\n" +
"Mur\n" +
"Corpas\n" +
"Cuadros\n" +
"Rendón\n" +
"Zarza\n" +
"Villarroel\n" +
"Herráez\n" +
"Pachón\n" +
"Pose\n" +
"Guillamón\n" +
"Bertomeu\n" +
"Alcocer\n" +
"De la Hoz\n" +
"Galarza\n" +
"Castiñeira\n" +
"Iñigo\n" +
"Gabaldón\n" +
"De los Reyes\n" +
"Piedra\n" +
"Calvente\n" +
"Tabares\n" +
"Gaitán\n" +
"Gijón\n" +
"Escolano\n" +
"Serrat\n" +
"Valdivieso\n" +
"Alberola\n" +
"Bayona\n" +
"Patón\n" +
"Losa\n" +
"Popescu\n" +
"Galisteo\n" +
"Oltra\n" +
"Sirvent\n" +
"Chinchilla\n" +
"Huang\n" +
"Avalos\n" +
"Vicario\n" +
"Quintela\n" +
"Vicens\n" +
"Corbalán\n" +
"Varona\n" +
"Algaba\n" +
"Aceituno\n" +
"Jin\n" +
"Noya\n" +
"Tercero\n" +
"Bajo\n" +
"Calabuig\n" +
"Salado\n" +
"Llado\n" +
"Colmenero\n" +
"Hita\n" +
"Gheorghe\n" +
"Notario\n" +
"Vasile\n" +
"Barrachina\n" +
"Pitarch\n" +
"March\n" +
"Torras\n" +
"Fresneda\n" +
"Arango\n" +
"Rego\n" +
"Melo\n" +
"Cruces\n" +
"Pagan\n" +
"Stan\n" +
"Velarde\n" +
"Pajuelo\n" +
"Córcoles\n" +
"Solsona\n" +
"Guillem\n" +
"Quispe\n" +
"Correas\n" +
"Lavín\n" +
"Saborido\n" +
"Espina\n" +
"Zarate\n" +
"Curiel\n" +
"Palencia\n" +
"Mulet\n" +
"Solera\n" +
"De Lucas\n" +
"Monzo\n" +
"Olea\n" +
"Aller\n" +
"Almendros\n" +
"Del Val\n" +
"Rosario\n" +
"Clavero\n" +
"Bedoya\n" +
"Curto\n" +
"De Blas\n" +
"Ballesta\n" +
"Mihai\n" +
"Georgiev\n" +
"Bernárdez\n" +
"Goicoechea\n" +
"Negrín\n" +
"Cao\n" +
"Pintor\n" +
"Barreda\n" +
"Franch\n" +
"Aguero\n" +
"Edo\n" +
"Bellón\n" +
"Lasa\n" +
"Bernad\n" +
"Morente\n" +
"Huete\n" +
"Izaguirre\n" +
"Guasch\n" +
"Mercader\n" +
"Tolosa\n" +
"Albero\n" +
"Pastrana\n" +
"Araque\n" +
"Cueva\n" +
"Mondéjar\n" +
"Stoica\n" +
"Constantin\n" +
"Coto\n" +
"Barquero\n" +
"Blanca\n" +
"Liñán\n" +
"Romeu\n" +
"Rangel\n" +
"Mate\n" +
"Yepes\n" +
"De Juan\n" +
"Pombo\n" +
"Pinedo\n" +
"Regalado\n" +
"Egido\n" +
"Curbelo\n" +
"Artero\n" +
"Navalón\n" +
"Estébanez\n" +
"Ortigosa\n" +
"Parreño\n" +
"Del Rey\n" +
"Llinares\n" +
"Cortina\n" +
"Vivancos\n" +
"Canet\n" +
"Jones\n" +
"Selles\n" +
"Acero\n" +
"Feliu\n" +
"Matilla\n" +
"Motos\n" +
"Arrabal\n" +
"Simarro\n" +
"Borrero\n" +
"Kaur\n" +
"Barral\n" +
"Gadea\n" +
"Lopes\n" +
"Blanes\n" +
"Iranzo\n" +
"Múgica\n" +
"Samaniego\n" +
"Nuño\n" +
"Toscano\n" +
"Carreira\n" +
"Rozas\n" +
"Baquero\n" +
"Lage\n" +
"Funes\n" +
"Alguacil\n" +
"Artigas\n" +
"Borges\n" +
"Bas\n" +
"Liébana\n" +
"Andrades\n" +
"Matamoros\n" +
"Pan\n" +
"Moll\n" +
"Duro\n" +
"Lastra\n" +
"Masip\n" +
"Ferrándiz\n" +
"Vendrell\n" +
"Barrionuevo\n" +
"Pereiro\n" +
"Marina\n" +
"Reinoso\n" +
"Mendizábal\n" +
"Yang\n" +
"Higuera\n" +
"Iborra\n" +
"Gonzálvez\n" +
"Amo\n" +
"Torrecilla\n" +
"Alcolea\n" +
"Valbuena\n" +
"Rosselló\n" +
"Torrico\n" +
"Laso\n" +
"Cayuela\n" +
"Viana\n" +
"Romeo\n" +
"Da Costa\n" +
"Couto\n" +
"Lavado\n" +
"Vicent\n" +
"Rúa\n" +
"Mendes\n" +
"Niño\n" +
"Yanes\n" +
"San Román\n" +
"Posada\n" +
"Pantoja\n" +
"Viejo\n" +
"Orta\n" +
"Arnal\n" +
"Barcia\n" +
"Varo\n" +
"Béjar\n" +
"Brea\n" +
"Cases\n" +
"Devesa\n" +
"Graña\n" +
"Parrado\n" +
"Torrecillas\n" +
"Gonzales\n" +
"Uceda\n" +
"Abadía\n" +
"Orts\n" +
"Busquets\n" +
"Ferri\n" +
"Aramburu\n" +
"Lahoz\n" +
"Ferro\n" +
"Vieira\n" +
"Casillas\n" +
"Landa\n" +
"Pablos\n" +
"Llano\n" +
"Quílez\n" +
"Roque\n" +
"Águila\n" +
"Diz\n" +
"Galiana\n" +
"Barrena\n" +
"Camarero\n" +
"Morata\n" +
"Torrente\n" +
"Cózar\n" +
"Rosas\n" +
"Fontán\n" +
"Artiles\n" +
"Monfort\n" +
"Huguet\n" +
"Seijas\n" +
"Del Barrio\n" +
"Nebot\n" +
"Mengual\n" +
"Mirón\n" +
"Venegas\n" +
"Salvatierra\n" +
"Pablo\n" +
"Escamilla\n" +
"Pedrero\n" +
"Oller\n" +
"Dumitru\n" +
"Carnero\n" +
"Parras\n" +
"Abascal\n" +
"Cutillas\n" +
"Félix\n" +
"Trinidad\n" +
"Henríquez\n" +
"Alsina\n" +
"Mangas\n" +
"Antelo\n" +
"Romano\n" +
"Terán\n" +
"Coronel\n" +
"Bolívar\n" +
"Vilariño\n" +
"Ramis\n" +
"Colom\n" +
"Torrijos\n" +
"Nicolau\n" +
"De Pedro\n" +
"Lledó\n" +
"Conejero\n" +
"Calzado\n" +
"Quintas\n" +
"Vigo\n" +
"Diop\n" +
"Aguayo\n" +
"Jáuregui\n" +
"Campaña\n" +
"Canal\n" +
"Armengol\n" +
"Iñiguez\n" +
"Cuartero\n" +
"Uribe\n" +
"Miras\n" +
"Canals\n" +
"Fabregat\n" +
"Sendra\n" +
"Riveiro\n" +
"Rosillo\n" +
"Cerrato\n" +
"Bazán\n" +
"Gandía\n" +
"Tébar\n" +
"Asencio\n" +
"Machín\n" +
"Escalona\n" +
"Amaro\n" +
"Barco\n" +
"Pradas\n" +
"Villarreal\n" +
"Caraballo\n" +
"Barón\n" +
"Plata\n" +
"Roa\n" +
"Mulero\n" +
"Sotelo\n" +
"Tornero\n" +
"Alcón\n" +
"Pomares\n" +
"De Paz\n" +
"Caravaca\n" +
"Cantón\n" +
"Castejón\n" +
"Concepción\n" +
"Dura\n" +
"Almazán\n" +
"Castell\n" +
"Utrera\n" +
"Rocamora\n" +
"Moliner\n" +
"Arguelles\n" +
"Sedano\n" +
"Manjón\n" +
"Gázquez\n" +
"Arregui\n" +
"Macho\n" +
"Vilas\n" +
"Loureiro\n" +
"Infantes\n" +
"Fortes\n" +
"Monroy\n" +
"Panadero\n" +
"Granero\n" +
"Milla\n" +
"Velásquez\n" +
"Cabañas\n" +
"Morell\n" +
"Moldovan\n" +
"Morgado\n" +
"Maqueda\n" +
"Carbó\n" +
"Valladares\n" +
"Vacas\n" +
"Cepeda\n" +
"Gabarre\n" +
"Carracedo\n" +
"Tenorio\n" +
"Castrillo\n" +
"Triguero\n" +
"Zambrana\n" +
"Morante\n" +
"Plana\n" +
"Priego\n" +
"Arcas\n" +
"Moraleda\n" +
"Ndiaye\n" +
"Querol\n" +
"Abella\n" +
"Ribeiro\n" +
"Peñas\n" +
"Muro\n" +
"Raposo\n" +
"Zheng\n" +
"Porto\n" +
"Puche\n" +
"Palmero\n" +
"Siles\n" +
"Bayo\n" +
"De Frutos\n" +
"Almansa\n" +
"Berlanga\n" +
"Regueiro\n" +
"Agüera\n" +
"Pozuelo\n" +
"Ivanova\n" +
"Roncero\n" +
"Bertrán\n" +
"Barahona\n" +
"De Oliveira\n" +
"María\n" +
"Mico\n" +
"Reguera\n" +
"Justo\n" +
"Terrón\n" +
"Aguiar\n" +
"Pelayo\n" +
"Jodar\n" +
"Teixeira\n" +
"Lluch\n" +
"Radu\n" +
"Carbajo\n" +
"Cisneros\n" +
"Montañés\n" +
"Clavijo\n" +
"Párraga\n" +
"Noriega\n" +
"Montesdeoca\n" +
"Cañada\n" +
"Gea\n" +
"Albarrán\n" +
"Ginés\n" +
"Miguélez\n" +
"Escrivá\n" +
"Sarabia\n" +
"Rabadán\n" +
"Cortijo\n" +
"Roda\n" +
"De Jesús\n" +
"Alberdi\n" +
"Cadenas\n" +
"Antequera\n" +
"Cascales\n" +
"Garrote\n" +
"Buitrago\n" +
"Picón\n" +
"Granda\n" +
"Ángel\n" +
"Giráldez\n" +
"Company\n" +
"Zorrilla\n" +
"Sanabria\n" +
"De Andrés\n" +
"Cuervo\n" +
"Castillejo\n" +
"Zhu\n" +
"Donaire\n" +
"Meneses\n" +
"Valentín\n" +
"Triviño\n" +
"Paya\n" +
"Blanch\n" +
"De la Calle\n" +
"Amigo\n" +
"Portero\n" +
"Dalmau\n" +
"Porta\n" +
"Gregorio\n" +
"De Pablo\n" +
"Carpintero\n" +
"Mediavilla\n" +
"Busto\n" +
"Milán\n" +
"Mancebo\n" +
"Monreal\n" +
"Villalobos\n" +
"Porcel\n" +
"Anguita\n" +
"Molla\n" +
"Miquel\n" +
"Piñol\n" +
"Poza\n" +
"Madrigal\n" +
"Torrent\n" +
"Larrañaga\n" +
"Val\n" +
"Pita\n" +
"Zúñiga\n" +
"Tormo\n" +
"Barreto\n" +
"Blas\n" +
"Donoso\n" +
"Rama\n" +
"Escalante\n" +
"De la Vega\n" +
"Barriga\n" +
"Bou\n" +
"Vadillo\n" +
"Montalbán\n" +
"Capilla\n" +
"Ayllón\n" +
"Salido\n" +
"Pintado\n" +
"Garay\n" +
"Martel\n" +
"Guardia\n" +
"Iriarte\n" +
"Cabo\n" +
"Quintanilla\n" +
"Hierro\n" +
"Ali\n" +
"Espinar\n" +
"Corbacho\n" +
"Torrado\n" +
"Albaladejo\n" +
"Puga\n" +
"Sabaté\n" +
"Ferrández\n" +
"Vilanova\n" +
"Garmendia\n" +
"Briones\n" +
"Monje\n" +
"Esparza\n" +
"Bayón\n" +
"Aragonés\n" +
"Matías\n" +
"Benavent\n" +
"Maestro\n" +
"Ropero\n" +
"Asenjo\n" +
"Palomar\n" +
"Pagés\n" +
"Candela\n" +
"Del Amo\n" +
"Casanovas\n" +
"Agulló\n" +
"Lorca\n" +
"Coello\n" +
"Déniz\n" +
"Arrieta\n" +
"Gallo\n" +
"Daza\n" +
"De Haro\n" +
"Simo\n" +
"Salamanca\n" +
"De la Peña\n" +
"Llorca\n" +
"Cerro\n" +
"Ferreras\n" +
"Cabrero\n" +
"Casero\n" +
"Montalvo\n" +
"Mérida\n" +
"Pajares\n" +
"Rius\n" +
"Mato\n" +
"Verdejo\n" +
"Anaya\n" +
"Vara\n" +
"De la Iglesia\n" +
"Reche\n" +
"Larrea\n" +
"Urrutia\n" +
"Jover\n" +
"Higueras\n" +
"Elías\n" +
"Cueto\n" +
"Bernardo\n" +
"Conejo\n" +
"Ivanov\n" +
"Casares\n" +
"Valderrama\n" +
"Pueyo\n" +
"Ferrera\n" +
"Calzada\n" +
"Chica\n" +
"Ruz\n" +
"Gomis\n" +
"Fernandes\n" +
"Dorta\n" +
"Tur\n" +
"Ugarte\n" +
"Florido\n" +
"Jorda\n" +
"Morato\n" +
"Pereda\n" +
"Abreu\n" +
"Benavente\n" +
"Gavilán\n" +
"Lillo\n" +
"Melgar\n" +
"Barbosa\n" +
"Guirao\n" +
"Paris\n" +
"Betancor\n" +
"Matos\n" +
"Samper\n" +
"Plasencia\n" +
"Barrientos\n" +
"Mármol\n" +
"Casals\n" +
"Espino\n" +
"Saldaña\n" +
"Morera\n" +
"Nogueira\n" +
"Gaspar\n" +
"Julia\n" +
"Oviedo\n" +
"Bastida\n" +
"San Miguel\n" +
"Cardoso\n" +
"Valcárcel\n" +
"Muriel\n" +
"Carranza\n" +
"Olivera\n" +
"Mercado\n" +
"Holgado\n" +
"Castells\n" +
"Tejera\n" +
"Carpio\n" +
"Camino\n" +
"Morilla\n" +
"Gabarri\n" +
"Torrejón\n" +
"Lima\n" +
"Amat\n" +
"Julián\n" +
"Reig\n" +
"Meseguer\n" +
"Smith\n" +
"Martins\n" +
"Campoy\n" +
"Quiñones\n" +
"Amado\n" +
"Chaparro\n" +
"Seco\n" +
"Tudela\n" +
"Cornejo\n" +
"Garriga\n" +
"San Juan\n" +
"Mañas\n" +
"Cerdán\n" +
"Monteagudo\n" +
"Aliaga\n" +
"Portela\n" +
"Aroca\n" +
"Gilabert\n" +
"Maza\n" +
"Trillo\n" +
"Cristóbal\n" +
"Piña\n" +
"Popa\n" +
"Espín\n" +
"Megias\n" +
"Gomes\n" +
"Figueras\n" +
"Cabanillas\n" +
"Gisbert\n" +
"Llanos\n" +
"Berrocal\n" +
"Cañizares\n" +
"Perello\n" +
"Zhou\n" +
"Guevara\n" +
"Liu\n" +
"Arnaiz\n" +
"Galiano\n" +
"Sans\n" +
"Roselló\n" +
"Feijoo\n" +
"Wu\n" +
"Montenegro\n" +
"Postigo\n" +
"Uriarte\n" +
"Canto\n" +
"Guirado\n" +
"Flórez\n" +
"Colomer\n" +
"Hoyos\n" +
"Guardiola\n" +
"Mansilla\n" +
"Verdugo\n" +
"Rio\n" +
"Capdevila\n" +
"Cordón\n" +
"Del Moral\n" +
"Sacristán\n" +
"Antúnez\n" +
"Vico\n" +
"Rosell\n" +
"Fonseca\n" +
"Centeno\n" +
"Sempere\n" +
"Belda\n" +
"Comas\n" +
"Elvira\n" +
"Nieves\n" +
"Benavides\n" +
"Silvestre\n" +
"Cantos\n" +
"Yagüe\n" +
"Lora\n" +
"Palazón\n" +
"Quero\n" +
"Alemany\n" +
"Torralba\n" +
"Vaca\n" +
"Neira\n" +
"Jimeno\n" +
"Jaime\n" +
"Hermoso\n" +
"Parejo\n" +
"Labrador\n" +
"Herraiz\n" +
"Pop\n" +
"Ramiro\n" +
"Sousa\n" +
"Caamaño\n" +
"Chico\n" +
"Li\n" +
"Nevado\n" +
"Toledano\n" +
"Espinoza\n" +
"De Dios\n" +
"Pellicer\n" +
"Revilla\n" +
"Vegas\n" +
"Rus\n" +
"Farré\n" +
"Calatayud\n" +
"Antolín\n" +
"Ribes\n" +
"Amores\n" +
"Adán\n" +
"Riquelme\n" +
"Vilches\n" +
"Mera\n" +
"Diallo\n" +
"Segui\n" +
"Viera\n" +
"Guisado\n" +
"Perera\n" +
"Botella\n" +
"Arellano\n" +
"Carrascosa\n" +
"Girón\n" +
"Romo\n" +
"Álamo\n" +
"Novo\n" +
"Arnau\n" +
"Amor\n" +
"Codina\n" +
"Quiroga\n" +
"Andújar\n" +
"Solana\n" +
"Gordo\n" +
"Sabater\n" +
"Torregrosa\n" +
"Oliveira\n" +
"Pico\n" +
"Mestre\n" +
"Ureña\n" +
"Frutos\n" +
"Cañadas\n" +
"Rial\n" +
"Palau\n" +
"Xu\n" +
"Céspedes\n" +
"Gamero\n" +
"Parada\n" +
"De los Santos\n" +
"Carrero\n" +
"Picazo\n" +
"Lema\n" +
"Goñi\n" +
"Sepúlveda\n" +
"Sales\n" +
"Narváez\n" +
"Zurita\n" +
"Mir\n" +
"Tovar\n" +
"Revuelta\n" +
"Pedraza\n" +
"Acuña\n" +
"Planas\n" +
"Fuente\n" +
"Cañete\n" +
"Piqueras\n" +
"Meléndez\n" +
"Quiles\n" +
"Mariscal\n" +
"Ye\n" +
"Valdivia\n" +
"Fariña\n" +
"Hinojosa\n" +
"Cuellar\n" +
"Fidalgo\n" +
"Mayoral\n" +
"Cervantes\n" +
"Vivas\n" +
"Costas\n" +
"Coca\n" +
"Rodenas\n" +
"Parrilla\n" +
"Saura\n" +
"Camps\n" +
"Melian\n" +
"Boix\n" +
"Martorell\n" +
"Arana\n" +
"Montilla\n" +
"Lloret\n" +
"Encinas\n" +
"Buendía\n" +
"Molinero\n" +
"Carro\n" +
"Monzón\n" +
"Giraldo\n" +
"Palacio\n" +
"Bernabéu\n" +
"Peiro\n" +
"Tome\n" +
"Sanmartín\n" +
"Lamas\n" +
"Badía\n" +
"Toribio\n" +
"Coronado\n" +
"Pina\n" +
"Cubero\n" +
"Peral\n" +
"Téllez\n" +
"Mayo\n" +
"Bernabé\n" +
"Mariño\n" +
"Barbera\n" +
"Talavera\n" +
"Ibarra\n" +
"Puerta\n" +
"Zamorano\n" +
"Granado\n" +
"Matas\n" +
"Espada\n" +
"Prat\n" +
"Bolaños\n" +
"Caparros\n" +
"De Diego\n" +
"Mejía\n" +
"Balaguer\n" +
"Puerto\n" +
"Quevedo\n" +
"Iniesta\n" +
"España\n" +
"Morillas\n" +
"Montaño\n" +
"Perdomo\n" +
"Herreros\n" +
"Segarra\n" +
"Macia\n" +
"De las Heras\n" +
"Acedo\n" +
"Hermida\n" +
"Francés\n" +
"Torre\n" +
"Rodrigues\n" +
"Lujan\n" +
"Merchán\n" +
"Trigo\n" +
"Francisco\n" +
"Robledo\n" +
"Almagro\n" +
"Checa\n" +
"Ares\n" +
"Úbeda\n" +
"Sevillano\n" +
"Ortuño\n" +
"Raya\n" +
"Manzanares\n" +
"Cifuentes\n" +
"Zhang\n" +
"Echevarría\n" +
"Medrano\n" +
"Teruel\n" +
"Lucena\n" +
"Dueñas\n" +
"Canales\n" +
"Villena\n" +
"Novoa\n" +
"Jaramillo\n" +
"Sampedro\n" +
"Del Olmo\n" +
"Villaverde\n" +
"Mota\n" +
"Pinilla\n" +
"Manrique\n" +
"Miro\n" +
"Pedrosa\n" +
"Atienza\n" +
"Echeverría\n" +
"Diego\n" +
"Machado\n" +
"Míguez\n" +
"Viñas\n" +
"Berenguer\n" +
"Nogales\n" +
"Galera\n" +
"Maroto\n" +
"Cerda\n" +
"Yuste\n" +
"Albert\n" +
"Alemán\n" +
"Infante\n" +
"Ribera\n" +
"Maya\n" +
"Peñalver\n" +
"Batista\n" +
"Manso\n" +
"Alves\n" +
"Álvaro\n" +
"Morón\n" +
"Barros\n" +
"Patiño\n" +
"De León\n" +
"Tamayo\n" +
"Abril\n" +
"Prados\n" +
"Padrón\n" +
"Diéguez\n" +
"Báez\n" +
"Ayuso\n" +
"Vásquez\n" +
"Bejarano\n" +
"Amorós\n" +
"Prada\n" +
"Sandoval\n" +
"Lobo\n" +
"Barrero\n" +
"Arteaga\n" +
"San Martin\n" +
"Del Campo\n" +
"Barea\n" +
"Taboada\n" +
"Almeida\n" +
"Climent\n" +
"Tortosa\n" +
"Montiel\n" +
"Mayor\n" +
"Catalá\n" +
"Moro\n" +
"Jordán\n" +
"Jara\n" +
"Fraga\n" +
"Orellana\n" +
"Verdú\n" +
"Ferrando\n" +
"Conesa\n" +
"Jerez\n" +
"Veiga\n" +
"Zabala\n" +
"Mari\n" +
"Sarmiento\n" +
"Ripoll\n" +
"Armas\n" +
"Salmerón\n" +
"Cazorla\n" +
"Pallares\n" +
"Rocha\n" +
"Ferre\n" +
"Tello\n" +
"Bustos\n" +
"Seoane\n" +
"Sobrino\n" +
"Sanjuán\n" +
"Tejedor\n" +
"Acevedo\n" +
"Ledesma\n" +
"Ahmed\n" +
"Monge\n" +
"Vilar\n" +
"Valera\n" +
"Cañas\n" +
"Baños\n" +
"De Castro\n" +
"Nadal\n" +
"Fuster\n" +
"Tejada\n" +
"Enríquez\n" +
"Casal\n" +
"Alegre\n" +
"Campillo\n" +
"Arcos\n" +
"Bustamante\n" +
"Gago\n" +
"Montoro\n" +
"Moreira\n" +
"Murcia\n" +
"Zaragoza\n" +
"Jaén\n" +
"Chávez\n" +
"Luengo\n" +
"Peris\n" +
"Perales\n" +
"Leiva\n" +
"Urbano\n" +
"Wang\n" +
"Vizcaíno\n" +
"Pareja\n" +
"Sebastián\n" +
"Gascón\n" +
"Bellido\n" +
"Olmos\n" +
"Vílchez\n" +
"Carreras\n" +
"Puertas\n" +
"Zafra\n" +
"Baeza\n" +
"Del Pino\n" +
"Felipe\n" +
"Ceballos\n" +
"Lin\n" +
"Mínguez\n" +
"Montesinos\n" +
"Castañeda\n" +
"Borja\n" +
"Prats\n" +
"San José\n" +
"Maestre\n" +
"Osuna\n" +
"Del Castillo\n" +
"Orozco\n" +
"Molero\n" +
"Alvarado\n" +
"Carreño\n" +
"Castello\n" +
"Osorio\n" +
"Palomares\n" +
"Laguna\n" +
"Ribas\n" +
"Mellado\n" +
"Palomino\n" +
"Calle\n" +
"Mira\n" +
"Garcés\n" +
"Fuertes\n" +
"Afonso\n" +
"Barceló\n" +
"Yáñez\n" +
"Bilbao\n" +
"Llopis\n" +
"Borras\n" +
"Valiente\n" +
"Giner\n" +
"Quirós\n" +
"Cabeza\n" +
"Souto\n" +
"Abellán\n" +
"Barranco\n" +
"Hervás\n" +
"Salguero\n" +
"Piñero\n" +
"Andrade\n" +
"Páez\n" +
"Amaya\n" +
"Olmo\n" +
"Haro\n" +
"Brito\n" +
"Arce\n" +
"Poveda\n" +
"Valles\n" +
"Salcedo\n" +
"Mateu\n" +
"Serna\n" +
"Bartolomé\n" +
"Chaves\n" +
"Garzón\n" +
"Araujo\n" +
"Rebollo\n" +
"Noguera\n" +
"Del Pozo\n" +
"Bonet\n" +
"Llorens\n" +
"Heras\n" +
"Pazos\n" +
"Avilés\n" +
"Lafuente\n" +
"Vives\n" +
"Alcalá\n" +
"Paniagua\n" +
"Sáenz\n" +
"De Miguel\n" +
"Ferrero\n" +
"Alcalde\n" +
"Alcázar\n" +
"Tena\n" +
"Figueroa\n" +
"Solano\n" +
"Rosado\n" +
"Pena\n" +
"Zambrano\n" +
"Olmedo\n" +
"Mosquera\n" +
"Huerta\n" +
"Pla\n" +
"Calleja\n" +
"Pizarro\n" +
"Frías\n" +
"Moyano\n" +
"Grande\n" +
"Dorado\n" +
"Dávila\n" +
"Chamorro\n" +
"Criado\n" +
"Freire\n" +
"Duque\n" +
"Valdés\n" +
"Tirado\n" +
"Dos Santos\n" +
"Espejo\n" +
"Rosales\n" +
"Portillo\n" +
"Lobato\n" +
"Galván\n" +
"Tejero\n" +
"Gordillo\n" +
"Real\n" +
"Gonzalo\n" +
"Llamas\n" +
"Agudo\n" +
"Morillo\n" +
"Barrio\n" +
"Royo\n" +
"Melero\n" +
"Alcaide\n" +
"Romera\n" +
"Jorge\n" +
"Cánovas\n" +
"Fajardo\n" +
"Sainz\n" +
"Peinado\n" +
"Ariza\n" +
"Carvajal\n" +
"Pavón\n" +
"Arjona\n" +
"Del Valle\n" +
"Duarte\n" +
"Toro\n" +
"Valenzuela\n" +
"Barbero\n" +
"Guijarro\n" +
"Ruano\n" +
"Aznar\n" +
"Morcillo\n" +
"Borrego\n" +
"Huertas\n" +
"Solé\n" +
"Segovia\n" +
"Ferreiro\n" +
"Cerezo\n" +
"Godoy\n" +
"Estrada\n" +
"Cebrián\n" +
"Alcántara\n" +
"Fraile\n" +
"Barragán\n" +
"Catalán\n" +
"Falcón\n" +
"Castellanos\n" +
"Corrales\n" +
"Egea\n" +
"Sastre\n" +
"Gámez\n" +
"Peralta\n" +
"Campo\n" +
"Rovira\n" +
"Mejías\n" +
"Losada\n" +
"Latorre\n" +
"Singh\n" +
"Alfaro\n" +
"Vergara\n" +
"Bello\n" +
"Valls\n" +
"Granados\n" +
"Tapia\n" +
"Navarrete\n" +
"Ocaña\n" +
"Pujol\n" +
"Ochoa\n" +
"Becerra\n" +
"Vaquero\n" +
"Madrid\n" +
"Puente\n" +
"Vélez\n" +
"Angulo\n" +
"Cervera\n" +
"Cuadrado\n" +
"Cabezas\n" +
"Cobos\n" +
"Barreiro\n" +
"Coll\n" +
"Ventura\n" +
"Barba\n" +
"Palma\n" +
"Pino\n" +
"Muñiz\n" +
"Recio\n" +
"Cardona\n" +
"Arranz\n" +
"Porras\n" +
"Belmonte\n" +
"Herranz\n" +
"Baena\n" +
"Nicolás\n" +
"Lago\n" +
"Rincón\n" +
"Miralles\n" +
"Casanova\n" +
"Sala\n" +
"De la Rosa\n" +
"Arévalo\n" +
"Palomo\n" +
"Sanchís\n" +
"Cantero\n" +
"Castilla\n" +
"Ballester\n" +
"Marrero\n" +
"Pineda\n" +
"Cid\n" +
"Perea\n" +
"Cámara\n" +
"Bosch\n" +
"Quintero\n" +
"Salinas\n" +
"Grau\n" +
"Pinto\n" +
"Solís\n" +
"Esteve\n" +
"Marques\n" +
"Barrios\n" +
"Da Silva\n" +
"Olivares\n" +
"Piñeiro\n" +
"Carballo\n" +
"Luis\n" +
"Ayala\n" +
"Font\n" +
"Sevilla\n" +
"Requena\n" +
"Peláez\n" +
"Alfonso\n" +
"Prado\n" +
"Villegas\n" +
"Arribas\n" +
"Carbonell\n" +
"Salgado\n" +
"Vela\n" +
"Moral\n" +
"Toledo\n" +
"Zapata\n" +
"Llorente\n" +
"Saavedra\n" +
"Chacón\n" +
"Mohamed\n" +
"Sola\n" +
"Riera\n" +
"Velázquez\n" +
"Alcaraz\n" +
"Juárez\n" +
"Domenech\n" +
"Cárdenas\n" +
"Cobo\n" +
"Correa\n" +
"Calero\n" +
"Ferreira\n" +
"Cáceres\n" +
"Córdoba\n" +
"Andreu\n" +
"Rosa\n" +
"Hernando\n" +
"Carrera\n" +
"Castellano\n" +
"Villa\n" +
"Chen\n" +
"Clemente\n" +
"Carrión\n" +
"Aragón\n" +
"Roig\n" +
"Sosa\n" +
"Bonilla\n" +
"Carretero\n" +
"Oliver\n" +
"Burgos\n" +
"Leal\n" +
"Ojeda\n" +
"Amador\n" +
"Linares\n" +
"Moran\n" +
"Reina\n" +
"Paz\n" +
"Villalba\n" +
"Mata\n" +
"Naranjo\n" +
"Aguirre\n" +
"Polo\n" +
"Caro\n" +
"Lucas\n" +
"Valencia\n" +
"Ramón\n" +
"Asensio\n" +
"Mena\n" +
"Vallejo\n" +
"Escribano\n" +
"Galindo\n" +
"Domingo\n" +
"Arenas\n" +
"Soria\n" +
"Aguado\n" +
"Navas\n" +
"Pulido\n" +
"Saiz\n" +
"Rojo\n" +
"Cabello\n" +
"Puig\n" +
"Alba\n" +
"Corral\n" +
"Gimeno\n" +
"Ordoñez\n" +
"Barrera\n" +
"De la Torre\n" +
"Quesada\n" +
"Ros\n" +
"Barroso\n" +
"Marco\n" +
"Cuevas\n" +
"Martos\n" +
"Montoya\n" +
"De la Cruz\n" +
"Cuenca\n" +
"Murillo\n" +
"Pozo\n" +
"Collado\n" +
"Cordero\n" +
"Mas\n" +
"Oliva\n" +
"Juan\n" +
"Lorente\n" +
"Rodrigo\n" +
"Ponce\n" +
"Bautista\n" +
"Valle\n" +
"Maldonado\n" +
"Valverde\n" +
"Ballesteros\n" +
"Antón\n" +
"Paredes\n" +
"Bermejo\n" +
"Salvador\n" +
"Zamora\n" +
"Castaño\n" +
"Luna\n" +
"Alarcón\n" +
"Millán\n" +
"Blasco\n" +
"Escobar\n" +
"Del Rio\n" +
"Mesa\n" +
"Sancho\n" +
"Lázaro\n" +
"De la Fuente\n" +
"Pons\n" +
"Ávila\n" +
"Pacheco\n" +
"Simón\n" +
"Trujillo\n" +
"Rueda\n" +
"Hurtado\n" +
"Tomas\n" +
"Manzano\n" +
"Cuesta\n" +
"Villanueva\n" +
"Guzmán\n" +
"Serra\n" +
"Salazar\n" +
"Santamaría\n" +
"Miguel\n" +
"Bermúdez\n" +
"Costa\n" +
"Roca\n" +
"Blázquez\n" +
"Aranda\n" +
"Acosta\n" +
"Plaza\n" +
"Jurado\n" +
"Quintana\n" +
"Salas\n" +
"Conde\n" +
"Gálvez\n" +
"Abad\n" +
"Calderón\n" +
"Rico\n" +
"Gracia\n" +
"Padilla\n" +
"Beltrán\n" +
"Estévez\n" +
"Rivero\n" +
"Aparicio\n" +
"Casas\n" +
"Aguilera\n" +
"Menéndez\n" +
"Escudero\n" +
"Mateos\n" +
"Guillen\n" +
"Miranda\n" +
"Contreras\n" +
"Villar\n" +
"Mateo\n" +
"Roldan\n" +
"Heredia\n" +
"Bueno\n" +
"Macías\n" +
"Guerra\n" +
"Varela\n" +
"Andrés\n" +
"Benito\n" +
"Pereira\n" +
"Expósito\n" +
"Palacios\n" +
"Valero\n" +
"Vila\n" +
"Bernal\n" +
"Robles\n" +
"Mendoza\n" +
"Soriano\n" +
"Martí\n" +
"Marcos\n" +
"Carrillo\n" +
"Segura\n" +
"Sierra\n" +
"Ríos\n" +
"Montes\n" +
"Luque\n" +
"Galán\n" +
"Otero\n" +
"Vera\n" +
"Camacho\n" +
"Rey\n" +
"Arroyo\n" +
"Redondo\n" +
"Rivera\n" +
"Casado\n" +
"Silva\n" +
"Rivas\n" +
"Lara\n" +
"Espinosa\n" +
"Izquierdo\n" +
"Franco\n" +
"Merino\n" +
"Pardo\n" +
"Rojas\n" +
"Gallardo\n" +
"Bravo\n" +
"Parra\n" +
"Esteban\n" +
"Moya\n" +
"Soler\n" +
"Velasco\n" +
"Sáez\n" +
"Soto\n" +
"Román\n" +
"Pastor\n" +
"Crespo\n" +
"Carmona\n" +
"Vargas\n" +
"Santiago\n" +
"Arias\n" +
"Benítez\n" +
"Mora\n" +
"Vicente\n" +
"Duran\n" +
"Ferrer\n" +
"Giménez\n" +
"Ibáñez\n" +
"Montero\n" +
"Hidalgo\n" +
"Lorenzo\n" +
"Santana\n" +
"Herrero\n" +
"Reyes\n" +
"Pascual\n" +
"Aguilar\n" +
"Nieto\n" +
"Caballero\n" +
"Carrasco\n" +
"Fuentes\n" +
"Diez\n" +
"Vega\n" +
"Campos\n" +
"Flores\n" +
"Cabrera\n" +
"Peña\n" +
"Márquez\n" +
"Herrera\n" +
"León\n" +
"Cruz\n" +
"Gallego\n" +
"Vidal\n" +
"Calvo\n" +
"Méndez\n" +
"Prieto\n" +
"Cano\n" +
"Guerrero\n" +
"Lozano\n" +
"Cortes\n" +
"Castillo\n" +
"Santos\n" +
"Garrido\n" +
"Medina\n" +
"Núñez\n" +
"Iglesias\n" +
"Sanz\n" +
"Marín\n" +
"Rubio\n" +
"Ortiz\n" +
"Castro\n" +
"Delgado\n" +
"Ortega\n" +
"Morales\n" +
"Molina\n" +
"Suarez\n" +
"Blanco\n" +
"Serrano\n" +
"Ramírez\n" +
"Gil\n" +
"Ramos\n" +
"Vázquez\n" +
"Domínguez\n" +
"Torres\n" +
"Navarro\n" +
"Gutiérrez\n" +
"Alonso\n" +
"Romero\n" +
"Muñoz\n" +
"Álvarez\n" +
"Moreno\n" +
"Díaz\n" +
"Hernández\n" +
"Ruiz\n" +
"Jiménez\n" +
"Martin\n" +
"Gómez\n" +
"Pérez\n" +
"Sánchez\n" +
"Martínez\n" +
"López\n" +
"Fernández\n" +
"Rodríguez\n" +
"González\n" +
"García";
    
    public static String nombres = "Mariem\n" +
"Saida\n" +
"Samir\n" +
"Sufian\n" +
"Laila\n" +
"Salma\n" +
"Farida\n" +
"Mina\n" +
"Erhimo\n" +
"Dunia\n" +
"Hamed\n" +
"Habiba\n" +
"Dina\n" +
"Yusef\n" +
"Fátima Sohora\n" +
"Nabil\n" +
"Adam\n" +
"Sohora\n" +
"Soraya\n" +
"Mimount\n" +
"Samira\n" +
"Abdeselam\n" +
"Farah\n" +
"María África\n" +
"Rahma\n" +
"Mimoun\n" +
"Karima\n" +
"Mariam\n" +
"Nora\n" +
"Yamina\n" +
"María Fuencisla\n" +
"Rachida\n" +
"Naima\n" +
"Alí\n" +
"Omar\n" +
"Fadma\n" +
"Karim\n" +
"Nadia\n" +
"Rachid\n" +
"Sonsoles\n" +
"Said\n" +
"Natividad\n" +
"África\n" +
"Yasmina\n" +
"Aicha\n" +
"Bilal\n" +
"Abdelkader\n" +
"Luis Angel\n" +
"Hassan\n" +
"María Sonsoles\n" +
"Blanca\n" +
"Malika\n" +
"Mustafa\n" +
"Celso\n" +
"Agustina\n" +
"Camilo\n" +
"Celsa\n" +
"Elisa\n" +
"Inés\n" +
"José Ángel\n" +
"María Cruz\n" +
"Celia\n" +
"Joel\n" +
"Merce\n" +
"Ahmed\n" +
"María Carme\n" +
"Roger\n" +
"Benito\n" +
"Héctor\n" +
"Cristian\n" +
"María Llanos\n" +
"María Prado\n" +
"Leyre\n" +
"Guadalupe\n" +
"Eduard\n" +
"Olatz\n" +
"Ainara\n" +
"Arnau\n" +
"Enric\n" +
"Elvira\n" +
"Aritz\n" +
"Martí\n" +
"Pino\n" +
"Carla\n" +
"Andoni\n" +
"Jonathan\n" +
"Antonio Manuel\n" +
"Felipe\n" +
"Rodrigo\n" +
"Joseba\n" +
"Carmen Delia\n" +
"Miren\n" +
"Juan María\n" +
"Idoia\n" +
"Igor\n" +
"Irati\n" +
"Joaquina\n" +
"Ramona\n" +
"Margalida\n" +
"Gloria\n" +
"Sagrario\n" +
"Victoria\n" +
"Maialen\n" +
"Iria\n" +
"Maider\n" +
"Bernardo\n" +
"Ana Cristina\n" +
"Juliana\n" +
"Aina\n" +
"Imanol\n" +
"Carles\n" +
"María Angustias\n" +
"César\n" +
"María Paz\n" +
"José Juan\n" +
"Bárbara\n" +
"Julen\n" +
"Adriá\n" +
"Joaquim\n" +
"José Javier\n" +
"Juan Luis\n" +
"Josu\n" +
"Fuensanta\n" +
"Pascual\n" +
"Petra\n" +
"Fátima\n" +
"Gregorio\n" +
"Iratxe\n" +
"María Dolors\n" +
"Lorenzo\n" +
"Gemma\n" +
"María Magdalena\n" +
"Carmelo\n" +
"Carme\n" +
"Carolina\n" +
"Trinidad\n" +
"Pedro José\n" +
"Aurora\n" +
"Carmen María\n" +
"Dolors\n" +
"Alfredo\n" +
"Guillermo\n" +
"Carmen Rosa\n" +
"José Francisco\n" +
"Estibaliz\n" +
"Samuel\n" +
"Candelaria\n" +
"María Aranzazu\n" +
"Víctor Manuel\n" +
"Martín\n" +
"Ascensión\n" +
"María Cinta\n" +
"María Lourdes\n" +
"Asunción\n" +
"María Asunción\n" +
"Antoni\n" +
"Lluis\n" +
"Ismael\n" +
"Antonio José\n" +
"Araceli\n" +
"Pere\n" +
"Itziar\n" +
"Mohammed\n" +
"Emilia\n" +
"Gerard\n" +
"Esperanza\n" +
"Ginés\n" +
"Felisa\n" +
"Remedios\n" +
"Eneko\n" +
"Pau\n" +
"Luisa\n" +
"Francisco Manuel\n" +
"Rafaela\n" +
"Francesc\n" +
"Maite\n" +
"Verónica\n" +
"Bartolomé\n" +
"Miquel\n" +
"José Carlos\n" +
"María Pino\n" +
"Ane\n" +
"Manuel Jesús\n" +
"María Rocío\n" +
"Juana María\n" +
"María Candelaria\n" +
"Purificación\n" +
"Josep María\n" +
"Josefina\n" +
"Gorka\n" +
"Magdalena\n" +
"María Nieves\n" +
"Eva María\n" +
"Ander\n" +
"Domingo\n" +
"Milagros\n" +
"Xabier\n" +
"Leire\n" +
"Unai\n" +
"María Luz\n" +
"Gabriel\n" +
"Begoña\n" +
"Noelia\n" +
"María Antonia\n" +
"Amaia\n" +
"Ainhoa\n" +
"Nerea\n" +
"Jesús María\n" +
"María Victoria\n" +
"Cristóbal\n" +
"Iñaki\n" +
"José Vicente\n" +
"María Amparo\n" +
"Oriol\n" +
"Juan Francisco\n" +
"José Ignacio\n" +
"Iker\n" +
"Asier\n" +
"Jon\n" +
"Gonzalo\n" +
"Paloma\n" +
"María Elena\n" +
"Agustín\n" +
"Iñigo\n" +
"Sebastián\n" +
"Alex\n" +
"Mariano\n" +
"Consuelo\n" +
"María Begoña\n" +
"Vicenta\n" +
"José Miguel\n" +
"Marcos\n" +
"Aitor\n" +
"Ana Belén\n" +
"Mikel\n" +
"Sergi\n" +
"Mireia\n" +
"Antonio Jesús\n" +
"Félix\n" +
"Tomas\n" +
"Laia\n" +
"Julio\n" +
"Esther\n" +
"María Mercedes\n" +
"María Rosa\n" +
"María Concepción\n" +
"Isabel María\n" +
"José Ramón\n" +
"Jaume\n" +
"Eva\n" +
"Amparo\n" +
"Ana Isabel\n" +
"Xavier\n" +
"Albert\n" +
"Catalina\n" +
"Margarita\n" +
"Mohamed\n" +
"Anna\n" +
"Emilio\n" +
"Alba\n" +
"Natalia\n" +
"María Rosario\n" +
"Julián\n" +
"Ángeles\n" +
"Mario\n" +
"Ricardo\n" +
"María Josefa\n" +
"Josep\n" +
"Yolanda\n" +
"Marina\n" +
"Marc\n" +
"Joan\n" +
"Alfonso\n" +
"Ignacio\n" +
"Inmaculada\n" +
"Andrea\n" +
"Sonia\n" +
"Sandra\n" +
"Ángela\n" +
"Jaime\n" +
"Francisco José\n" +
"Alicia\n" +
"Irene\n" +
"María Mar\n" +
"Susana\n" +
"Juan Manuel\n" +
"Salvador\n" +
"Víctor\n" +
"Rocío\n" +
"Jordi\n" +
"Mónica\n" +
"Roberto\n" +
"Nuria\n" +
"Eduardo\n" +
"Julia\n" +
"Encarnación\n" +
"Montserrat\n" +
"Rubén\n" +
"Rosa\n" +
"Vicente\n" +
"Patricia\n" +
"Óscar\n" +
"Joaquín\n" +
"Silvia\n" +
"Santiago\n" +
"Iván\n" +
"Beatriz\n" +
"Rosario\n" +
"Juan Antonio\n" +
"Adrián\n" +
"Diego\n" +
"Ramón\n" +
"Andrés\n" +
"Álvaro\n" +
"Raúl\n" +
"Juana\n" +
"Paula\n" +
"María Jesús\n" +
"Sara\n" +
"Enrique\n" +
"Teresa\n" +
"Raquel\n" +
"Manuela\n" +
"Rosa María\n" +
"Lucia\n" +
"Elena\n" +
"Juan José\n" +
"Mercedes\n" +
"Juan Carlos\n" +
"Concepción\n" +
"María Luisa\n" +
"Pilar\n" +
"Alberto\n" +
"Pablo\n" +
"Jorge\n" +
"Sergio\n" +
"María José\n" +
"María Isabel\n" +
"Marta\n" +
"Luis\n" +
"Fernando\n" +
"Alejandro\n" +
"José María\n" +
"Miguel Ángel\n" +
"Dolores\n" +
"Cristina\n" +
"Antonia\n" +
"María Ángeles\n" +
"Ángel\n" +
"Francisca\n" +
"Laura\n" +
"José Manuel\n" +
"Pedro\n" +
"Rafael\n" +
"Ana\n" +
"María Teresa\n" +
"Miguel\n" +
"Daniel\n" +
"María Pilar\n" +
"María Dolores\n" +
"Carlos\n" +
"Ana María\n" +
"Francisco Javier\n" +
"Javier\n" +
"Jesús\n" +
"Isabel\n" +
"José Luis\n" +
"José Antonio\n" +
"Josefa\n" +
"David\n" +
"Juan\n" +
"Carmen\n" +
"Francisco\n" +
"Manuel\n" +
"María\n" +
"María Carmen\n" +
"José\n" +
"Antonio";
    
    public static String paises = "Ciudad del Vaticano,1000\n" +
"Nauru,10000\n" +
"Tuvalu,10000\n" +
"Palaos,21000\n" +
"San Marino,32000\n" +
"Mónaco,35000\n" +
"Liechtenstein,37000\n" +
"San Cristóbal y Nieves,54000\n" +
"Islas Marshall,56000\n" +
"Dominica,68000\n" +
"Seychelles,87000\n" +
"Andorra,88000\n" +
"Antigua y Barbuda,91000\n" +
"Kiribati,103000\n" +
"Granada,105000\n" +
"Tonga,105000\n" +
"San Vicente y las Granadinas,109000\n" +
"Micronesia,112000\n" +
"Santo Tomé y Príncipe,172000\n" +
"Santa Lucía,178000\n" +
"Samoa,185000\n" +
"Guayana Francesa,243000\n" +
"Vanuatu,252000\n" +
"Barbados,275000\n" +
"Polinesia Francesa,277000\n" +
"Belice,324000\n" +
"Maldivas,324000\n" +
"Islandia,328000\n" +
"Bahamas,351000\n" +
"Brunéi,413000\n" +
"Malta,419000\n" +
"Cabo Verde,505000\n" +
"Luxemburgo,523000\n" +
"Surinam,534000\n" +
"Islas Salomón,566000\n" +
"República Árabe Saharaui Democrática,567000\n" +
"Montenegro,633000\n" +
"Guinea Ecuatorial,740000\n" +
"Bután,750000\n" +
"Guyana,758000\n" +
"Comoras,773000\n" +
"Fiyi,876000\n" +
"Yibuti,923000\n" +
"Chipre,1129000\n" +
"Timor Oriental,1187000\n" +
"Suazilandia,1220000\n" +
"Mauricio,1314000\n" +
"Estonia,1340000\n" +
"Trinidad y Tobago,1351000\n" +
"Baréin,1359000\n" +
"Gabón,1564000\n" +
"Guinea-Bissau,1580000\n" +
"Gambia,1825000\n" +
"Catar,1939000\n" +
"Eslovenia,2040000\n" +
"Botsuana,2053000\n" +
"República de Macedonia,2067000\n" +
"Lesoto,2217000\n" +
"Letonia,2235000\n" +
"Namibia,2364000\n" +
"Jamaica,2761000\n" +
"Mongolia,2844000\n" +
"Kuwait,2892000\n" +
"Omán,2904000\n" +
"Armenia,3109000\n" +
"Albania,3227000\n" +
"Lituania,3292000\n" +
"Uruguay,3391000\n" +
"Moldavia,3519000\n" +
"Mauritania,3623000\n" +
"Panamá,3625000\n" +
"Puerto Rico,3743000\n" +
"Bosnia y Herzegovina,3744000\n" +
"República del Congo,4233000\n" +
"Liberia,4245000\n" +
"Autoridad Nacional Palestina,4271000\n" +
"Líbano,4292000\n" +
"Georgia,4304000\n" +
"Croacia,4387000\n" +
"Nueva Zelanda,4461000\n" +
"República Centroafricana,4576000\n" +
"Irlanda,4579000\n" +
"Costa Rica,4794000\n" +
"Noruega,4960000\n" +
"Turkmenistán,5170000\n" +
"Singapur,5256000\n" +
"Finlandia,5403000\n" +
"Kirguistán,5448000\n" +
"Eslovaquia,5480000\n" +
"Eritrea,5581000\n" +
"Dinamarca,5593000\n" +
"Nicaragua,5955000\n" +
"Sierra Leona,6126000\n" +
"El Salvador,6264000\n" +
"Togo,6283000\n" +
"Laos,6374000\n" +
"Jordania,6457000\n" +
"Libia,6469000\n" +
"Paraguay,6683000\n" +
"Tayikistán,7079000\n" +
"Papúa Nueva Guinea,7170000\n" +
"Hong Kong,7196000\n" +
"Bulgaria,7398000\n" +
"Israel,7695000\n" +
"Suiza,7734000\n" +
"Honduras,7912000\n" +
"Emiratos Árabes Unidos,8106000\n" +
"Austria,8429000\n" +
"Burundi,8749000\n" +
"Benín,9352000\n" +
"Azerbaiyán,9421000\n" +
"Suecia,9495000\n" +
"Bielorrusia,9527000\n" +
"Somalia,9797000\n" +
"Serbia,9847000\n" +
"Hungría,9950000\n" +
"República Dominicana,10183000\n" +
"Bolivia,10248000\n" +
"Haití,10256000\n" +
"Guinea,10481000\n" +
"República Checa,10566000\n" +
"Portugal,10699000\n" +
"Túnez,10705000\n" +
"Bélgica,10788000\n" +
"Cuba,11249000\n" +
"Ruanda,11272000\n" +
"Grecia,11419000\n" +
"Chad,11831000\n" +
"Zimbabue,13014000\n" +
"Senegal,13108000\n" +
"Zambia,13884000\n" +
"Camboya,14478000\n" +
"Ecuador,14865000\n" +
"Guatemala,15138000\n" +
"Malaui,15883000\n" +
"Malí,16319000\n" +
"Kazajistán,16381000\n" +
"Níger,16644000\n" +
"Países Bajos,16714000\n" +
"Chile,17423000\n" +
"Burkina Faso,17482000\n" +
"Angola,20163000\n" +
"Camerún,20469000\n" +
"Costa de Marfil,20595000\n" +
"Siria,21118000\n" +
"Sri Lanka,21224000\n" +
"Rumania,21388000\n" +
"Madagascar,21929000\n" +
"Australia,22919000\n" +
"Mozambique,24475000\n" +
"Corea del Norte,24554000\n" +
"Ghana,25546000\n" +
"Yemen,25569000\n" +
"Uzbekistán,28077000\n" +
"Arabia Saudita,28705000\n" +
"Malasia,29322000\n" +
"Perú,29734000\n" +
"Venezuela,29891000\n" +
"Nepal,31011000\n" +
"Marruecos,32599000\n" +
"Afganistán,33397000\n" +
"Irak,33703000\n" +
"Canadá,34675000\n" +
"Uganda,35621000\n" +
"Argelia,36486000\n" +
"Polonia,38317000\n" +
"Argentina,41119000\n" +
"Kenia,42749000\n" +
"Ucrania,44940000\n" +
"Sudán,45722000\n" +
"España,46772000\n" +
"Colombia,47551000\n" +
"Tanzania,47656000\n" +
"Corea del Sur,48588000\n" +
"Birmania,48724000\n" +
"Sudáfrica,50738000\n" +
"Italia,60964000\n" +
"Reino Unido,62798000\n" +
"Francia,63458000\n" +
"Rep. Dem. del Congo,69575000\n" +
"Tailandia,69892000\n" +
"Turquía,74509000\n" +
"Irán,75612000\n" +
"Alemania,81991000\n" +
"Egipto,83958000\n" +
"Etiopía,86539000\n" +
"Vietnam,89730000\n" +
"Filipinas,96471000\n" +
"México,116147000\n" +
"Japón,126435000\n" +
"Rusia,142703000\n" +
"Bangladés,152409000\n" +
"Nigeria,166629000\n" +
"Pakistán,179951000\n" +
"Brasil,198361000\n" +
"Indonesia,244769000\n" +
"Estados Unidos,315791000\n" +
"India,1258351000\n" +
"China,1353601000";
    
    public static String palabras = "La Abdicación\n" +
"El Abastecimiento\n" +
"El Abceso\n" +
"El Abdomen\n" +
"El Abecedario\n" +
"La Abeja\n" +
"El Abiótico\n" +
"La Abnegación\n" +
"Lo Abovedado\n" +
"El Abraham\n" +
"El Abrasivo\n" +
"La Abreviatura\n" +
"El Abrupto\n" +
"La Absolución\n" +
"La Absorción\n" +
"La Abstención\n" +
"La Abstinencia\n" +
"La Abstracción\n" +
"Lo Abstracto\n" +
"La Abundancia\n" +
"El Acaecimiento\n" +
"El Acceso\n" +
"Lo Accesible\n" +
"Lo Accesorio\n" +
"La Acepción\n" +
"La Aceptación\n" +
"Lo Aconsejable\n" +
"El Acribillamiento\n" +
"La Acrobacia\n" +
"La Actitud\n" +
"La Actividad\n" +
"La Acusación\n" +
"La Adaptación\n" +
"La Adherencia\n" +
"El Adherente\n" +
"La Adhesión\n" +
"El Adhesivo\n" +
"La Adicción\n" +
"La Adivinanza\n" +
"El Adjetivo\n" +
"La Adjudicación\n" +
"La Adjudicación\n" +
"La Admisión\n" +
"El Adolescente\n" +
"La Adquisición\n" +
"La Adsorción\n" +
"El Adverbio\n" +
"El Adversario\n" +
"El Adversativo\n" +
"La Adversidad\n" +
"La Advertencia\n" +
"La Advocación\n" +
"Lo Adyacente\n" +
"La Aflicción\n" +
"La Afluencia\n" +
"El Aforo\n" +
"La Agilidad\n" +
"El Agobiante\n" +
"La Agresividad\n" +
"El Agudizamiento\n" +
"La Aliteración\n" +
"La Ambición\n" +
"La Amnistía\n" +
"El Amstrong\n" +
"El Anhídrido\n" +
"La Anorexia\n" +
"El Antecesor\n" +
"El Antibiótico\n" +
"La Anticipación\n" +
"El Anverso\n" +
"La Aposición\n" +
"La Aristocracia\n" +
"La Arteriosclerosis\n" +
"La Ascendencia\n" +
"El Asentamiento\n" +
"El Aseverativo\n" +
"El Asia\n" +
"La Asimilación\n" +
"El Astigmatismo\n" +
"El Astringente\n" +
"El Astronauta\n" +
"La Asunción\n" +
"La Atribución\n" +
"El Audiovisual\n" +
"La Auscultación\n" +
"La Ausencia\n" +
"La Autarquía\n" +
"El Autoadhesivo\n" +
"El Autótrofo\n" +
"El Aval\n" +
"El Ave\n" +
"La Avidez\n" +
"El Axioma\n" +
"El Azteca\n" +
"La Babilonia\n" +
"El Bacilo\n" +
"La Bacteria\n" +
"La Bahía\n" +
"El Bajorrelieve\n" +
"El Barbarismo\n" +
"El Bario\n" +
"La Báscula\n" +
"Lo Básico\n" +
"La Basílica\n" +
"La Batalla\n" +
"El Bautismo\n" +
"La Beatificación\n" +
"La Bebida\n" +
"Lo Bélico\n" +
"La Bendición\n" +
"La Beneficencia\n" +
"La Biblia\n" +
"La Bibliografía\n" +
"El Bíceps\n" +
"Lo Bicóncavo\n" +
"La Bienaventuranza\n" +
"La Bienvenida\n" +
"La Bifurcación\n" +
"El Bimestre\n" +
"El Binomio\n" +
"La Biografía\n" +
"La Biosfera\n" +
"El Bióxido\n" +
"El Bípedo\n" +
"La Bisectriz\n" +
"El Bisiesto\n" +
"El Bisílabo\n" +
"El Bivalente\n" +
"El Bizcocho\n" +
"La Bombilla\n" +
"El Bovino\n" +
"La Brevedad\n" +
"La Buenaventura\n" +
"La Bulimia\n" +
"El Bullicio\n" +
"El Buscador\n" +
"La Cabeza\n" +
"El Cabildo\n" +
"La Callosidad\n" +
"La Calvicie\n" +
"La Canción\n" +
"La Capacidad\n" +
"La Capilaridad\n" +
"La Capitulación\n" +
"El Carnívoro\n" +
"El Castellano\n" +
"El Cautiverio\n" +
"La Celebración\n" +
"El Centesimal\n" +
"El Centímetro\n" +
"La Cibernética\n" +
"La Ciencia\n" +
"La Científica\n" +
"La Circunferencia\n" +
"Lo Circunstancial\n" +
"El Citoplasma\n" +
"El Cívico\n" +
"El Clásico\n" +
"La Clavícula\n" +
"El Clavo\n" +
"La Coalición\n" +
"La Cocina\n" +
"La Coherencia\n" +
"La Cohesión\n" +
"La Colección\n" +
"La Comercialización\n" +
"El Comezón\n" +
"La Complicación\n" +
"La Composición\n" +
"La Comprensión\n" +
"La Comprobación\n" +
"El Comunicativo\n" +
"Lo Cóncavo\n" +
"La Concentración\n" +
"La Concepción\n" +
"La Concesión\n" +
"La Conciencia\n" +
"El Concilio\n" +
"La Concordancia\n" +
"La Conductividad\n" +
"La Confesión\n" +
"La Congruencia\n" +
"La Conjugación\n" +
"La Conjunción\n" +
"El Conmutativo\n" +
"La Connotación\n" +
"El Conocimiento\n" +
"El Consejo\n" +
"La Conserva\n" +
"La Consideración\n" +
"La Consigna\n" +
"La Consistencia\n" +
"La Constelación\n" +
"La Constitución\n" +
"La Construcción\n" +
"La Contribución\n" +
"La Convalescencia\n" +
"La Conversación\n" +
"La Conversión\n" +
"Lo Convexo\n" +
"La Convivencia\n" +
"La Convocatoria\n" +
"La Coordinación\n" +
"El Cosmos\n" +
"Lo Covalente\n" +
"El Crecimiento\n" +
"El Cuadrúpedo\n" +
"El Cuádruple\n" +
"El Débil\n" +
"La Decadencia\n" +
"El Décimo\n" +
"La Decisión\n" +
"La Definición\n" +
"La Delgadez\n" +
"La Democracia\n" +
"La Depresión\n" +
"La Derivación\n" +
"El Desahogo\n" +
"Lo Desastroso\n" +
"El Descendiente\n" +
"La Descriptiva\n" +
"El Deshabitado\n" +
"La Desinencia\n" +
"El Deslizamiento\n" +
"La Desvalorización\n" +
"La Devastación\n" +
"La Devoción\n" +
"El Diagnóstico\n" +
"El Dibujo\n" +
"El Diezmo\n" +
"El Dihíbrido\n" +
"El Dilúbrido\n" +
"El Diptongo\n" +
"La Disciplina\n" +
"El Discípulo\n" +
"La Discordancia\n" +
"La Discriminación\n" +
"La Disección\n" +
"El Disociamiento\n" +
"La Distribución\n" +
"La Disyunción\n" +
"El Divergente\n" +
"La Diversión\n" +
"El Divisible\n" +
"La División\n" +
"La Divulgación\n" +
"La Eficiencia\n" +
"El Egipto\n" +
"La Elaboración\n" +
"La Elipsis\n" +
"El Encabezamiento\n" +
"El Endocrino\n" +
"El Endoplasmático\n" +
"El Enlace\n" +
"La Enseñanza\n" +
"La Entrevista\n" +
"El Envase\n" +
"El Envío\n" +
"La Envoltura\n" +
"El Erlemeyer\n" +
"La Erosión\n" +
"La Escena\n" +
"La Escenografía\n" +
"La Esclavitud\n" +
"Lo Esencial\n" +
"El Espermatozoide\n" +
"El Estival\n" +
"El Estratega\n" +
"La Estrella\n" +
"La Evaluación\n" +
"El Evangelio\n" +
"La Evaporación\n" +
"La Evolución\n" +
"El Examen\n" +
"La Excavación\n" +
"La Excelencia\n" +
"El Excepcional\n" +
"La Exclusión\n" +
"La Excreción\n" +
"La Excursión\n" +
"La Exhibición\n" +
"La Exhortación\n" +
"La Exigencia\n" +
"El Exilio\n" +
"La Existencia\n" +
"El Éxodo\n" +
"La Expansión\n" +
"La Expedición\n" +
"La Experiencia\n" +
"El Experimento\n" +
"La Explosión\n" +
"La Expresión\n" +
"La Expresiva\n" +
"La Expulsión\n" +
"La Exuberancia\n" +
"La Fabricación\n" +
"La Fábula\n" +
"Lo Fácil\n" +
"La Fenicia\n" +
"La Física\n" +
"La Fisiología\n" +
"El Flagelo\n" +
"La Flexibilidad\n" +
"La Fortuna\n" +
"El Fósil\n" +
"La Fotólisis\n" +
"La Fotometría\n" +
"La Fotoquímica\n" +
"La Fotosíntesis\n" +
"La Frase\n" +
"La Fraternidad\n" +
"La Frontera\n" +
"El Frugívoro\n" +
"La Función\n" +
"La Galaxia\n" +
"La Genealogía\n" +
"La Generalización\n" +
"La Génesis\n" +
"El Genoma\n" +
"El Genotipo\n" +
"La Gimnasia\n" +
"La Globalización\n" +
"El Graffiti\n" +
"La Gramática\n" +
"la Grandiosidad\n" +
"El Guía\n" +
"La Habitación\n" +
"La Habladuría\n" +
"El Hecho\n" +
"El Hallazgo\n" +
"La Hamaca\n" +
"La Hectárea\n" +
"El Hemisferio\n" +
"El Hemograma\n" +
"Lo Hepático\n" +
"El Heptágono\n" +
"El Herbívoro\n" +
"La Herencia\n" +
"Lo Hervido\n" +
"El Heterótrofo\n" +
"El Híbrido\n" +
"El Hidrofílico\n" +
"El Hidrófobo\n" +
"El Hidrógeno\n" +
"La Hidrólisis\n" +
"El Hiperónimo\n" +
"La Hipertensión\n" +
"El Hipónimo\n" +
"La Hipótesis\n" +
"El Hispanoamericano\n" +
"El Histológico\n" +
"El Hitita\n" +
"El Homónimo\n" +
"El Icónico\n" +
"La Idiosincrasia\n" +
"Lo Implícito\n" +
"Lo Imprescindible\n" +
"La Improvisación\n" +
"La Incisión\n" +
"La Indagación\n" +
"La Inducción\n" +
"La Inecuación\n" +
"El Inefable\n" +
"La Inhabilitación\n" +
"La Insercción\n" +
"Lo Instructivo\n" +
"La Intencionalidad\n" +
"El Interés\n" +
"La Interespecífica\n" +
"La Intervención\n" +
"La Intraespecífica\n" +
"La Introducción\n" +
"El Invasor\n" +
"La Invención\n" +
"El Inverso\n" +
"La Investigación\n" +
"Lo Invisible\n" +
"La Ionización\n" +
"Lo Irregular\n" +
"Lo Irreversible\n" +
"La Izquierda\n" +
"La Jabalina\n" +
"El Jilguero\n" +
"El Joule\n" +
"El Júbilo\n" +
"Lo Jurídico\n" +
"La Jurisdicción\n" +
"La Jurisprudencia\n" +
"La Justicia\n" +
"La Juventud\n" +
"El Laceramiento\n" +
"La Laringe\n" +
"El Levítico\n" +
"La Libertad\n" +
"La Licencia\n" +
"La Limnología\n" +
"El Limo\n" +
"La Línea\n" +
"La Lingüística\n" +
"El Lisosoma\n" +
"La Longitud\n" +
"El Lumen\n" +
"El Lúteo\n" +
"Lo Macrométrico\n" +
"El Magnánimo\n" +
"Lo Maleable\n" +
"La Maquinaria\n" +
"El Medieval\n" +
"El Mesías\n" +
"El Microorganismo\n" +
"El Micrótomo\n" +
"La Misión\n" +
"El Monocárpico\n" +
"El Monohíbrido\n" +
"La Morfología\n" +
"La Motilidad\n" +
"La Movilidad\n" +
"El Municipio\n" +
"El Nacimiento\n" +
"La Nacionalidad\n" +
"El Nacionalismo\n" +
"El Nanómetro\n" +
"La Navegación\n" +
"La Necesidad\n" +
"El Neoclasicismo\n" +
"El Neologismo\n" +
"La Nervadura\n" +
"El Nobiliario\n" +
"La Novela\n" +
"El Nucela\n" +
"La Nueva\n" +
"La Obediencia\n" +
"La Objeción\n" +
"El Objetivo\n" +
"El Objeto\n" +
"La Observación\n" +
"La Obsesión\n" +
"El Obtusángulo\n" +
"La Ocasión\n" +
"El Octosílabo\n" +
"El Oficial\n" +
"El Oleoducto\n" +
"La Omisión\n" +
"El Omnipotente\n" +
"El Omnisciente\n" +
"La Oposición\n" +
"La Organogénesis\n" +
"El Orgánulo\n" +
"El Origen\n" +
"El Ortográfico\n" +
"El Ovíparo\n" +
"El Ovovivíparo\n" +
"El Óvulo\n" +
"La Paciencia\n" +
"El Pacífico\n" +
"La Parábola\n" +
"La Parsimonia\n" +
"La Partenocarpia\n" +
"La Partenogénesis\n" +
"La Participación\n" +
"El Pasivo\n" +
"La Pasteurización\n" +
"El Perezoso\n" +
"La Persistencia\n" +
"El Perspicaz\n" +
"La Persuasión\n" +
"La Placenta\n" +
"El Plancton\n" +
"La Plasmólisis\n" +
"La Polinización\n" +
"La Posesión\n" +
"La Posibilidad\n" +
"La Precipitación\n" +
"La Precisión\n" +
"La Predación\n" +
"El Predecesor\n" +
"El Predicativo\n" +
"La Predilección\n" +
"La Predisposición\n" +
"La Prehistoria\n" +
"La Presencia\n" +
"La Preservación\n" +
"La Pretensión\n" +
"La Prevención\n" +
"La Probabilidad\n" +
"La Procesión\n" +
"La Profesión\n" +
"El Programario\n" +
"La Prohibición\n" +
"La Proposición\n" +
"El Proverbio\n" +
"La Provincia\n" +
"La Provisión\n" +
"La Prueba\n" +
"Lo Psíquico\n" +
"La Recepción\n" +
"La Recesión\n" +
"El Recibimiento\n" +
"El Reciclacimiento\n" +
"El Reconocimiento\n" +
"La Reflexión\n" +
"La Rehabilitación\n" +
"La Relación\n" +
"Lo Relativo\n" +
"La Religión\n" +
"La Reminiscencia\n" +
"El Renacimiento\n" +
"La Repercusión\n" +
"La Representación\n" +
"La Reserva\n" +
"La Residencia\n" +
"La Residencia\n" +
"La Resignación\n" +
"La Resistencia\n" +
"La Resolución\n" +
"La Responsabilidad\n" +
"La Restauración\n" +
"El Retículo\n" +
"La Reverencia\n" +
"Lo Reversible\n" +
"La Revisión\n" +
"El Ribosoma\n" +
"El Saber\n" +
"La Sabiduría\n" +
"La Selección\n" +
"La Selectividad\n" +
"La Selva\n" +
"La Semblanza\n" +
"El Sencillo\n" +
"La Sensibilidad\n" +
"El Septentrional\n" +
"El Servicio\n" +
"La Sílaba\n" +
"El Símbolo\n" +
"El Simposio\n" +
"La Sinalefa\n" +
"La Soberanía\n" +
"La Soberbia\n" +
"La Sociedad\n" +
"El Sosiego\n" +
"La Subida\n" +
"La Sublevación\n" +
"La Subordinación\n" +
"El Subsidio\n" +
"El Suburbio\n" +
"La Subvención\n" +
"La Sucesión\n" +
"La Suciedad\n" +
"La Sugerencia\n" +
"La Supervivencia\n" +
"El Sustantivo\n" +
"La Sustentación\n" +
"La Tecnología\n" +
"El Torbellino\n" +
"La Tradición\n" +
"La Tragedia\n" +
"La Tragicomedia\n" +
"La Transcripción\n" +
"La Transferencia\n" +
"La Transformación\n" +
"La Transfusión\n" +
"La Transición\n" +
"Lo Transitivo\n" +
"La Transmisión\n" +
"La Transpiración\n" +
"El Transporte\n" +
"El Trapezoide\n" +
"Lo Trascendental\n" +
"La Traslación\n" +
"El Triptongo\n" +
"El Tubérculo\n" +
"La Turbulencia\n" +
"La Turgencia\n" +
"El Ultimátum\n" +
"El Único\n" +
"Lo Unilateral\n" +
"El Universo\n" +
"El Unívoco\n" +
"La Urbanización\n" +
"La Urgencia\n" +
"El Vacío\n" +
"La Vacuna\n" +
"La Vegetación\n" +
"El Vegetal\n" +
"La Vellosidad\n" +
"La Ventosidad\n" +
"La Veracidad\n" +
"El Verbo\n" +
"Lo Verboides\n" +
"Lo Verosímil\n" +
"El Versículo\n" +
"La Versificación\n" +
"El Vertebrado\n" +
"El Vértice\n" +
"La Vesícula\n" +
"El Vestíbulo\n" +
"El Vestigio\n" +
"El Víbora\n" +
"La Viceversa\n" +
"La Vicisitud\n" +
"La Violencia\n" +
"El Virus\n" +
"La Víscera\n" +
"La Viscosa\n" +
"Lo Visible\n" +
"La Vivienda\n" +
"El Vivíparo\n" +
"El Vocabulario\n" +
"El Vocativo\n" +
"Lo Voluble\n" +
"La Vuelta\n" +
"La Votación\n" +
"El Vulcanismo\n" +
"Lo Vulnerable\n" +
"La Zambullida\n" +
"La Zoología\n" +
"El Zooplancton\n" +
"La Zootecnia";
    
    public static String localidades = "12 DE OCTUBRE\n" +
"ALGARROBAL ARRIBA\n" +
"ALGARROBAL PUISOYE\n" +
"ALGARROBAL VIEJO\n" +
"ALGARROBALES\n" +
"ALGARROBITO\n" +
"ALGARROBITO 1RO\n" +
"ALGARROBITOS\n" +
"ALGARROBO\n" +
"ALGARROBO DE SORTUE\n" +
"ALGARROBO DEL AGUILA\n" +
"ALGARROBO DEL CURA\n" +
"ALGARROBO GRANDE\n" +
"ALGARROBO PARAJE\n" +
"ALGARROBO VERDE\n" +
"ALGARROBOS GRANDES\n" +
"ALHUAMPA\n" +
"ALIANZA\n" +
"ALICIA\n" +
"ALICURA\n" +
"ALIJILAN\n" +
"ALISOS\n" +
"ALISOS  DE ABAJO\n" +
"ALISOS DE ARRIBA\n" +
"ALIZAL\n" +
"ALLEN\n" +
"ALLENDE\n" +
"ALMA GRANDE\n" +
"ALMACEN CASTRO\n" +
"ALMACEN CRISTIAN SCHUBERT\n" +
"ALMACEN EL CRUCE\n" +
"ALMACEN EL DESCANSO\n" +
"ALTO CARRIZAL\n" +
"ALTO CASTRO\n" +
"ALTO CAZADERA\n" +
"ALTO COMEDERO\n" +
"ALTO CON ZAMPA\n" +
"ALTO DE ANFAMA\n" +
"ALTO DE CASA\n" +
"ALTO DE CASTILLO\n" +
"ALTO DE FIERRO\n" +
"ALTO DE FLORES\n" +
"ALTO DE LA ANGOSTURA\n" +
"ALTO DE LA JUNTA\n" +
"ALTO DE LA LE?A\n" +
"ALTO DE LA SIERRA\n" +
"ALTO DE LAS ARA?AS\n" +
"ALTO DE LAS MULAS\n" +
"ALTO DE LAS PLUMAS\n" +
"ALTO DE LEIVA\n" +
"ALTO DE LOS GIMENEZ\n" +
"ALTO DE LOS MANANTIALES\n" +
"ALTO DE LOS PERROS\n" +
"ALTO DE LOS QUEBRACHOS\n" +
"ALTO DE LOS REALES\n" +
"ALTO DE LOS SAPOS\n" +
"ALTO DE LOZANO\n" +
"ALTO DE MEDINA\n" +
"ALTO DE MOJON\n" +
"ALTO DE SAN PEDRO\n" +
"ALTO DE SIERRA\n" +
"ALTO DEL ANGOSTO\n" +
"ALTO DEL DURAZNO\n" +
"ALTO DEL HUASCHO\n" +
"ALTO DEL LAMPAZO\n" +
"ALTO DEL LEON\n" +
"ALTO DEL MISTOL\n" +
"ALTOS DE CHIPION\n" +
"ALTOS HORNOS GUEMES\n" +
"ALUMBRERA\n" +
"ALUMINE\n" +
"ALURRALDE\n" +
"ALVAREZ\n" +
"ALVAREZ CONDARCO\n" +
"ALVAREZ DE TOLEDO\n" +
"ALVAREZ JONTE\n" +
"ALVARO BARROS\n" +
"ALVEAR\n" +
"ALZA NUEVA\n" +
"ALZAGA\n" +
"AMADORES\n" +
"BARRIO VILLA ADELA\n" +
"BARRIO VILLA COHESA\n" +
"BARRIO VILLA CORDOBA\n" +
"BARRIO VILLA FERNANDEZ\n" +
"BARRIO VILLA MU?IZ\n" +
"BARRIO VILLA ORTEGA\n" +
"BARRIO VILLA SALADILLO\n" +
"BARRIO VILLA UNION\n" +
"CAMPO GENERO\n" +
"CAMPO GIMBATTI\n" +
"CAMPO GIMENEZ\n" +
"CAMPO GOLA\n" +
"CAMPO GORETA\n" +
"CAMPO GRANDE\n" +
"CAMPO HARDY\n" +
"CAMPO HERRERA\n" +
"CAMPO HORQUESCO\n" +
"EL CANO\n" +
"EL CANQUEL\n" +
"EL CANTADERO\n" +
"EL CANTOR\n" +
"EL CAPACHO\n" +
"EL CARACOL\n" +
"EL CARAMELO\n" +
"EL CARANCHITO\n" +
"EL CARANCHO\n" +
"EL CARBALINO\n" +
"PASO ALGARROBO\n" +
"PASO ALSINA\n" +
"PASO ANCHO\n" +
"PASO BANDERA\n" +
"PASO BARDA\n" +
"PASO BERMUDEZ\n" +
"PASO CABRAL\n" +
"PASO CASTELLANOS\n" +
"PASO CATA TUN\n" +
"RIACHO HE HE\n" +
"RIACHO LINDO\n" +
"RIACHO NEGRO\n" +
"RIACHO RAMIREZ\n" +
"RIACHUELITO\n" +
"RIACHUELO\n" +
"CHORRILLO\n" +
"1 DE MAYO\n" +
"EL REMANCE\n" +
"YRAIZOS";
            
    public static String pcias = "BUENOS AIRES                                      \n" +
"CATAMARCA                                         \n" +
"CORDOBA                                           \n" +
"CORRIENTES                                        \n" +
"ENTRE RIOS                                        \n" +
"JUJUY                                             \n" +
"MENDOZA                                           \n" +
"LA RIOJA                                          \n" +
"SALTA                                             \n" +
"SAN JUAN                                          \n" +
"SAN LUIS                                          \n" +
"SANTA FE                                          \n" +
"SANTIAGO DEL ESTERO                               \n" +
"TUCUMAN                                           \n" +
"CHACO                                             \n" +
"CHUBUT                                            \n" +
"FORMOSA                                           \n" +
"MISIONES                                          \n" +
"NEUQUEN                                           \n" +
"LA PAMPA                                          \n" +
"RIO NEGRO                                         \n" +
"SANTA CRUZ                                        \n" +
"TIERRA DEL FUEGO                                  \n" +
"CIUDAD AUTONOMA BUENOS AIRES";

    private DataSource() throws InstantiationException {
        throw new InstantiationException("This class is not created for instntiation");
    }

}

/**
 * These functions are required very early in the Moodle
 * setup process, before any of the main libraries are
 * loaded.
 *
 * @package    core
 * @subpackage lib
 * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

defined('MOODLE_INTERNAL') || die();

// Debug levels - always keep the values in ascending order!
/** No warnings and errors at all */
define('DEBUG_NONE', 0);
/** Fatal errors only */
define('DEBUG_MINIMAL', E_ERROR | E_PARSE);
/** Errors, warnings and notices */
define('DEBUG_NORMAL', E_ERROR | E_PARSE | E_WARNING | E_NOTICE);
/** All problems except strict PHP warnings */
define('DEBUG_ALL', E_ALL & ~E_STRICT);
/** DEBUG_ALL with all debug messages and strict warnings */
define('DEBUG_DEVELOPER', E_ALL | E_STRICT);

/** Remove any memory limits */
define('MEMORY_UNLIMITED', -1);
/** Standard memory limit for given platform */
define('MEMORY_STANDARD', -2);
/**
 * Large memory limit for given platform - used in cron, upgrade, and other places that need a lot of memory.
 * Can be overridden with $CFG->extramemorylimit setting.
 */
define('MEMORY_EXTRA', -3);
/** Extremely large memory limit - not recommended for standard scripts */
define('MEMORY_HUGE', -4);


/**
 * Simple class. It is usually used instead of stdClass because it looks
 * more familiar to Java developers ;-) Do not use for type checking of
 * function parameters. Please use stdClass instead.
 *
 * @package    core
 * @subpackage lib
 * @copyright  2009 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @deprecated since 2.0
 */
class object extends stdClass {};

/**
 * Base Moodle Exception class
 *
 * Although this class is defined here, you cannot throw a moodle_exception until
 * after moodlelib.php has been included (which will happen very soon).
 *
 * @package    core
 * @subpackage lib
 * @copyright  2008 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class moodle_exception extends Exception {

    /**
     * @var string The name of the string from error.php to print
     */
    public $errorcode;

    /**
     * @var string The name of module
     */
    public $module;

    /**
     * @var mixed Extra words and phrases that might be required in the error string
     */
    public $a;

    /**
     * @var string The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
     */
    public $link;

    /**
     * @var string Optional information to aid the debugging process
     */
    public $debuginfo;

    /**
     * Constructor
     * @param string $errorcode The name of the string from error.php to print
     * @param string $module name of module
     * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
     * @param mixed $a Extra words and phrases that might be required in the error string
     * @param string $debuginfo optional debugging information
     */
    function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
        if (empty($module) || $module == 'moodle' || $module == 'core') {
            $module = 'error';
        }

        $this->errorcode = $errorcode;
        $this->module    = $module;
        $this->link      = $link;
        $this->a         = $a;
        $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;

        if (get_string_manager()->string_exists($errorcode, $module)) {
            $message = get_string($errorcode, $module, $a);
            $haserrorstring = true;
        } else {
            $message = $module . '/' . $errorcode;
            $haserrorstring = false;
        }

        if (defined('PHPUNIT_TEST') and PHPUNIT_TEST and $debuginfo) {
            $message = "$message ($debuginfo)";
        }

        if (!$haserrorstring and defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
            // Append the contents of $a to $debuginfo so helpful information isn't lost.
            // This emulates what {@link get_exception_info()} does. Unfortunately that
            // function is not used by phpunit.
            $message .= PHP_EOL.'$a contents: '.print_r($a, true);
        }

        parent::__construct($message, 0);
    }
}

/**
 * Course/activity access exception.
 *
 * This exception is thrown from require_login()
 *
 * @package    core_access
 * @copyright  2010 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class require_login_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $debuginfo Information to aid the debugging process
     */
    function __construct($debuginfo) {
        parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
    }
}

/**
 * Web service parameter exception class
 * @deprecated since Moodle 2.2 - use moodle exception instead
 * This exception must be thrown to the web service client when a web service parameter is invalid
 * The error string is gotten from webservice.php
 */
class webservice_parameter_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $errorcode The name of the string from webservice.php to print
     * @param string $a The name of the parameter
     * @param string $debuginfo Optional information to aid debugging
     */
    function __construct($errorcode=null, $a = '', $debuginfo = null) {
        parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
    }
}

/**
 * Exceptions indicating user does not have permissions to do something
 * and the execution can not continue.
 *
 * @package    core_access
 * @copyright  2009 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class required_capability_exception extends moodle_exception {
    /**
     * Constructor
     * @param context $context The context used for the capability check
     * @param string $capability The required capability
     * @param string $errormessage The error message to show the user
     * @param string $stringfile
     */
    function __construct($context, $capability, $errormessage, $stringfile) {
        $capabilityname = get_capability_string($capability);
        if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
            // we can not go to mod/xx/view.php because we most probably do not have cap to view it, let's go to course instead
            $parentcontext = $context->get_parent_context();
            $link = $parentcontext->get_url();
        } else {
            $link = $context->get_url();
        }
        parent::__construct($errormessage, $stringfile, $link, $capabilityname);
    }
}

/**
 * Exception indicating programming error, must be fixed by a programer. For example
 * a core API might throw this type of exception if a plugin calls it incorrectly.
 *
 * @package    core
 * @subpackage lib
 * @copyright  2008 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class coding_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $hint short description of problem
     * @param string $debuginfo detailed information how to fix problem
     */
    function __construct($hint, $debuginfo=null) {
        parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
    }
}

/**
 * Exception indicating malformed parameter problem.
 * This exception is not supposed to be thrown when processing
 * user submitted data in forms. It is more suitable
 * for WS and other low level stuff.
 *
 * @package    core
 * @subpackage lib
 * @copyright  2009 Petr Skoda  {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class invalid_parameter_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $debuginfo some detailed information
     */
    function __construct($debuginfo=null) {
        parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
    }
}

/**
 * Exception indicating malformed response problem.
 * This exception is not supposed to be thrown when processing
 * user submitted data in forms. It is more suitable
 * for WS and other low level stuff.
 */
class invalid_response_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $debuginfo some detailed information
     */
    function __construct($debuginfo=null) {
        parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
    }
}

/**
 * An exception that indicates something really weird happened. For example,
 * if you do switch ($context->contextlevel), and have one case for each
 * CONTEXT_... constant. You might throw an invalid_state_exception in the
 * default case, to just in case something really weird is going on, and
 * $context->contextlevel is invalid - rather than ignoring this possibility.
 *
 * @package    core
 * @subpackage lib
 * @copyright  2009 onwards Martin Dougiamas  {@link http://moodle.com}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class invalid_state_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $hint short description of problem
     * @param string $debuginfo optional more detailed information
     */
    function __construct($hint, $debuginfo=null) {
        parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
    }
}

/**
 * An exception that indicates incorrect permissions in $CFG->dataroot
 *
 * @package    core
 * @subpackage lib
 * @copyright  2010 Petr Skoda {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class invalid_dataroot_permissions extends moodle_exception {
    /**
     * Constructor
     * @param string $debuginfo optional more detailed information
     */
    function __construct($debuginfo = NULL) {
        parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
    }
}

/**
 * An exception that indicates that file can not be served
 *
 * @package    core
 * @subpackage lib
 * @copyright  2010 Petr Skoda {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class file_serving_exception extends moodle_exception {
    /**
     * Constructor
     * @param string $debuginfo optional more detailed information
     */
    function __construct($debuginfo = NULL) {
        parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
    }
}

/**
 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
 *
 * @param Exception $ex
 * @return void -does not return. Terminates execution!
 */
function default_exception_handler($ex) {
    global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;

    // detect active db transactions, rollback and log as error
    abort_all_db_transactions();

    if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
        $SESSION->wantsurl = qualified_me();
        redirect(get_login_url());
    }

    $info = get_exception_info($ex);

    if (debugging('', DEBUG_MINIMAL)) {
        $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
        error_log($logerrmsg);
    }

    if (is_early_init($info->backtrace)) {
        echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
    } else {
        try {
            if ($DB) {
                // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
                $DB->set_debug(0);
            }
            echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
        } catch (Exception $out_ex) {
            // default exception handler MUST not throw any exceptions!!
            // the problem here is we do not know if page already started or not, we only know that somebody messed up in outputlib or theme
            // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
            if (CLI_SCRIPT or AJAX_SCRIPT) {
                // just ignore the error and send something back using the safest method
                echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
            } else {
                echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
                $outinfo = get_exception_info($out_ex);
                echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
            }
        }
    }

    exit(1); // General error code
}

/**
 * Default error handler, prevents some white screens.
 * @param int $errno
 * @param string $errstr
 * @param string $errfile
 * @param int $errline
 * @param array $errcontext
 * @return bool false means use default error handler
 */
function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    if ($errno == 4096) {
        //fatal catchable error
        throw new coding_exception('PHP catchable fatal error', $errstr);
    }
    return false;
}

/**
 * Unconditionally abort all database transactions, this function
 * should be called from exception handlers only.
 * @return void
 */
function abort_all_db_transactions() {
    global $CFG, $DB, $SCRIPT;

    // default exception handler MUST not throw any exceptions!!

    if ($DB && $DB->is_transaction_started()) {
        error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
        // note: transaction blocks should never change current $_SESSION
        $DB->force_transaction_rollback();
    }
}

/**
 * This function encapsulates the tests for whether an exception was thrown in
 * early init -- either during setup.php or during init of $OUTPUT.
 *
 * If another exception is thrown then, and if we do not take special measures,
 * we would just get a very cryptic message "Exception thrown without a stack
 * frame in Unknown on line 0". That makes debugging very hard, so we do take
 * special measures in default_exception_handler, with the help of this function.
 *
 * @param array $backtrace the stack trace to analyse.
 * @return boolean whether the stack trace is somewhere in output initialisation.
 */
function is_early_init($backtrace) {
    $dangerouscode = array(
        array('function' => 'header', 'type' => '->'),
        array('class' => 'bootstrap_renderer'),
        array('file' => dirname(__FILE__).'/setup.php'),
    );
    foreach ($backtrace as $stackframe) {
        foreach ($dangerouscode as $pattern) {
            $matches = true;
            foreach ($pattern as $property => $value) {
                if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
                    $matches = false;
                }
            }
            if ($matches) {
                return true;
            }
        }
    }
    return false;
}

/**
 * Abort execution by throwing of a general exception,
 * default exception handler displays the error message in most cases.
 *
 * @param string $errorcode The name of the language string containing the error message.
 *      Normally this should be in the error.php lang file.
 * @param string $module The language file to get the error message from.
 * @param string $link The url where the user will be prompted to continue.
 *      If no url is provided the user will be directed to the site index page.
 * @param object $a Extra words and phrases that might be required in the error string
 * @param string $debuginfo optional debugging information
 * @return void, always throws exception!
 */
function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
    throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
}

/**
 * Returns detailed information about specified exception.
 * @param exception $ex
 * @return object
 */
function get_exception_info($ex) {
    global $CFG, $DB, $SESSION;

    if ($ex instanceof moodle_exception) {
        $errorcode = $ex->errorcode;
        $module = $ex->module;
        $a = $ex->a;
        $link = $ex->link;
        $debuginfo = $ex->debuginfo;
    } else {
        $errorcode = 'generalexceptionmessage';
        $module = 'error';
        $a = $ex->getMessage();
        $link = '';
        $debuginfo = '';
    }

    // Append the error code to the debug info to make grepping and googling easier
    $debuginfo .= PHP_EOL."Error code: $errorcode";

    $backtrace = $ex->getTrace();
    $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
    array_unshift($backtrace, $place);

    // Be careful, no guarantee moodlelib.php is loaded.
    if (empty($module) || $module == 'moodle' || $module == 'core') {
        $module = 'error';
    }
    // Search for the $errorcode's associated string
    // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
    if (function_exists('get_string_manager')) {
        if (get_string_manager()->string_exists($errorcode, $module)) {
            $message = get_string($errorcode, $module, $a);
        } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
            // Search in moodle file if error specified - needed for backwards compatibility
            $message = get_string($errorcode, 'moodle', $a);
        } else {
            $message = $module . '/' . $errorcode;
            $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
        }
    } else {
        $message = $module . '/' . $errorcode;
        $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
    }

    // Remove some absolute paths from message and debugging info.
    $searches = array();
    $replaces = array();
    $cfgnames = array('tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
    foreach ($cfgnames as $cfgname) {
        if (property_exists($CFG, $cfgname)) {
            $searches[] = $CFG->$cfgname;
            $replaces[] = "[$cfgname]";
        }
    }
    if (!empty($searches)) {
        $message   = str_replace($searches, $replaces, $message);
        $debuginfo = str_replace($searches, $replaces, $debuginfo);
    }

    // Be careful, no guarantee weblib.php is loaded.
    if (function_exists('clean_text')) {
        $message = clean_text($message);
    } else {
        $message = htmlspecialchars($message);
    }

    if (!empty($CFG->errordocroot)) {
        $errordoclink = $CFG->errordocroot . '/en/';
    } else {
        $errordoclink = get_docs_url();
    }

    if ($module === 'error') {
        $modulelink = 'moodle';
    } else {
        $modulelink = $module;
    }
    $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;

    if (empty($link)) {
        if (!empty($SESSION->fromurl)) {
            $link = $SESSION->fromurl;
            unset($SESSION->fromurl);
        } else {
            $link = $CFG->wwwroot .'/';
        }
    }

    // when printing an error the continue button should never link offsite
    if (stripos($link, $CFG->wwwroot) === false &&
        stripos($link, $CFG->httpswwwroot) === false) {
        $link = $CFG->wwwroot.'/';
    }

    $info = new stdClass();
    $info->message     = $message;
    $info->errorcode   = $errorcode;
    $info->backtrace   = $backtrace;
    $info->link        = $link;
    $info->moreinfourl = $moreinfourl;
    $info->a           = $a;
    $info->debuginfo   = $debuginfo;

    return $info;
}

/**
 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
 *
 * There are three cases:
 *
 * 1. In the normal case, $path will be a short relative path 'component/thing',
 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
 * MoodleDocs in the user's language, and for the appropriate Moodle version.
 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
 *
 * This is the only option that should be used in standard Moodle code. The other
 * two options have been implemented because they are useful for third-party plugins.
 *
 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
 * the link is used as is.
 *
 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
 * $CFG->wwwroot to make the link.
 *
 * @param string $path the place to link to. See above for details.
 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
 */
function get_docs_url($path = null) {
    global $CFG;

    // Absolute URLs are used unmodified.
    if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
        return $path;
    }

    // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
    if (substr($path, 0, 11) === '%%WWWROOT%%') {
        return $CFG->wwwroot . substr($path, 11);
    }

    // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.

    // Check that $CFG->branch has been set up, during installation it won't be.
    if (empty($CFG->branch)) {
        // It's not there yet so look at version.php.
        include($CFG->dirroot.'/version.php');
    } else {
        // We can use $CFG->branch and avoid having to include version.php.
        $branch = $CFG->branch;
    }
    // ensure branch is valid.
    if (!$branch) {
        // We should never get here but in case we do lets set $branch to .
        // the smart one's will know that this is the current directory
        // and the smarter ones will know that there is some smart matching
        // that will ensure people end up at the latest version of the docs.
        $branch = '.';
    }
    if (!empty($CFG->docroot)) {
        return $CFG->docroot . '/' . $branch . '/' . current_language() . '/' . $path;
    } else {
        return 'http://docs.moodle.org/'. $branch . '/' . current_language() . '/' . $path;
    }
}

/**
 * Formats a backtrace ready for output.
 *
 * @param array $callers backtrace array, as returned by debug_backtrace().
 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
 * @return string formatted backtrace, ready for output.
 */
function format_backtrace($callers, $plaintext = false) {
    // do not use $CFG->dirroot because it might not be available in destructors
    $dirroot = dirname(dirname(__FILE__));

    if (empty($callers)) {
        return '';
    }

    $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
    foreach ($callers as $caller) {
        if (!isset($caller['line'])) {
            $caller['line'] = '?'; // probably call_user_func()
        }
        if (!isset($caller['file'])) {
            $caller['file'] = 'unknownfile'; // probably call_user_func()
        }
        $from .= $plaintext ? '* ' : '<li>';
        $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
        if (isset($caller['function'])) {
            $from .= ': call to ';
            if (isset($caller['class'])) {
                $from .= $caller['class'] . $caller['type'];
            }
            $from .= $caller['function'] . '()';
        } else if (isset($caller['exception'])) {
            $from .= ': '.$caller['exception'].' thrown';
        }
        $from .= $plaintext ? "\n" : '</li>';
    }
    $from .= $plaintext ? '' : '</ul>';

    return $from;
}

/**
 * This function makes the return value of ini_get consistent if you are
 * setting server directives through the .htaccess file in apache.
 *
 * Current behavior for value set from php.ini On = 1, Off = [blank]
 * Current behavior for value set from .htaccess On = On, Off = Off
 * Contributed by jdell @ unr.edu
 *
 * @param string $ini_get_arg The argument to get
 * @return bool True for on false for not
 */
function ini_get_bool($ini_get_arg) {
    $temp = ini_get($ini_get_arg);

    if ($temp == '1' or strtolower($temp) == 'on') {
        return true;
    }
    return false;
}

/**
 * This function verifies the sanity of PHP configuration
 * and stops execution if anything critical found.
 */
function setup_validate_php_configuration() {
   // this must be very fast - no slow checks here!!!

   if (ini_get_bool('register_globals')) {
       print_error('globalswarning', 'admin');
   }
   if (ini_get_bool('session.auto_start')) {
       print_error('sessionautostartwarning', 'admin');
   }
   if (ini_get_bool('magic_quotes_runtime')) {
       print_error('fatalmagicquotesruntime', 'admin');
   }
}

/**
 * Initialise global $CFG variable.
 * @private to be used only from lib/setup.php
 */
function initialise_cfg() {
    global $CFG, $DB;

    if (!$DB) {
        // This should not happen.
        return;
    }

    try {
        $localcfg = get_config('core');
    } catch (dml_exception $e) {
        // Most probably empty db, going to install soon.
        return;
    }

    foreach ($localcfg as $name => $value) {
        // Note that get_config() keeps forced settings
        // and normalises values to string if possible.
        $CFG->{$name} = $value;
    }
}

/**
 * Initialises $FULLME and friends. Private function. Should only be called from
 * setup.php.
 */
function initialise_fullme() {
    global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;

    // Detect common config error.
    if (substr($CFG->wwwroot, -1) == '/') {
        print_error('wwwrootslash', 'error');
    }

    if (CLI_SCRIPT) {
        initialise_fullme_cli();
        return;
    }

    $rurl = setup_get_remote_url();
    $wwwroot = parse_url($CFG->wwwroot.'/');

    if (empty($rurl['host'])) {
        // missing host in request header, probably not a real browser, let's ignore them

    } else if (!empty($CFG->reverseproxy)) {
        // $CFG->reverseproxy specifies if reverse proxy server used
        // Used in load balancing scenarios.
        // Do not abuse this to try to solve lan/wan access problems!!!!!

    } else {
        if (($rurl['host'] !== $wwwroot['host']) or
                (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
                (strpos($rurl['path'], $wwwroot['path']) !== 0)) {

            // Explain the problem and redirect them to the right URL
            if (!defined('NO_MOODLE_COOKIES')) {
                define('NO_MOODLE_COOKIES', true);
            }
            // The login/token.php script should call the correct url/port.
            if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
                $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
                $calledurl = $rurl['host'];
                if (!empty($rurl['port'])) {
                    $calledurl .=  ':'. $rurl['port'];
                }
                $correcturl = $wwwroot['host'];
                if (!empty($wwwrootport)) {
                    $correcturl .=  ':'. $wwwrootport;
                }
                throw new moodle_exception('requirecorrectaccess', 'error', '', null,
                    'You called ' . $calledurl .', you should have called ' . $correcturl);
            }
            redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 0);
        }
    }

    // Check that URL is under $CFG->wwwroot.
    if (strpos($rurl['path'], $wwwroot['path']) === 0) {
        $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
    } else {
        // Probably some weird external script
        $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
        return;
    }

    // $CFG->sslproxy specifies if external SSL appliance is used
    // (That is, the Moodle server uses http, with an external box translating everything to https).
    if (empty($CFG->sslproxy)) {
        if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
            print_error('sslonlyaccess', 'error');
        }
    } else {
        if ($wwwroot['scheme'] !== 'https') {
            throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
        }
        $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
    }

    // hopefully this will stop all those "clever" admins trying to set up moodle
    // with two different addresses in intranet and Internet
    if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
        print_error('reverseproxyabused', 'error');
    }

    $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
    if (!empty($wwwroot['port'])) {
        $hostandport .= ':'.$wwwroot['port'];
    }

    $FULLSCRIPT = $hostandport . $rurl['path'];
    $FULLME = $hostandport . $rurl['fullpath'];
    $ME = $rurl['fullpath'];
}

/**
 * Initialises $FULLME and friends for command line scripts.
 * This is a private method for use by initialise_fullme.
 */
function initialise_fullme_cli() {
    global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;

    // Urls do not make much sense in CLI scripts
    $backtrace = debug_backtrace();
    $topfile = array_pop($backtrace);
    $topfile = realpath($topfile['file']);
    $dirroot = realpath($CFG->dirroot);

    if (strpos($topfile, $dirroot) !== 0) {
        // Probably some weird external script
        $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
    } else {
        $relativefile = substr($topfile, strlen($dirroot));
        $relativefile = str_replace('\\', '/', $relativefile); // Win fix
        $SCRIPT = $FULLSCRIPT = $relativefile;
        $FULLME = $ME = null;
    }
}

/**
 * Get the URL that PHP/the web server thinks it is serving. Private function
 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
 * @return array in the same format that parse_url returns, with the addition of
 *      a 'fullpath' element, which includes any slasharguments path.
 */
function setup_get_remote_url() {
    $rurl = array();
    if (isset($_SERVER['HTTP_HOST'])) {
        list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
    } else {
        $rurl['host'] = null;
    }
    $rurl['port'] = $_SERVER['SERVER_PORT'];
    $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
    $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';

    if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
        //Apache server
        $rurl['fullpath'] = $_SERVER['REQUEST_URI'];

    } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
        //IIS - needs a lot of tweaking to make it work
        $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];

        // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
        //       since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
        //       example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]

        if ($_SERVER['QUERY_STRING'] != '') {
            $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
        }
        $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility

/* NOTE: following servers are not fully tested! */

    } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
        //lighttpd - not officially supported
        $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

    } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
        //nginx - not officially supported
        if (!isset($_SERVER['SCRIPT_NAME'])) {
            die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
        }
        $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
         //cherokee - not officially supported
         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
         //zeus - not officially supported
         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

    } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
        //LiteSpeed - not officially supported
        $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

    } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
        //obscure name found on some servers - this is definitely not supported
        $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

    } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
        // built-in PHP Development Server
        $rurl['fullpath'] = $_SERVER['REQUEST_URI'];

    } else {
        throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
    }

    // sanitize the url a bit more, the encoding style may be different in vars above
    $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
    $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);

    return $rurl;
}

/**
 * Try to work around the 'max_input_vars' restriction if necessary.
 */
function workaround_max_input_vars() {
    // Make sure this gets executed only once from lib/setup.php!
    static $executed = false;
    if ($executed) {
        debugging('workaround_max_input_vars() must be called only once!');
        return;
    }
    $executed = true;

    if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
        // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
        return;
    }

    if (!isloggedin() or isguestuser()) {
        // Only real users post huge forms.
        return;
    }

    $max = (int)ini_get('max_input_vars');

    if ($max <= 0) {
        // Most probably PHP < 5.3.9 that does not implement this limit.
        return;
    }

    if ($max >= 200000) {
        // This value should be ok for all our forms, by setting it in php.ini
        // admins may prevent any unexpected regressions caused by this hack.

        // Note there is no need to worry about DDoS caused by making this limit very high
        // because there are very many easier ways to DDoS any Moodle server.
        return;
    }

    if (count($_POST, COUNT_RECURSIVE) < $max) {
        return;
    }

    // Large POST request with enctype supported by php://input.
    // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
    $str = file_get_contents("php://input");
    if ($str === false or $str === '') {
        // Some weird error.
        return;
    }

    $delim = '&';
    $fun = create_function('$p', 'return implode("'.$delim.'", $p);');
    $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));

    foreach ($chunks as $chunk) {
        $values = array();
        parse_str($chunk, $values);

        if (ini_get_bool('magic_quotes_gpc')) {
            // Use the same logic as lib/setup.php to work around deprecated magic quotes.
            $values = array_map('stripslashes_deep', $values);
        }

        merge_query_params($_POST, $values);
        merge_query_params($_REQUEST, $values);
    }
}

/**
 * Merge parsed POST chunks.
 *
 * NOTE: this is not perfect, but it should work in most cases hopefully.
 *
 * @param array $target
 * @param array $values
 */
function merge_query_params(array &$target, array $values) {
    if (isset($values[0]) and isset($target[0])) {
        // This looks like a split [] array, lets verify the keys are continuous starting with 0.
        $keys1 = array_keys($values);
        $keys2 = array_keys($target);
        if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
            foreach ($values as $v) {
                $target[] = $v;
            }
            return;
        }
    }
    foreach ($values as $k => $v) {
        if (!isset($target[$k])) {
            $target[$k] = $v;
            continue;
        }
        if (is_array($target[$k]) and is_array($v)) {
            merge_query_params($target[$k], $v);
            continue;
        }
        // We should not get here unless there are duplicates in params.
        $target[$k] = $v;
    }
}

/**
 * Initializes our performance info early.
 *
 * Pairs up with get_performance_info() which is actually
 * in moodlelib.php. This function is here so that we can
 * call it before all the libs are pulled in.
 *
 * @uses $PERF
 */
function init_performance_info() {

    global $PERF, $CFG, $USER;

    $PERF = new stdClass();
    $PERF->logwrites = 0;
    if (function_exists('microtime')) {
        $PERF->starttime = microtime();
    }
    if (function_exists('memory_get_usage')) {
        $PERF->startmemory = memory_get_usage();
    }
    if (function_exists('posix_times')) {
        $PERF->startposixtimes = posix_times();
    }
}

/**
 * Indicates whether we are in the middle of the initial Moodle install.
 *
 * Very occasionally it is necessary avoid running certain bits of code before the
 * Moodle installation has completed. The installed flag is set in admin/index.php
 * after Moodle core and all the plugins have been installed, but just before
 * the person doing the initial install is asked to choose the admin password.
 *
 * @return boolean true if the initial install is not complete.
 */
function during_initial_install() {
    global $CFG;
    return empty($CFG->rolesactive);
}

/**
 * Function to raise the memory limit to a new value.
 * Will respect the memory limit if it is higher, thus allowing
 * settings in php.ini, apache conf or command line switches
 * to override it.
 *
 * The memory limit should be expressed with a constant
 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
 * It is possible to use strings or integers too (eg:'128M').
 *
 * @param mixed $newlimit the new memory limit
 * @return bool success
 */
function raise_memory_limit($newlimit) {
    global $CFG;

    if ($newlimit == MEMORY_UNLIMITED) {
        ini_set('memory_limit', -1);
        return true;

    } else if ($newlimit == MEMORY_STANDARD) {
        if (PHP_INT_SIZE > 4) {
            $newlimit = get_real_size('128M'); // 64bit needs more memory
        } else {
            $newlimit = get_real_size('96M');
        }

    } else if ($newlimit == MEMORY_EXTRA) {
        if (PHP_INT_SIZE > 4) {
            $newlimit = get_real_size('384M'); // 64bit needs more memory
        } else {
            $newlimit = get_real_size('256M');
        }
        if (!empty($CFG->extramemorylimit)) {
            $extra = get_real_size($CFG->extramemorylimit);
            if ($extra > $newlimit) {
                $newlimit = $extra;
            }
        }

    } else if ($newlimit == MEMORY_HUGE) {
        // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
        $newlimit = get_real_size('2G');
        if (!empty($CFG->extramemorylimit)) {
            $extra = get_real_size($CFG->extramemorylimit);
            if ($extra > $newlimit) {
                $newlimit = $extra;
            }
        }

    } else {
        $newlimit = get_real_size($newlimit);
    }

    if ($newlimit <= 0) {
        debugging('Invalid memory limit specified.');
        return false;
    }

    $cur = ini_get('memory_limit');
    if (empty($cur)) {
        // if php is compiled without --enable-memory-limits
        // apparently memory_limit is set to ''
        $cur = 0;
    } else {
        if ($cur == -1){
            return true; // unlimited mem!
        }
        $cur = get_real_size($cur);
    }

    if ($newlimit > $cur) {
        ini_set('memory_limit', $newlimit);
        return true;
    }
    return false;
}

/**
 * Function to reduce the memory limit to a new value.
 * Will respect the memory limit if it is lower, thus allowing
 * settings in php.ini, apache conf or command line switches
 * to override it
 *
 * The memory limit should be expressed with a string (eg:'64M')
 *
 * @param string $newlimit the new memory limit
 * @return bool
 */
function reduce_memory_limit($newlimit) {
    if (empty($newlimit)) {
        return false;
    }
    $cur = ini_get('memory_limit');
    if (empty($cur)) {
        // if php is compiled without --enable-memory-limits
        // apparently memory_limit is set to ''
        $cur = 0;
    } else {
        if ($cur == -1){
            return true; // unlimited mem!
        }
        $cur = get_real_size($cur);
    }

    $new = get_real_size($newlimit);
    // -1 is smaller, but it means unlimited
    if ($new < $cur && $new != -1) {
        ini_set('memory_limit', $newlimit);
        return true;
    }
    return false;
}

/**
 * Converts numbers like 10M into bytes.
 *
 * @param string $size The size to be converted
 * @return int
 */
function get_real_size($size = 0) {
    if (!$size) {
        return 0;
    }
    $scan = array();
    $scan['GB'] = 1073741824;
    $scan['Gb'] = 1073741824;
    $scan['G'] = 1073741824;
    $scan['MB'] = 1048576;
    $scan['Mb'] = 1048576;
    $scan['M'] = 1048576;
    $scan['m'] = 1048576;
    $scan['KB'] = 1024;
    $scan['Kb'] = 1024;
    $scan['K'] = 1024;
    $scan['k'] = 1024;

    while (list($key) = each($scan)) {
        if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
            $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
            break;
        }
    }
    return $size;
}

/**
 * Try to disable all output buffering and purge
 * all headers.
 *
 * @access private to be called only from lib/setup.php !
 * @return void
 */
function disable_output_buffering() {
    $olddebug = error_reporting(0);

    // disable compression, it would prevent closing of buffers
    if (ini_get_bool('zlib.output_compression')) {
        ini_set('zlib.output_compression', 'Off');
    }

    // try to flush everything all the time
    ob_implicit_flush(true);

    // close all buffers if possible and discard any existing output
    // this can actually work around some whitespace problems in config.php
    while(ob_get_level()) {
        if (!ob_end_clean()) {
            // prevent infinite loop when buffer can not be closed
            break;
        }
    }

    // disable any other output handlers
    ini_set('output_handler', '');

    error_reporting($olddebug);
}

/**
 * Check whether a major upgrade is needed. That is defined as an upgrade that
 * changes something really fundamental in the database, so nothing can possibly
 * work until the database has been updated, and that is defined by the hard-coded
 * version number in this function.
 */
function redirect_if_major_upgrade_required() {
    global $CFG;
    $lastmajordbchanges = 2013100400.02;
    if (empty($CFG->version) or (float)$CFG->version < $lastmajordbchanges or
            during_initial_install() or !empty($CFG->adminsetuppending)) {
        try {
            @\core\session\manager::terminate_current();
        } catch (Exception $e) {
            // Ignore any errors, redirect to upgrade anyway.
        }
        $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
        @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
        @header('Location: ' . $url);
        echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
        exit;
    }
}

/**
 * Makes sure that upgrade process is not running
 *
 * To be inserted in the core functions that can not be called by pluigns during upgrade.
 * Core upgrade should not use any API functions at all.
 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
 *
 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
 * @param bool $warningonly if true displays a warning instead of throwing an exception
 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
 */
function upgrade_ensure_not_running($warningonly = false) {
    global $CFG;
    if (!empty($CFG->upgraderunning)) {
        if (!$warningonly) {
            throw new moodle_exception('cannotexecduringupgrade');
        } else {
            debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
            return false;
        }
    }
    return true;
}

/**
 * Function to check if a directory exists and by default create it if not exists.
 *
 * Previously this was accepting paths only from dataroot, but we now allow
 * files outside of dataroot if you supply custom paths for some settings in config.php.
 * This function does not verify that the directory is writable.
 *
 * NOTE: this function uses current file stat cache,
 *       please use clearstatcache() before this if you expect that the
 *       directories may have been removed recently from a different request.
 *
 * @param string $dir absolute directory path
 * @param boolean $create directory if does not exist
 * @param boolean $recursive create directory recursively
 * @return boolean true if directory exists or created, false otherwise
 */
function check_dir_exists($dir, $create = true, $recursive = true) {
    global $CFG;

    umask($CFG->umaskpermissions);

    if (is_dir($dir)) {
        return true;
    }

    if (!$create) {
        return false;
    }

    return mkdir($dir, $CFG->directorypermissions, $recursive);
}

/**
 * Create a directory and make sure it is writable.
 *
 * @private
 * @param string $dir  the full path of the directory to be created
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function make_writable_directory($dir, $exceptiononerror = true) {
    global $CFG;

    if (file_exists($dir) and !is_dir($dir)) {
        if ($exceptiononerror) {
            throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
        } else {
            return false;
        }
    }

    umask($CFG->umaskpermissions);

    if (!file_exists($dir)) {
        if (!mkdir($dir, $CFG->directorypermissions, true)) {
            clearstatcache();
            // There might be a race condition when creating directory.
            if (!is_dir($dir)) {
                if ($exceptiononerror) {
                    throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
                } else {
                    debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
                    return false;
                }
            }
        }
    }

    if (!is_writable($dir)) {
        if ($exceptiononerror) {
            throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
        } else {
            return false;
        }
    }

    return $dir;
}

/**
 * Protect a directory from web access.
 * Could be extended in the future to support other mechanisms (e.g. other webservers).
 *
 * @private
 * @param string $dir  the full path of the directory to be protected
 */
function protect_directory($dir) {
    global $CFG;
    // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
    if (!file_exists("$dir/.htaccess")) {
        if ($handle = fopen("$dir/.htaccess", 'w')) {   // For safety
            @fwrite($handle, "deny from all\r\nAllowOverride None\r\nNote: this file is broken intentionally, we do not want anybody to undo it in subdirectory!\r\n");
            @fclose($handle);
            @chmod("$dir/.htaccess", $CFG->filepermissions);
        }
    }
}

/**
 * Create a directory under dataroot and make sure it is writable.
 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
 *
 * @param string $directory  the full path of the directory to be created under $CFG->dataroot
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function make_upload_directory($directory, $exceptiononerror = true) {
    global $CFG;

    if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
        debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');

    } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
        debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');

    } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
        debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
    }

    protect_directory($CFG->dataroot);
    return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
}

/**
 * Create a directory under tempdir and make sure it is writable.
 * Temporary files should be used during the current request only!
 *
 * @param string $directory  the full path of the directory to be created under $CFG->tempdir
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function make_temp_directory($directory, $exceptiononerror = true) {
    global $CFG;
    if ($CFG->tempdir !== "$CFG->dataroot/temp") {
        check_dir_exists($CFG->tempdir, true, true);
        protect_directory($CFG->tempdir);
    } else {
        protect_directory($CFG->dataroot);
    }
    return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
}

/**
 * Create a directory under cachedir and make sure it is writable.
 *
 * Note: this cache directory is shared by all cluster nodes.
 *
 * @param string $directory  the full path of the directory to be created under $CFG->cachedir
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function make_cache_directory($directory, $exceptiononerror = true) {
    global $CFG;
    if ($CFG->cachedir !== "$CFG->dataroot/cache") {
        check_dir_exists($CFG->cachedir, true, true);
        protect_directory($CFG->cachedir);
    } else {
        protect_directory($CFG->dataroot);
    }
    return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
}

/**
 * Create a directory under localcachedir and make sure it is writable.
 * The files in this directory MUST NOT change, use revisions or content hashes to
 * work around this limitation - this means you can only add new files here.
 *
 * The content of this directory gets purged automatically on all cluster nodes
 * after calling purge_all_caches() before new data is written to this directory.
 *
 * Note: this local cache directory does not need to be shared by cluster nodes.
 *
 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
 * @param bool $exceptiononerror throw exception if error encountered
 * @return string|false Returns full path to directory if successful, false if not; may throw exception
 */
function make_localcache_directory($directory, $exceptiononerror = true) {
    global $CFG;

    make_writable_directory($CFG->localcachedir, $exceptiononerror);

    if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
        protect_directory($CFG->localcachedir);
    } else {
        protect_directory($CFG->dataroot);
    }

    if (!isset($CFG->localcachedirpurged)) {
        $CFG->localcachedirpurged = 0;
    }
    $timestampfile = "$CFG->localcachedir/.lastpurged";

    if (!file_exists($timestampfile)) {
        touch($timestampfile);
        @chmod($timestampfile, $CFG->filepermissions);

    } else if (filemtime($timestampfile) <  $CFG->localcachedirpurged) {
        // This means our local cached dir was not purged yet.
        remove_dir($CFG->localcachedir, true);
        if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
            protect_directory($CFG->localcachedir);
        }
        touch($timestampfile);
        @chmod($timestampfile, $CFG->filepermissions);
        clearstatcache();
    }

    if ($directory === '') {
        return $CFG->localcachedir;
    }

    return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
}

/**
 * Checks if current user is a web crawler.
 *
 * This list can not be made complete, this is not a security
 * restriction, we make the list only to help these sites
 * especially when automatic guest login is disabled.
 *
 * If admin needs security they should enable forcelogin
 * and disable guest access!!
 *
 * @return bool
 */
function is_web_crawler() {
    if (!empty($_SERVER['HTTP_USER_AGENT'])) {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) {  // Yahoo
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) {  // Zoomspider
            return true;
        } else if (stripos($_SERVER['HTTP_USER_AGENT'], 'msnbot') !== false ) {  // MSN Search
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'bingbot') !== false ) {  // Bing
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yandex') !== false ) {
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'AltaVista') !== false ) {
            return true;
        } else if (stripos($_SERVER['HTTP_USER_AGENT'], 'baiduspider') !== false ) {  // Baidu
            return true;
        } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Teoma') !== false ) {  // Ask.com
            return true;
        }
    }
    return false;
}

/**
 * This class solves the problem of how to initialise $OUTPUT.
 *
 * The problem is caused be two factors
 * <ol>
 * <li>On the one hand, we cannot be sure when output will start. In particular,
 * an error, which needs to be displayed, could be thrown at any time.</li>
 * <li>On the other hand, we cannot be sure when we will have all the information
 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
 * (potentially) depends on the current course, course categories, and logged in user.
 * It also depends on whether the current page requires HTTPS.</li>
 * </ol>
 *
 * So, it is hard to find a single natural place during Moodle script execution,
 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
 * adopt the following strategy
 * <ol>
 * <li>We will initialise $OUTPUT the first time it is used.</li>
 * <li>If, after $OUTPUT has been initialised, the script tries to change something
 * that $OUTPUT depends on, we throw an exception making it clear that the script
 * did something wrong.
 * </ol>
 *
 * The only problem with that is, how do we initialise $OUTPUT on first use if,
 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
 *
 * Note that this class is used before lib/outputlib.php has been loaded, so we
 * must be careful referring to classes/functions from there, they may not be
 * defined yet, and we must avoid fatal errors.
 *
 * @copyright 2009 Tim Hunt
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since     Moodle 2.0
 */
class bootstrap_renderer {
    /**
     * Handles re-entrancy. Without this, errors or debugging output that occur
     * during the initialisation of $OUTPUT, cause infinite recursion.
     * @var boolean
     */
    protected $initialising = false;

    /**
     * Have we started output yet?
     * @return boolean true if the header has been printed.
     */
    public function has_started() {
        return false;
    }

    /**
     * Constructor - to be used by core code only.
     * @param string $method The method to call
     * @param array $arguments Arguments to pass to the method being called
     * @return string
     */
    public function __call($method, $arguments) {
        global $OUTPUT, $PAGE;

        $recursing = false;
        if ($method == 'notification') {
            // Catch infinite recursion caused by debugging output during print_header.
            $backtrace = debug_backtrace();
            array_shift($backtrace);
            array_shift($backtrace);
            $recursing = is_early_init($backtrace);
        }

        $earlymethods = array(
            'fatal_error' => 'early_error',
            'notification' => 'early_notification',
        );

        // If lib/outputlib.php has been loaded, call it.
        if (!empty($PAGE) && !$recursing) {
            if (array_key_exists($method, $earlymethods)) {
                //prevent PAGE->context warnings - exceptions might appear before we set any context
                $PAGE->set_context(null);
            }
            $PAGE->initialise_theme_and_output();
            return call_user_func_array(array($OUTPUT, $method), $arguments);
        }

        $this->initialising = true;

        // Too soon to initialise $OUTPUT, provide a couple of key methods.
        if (array_key_exists($method, $earlymethods)) {
            return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
        }

        throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
    }

    /**
     * Returns nicely formatted error message in a div box.
     * @static
     * @param string $message error message
     * @param string $moreinfourl (ignored in early errors)
     * @param string $link (ignored in early errors)
     * @param array $backtrace
     * @param string $debuginfo
     * @return string
     */
    public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
        global $CFG;

        $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
width: 80%; -moz-border-radius: 20px; padding: 15px">
' . $message . '
</div>';
        // Check whether debug is set.
        $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
        // Also check we have it set in the config file. This occurs if the method to read the config table from the
        // database fails, reading from the config table is the first database interaction we have.
        $debug = $debug || (!empty($CFG->config_php_settings['debug'])  && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
        if ($debug) {
            if (!empty($debuginfo)) {
                $debuginfo = s($debuginfo); // removes all nasty JS
                $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
                $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
            }
            if (!empty($backtrace)) {
                $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
            }
        }

        return $content;
    }

    /**
     * This function should only be called by this class, or from exception handlers
     * @static
     * @param string $message error message
     * @param string $moreinfourl (ignored in early errors)
     * @param string $link (ignored in early errors)
     * @param array $backtrace
     * @param string $debuginfo extra information for developers
     * @return string
     */
    public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
        global $CFG;

        if (CLI_SCRIPT) {
            echo "!!! $message !!!\n";
            if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
                if (!empty($debuginfo)) {
                    echo "\nDebug info: $debuginfo";
                }
                if (!empty($backtrace)) {
                    echo "\nStack trace: " . format_backtrace($backtrace, true);
                }
            }
            return;

        } else if (AJAX_SCRIPT) {
            $e = new stdClass();
            $e->error      = $message;
            $e->stacktrace = NULL;
            $e->debuginfo  = NULL;
            if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
                if (!empty($debuginfo)) {
                    $e->debuginfo = $debuginfo;
                }
                if (!empty($backtrace)) {
                    $e->stacktrace = format_backtrace($backtrace, true);
                }
            }
            $e->errorcode  = $errorcode;
            @header('Content-Type: application/json; charset=utf-8');
            echo json_encode($e);
            return;
        }

        // In the name of protocol correctness, monitoring and performance
        // profiling, set the appropriate error headers for machine consumption.
        $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
        @header($protocol . ' 503 Service Unavailable');

        // better disable any caching
        @header('Content-Type: text/html; charset=utf-8');
        @header('X-UA-Compatible: IE=edge');
        @header('Cache-Control: no-store, no-cache, must-revalidate');
        @header('Cache-Control: post-check=0, pre-check=0', false);
        @header('Pragma: no-cache');
        @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
        @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');

        if (function_exists('get_string')) {
            $strerror = get_string('error');
        } else {
            $strerror = 'Error';
        }

        $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);

        return self::plain_page($strerror, $content);
    }

    /**
     * Early notification message
     * @static
     * @param string $message
     * @param string $classes usually notifyproblem or notifysuccess
     * @return string
     */
    public static function early_notification($message, $classes = 'notifyproblem') {
        return '<div class="' . $classes . '">' . $message . '</div>';
    }

    /**
     * Page should redirect message.
     * @static
     * @param string $encodedurl redirect url
     * @return string
     */
    public static function plain_redirect_message($encodedurl) {
        $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
                $encodedurl .'">'. get_string('continue') .'</a></div>';
        return self::plain_page(get_string('redirect'), $message);
    }

    /**
     * Early redirection page, used before full init of $PAGE global
     * @static
     * @param string $encodedurl redirect url
     * @param string $message redirect message
     * @param int $delay time in seconds
     * @return string redirect page
     */
    public static function early_redirect_message($encodedurl, $message, $delay) {
        $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
        $content = self::early_error_content($message, null, null, null);
        $content .= self::plain_redirect_message($encodedurl);

        return self::plain_page(get_string('redirect'), $content, $meta);
    }

    /**
     * Output basic html page.
     * @static
     * @param string $title page title
     * @param string $content page content
     * @param string $meta meta tag
     * @return string html page
     */
    public static function plain_page($title, $content, $meta = '') {
        if (function_exists('get_string') && function_exists('get_html_lang')) {
            $htmllang = get_html_lang();
        } else {
            $htmllang = '';
        }

        $footer = '';
        if (MDL_PERF_TEST) {
            $perfinfo = get_performance_info();
            $footer = '<footer>' . $perfinfo['html'] . '</footer>';
        }

        return '<!DOCTYPE html>
<html ' . $htmllang . '>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
'.$meta.'
<title>' . $title . '</title>
</head><body>' . $content . $footer . '</body></html>';
    }
}
package poker

import (
	"encoding/json"
	"os"
	"fmt"
	"sort"
)

type FileSystemPlayerStore struct {
	database *json.Encoder
	league   League
}

func FileSystemPlayerStoreFromFile(dbFileName string) (*FileSystemPlayerStore, func(), error) {
	db, err := os.OpenFile(dbFileName, os.O_CREATE|os.O_RDWR, 0666)
	err = ErrorFileOpening(err, dbFileName)
	if err != nil {
		return nil, nil, err
	}
	closeFunc := func() {
		db.Close()
	}
	store, err := NewFileSystemPlayerStore(db)
	err = ErrorFileCreation(err)
	if err != nil {
		return nil, nil, err
	}
	return store, closeFunc, nil
}

func initializePlayerDBFile(file *os.File) error {
	file.Seek(0, 0)
	info, err := file.Stat()
	if err != nil {
		return fmt.Errorf("problem getting file info from file %s, %v", file.Name(), err)
	}
	if info.Size() == 0 {
		file.Write([]byte("[]"))
		file.Seek(0, 0)
	}
	return nil
}

func NewFileSystemPlayerStore(file *os.File) (*FileSystemPlayerStore, error) {
	err := initializePlayerDBFile(file)
	if err != nil {
		return nil, fmt.Errorf("problem initializing player db file, %v", err)
	}
	league, err := NewLeague(file)
	if err != nil {
		return nil, fmt.Errorf("problem loading player store from file %s, %v", file.Name(), err)
	}
	return &FileSystemPlayerStore{json.NewEncoder(&Tape{file}), league}, nil
}

func (i *FileSystemPlayerStore) getPlayerScore(player string) int {
	play := i.GetLeague().Find(player)
	if play != nil {
		return play.Wins
	}
	return 0
}

func (i *FileSystemPlayerStore) RecordWin(player string) {
	play := i.league.Find(player)
	if play != nil {
		play.Wins++
	} else {
		i.league = append(i.league, Player{player, 1})
	}
	i.database.Encode(i.league)
}

func (i *FileSystemPlayerStore) GetLeague() League {
	sort.SliceStable(i.league, func(k, j int) bool {
		return i.league[k].Wins > i.league[j].Wins
	})
	return i.league
}
#include "WinSystemMirGLContext.h"

bool CWinSystemMirGLContext::CreateNewWindow(const std::string& name,
                                               bool fullScreen,
                                               const RESOLUTION_INFO& res)
{
  if (!m_pGLContext.CreateDisplay(m_connection,
                                  EGL_OPENGL_BIT,
                                  EGL_OPENGL_API))
  {
    return false;
  }

  m_pixel_format = mir_connection_get_egl_pixel_format(m_connection,
                                                       m_pGLContext.m_eglDisplay,
                                                       m_pGLContext.m_eglConfig);

  CWinSystemMir::CreateNewWindow(name, fullScreen, res);

  if (!m_pGLContext.CreateSurface(m_window))
  {
    return false;
  }

  if (!m_pGLContext.CreateContext())
  {
    return false;
  }

  return SetFullScreen(fullScreen, res, false);
}

bool CWinSystemMirGLContext::SetFullScreen(bool fullScreen, const RESOLUTION_INFO& res, bool blankOtherDisplays)
{
  auto ret = CWinSystemMir::SetFullScreen(fullScreen, res, blankOtherDisplays);
  if (ret)
  {
    CRenderSystemGL::ResetRenderSystem(res.iWidth, res.iHeight);
  }

  return ret;
}

void CWinSystemMirGLContext::SetVSyncImpl(bool enable)
{
  m_pGLContext.SetVSync(enable);
}

void CWinSystemMirGLContext::PresentRenderImpl(bool rendered)
{
  if (rendered)
  {
    m_pGLContext.SwapBuffers();
  }
}

EGLDisplay CWinSystemMirGLContext::GetEGLDisplay() const
{
  return m_pGLContext.m_eglDisplay;
}

EGLSurface CWinSystemMirGLContext::GetEGLSurface() const
{
  return m_pGLContext.m_eglSurface;
}

EGLContext CWinSystemMirGLContext::GetEGLContext() const
{
  return m_pGLContext.m_eglContext;
}

EGLConfig  CWinSystemMirGLContext::GetEGLConfig() const
{
  return m_pGLContext.m_eglConfig;
}

// FIXME Implement
bool CWinSystemMirGLContext::IsExtSupported(const char* extension)
{
  return false;
}
function disp_path(id) {    
    routeLayer.destroyFeatures();
    features = geojson_reader.read(paths[id]);
    if(features)
        routeLayer.addFeatures(features);
}

function compute() {
    if( areBothMarked() )
    {
        $.getJSON("path", {slon: nodes['start'].lon, 
                slat: nodes['start'].lat,
                dlon: nodes['dest'].lon,
                dlat: nodes['dest'].lat,
                time: $("#datepicker").val()
                },
        function(data) {
                if(data.error) {
                    $("#path_costs").html("<span class=\"errorOrange\">No route found</span>");
                clearPath();
                clearArrow("start");
                clearArrow("dest");
                }
            else {
                $("#path_costs").html("<span class=\"tableDes\">Costs:</span>\n<table id=\"costs_table\" class=\"tablesorter\">\n");
                $("#path_costs table").append("<thead><tr>");
                $.each(data.objectives, function(key, val){$("#path_costs tr").append(
                                        "<th>"+val+"</th>"
                                    );});
                $("#path_costs table").append("<tbody>");
                    $.each( data.paths, function(key, val){
                        $("#path_costs tbody").append("<tr>");
                        $.each(val.cost, function(k,v){
                        if( k != 0 ) {
                            if( parseInt(v) != 0 )
                                $("#path_costs tbody tr:last").append("<td><span class=\"tableDes\">"+v+"</span></td>");
                            else
                                $("#path_costs tbody tr:last").append("<td><span class=\"tableDes\">None</span></td>");
                        }
                        else {
                            $("#path_costs tbody tr:last").append(
                                        "<td>"+transformToDurationString(v)+"</td>"
                            );
                        }
                    });
                        $("#path_costs tbody tr:last").click(function(){disp_path(key); 
                    $("#path_costs tbody tr").removeClass("hl"); 
                    $(this).addClass("hl"); });});
                    $("#costs_table").tablesorter();
                paths = data.paths;
                disp_path(0);
                if( !fromHash )
                    addToHash();
            }
        });
        }
}

function handleClick(coord, mark) {
    var lonlat = map.getLonLatFromViewPortPx(coord);
    lonlat.transform(proj900913, proj4326);
    nodes['fmouse_'+mark]=true;
    reverseGeocoding(lonlat,mark);
}

// Coordinates in 4326 projection (lon/lat)
function setMark(lonlat, mark)
{
    if(node_markers[mark]) {
        layerMarkers.removeFeatures(node_markers[mark]);
        node_markers[mark].destroy();
        node_markers[mark] = null;
    }
    node_markers[mark] = new OpenLayers.Feature.Vector(LonLatToPoint(LonLatToM(
                                        new OpenLayers.LonLat(lonlat.lon,lonlat.lat))), 
                                        mark, 
                                        icon[mark]
    );
    layerMarkers.addFeatures(node_markers[mark]);
    layerMarkers.drawFeature(node_markers[mark]);
    
} // End of function setMark(lonlat, mark)

function areBothMarked() {
        return nodes['start'].lon && nodes['dest'].lat && nodes['dest'].lon && nodes['dest'].lat; 
}

function addToHash() {
    var tmp = new OpenLayers.LonLat(map.center.lon, map.center.lat).transform(
                                map.getProjectionObject(),
                                new OpenLayers.Projection("EPSG:4326")
    );                      
    $.getJSON("addhash", {
                mlon: tmp.lon,
                mlat: tmp.lat,
                zoom: map.zoom,                                 
                slon: nodes['start'].lon, 
                slat: nodes['start'].lat,
                dlon: nodes['dest'].lon,
                dlat: nodes['dest'].lat,
                time: $("#datepicker").val(),
                saddress: document.getElementById('startAdr').value,
                daddress: document.getElementById('endAdr').value
                },
                function(data)
                {
                    if(data.error)
                    {
                        $("#hash_url").html(
                        "<span class=\"errorOrange\">Couldn't add the route into the database</span>"
                        );
                    }
                    else
                    {
                        $("#hash_url").html(
                        "<p>Send this url to a friend : <br/><span class=\"tinyText\">" +
                        hurl +"h?id="+data.h+"</span></p>"
                        );  
                    }
                }
    );
}

function transformToDurationString(v) {
    var tmp = parseInt(v);
    var minutes = ( tmp / 60) % 60;
    var hours = tmp / 3600;
    if( (Math.ceil(hours) - 1) > 0 )
        return ( (Math.ceil(hours) - 1) + "h" + (Math.ceil(minutes)) + "m");
    else
        return ( (Math.ceil(minutes) ) + "m");
}       

//Initialise the 'map' object
function init() {
    AnyTime.picker( "datepicker", { format: "%e/%m/%Y %H:%i", firstDOW: 1 } );
    $("#datepicker").val(now);
    document.getElementById('startAdr').value = initialStartText;
    document.getElementById('endAdr').value = initialDestText;
    cacheStart = "";
    cacheDest = "";
    nodes['fmouse_start'] = true;
    nodes['fmouse_dest'] = true;
    map = new OpenLayers.Map ("map",
                
                {
                    maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
                    maxResolution: 156543.0399,
                    numZoomLevels: 19,
                    units: 'm',
                    projection: proj900913,
                    displayProjection: proj4326,
                    controls: [
                      new OpenLayers.Control.Navigation({zoomWheelEnabled: true}),
                      new OpenLayers.Control.PanZoomBar(),
                      new OpenLayers.Control.LayerSwitcher(),
                  ]
                }
    );
    // Define the map layer
    // Other defined layers are OpenLayers.Layer.OSM.Mapnik, OpenLayers.Layer.OSM.Maplint and OpenLayers.Layer.OSM.CycleMap
    layerTilesMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
    map.addLayer(layerTilesMapnik);
    var cloudmade = new OpenLayers.Layer.CloudMade("CloudMade", {
    key: 'fff941bc66c34422a2e41a529e34aebc',
    styleId: 7843
});
    map.addLayer(cloudmade);
     layerTilesCycle = new OpenLayers.Layer.OSM.CycleMap("CycleMap");
    map.addLayer(layerTilesCycle);
    layerTilesAtHome = new OpenLayers.Layer.OSM.Osmarender("Osmarender");
    map.addLayer(layerTilesAtHome);
    var styleMap = new OpenLayers.StyleMap({strokeWidth: 3});
    layers[ "connection" ] = {strokeColor: '#830531', strokeDashstyle: 'dashdot', strokeWidth: 2}
    styleMap.addUniqueValueRules("default", "layer", layers);
    routeLayer = new OpenLayers.Layer.Vector("Route", {
                    styleMap: styleMap
                    });
    map.addLayer(routeLayer);
    bikeLayer = new OpenLayers.Layer.Text( "Bike Stations",{
                    location:"./bikes",
                    projection: map.displayProjection
                    });
    map.addLayer(layerMarkers);
    map.addLayer(bikeLayer);
    bikeLayer.setZIndex(730);
    if( ! map.getCenter() ){
        var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
        map.setCenter (lonLat, zoom);
    }
    controlDrag = new OpenLayers.Control.DragFeature(layerMarkers, {
            'onStart': function(feature) {
                feature.style.graphicOpacity = 0.5;
            },
            'onComplete': function(feature) {
                lonlat = new OpenLayers.LonLat(feature.geometry.x,feature.geometry.y);
                ll = MToLonLat(lonlat);
                feature.style.graphicOpacity = 1.0;
                nodes['fmouse_'+feature.data]=true;
                reverseGeocoding(lonlat,feature.data);
                setMark(lonlat,feature.data);
            }
    });
    map.addControl(controlDrag);
    controlDrag.activate();
    if( fromHash ) {
        var tmpStart = new OpenLayers.LonLat(lonStart, latStart);
        var tmpDest = new OpenLayers.LonLat(lonDest, latDest);
        nodes['start'] = {
            'lon': lonStart,
            'lat': latStart
        };
        nodes['dest'] = {
            'lon': lonDest,
            'lat': latDest
        };
        setMark(tmpStart,"start");
        setMark(tmpDest,"dest");
        compute();
    }
    else {
        s = {
            'lon': lonStart,
            'lat': latStart
        }
        d = {
            'lon': lonDest,
            'lat': latDest
        }
        centerToMap(s,d)
    }
    $("#map").contextMenu({
        menu: 'myMenu'
    },
        function(action, el, pos) {
            var tmp = {
                'x': pos.x,
                    'y': pos.y
            };          
            handleClick( tmp, action);
    });
    showDescription( layers );  
} //End of function init()

function hasChanged(mark) {
    if( mark == "start" ) {
        var tmp = document.getElementById('startAdr').value;
        if( tmp.length == cacheStart.length ) {
            if( tmp == cacheStart)
                return false;
            else
                return true;
        }
        else
            return true;
    }
    else if( mark == "dest" ) {
        var tmp = document.getElementById('endAdr').value;
        if( tmp.length == cacheDest.length ) {
            if( tmp == cachDest)
                return false;
            else
                return true;
        }
        else
            return true;
    }
}

function clearPath() {
    $("#routing_description").html("");
    $("#path_costs").html("");
    $("#hash_url").html("");
    routeLayer.destroyFeatures();   
}

function clearArrow(mark) {
    nodes[mark] = null;
    layerMarkers.removeFeatures(node_markers[mark]);
    node_markers[mark].destroy(); 
    node_markers[mark] = null;
}

function geocoding(str,mark) {
    var url = "geo";
    $.getJSON(url, {q: str},
        function(data) {
                if( data.cord_error != '' ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html("<span class=\"errorOrange\">Nothing found. Please type again.</span>");
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html("<span class=\"errorOrange\">Nothing found. Please type again.</span>");
                        clearPath();
                        clearArrow(mark);
                    }               
                }
                else if( !data.is_covered ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html("<span class=\"errorOrange\">Not in covered zone.</span>");
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html("<span class=\"errorOrange\">Not in covered zone.</span>");
                        clearPath();
                        clearArrow(mark);
                    }               
                }               
                else if( data.node_error != '' ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html(
                            "<span class=\"errorOrange\">Can not find a node. Retry with a different address.</span>"
                        );
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html(
                            "<span class=\"errorOrange\">Can not find a node. Retry with a different address.</span>"
                        );
                        clearPath();
                        clearArrow(mark);
                    }               
                }
                else {              
                    var cord = new OpenLayers.LonLat(data.lon, data.lat);
                    if( mark == "start" )
                        document.getElementById('startAdr').value = data.display_name;
                    else if( mark == "dest" )
                        document.getElementById('endAdr').value = data.display_name;
                    if( hasChanged(mark) ) {    
                        nodes['fmouse_'+mark] = false;      
                        nodes[mark] = {
                            'lon': data.lon,
                            'lat': data.lat
                        };                      
                        setMark(cord,mark);
                        if( areBothMarked() ) { 
                            if( !nodes['fmouse_start'] || !nodes['fmouse_dest'] ) {
                                centerToMap(nodes['start'],nodes['dest']);
                            }
                            compute();
                        }
                    }
                }
        }
    );
}

function validateAddresses(f) {
    document.getElementById('startAdr').style.backgroundColor = "#ffffff";
    document.getElementById('endAdr').style.backgroundColor = "#ffffff";
    if($("#startAdr").val() == '') {
        document.getElementById('startAdr').focus();
        document.getElementById('startAdr').style.backgroundColor = "#f64444";
        $("#formError_start").html("<span class=\"errorRed\">Enter a starting address</span>");
        clearPath();
        clearArrow("start");
    }
    else {
        document.getElementById('startAdr').style.backgroundColor = "#ffffff";
        $("#formError_start").html("");
    }
    if($("#endAdr").val() == '') {
        document.getElementById('endAdr').focus();
        document.getElementById('endAdr').style.backgroundColor = "#f64444";
        $("#formError_dest").html("<span class=\"errorRed\">Enter a destination</span>");
        clearPath();
        clearArrow("dest");
    }
    else {
        document.getElementById('endAdr').style.backgroundColor = "#ffffff";
        $("#formError_dest").html("");
    }
    if( ($("#startAdr").val() != '') && ($("#endAdr").val() != '') ) {
        document.getElementById('startAdr').style.backgroundColor = "#ffffff";
        document.getElementById('endAdr').style.backgroundColor = "#ffffff";
        geocoding( $("#startAdr").val(), "start" );
        geocoding( $("#endAdr").val(), "dest" );
    }
}

function reverseLocations() {
    var tmp = document.getElementById("startAdr").value;
    document.getElementById("startAdr").value = document.getElementById("endAdr").value;
    document.getElementById("endAdr").value = tmp;
    return true;
}

function reverseGeocoding(lonlat,mark) {
    var url = "revgeo";
    $.getJSON(url, {lon: lonlat.lon, lat:lonlat.lat},
        function(data) {
            if( data.cord_error != '' ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html("<span class=\"errorOrange\">Nothing found. Please type again.</span>");
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html("<span class=\"errorOrange\">Nothing found. Please type again.</span>");
                        clearPath();
                        clearArrow(mark);
                    }               
                }
                else if( !data.is_covered ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html("<span class=\"errorOrange\">Not in covered zone.</span>");
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html("<span class=\"errorOrange\">Not in covered zone.</span>");
                        clearPath();
                        clearArrow(mark);
                    }               
                }               
                else if( data.node_error != '' ) {
                    if( mark == "start" ) {
                        document.getElementById('startAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_start").html(
                            "<span class=\"errorOrange\">Can not find a node. Retry with a different address.</span>"
                        );
                        clearPath();
                        clearArrow(mark);
                    
                    }                   
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').style.backgroundColor = "#f48b5d";
                        $("#formError_dest").html(
                            "<span class=\"errorOrange\">Can not find a node. Retry with a different address.</span>"
                        );
                        clearPath();
                        clearArrow(mark);
                    }               
                }
                else {              
                    var cord = new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
                    if( mark == "start" ) {
                        document.getElementById('startAdr').value = data.display_name;
                        document.getElementById('startAdr').style.backgroundColor = "#ffffff";
                        $("#formError_start").html("");
                    }
                    else if( mark == "dest" ) {
                        document.getElementById('endAdr').value = data.display_name;
                        document.getElementById('endAdr').style.backgroundColor = "#ffffff";
                        $("#formError_dest").html("");
                    }
                    nodes[mark] = {
                        'lon': lonlat.lon,
                        'lat': lonlat.lat
                    };
                    setMark(cord,mark);                 
                    
                     if( areBothMarked() ) { 
                        compute();
                    }
                }
        });
}

function centerToMap(start,dest) {
    var left,right,top,bottom;  
    var tmps = new OpenLayers.LonLat(start.lon, start.lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
    var tmpd = new OpenLayers.LonLat(dest.lon, dest.lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
    if( tmps.lon > tmpd.lon) {
        right = tmps.lon;
        left = tmpd.lon;
    }       
    else {
        left = tmps.lon;
        right = tmpd.lon;
    }   
    if( tmps.lat > tmpd.lat) {
        top = tmps.lat;
        bottom = tmpd.lat;  
    }   
    else {
        bottom = tmps.lat;
        top = tmpd.lat;
    }
    map.zoomToExtent( new OpenLayers.Bounds( left, bottom, right, top ) );
}


function LonLatToPoint(ll) {
    return new OpenLayers.Geometry.Point(ll.lon,ll.lat);
}

function LonLatToM(ll) {
    return ll.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
}

function MToLonLat(ll) {
    return ll.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
}

function showDescription( l ) {
    //$("#routing_description").html("<table><caption><span>Routing description:</span></caption><thread><tr><td><span class=\"tinyText\">Transport</span></td><td><span class=\"tinyText\">Color<span class=\"tinyText\"></td></tr></thread><tbody>");
    $("#routing_description").html("<caption><span>Routing description:</span></caption><thread><tr><td><span class=\"tinyText\">Transport</span></td><td><span class=\"tinyText\">Color<span class=\"tinyText\"></td></tr></thread><tbody>");
    $.each( l, function(key, val){
        $("#routing_description").append("<tr><td><span class=\"tinyText\">" + key + "</span></td><td><hr width=\"60\" size=\"4\" color=\"" + val.strokeColor + "\"></td></tr>");
    });
    $("#routing_description").append("</tbody>");
    
}


