text:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>

#include <iostream>
#include "p1.h"
#include "ParserUtil.h"
#include "DistMetric.h"

#define FIND_OVERLAPS

int printDistMatrix = 0;
#ifdef DBG
int printMatch = 1;
#else
int printMatch = 0;
#endif
int printAllMatches = 0;
int printAllMatchSummary = 0;
int warnNoMatch = 0;
//int printApproxMatches = 1;
int printApproxMatches = 0;

int p1MatchCalls;
double p1MatchLenTot;
double p1MatchLenSqTot;
int p1MatchLenMax;
int p1MatchLenSqMax;
int p1FMatchCalls;
double p1FMatchLenTot;
double p1FMatchLenSqTot;
int p1FMatchLenMax;
int p1FMatchLenSqMax;

 int printPerfStats;

#define MAX_DIST 100000000

#define dist(a, b) dist[(a)*(slen+1)+(b)]

inline void
printDist(int *dist, int slen, int plen) {
  if (printDistMatrix) {
	int i, j;
	printf("  *");
	for (j = 0; j <= slen; j++)
	  printf("%5d", j);
	printf("\n");

	for (i = 0; i <= plen; i++) {
	  printf("%3d", i);
	  for (j = 0; j <= slen; j++)
		printf("%5d", dist(i, j));
	  printf("\n");
	}
  }
}

#define NONE 4
#define SUBST 1
#define DELETE 2
#define INSERT 3

inline void
prtMatch(int b, int e, float d, const char *p, const char *s,
		 const char *op, bool printMatch) {
  int i, j; bool done;
  if (printMatch) {
	printf("s[%d-%d]: %g\n\tp: ", b, e, d);
	for (i=0, j=0, done=false; (!done); j++) {
	  switch (op[j]) {
	  case NONE:
	  case SUBST:
		putchar(p[i]); i++; continue;
	  case DELETE:
		putchar(p[i]); i++; continue;
	  case INSERT:
		putchar('-'); continue;
	  default:
		done=true; break;
	  }
	}
	printf("\n\ts: ");
	for (i=b, j=0, done=false; (!done); j++) {
	  switch (op[j]) {
	  case NONE:
	  case SUBST:
		putchar(s[i]); i++; continue;
	  case INSERT:
		putchar(s[i]); i++; continue;
	  case DELETE:
		putchar('-'); continue;
	  default:
		done=true; break;
	  }
	}
	printf("\n\to: ");
	for (i=b, j=0, done=false; (!done); j++) {
	  switch (op[j]) {
	  case NONE:
		putchar('N'); continue;
	  case SUBST:
		putchar('S'); continue;
	  case INSERT:
		putchar('I'); continue;
	  case DELETE:
		putchar('D'); continue;
	  default:
		done=true; break;
	  }
	}
	printf("\n");
  }
}

inline int getMatch(int *dist, const char *p, const char *s, int plen,int slen,
					int sEnd, DistMetric& dm, float thresh, char *& opmap) {
  // If we need to print the match, then we need to create the
  // string s1 and p1 that are obtained by aligning the matching
  // portion of s with p, and inserting '-' characters where
  // insertions/deletions take place.
  //
  // If we dont need to print, then we need only compute the
  // beginning of the match, which is in "j" at the end of the loop below

  int i = plen, j = sEnd;
  int k = i+sEnd+1;
  int rv;

  char *op = (char *)alloca(k+1);
  op[k--] = 0;

  while ((i > 0) && (j > 0)) {
	char sc = s[j-1], pc = p[i-1];
	int curDist = dist(i, j);
	if (curDist == dist(i-1, j) + dm.delCost(pc)) {
	  op[k] = DELETE;
	  i--;
	}
	else if (curDist == dist(i, j-1) + dm.insCost(sc)) {
	  op[k] = INSERT;
	  j--;
	}
	else {
	  if (dm.subCost(pc, sc) == 0)
		op[k] = NONE;
	  else op[k] = SUBST;
	  i--; j--;
	}
	k--;
  }

  k++;
  rv = j;
  opmap = strdup(&op[k]);
  return rv;
}

MatchRes&
p1Match(const char* p, const int plen, const char *pnm,
		const char* s, const int slen, const char *snm,
		int sOffset, DistMetric& dm, float distThreshold, MatchRes& mres) {
  int i, j, l;
  int sBeg, sEnd;
  int bestDist=MAX_DIST;
  int prevBest;
  int distDn=0, distRt=0, distDiag=0;
  int* dist;
  char *opmap;

  if ((dist = (int *)alloca((plen+1)*(slen+1)*sizeof(int *))) == NULL) {
	printf("dist is NULL!\n");
	exit(-1);
  }

  MatchRes& rv = mres;
  int costThresh;

  if (printPerfStats) {
	p1MatchCalls++;
	p1MatchLenTot += slen;
	p1MatchLenSqTot += slen*plen;
	p1MatchLenMax = max(p1MatchLenMax, slen);
	p1MatchLenSqMax = max(p1MatchLenSqMax, slen*plen);

	if (printAllMatchSummary)
	  if (loglevel >= LOG_INFO)
		cout << "p1Match(p, s[" << sOffset << '-' << sOffset+slen << "])\n";
  }

  // Initialize costThresh from mres parameter. If mres parameter (now in rv)
  // is not initialized, compute it from distThreshold.

  if (rv.costThresh_ < 0) {
	int maxCost = 0;
	prevBest = MAX_DIST;
	for (i = 0; i < plen; i++)
	  maxCost += dm.delCost(p[i]);
	costThresh = (int)floorf(distThreshold * maxCost);
	rv.costThresh_ = costThresh;
  }
  else {
	prevBest = rv.bestDist_;
	costThresh = rv.costThresh_;
  }

  // Initialize distance matrix

  dist(0, 0) = 0;
  for (j=1; j <= slen; j++)
#ifdef EQUALSTRINGS
	dist(0, j) = dist(0, j-1) + dm.insCost(s[j-1]);
#else
	dist(0, j) = 0;
#endif
  for (i=1; i <= plen; i++)
	dist(i, 0) = dist(i-1, 0) + dm.delCost(p[i-1]);
  printDist(dist, slen, plen);

  // Main loop: compute the minimum distance matrix

  for (i = 1; i <= plen; i++) {
	for (j = 1; j <= slen; j++) {
	  char sc = s[j-1], pc = p[i-1];
	  distDn = dist(i-1, j) + dm.delCost(pc);
	  distRt = dist(i, j-1) + dm.insCost(sc);
	  distDiag = dist(i-1, j-1) + dm.subCost(pc, sc);
      dist(i, j) = min3(distDn, distRt, distDiag);
	}
  }
  printDist(dist, slen, plen);

  /* Now, look for j such that dist(plen, j) is minimum.
	 This gives the lowest cost substring match between p and s */

#ifdef EQUALSTRINGS
  if (plen != slen) {
	cout << plen << "!=" << slen << ", exiting\n";
	exit(1);
  }
  sEnd = slen;
  bestDist = dist(plen, slen);
#else
  sEnd = 1;
  for (j=1; j <= slen; j++) {
	if (dist(plen, j) < bestDist) {
	  bestDist = dist(plen, j);
	  sEnd = j;
	}
  }
#endif
  // Compare the best with previous best matches to see if there is any
  // sense in continuing further. We retain results that are below costThresh
  // that are within 50% of costThresh from the best result so far.

  if (bestDist <= prevBest + (costThresh/2)) {
	int bestSoFar = min(bestDist, prevBest);
	rv.bestDist_ = bestSoFar;

	if (bestDist < prevBest) {
	  for (MatchesIt mi=rv.elem_.begin(); mi != rv.elem_.end();) {
		if ((mi->dist_ > costThresh)&&(mi->dist_ > bestDist+(costThresh/2))) {
		  MatchesIt mi1 = mi;
		  mi++;
		  rv.elem_.erase(mi1);
		}
		else mi++;
	  }
	}

    sBeg = getMatch(dist, p, s, plen, slen, sEnd, dm, distThreshold, opmap);
	prtMatch(sBeg, sEnd, bestDist, p, s, opmap, printMatch);

	MatchResElem mre(bestDist, sBeg + sOffset, sEnd-1 + sOffset, opmap);
	rv.elem_.push_front(mre);

	// Now, compare the best match with other possible matches
	// identified in this invocation of this function

#ifdef FIND_OVERLAPS
	for (l=1; l <= slen; l++) {
	  int currDist  = dist(plen, l);
	  if (((currDist <= costThresh) ||
		   (currDist <= bestSoFar + (costThresh/2))) &&
		  // The first two tests below eliminate consideration of distances
		  // that do not correspond to local minima
		  (currDist < dist(plen, l-1)) &&
		  ((l == slen) || currDist < dist(plen, l+1)) &&
		  (l != sEnd)) /* Dont consider the global minima, either */ {

		j = getMatch(dist, p, s, plen, slen, l, dm, distThreshold, opmap);

		/* s[j]...s[l-1] are included in the match with p */

		// Eliminate matches that have large overlap with the main match.
		// This is necessary since the "non-local minima" test earlier misses
		// situations where the distance increases briefly but then
		// decreases after a few more characters. In that case, you seem to
		// have a local minima, but the corresponding match is subsumed in
		// the ultimate match that is discovered.

		int uniqLen=0;
		if (j < sBeg)
		  uniqLen += sBeg-j;
		if (l > sEnd)
		  uniqLen += l-sEnd;
		if (uniqLen > (plen*distThreshold)) {
		  MatchResElem mre(bestDist, j + sOffset, l-1 + sOffset, opmap);
		  rv.elem_.push_front(mre);
		  prtMatch(j, l, dist(plen, l), p, s, opmap, printAllMatches);
		}
	  } // if ((currDist <= costThresh) ...
	} // for (l=1; ...
#endif
  } // if (bestDist <= ...

  return rv;
}

