text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SimpleVariableDeclarations.VariableInitializer</title>
<meta name="date" content="2015-09-10">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

weka.core.expressionlanguage.common

Class SimpleVariableDeclarations.VariableInitializer

java.lang.Object

weka.core.expressionlanguage.common.SimpleVariableDeclarations.VariableInitializer

All Implemented Interfaces:

java.io.Serializable

Enclosing class:

SimpleVariableDeclarations

public static class SimpleVariableDeclarations.VariableInitializer
extends java.lang.Object
implements java.io.Serializable

A class to initialize variables that have been declared by a
 SimpleVariableDeclarations class and used inside a program

 Note that not all variables declared can be initialized!

 Particularly variables that have been declared but are never used inside a
 program can't be initialized.

 Then variable values that are expensive to compute don't have to be computed
 if the values are never used inside a program.

Version:

$Revision: 1000 $

Author:

Benjamin Weber ( benweber at student dot ethz dot ch )

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

SimpleVariableDeclarations.VariableInitializer()

Method Summary

Methods

Modifier and Type
Method and Description

java.util.Set<java.lang.String>
getVariables()

Returns the set of variable names that can be initialized

boolean
hasVariable(java.lang.String variable)

Returns whether the SimpleVariableDeclarations.VariableInitializer contains the variable

void
setBoolean(java.lang.String name,
          boolean value)

Sets the value of a boolean variable

void
setDouble(java.lang.String name,
         double value)

Sets the value of a double variable

void
setString(java.lang.String name,
         java.lang.String value)

Sets the value of a string variable

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SimpleVariableDeclarations.VariableInitializer

public SimpleVariableDeclarations.VariableInitializer()

Method Detail

getVariables

public java.util.Set<java.lang.String> getVariables()

Returns the set of variable names that can be initialized

Returns:

the set of variable names that can be initialized

hasVariable

public boolean hasVariable(java.lang.String variable)

Returns whether the SimpleVariableDeclarations.VariableInitializer contains the variable

Parameters:

variable - name of the variable

Returns:

whether the variable exists

setBoolean

public void setBoolean(java.lang.String name,
              boolean value)

Sets the value of a boolean variable

 Requires that the variable exists and is of boolean type.

Parameters:

name - name of the boolean variable

value - the value the boolean variable will be set to

setDouble

public void setDouble(java.lang.String name,
             double value)

Sets the value of a double variable

 Requires that the variable exists and is of double type.

Parameters:

name - the name of the double variable

value - the value the double variable will be set to

setString

public void setString(java.lang.String name,
             java.lang.String value)

Sets the value of a string variable

 Requires that the variable exists and is of string type.

Parameters:

name - the name of the string variable

value - the value the string variable will be set to

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
require 'spec_helper'

RSpec.describe OneviewSDK::API800::C7000::FCNetwork do
  include_context 'shared context'

  it 'inherits from OneviewSDK::API600::C7000::FCNetwork' do
    expect(described_class).to be < OneviewSDK::API600::C7000::FCNetwork
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?><concept xmlns="http://www.w3.org/2004/02/skos/core#">
      <prefLabel>UNASSIGNED CLAIM</prefLabel>
      <definition>A claim submitted for a service or supply by a provider who does not accept
         assignment.</definition>
   </concept>


text:
namespace net {

namespace sha256_interception {

namespace {

using ScopedX509_ALGOR = crypto::ScopedOpenSSL<X509_ALGOR, X509_ALGOR_free>;

bool IsSupportedSubjectType(DWORD subject_type) {
  switch (subject_type) {
    case CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB:
    case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT:
    case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL:
      return true;
  }
  return false;
}

bool IsSupportedIssuerType(DWORD issuer_type) {
  switch (issuer_type) {
    case CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY:
    case CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT:
    case CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN:
      return true;
  }
  return false;
}

base::StringPiece GetSubjectSignature(DWORD subject_type,
                                      void* subject_data) {
  switch (subject_type) {
    case CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB: {
      CRYPT_DATA_BLOB* data_blob =
          reinterpret_cast<CRYPT_DATA_BLOB*>(subject_data);
      return base::StringPiece(reinterpret_cast<char*>(data_blob->pbData),
                               data_blob->cbData);
    }
    case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT: {
      PCCERT_CONTEXT subject_cert =
          reinterpret_cast<PCCERT_CONTEXT>(subject_data);
      return base::StringPiece(
          reinterpret_cast<char*>(subject_cert->pbCertEncoded),
          subject_cert->cbCertEncoded);
    }
    case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL: {
      PCCRL_CONTEXT subject_crl =
          reinterpret_cast<PCCRL_CONTEXT>(subject_data);
      return base::StringPiece(
          reinterpret_cast<char*>(subject_crl->pbCrlEncoded),
          subject_crl->cbCrlEncoded);
    }
  }
  return base::StringPiece();
}

PCERT_PUBLIC_KEY_INFO GetIssuerPublicKey(DWORD issuer_type,
                                         void* issuer_data) {
  switch (issuer_type) {
    case CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY:
      return reinterpret_cast<PCERT_PUBLIC_KEY_INFO>(issuer_data);
    case CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT: {
      PCCERT_CONTEXT cert = reinterpret_cast<PCCERT_CONTEXT>(issuer_data);
      return &cert->pCertInfo->SubjectPublicKeyInfo;
    }
    case CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN: {
      PCCERT_CHAIN_CONTEXT chain =
          reinterpret_cast<PCCERT_CHAIN_CONTEXT>(issuer_data);
      PCCERT_CONTEXT cert = chain->rgpChain[0]->rgpElement[0]->pCertContext;
      return &cert->pCertInfo->SubjectPublicKeyInfo;
    }
  }
  return NULL;
}

// Parses |subject_signature| and writes the components into |*out_tbs_data|,
// |*out_algor|, and |*out_signature|. The BIT STRING in the signature must be
// a multiple of 8 bits. |*out_signature| will have the padding byte removed.
// It returns true on success and false on failure.
bool ParseSubjectSignature(const base::StringPiece& subject_signature,
                           CBS* out_tbs_data,
                           ScopedX509_ALGOR* out_algor,
                           CBS* out_signature) {
  CBS cbs, sequence, tbs_data, algorithm, signature;
  CBS_init(&cbs, reinterpret_cast<const uint8_t*>(subject_signature.data()),
           subject_signature.size());
  if (!CBS_get_asn1(&cbs, &sequence, CBS_ASN1_SEQUENCE) || CBS_len(&cbs) != 0 ||
      !CBS_get_any_asn1_element(&sequence, &tbs_data, nullptr, nullptr) ||
      !CBS_get_asn1_element(&sequence, &algorithm, CBS_ASN1_SEQUENCE) ||
      !CBS_get_asn1(&sequence, &signature, CBS_ASN1_BITSTRING) ||
      CBS_len(&sequence) != 0) {
    return false;
  }

  // Decode the algorithm.
  const uint8_t* ptr = CBS_data(&algorithm);
  ScopedX509_ALGOR algor(d2i_X509_ALGOR(NULL, &ptr, CBS_len(&algorithm)));
  if (!algor || ptr != CBS_data(&algorithm) + CBS_len(&algorithm))
    return false;

  // An ASN.1 BIT STRING is encoded with a leading byte denoting the number of
  // padding bits. All supported signature algorithms output octets, so the
  // leading byte must be zero.
  uint8_t padding;
  if (!CBS_get_u8(&signature, &padding) || padding != 0)
    return false;

  *out_tbs_data = tbs_data;
  *out_algor = algor.Pass();
  *out_signature = signature;
  return true;
}

}  // namespace

BOOL CryptVerifyCertificateSignatureExHook(
    CryptVerifyCertificateSignatureExFunc original_func,
    HCRYPTPROV_LEGACY provider,
    DWORD encoding_type,
    DWORD subject_type,
    void* subject_data,
    DWORD issuer_type,
    void* issuer_data,
    DWORD flags,
    void* extra) {
  CHECK(original_func);

  // Only intercept if the arguments are supported.
  if (provider != NULL || (encoding_type != X509_ASN_ENCODING) ||
      !IsSupportedSubjectType(subject_type) || subject_data == NULL ||
      !IsSupportedIssuerType(issuer_type) || issuer_data == NULL) {
    return original_func(provider, encoding_type, subject_type, subject_data,
                         issuer_type, issuer_data, flags, extra);
  }

  base::StringPiece subject_signature =
      GetSubjectSignature(subject_type, subject_data);
  bool should_intercept = false;

  // Parse out the data, AlgorithmIdentifier, and signature.
  CBS tbs_data, signature;
  ScopedX509_ALGOR algor;
  if (ParseSubjectSignature(subject_signature, &tbs_data, &algor, &signature)) {
    // If the signature algorithm is RSA with one of the SHA-2 algorithms
    // supported by BoringSSL (excluding SHA-224, which is pointless), then
    // defer to the BoringSSL implementation. Otherwise, fall back and let the
    // OS handle it (e.g. in case there are any algorithm policies in effect).
    int nid = OBJ_obj2nid(algor->algorithm);
    if (nid == NID_sha256WithRSAEncryption ||
        nid == NID_sha384WithRSAEncryption ||
        nid == NID_sha512WithRSAEncryption) {
      should_intercept = true;
    }
  }

  if (!should_intercept) {
    return original_func(provider, encoding_type, subject_type, subject_data,
                         issuer_type, issuer_data, flags, extra);
  }

  // Rather than attempting to synthesize an EVP_PKEY by hand, just force the
  // OS to do an ASN.1 encoding and then decode it back into BoringSSL. This
  // is silly for performance, but safest for consistency.
  PCERT_PUBLIC_KEY_INFO issuer_public_key =
      GetIssuerPublicKey(issuer_type, issuer_data);
  if (!issuer_public_key) {
    SetLastError(static_cast<DWORD>(NTE_BAD_ALGID));
    return FALSE;
  }

  uint8_t* issuer_spki_data = NULL;
  DWORD issuer_spki_len = 0;
  if (!CryptEncodeObjectEx(X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO,
                           issuer_public_key, CRYPT_ENCODE_ALLOC_FLAG, NULL,
                           &issuer_spki_data, &issuer_spki_len)) {
    return FALSE;
  }

  const uint8_t* ptr = issuer_spki_data;
  crypto::ScopedEVP_PKEY pubkey(d2i_PUBKEY(NULL, &ptr, issuer_spki_len));
  if (!pubkey.get() || ptr != issuer_spki_data + issuer_spki_len) {
    ::LocalFree(issuer_spki_data);
    SetLastError(static_cast<DWORD>(NTE_BAD_ALGID));
    return FALSE;
  }
  ::LocalFree(issuer_spki_data);

  crypto::ScopedEVP_MD_CTX md_ctx(EVP_MD_CTX_create());
  if (!EVP_DigestVerifyInitFromAlgorithm(md_ctx.get(), algor.get(),
                                         pubkey.get()) ||
      !EVP_DigestVerifyUpdate(md_ctx.get(), CBS_data(&tbs_data),
                              CBS_len(&tbs_data)) ||
      !EVP_DigestVerifyFinal(md_ctx.get(), CBS_data(&signature),
                             CBS_len(&signature))) {
    SetLastError(static_cast<DWORD>(NTE_BAD_SIGNATURE));
    return FALSE;
  }
  return TRUE;
}

}  // namespace sha256_interception

}  // namespace net


text:
var QUnit = require("steal-qunit");

var define = require("can-define");
var queues = require("can-queues");
var canSymbol = require("can-symbol");
var SimpleObservable = require("can-simple-observable");
var testHelpers = require("can-test-helpers");
var canReflect = require("can-reflect");
var ObservationRecorder = require("can-observation-recorder");

QUnit.module("can-define");

QUnit.test("basics on a prototype", function(assert) {
	assert.expect(5);

	var Person = function(first, last) {
		this.first = first;
		this.last = last;
	};
	define(Person.prototype, {
		first: "*",
		last: "*",
		fullName: {
			get: function() {
				return this.first + " " + this.last;
			}
		}
	});

	var p = new Person("Mohamed", "Cherif");

	p.bind("fullName", function(ev, newVal, oldVal) {
		assert.equal(oldVal, "Mohamed Cherif");
		assert.equal(newVal, "Justin Meyer");
	});

	assert.equal(p.fullName, "Mohamed Cherif", "fullName initialized right");

	p.bind("first", function(el, newVal, oldVal) {
		assert.equal(newVal, "Justin", "first new value");
		assert.equal(oldVal, "Mohamed", "first old value");
	});

	queues.batch.start();
	p.first = "Justin";
	p.last = "Meyer";
	queues.batch.stop();

});

QUnit.test('basics set', function(assert) {
	assert.expect(2);
	var Defined = function(prop) {
		this.prop = prop;
	};

	define(Defined.prototype, {
		prop: {
			set: function(newVal) {
				return "foo" + newVal;
			}
		}
	});

	var def = new Defined();
	def.prop = "bar";

	assert.equal(def.prop, "foobar", "setter works");

	var DefinedCB = function(prop) {
		this.prop = prop;
	};

	define(DefinedCB.prototype, {
		prop: {
			set: function(newVal, setter) {
				setter("foo" + newVal);
			}
		}
	});

	var defCallback = new DefinedCB();
	defCallback.prop = "bar";
	assert.equal(defCallback.prop, "foobar", "setter callback works");

});

QUnit.test("basic Type", function(assert) {
	var Foo = function(name) {
		this.name = name;
	};
	Foo.prototype.getName = function() {
		return this.name;
	};

	var Typer = function(foo) {
		this.foo = foo;
	};

	define(Typer.prototype, {
		foo: {
			Type: Foo
		}
	});

	var t = new Typer("Justin");
	assert.equal(t.foo.getName(), "Justin", "correctly created an instance");

	var brian = new Foo("brian");

	t.foo = brian;

	assert.equal(t.foo, brian, "same instances");

});

QUnit.test("type converters", function(assert) {

	var Typer = function(date, string, number, bool, htmlbool, leaveAlone) {
		this.date = date;
		this.string = string;
		this.number = number;
		this.bool = bool;
		this.htmlbool = htmlbool;
		this.leaveAlone = leaveAlone;
	};

	define(Typer.prototype, {
		date: {
			type: 'date'
		},
		string: {
			type: 'string'
		},
		number: {
			type: 'number'
		},
		bool: {
			type: 'boolean'
		},
		htmlbool: {
			type: 'htmlbool'
		},
		leaveAlone: {
			type: '*'
		},
	});

	var obj = {};

	var t = new Typer(
		1395896701516,
		5,
		'5',
		'false',
		"",
		obj
	);

	assert.ok(t.date instanceof Date, "converted to date");

	assert.equal(t.string, '5', "converted to string");

	assert.equal(t.number, 5, "converted to number");

	assert.equal(t.bool, false, "converted to boolean");

	assert.equal(t.htmlbool, true, "converted to htmlbool");

	assert.equal(t.leaveAlone, obj, "left as object");

	t.number = '15';

	assert.ok(t.number === 15, "converted to number");

});

QUnit.test("basics value", function(assert) {

	var Typer = function(prop) {
		if (prop !== undefined) {
			this.prop = prop;
		}
	};

	define(Typer.prototype, {
		prop: {
			default: 'foo'
		}
	});
	var t = new Typer();

	assert.equal(t.prop, "foo", "value is used as default value");

	var Typer2 = function(prop) {
		if (prop !== undefined) {
			this.prop = prop;
		}
	};

	define(Typer2.prototype, {
		prop: {
			default: function() {
				return [];
			},
			type: "*"
		}
	});

	var t1 = new Typer2(),
		t2 = new Typer2();

	assert.ok(t1.prop !== t2.prop, "different array instances");
	assert.ok(Array.isArray(t1.prop), "its an array");

});

QUnit.test("basics Value", function(assert) {

	var Typer = function(prop) {
		//this.prop = prop;
	};
	define(Typer.prototype, {

		prop: {
			Default: Array,
			type: "*"
		}

	});

	var t1 = new Typer(),
		t2 = new Typer();
	assert.ok(t1.prop !== t2.prop, "different array instances");
	assert.ok(Array.isArray(t1.prop), "its an array");

});

QUnit.test("setter with no arguments and returns undefined does the default behavior, the setter is for side effects only", function(assert) {
	var Typer = function(prop) {
		//this.prop = prop;
	};
	define(Typer.prototype, {

		prop: {
			set: function() {
				this.foo = "bar";
			}
		},
		foo: "*"

	});

	var t = new Typer();

	t.prop = false;

	assert.deepEqual({
		foo: t.foo,
		prop: t.prop
	}, {
		foo: "bar",
		prop: false
	}, "got the right props");

});

QUnit.test("type happens before the set", function(assert) {
	assert.expect(2);

	var Typer = function() {};
	define(Typer.prototype, {

		prop: {
			type: "number",
			set: function(newValue) {
				assert.equal(typeof newValue, "number", "got a number");
				return newValue + 1;
			}
		}

	});

	var map = new Typer();
	map.prop = "5";

	assert.equal(map.prop, 6, "number");
});

QUnit.test("getter and setter work", function(assert) {
	assert.expect(5);

	var Paginate = define.Constructor({
		limit: "*",
		offset: "*",
		page: {
			set: function(newVal) {
				this.offset = (parseInt(newVal) - 1) * this.limit;
			},
			get: function() {
				return Math.floor(this.offset / this.limit) + 1;
			}
		}
	});

	var p = new Paginate({
		limit: 10,
		offset: 20
	});

	assert.equal(p.page, 3, "page get right");

	p.bind("page", function(ev, newValue, oldValue) {
		assert.equal(newValue, 2, "got new value event");
		assert.equal(oldValue, 3, "got old value event");
	});

	p.page = 2;

	assert.equal(p.page, 2, "page set right");

	assert.equal(p.offset, 10, "page offset set");

});

QUnit.test("getter with initial value", function(assert) {

	var comp = new SimpleObservable(1);

	var Grabber = define.Constructor({
		vals: {
			type: "*",
			Default: Array,
			get: function(current, setVal) {
				if (setVal) {
					current.push(comp.get());
				}
				return current;
			}
		}
	});

	var g = new Grabber();
	// This assertion doesn't mean much.  It's mostly testing
	// that there were no errors.
	assert.equal(g.vals.length, 0, "zero items in array");

});