/*
  NOTE: In the fastmatch algorithm below, and its proof of correctness, we
  only consider insertions and deletions, thus treating a substitution as
  a combination of the two. In reality, the D metric treats substitutions
  differently. But the cost function for substitution is set up to be very
  close to insertion+deletion cost except in two cases: case-folding, and
  substitution of one white space character with another. We handle these
  two cases by using the "normalize" function below to map all alphabetic
  characters into upper case and by mapping all white space character to '_'
*/

/*
  The following fastmatch algorithm computes a fast approximation of the
  distance between a string p and substrings of s. It ensures that

  [A] For any s1=s[i...j] such that D(p, s1) <= t, p1FastMatch will
      invoke p1Match(p, s2) for some string s2 that contains s1 as
	  a substring.

  The algorithm operates by comparing p with every substring
  s_k = s[k-plen+1...k] that is of length plen. It computes an
  approximation FD(p, s_k). Let k_1...k_2 be any maximal subrange
  of [0...slen-1] such that FD(p, s_l) <= t' for k_1 <= l <= k_2.
  Then it invokes p1Match(p, s[k_1-plen+1...k_2]).

  To be useful, FD for all s_k should be computable in time that is linear
  in slen. To do this, we define FD as follows. Let P denote the multiset
  of characters in p, i.e., the number of occurrences of each character in
  p is preserved in P, but their order of occurrence isn't. Similarly, let
  S_k denote the multiset of characters in s_k. We define

    P^u_k = P - S_k   [Denotes characters in p that are "unmatched" by
                      characters in S_k. "-" denotes set difference operation.]
	S^u_k = S_k - P   [Chars in S_k unmatched by characters in p]
	FD(p, s_k) = DelCost(P^u_k) + InsCost(S^u_k)

  Note that FD(p, s_k) <= D(p, s_k): in order to make s_k the same as p,
  you will at least need to delete every characters in P^u_k from p, and then
  insert all the characters in S^u_k. However, it is not enough to set a
  the same threshold on FD as D, or otherwise we can't ensure [A]. So we
  define FD in a slightly different way that lets us use a threshold as t:

        FD(p, s_k) = min(DCost(P^u_k), ICost(S^u_k))

  We can compute both the above quantities in an incremental way as k
  goes from plen-1 to slen.

  We will now show that [A] holds if FD is defined as above. There are two
  cases to consider for our proof, depending on whether s1=s[i...j] is longer
  than or shorter than p.

  1. |s1| >= plen. We will show that for every substring s_k of s1,
     ICost(S^u_k) <= t. (Since s1 = s[i...j], it must be the case that
	 i+plen-1 <= k <= j.) Suppose it is not. Note that S^u_k contains the
	 "excess" characters in s_k that aren't matched by any character in p.
	 Since s_k is a substring of s1, all these characters are included in
	 s1 as well, and must be deleted before s1 can be identical to p.
	 Thus D(p, s1) >= ICost(S^u_k) > t, which contradicts the assumption
	 that D(p, s1) <= t.

  2. |s1| < plen. We will show that for the superstring s_j = s[j-plen+1...j]
     of s1, DCost(P^u_j) <= t. Suppose it is not. Then p has P^u_j unmatched
	 characters in s_j. Since s1 is a substring of s_j, all these will
	 continue to be unmatched in s1, which means that
	 D(p, s1) >= DCost(P^u_j) > t,  again contradicting our assumption.

  To show that the definition FD above captures a necessary condition,
  we can give examples in case 1 where D(p, s1) = ICost(S^u_k). Consider
	    xxxxyyyyxxxx     <--- p     P^u_k = {xx}
       xzxxxyyyyxxxzx    <--- s1    S^u_k = {zz}
  Assume ICost and DCost are equal, and are also equal for all characters.
*/

inline void
adjustDiffIns(char c, short vec[], DistMetric& dm, int& idiff, int& ddiff) {
  if (vec[c] > 0) // an excess of c in p, now reduced when c is added to s
	ddiff -= dm.delCost(c);
  else // an excess of c in s, now excess further increased
	idiff += dm.insCost(c);
  vec[c]--;
}

inline void
adjustDiffDel(char c, short vec[], DistMetric& dm, int& idiff, int& ddiff) {
  if (vec[c] >= 0) // an excess of c in p, further increased now
	ddiff += dm.delCost(c);
  else // an excess of c in s, excess being reduced now, so decrease
	idiff -= dm.insCost(c); // insertion cost correspondingly.
  vec[c]++;
}