/*
test("value generator is not called if default passed", function () {
	var TestMap = define.Constructor({
		foo: {
			value: function () {
				throw '"foo"\'s value method should not be called.';
			}
		}
	});

	var tm = new TestMap({ foo: 'baz' });

	equal(tm.foo, 'baz');
});*/

QUnit.test('default behaviors with "*" work for attributes', function(assert) {
	assert.expect(6);
	var DefaultMap = define.Constructor({
		'*': {
			type: 'number',
			set: function(newVal) {
				assert.ok(true, 'set called');
				return newVal;
			}
		},
		someNumber: {
			default: '5'
		},
		number: {}
	});

	var map = new DefaultMap();

	assert.equal(map.someNumber, '5', 'default values are not type converted anymore');
	map.someNumber = '5';
	assert.equal(map.someNumber, 5, 'on a set, they should be type converted');

	map.number = '10'; // Custom set should be called
	assert.equal(map.number, 10, 'value of number should be converted to a number');

});

QUnit.test("nested define", function(assert) {
	var nailedIt = 'Nailed it';

	var Example = define.Constructor({
		name: {
			default: nailedIt
		}
	});

	var NestedMap = define.Constructor({
		isEnabled: {
			default: true
		},
		test: {
			Default: Example
		},
		examples: {
			type: {
				one: {
					Default: Example
				},
				two: {
					type: {
						deep: {
							Default: Example
						}
					},
					Default: Object
				}
			},
			Default: Object
		}
	});

	var nested = new NestedMap();

	// values are correct
	assert.equal(nested.test.name, nailedIt);
	assert.equal(nested.examples.one.name, nailedIt);
	assert.equal(nested.examples.two.deep.name, nailedIt);

	// objects are correctly instanced
	assert.ok(nested.test instanceof Example);
	assert.ok(nested.examples.one instanceof Example);
	assert.ok(nested.examples.two.deep instanceof Example);
});

QUnit.test('Can make an attr alias a compute (#1470)', function(assert) {
	assert.expect(9);
	var computeValue = new SimpleObservable(1);

	var GetMap = define.Constructor({
		value: {
			set: function(newValue, setVal, oldValue) {
				if (newValue instanceof SimpleObservable) {
					return newValue;
				}
				if (oldValue && (oldValue instanceof SimpleObservable)) {
					oldValue.set(newValue);
					return oldValue;
				}
				return newValue;
			},
			get: function(value) {
				return value instanceof SimpleObservable ? value.get() : value;
			}
		}
	});

	var getMap = new GetMap();

	getMap.value = computeValue;

	assert.equal(getMap.value, 1, "initial value read from compute");

	var bindCallbacks = 0;

	getMap.bind("value", function(ev, newVal, oldVal) {

		switch (bindCallbacks) {
			case 0:
				assert.equal(newVal, 2, "0 - bind called with new val");
				assert.equal(oldVal, 1, "0 - bind called with old val");
				break;
			case 1:
				assert.equal(newVal, 3, "1 - bind called with new val");
				assert.equal(oldVal, 2, "1 - bind called with old val");
				break;
			case 2:
				assert.equal(newVal, 4, "2 - bind called with new val");
				assert.equal(oldVal, 3, "2 - bind called with old val");
				break;
		}

		bindCallbacks++;
	});

	// Try updating the compute's value
	computeValue.set(2);

	// Try setting the value of the property
	getMap.value = 3;

	assert.equal(getMap.value, 3, "read value is 3");
	assert.equal(computeValue.get(), 3, "the compute value is 3");

	// Try setting to a new comptue
	var newComputeValue = new SimpleObservable(4);

	getMap.value = newComputeValue;

});

QUnit.test("One event on getters (#1585)", function(assert) {

	var Person = define.Constructor({
		name: "*",
		id: "number"
	});

	var AppState = define.Constructor({
		person: {
			get: function appState_person_get(lastSetValue, resolve) {
				if (lastSetValue) {
					return lastSetValue;
				} else if (this.personId) {
					resolve(new Person({
						name: "Jose",
						id: 5
					}));
				} else {
					return null;
				}
			},
			Type: Person
		},
		personId: "*"
	});

	var appState = new AppState();
	var personEvents = 0;
	appState.bind("person", function addPersonEvents(ev, person) {
		personEvents++;
	});

	assert.equal(appState.person, null, "no personId and no lastSetValue");

	appState.personId = 5;
	assert.equal(appState.person.name, "Jose", "a personId, providing Jose");
	assert.ok(appState.person instanceof Person, "got a person instance");

	appState.person = {
		name: "Julia"
	};
	assert.ok(appState.person instanceof Person, "got a person instance");

	assert.equal(personEvents, 2);
});

QUnit.test('Can read a defined property with a set/get method (#1648)', function(assert) {
	// Problem: "get" is not passed the correct "lastSetVal"
	// Problem: Cannot read the value of "foo"

	var Map = define.Constructor({
		foo: {
			default: '',
			set: function(setVal) {
				return setVal;
			},
			get: function(lastSetVal) {
				return lastSetVal;
			}
		}
	});

	var map = new Map();

	assert.equal(map.foo, '', 'Calling .foo returned the correct value');

	map.foo = 'baz';

	assert.equal(map.foo, 'baz', 'Calling .foo returned the correct value');
});

QUnit.test('Can bind to a defined property with a set/get method (#1648)', function(assert) {
	assert.expect(3);
	// Problem: "get" is not called before and after the "set"
	// Problem: Function bound to "foo" is not called
	// Problem: Cannot read the value of "foo"

	var Map = define.Constructor({
		foo: {
			default: '',
			set: function(setVal) {
				return setVal;
			},
			get: function(lastSetVal) {
				return lastSetVal;
			}
		}
	});

	var map = new Map();

	map.bind('foo', function() {
		assert.ok(true, 'Bound function is called');
	});

	assert.equal(map.foo, '', 'Calling .attr(\'foo\') returned the correct value');

	map.foo = 'baz';

	assert.equal(map.foo, 'baz', 'Calling .attr(\'foo\') returned the correct value');
});

QUnit.test("type converters handle null and undefined in expected ways (1693)", function(assert) {

	var Typer = define.Constructor({
		date: {
			type: 'date'
		},
		string: {
			type: 'string'
		},
		number: {
			type: 'number'
		},
		'boolean': {
			type: 'boolean'
		},
		htmlbool: {
			type: 'htmlbool'
		},
		leaveAlone: {
			type: '*'
		}
	});

	var t = new Typer({
		date: undefined,
		string: undefined,
		number: undefined,
		'boolean': undefined,
		htmlbool: undefined,
		leaveAlone: undefined
	});

	assert.equal(t.date, undefined, "converted to date");

	assert.equal(t.string, undefined, "converted to string");

	assert.equal(t.number, undefined, "converted to number");

	assert.equal(t.boolean, undefined, "converted to boolean"); //Updated for canjs#2316

	assert.equal(t.htmlbool, false, "converted to htmlbool");

	assert.equal(t.leaveAlone, undefined, "left as object");

	t = new Typer({
		date: null,
		string: null,
		number: null,
		'boolean': null,
		htmlbool: null,
		leaveAlone: null
	});

	assert.equal(t.date, null, "converted to date");

	assert.equal(t.string, null, "converted to string");

	assert.equal(t.number, null, "converted to number");

	assert.equal(t.boolean, null, "converted to boolean"); //Updated for canjs#2316

	assert.equal(t.htmlbool, false, "converted to htmlbool");

	assert.equal(t.leaveAlone, null, "left as object");

});

QUnit.test('Initial value does not call getter', function(assert) {
	assert.expect(0);

	var Map = define.Constructor({
		count: {
			get: function(lastVal) {
				assert.ok(false, 'Should not be called');
				return lastVal;
			}
		}
	});

	new Map({
		count: 100
	});
});

QUnit.test("getters produce change events", function(assert) {
	var Map = define.Constructor({
		count: {
			get: function(lastVal) {
				return lastVal;
			}
		}

	});

	var map = new Map();

	// map.bind("change", function(){
	//   ok(true, "change called");
	// });

	map.bind('count', function() {
		assert.ok(true, "change called");
	});

	map.count = 22;
});

QUnit.test("Asynchronous virtual properties cause extra recomputes (#1915)", function(assert) {

	var done = assert.async();

	var ran = false;

	var VM = define.Constructor({
		foo: {
			get: function(lastVal, setVal) {
				setTimeout(function() {
					if (setVal) {
						setVal(5);
					}
				}, 10);
			}
		},
		bar: {
			get: function() {
				var foo = this.foo;
				if (foo) {
					if (ran) {
						assert.ok(false, 'Getter ran twice');
					}
					ran = true;
					return foo * 2;
				}
			}
		}
	});

	var vm = new VM();
	vm.bind('bar', function() {});

	setTimeout(function() {
		assert.equal(vm.bar, 10);
		done();
	}, 200);

});

QUnit.test('Default values cannot be set (#8)', function(assert) {
	var Person = function() {};

	define(Person.prototype, {
		first: {
			type: 'string',
			default: 'Chris'
		},
		last: {
			type: 'string',
			default: 'Gomez'
		},
		fullName: {
			get: function() {
				return this.first + ' ' + this.last;
			}
		}
	});

	var p = new Person();

	assert.equal(p.fullName, 'Chris Gomez', 'Fullname is correct');
	p.first = 'Sara';
	assert.equal(p.fullName, 'Sara Gomez', 'Fullname is correct after update');
});

QUnit.test('default type is setable', function(assert) {
	var Person = function() {};

	define(Person.prototype, {
		'*': 'string',
		first: {
			default: 1
		},
		last: {
			default: 2
		}
	});

	var p = new Person();

	assert.ok(p.first === '1', typeof p.first);
	assert.ok(p.last === '2', typeof p.last);
});

QUnit.test("expandos are added in define.setup (#25)", function(assert) {
	var MyMap = define.Constructor({});

	var map = new MyMap({
		prop: 4
	});
	map.on("prop", function() {
		assert.ok(true, "prop event called");
	});
	map.prop = 5;
});

QUnit.test('Set property with type compute', function(assert) {
	var MyMap = define.Constructor({
		computeProp: {
			type: 'compute'
		}
	});

	var m = new MyMap();

	m.computeProp = new SimpleObservable(0);
	assert.equal(m.computeProp, 0, 'Property has correct value');

	m.computeProp = new SimpleObservable(1);
	assert.equal(m.computeProp, 1, 'Property has correct value');
});

QUnit.test('Compute type property can have a default value', function(assert) {
	var MyMap = define.Constructor({
		computeProp: {
			type: 'compute',
			default: function() {
				return 0;
			}
		}
	});

	var m = new MyMap();
	assert.equal(m.computeProp, 0, 'Property has correct value');

	m.computeProp = 1;
	assert.equal(m.computeProp, 1, 'Property has correct value');
});

QUnit.test('Compute type property with compute default value triggers change events when updated', function(assert) {
	var expected = 0;
	var c = new SimpleObservable(0);

	var MyMap = define.Constructor({
		computeProp: {
			type: 'compute',
			default: function() {
				return c;
			}
		}
	});

	var m = new MyMap();

	c.on(function(newVal) {
		assert.equal(newVal, expected, 'Compute fired change event');
	});

	m.on('computeProp', function(ev, newVal) {
		assert.equal(newVal, expected, 'Map fired change event');
	});

	expected = 1;
	m.computeProp = expected;

	expected = 2;
	c.set(expected);
});

QUnit.test('Compute type property can have a default value that is a compute', function(assert) {
	var c = new SimpleObservable(0);

	var MyMap = define.Constructor({
		computeProp: {
			type: 'compute',
			default: function() {
				return c;
			}
		}
	});

	var m = new MyMap();
	assert.equal(m.computeProp, 0, 'Property has correct value');

	c.set(1);
	assert.equal(m.computeProp, 1, 'Property has correct value');
});

QUnit.test('Extensions can modify definitions', function(assert) {
	var oldExtensions = define.extensions;

	define.behaviors.push('extended');

	define.extensions = function(objPrototype, prop, definition) {
		if (definition.extended) {
			return {
				default: 'extended'
			};
		}
	};

	var MyMap = define.Constructor({
		foo: {
			default: 'defined',
			extended: true,
		},
		bar: {
			default: 'defined'
		}
	});

	var map = new MyMap();

	assert.equal(map.foo, 'extended', 'Value was set via extension');
	assert.equal(map.bar, 'defined', 'Value was set via definition');

	define.extensions = oldExtensions;
});

QUnit.test("Properties are enumerable", function(assert) {
	assert.expect(1);

	function VM(foo) {
		this.foo = foo;
	}

	define(VM.prototype, {
		foo: "string"
	});

	var vm = new VM("bar");
	vm.baz = "qux";

	var copy = {};
	for(var key in vm) {
		copy[key] = vm[key];

	}
	assert.deepEqual(copy,{
		foo: "bar",
		baz: "qux"
	});

});

QUnit.test("Doesn't override canSymbol.iterator if already on the prototype", function(assert) {
	function MyMap() {}

	MyMap.prototype[canSymbol.iterator || canSymbol.for("iterator")] = function() {
		var i = 0;
		return {
			next: function() {
				if (i === 0) {
					i++;
					return {
						value: ["it", "worked"],
						done: false
					};
				}

				return {
					value: undefined,
					done: true
				};
			}
		};
	};

	define(MyMap.prototype, {
		foo: "string"
	});

	var map = new MyMap();
	map.foo = "bar";

	canReflect.eachIndex(map, function(value) {
		assert.deepEqual(value, ["it","worked"]);
	});
});

QUnit.test("nullish values are not converted for type or Type", function(assert) {

	var Foo = function() {};

	var MyMap = define.Constructor({
		map: {
			Type: Foo
		},
		notype: {}
	});

	var vm = new MyMap({
		map: {},
		notype: {}
	});

	// Sanity check
	assert.ok(vm.map instanceof Foo, "map is another type");
	assert.ok(vm.notype instanceof Object, "notype is an Object");

	vm.map = null;
	vm.notype = null;

	assert.equal(vm.map, null, "map is null");
	assert.equal(vm.map, null, "notype is null");
});

QUnit.test("shorthand getter (#56)", function(assert) {
	var Person = function(first, last) {
		this.first = first;
		this.last = last;
	};
	define(Person.prototype, {
		first: "*",
		last: "*",
		get fullName() {
			return this.first + " " + this.last;
		}
	});

	var p = new Person("Mohamed", "Cherif");

	p.on("fullName", function(ev, newVal, oldVal) {
		assert.equal(oldVal, "Mohamed Cherif");
		assert.equal(newVal, "Justin Meyer");
	});

	assert.equal(p.fullName, "Mohamed Cherif", "fullName initialized right");

	queues.batch.start();
	p.first = "Justin";
	p.last = "Meyer";
	queues.batch.stop();
});

QUnit.test("shorthand getter setter (#56)", function(assert) {
	var Person = function(first, last) {
		this.first = first;
		this.last = last;
	};
	define(Person.prototype, {
		first: "*",
		last: "*",
		get fullName() {
			return this.first + " " + this.last;
		},
		set fullName(newVal) {
			var parts = newVal.split(" ");
			this.first = parts[0];
			this.last = parts[1];
		}
	});

	var p = new Person("Mohamed", "Cherif");

	p.on("fullName", function(ev, newVal, oldVal) {
		assert.equal(oldVal, "Mohamed Cherif");
		assert.equal(newVal, "Justin Meyer");
	});

	assert.equal(p.fullName, "Mohamed Cherif", "fullName initialized right");

	p.fullName = "Justin Meyer";
});

QUnit.test("set and value work together (#87)", function(assert) {

	var Type = define.Constructor({
		prop: {
			default: 2,
			set: function(num){
				return num * num;
			}
		}
	});

	var instance = new Type();

	assert.equal(instance.prop, 4, "used setter");

});

QUnit.test("async setter is provided", function(assert) {
	assert.expect(5);
	var RESOLVE;

	var Type = define.Constructor({
		prop: {
			default: 2,
			set: function(num, resolve){
				resolve( num * num );
			}
		},
		prop2: {
			default: 3,
			set: function(num, resolve){
				RESOLVE = resolve;
			}
		}
	});

	var instance = new Type();

	assert.equal(instance.prop, 4, "used async setter");

	assert.equal(instance.prop2, undefined, "used async setter");

	instance.on("prop2", function(ev, newVal, oldVal){
		assert.equal(newVal, 9, "updated");
		assert.equal(oldVal, undefined, "updated");
	});
	RESOLVE(9);

	assert.equal(instance.prop2, 9, "used async setter updates after");

});

QUnit.test('setter with default value causes an infinite loop (#142)', function(assert) {
	var A = define.Constructor({
		val: {
			default: 'hello',
			set: function(val){
				if(this.val) {}
				return val;
			}
		}
	});

	var a = new A();
	assert.equal(a.val, 'hello', 'creating an instance should not cause an inifinte loop');
});

QUnit.test('defined properties are configurable', function(assert) {
	var A = define.Constructor({
		val: {
			get: function(){
				return "foo";
			}
		}
	});

	var dataInitializers = A.prototype._define.dataInitializers,
	computedInitializers = A.prototype._define.computedInitializers;

	var newDefinition = {
		get: function(){
			return "bar";
		}
	};

	define.property(A.prototype, "val", newDefinition, dataInitializers,
		computedInitializers);

	var a = new A();
	assert.equal(a.val, "bar", "It was redefined");
});

testHelpers.dev.devOnlyTest("warn on using a Constructor for small-t type definitions", function (assert) {
	assert.expect(1);

	var message = /can-define: the definition for [\w{}\.]+ uses a constructor for "type"\. Did you mean "Type"\?/;
	var finishErrorCheck = testHelpers.dev.willWarn(message);

	function Currency() {
		return this;
	}
	Currency.prototype = {
		symbol: "USD"
	};

	function VM() {}
	define(VM.prototype, {
		currency: {
			type: Currency, // should be `Type: Currency`
			default: function() {
				return new Currency({});
			}
		}
	});

	assert.equal(finishErrorCheck(), 1);

});

testHelpers.dev.devOnlyTest("warn with constructor for Value instead of Default (#340)", function (assert) {
	assert.expect(1);

	var message = /can-define: Change the 'Value' definition for [\w\.{}]+.currency to 'Default'./;
	var finishErrorCheck = testHelpers.dev.willWarn(message);

	function Currency() {
		return this;
	}
	Currency.prototype = {
		symbol: "USD"
	};

	function VM() {}
	define(VM.prototype, {
		currency: {
			Value: Currency
		}
	});
	assert.equal(finishErrorCheck(), 1);
});