MatchRes
p1FastMatch(const char* p, int plen, const char *pnm,
			const char* s, int slen, const char *snm,
			float distThreshold, DistMetric& dm) {

  int idiff=0, ddiff=0, diff;
  int diffThresh;
  int start=-1, end=-1;
  short diffVec[256];
  MatchRes rv;

  p1FMatchCalls++;
  p1FMatchLenTot += slen;
  p1FMatchLenSqTot += slen*plen;
  p1FMatchLenMax = max(p1FMatchLenMax, slen);
  p1FMatchLenSqMax = max(p1FMatchLenSqMax, slen*plen);

  rv.costThresh_ = -1;
  rv.bestDist_ = MAX_DIST;

  memset(diffVec,0, sizeof(diffVec));

  for (int i=0; i < plen; i++) {
	char c = dm.normalize(p[i]);
	adjustDiffDel(c, diffVec, dm, idiff, ddiff);
  }

  diffThresh = (int)floorf(ddiff*distThreshold);

  for (int i=0; i < plen; i++) {
	char d = dm.normalize(s[i]);
	adjustDiffIns(d, diffVec, dm, idiff, ddiff);
  }

  diff = min(idiff, ddiff);
  //  assert(idiff==ddiff);
#ifdef VERBOSE
  cout << "diff=" << diff << ", diffThresh=" << diffThresh << endl;
#endif

  if (diff <= diffThresh)
	start = 0;

  for (int j=plen; j < slen; j++) {
	char c = dm.normalize(s[j-plen]);
	char d = dm.normalize(s[j]);

	adjustDiffDel(c, diffVec, dm, idiff, ddiff);
	adjustDiffIns(d, diffVec, dm, idiff, ddiff);
	diff = min(idiff, ddiff);

	if (start == -1) {
	  if (diff <= diffThresh)
		start = j-plen+1;
	}
	else if (diff > diffThresh) {
	  end = j+1;//-1+diffThresh;
	  if (end >= slen)
		end = slen;
	  start -= 1;//diffThresh;
	  if (start < 0)
		start = 0;

#ifdef VERBOSE
	  cout << "Calling p1Match " << start << ", " << end << endl;
#endif
	  p1Match(p, plen, pnm, &s[start], end-start+1, snm, start,
			  dm, distThreshold, rv);
	  start = -1;
	  //j = end-1;
	}
  }

  if (start != -1) {
	end = slen-1;
#ifdef VERBOSE
	cout << "Calling p1Match " << start << ", " << end << endl;
#endif
	p1Match(p, plen, pnm, &s[start], end-start+1, snm, start,
			dm, distThreshold, rv);
  }

  if (printApproxMatches || printAllMatchSummary) {
	if (!rv.elem_.empty() && (rv.bestDist_ <= rv.costThresh_) &&
		(printAllMatchSummary
		 || ((rv.bestDist_ > 0) || (rv.elem_.size() != 1)))) {
	  if (loglevel >= LOG_INFO) {
		cout << "(" << pnm << " Vs " << snm << "): " << endl;
		cout << "         " << p << endl;
	  }
#ifdef VERBOSE
	  for (MatchesIt mi = rv.elem_.begin(); mi != rv.elem_.end(); mi++) {
		prtMatch(mi->matchBeg_, mi->matchEnd_, mi->dist_, p, s, mi->opmap_, true);
	  }
#endif

	  if (loglevel >= LOG_INFO) {
		for (MatchesIt mi = rv.elem_.begin(); mi != rv.elem_.end(); mi++) {
		  int smin = mi->matchBeg_-6;
		  int smax = mi->matchEnd_+6;
		  if (smin > 0)
			cout << "...";
		  else cout << "   ";
		  for (int i=smin; i <= min(smax, slen-1); i++) {
			if (i >= 0)
			  if ((s[i] == '\n') || (s[i] == '\t'))
				cout << ' ';
			  else cout << s[i];
			else cout << ' ';
		  }
		  if (smax < slen-1)
			cout << "...";
		  cout << '[' << mi->matchBeg_ << ',' << mi->matchEnd_ << "]";
		  if (mi->dist_ != 0)
			cout << ": "
				 << (mi->dist_*distThreshold)/rv.costThresh_;
		  cout << endl;
		}
	  }
	}
  }

  return rv;
}

void printMatchPerfStats(ostream& os) {
  if (loglevel >= LOG_INFO) {
	os << "\n\t\tCalls\tAvgLen\tAvLenSq\tMaxLen\tMaxLenSq\n";
	os << "p1Match\t\t"<< p1MatchCalls << '\t'
	   << round(p1MatchLenTot/(1e-9+p1MatchCalls)) << '\t'
	   << round(p1MatchLenSqTot/(1e-9+p1MatchCalls)) << '\t'
	   << p1MatchLenMax << '\t' << p1MatchLenSqMax << '\n';
	os << "p1FMatch\t"<< p1FMatchCalls << '\t'
	   << round(p1FMatchLenTot/(1e-9+p1FMatchCalls)) << '\t'
	   << round(p1FMatchLenSqTot/(1e-9+p1FMatchCalls)) << '\t'
	   << p1FMatchLenMax << '\t' << p1FMatchLenSqMax << '\n';

	os << "Estimated performance improvement by using fast match: "
	   << round(p1FMatchLenSqTot/(1e-9+max(p1MatchLenSqTot, p1FMatchLenTot)))
	   << "x\n";
	os << "Memory savings due to fast match: "
	   << round(p1FMatchLenSqMax/(p1MatchLenSqMax + 1e-9))
	   << "x\n";
  }
}


text:
layout: "sakuracloud"
page_title: "SakuraCloud: sakuracloud_proxylb"
subcategory: "Global"
description: |-
  Get information about an existing ProxyLB.
---

# Data Source: sakuracloud_proxylb

Get information about an existing ProxyLB.

## Example Usage

```hcl
data "sakuracloud_proxylb" "foobar" {
  filter {
    names = ["foobar"]
  }
}
```
## Argument Reference

* `filter` - (Optional) One or more values used for filtering, as defined below.

---

A `filter` block supports the following:

* `condition` - (Optional) One or more name/values pairs used for filtering. There are several valid keys, for a full reference, check out finding section in the [SakuraCloud API reference](https://developer.sakura.ad.jp/cloud/api/1.1/).
* `id` - (Optional) The resource id on SakuraCloud used for filtering.
* `names` - (Optional) The resource names on SakuraCloud used for filtering. If multiple values are specified, they combined as AND condition.
* `tags` - (Optional) The resource tags on SakuraCloud used for filtering. If multiple values are specified, they combined as AND condition.

---

A `condition` block supports the following:

* `name` - (Required) The name of the target field. This value is case-sensitive.
* `values` - (Required) The values of the condition. If multiple values are specified, they combined as AND condition.
* `operator` - (Optional) The filtering operator. This must be one of following: `partial_match_and`/`exact_match_or`. Default: `partial_match_and`

## Attribute Reference

* `id` - The id of the ProxyLB.
* `bind_port` - A list of `bind_port` blocks as defined below.
* `certificate` - A list of `certificate` blocks as defined below.
* `description` - The description of the ProxyLB.
* `fqdn` - The FQDN for accessing to the ProxyLB. This is typically used as value of CNAME record.
* `gzip` - The flag to enable gzip compression.
* `proxy_protocol` - The flag to enable proxy protocol v2.
* `health_check` - A list of `health_check` blocks as defined below.
* `icon_id` - The icon id attached to the ProxyLB.
* `name` - The name of the ProxyLB.
* `plan` - The plan name of the ProxyLB. This will be one of [`100`/`500`/`1000`/`5000`/`10000`/`50000`/`100000`/`400000`].
* `proxy_networks` - A list of CIDR block used by the ProxyLB to access the server.
* `region` - The name of region that the proxy LB is in. This will be one of [`tk1`/`is1`/`anycast`].
* `rule` - A list of `rule` blocks as defined below.
* `server` - A list of `server` blocks as defined below.
* `sorry_server` - A list of `sorry_server` blocks as defined below.
* `sticky_session` - The flag to enable sticky session.
* `syslog` - A list of `syslog` blocks as defined below.
* `tags` - Any tags assigned to the ProxyLB.
* `timeout` - The timeout duration in seconds.
* `vip` - The virtual IP address assigned to the ProxyLB.
* `vip_failover` - The flag to enable VIP fail-over.

---

A `bind_port` block exports the following:

* `port` - The number of listening port.
* `proxy_mode` - The proxy mode. This will be one of [`http`/`https`/`tcp`].
* `redirect_to_https` - The flag to enable redirection from http to https. This flag is used only when `proxy_mode` is `http`.
* `response_header` - A list of `response_header` blocks as defined below.
* `support_http2` - The flag to enable HTTP/2. This flag is used only when `proxy_mode` is `https`.

---

A `response_header` block exports the following:

* `header` - The field name of HTTP header added to response by the ProxyLB.
* `value` - The field value of HTTP header added to response by the ProxyLB.

---

A `certificate` block exports the following:

* `additional_certificate` - A list of `additional_certificate` blocks as defined below.
* `common_name` - The common name of the certificate.
* `intermediate_cert` - The intermediate certificate for a server.
* `private_key` - The private key for a server.
* `server_cert` - The certificate for a server.
* `subject_alt_names` - The subject alternative names of the certificate.

---

A `additional_certificate` block exports the following:

* `intermediate_cert` - The intermediate certificate for a server.
* `private_key` - The private key for a server.
* `server_cert` - The certificate for a server.

---

A `health_check` block exports the following:

* `delay_loop` - The interval in seconds between checks.
* `host_header` - The value of host header send when checking by HTTP.
* `path` - The path used when checking by HTTP.
* `port` - The port number used when checking by TCP.
* `protocol` - The protocol used for health checks. This will be one of [`http`/`tcp`].

---

A `rule` block exports the following:

* `action` - The type of action to be performed when requests matches the rule. This will be one of [`forward`/`redirect`/`fixed`].
* `fixed_content_type` - Content-Type header value for fixed response sent when requests matches the rule. This will be one of [`text/plain`/`text/html`/`application/javascript`/`application/json`].
* `fixed_message_body` - Content body for fixed response sent when requests matches the rule.
* `fixed_status_code` - HTTP status code for fixed response sent when requests matches the rule. This will be one of [`200`/`403`/`503`].
* `group` - The name of load balancing group. When proxyLB received request which matched to `host` and `path`, proxyLB forwards the request to servers that having same group name.
* `host` - The value of HTTP host header that is used as condition of rule-based balancing.
* `path` - The request path that is used as condition of rule-based balancing.
* `redirect_location` - The URL to redirect to when the request matches the rule. see https://manual.sakura.ad.jp/cloud/appliance/enhanced-lb/#enhanced-lb-rule for details.
* `redirect_status_code` - HTTP status code for redirects sent when requests matches the rule. This will be one of [`301`/`302`].

---

A `server` block exports the following:

* `enabled` - The flag to enable as destination of load balancing.
* `group` - The name of load balancing group. This is used when using rule-based load balancing.
* `ip_address` - The IP address of the destination server.
* `port` - The port number of the destination server.

---

A `sorry_server` block exports the following:

* `ip_address` - The IP address of the SorryServer. This will be used when all servers are down.
* `port` - The port number of the SorryServer. This will be used when all servers are down.

---

A `syslog` block exports the following:

* `port` - The number of syslog port.
* `server` - The address of syslog server.

redpajama_set_name: RedPajamaGithub


text:
// This is ExFat, an exFAT accessor written in pure C#
// Released under MIT license
// https://github.com/picrap/ExFat

namespace ExFat.Partition.Entries
{
    using System;

    /// <summary>
    /// File attributes. Here are the only attributes supported by exFAT
    /// </summary>
    [Flags]
    public enum ExFatFileAttributes : UInt16
    {
        /// <summary>
        /// Read-only file
        /// </summary>
        ReadOnly = 0x01,
        /// <summary>
        /// Hidden entry
        /// </summary>
        Hidden = 0x02,
        /// <summary>
        /// System entry
        /// </summary>
        System = 0x04,
        /// <summary>
        /// Marks a directory (otherwise the entry is a file)
        /// </summary>
        Directory = 0x10,
        /// <summary>
        /// Marks a file for archive (indicates it was modified)
        /// </summary>
        Archive = 0x20,
    }
}


text:
/**
 *  @module   Nomenclatures
 *
 *  @access   public
 *  @author   TAurelien
 *  @date     2015-05-02
 *  @version  1.0.0
 */
'use strict';

// Module dependencies ========================================================
var events = require('events');

module.exports = function setup(options, imports, register) {
	console.log();
	console.log('Registering the nomenclatures component module ...');

	/**
	 *  Nomenclatures
	 *
	 *  @class  Nomenclatures
	 *
	 *  @type  {Object}
	 */
	var Nomenclatures = new events.EventEmitter();

	var emitter = require('./events')(options, imports, Nomenclatures);
	require('./api')(options, imports, emitter, Nomenclatures);

	// Register --------------

	register(null, {
		nomenclatures: Nomenclatures
	});

};


text:
import { connect } from 'react-redux';
import { injectIntl } from 'react-intl';
import { push } from 'connected-react-router';
import { createStructuredSelector } from 'reselect';

import {
  factionFormSelector,
  currentEntitySelector,
  factionIsCreatingSelector,
} from 'store/selectors/base.selectors';
import { getCurrentEntities } from 'store/selectors/entity.selectors';
import {
  currentFormHitPoints,
  isValidFactionForm,
} from 'store/selectors/faction.selectors';
import {
  updateFaction,
  updateFactionAsset,
  createBlankAsset,
  submitForm,
} from 'store/actions/faction.actions';

import FactionForm from './faction-form';

const mapStateToProps = createStructuredSelector({
  currentFaction: currentEntitySelector,
  isCreating: factionIsCreatingSelector,
  isValid: isValidFactionForm,
  form: factionFormSelector,
  currentEntities: getCurrentEntities,
  hitPoints: currentFormHitPoints,
});

const mapDispatchToProps = (dispatch, props) => ({
  updateFaction: update => dispatch(updateFaction(update)),
  createBlankAsset: () => dispatch(createBlankAsset()),
  toRoute: route => dispatch(push(route)),
  updateFactionAsset: (key, update) =>
    dispatch(updateFactionAsset(key, update)),
  submitForm: () => dispatch(submitForm(props.intl)),
});

export default injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(FactionForm),
);


text:
import Ember from 'ember';
import ChartsMixin from '../../../mixins/charts';
import { module, test } from 'qunit';

module('Unit | Mixin | charts');

// Replace this with your real tests.
test('it works', function(assert) {
  var ChartsObject = Ember.Object.extend(ChartsMixin);
  var subject = ChartsObject.create();
  assert.ok(subject);
});


text:
using System;
using Gtk;
using Pinta.Resources;

namespace Pinta.Core
{
	public static class PintaCore
	{
		public static LayerManager Layers { get; private set; }
		public static PaintBrushManager PaintBrushes { get; private set; }
		public static ToolManager Tools { get; private set; }
		public static ChromeManager Chrome { get; private set; }
		public static PaletteManager Palette { get; private set; }
		public static ResourceManager Resources { get; private set; }
		public static ActionManager Actions { get; private set; }
		public static WorkspaceManager Workspace { get; private set; }
		public static SystemManager System { get; private set; }
		public static LivePreviewManager LivePreview { get; private set; }
		public static SettingsManager Settings { get; private set; }
		public static EffectsManager Effects { get; private set; }
		public static IServiceManager Services { get; }

		public const string ApplicationVersion = "2.1";

		static PintaCore ()
		{
			// Resources and Settings are intialized first so later
			// Managers can access them as needed.
			Resources = new ResourceManager ();
			Settings = new SettingsManager ();

			Actions = new ActionManager ();
			Workspace = new WorkspaceManager ();
			Layers = new LayerManager ();
			PaintBrushes = new PaintBrushManager ();
			Tools = new ToolManager ();
			System = new SystemManager ();
			LivePreview = new LivePreviewManager ();
			Palette = new PaletteManager ();
			Chrome = new ChromeManager ();
			Effects = new EffectsManager ();

			Services = new ServiceManager ();

			Services.AddService<IResourceService> (Resources);
			Services.AddService<ISettingsService> (Settings);
			Services.AddService (Actions);
			Services.AddService<IWorkspaceService> (Workspace);
			Services.AddService (Layers);
			Services.AddService<IPaintBrushService> (PaintBrushes);
			Services.AddService<IToolService> (Tools);
			Services.AddService (System);
			Services.AddService (LivePreview);
			Services.AddService<IPaletteService> (Palette);
			Services.AddService (Chrome);
			Services.AddService (Effects);
		}

		public static void Initialize ()
		{
			Actions.RegisterHandlers ();
		}
	}
}


text:
- support useCssTransform

## 1.4.0

- only flip if it's visible

## 1.1.0

- support targetOffset
- offset/targetOffset support percentage value


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

    <!-- From: file:/Users/chris/Development/ActionBar-PullToRefresh/library/src/main/res/values-sv/pull_refresh_strings.xml -->
    <eat-comment />

    <string name="pull_to_refresh_pull_label">Dra nedåt om du vill uppdatera</string>
    <string name="pull_to_refresh_refreshing_label">Uppdaterar…</string>
    <string name="pull_to_refresh_release_label">Släpp om du vill uppdatera</string>

</resources>


text:
require 'sketchup'

require File.dirname(__FILE__) + '/sitecfg.rb'

require 'gratr'