QUnit.test("canReflect.onKeyValue (#363)", function(assert) {
	var Greeting = function( message ) {
		this.message = message;
	};

	define( Greeting.prototype, {
		message: { type: "string" }
	} );

	var greeting = new Greeting("Hello");

	canReflect.onKeyValue(greeting, "message", function(newVal, oldVal) {
		assert.equal(newVal, "bye");
		assert.equal(oldVal, "Hello");
	});

	greeting.message = "bye";
});

QUnit.test("value lastSet has default value (#397)", function(assert) {
	var Defaulted = function() {};

	define(Defaulted.prototype, {
		hasDefault: {
			default: 42,
			value: function hasDefaultValue(props) {
				assert.equal(props.lastSet.get(), 42, "props.lastSet works");
				props.resolve(props.lastSet.get());
			}
		}
	});
	var defaulted = new Defaulted();
	assert.equal(defaulted.hasDefault, 42,
		"hasDefault value.lastSet set default value");
});

QUnit.test("binding computed properties do not observation recordings (#406)", function(assert) {
	var Type = function() {};

	define(Type.prototype, {
		prop: {
			get: function(){
				return "foo";
			}
		}
	});

	var inst = new Type();

	ObservationRecorder.start();
	inst.on("prop", function(){});
	var records = ObservationRecorder.stop();
	assert.equal(records.valueDependencies.size, 0, "nothing recorded");
});

testHelpers.dev.devOnlyTest("warning when setting during a get", function(assert){
	var Type = function Type() {};

	var msg = /.* This can cause infinite loops and performance issues.*/;
	var teardownWarn = testHelpers.dev.willWarn(msg, function(text, match) {
		if(match) {
			assert.ok(true, "warning fired");
		}
	});

	define(Type.prototype, {
		prop: {
			get: function(){
				if(!this.prop2) {
					this.prop2 = "baz";
				}
				return "";
			}
		},
		prop2: "string"
	});

	var inst = new Type();

	inst.on("prop", function(){});
	inst.prop2 = "";
	assert.equal(teardownWarn(), 1, "warning correctly generated");
	teardownWarn = testHelpers.dev.willWarn(msg, function(text, match) {
		if(match) {
			assert.ok(false, "warning incorrectly fired");
		}
	});
	inst.prop2 = "quux";
	teardownWarn();
});

testHelpers.dev.devOnlyTest("warning when setting during a get (batched)", function(assert){
	var msg = /.* This can cause infinite loops and performance issues.*/;
	var Type = function Type() {};
	var teardownWarn = testHelpers.dev.willWarn(msg, function(text, match) {
		if(match) {
			assert.ok(true, "warning fired");
		}
	});

	define(Type.prototype, {
		prop: {
			get: function(){
				if(!this.prop2) {
					this.prop2 = "baz";
					return "";
				}
			}
		},
		prop2: "string"
	});

	var inst = new Type();

	queues.batch.start();
	inst.on("prop", function(){});
	inst.prop2 = "";
	queues.batch.stop();
	assert.equal(teardownWarn(), 1, "warning correctly generated");
	teardownWarn = testHelpers.dev.willWarn(msg, function(text, match) {
		if(match) {
			assert.ok(false, "warning incorrectly fired");
		}
	});
	queues.batch.start();
	inst.prop2 = "quux";
	queues.batch.stop();
	teardownWarn();
});

testHelpers.dev.devOnlyTest("warning when setting during a get (setter)", function(assert){
	var msg = /.* This can cause infinite loops and performance issues.*/;
	var Type = function Type() {};
	var teardownWarn = testHelpers.dev.willWarn(msg, function(text, match) {
		if(match) {
			assert.ok(true, "warning fired");
		}
	});

	var cell;
	define(Type.prototype, {
		prop: {
			get: function() {
				if(!this.prop2) {
					this.prop2 = "baz";
				}
				return cell;
			},
			set: function(val) {
				cell = val;
			}
		},
		prop2: "string"
	});

	var inst = new Type();

	inst.on("prop", function(){}); // generates a warning
	inst.prop2 = ""; // also generates a warning, as the bound getter will fire again
	assert.equal(teardownWarn(), 1, "warning correctly generated");
	teardownWarn = testHelpers.dev.willWarn(msg, function(text, match) {
		if(match) {
			assert.ok(false, "warning incorrectly fired");
		}
	});
	inst.prop2 = "quux";
	teardownWarn();
});

testHelpers.dev.devOnlyTest("warnings are given when type or default is ignored", function(assert) {
	var testCases = [
		{
			name: "zero-arg getter, no setter when property is set",
			definition: {
				get: function() { return "whatever"; }
			},
			warning: /Set value for property .* ignored/,
			setProp: true,
			expectedWarnings: 1
		},
		{
			name: "type with zero-arg getter, no setter",
			definition: {
				type: String,
				get: function() { return "whatever"; }
			},
			warning: /type value for property .* ignored/,
			setProp: false,
			expectedWarnings: 1
		},
		{
			name: "Type with zero-arg getter, no setter",
			definition: {
				Type: {},
				get: function() { return "whatever"; }
			},
			warning: /Type value for property .* ignored/,
			setProp: false,
			expectedWarnings: 1
		},
		{
			name: "only default type with zero-arg getter, no setter - should not warn",
			definition: {
				get: function() { return "whatever"; }
			},
			warning: /type value for property .* ignored/,
			setProp: false,
			expectedWarnings: 0
		},
		{
			name: "type with zero-arg getter, with setter - should not warn",
			definition: {
				type: String,
				get: function() { return "whatever"; },
				set: function (val) { return val; }
			},
			warning: /type value for property .* ignored/,
			setProp: false,
			expectedWarnings: 0
		},
		{
			name: "Type with zero-arg getter, with setter - should not warn",
			definition: {
				Type: {},
				get: function() { return "whatever"; },
				set: function (val) { return val; }
			},
			warning: /Type value for property .* ignored/,
			setProp: false,
			expectedWarnings: 0
		},
		{
			name: "default with zero-arg getter, no setter",
			definition: {
				default: "some thing",
				get: function() { return "whatever"; }
			},
			warning: /default value for property .* ignored/,
			setProp: false,
			expectedWarnings: 1
		},
		{
			name: "Default with zero-arg getter, no setter",
			definition: {
				Default: function () {},
				get: function() { return "whatever"; }
			},
			warning: /Default value for property .* ignored/,
			setProp: false,
			expectedWarnings: 1
		},
		{
			name: "default with zero-arg getter, with setter - should not warn",
			definition: {
				default: "some thing",
				get: function() { return "whatever"; },
				set: function (val) { return val; }
			},
			warning: /default value for property .* ignored/,
			setProp: false,
			expectedWarnings: 0
		},
		{
			name: "Default with zero-arg getter, with setter - should not warn",
			definition: {
				Default: function () {},
				get: function() { return "whatever"; },
				set: function (val) { return val; }
			},
			warning: /Default value for property .* ignored/,
			setProp: false,
			expectedWarnings: 0
		}
	];

	testCases.forEach(function(testCase) {
		var VM = function() {};
		var warnCount = testHelpers.dev.willWarn(testCase.warning);

		define(VM.prototype, {
			derivedProp: testCase.definition,
			"*": { // emulates can-define/map/map setting default type
				type: define.types.observable
			}
		});

		var vm = new VM();

		// read prop for 'lazy' setup
		canReflect.onKeyValue(vm, 'derivedProp', function() {});

		if (testCase.setProp) {
			vm.derivedProp = "smashed it!";
		}

		assert.equal(warnCount(), testCase.expectedWarnings, "got correct number of warnings for " + testCase.name);
	});
});


text:
<?xml version="1.0"?>
<form string="Create Nereid Website" col="2">
    <image name="tryton-dialog-information" xexpand="0" xfill="0"/>
    <label string="You can now add nereid website into the system." id="add"
        yalign="0.0" xalign="0.0" xexpand="1"/>
</form>


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Котики</title>
    <link rel="stylesheet" type="text/css" href="css/style.css" media="all" />
    <link rel="stylesheet" type="text/css" href="css/index.css" media="all" />

Котики

          Погладить котика...


text:
title: "Notes from Online Courses"
date: 2019-06-25
categories: [notes]
tags: [notes]
---

In early 2019, I joined JPMorgan Chase & Co. and I made a conscious switch from being a front-end engineer to a full-stack engineer focusing predominantly on the back-end. It was a tough endeavour and to get productive, I needed to improve my skillset in a bunch of new technologies.

I decided to spend some time doing courses on a few massive-open-online-course platforms like Pluralsight and Coursera and took down notes. [Check them out](https://raghavramesh.github.io/mooc-notes).


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.hadoop.mapreduce.lib.reduce Class Hierarchy (hadoop-mapreduce-client-core 2.2.0 API)</title>
<meta name="date" content="2013-12-16">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Hierarchy For Package org.apache.hadoop.mapreduce.lib.reduce

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.hadoop.mapreduce.Reducer<KEYIN,VALUEIN,KEYOUT,VALUEOUT>

org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer<Key>

org.apache.hadoop.mapreduce.lib.reduce.LongSumReducer<KEY>

org.apache.hadoop.mapreduce.lib.reduce.WrappedReducer<KEYIN,VALUEIN,KEYOUT,VALUEOUT>

org.apache.hadoop.mapreduce.Reducer.Context (implements org.apache.hadoop.mapreduce.ReduceContext<KEYIN,VALUEIN,KEYOUT,VALUEOUT>)

org.apache.hadoop.mapreduce.lib.reduce.WrappedReducer.Context

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Copyright © 2013 Apache Software Foundation. All Rights Reserved.


text:
import unittest

from airflow import configuration
from airflow import models
from airflow.exceptions import AirflowException
from airflow.utils import db

try:
    from airflow.hooks.docker_hook import DockerHook
except ImportError:
    pass

try:
    from unittest import mock
except ImportError:
    try:
        import mock
    except ImportError:
        mock = None

@mock.patch('airflow.hooks.docker_hook.APIClient', autospec=True)
class DockerHookTest(unittest.TestCase):
    def setUp(self):
        configuration.load_test_config()
        db.merge_conn(
            models.Connection(
                conn_id='docker_default',
                conn_type='docker',
                host='some.docker.registry.com',
                login='some_user',
                password='some_p4$$w0rd'
            )
        )
        db.merge_conn(
            models.Connection(
                conn_id='docker_with_extras',
                conn_type='docker',
                host='some.docker.registry.com',
                login='some_user',
                password='some_p4$$w0rd',
                extra='{"email": "some@example.com", "reauth": "no"}'
            )
        )

    def test_init_fails_when_no_base_url_given(self, _):
        with self.assertRaises(AirflowException):
            DockerHook(
                docker_conn_id='docker_default',
                version='auto',
                tls=None
            )

    def test_init_fails_when_no_api_version_given(self, _):
        with self.assertRaises(AirflowException):
            DockerHook(
                docker_conn_id='docker_default',
                base_url='unix://var/run/docker.sock',
                tls=None
            )

    def test_get_conn_override_defaults(self, docker_client_mock):
        hook = DockerHook(
            docker_conn_id='docker_default',
            base_url='https://index.docker.io/v1/',
            version='1.23',
            tls='someconfig'
        )
        hook.get_conn()
        docker_client_mock.assert_called_with(
            base_url='https://index.docker.io/v1/',
            version='1.23',
            tls='someconfig'
        )

    def test_get_conn_with_standard_config(self, _):
        try:
            hook = DockerHook(
                docker_conn_id='docker_default',
                base_url='unix://var/run/docker.sock',
                version='auto'
            )
            client = hook.get_conn()
            self.assertIsNotNone(client)
        except Exception:
            self.fail('Could not get connection from Airflow')

    def test_get_conn_with_extra_config(self, _):
        try:
            hook = DockerHook(
                docker_conn_id='docker_with_extras',
                base_url='unix://var/run/docker.sock',
                version='auto'
            )
            client = hook.get_conn()
            self.assertIsNotNone(client)
        except Exception:
            self.fail('Could not get connection from Airflow')

    def test_conn_with_standard_config_passes_parameters(self, _):
        hook = DockerHook(
            docker_conn_id='docker_default',
            base_url='unix://var/run/docker.sock',
            version='auto'
        )
        client = hook.get_conn()
        client.login.assert_called_with(
            username='some_user',
            password='some_p4$$w0rd',
            registry='some.docker.registry.com',
            reauth=True,
            email=None
        )

    def test_conn_with_extra_config_passes_parameters(self, _):
        hook = DockerHook(
            docker_conn_id='docker_with_extras',
            base_url='unix://var/run/docker.sock',
            version='auto'
        )
        client = hook.get_conn()
        client.login.assert_called_with(
            username='some_user',
            password='some_p4$$w0rd',
            registry='some.docker.registry.com',
            reauth=False,
            email='some@example.com'
        )

    def test_conn_with_broken_config_missing_username_fails(self, _):
        db.merge_conn(
            models.Connection(
                conn_id='docker_without_username',
                conn_type='docker',
                host='some.docker.registry.com',
                password='some_p4$$w0rd',
                extra='{"email": "some@example.com"}'
            )
        )
        with self.assertRaises(AirflowException):
            DockerHook(
                docker_conn_id='docker_without_username',
                base_url='unix://var/run/docker.sock',
                version='auto'
            )

    def test_conn_with_broken_config_missing_host_fails(self, _):
        db.merge_conn(
            models.Connection(
                conn_id='docker_without_host',
                conn_type='docker',
                login='some_user',
                password='some_p4$$w0rd'
            )
        )
        with self.assertRaises(AirflowException):
            DockerHook(
                docker_conn_id='docker_without_host',
                base_url='unix://var/run/docker.sock',
                version='auto'
            )


text:
<?php

namespace WindowsAzure\Table\Internal;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Utilities;

/**
 * Reads and writes MIME for batch API.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Table\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.2_2016-04
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class MimeReaderWriter implements IMimeReaderWriter
{
    /**
     * Given array of MIME parts in raw string, this function converts them into MIME
     * representation.
     *
     * @param array $bodyPartContents The MIME body parts.
     *
     * @return array Returns array with two elements 'headers' and 'body' which
     * represents the MIME message.
     */
    public function encodeMimeMultipart($bodyPartContents)
    {
        $count         = count($bodyPartContents);
        $mimeType      = Resources::MULTIPART_MIXED_TYPE;
        $batchGuid     = Utilities::getGuid();
        $batchId       = sprintf('batch_%s', $batchGuid);
        $contentType1  = array('content_type' => "$mimeType");
        $changeSetGuid = Utilities::getGuid();
        $changeSetId   = sprintf('changeset_%s', $changeSetGuid);
        $contentType2  = array('content_type' => "$mimeType; boundary=$changeSetId");
        $options       = array(
            'encoding'     => 'binary',
            'content_type' => Resources::HTTP_TYPE
        );

        // Create changeset MIME part
        $changeSet = new \Mail_mimePart();

        for ($i = 0; $i < $count; $i++) {
            $changeSet->addSubpart($bodyPartContents[$i], $options);
        }

        // Encode the changeset MIME part
        $changeSetEncoded = $changeSet->encode($changeSetId);

        // Create the batch MIME part
        $batch = new \Mail_mimePart(Resources::EMPTY_STRING, $contentType1);

        // Add changeset encoded to batch MIME part
        $batch->addSubpart($changeSetEncoded['body'], $contentType2);

        // Encode batch MIME part
        $batchEncoded = $batch->encode($batchId);

        return $batchEncoded;
    }

    /**
     * Parses given mime HTTP response body into array. Each array element
     * represents a change set result.
     *
     * @param string $mimeBody The raw MIME body result.
     *
     * @return array
     */
    public function decodeMimeMultipart($mimeBody)
    {
        $params['include_bodies'] = true;
        $params['input']          = $mimeBody;
        $mimeDecoder              = new \Mail_mimeDecode($mimeBody);
        $structure                = $mimeDecoder->decode($params);
        $parts                    = $structure->parts;
        $bodies                   = array();

        foreach ($parts as $part) {
            $bodies[] = $part->body;
        }

        return $bodies;
    }
}


text:
// Notifications and their manager

var NotificationsManager = new Class({

  Implements: [Options, Chain, Events],

  options: {
    notification: {
      // any Notification option, plus
      animationDuration: 1500, // needed here
      clear: false,
      once:  true
    }
  },

  initialize: function (holder, options) {
    this.holder = document.id(holder);
    this.setOptions(options);
    this.currentStack = [];
    this.archiveStack = [];
  },

  add: function (message, options) {
    options = Object.merge({}, this.options.notification, options);

    if (true == options.once && this.hasShown(message, options)) {
      return false;
    } else if (true == options.clear) {
      this.clear();
      options.clear = false;
      return this.add.delay(this.options.notification.animationDuration, this, [message, options]);
    } else {
      var n = new Notification(this, message, options);
      n.getElement().inject(this.holder);
      n.show();
      n.getElement().setStyle('visibility', 'visible');
      this.currentStack.push(n);
      this.archiveStack.push(n);
      return true;
    }
  },

  remove: function (notification) {
    var i = this.currentStack.indexOf(notification);
    if (i != -1) {
      this.currentStack.splice(i,1);
      notification.hideAndDestroy();
    }
  },

  clear: function () {
    var n;
    while (n = this.currentStack.pop()) {
      n.hideAndDestroy();
    }
  },

  hasShown: function (message, options) {
    var has = false; var n;
    var i = 0;
    while (false == has && i < this.archiveStack.length) {
      if (this.archiveStack[i].message == message)  {
        has = true;
      }
      i++;
    }
    return has;
  }

});

var Notification = new Class({

  Implements: [Options, Chain, Events],

  options: {
    classes:  ['notification'],
    classShow: 'animateIn',
    classHide: 'animateOut',
    speaker:    null, // string, class the speaker will have
    animationDuration: 1500,
    onClick:  function(){ /*this.manager.remove(this);*/ },
    onCreate: function(){}
  },

  initialize: function (manager, message, options) {
    this.manager = manager;
    this.message = message;
    this.setOptions(options);
  },

  _createDOM: function () {
    this.element = new Element('div');
    this.element.addClasses(this.options.classes);
    var p = new Element('p');
    p.set('html', this.message);
    p.inject(this.element);
    if (this.options.speaker) {
      var speaker = new Element('div');
      speaker.addClass('speaker');
      speaker.addClass(this.options.speaker);
      speaker.inject(this.element);
    }

    this.element.addEvents ({
      'click': function(){this.fireEvent('click')}.bind(this)
    });

    this.fireEvent('create');

    return this.element;
  },

  getElement: function () {
    return this.element ? this.element : this._createDOM();
  },

  show: function () {
    this.getElement().removeClass(this.options.classShow).addClass(this.options.classShow);
  },

  hide: function () {
    this.getElement().removeClass(this.options.classHide).addClass(this.options.classHide);
  },

  hideAndDestroy: function () {
    this.hide();
    (function(){
      this.element.destroy();
    }).delay(this.options.animationDuration, this);
  }

});