require 'buildGeometryManager'
require 'buildDDLCallBacks'
require 'readXMLFiles'
require 'PartBuilder'
require 'solids'
require 'graph_functions.rb'
require 'graph_functions_DD'
load 'PosPartExecuter.rb'
load 'LogicalPartInstance.rb'
load 'LogicalPartDefiner.rb'

##__________________________________________________________________||
def cmsmain

  read_xmlfiles
  # read_xmlfiles_from_cache

  draw_gratr

end

##__________________________________________________________________||
def draw_gratr

  # all PosParts in the XML file
  graphAll = GRATR::DirectedPseudoGraph.new
  $posPartsManager.parts.each { |pp| graphAll.add_edge!(pp.parentName, pp.childName, pp) }

  vertices = Hash[$logicalPartsManager.parts.map { |p| [p.name, LogicalPartInstance.new($geometryManager, p)] } ]

  topName = :"cms:CMSE"

  nameDepthEB = [ {:name => :"ebalgo:ESPM", :depth => 0},
                ]

  nameDepthEE = [ {:name => :"eehier:ENCA", :depth => 0},
                  {:name => :"esalgo:SF", :depth => 0},
                ]

  ## nameDepthHB = [ {:name => :"hcalbarrelalgo:HBModule", :depth => 0},
  ##               ]

  nameDepthHB = [ {:name => :"hcalbarrelalgo:HB", :depth => 0},
                ]

  nameDepthHE = [ {:name => :"hcalalgo:HEC1", :depth => 0},
                  {:name => :"hcalalgo:HEC2", :depth => 0},
                  {:name => :"hcalendcapalgo:HEModule", :depth => 0},
                ]

  nameDepthHE = [ {:name => :"hcalendcapalgo:HEFront", :depth => 0},
                ]

  nameDepthHF = [ {:name => :"hcalforwardalgo:VCAL", :depth => 2},
                ]

  nameDepthECAL = nameDepthEB + nameDepthEE
  ## nameDepthHCAL = nameDepthHB + nameDepthHE + nameDepthHF
  nameDepthHCAL = nameDepthHB + nameDepthHE

  nameDepthList = nameDepthHCAL + nameDepthECAL

  names = nameDepthList.collect { |e| e[:name] }
  graphTopToNames = subgraph_from_to(graphAll, topName, names)

  graphNamesToDepths = graphAll.class.new
  nameDepthList.each do |e|
    graphNamesToDepths = graphNamesToDepths + subgraph_from_depth(graphAll, e[:name], e[:depth])
  end

  graph = graphTopToNames + graphNamesToDepths

  draw_array graph, vertices, topName

end

##__________________________________________________________________||
def draw_array graph, vertexLabel, topName

  Sketchup.active_model.definitions.purge_unused
  start_time = Time.now
  Sketchup.active_model.start_operation("Draw CMS", true)

  posPartExecuter = PosPartExecuter.new $geometryManager

  graph.edges.each do |edge|
    posPart = edge.label
    posPartExecuter.exec posPart, vertexLabel[edge.source], vertexLabel[edge.target]
  end

  graph.topsort.reverse.each do |v|
    logicalPart = vertexLabel[v]
    next if logicalPart.children.size > 0 and logicalPart.materialName.to_s =~ /Air$/
    next if logicalPart.children.size > 0 and logicalPart.materialName.to_s =~ /free_space$/
    logicalPart.placeSolid()
  end

  # $logicalPartsManager.get(topName).placeSolid()

  graph.topsort.reverse.each do |v|
    logicalPart = vertexLabel[v]
    logicalPart.define()
  end

  lp = vertexLabel[topName.to_sym]
  definition = lp.definition
  if definition
    entities = Sketchup.active_model.entities
    transform = Geom::Transformation.new(Geom::Point3d.new(0, 0, 15.m))
    solidInstance = entities.add_instance definition, transform
  end

  Sketchup.active_model.commit_operation
  end_time = Time.now
  puts "Time elapsed #{(end_time - start_time)*1000} milliseconds"

end

##__________________________________________________________________||
def read_xmlfiles
  topDir = File.expand_path(File.dirname(__FILE__)) + '/'
  xmlfileListTest = [
    'GeometryExtended.xml'
                    ]

  xmlfileList = xmlfileListTest

  xmlfileList.map! {|f| f = topDir + f }

  p xmlfileList

  geometryManager = buildGeometryManager()
  callBacks = buildDDLCallBacks(geometryManager)
  readXMLFiles(xmlfileList, callBacks)
end

##__________________________________________________________________||
def read_xmlfiles_from_cache
  fillGeometryManager($geometryManager)
  $geometryManager.reload_from_cache
end

##__________________________________________________________________||

cmsmain


text:
<?php
use DrestTests\Writer\WriterTestCase;
use Drest\Configuration;

error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', 'On');

$loader = require '../../../vendor/autoload.php';

// Add the entities namespace to the loader
$loader->add('Entities', __DIR__.'/../');
$loader->add('Service', __DIR__.'/../');

// Create an example doctrine application
$ormConfig = new \Doctrine\ORM\Configuration();

$pathToEntities = array(__DIR__ . '/../Entities');
$ORMDriver = $ormConfig->newDefaultAnnotationDriver($pathToEntities, false);

$ormConfig->setMetadataDriverImpl($ORMDriver);

// Do proxy stuff
$ormConfig->setProxyDir(__DIR__ . '/Entities/Proxies');
$ormConfig->setProxyNamespace('Entities\Proxies');
$ormConfig->setAutoGenerateProxyClasses(true);

$em = \Doctrine\ORM\EntityManager::create(array(
	'host' => 'localhost',
	'user' => 'developer',
	'password' => 'developer',
	'dbname' => 'drest',
	'driver' => 'pdo_mysql'
), $ormConfig);

try
{
	$drestConfig = new Configuration();

	$drestConfig->setDetectContentOptions(array(
	    Configuration::DETECT_CONTENT_HEADER => 'Accept',
	    Configuration::DETECT_CONTENT_EXTENSION => true,
	    Configuration::DETECT_CONTENT_PARAM => 'format'
    ));

    $drestConfig->setExposureDepth(3);

    $drestConfig->setExposeRequestOption(Configuration::EXPOSE_REQUEST_PARAM_GET, 'expose');

	$drestConfig->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache());

	$drestConfig->setDebugMode(true);

	$drestConfig->addPathsToConfigFiles($pathToEntities);

	$drestManager = \Drest\Manager::create($em, $drestConfig);

} catch (Exception $e) {
	echo $e->getMessage() . PHP_EOL;
	echo $e->getTraceAsString() . PHP_EOL;
}

echo $drestManager->dispatch();

//echo $drestManager->dispatch(new \Zend\Http\PhpEnvironment\Request(), new Zend\Http\PhpEnvironment\Response());


text:
package com.ark.android.weatherapp.ui.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ark.android.weatherapp.R;
import com.ark.android.weatherapp.mvpContract.ActivityFragmentContract;
import com.ark.android.weatherapp.ui.custom.NestedWebView;

/**
 *
 * Created by Ark on 6/26/2017.
 */

public class AboutFragment extends Fragment implements ActivityFragmentContract.FragmentToolBarSetupInterface{

    private NestedWebView aboutWebView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.about_fragment, container, false);

        initUi(rootView);
        loadAboutPage();

        return rootView;
    }

    private void loadAboutPage() {
        aboutWebView.loadUrl("file:///android_asset/about.html");
    }

    private void initUi(View rootView) {
        aboutWebView = (NestedWebView) rootView.findViewById(R.id.aboutWebView);
    }

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

    @Override
    public void setupToolBar() {
        ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
        if(actionBar != null){
            actionBar.setTitle(R.string.aboutApp);
            ((ActivityFragmentContract.FragmentInteractionListener)getActivity()).showBackBtn(true);
        }

        ((ActivityFragmentContract.FragmentInteractionListener)getActivity()).changeToolbarButtonsVisibility(false, false, false);
    }
}


text:
<?php