text:
/************************************************************
************************************************************/
#pragma once

#include "sj_common.h"

/************************************************************
************************************************************/
class SHORT_PATTERN{
private:
	enum{
		MAX_PROGRESS = 100,
	};

	static const double Lev_Flow_L;
	static const double Lev_Flash_L;

public:
	static void SpLev_test();

	static double Sp_FlowOn(const double Progress, const int NUM_CHS, const int N, const double NUM_WAVES_IN_SPACE);
	static double Sp_FlowOff(const double Progress, const int NUM_CHS, const int N, const double NUM_WAVES_IN_SPACE);
	static double Sp_cos(const double Progress, const int NUM_CHS, const int N, const double NUM_WAVES_IN_SPACE);
	static double Sp_On_High(const double Progress, const int NUM_CHS, const int N, const double NUM_WAVES_IN_SPACE);
	static double Sp_cos_forFlash(const double Progress, const int NUM_CHS, const int N, const double NUM_WAVES_IN_SPACE);
	static double Sp_Flash__1_1(const double Progress, const int NUM_CHS, const int N, const double NUM_WAVES_IN_SPACE);
	static double Sp_Flash__1_2(const double Progress, const int NUM_CHS, const int N, const double NUM_WAVES_IN_SPACE);
	static double Sp_Flash__2_2(const double Progress, const int NUM_CHS, const int N, const double NUM_WAVES_IN_SPACE);
};

/************************************************************
************************************************************/
typedef double (*FUNC_SP)(const double Progress, const int NUM_CHS, const int N, const double NUM_WAVES_IN_SPACE);


text:
#include "src/core/SkWriteBuffer.h"

#include "include/core/SkBitmap.h"
#include "include/core/SkData.h"
#include "include/core/SkM44.h"
#include "include/core/SkStream.h"
#include "include/core/SkTypeface.h"
#include "include/private/SkTo.h"
#include "src/core/SkImagePriv.h"
#include "src/core/SkMatrixPriv.h"
#include "src/core/SkPaintPriv.h"
#include "src/core/SkPtrRecorder.h"

///////////////////////////////////////////////////////////////////////////////////////////////////

SkBinaryWriteBuffer::SkBinaryWriteBuffer()
    : fFactorySet(nullptr)
    , fTFSet(nullptr) {
}

SkBinaryWriteBuffer::SkBinaryWriteBuffer(void* storage, size_t storageSize)
    : fFactorySet(nullptr)
    , fTFSet(nullptr)
    , fWriter(storage, storageSize)
{}

SkBinaryWriteBuffer::~SkBinaryWriteBuffer() {}

bool SkBinaryWriteBuffer::usingInitialStorage() const {
    return fWriter.usingInitialStorage();
}

void SkBinaryWriteBuffer::writeByteArray(const void* data, size_t size) {
    fWriter.write32(SkToU32(size));
    fWriter.writePad(data, size);
}

void SkBinaryWriteBuffer::writeBool(bool value) {
    fWriter.writeBool(value);
}

void SkBinaryWriteBuffer::writeScalar(SkScalar value) {
    fWriter.writeScalar(value);
}

void SkBinaryWriteBuffer::writeScalarArray(const SkScalar* value, uint32_t count) {
    fWriter.write32(count);
    fWriter.write(value, count * sizeof(SkScalar));
}

void SkBinaryWriteBuffer::writeInt(int32_t value) {
    fWriter.write32(value);
}

void SkBinaryWriteBuffer::writeIntArray(const int32_t* value, uint32_t count) {
    fWriter.write32(count);
    fWriter.write(value, count * sizeof(int32_t));
}

void SkBinaryWriteBuffer::writeUInt(uint32_t value) {
    fWriter.write32(value);
}

void SkBinaryWriteBuffer::writeString(std::string_view value) {
    fWriter.writeString(value.data(), value.size());
}

void SkBinaryWriteBuffer::writeColor(SkColor color) {
    fWriter.write32(color);
}

void SkBinaryWriteBuffer::writeColorArray(const SkColor* color, uint32_t count) {
    fWriter.write32(count);
    fWriter.write(color, count * sizeof(SkColor));
}

void SkBinaryWriteBuffer::writeColor4f(const SkColor4f& color) {
    fWriter.write(&color, sizeof(SkColor4f));
}

void SkBinaryWriteBuffer::writeColor4fArray(const SkColor4f* color, uint32_t count) {
    fWriter.write32(count);
    fWriter.write(color, count * sizeof(SkColor4f));
}

void SkBinaryWriteBuffer::writePoint(const SkPoint& point) {
    fWriter.writeScalar(point.fX);
    fWriter.writeScalar(point.fY);
}

void SkBinaryWriteBuffer::writePoint3(const SkPoint3& point) {
    this->writePad32(&point, sizeof(SkPoint3));
}

void SkBinaryWriteBuffer::writePointArray(const SkPoint* point, uint32_t count) {
    fWriter.write32(count);
    fWriter.write(point, count * sizeof(SkPoint));
}

void SkBinaryWriteBuffer::write(const SkM44& matrix) {
    fWriter.write(SkMatrixPriv::M44ColMajor(matrix), sizeof(float) * 16);
}

void SkBinaryWriteBuffer::writeMatrix(const SkMatrix& matrix) {
    fWriter.writeMatrix(matrix);
}

void SkBinaryWriteBuffer::writeIRect(const SkIRect& rect) {
    fWriter.write(&rect, sizeof(SkIRect));
}

void SkBinaryWriteBuffer::writeRect(const SkRect& rect) {
    fWriter.writeRect(rect);
}

void SkBinaryWriteBuffer::writeRegion(const SkRegion& region) {
    fWriter.writeRegion(region);
}

void SkBinaryWriteBuffer::writeSampling(const SkSamplingOptions& sampling) {
    fWriter.writeSampling(sampling);
}

void SkBinaryWriteBuffer::writePath(const SkPath& path) {
    fWriter.writePath(path);
}

size_t SkBinaryWriteBuffer::writeStream(SkStream* stream, size_t length) {
    fWriter.write32(SkToU32(length));
    size_t bytesWritten = fWriter.readFromStream(stream, length);
    if (bytesWritten < length) {
        fWriter.reservePad(length - bytesWritten);
    }
    return bytesWritten;
}

bool SkBinaryWriteBuffer::writeToStream(SkWStream* stream) const {
    return fWriter.writeToStream(stream);
}

#include "src/image/SkImage_Base.h"

/*  Format:
 *      flags: U32
 *      encoded : size_32 + data[]
 *      [subset: IRect]
 *      [mips]  : size_32 + data[]
 */
void SkBinaryWriteBuffer::writeImage(const SkImage* image) {
    uint32_t flags = 0;
    const SkMipmap* mips = as_IB(image)->onPeekMips();
    if (mips) {
        flags |= SkWriteBufferImageFlags::kHasMipmap;
    }
    if (image->alphaType() == kUnpremul_SkAlphaType) {
        flags |= SkWriteBufferImageFlags::kUnpremul;
    }

    this->write32(flags);

    sk_sp<SkData> data;
    if (fProcs.fImageProc) {
        data = fProcs.fImageProc(const_cast<SkImage*>(image), fProcs.fImageCtx);
    }
    if (!data) {
        data = image->encodeToData();
    }
    this->writeDataAsByteArray(data.get());

    if (flags & SkWriteBufferImageFlags::kHasMipmap) {
        this->writeDataAsByteArray(mips->serialize().get());
    }
}

void SkBinaryWriteBuffer::writeTypeface(SkTypeface* obj) {
    // Write 32 bits (signed)
    //   0 -- default font
    //  >0 -- index
    //  <0 -- custom (serial procs)

    if (obj == nullptr) {
        fWriter.write32(0);
    } else if (fProcs.fTypefaceProc) {
        auto data = fProcs.fTypefaceProc(obj, fProcs.fTypefaceCtx);
        if (data) {
            size_t size = data->size();
            if (!SkTFitsIn<int32_t>(size)) {
                size = 0;               // fall back to default font
            }
            int32_t ssize = SkToS32(size);
            fWriter.write32(-ssize);    // negative to signal custom
            if (size) {
                this->writePad32(data->data(), size);
            }
            return;
        }
        // no data means fall through for std behavior
    }
    fWriter.write32(fTFSet ? fTFSet->add(obj) : 0);
}

void SkBinaryWriteBuffer::writePaint(const SkPaint& paint) {
    SkPaintPriv::Flatten(paint, *this);
}

void SkBinaryWriteBuffer::setFactoryRecorder(sk_sp<SkFactorySet> rec) {
    fFactorySet = std::move(rec);
}