namespace SVG\Nodes\Structures;

use SVG\Nodes\SVGNodeContainer;
use SVG\Rasterization\SVGRasterizer;

/**
 * Represents the SVG tag 'symbol'.
 */
class SVGSymbol extends SVGNodeContainer
{
    const TAG_NAME = 'symbol';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @inheritdoc
     */
    public function rasterize(SVGRasterizer $rasterizer)
    {
        // Nothing to rasterize.
    }
}


text:
package org.vitrivr.cineast.standalone.importer.handlers;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.vitrivr.cineast.core.util.LogHelper;
import org.vitrivr.cineast.standalone.importer.LIREImporter;

public class LIREImportHandler extends DataImportHandler {
    /** */
    private static final Logger LOGGER = LogManager.getLogger();

    /**
     * Default constructor for {@link LIREImportHandler}.
     *
     * @param threads Number if threads to use
     * @param batchSize Batch size to use for import.
     */
    public LIREImportHandler(int threads, int batchSize) {
        super(threads, batchSize);
    }

    @Override
    public void doImport(Path path) {
        try {
            LOGGER.info("Starting data import with LIRE files in: {}", path.toString());
            if (!Files.isDirectory(path)) {
                LOGGER.error("Could not start data import process with path '{}', because it is not a directory.", path);
                return;
            }

            final String name = path.getFileName().toString();
            Files.walk(path, 2).filter(p -> p.toString().toLowerCase().endsWith("." + name)).forEach(p -> {
                final String filename = p.getFileName().toString();
                final String suffix = filename.substring(filename.lastIndexOf("."));
                try {
                    this.futures.add(this.service.submit(new DataImportRunner(new LIREImporter(p.toFile()), "feature_" + name, "lire_" + filename.replace(suffix, ""))));
                } catch (IOException e) {
                    LOGGER.error("Could not start data import for file '{}'. Skipping...?", p.toString());
                }
            });
        } catch (IOException e) {
            LOGGER.error("Could not start data import process with path '{}' due to an IOException: {}. Aborting...", path.toString(), LogHelper.getStackTrace(e));
        }
    }
}


text:
package com.netflix.nicobar.example.groovy2;

import static com.netflix.nicobar.example.groovy2.ExampleResourceLocator.GROOVY2_COMPILER_PLUGIN_CLASS;
import static com.netflix.nicobar.example.groovy2.ExampleResourceLocator.GROOVY2_PLUGIN_ID;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.IOUtils;

import com.netflix.hystrix.Hystrix;
import com.netflix.nicobar.core.archive.JarScriptArchive;
import com.netflix.nicobar.core.execution.HystrixScriptModuleExecutor;
import com.netflix.nicobar.core.execution.ScriptModuleExecutable;
import com.netflix.nicobar.core.module.BaseScriptModuleListener;
import com.netflix.nicobar.core.module.ScriptModule;
import com.netflix.nicobar.core.module.ScriptModuleLoader;
import com.netflix.nicobar.core.module.ScriptModuleUtils;
import com.netflix.nicobar.core.persistence.ArchiveRepository;
import com.netflix.nicobar.core.persistence.ArchiveRepositoryPoller;
import com.netflix.nicobar.core.persistence.JarArchiveRepository;
import com.netflix.nicobar.core.plugin.ScriptCompilerPluginSpec;

/**
 * Example of how to build a script runtime that polls for Groovy based archives on disk.
 * At the end of this example, there will be a the following classloaders
 *
 *<pre>
 *  Bootstrap Classloader  (/jre/lib) - virtual
 *  ExtClassLoader         (/jre/lib/exp)
 *  AppClassLoader         (nicobar-core, nicobar-example)
 *  Groovy2RuntimeModule   (nicobar-groovy2, groovy-all.jar)
 *  HelloWorld             (HelloWorld.class)
 *  </pre>
 * @author James Kojo
 */
public class GroovyModuleLoaderExample {
    // test script module info
    private static final String SCRIPT_MODULE_ID = "HelloWorld";
    private static final String ARCHIVE_JAR_NAME = "HelloWorld.jar";

    public static void main(String[] args) throws Exception {
        new GroovyModuleLoaderExample().runExample();
    }

    public void runExample() throws Exception {

        // create the loader with the groovy plugin
        ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder()
            .addPluginSpec(new ScriptCompilerPluginSpec.Builder(GROOVY2_PLUGIN_ID) // configure Groovy plugin
                .addRuntimeResource(ExampleResourceLocator.getGroovyRuntime())
                .addRuntimeResource(ExampleResourceLocator.getGroovyPluginLocation())
                .withPluginClassName(GROOVY2_COMPILER_PLUGIN_CLASS)
                .build())
            .addListener(new BaseScriptModuleListener() {                // add an example listener for module updates
                public void moduleUpdated(ScriptModule newScriptModule, ScriptModule oldScriptModule) {
                    System.out.printf("Received module update event. newModule: %s,  oldModule: %s%n", newScriptModule, oldScriptModule);
                }
            })
            .build();

        // create an archive repository and wrap a poller around it to feed updates to the module loader
        Path baseArchiveDir = Files.createTempDirectory(GroovyModuleLoaderExample.class.getSimpleName());
        JarArchiveRepository repository = new JarArchiveRepository.Builder(baseArchiveDir).build();
        deployTestArchive(repository);
        ArchiveRepositoryPoller poller = new ArchiveRepositoryPoller.Builder(moduleLoader).build();
        poller.addRepository(repository, 30, TimeUnit.SECONDS, true);

        // the test module has now been compiled and is ready for execution.
        // create a closure which knows how to bind any request time inputs (if any) and execute the module.
        ScriptModuleExecutable<String> executable = new ScriptModuleExecutable<String>() {
            @Override
            public String execute(ScriptModule scriptModule) throws Exception {
                // the script doesn't necessarily have to implement any specific interfaces, but it does need to
                // be compilable to a class.
                Class<?> callable = ScriptModuleUtils.findAssignableClass(scriptModule, Callable.class);
                @SuppressWarnings("unchecked")
                Callable<String> instance = (Callable<String>) callable.newInstance();
                String result = instance.call();
                return result;
            }
        };

        // Execute it in a Hystrix command.
        HystrixScriptModuleExecutor<String> executor = new HystrixScriptModuleExecutor<String>("TestModuleExecutor");
        List<String> results = executor.executeModules(Collections.singletonList(SCRIPT_MODULE_ID), executable, moduleLoader);
        System.out.println("Module(s) have been executed. Output: " + results);

        // release the Hystrix resources
        Hystrix.reset();
    }

    /*
     * Copy the example script module files to temporary directory and insert it into the repository
     */
    private static void deployTestArchive(ArchiveRepository repository) throws IOException {
        InputStream archiveJarIs = GroovyModuleLoaderExample.class.getClassLoader().getResourceAsStream(ARCHIVE_JAR_NAME);
        Path archiveToDeploy = Files.createTempFile(SCRIPT_MODULE_ID, ".jar");
        Files.copy(archiveJarIs, archiveToDeploy, StandardCopyOption.REPLACE_EXISTING);
        IOUtils.closeQuietly(archiveJarIs);
        JarScriptArchive jarScriptArchive = new JarScriptArchive.Builder(archiveToDeploy).build();
        repository.insertArchive(jarScriptArchive);
    }
}


text:
Difficulty: Medium

https://leetcode.com/problems/permutations-ii/

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

**Example:**
```
Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
```


text:
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

public class BLETestScript : MonoBehaviour
{
	public Transform PanelActive;
	public Transform PanelInActive;
	public Transform PanelTypeSelection;

	static private BLETestScript _bleTestSCript;
	static public void Show (Transform panel)
	{
		if (_bleTestSCript == null)
		{
			GameObject gameObject = GameObject.Find ("Canvas");
			if (gameObject != null)
				_bleTestSCript = gameObject.GetComponent<BLETestScript> ();
		}

		if (_bleTestSCript != null)
		{
			while (_bleTestSCript.PanelActive.childCount > 0)
				_bleTestSCript.PanelActive.GetChild (0).transform.SetParent (_bleTestSCript.PanelInActive);

			panel.SetParent (_bleTestSCript.PanelActive);
		}
	}