void SkBinaryWriteBuffer::setTypefaceRecorder(sk_sp<SkRefCntSet> rec) {
    fTFSet = std::move(rec);
}

void SkBinaryWriteBuffer::writeFlattenable(const SkFlattenable* flattenable) {
    if (nullptr == flattenable) {
        this->write32(0);
        return;
    }

    /*
     *  We can write 1 of 2 versions of the flattenable:
     *
     *  1. index into fFactorySet: This assumes the writer will later resolve the function-ptrs
     *     into strings for its reader. SkPicture does exactly this, by writing a table of names
     *     (matching the indices) up front in its serialized form.
     *
     *  2. string name of the flattenable or index into fFlattenableDict:  We store the string to
     *     allow the reader to specify its own factories after write time. In order to improve
     *     compression, if we have already written the string, we write its index instead.
     */

    if (SkFlattenable::Factory factory = flattenable->getFactory(); factory && fFactorySet) {
        this->write32(fFactorySet->add(factory));
    } else {
        const char* name = flattenable->getTypeName();
        SkASSERT(name);
        SkASSERT(0 != strcmp("", name));

        if (uint32_t* indexPtr = fFlattenableDict.find(name)) {
            // We will write the index as a 32-bit int.  We want the first byte
            // that we send to be zero - this will act as a sentinel that we
            // have an index (not a string).  This means that we will send the
            // the index shifted left by 8.  The remaining 24-bits should be
            // plenty to store the index.  Note that this strategy depends on
            // being little endian, and type names being non-empty.
            SkASSERT(0 == *indexPtr >> 24);
            this->write32(*indexPtr << 8);
        } else {
            this->writeString(name);
            fFlattenableDict.set(name, fFlattenableDict.count() + 1);
        }
    }

    // make room for the size of the flattened object
    (void)fWriter.reserve(sizeof(uint32_t));
    // record the current size, so we can subtract after the object writes.
    size_t offset = fWriter.bytesWritten();
    // now flatten the object
    flattenable->flatten(*this);
    size_t objSize = fWriter.bytesWritten() - offset;
    // record the obj's size
    fWriter.overwriteTAt(offset - sizeof(uint32_t), SkToU32(objSize));
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 34: 105 (1895)

#### Original name
Dimerosporium forsteroniae Henn.

### Remarks
null


text:
var _ = require('underscore');

exports.main = function(request, response) {
	response.render('index', {
		feed: getFeed()
	});
}


text:
package org.apache.derby.client.am;

/**
 * Converters from floating point bytes to Java float, double, or
 * java.math.BigDecimal.
 */
public class FloatingPoint {
    // Hide the default constructor, this is a static class.
    private FloatingPoint() {
    }

    /**
     * Supported Unix Big Endian IEEE 754 floating point representation.
     */
    public final static int IEEE_754_FLOATING_POINT = 0x48;

    //--------------------------private helper methods----------------------------

    /**
     * Convert the byte array to an int.
     */
    private static final int convertFromByteToInt(byte[] buffer, int offset) {
        return (buffer[offset] << 24) |
                ((buffer[offset + 1] & 0xFF) << 16) |
                ((buffer[offset + 2] & 0xFF) << 8) |
                (buffer[offset + 3] & 0xFF);
    }

    /**
     * Convert the byte array to a long.
     */
    private static final long convertFromByteToLong(byte[] buffer, int offset) {
        return ((buffer[offset] & 0xFFL) << 56) |
                ((buffer[offset + 1] & 0xFFL) << 48) |
                ((buffer[offset + 2] & 0xFFL) << 40) |
                ((buffer[offset + 3] & 0xFFL) << 32) |
                ((buffer[offset + 4] & 0xFFL) << 24) |
                ((buffer[offset + 5] & 0xFFL) << 16) |
                ((buffer[offset + 6] & 0xFFL) << 8) |
                (buffer[offset + 7] & 0xFFL);
    }

    //--------------entry points for runtime representation-----------------------

    /**
     * Build a Java float from a 4-byte floating point representation.
     *

     * This includes DERBY types:

 REAL
 FLOAT(1<=n<=24)

     *
     * @throws IllegalArgumentException if the specified representation is not recognized.
     */
    static float getFloat(byte[] buffer, int offset) {
        return Float.intBitsToFloat(convertFromByteToInt(buffer, offset));
    }

    /**
     * Build a Java double from an 8-byte floating point representation.
     *

     *

     * This includes DERBY types:

 FLOAT
 DOUBLE [PRECISION]

     *
     * @throws IllegalArgumentException if the specified representation is not recognized.
     */
    static double getDouble(byte[] buffer, int offset) {
        return Double.longBitsToDouble(convertFromByteToLong(buffer, offset));
    }

}


text:
package com.lv.datasource;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.bind.RelaxedDataBinder;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

/**
 * 动态数据源注册;
 * @author Angel(QQ:412887952)
 * @version v.0.1
 */
public class DynamicDataSourceRegister  implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    //如配置文件中未指定数据源类型,使用该默认值
    private static final Object DATASOURCE_TYPE_DEFAULT = "org.apache.tomcat.jdbc.pool.DataSource";
    private ConversionService conversionService = new DefaultConversionService();
    private PropertyValues dataSourcePropertyValues;

    // 默认数据源
    private DataSource defaultDataSource;

    private Map<String, DataSource> customDataSources = new HashMap<>();

    /**
     * 加载多数据源配置
     */
    @Override
    public void setEnvironment(Environment environment) {
       System.out.println("DynamicDataSourceRegister.setEnvironment()");
       initDefaultDataSource(environment);
        initCustomDataSources(environment);
    }

    /**
     * 加载主数据源配置.
     * @param env
     */
    private void initDefaultDataSource(Environment env){
       // 读取主数据源
       RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
       Map<String, Object> dsMap = new HashMap<>();
       dsMap.put("type", propertyResolver.getProperty("type"));
        dsMap.put("driverClassName", propertyResolver.getProperty("driverClassName"));
        dsMap.put("url", propertyResolver.getProperty("url"));
        dsMap.put("username", propertyResolver.getProperty("username"));
        dsMap.put("password", propertyResolver.getProperty("password"));

        //创建数据源;
        defaultDataSource = buildDataSource(dsMap);
        dataBinder(defaultDataSource, env);
    }

    /**
     * 初始化更多数据源
     *
     * @author SHANHY
     * @create 2016年1月24日
     */
    private void initCustomDataSources(Environment env) {
        // 读取配置文件获取更多数据源,也可以通过defaultDataSource读取数据库获取更多数据源
        RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "custom.datasource.");
        String dsPrefixs = propertyResolver.getProperty("names");
        for (String dsPrefix : dsPrefixs.split(",")) {// 多个数据源
            Map<String, Object> dsMap = propertyResolver.getSubProperties(dsPrefix + ".");
            DataSource ds = buildDataSource(dsMap);
            customDataSources.put(dsPrefix, ds);
            dataBinder(ds, env);
        }
    }

    /**
     * 创建datasource.
     * @param dsMap
     * @return
     */
    @SuppressWarnings("unchecked")
    public DataSource buildDataSource(Map<String, Object> dsMap) {
       Object type = dsMap.get("type");
        if (type == null){
            type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource
        }
        Class<? extends DataSource> dataSourceType;

       try {
           dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);
           String driverClassName = dsMap.get("driverClassName").toString();
            String url = dsMap.get("url").toString();
            String username = dsMap.get("username").toString();
            String password = dsMap.get("password").toString();
            DataSourceBuilder factory =   DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(username).password(password).type(dataSourceType);
            return factory.build();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
       return null;
    }

    /**
     * 为DataSource绑定更多数据
     * @param dataSource
     * @param env
     */
    private void dataBinder(DataSource dataSource, Environment env){
       RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);
       dataBinder.setConversionService(conversionService);
       dataBinder.setIgnoreNestedProperties(false);//false
        dataBinder.setIgnoreInvalidFields(false);//false
        dataBinder.setIgnoreUnknownFields(true);//true

        if(dataSourcePropertyValues == null){
            Map<String, Object> rpr = new RelaxedPropertyResolver(env, "spring.datasource").getSubProperties(".");
            Map<String, Object> values = new HashMap<>(rpr);
            // 排除已经设置的属性
            values.remove("type");
            values.remove("driverClassName");
            values.remove("url");
            values.remove("username");
            values.remove("password");
            dataSourcePropertyValues = new MutablePropertyValues(values);
        }
        dataBinder.bind(dataSourcePropertyValues);

    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
       System.out.println("DynamicDataSourceRegister.registerBeanDefinitions()");
       Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
       // 将主数据源添加到更多数据源中
        targetDataSources.put("dataSource", defaultDataSource);
        DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
        // 添加更多数据源
        targetDataSources.putAll(customDataSources);
        for (String key : customDataSources.keySet()) {
            DynamicDataSourceContextHolder.dataSourceIds.add(key);
        }

        // 创建DynamicDataSource
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(DynamicDataSource.class);

        beanDefinition.setSynthetic(true);
        MutablePropertyValues mpv = beanDefinition.getPropertyValues();
        //添加属性:AbstractRoutingDataSource.defaultTargetDataSource
        mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
        mpv.addPropertyValue("targetDataSources", targetDataSources);
        registry.registerBeanDefinition("dataSource", beanDefinition);
    }

}