	// Use this for initialization
	void Start ()
	{
		BusyScript.IsBusy = false;
		Show (PanelTypeSelection);
	}

	// Update is called once per frame
	void Update ()
	{
	}
}


text:
package org.openfact.models.jpa.ubl.common;

import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityManager;

import org.jboss.logging.Logger;
import org.openfact.models.OpenfactSession;
import org.openfact.models.jpa.JpaModel;
import org.openfact.models.jpa.entities.ubl.common.PartyEntity;
import org.openfact.models.jpa.entities.ubl.common.ShipmentStageEntity;
import org.openfact.models.ubl.common.LocationCommAggModel;
import org.openfact.models.ubl.common.PartyModel;
import org.openfact.models.ubl.common.PeriodModel;
import org.openfact.models.ubl.common.ShipmentStageModel;
import org.openfact.models.ubl.common.TransportMeansModel;

public class ShipmentStageAdapter implements ShipmentStageModel, JpaModel<ShipmentStageEntity> {

	protected static final Logger logger = Logger.getLogger(ShipmentStageAdapter.class);

	protected ShipmentStageEntity shipmentStage;
	protected EntityManager em;
	protected OpenfactSession session;

	public ShipmentStageAdapter(OpenfactSession session, EntityManager em, ShipmentStageEntity shipmentStage) {
		this.session = session;
		this.em = em;
		this.shipmentStage = shipmentStage;
	}

	@Override
	public ShipmentStageEntity getEntity() {
		return shipmentStage;
	}

	@Override
	public String getID() {
		return shipmentStage.getID();
	}

	@Override
	public void setID(String value) {
		shipmentStage.setID(value);
	}

	@Override
	public String getTransportModeCode() {
		return shipmentStage.getTransportModeCode();
	}

	@Override
	public void setTransportModeCode(String value) {
		shipmentStage.setTransportModeCode(value);
	}

	@Override
	public String getTransportMeansTypeCode() {
		return shipmentStage.getTransportMeansTypeCode();
	}

	@Override
	public void setTransportMeansTypeCode(String value) {
		shipmentStage.setTransportMeansTypeCode(value);
	}

	@Override
	public String getTransitDirectionCode() {
		return shipmentStage.getTransitDirectionCode();
	}

	@Override
	public void setTransitDirectionCode(String value) {
		shipmentStage.setTransitDirectionCode(value);
	}

	@Override
	public boolean getPreCarriageIndicator() {
		return shipmentStage.isPreCarriageIndicator();
	}

	@Override
	public void setPreCarriageIndicator(boolean value) {
		shipmentStage.setPreCarriageIndicator(value);
	}

	@Override
	public boolean getOnCarriageIndicator() {
		return shipmentStage.isOnCarriageIndicator();
	}

	@Override
	public void setOnCarriageIndicator(boolean value) {
		shipmentStage.setOnCarriageIndicator(value);
	}

	@Override
	public PeriodModel getTransitPeriod() {
		return new PeriodAdapter(session, em, shipmentStage.getTransitPeriod());
	}

	@Override
	public void setTransitPeriod(PeriodModel value) {
		shipmentStage.setTransitPeriod(PeriodAdapter.toEntity(value, em));
	}

	@Override
	public List<PartyModel> getCarrierParty() {
		return shipmentStage.getCarrierParty().stream().map(f -> new PartyAdapter(session, em, f))
				.collect(Collectors.toList());
	}

	@Override
	public void setCarrierParty(List<PartyModel> carrierParty) {
		List<PartyEntity> entities = carrierParty.stream().map(f -> PartyAdapter.toEntity(f, em))
				.collect(Collectors.toList());
		shipmentStage.setCarrierParty(entities);

	}

	@Override
	public TransportMeansModel getTransportMeans() {
		return new TransportMeansAdapter(session, em, shipmentStage.getTransportMeans());
	}

	@Override
	public void setTransportMeans(TransportMeansModel value) {
		shipmentStage.setTransportMeans(TransportMeansAdapter.toEntity(value, em));
	}

	@Override
	public LocationCommAggModel getLoadingPortLocation() {
		return new LocationCommAggAdapter(session, em, shipmentStage.getLoadingPortLocation());
	}

	@Override
	public void setLoadingPortLocation(LocationCommAggModel value) {
		shipmentStage.setLoadingPortLocation(LocationCommAggAdapter.toEntity(value, em));
	}

	@Override
	public LocationCommAggModel getUnloadingPortLocation() {
		return new LocationCommAggAdapter(session, em, shipmentStage.getUnloadingPortLocation());
	}

	@Override
	public void setUnloadingPortLocation(LocationCommAggModel value) {
		shipmentStage.setUnloadingPortLocation(LocationCommAggAdapter.toEntity(value, em));
	}

	@Override
	public LocationCommAggModel getTransshipPortLocation() {
		return new LocationCommAggAdapter(session, em, shipmentStage.getTransshipPortLocation());
	}

	@Override
	public void setTransshipPortLocation(LocationCommAggModel value) {
		shipmentStage.setTransshipPortLocation(LocationCommAggAdapter.toEntity(value, em));
	}

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

	public static ShipmentStageEntity toEntity(ShipmentStageModel model, EntityManager em) {
		if (model instanceof ShipmentStageAdapter) {
			return ((ShipmentStageAdapter) model).getEntity();
		}
		return em.getReference(ShipmentStageEntity.class, model.getId());
	}

}


text:
namespace WingEngine
{

	Material::Material()
	{

	}

	Material::~Material()
	{

	}

}


text:
<?PHP

Lang::init();

/**
 * The Lang class allows you to set language variables using language files in your application.
 *
 * @package core
 * @author liut
 **/
class Lang
{
	/**
	 * @var    array    $paths    array of paths
	 */
	protected static $paths = [];

	/**
	 * @var    array    $loaded    array of loaded files
	 */
	protected static $loaded = [];

	/**
	 * @var  array  language lines
	 */
	protected static $lines = [];

	/**
	 * @var  array  available langs
	 */
	protected static $available = [];

	/**
	 * @var  string current select language
	 */
	protected static $current = NULL;

	/**
	 * @var  array  language(s) to fall back on when loading a file from the current lang fails
	 */
	protected static $fallback = [];

	/**
	 * init
	 */
	public static function init()
	{
		$available = defined('LANG_AVAILABLE') ? LANG_AVAILABLE : 'en';
		static::$available = explode(' ', $available);

		$fallback = defined('LANG_FALLBACK') ? LANG_FALLBACK : 'en';
		static::$fallback = explode(',', $fallback);
	}

	/**
	 * Returns currently active language.
	 *
	 * @return   string    currently active language
	 */
	public static function current($language = NULL)
	{
		if (is_null($language)) {
			if (is_null(static::$current)) {
				return static::$fallback[0];
			}
			return static::$current;
		}

		if (in_array($language, static::$available)) {
			static::$current = $language;
		} else {
			throw new InvalidArgumentException('Invalid language `'.$language.'`');
		}
	}

	public static function fallback()
	{
		return static::$fallback[0];
	}

	/**
	 * 判断是否不是默认语言
	 *
	 * @param string $lang
	 * @return void
	 **/
	public static function changed($lang)
	{
		return $lang && $lang !== static::fallback();
	}

	/**
	 * check or return available language.
	 *
	 * @return   string    currently active language
	 */
	public static function available($language = NULL)
	{
		if (is_null($language)) {
			return static::$available;
		}

		return in_array($language, static::$available);
	}

	/**
	 * get all paths or add a valid path
	 *
	 * @param string $path
	 * @return void
	 **/
	public static function path($path = NULL)
	{
		if(is_null($path)) {
			if (empty(static::$paths)) {
				static::$paths = [LIB_ROOT . 'lang', APP_ROOT . 'lang', DATA_ROOT . 'lang'];
			}
			return static::$paths;
		}

		if (is_string($path)) {
			$path = rtrim($path, '\\/');
			if(is_dir($path) && !in_array($path, static::$paths)) {
				static::$paths[] = $path;
			}
		}
	}

	/**
	 * Loads a language file.
	 *
	 * @param    mixed        $file        string file | language array
	 * @param    mixed       $group        null for no group, true for group is filename, false for not storing in the master lang
	 * @param    string|null $language     name of the language to load, null for the configurated language
	 * @param    bool        $overwrite    true for array_merge, false for Arr::merge
	 * @param    bool        $reload       true to force a reload even if the file is already loaded
	 * @return   array                     the (loaded) language array
	 */
	public static function load($file, $group = NULL, $language = NULL, $overwrite = false, $reload = false)
	{
		// get the active language and all fallback languages
		$language or $language = static::current();
		$languages = static::$fallback;

		Log::debug('file: ' . $file . ' group: ' . $group . ' lang: ' . $language, __METHOD__);

		// make sure we don't have the active language in the fallback array
		if (in_array($language, $languages))
		{
			unset($languages[array_search($language, $languages)]);
		}

		// stick the active language to the front of the list
		array_unshift($languages, $language);

		//Log::debug($languages, __METHOD__);

		if ( ! $reload and
		     ! is_array($file) and
		     ! is_object($file) and
		    array_key_exists($file, static::$loaded))
		{
			$group === true and $group = $file;
			if ($group === NULL or $group === false or ! isset(static::$lines[$language][$group]))
			{
				return false;
			}
			return static::$lines[$language][$group];
		}

		$lang = [];
		if (is_array($file))
		{
			$lang = $file;
		}
		elseif (is_string($file))
		{
			foreach ($languages as $language) {
				foreach (static::path() as $path) {
					$name = $language . '.' . $file;
					$_lang = Loader::config($name, [], $path);//Log::debug($_lang, 'loader::config ' . $name);

					if (is_array($_lang) && !empty($_lang)) {
						$lang = array_merge($lang, $_lang);
						// Log::debug(' ' . $name . ' loaded ' . count($_lang) . ' from ' . Loader::safePath($path), __METHOD__);
						break;
					}
					// else {
					// 	if (strpos($file, '.') === FALSE) {
					// 		Log::info(Loader::safePath($path) . DS . $name . ' not found', __METHOD__);
					// 	}
					// }

					unset($_lang);
				}

				if ($lang) {
					break;
				}
			}

			if (empty($lang)) {
				Log::notice('lang: ' . $language . ', file: ' . $file . ' not found', __METHOD__);
			}

			static::$loaded[$file] = count($lang);
		}

		if ($group === NULL)
		{
			isset(static::$lines[$language]) or static::$lines[$language] = array();
			static::$lines[$language] = $overwrite ? array_merge(static::$lines[$language], $lang) : Arr::merge(static::$lines[$language], $lang);
		}
		else
		{
			$group = ($group === true) ? $file : $group;
			isset(static::$lines[$language][$group]) or static::$lines[$language][$group] = array();
			static::$lines[$language][$group] = $overwrite ? array_merge(static::$lines[$language][$group], $lang) : Arr::merge(static::$lines[$language][$group], $lang);
		}

		return $lang;
	}

	/**
	 * Save a language array to disk.
	 *
	 * @param   string          $file      desired file name
	 * @param   string|array    $lang      master language array key or language array
	 * @param   string|null     $language  name of the language to load, null for the configurated language
	 * @return  bool                       false when language is empty or invalid else \File::update result
	 */
	public static function save($file, $lang, $language = NULL)
	{
		($language === NULL) and $language = static::current();

		// prefix the file with the language
		if ( ! is_null($language))
		{
			$file = explode('::', $file);
			end($file);
			$file[key($file)] = $language.DS.end($file);
			$file = implode('::', $file);
		}

		if ( ! is_array($lang))
		{
			if ( ! isset(static::$lines[$language][$lang]))
			{
				return false;
			}
			$lang = static::$lines[$language][$lang];
		}

		$type = pathinfo($file, PATHINFO_EXTENSION);
		if( ! $type)
		{
			$type = 'php';
			$file .= '.'.$type;
		}

		$dir = end(static::$paths);

		$output = static::_export($lang, $type);

		file_put_contents($dir . DS . $file, $output);

	}

	/**
	 * Returns a (dot notated) language string
	 *
	 * @param   string       $line      key for the line
	 * @param   array        $params    array of params to str_replace
	 * @param   mixed        $default   default value to return
	 * @param   string|null  $language  name of the language to get, null for the configurated language
	 * @return  mixed                   either the line or default when not found
	 */
	public static function get($line, array $params = array(), $default = NULL, $language = NULL)
	{
		($language === NULL) and $language = static::current();

		Log::debug('line: ' . $line . ' default: ' . $default . ' lang: ' . $language, __METHOD__);

		if (isset(static::$lines[$language])) {
			return static::_str_tr(Arr::get(static::$lines[$language], $line, $default), $params);
		}
		return $default;
	}

	/**
	 * Sets a (dot notated) language string
	 *
	 * @param    string       $line      a (dot notated) language key
	 * @param    mixed        $value     the language string
	 * @param    string       $group     group
	 * @param    string|null  $language  name of the language to set, null for the configurated language
	 * @return   void                    the Arr::set result
	 */
	public static function set($line, $value, $group = NULL, $language = NULL)
	{
		$group === NULL or $line = $group.'.'.$line;

		($language === NULL) and $language = static::current();

		isset(static::$lines[$language]) or static::$lines[$language] = array();

		return Arr::set(static::$lines[$language], $line, $value);
	}

	/**
	 * Deletes a (dot notated) language string
	 *
	 * @param    string       $item      a (dot notated) language key
	 * @param    string       $group     group
	 * @param    string|null  $language  name of the language to set, null for the configurated language
	 * @return   array|bool              the Arr::delete result, success boolean or array of success booleans
	 */
	public static function delete($item, $group = NULL, $language = NULL)
	{
		$group === NULL or $line = $group.'.'.$line;

		($language === NULL) and $language = static::current();

		return isset(static::$lines[$language]) ? Arr::delete(static::$lines[$language], $item) : false;
	}

	/**
	 * Returns the formatted language file contents.
	 *
	 * @param   array   $content  config array
	 * @return  string  formatted config file contents
	 */
	protected static function _export($contents, $type = 'php')
	{
		if (is_string($contents)) {
			return $contents;
		}

		// TODO: add to support ini

		$output = <<<CONF
<?php

CONF;
		$output .= 'return '.str_replace(array('  ', 'array (', '\''.APP_ROOT, '\''.CONF_ROOT, '\''.WEB_ROOT, '\''.LIB_ROOT), array("\t", 'array(', 'APP_ROOT.\'', 'CONF_ROOT.\'', 'WEB_ROOT.\'', 'LIB_ROOT.\''), var_export($contents, true)).";\n";
		return $output;
	}

	/**
	 * Parse the params from a string using strtr()
	 *
	 * @param   string  string to parse
	 * @param   array   params to str_replace
	 * @return  string
	 */
	public static function _str_tr($string, $array = [])
	{
		if (is_string($string))
		{
			$tr_arr = array();

			foreach ($array as $from => $to)
			{
				substr($from, 0, 1) !== ':' and $from = ':'.$from;
				$tr_arr[$from] = $to;
			}
			unset($array);

			return strtr($string, $tr_arr);
		}
		else
		{
			return $string;
		}
	}

	public static function loaded()
	{
		return static::$loaded;
	}

	public static function lines()
	{
		return static::$lines;
	}

	public static function label($lang)
	{
		static $languages = NULL;
		if (is_null($languages)) {
			$languages = Loader::config('languages');
		}

		if (isset($languages[$lang])) {
			return $languages[$lang];
		}

		return $lang;
	}

} // END class


text:
package kana

func init() {
	Initialize()
}


text:
<Alloy>
	<Window class="container" id="buyTickets" onOpen="onOpen" onClose="onClose">
	</Window>
</Alloy>