text:
Clazz.declarePackage ("J.modelsetbio");
Clazz.load (["J.api.JmolBioResolver"], "J.modelsetbio.Resolver", ["java.lang.Boolean", "$.NullPointerException", "java.util.Arrays", "$.Hashtable", "JU.BS", "$.P3", "$.P4", "$.PT", "$.SB", "$.V3", "J.constant.EnumStructure", "J.modelset.Group", "J.modelsetbio.AlphaMonomer", "$.AlphaPolymer", "$.AminoMonomer", "$.AminoPolymer", "$.BioModel", "$.CarbohydrateMonomer", "$.CarbohydratePolymer", "$.Monomer", "$.NucleicMonomer", "$.NucleicPolymer", "$.PhosphorusMonomer", "$.PhosphorusPolymer", "J.util.BSUtil", "$.Logger", "$.Measure", "$.Txt", "J.viewer.JC"], function () {
c$ = Clazz.decorateAsClass (function () {
this.modelLoader = null;
this.modelSet = null;
this.bsAddedHydrogens = null;
this.bsAtomsForHs = null;
this.htBondMap = null;
this.htGroupBonds = null;
this.hNames = null;
this.lastSetH = -2147483648;
this.maxSerial = 0;
this.baseBondIndex = 0;
this.haveHsAlready = false;
this.vAB = null;
this.vAC = null;
this.vNorm = null;
this.plane = null;
if (!Clazz.isClassDefined ("J.modelsetbio.Resolver.BondSorter")) {
J.modelsetbio.Resolver.$Resolver$BondSorter$ ();
}
this.bsAssigned = null;
Clazz.instantialize (this, arguments);
}, J.modelsetbio, "Resolver", null, J.api.JmolBioResolver);
Clazz.makeConstructor (c$,
function () {
});
$_V(c$, "getBioModel",
function (modelIndex, trajectoryBaseIndex, jmolData, modelProperties, modelAuxiliaryInfo) {
return  new J.modelsetbio.BioModel (this.modelSet, modelIndex, trajectoryBaseIndex, jmolData, modelProperties, modelAuxiliaryInfo);
}, "~N,~N,~S,java.util.Properties,java.util.Map");
$_V(c$, "distinguishAndPropagateGroup",
function (chain, group3, seqcode, firstAtomIndex, maxAtomIndex, modelIndex, specialAtomIndexes, atoms) {
var lastAtomIndex = maxAtomIndex - 1;
var distinguishingBits = 0;
for (var i = J.viewer.JC.ATOMID_MAX; --i >= 0; ) specialAtomIndexes[i] = -2147483648;

for (var i = maxAtomIndex; --i >= firstAtomIndex; ) {
var specialAtomID = atoms[i].getAtomID ();
if (specialAtomID <= 0) continue;
if (specialAtomID < 14) {
distinguishingBits |= (1 << specialAtomID);
}specialAtomIndexes[specialAtomID] = i;
}
if (lastAtomIndex < firstAtomIndex) throw  new NullPointerException ();
var m = null;
if ((distinguishingBits & 14) == 14) m = J.modelsetbio.AminoMonomer.validateAndAllocate (chain, group3, seqcode, firstAtomIndex, lastAtomIndex, specialAtomIndexes, atoms);
 else if (distinguishingBits == 4) m = J.modelsetbio.AlphaMonomer.validateAndAllocateA (chain, group3, seqcode, firstAtomIndex, lastAtomIndex, specialAtomIndexes);
 else if (((distinguishingBits & 8128) == 8128)) m = J.modelsetbio.NucleicMonomer.validateAndAllocate (chain, group3, seqcode, firstAtomIndex, lastAtomIndex, specialAtomIndexes);
 else if (distinguishingBits == 8192) m = J.modelsetbio.PhosphorusMonomer.validateAndAllocateP (chain, group3, seqcode, firstAtomIndex, lastAtomIndex, specialAtomIndexes);
 else if (J.viewer.JC.checkCarbohydrate (group3)) m = J.modelsetbio.CarbohydrateMonomer.validateAndAllocate (chain, group3, seqcode, firstAtomIndex, lastAtomIndex);
return (m != null && m.leadAtomIndex >= 0 ? m : null);
}, "J.modelset.Chain,~S,~N,~N,~N,~N,~A,~A");
$_V(c$, "setHaveHsAlready",
function (b) {
this.haveHsAlready = b;
}, "~B");
$_V(c$, "initialize",
function (modelLoader) {
this.modelLoader = modelLoader;
this.modelSet = modelLoader.modelSet;
}, "J.modelset.ModelLoader");
$_V(c$, "initializeHydrogenAddition",
function () {
this.baseBondIndex = this.modelLoader.modelSet.bondCount;
this.bsAddedHydrogens =  new JU.BS ();
this.bsAtomsForHs =  new JU.BS ();
this.htBondMap =  new java.util.Hashtable ();
this.htGroupBonds =  new java.util.Hashtable ();
this.hNames =  new Array (3);
this.vAB =  new JU.V3 ();
this.vAC =  new JU.V3 ();
this.vNorm =  new JU.V3 ();
this.plane =  new JU.P4 ();
});
$_V(c$, "addImplicitHydrogenAtoms",
function (adapter, iGroup, nH) {
var group3 = this.modelLoader.getGroup3 (iGroup);
var nH1;
if (this.haveHsAlready || group3 == null || (nH1 = J.viewer.JC.getStandardPdbHydrogenCount (J.modelset.Group.lookupGroupID (group3))) == 0) return;
nH = (nH1 < 0 ? -1 : nH1 + nH);
var model = null;
var iFirst = this.modelLoader.getFirstAtomIndex (iGroup);
var atomCount = this.modelSet.getAtomCount ();
if (nH < 0) {
if (atomCount - iFirst == 1) return;
model = this.modelSet.viewer.getLigandModel (group3, "ligand_", "_data", null);
if (model == null) return;
nH = adapter.getHydrogenAtomCount (model);
if (nH < 1) return;
}this.getBondInfo (adapter, group3, model);
this.modelSet.models[this.modelSet.atoms[iFirst].modelIndex].isPdbWithMultipleBonds = true;
this.bsAtomsForHs.setBits (iFirst, atomCount);
this.bsAddedHydrogens.setBits (atomCount, atomCount + nH);
var isHetero = this.modelSet.atoms[iFirst].isHetero ();
var xyz = JU.P3.new3 (NaN, NaN, NaN);
for (var i = 0; i < nH; i++) this.modelSet.addAtom (this.modelSet.atoms[iFirst].modelIndex, this.modelSet.atoms[iFirst].getGroup (), 1, "H", 0, 0, xyz, NaN, null, 0, 0, 1, 0, null, isHetero, 0, null).deleteBonds (null);

}, "J.api.JmolAdapter,~N,~N");
$_M(c$, "getBondInfo",
function (adapter, group3, model) {
if (this.htGroupBonds.get (group3) != null) return;
var bondInfo;
if (model == null) {
bondInfo = this.modelSet.viewer.getPdbBondInfo (group3);
} else {
bondInfo = this.getLigandBondInfo (adapter, model, group3);
}if (bondInfo == null) return;
this.htGroupBonds.put (group3, Boolean.TRUE);
for (var i = 0; i < bondInfo.length; i++) {
if (bondInfo[i] == null) continue;
if (bondInfo[i][1].charAt (0) == 'H') this.htBondMap.put (group3 + "." + bondInfo[i][0], bondInfo[i][1]);
 else this.htBondMap.put (group3 + ":" + bondInfo[i][0] + ":" + bondInfo[i][1], bondInfo[i][2]);
}
}, "J.api.JmolAdapter,~S,~O");
$_M(c$, "getLigandBondInfo",
($fz = function (adapter, model, group3) {
var dataIn = adapter.getBondList (model);
var htAtoms =  new java.util.Hashtable ();
var iterAtom = adapter.getAtomIterator (model);
while (iterAtom.hasNext ()) htAtoms.put (iterAtom.getAtomName (), iterAtom.getXYZ ());

var bondInfo =  new Array (dataIn.length * 2);
var n = 0;
for (var i = 0; i < dataIn.length; i++) {
var b = dataIn[i];
if (b[0].charAt (0) != 'H') bondInfo[n++] = [b[0], b[1], b[2], b[1].startsWith ("H") ? "0" : "1"];
if (b[1].charAt (0) != 'H') bondInfo[n++] = [b[1], b[0], b[2], b[0].startsWith ("H") ? "0" : "1"];
}
java.util.Arrays.sort (bondInfo, Clazz.innerTypeInstance (J.modelsetbio.Resolver.BondSorter, this, null));
var t;
for (var i = 0; i < n; ) {
t = bondInfo[i];
var a1 = t[0];
var nH = 0;
var nC = 0;
for (; i < n && (t = bondInfo[i])[0].equals (a1); i++) {
if (t[3].equals ("0")) {
nH++;
continue;
}if (t[3].equals ("1")) nC++;
}
var pt = i - nH - nC;
if (nH == 1) continue;
switch (nC) {
case 1:
var sep = (nH == 2 ? '@' : '|');
for (var j = 1; j < nH; j++) {
bondInfo[pt][1] += sep + bondInfo[pt + j][1];
bondInfo[pt + j] = null;
}
continue;
case 2:
if (nH != 2) continue;
var name = bondInfo[pt][0];
var name1 = bondInfo[pt + nH][1];
var name2 = bondInfo[pt + nH + 1][1];
var factor = name1.compareTo (name2);
J.util.Measure.getPlaneThroughPoints (htAtoms.get (name1), htAtoms.get (name), htAtoms.get (name2), this.vNorm, this.vAB, this.vAC, this.plane);
var d = J.util.Measure.distanceToPlane (this.plane, htAtoms.get (bondInfo[pt][1])) * factor;
bondInfo[pt][1] = (d > 0 ? bondInfo[pt][1] + "@" + bondInfo[pt + 1][1] : bondInfo[pt + 1][1] + "@" + bondInfo[pt][1]);
bondInfo[pt + 1] = null;
}
}
for (var i = 0; i < n; i++) {
if ((t = bondInfo[i]) != null && t[1].charAt (0) != 'H' && t[0].compareTo (t[1]) > 0) {
bondInfo[i] = null;
continue;
}if (t != null) J.util.Logger.info (" ligand " + group3 + ": " + bondInfo[i][0] + " - " + bondInfo[i][1] + " order " + bondInfo[i][2]);
}
return bondInfo;
}, $fz.isPrivate = true, $fz), "J.api.JmolAdapter,~O,~S");
$_V(c$, "finalizeHydrogens",
function () {
this.modelSet.viewer.getLigandModel (null, null, null, null);
this.finalizePdbMultipleBonds ();
this.addHydrogens ();
});
$_M(c$, "addHydrogens",
($fz = function () {
if (this.bsAddedHydrogens.nextSetBit (0) < 0) return;
this.finalizePdbCharges ();
var nTotal =  Clazz.newIntArray (1, 0);
var pts = this.modelSet.calculateHydrogens (this.bsAtomsForHs, nTotal, true, false, null);
var groupLast = null;
var ipt = 0;
for (var i = 0; i < pts.length; i++) {
if (pts[i] == null) continue;
var atom = this.modelSet.atoms[i];
var g = atom.getGroup ();
if (g !== groupLast) {
groupLast = g;
ipt = g.lastAtomIndex;
while (this.bsAddedHydrogens.get (ipt)) ipt--;

}var gName = atom.getGroup3 (false);
var aName = atom.getAtomName ();
var hName = this.htBondMap.get (gName + "." + aName);
if (hName == null) continue;
var isChiral = hName.contains ("@");
var isMethyl = (hName.endsWith ("?") || hName.indexOf ("|") >= 0);
var n = pts[i].length;
if (n == 3 && !isMethyl && hName.equals ("H@H2")) {
hName = "H|H2|H3";
isMethyl = true;
isChiral = false;
}if (isChiral && n == 3 || isMethyl != (n == 3)) {
J.util.Logger.info ("Error adding H atoms to " + gName + g.getResno () + ": " + pts[i].length + " atoms should not be added to " + aName);
continue;
}var pt = hName.indexOf ("@");
switch (pts[i].length) {
case 1:
if (pt > 0) hName = hName.substring (0, pt);
this.setHydrogen (i, ++ipt, hName, pts[i][0]);
break;
case 2:
var hName1;
var hName2;
var d = -1;
var bonds = atom.getBonds ();
if (bonds != null) switch (bonds.length) {
case 2:
var atom1 = bonds[0].getOtherAtom (atom);
var atom2 = bonds[1].getOtherAtom (atom);
var factor = atom1.getAtomName ().compareTo (atom2.getAtomName ());
J.util.Measure.getPlaneThroughPoints (atom1, atom, atom2, this.vNorm, this.vAB, this.vAC, this.plane);
d = J.util.Measure.distanceToPlane (this.plane, pts[i][0]) * factor;
break;
}
if (pt < 0) {
J.util.Logger.info ("Error adding H atoms to " + gName + g.getResno () + ": expected to only need 1 H but needed 2");
hName1 = hName2 = "H";
} else if (d < 0) {
hName2 = hName.substring (0, pt);
hName1 = hName.substring (pt + 1);
} else {
hName1 = hName.substring (0, pt);
hName2 = hName.substring (pt + 1);
}this.setHydrogen (i, ++ipt, hName1, pts[i][0]);
this.setHydrogen (i, ++ipt, hName2, pts[i][1]);
break;
case 3:
var pt1 = hName.indexOf ('|');
if (pt1 >= 0) {
var pt2 = hName.lastIndexOf ('|');
this.hNames[0] = hName.substring (0, pt1);
this.hNames[1] = hName.substring (pt1 + 1, pt2);
this.hNames[2] = hName.substring (pt2 + 1);
} else {
this.hNames[0] = hName.$replace ('?', '1');
this.hNames[1] = hName.$replace ('?', '2');
this.hNames[2] = hName.$replace ('?', '3');
}this.setHydrogen (i, ++ipt, this.hNames[0], pts[i][0]);
this.setHydrogen (i, ++ipt, this.hNames[1], pts[i][2]);
this.setHydrogen (i, ++ipt, this.hNames[2], pts[i][1]);
break;
}
}
this.deleteUnneededAtoms ();
this.modelSet.fixFormalCharges (J.util.BSUtil.newBitSet2 (this.modelLoader.baseAtomIndex, this.modelLoader.modelSet.atomCount));
}, $fz.isPrivate = true, $fz));
$_M(c$, "deleteUnneededAtoms",
($fz = function () {
var bsBondsDeleted =  new JU.BS ();
for (var i = this.bsAtomsForHs.nextSetBit (0); i >= 0; i = this.bsAtomsForHs.nextSetBit (i + 1)) {
var atom = this.modelSet.atoms[i];
if (!atom.isHetero () || atom.getElementNumber () != 8 || atom.getFormalCharge () != 0 || atom.getCovalentBondCount () != 2) continue;
var bonds = atom.getBonds ();
var atom1 = bonds[0].getOtherAtom (atom);
var atomH = bonds[1].getOtherAtom (atom);
if (atom1.getElementNumber () == 1) {
var a = atom1;
atom1 = atomH;
atomH = a;
}if (atomH.getElementNumber () != 1) continue;
var bonds1 = atom1.getBonds ();
for (var j = 0; j < bonds1.length; j++) {
if (bonds1[j].order == 2) {
var atomO = bonds1[j].getOtherAtom (atom1);
if (atomO.getElementNumber () == 8) {
this.bsAddedHydrogens.set (atomH.index);
atomH.deleteBonds (bsBondsDeleted);
break;
}}}
}
this.modelSet.deleteBonds (bsBondsDeleted, true);
this.modelLoader.deleteAtoms (this.bsAddedHydrogens);
}, $fz.isPrivate = true, $fz));
$_M(c$, "finalizePdbCharges",
($fz = function () {
var atoms = this.modelSet.atoms;
for (var i = this.bsAtomsForHs.nextSetBit (0); i >= 0; i = this.bsAtomsForHs.nextSetBit (i + 1)) {
var a = atoms[i];
if (a.getGroup ().getNitrogenAtom () === a && a.getCovalentBondCount () == 1) a.setFormalCharge (1);
if ((i = this.bsAtomsForHs.nextClearBit (i + 1)) < 0) break;
}
}, $fz.isPrivate = true, $fz));
$_M(c$, "finalizePdbMultipleBonds",
($fz = function () {
var htKeysUsed =  new java.util.Hashtable ();
var bondCount = this.modelSet.bondCount;
var bonds = this.modelSet.bonds;
for (var i = this.baseBondIndex; i < bondCount; i++) {
var a1 = bonds[i].getAtom1 ();
var a2 = bonds[i].getAtom2 ();
var g = a1.getGroup ();
if (g !== a2.getGroup ()) continue;
var key =  new JU.SB ().append (g.getGroup3 ());
key.append (":");
var n1 = a1.getAtomName ();
var n2 = a2.getAtomName ();
if (n1.compareTo (n2) > 0) key.append (n2).append (":").append (n1);
 else key.append (n1).append (":").append (n2);
var skey = key.toString ();
var type = this.htBondMap.get (skey);
if (type == null) continue;
htKeysUsed.put (skey, Boolean.TRUE);
bonds[i].setOrder (JU.PT.parseInt (type));
}
for (var key, $key = this.htBondMap.keySet ().iterator (); $key.hasNext () && ((key = $key.next ()) || true);) {
if (htKeysUsed.get (key) != null) continue;
if (key.indexOf (":") < 0) {
htKeysUsed.put (key, Boolean.TRUE);
continue;
}var value = this.htBondMap.get (key);
J.util.Logger.info ("bond " + key + " was not used; order=" + value);
if (this.htBondMap.get (key).equals ("1")) {
htKeysUsed.put (key, Boolean.TRUE);
continue;
}}
var htKeysBad =  new java.util.Hashtable ();
for (var key, $key = this.htBondMap.keySet ().iterator (); $key.hasNext () && ((key = $key.next ()) || true);) {
if (htKeysUsed.get (key) != null) continue;
htKeysBad.put (key.substring (0, key.lastIndexOf (":")), this.htBondMap.get (key));
}
if (htKeysBad.isEmpty ()) return;
for (var i = 0; i < bondCount; i++) {
var a1 = bonds[i].getAtom1 ();
var a2 = bonds[i].getAtom2 ();
if (a1.getGroup () === a2.getGroup ()) continue;
var value;
if ((value = htKeysBad.get (a1.getGroup3 (false) + ":" + a1.getAtomName ())) == null && ((value = htKeysBad.get (a2.getGroup3 (false) + ":" + a2.getAtomName ())) == null)) continue;
bonds[i].setOrder (JU.PT.parseInt (value));
J.util.Logger.info ("assigning order " + bonds[i].order + " to bond " + bonds[i]);
}
}, $fz.isPrivate = true, $fz));
$_M(c$, "setHydrogen",
($fz = function (iTo, iAtom, name, pt) {
if (!this.bsAddedHydrogens.get (iAtom)) return;
var atoms = this.modelSet.atoms;
if (this.lastSetH == -2147483648 || atoms[iAtom].modelIndex != atoms[this.lastSetH].modelIndex) this.maxSerial = (this.modelSet.getModelAuxiliaryInfoValue (atoms[this.lastSetH = iAtom].modelIndex, "PDB_CONECT_firstAtom_count_max"))[2];
this.bsAddedHydrogens.clear (iAtom);
this.modelSet.setAtomName (iAtom, name);
atoms[iAtom].setT (pt);
this.modelSet.setAtomNumber (iAtom, ++this.maxSerial);
atoms[iAtom].setAtomSymmetry (atoms[iTo].getAtomSymmetry ());
this.modelLoader.undeleteAtom (iAtom);
this.modelSet.bondAtoms (atoms[iTo], atoms[iAtom], 1, this.modelSet.getDefaultMadFromOrder (1), null, 0, true, false);
}, $fz.isPrivate = true, $fz), "~N,~N,~S,JU.P3");
$_V(c$, "fixPropertyValue",
function (bsAtoms, data) {
var aData = JU.PT.split (data, "\n");
var atoms = this.modelSet.atoms;
var newData =  new Array (bsAtoms.cardinality ());
var lastData = "";
for (var pt = 0, iAtom = 0, i = bsAtoms.nextSetBit (0); i >= 0; i = bsAtoms.nextSetBit (i), iAtom++) {
if (atoms[i].getElementNumber () != 1) lastData = aData[pt++];
newData[iAtom] = lastData;
}
return J.util.Txt.join (newData, '\n', 0);
}, "JU.BS,~S");
c$.allocateBioPolymer = $_M(c$, "allocateBioPolymer",
function (groups, firstGroupIndex, checkConnections) {
var previous = null;
var count = 0;
for (var i = firstGroupIndex; i < groups.length; ++i) {
var group = groups[i];
var current;
if (!(Clazz.instanceOf (group, J.modelsetbio.Monomer)) || (current = group).bioPolymer != null || previous != null && previous.getClass () !== current.getClass () || checkConnections && !current.isConnectedAfter (previous)) break;
previous = current;
count++;
}
if (count == 0) return null;
var monomers =  new Array (count);
for (var j = 0; j < count; ++j) monomers[j] = groups[firstGroupIndex + j];

if (Clazz.instanceOf (previous, J.modelsetbio.AminoMonomer)) return  new J.modelsetbio.AminoPolymer (monomers);
if (Clazz.instanceOf (previous, J.modelsetbio.AlphaMonomer)) return  new J.modelsetbio.AlphaPolymer (monomers);
if (Clazz.instanceOf (previous, J.modelsetbio.NucleicMonomer)) return  new J.modelsetbio.NucleicPolymer (monomers);
if (Clazz.instanceOf (previous, J.modelsetbio.PhosphorusMonomer)) return  new J.modelsetbio.PhosphorusPolymer (monomers);
if (Clazz.instanceOf (previous, J.modelsetbio.CarbohydrateMonomer)) return  new J.modelsetbio.CarbohydratePolymer (monomers);
J.util.Logger.error ("Polymer.allocatePolymer() ... no matching polymer for monomor " + previous);
throw  new NullPointerException ();
}, "~A,~N,~B");
$_V(c$, "iterateOverAllNewStructures",
function (adapter, atomSetCollection) {
var iterStructure = adapter.getStructureIterator (atomSetCollection);
if (iterStructure == null) return;
var bs = iterStructure.getStructuredModels ();
if (bs != null) for (var i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1)) this.modelLoader.structuresDefinedInFile.set (this.modelLoader.baseModelIndex + i);

while (iterStructure.hasNext ()) if (iterStructure.getStructureType () !== J.constant.EnumStructure.TURN) this.setStructure (iterStructure);

iterStructure = adapter.getStructureIterator (atomSetCollection);
while (iterStructure.hasNext ()) if (iterStructure.getStructureType () === J.constant.EnumStructure.TURN) this.setStructure (iterStructure);

}, "J.api.JmolAdapter,~O");
$_M(c$, "setStructure",
($fz = function (iterStructure) {
var t = iterStructure.getSubstructureType ();
var id = iterStructure.getStructureID ();
var serID = iterStructure.getSerialID ();
var count = iterStructure.getStrandCount ();
var atomRange = iterStructure.getAtomIndices ();
var modelRange = iterStructure.getModelIndices ();
if (this.bsAssigned == null) this.bsAssigned =  new JU.BS ();
this.defineStructure (t, id, serID, count, iterStructure.getStartChainID (), iterStructure.getStartSequenceNumber (), iterStructure.getStartInsertionCode (), iterStructure.getEndChainID (), iterStructure.getEndSequenceNumber (), iterStructure.getEndInsertionCode (), atomRange, modelRange, this.bsAssigned);
}, $fz.isPrivate = true, $fz), "J.api.JmolAdapterStructureIterator");
$_M(c$, "defineStructure",
($fz = function (subType, structureID, serialID, strandCount, startChainID, startSequenceNumber, startInsertionCode, endChainID, endSequenceNumber, endInsertionCode, atomRange, modelRange, bsAssigned) {
var type = (subType === J.constant.EnumStructure.NOT ? J.constant.EnumStructure.NONE : subType);
var startSeqCode = J.modelset.Group.getSeqcodeFor (startSequenceNumber, startInsertionCode);
var endSeqCode = J.modelset.Group.getSeqcodeFor (endSequenceNumber, endInsertionCode);
var models = this.modelSet.models;
if (this.modelLoader.isTrajectory) {
modelRange[1] = modelRange[0];
} else {
modelRange[0] += this.modelLoader.baseModelIndex;
modelRange[1] += this.modelLoader.baseModelIndex;
}this.modelLoader.structuresDefinedInFile.setBits (modelRange[0], modelRange[1] + 1);
for (var i = modelRange[0]; i <= modelRange[1]; i++) {
var i0 = models[i].firstAtomIndex;
if (Clazz.instanceOf (models[i], J.modelsetbio.BioModel)) (models[i]).addSecondaryStructure (type, structureID, serialID, strandCount, startChainID, startSeqCode, endChainID, endSeqCode, i0 + atomRange[0], i0 + atomRange[1], bsAssigned);
}
}, $fz.isPrivate = true, $fz), "J.constant.EnumStructure,~S,~N,~N,~N,~N,~S,~N,~N,~S,~A,~A,JU.BS");
c$.$Resolver$BondSorter$ = function () {
Clazz.pu$h ();
c$ = Clazz.decorateAsClass (function () {
Clazz.prepareCallback (this, arguments);
Clazz.instantialize (this, arguments);
}, J.modelsetbio.Resolver, "BondSorter", null, java.util.Comparator);
$_V(c$, "compare",
function (a, b) {
return (b == null ? (a == null ? 0 : -1) : a == null ? 1 : a[0].compareTo (b[0]) < 0 ? -1 : a[0].compareTo (b[0]) > 0 ? 1 : a[3].compareTo (b[3]) < 0 ? -1 : a[3].compareTo (b[3]) > 0 ? 1 : a[1].compareTo (b[1]) < 0 ? -1 : a[1].compareTo (b[1]) > 0 ? 1 : 0);
}, "~A,~A");
c$ = Clazz.p0p ();
};
});


text:
package com.sillelien.jas.impl.jproxy.core.clsmgr.srcunit;

import com.sillelien.jas.impl.FileExt;
import com.sillelien.jas.impl.jproxy.JProxyUtil;
import com.sillelien.jas.impl.jproxy.core.clsmgr.FolderSourceList;
import org.jetbrains.annotations.NotNull;

/**
 * @author jmarranz
 */
public class SourceScriptRootFileJavaExt extends SourceScriptRootFile {
    public SourceScriptRootFileJavaExt(@NotNull FileExt sourceFile, @NotNull FolderSourceList folderSourceList) {
        super(sourceFile, folderSourceList);
    }

    @NotNull
    @Override
    public String getScriptCode(@NotNull String encoding, @NotNull boolean[] hasHashBang) {
        hasHashBang[0] = false;
        return JProxyUtil.readTextFile(sourceFile.getFile(), encoding);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.switchyard.console.client.ui.config;

import java.util.List;

import org.jboss.as.console.client.Console;
import org.jboss.as.console.client.shared.subsys.RevealStrategy;
import org.jboss.as.console.spi.AccessControl;
import org.jboss.ballroom.client.layout.LHSHighlightEvent;
import org.switchyard.console.client.NameTokens;
import org.switchyard.console.client.Singleton;
import org.switchyard.console.client.model.SwitchYardStore;
import org.switchyard.console.client.model.SystemDetails;
import org.switchyard.console.client.ui.component.ComponentPresenter.PresenterFactory;
import org.switchyard.console.components.client.model.Component;
import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ContentSlot;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.Place;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.Proxy;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest.Builder;

/**
 * ConfigPresenter
 *
 * Presenter for SwitchYard system configuration.
 *
 * @author Rob Cernich
 */
public class ConfigPresenter extends Presenter<ConfigPresenter.MyView, ConfigPresenter.MyProxy> {

    /**
     * MyProxy
     *
     * The proxy type associated with this presenter.
     */
    @ProxyCodeSplit
    @NameToken(NameTokens.SYSTEM_CONFIG_PRESENTER)
    @AccessControl(resources = {"/{selected.host}/{selected.server}/subsystem=switchyard" })
    public interface MyProxy extends Proxy<ConfigPresenter>, Place {
    }

    /** The slot where component specific details are displayed. */
    @ContentSlot
    public static final GwtEvent.Type<RevealContentHandler<?>> TYPE_COMPONENT_CONTENT = new GwtEvent.Type<RevealContentHandler<?>>();

    /** The slot where extension specific details are displayed. */
    @ContentSlot
    public static final GwtEvent.Type<RevealContentHandler<?>> TYPE_EXTENSION_CONTENT = new GwtEvent.Type<RevealContentHandler<?>>();

    /**
     * MyView
     *
     * The view type associated with this presenter.
     */
    public interface MyView extends View {
        /**
         * @param presenter the presenter for the view.
         */
        void setPresenter(ConfigPresenter presenter);

        /**
         * @param systemDetails details of the SwitchYard system.
         */
        void setSystemDetails(SystemDetails systemDetails);

        /**
         * @param components the installed components.
         */
        void setComponents(List<Component> components);

        /**
         * @param extensions the installed extensions.
         */
        void setExtensions(List<Component> extensions);
}

    private final PlaceManager _placeManager;
    private final RevealStrategy _revealStrategy;
    private final SwitchYardStore _switchYardStore;
    private final PresenterFactory _factory;
    private String _componentName;
    private ComponentConfigurationPresenter _componentPresenterWidget;
    private String _extensionName;
    private ComponentConfigurationPresenter _extensionPresenterWidget;

    /**
     * Create a new ConfigPresenter.
     *
     * @param eventBus the injected EventBus.
     * @param view the injected MyView.
     * @param proxy the injected MyProxy.
     * @param placeManager the injected PlaceManager.
     * @param revealStrategy the RevealStrategy
     * @param switchYardStore the injected SwitchYardStore.
     * @param factory the PresenterFactory for specialized component presenters.
     */
    @Inject
    public ConfigPresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager,
            RevealStrategy revealStrategy, SwitchYardStore switchYardStore, PresenterFactory factory) {
        super(eventBus, view, proxy);

        _placeManager = placeManager;
        _revealStrategy = revealStrategy;
        _switchYardStore = switchYardStore;
        _factory = factory;
    }

    /**
     * Notifies the presenter that the user wishes to view details about a
     * specific component. The presenter will load the details and pass them
     * back to the view to be displayed.
     *
     * @param component the selected component.
     */
    public void onComponentSelected(Component component) {
        clearComponentContent();

        Builder requestBuilder = new Builder().nameToken(NameTokens.SYSTEM_CONFIG_PRESENTER);
        if (_extensionName != null) {
            requestBuilder.with(NameTokens.EXTENSION_NAME_PARAM, URL.encode(_extensionName));
        }
        if (component != null) {
            requestBuilder.with(NameTokens.COMPONENT_NAME_PARAM, URL.encode(component.getName()));
        }
        _placeManager.revealRelativePlace(requestBuilder.build(), -1);
    }

    /**
     * Notifies the presenter that the user wishes to view details about a
     * specific extension. The presenter will load the details and pass them
     * back to the view to be displayed.
     *
     * @param extension the selected extension.
     */
    public void onExtensionSelected(Component extension) {
        clearExtensionContent();

        Builder requestBuilder = new Builder().nameToken(NameTokens.SYSTEM_CONFIG_PRESENTER);
        if (_componentName != null) {
            requestBuilder.with(NameTokens.COMPONENT_NAME_PARAM, URL.encode(_componentName));
        }
        if (extension != null) {
            requestBuilder.with(NameTokens.EXTENSION_NAME_PARAM, URL.encode(extension.getName()));
        }
        _placeManager.revealRelativePlace(requestBuilder.build(), -1);
    }

    @Override
    protected void onBind() {
        super.onBind();
        getView().setPresenter(this);
    }

    @Override
    public void prepareFromRequest(PlaceRequest request) {
        super.prepareFromRequest(request);
        _componentName = request.getParameter(NameTokens.COMPONENT_NAME_PARAM, null);
        if (_componentName != null) {
            _componentName = URL.decode(_componentName);
        }
        _extensionName = request.getParameter(NameTokens.EXTENSION_NAME_PARAM, null);
        if (_extensionName != null) {
            _extensionName = URL.decode(_extensionName);
        }
    }

    @Override
    protected void onReveal() {
        super.onReveal();
        Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
            @Override
            public void execute() {
                fireEvent(new LHSHighlightEvent("unused", NameTokens.SYSTEM_CONFIG_TEXT, //$NON-NLS-1$
                        NameTokens.SUBSYSTEM_TREE_CATEGORY));
            }
        });
    }

    @Override
    protected void onReset() {
        super.onReset();

        loadSystemDetails();
        loadComponentsList();
        loadComponent();
        loadExtensionsList();
        loadExtension();
    }

    @Override
    protected void onHide() {
        super.onHide();
        clearComponentContent();
        clearExtensionContent();
    }

    @Override
    protected void revealInParent() {
        _revealStrategy.revealInParent(this);
    }

    private void loadSystemDetails() {
        _switchYardStore.loadSystemDetails(new AsyncCallback<SystemDetails>() {

            @Override
            public void onSuccess(SystemDetails systemDetails) {
                getView().setSystemDetails(systemDetails);
            }

            @Override
            public void onFailure(Throwable caught) {
                Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage());
            }
        });
    }

    private void loadComponentsList() {
        _switchYardStore.loadComponents(new AsyncCallback<List<Component>>() {
            @Override
            public void onSuccess(List<Component> components) {
                getView().setComponents(components);
            }

            @Override
            public void onFailure(Throwable caught) {
                Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage());
            }
        });
    }

    private void loadComponent() {
        if (_componentName == null) {
            clearComponentContent();
            return;
        }
        _switchYardStore.loadComponent(_componentName, new AsyncCallback<Component>() {
            @Override
            public void onSuccess(Component component) {
                _componentPresenterWidget = _factory.create(component.getName());
                _componentPresenterWidget.bind();
                setInSlot(TYPE_COMPONENT_CONTENT, _componentPresenterWidget, false);
                _componentPresenterWidget.setComponent(component);
            }

            @Override
            public void onFailure(Throwable caught) {
                Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage());
            }
        });
    }

    private void clearComponentContent() {
        clearSlot(TYPE_COMPONENT_CONTENT);
        releaseComponentPresenterWidget();
    }

    private void releaseComponentPresenterWidget() {
        if (_componentPresenterWidget == null) {
            return;
        }
        _componentPresenterWidget.unbind();
        _componentPresenterWidget = null;
    }

    private void loadExtensionsList() {
        _switchYardStore.loadExtensions(new AsyncCallback<List<Component>>() {
            @Override
            public void onSuccess(List<Component> extensions) {
                getView().setExtensions(extensions);
            }

            @Override
            public void onFailure(Throwable caught) {
                Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage());
            }
        });
    }

    private void loadExtension() {
        if (_extensionName == null) {
            clearExtensionContent();
            return;
        }
        _switchYardStore.loadExtension(_extensionName, new AsyncCallback<Component>() {
            @Override
            public void onSuccess(Component extension) {
                _extensionPresenterWidget = _factory.create(extension.getName());
                _extensionPresenterWidget.bind();
                setInSlot(TYPE_EXTENSION_CONTENT, _extensionPresenterWidget, false);
                _extensionPresenterWidget.setComponent(extension);
            }

            @Override
            public void onFailure(Throwable caught) {
                Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage());
            }
        });
    }

    private void clearExtensionContent() {
        clearSlot(TYPE_EXTENSION_CONTENT);
        releaseExtensionPresenterWidget();
    }

    private void releaseExtensionPresenterWidget() {
        if (_extensionPresenterWidget == null) {
            return;
        }
        _extensionPresenterWidget.unbind();
        _extensionPresenterWidget = null;
    }

}


text:
name: Problem with a resource
about: If you have a problem, bug, or enhancement with a resource in this resource module.
---
<!--
    Your feedback and support is greatly appreciated, thanks for contributing!

    ISSUE TITLE:
    Please prefix the issue title with the resource name, e.g.
    'ResourceName: Short description of my issue'

    ISSUE DESCRIPTION (this template):
    Please provide information regarding your issue under each header below.
    Write N/A under any headers that do not apply to your issue, or if the
    information is not available.

    NOTE! Sensitive information should be obfuscated.

    PLEASE KEEP THE HEADERS.

    You may remove this comment block, and the other comment blocks,
    but please keep the headers.
-->
#### Details of the scenario you tried and the problem that is occurring

#### Verbose logs showing the problem

#### Suggested solution to the issue

#### The DSC configuration that is used to reproduce the issue (as detailed as possible)
```powershell
# insert configuration here
```

#### Exchange Server edition and version the target node is running

#### The operating system the target node is running
<!--
    Please provide as much as possible about the target node, for example
    edition, version, build and language.
    On OS with WMF 5.1 the following command can help get this information.

    Get-ComputerInfo -Property @(
        'OsName',
        'OsOperatingSystemSKU',
        'OSArchitecture',
        'WindowsVersion',
        'WindowsBuildLabEx',
        'OsLanguage',
        'OsMuiLanguages')
-->

#### Version and build of PowerShell the target node is running
<!--
    To help with this information, please run this command:
    $PSVersionTable
-->

#### Version of the DSC module that was used ('dev' if using current dev branch)
<!--
    To help with this information, please run this command:
    Get-Module -Name 'xExchange' -ListAvailable | ft Name,Version,Path
-->


text:
import itertools
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import math

particles = []
n_particles = None
dims = None

min_particle = -1*float("inf")
max_particle =float("inf")

labels = np.fromfile('../train-labels.idx1-ubyte', dtype=np.uint8)
labels = labels[8:].astype(np.int32)

with open('../build/dump_ys.txt') as f:
    line = f.readline().split()
    n_particles = int(line[0])
    dims = float(line[1])
    line = f.readline()
    while line:
        particles.append([float(pos) for pos in line.split()])
        line = f.readline()

particles = np.array(particles)

print(particles.shape)
particles = particles.reshape((-1, n_particles, 2))
print(particles.shape)
n_timesteps = particles.shape[0]

min_particle = np.amin(particles)
max_particle = np.amax(particles)

print(particles[0].shape)
print(particles[0,:,0].shape)

fig, ax = plt.subplots()
mat = ax.scatter(particles[-1,:,0], particles[-1,:,0], s=0.6,c=labels,cmap='tab10')

# def animate(i):
#     i = i % n_timesteps
#     mat.set_offsets(particles[i])
#     return mat,

ax = plt.axis([min_particle, max_particle, min_particle, max_particle])
# ani = animation.FuncAnimation(fig, animate, interval=1)
# ani.save('animation.gif', writer='imagemagick', fps=50)
plt.show()


text:
package network

import (
	"fmt"
	"github.com/dotcloud/docker/pkg/libcontainer"
	"github.com/dotcloud/docker/pkg/libcontainer/utils"
)

// Veth is a network strategy that uses a bridge and creates
// a veth pair, one that stays outside on the host and the other
// is placed inside the container's namespace
type Veth struct {
}

const defaultDevice = "eth0"

func (v *Veth) Create(n *libcontainer.Network, nspid int, context libcontainer.Context) error {
	var (
		bridge string
		prefix string
		exists bool
	)
	if bridge, exists = n.Context["bridge"]; !exists {
		return fmt.Errorf("bridge does not exist in network context")
	}
	if prefix, exists = n.Context["prefix"]; !exists {
		return fmt.Errorf("veth prefix does not exist in network context")
	}
	name1, name2, err := createVethPair(prefix)
	if err != nil {
		return err
	}
	context["veth-host"] = name1
	context["veth-child"] = name2
	if err := SetInterfaceMaster(name1, bridge); err != nil {
		return err
	}
	if err := SetMtu(name1, n.Mtu); err != nil {
		return err
	}
	if err := InterfaceUp(name1); err != nil {
		return err
	}
	if err := SetInterfaceInNamespacePid(name2, nspid); err != nil {
		return err
	}
	return nil
}

func (v *Veth) Initialize(config *libcontainer.Network, context libcontainer.Context) error {
	var (
		vethChild string
		exists    bool
	)
	if vethChild, exists = context["veth-child"]; !exists {
		return fmt.Errorf("vethChild does not exist in network context")
	}
	if err := InterfaceDown(vethChild); err != nil {
		return fmt.Errorf("interface down %s %s", vethChild, err)
	}
	if err := ChangeInterfaceName(vethChild, defaultDevice); err != nil {
		return fmt.Errorf("change %s to %s %s", vethChild, defaultDevice, err)
	}
	if err := SetInterfaceIp(defaultDevice, config.Address); err != nil {
		return fmt.Errorf("set %s ip %s", defaultDevice, err)
	}
	if err := SetMtu(defaultDevice, config.Mtu); err != nil {
		return fmt.Errorf("set %s mtu to %d %s", defaultDevice, config.Mtu, err)
	}
	if err := InterfaceUp(defaultDevice); err != nil {
		return fmt.Errorf("%s up %s", defaultDevice, err)
	}
	if config.Gateway != "" {
		if err := SetDefaultGateway(config.Gateway, defaultDevice); err != nil {
			return fmt.Errorf("set gateway to %s on device %s failed with %s", config.Gateway, defaultDevice, err)
		}
	}
	return nil
}

// createVethPair will automatically generage two random names for
// the veth pair and ensure that they have been created
func createVethPair(prefix string) (name1 string, name2 string, err error) {
	name1, err = utils.GenerateRandomName(prefix, 4)
	if err != nil {
		return
	}
	name2, err = utils.GenerateRandomName(prefix, 4)
	if err != nil {
		return
	}
	if err = CreateVethPair(name1, name2); err != nil {
		return
	}
	return
}


text:
var MongoOplog = require('mongo-oplog');
var _ = require('lodash');

var TICK_INTERVAL = 1000 * 60 * 5;
var OPLOG_WARN_THRESHOLD = 1000 * 5;
var OplogListener = function (mongodb, namespaceFilter) {
  var self = this;
  this._mongodb = mongodb;
  var mongodbOplog = mongodb.db('local');
  this._options = {};
  if (namespaceFilter) {
    this._options.ns = namespaceFilter;
  }
  this._oplog = MongoOplog(mongodbOplog, this._options);
  this._oplog.on('error', self._onError.bind(self));
  setInterval(function () {
    self.tick(namespaceFilter)
  }, TICK_INTERVAL);
  this._isTailing = false;
  this._listeners = []
  this._logThrottled = _.throttle(console.log, 1000 * 10);
};

OplogListener.prototype.tick = function (namespaceFilter) {
  console.log('[mongo-oplog] - TICK - ' + this._listeners.length + ' listeners for namespace: ' + namespaceFilter);
};

OplogListener.prototype._onError = function (err) {
  console.log('Error in oplog listener', _.get(err, 'message'));
  var self = this;
  var retryTimeout = 1000 + Math.floor(Math.random() * 250);
  setTimeout(function () {
    var mongodbOplog = self._mongodb.db('local');
    self._oplog = MongoOplog(mongodbOplog, self._options);
    self._oplog.on('error', self._onError.bind(self));
    self._isTailing = false;
    self.start().then(function () {
      console.log('[mongo-oplog] - Reconnected. Restoring ' + self._listeners.length + ' listeners');
    })
  }, retryTimeout);
};

OplogListener.prototype.start = function () {
  if (!this._isTailing) {
    console.log('[mongo-oplog] - connecting to oplog stream');
    this._isTailing = true;
    var self = this;
    return this._oplog.tail().then(function (stream) {
      if (stream) {
        console.log('[mongo-oplog] - connected to oplog stream');
        self._oplog.on('op', self.onOperation.bind(self));
      }
    });
  }
  return Promise.resolve();
};

OplogListener.prototype.onOperation = function (doc) {
  var opNotified = new Date().getTime();
  var self = this;
  try {
    var opTs = doc.ts.getHighBits() * 1000
    var oplogDiff = opNotified - opTs;
    if (oplogDiff > OPLOG_WARN_THRESHOLD) {
      self._logThrottled('[mongo-oplog] - WARN: got notified of operation with a delay of ' + oplogDiff + 'ms')
    }
  } catch (ignored) {}

  var listeners = _.filter(this._listeners, { namespace: doc.ns })
  if (_.isEmpty(listeners)) {
    return;
  }
  if (!_.has(doc, 'o.$set')) { // no need to resolve - doc already there
    _.forEach(listeners, function (listener) {
      listener.onOperation.call(listener.context, doc);
    });
  } else { // need to resolve document before notifying listeners
    var id = doc.o2._id;
    var observer = listeners[0].context;
    observer._collection.find({ _id: id }).toArray(function (err, results) {
      var resolvedSetDiff = new Date().getTime() - opNotified;
      if (resolvedSetDiff > OPLOG_WARN_THRESHOLD) {
        self._logThrottled('[mongo-oplog] - WARN: took ' + resolvedSetDiff + 'ms to resolve the document for oplog event')
      }
      if (err || !results[0]) {
        console.log('ERROR.. TODO - IMPLEMENT RETRY ?', err);
      } else {
        var res = results[0];
        _.forEach(listeners, function (listener) {
          listener.onOperation.call(listener.context, { op: doc.op, o: res });
        });
      }
      var finishedDiff = new Date().getTime() - opNotified;
      if (finishedDiff > OPLOG_WARN_THRESHOLD) {
        self._logThrottled('[mongo-oplog] - WARN: took ' + finishedDiff + 'ms to finish notifying oplog event')
      }
    });
  }
};

OplogListener.prototype.listen = function (namespace, onOperation, context) {
  var self = this;
  var listenerId = '_' + Math.random().toString(36).substr(2, 9);
  this.start().then(function () {
    self._listeners.push({ listenerId: listenerId, namespace: namespace, onOperation: onOperation, context: context })
  });
  return {
    dispose: function () {
      _.remove(self._listeners, { listenerId: listenerId })
    }
  }
};

module.exports = OplogListener;


text:
import sys
if len(sys.argv)>1: mode = sys.argv[1]
else: mode = 'both'

import elasticite as el

e = el.EdgeGrid(mode=mode)
el.main(e)


text:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');

const index = require('./server/routes/index');

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);

// catch 404 and forward to error handler
app.use((req, res, next) => {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.send(err);
});

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

module.exports = app;


text:
'use strict';

const licenseChecker = require('license-checker');

const check = (cwd, productionOnly) => {
  return new Promise((resolve, reject) => {
    licenseChecker.init(
      { start: cwd, production: productionOnly },
      (error, json) => {
        if (error) {
          reject(error);
        } else {
          resolve(
            Object.keys(json).map((j) => {
              json[j].dependency = j;
              return {
                dependency: json[j].dependency,
                licenses: json[j].licenses,
                file: json[j].licenseFile
              };
            })
          );
        }
      }
    );
  });
};

module.exports = {
  check
};


text:
using Flurl;
using Flurl.Http;
using Flurl.Http.Content;
using System.Net.Http;
using System.Threading.Tasks;

namespace Bot.Common
{
	public static class FlurlExtensions
	{
		public static Task<HttpResponseMessage> PostJsonStringAsync(this Url url, string jsonContent)
		{
			return url.SendAsync(HttpMethod.Post, new CapturedJsonContent(jsonContent));
		}
	}
}


text:
package edu.wfu.inotado.marshalobj.sc;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="course_id" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="created_at" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="display_order" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="document_id" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="updated_at" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "course_id",
    "created_at",
    "display_order",
    "document_id",
    "id",
    "updated_at"
})
@XmlRootElement(name = "CourseDocument")
public class ScCourseDocument {

    protected int course_id;
    @XmlElement(required = true)
    protected String created_at;
    protected int display_order;
    protected int document_id;
    protected int id;
    @XmlElement(required = true)
    protected String updated_at;

    /**
     * Gets the value of the course_id property.
     *
     */
    public int getcourse_id() {
        return course_id;
    }

    /**
     * Sets the value of the course_id property.
     *
     */
    public void setcourse_id(int value) {
        this.course_id = value;
    }

    /**
     * Gets the value of the created_at property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getcreated_at() {
        return created_at;
    }

    /**
     * Sets the value of the created_at property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setcreated_at(String value) {
        this.created_at = value;
    }

    /**
     * Gets the value of the display_order property.
     *
     */
    public int getdisplay_order() {
        return display_order;
    }

    /**
     * Sets the value of the display_order property.
     *
     */
    public void setdisplay_order(int value) {
        this.display_order = value;
    }

    /**
     * Gets the value of the document_id property.
     *
     */
    public int getdocument_id() {
        return document_id;
    }

    /**
     * Sets the value of the document_id property.
     *
     */
    public void setdocument_id(int value) {
        this.document_id = value;
    }

    /**
     * Gets the value of the id property.
     *
     */
    public int getid() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     */
    public void setid(int value) {
        this.id = value;
    }

    /**
     * Gets the value of the updated_at property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getupdated_at() {
        return updated_at;
    }

    /**
     * Sets the value of the updated_at property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setupdated_at(String value) {
        this.updated_at = value;
    }

}


text:
#include "PiSmmCpuDxeSmm.h"

UINT64   mTimeoutTicker = 0;
//
//  Number of counts in a roll-over cycle of the performance counter.
//
UINT64   mCycle = 0;
//
// Flag to indicate the performance counter is count-up or count-down.
//
BOOLEAN  mCountDown;

/**
  Initialize Timer for SMM AP Sync.

**/
VOID
InitializeSmmTimer (
  VOID
  )
{
  UINT64  TimerFrequency;
  UINT64  Start;
  UINT64  End;

  TimerFrequency = GetPerformanceCounterProperties (&Start, &End);
  mTimeoutTicker = DivU64x32 (
                     MultU64x64(TimerFrequency, PcdGet64 (PcdCpuSmmApSyncTimeout)),
                     1000 * 1000
                     );
  if (End < Start) {
    mCountDown = TRUE;
    mCycle = Start - End;
  } else {
    mCountDown = FALSE;
    mCycle = End - Start;
  }
}

/**
  Start Timer for SMM AP Sync.

**/
UINT64
EFIAPI
StartSyncTimer (
  VOID
  )
{
  return GetPerformanceCounter ();
}

/**
  Check if the SMM AP Sync timer is timeout.

  @param Timer  The start timer from the begin.

**/
BOOLEAN
EFIAPI
IsSyncTimerTimeout (
  IN      UINT64                    Timer
  )
{
  UINT64  CurrentTimer;
  UINT64  Delta;

  CurrentTimer = GetPerformanceCounter ();
  //
  // We need to consider the case that CurrentTimer is equal to Timer
  // when some timer runs too slow and CPU runs fast. We think roll over
  // condition does not happen on this case.
  //
  if (mCountDown) {
    //
    // The performance counter counts down.  Check for roll over condition.
    //
    if (CurrentTimer <= Timer) {
      Delta = Timer - CurrentTimer;
    } else {
      //
      // Handle one roll-over.
      //
      Delta = mCycle - (CurrentTimer - Timer) + 1;
    }
  } else {
    //
    // The performance counter counts up.  Check for roll over condition.
    //
    if (CurrentTimer >= Timer) {
      Delta = CurrentTimer - Timer;
    } else {
      //
      // Handle one roll-over.
      //
      Delta = mCycle - (Timer - CurrentTimer) + 1;
    }
  }

  return (BOOLEAN) (Delta >= mTimeoutTicker);
}


text:
package net.novaviper.zeroquest.common.world.biome;

import java.util.Random;

import net.minecraft.block.BlockDoublePlant;
import net.minecraft.entity.monster.EntitySkeleton;
import net.minecraft.entity.monster.EntitySpider;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.passive.EntityChicken;
import net.minecraft.entity.passive.EntityCow;
import net.minecraft.entity.passive.EntityHorse;
import net.minecraft.entity.passive.EntityPig;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.novaviper.zeroquest.ModBlocks;
import net.novaviper.zeroquest.common.entity.creature.EntityRedZertum;
import net.novaviper.zeroquest.common.lib.Constants;

public class BiomeGenRedSeed extends BiomeGenBase {

    public Random par2Random;
    protected boolean field_150628_aC;
    private static final String __OBFID = "CL_00000180";

	public BiomeGenRedSeed(int id) {
        super(id);
       	this.waterColorMultiplier = 0x003333;
        this.theBiomeDecorator.treesPerChunk = -999;
        this.theBiomeDecorator.flowersPerChunk = 4;
        this.theBiomeDecorator.grassPerChunk = 10;
        this.flowers.clear();
        this.addFlower(Blocks.red_flower.getDefaultState(), 4);
        this.addFlower(ModBlocks.nileBlackFlower.getDefaultState(), 90);
        this.spawnableMonsterList.clear();
        this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityHorse.class, 5, 2, 6));
        this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityChicken.class, 5, 1, 5));
        this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityCow.class, 5, 1, 5));
        this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityPig.class, 5, 1, 5));
        this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntitySpider.class, 100, 4, 4));
        this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityZombie.class, 100, 4, 4));
        this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntitySkeleton.class, 100, 4, 4));
    }

    @SideOnly(Side.CLIENT)
    @Override
    public int getModdedBiomeGrassColor(int par1){return 0xB20024;}
    @SideOnly(Side.CLIENT)
    @Override
    public int getModdedBiomeFoliageColor(int par1){return 0xFF0033;}
    @SideOnly(Side.CLIENT)
    @Override
    public int getSkyColorByTemp(float par1){return 0x666600;}

    public void decorate(World worldIn, Random p_180624_2_, BlockPos p_180624_3_)
    {
        double d0 = GRASS_COLOR_NOISE.func_151601_a((double)(p_180624_3_.getX() + 8) / 200.0D, (double)(p_180624_3_.getZ() + 8) / 200.0D);
        int i;
        int j;
        int k;
        int l;

        if (d0 < -0.8D)
        {
            this.theBiomeDecorator.flowersPerChunk = 15;
            this.theBiomeDecorator.grassPerChunk = 5;
        }
        else
        {
            this.theBiomeDecorator.flowersPerChunk = 4;
            this.theBiomeDecorator.grassPerChunk = 10;
            DOUBLE_PLANT_GENERATOR.func_180710_a(BlockDoublePlant.EnumPlantType.GRASS);

            for (i = 0; i < 7; ++i)
            {
                j = p_180624_2_.nextInt(16) + 8;
                k = p_180624_2_.nextInt(16) + 8;
                l = p_180624_2_.nextInt(worldIn.getHeight(p_180624_3_.add(j, 0, k)).getY() + 32);
                DOUBLE_PLANT_GENERATOR.generate(worldIn, p_180624_2_, p_180624_3_.add(j, l, k));
            }
        }

        if (this.field_150628_aC)
        {
            DOUBLE_PLANT_GENERATOR.func_180710_a(BlockDoublePlant.EnumPlantType.SUNFLOWER);

            for (i = 0; i < 10; ++i)
            {
                j = p_180624_2_.nextInt(16) + 8;
                k = p_180624_2_.nextInt(16) + 8;
                l = p_180624_2_.nextInt(worldIn.getHeight(p_180624_3_.add(j, 0, k)).getY() + 32);
                DOUBLE_PLANT_GENERATOR.generate(worldIn, p_180624_2_, p_180624_3_.add(j, l, k));
            }
        }

        super.decorate(worldIn, p_180624_2_, p_180624_3_);
    }

    public BiomeGenBase createMutatedBiome(int p_180277_1_)
    {
    	BiomeGenRedSeed biomegenplains = new BiomeGenRedSeed(p_180277_1_);
        biomegenplains.setBiomeName("Sunflower Plains");
        biomegenplains.field_150628_aC = true;
        biomegenplains.setColor(9286496);
        biomegenplains.field_150609_ah = 14273354;
        return biomegenplains;
    }
}


text:
var App = require('app');

App.AddAlertDefinitionView = Em.View.extend(App.WizardMenuMixin, {

  templateName: require('templates/main/alerts/add_alert_definition/add_alert_definition')

});


text:
<?php

namespace Eloquent\Schemer\Constraint\StringValue;

use Eloquent\Schemer\Constraint\FormatConstraintInterface;
use Eloquent\Schemer\Constraint\Visitor\ConstraintVisitorInterface;

class HostnameFormatConstraint implements FormatConstraintInterface
{
    /**
     * @param ConstraintVisitorInterface $visitor
     *
     * @return mixed
     */
    public function accept(ConstraintVisitorInterface $visitor)
    {
        return $visitor->visitHostnameFormatConstraint($this);
    }
}


text:
package org.synyx.urlaubsverwaltung.application.application;

public class EditApplicationForLeaveNotAllowedException extends RuntimeException {

    EditApplicationForLeaveNotAllowedException(String message) {
        super(message);
    }
}


text:
"""
This module provides helpers for generating the metadata stored in .disk/ on
the cdroot.
"""

import os

def install_disk_info():
    """
    This function creates the .disk/info metadata and installs it into the
    cdroot.
    """

    os.mkdir("cdroot/.disk")
    with open("cdroot/.disk/info", "w") as i:
        i.write("HELLO")


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (c) 2019 The Gulden developers
Authored by: Malcolm MacLeod (mmacleod@gmx.com), Willem de Jonge (willem@isnapp.nl)
Distributed under the GULDEN software license, see the accompanying
file COPYING
!-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clipToPadding="false"
    android:gravity="center_vertical"
    android:orientation="vertical"
    >

    <View
        android:layout_marginBottom="59dp"
        style="@style/ThinHorizontalDivider"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/about_text_app_name" />

    <com.gulden.unity_wallet.ui.widgets.UnityBuildInfoView
        android:id="@+id/textUnityCoreBuild"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/about_text_app_copyright"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="18dp"
        android:orientation="horizontal">

        <Space
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="10" />

        <TextView
            android:id="@+id/textViewSupport"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:onClick="onRequestSupport"
            android:padding="10dp"
            android:text="@string/preferences_support_button"
            android:textColor="@color/colorPrimary" />

        <TextView
            android:id="@+id/textViewAdvancedSettings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:onClick="onRequestAdvancedSettings"
            android:padding="10dp"
            android:text="@string/preferences_advanced_button"
            android:textColor="@color/colorPrimary" />

        <TextView
            android:id="@+id/textViewLicense"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:onClick="onRequestLicense"
            android:padding="10dp"
            android:text="@string/preferences_license_button"
            android:textColor="@color/colorPrimary" />

        <Space
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="10" />
    </LinearLayout>
</LinearLayout>


text:
module Sipity
  # An actor can take the given action
  class WorkflowStateAction < ActiveRecord::Base
    self.table_name = 'sipity_workflow_state_actions'
    belongs_to :originating_workflow_state, class_name: 'Sipity::WorkflowState'
    belongs_to :workflow_action, class_name: 'Sipity::WorkflowAction'
    has_many :workflow_state_action_permissions, dependent: :destroy, class_name: 'Sipity::WorkflowStateActionPermission'
  end
end


text:
function submitAccount() {
	var nameBox = document.getElementById('nickname'),
		balBox = document.getElementById('balance'),
		typeBtns = document.getElementsByName('account-type'),
		name,
		balance,
		type;
	name = nameBox.value;
	balance = balBox.value;
	for (var i = 0, btn; i < typeBtns.length; i++) {
		btn = typeBtns[i];
		if (btn.checked) {
			type = btn.value;
			break;
		}
	}
	console.log('name: ' + name + ', type: ' + type + ', bal: ' + balance);
	// perform ajax post request
	axios.post('/api/Accounts', {nickname: name, accountType: type, balance: balance})
	.then(function(resp) {
		console.log(resp);
	}).catch(function(error) {
		console.log(error);
	});
}

function clearForm() {
	var nameBox = document.getElementById('nickname'),
		balBox = document.getElementById('balance'),
		typeBtns = document.getElementsByName('account-type');
	nameBox.value = '';
	balBox.value = '';
	typeBtns.forEach(function(btn) {
		btn.checked = false;
	});
}


text:
/*
 *  SphereReflection2D.h
 *  emptyExample
 *
 *  Created by Josh Nimoy on 2/19/11.
 *
 */

#pragma once

#include "ofMain.h"

namespace SphereReflection2D{
	class Sphere{
	public:
		Sphere(ofVec3f p,float r,ofColor c);
		ofVec3f pos;
		float radius;
		ofColor color;
		static int reflection_resolution;
		static bool draw_back_reflections;
		static ofVec2f spherize(ofVec2f p,double radius);
		void drawReflection(ofVec3f targetPos, float targetRad,float zOff);
	};
}


text:
<?php

namespace nv\PROJECT_NAME\Model;

/**
 * Class TimestampableInterface
 * @package nv\PROJECT_NAME\Model
 */
interface TimestampableInterface
{
    /**
     * Returns the time the record was last modified.
     *
     * @return \DateTime
     */
    public function getTimeModified();

    /**
     * Sets the time the record was last modified
     *
     * @return mixed
     */
    public function setTimeModified();

    /**
     * Gets the time the record was created
     *
     * @return \DateTime
     */
    public function getTimeCreated();

    /**
     * Sets the time the record was created
     *
     * @return mixed
     */
    public function setTimeCreated();
}


text:
import datetime
import logging

from django.conf import settings
from django.db import connections
from django.db import DEFAULT_DB_ALIAS

from django_transaction_barrier import postgresql
from django_transaction_barrier import sqlite3
from django_transaction_barrier.models import TransactionCommitBarrier

log = logging.getLogger(__name__)

class TransactionAborted(Exception):
  pass

def _db_backend(using):
  engine = settings.DATABASES[using]['ENGINE']
  return {'django.db.backends.postgresql_psycopg2': postgresql,
          'django.db.backends.sqlite3': sqlite3}[engine]

def get_debug_info(barrier=None):
  info = []
  using = DEFAULT_DB_ALIAS
  if barrier:
    using = barrier['using']
    info.append(u'[Barrier %s]' % unicode(barrier))
    commit_barriers = TransactionCommitBarrier.objects.using(using).filter(
        uuid=barrier['uuid'])
    if commit_barriers:
      info.append(u'[TransactionCommitBarrier: %s]' % (
          unicode(commit_barriers[0])))
  cursor = connections[using].cursor()
  info.append(u'[Backend: %s]' % _db_backend(using).get_debug_info(cursor))
  return u','.join(info)

def new_transaction_barrier(using=None):
  """Create a new transaction barrier and return it.

  The barrier implicity supports only 1 waiter. In other words, for a given
  barrier, only one process/thread/task should call poll_transaction_barrier.
  If more than one calls poll_transaction_barrier the semantics are undefined.
  The caller should consider the barrier opaque and specific to DB backend
  type. ``using`` is the Django DB alias to use."""
  using = using or DEFAULT_DB_ALIAS

  # First save a commit barrier.
  commit_barrier = TransactionCommitBarrier()
  commit_barrier.save(using=using)

  # Second get the current transaction metadata (e.g., a Postgres transaction
  # ID). Using the metadata the backend determines if the transaction finishes
  # (either aborts of commits).
  cursor = connections[using].cursor()
  metadata = _db_backend(using).get_transaction_metadata(cursor)

  return dict(uuid=commit_barrier.uuid, metadata=metadata, using=using)

def delete_transaction_barrier(barrier):
  (TransactionCommitBarrier.objects.using(barrier['using'])
   .get(uuid=barrier['uuid']).delete())

def poll_transaction_barrier(barrier):
  """Poll the transaction barrier.

  Return True if the barrier is satisfied, return False if it's still waiting.
  Raise TransactionAborted if the transaction was aborted.
  """
  # Optimistically poll the DB for the TransactionCommitBarrier. If it exists,
  # we know that the transaction is committed successfully.
  if _poll_transaction_commit_barrier(barrier['uuid'], barrier['using']):
    return True

  # If the transaction is finished according to the DB-specific functions,
  # but we can't find the TransactionCommitBarrier, we know the transaction is
  # aborted.
  cursor = connections[barrier['using']].cursor()
  if _db_backend(barrier['using']).is_transaction_complete(
      cursor, barrier['metadata']):
    if _poll_transaction_commit_barrier(barrier['uuid'], barrier['using']):
      return True
    raise TransactionAborted()

  return False

def reap_commit_barriers(age_in_seconds, using=None):
  """Delete all TransactionCommitBarriers older than ``age_in_seconds``.

  If an applications allocates a barrier with new_transaction_barrier, but
  fails to delete it, metadata might linger in the database.
  reap_commit_barriers is a hack to help remove that metadata. ``using`` is
  the Django DB alias to use. ``using_barrier`` is a barrier to extract the
  Django DB alias from (instead of using ``using``).

  If your application uses TransactionBarrierTask and never calls
  new_transaction_barrier directly, you can ignore this function.
  """
  using = using or DEFAULT_DB_ALIAS

  time_threshold = (
      datetime.datetime.now() - datetime.timedelta(seconds=age_in_seconds))
  TransactionCommitBarrier.objects.using(using).filter(
      creation_date__lt=time_threshold).delete()

def _poll_transaction_commit_barrier(uuid, using):
  try:
    TransactionCommitBarrier.objects.using(using).get(uuid=uuid)
    return True
  except TransactionCommitBarrier.DoesNotExist:
    return False


text:
Sign up....

<button class="login-title" (click)="ws.changeView('login')">Go to Login</button>

    <form [ngFormModel]="signupForm" (ngSubmit)="onSubmit(signupForm.value)">
      <input type="email" name="email" placeholder="EMAIL" [ngFormControl]="signupForm.controls['email']">

      <input type="password" name="password" placeholder="PASSWORD" [ngFormControl]="signupForm.controls['password']">

      <input type="password" name="confirm" placeholder="CONFIRM PASSWORD" [ngFormControl]="signupForm.controls['confirm']">

        <input type="submit" value="SIGN UP" class="signup">
        <button type="button" class="cancel" (click)="ws.changeView('welcome')">
          CANCEL
        </button>

    </form>


text:
from robotpy_ext.autonomous import StatefulAutonomous

class SensorStatefulAutonomous(StatefulAutonomous):

    def on_iteration(self, tm):
        self.sensors.update()
        return StatefulAutonomous.on_iteration(self, tm)


text:
<?php
/*
 * This class is used for managing app and its attributes
 *
 * Author: Bismay Kumar Mohapatra bismay4u@gmail.com
 * Version: 1.0
 */
if(!defined('ROOT')) exit('No direct script access allowed');

if(!function_exists("loadLogiksApp")) {

  function loadLogiksApp($appName=SITENAME) {
    if(defined("BASEPATH")) {
      trigger_logikserror("App '".$appName."' has already been activated",E_ERROR);
    }

    define("BASEPATH",APPS_FOLDER . $appName . "/");
    define("APPROOT", ROOT . BASEPATH);
    define("WEBAPPROOT",SiteLocation . BASEPATH);

    if(!file_exists(APPROOT)) {
      trigger_logikserror("Site Not Found '".$appName."'",E_ERROR);
    }

    $apps_cfg=APPROOT."apps.cfg";
    if(!file_exists($apps_cfg)) {
    	trigger_logikserror("Site '".$appName."' Has Not Yet Been Activated (missing apps.cfg).",E_ERROR);
    }
    loadConfigs($apps_cfg,true);

    if(defined("RELINK") && strlen(RELINK)>0) {
      if(substr(RELINK, 0,7)=="http://" || substr(RELINK, 0,8)=="https://") {
        redirectTo(RELINK);
      } else {
        $relink=SiteLocation."?site=".RELINK;
        redirectTo($relink);
      }
    }

    if(defined("APPS_TYPE") && strtolower(APPS_TYPE)=="3rdparty") {
    	$relink=WEBAPPROOT;
    	redirectTo($relink);
    }

    loadConfigDir(APPROOT."config/");

    if(!defined("APPS_CONFIG_FOLDER")) {
      loadConfigs(ROOT."config/masters/folders.cfg");
    }

    if(defined("LINGUALIZER_DICTIONARIES")) Lingualizer::getInstance()->loadLocaleFile(LINGUALIZER_DICTIONARIES);

    if(!defined("APPS_THEME")) define("APPS_THEME",getConfig("APPS_THEME"));
    if(!defined("APPS_TEMPLATEENGINE")) define("APPS_TEMPLATEENGINE",getConfig("APPS_TEMPLATEENGINE"));

    if(!defined("APPNAME")) define("APPNAME",SITENAME);

    return true;
  }

  function loadAppServices($appName=SITENAME) {
    if(defined("BASEPATH")) {
      trigger_logikserror("App '".$appName."' has already been activated",E_ERROR);
    }

    define("BASEPATH",APPS_FOLDER . $appName . "/");
    define("APPROOT", ROOT . BASEPATH);
    define("WEBAPPROOT",SiteLocation . BASEPATH);

    if(!file_exists(APPROOT)) {
      trigger_logikserror("Site Not Found '".$appName."'",E_ERROR);
    }

    $apps_cfg=APPROOT."apps.cfg";
    if(!file_exists($apps_cfg)) {
      trigger_logikserror("Site '".$appName."' Has Not Yet Been Activated (missing apps.cfg).",E_ERROR);
    }
    loadConfigs($apps_cfg);

    loadConfigDir(APPROOT."config/");

    if(!defined("APPS_CONFIG_FOLDER")) {
      loadConfigs(ROOT."config/masters/folders.cfg");
    }

    if(defined("LINGUALIZER_DICTIONARIES")) Lingualizer::getInstance()->loadLocaleFile(LINGUALIZER_DICTIONARIES);

    if(!defined("APPS_THEME")) define("APPS_THEME",getConfig("APPS_THEME"));
    if(!defined("APPS_TEMPLATEENGINE")) define("APPS_TEMPLATEENGINE",getConfig("APPS_TEMPLATEENGINE"));

    if(!defined("APPNAME")) define("APPNAME",SITENAME);

    return true;
  }

  function fetchLogiksAppInfo($appName=SITENAME) {
    $cfgPath=ROOT.APPS_FOLDER . $appName . "/apps.cfg";
    if(file_exists($cfgPath)) return LogiksConfig::parseConfigFile($cfgPath);
    return false;
  }

  function configureAppLinking() {
      if(defined("LINKED_APPS")) {
          $parentApps = explode(",",LINKED_APPS);
          if(getConfig("APPS_STATUS")=="production") {
              foreach($parentApps as $app) {
                  $GLOBALS['pluginPaths'][] = "#ROOT#apps/{$app}/plugins/";
                  $GLOBALS['vendorPath'][] = "#ROOT#apps/{$app}/plugins/";
              }
          } else {
              foreach($parentApps as $app) {
                  $GLOBALS['pluginPaths'][] = "#ROOT#apps/{$app}/plugins/";
                  $GLOBALS['pluginPaths'][] = "#ROOT#apps/{$app}/pluginsDev/";

                  $GLOBALS['vendorPath'][] = "#ROOT#apps/{$app}/plugins/";
                  $GLOBALS['vendorPath'][] = "#ROOT#apps/{$app}/pluginsDev/";
              }
          }

          $GLOBALS['mediaPaths'][] = "#ROOT#apps/{$app}/usermedia/";
          $GLOBALS['mediaPaths'][] = "#ROOT#apps/{$app}/userdata/";
      }
  }
}
?>


text:
package com.stratio.decision.generator;

import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ValuesGenerator {
    private static final Logger log = LoggerFactory.getLogger(ValuesGenerator.class);

    private List<RangeData> ranges;
    private double valueDeviation = 0;

    private double initValue = 0;

    public ValuesGenerator() {
        this.ranges = new LinkedList<>();
    }

    public ValuesGenerator(double initValue) {
        this();
        this.initValue = initValue;
    }

    public List<Double> build() {
        List<Double> values = new ArrayList<>();

        // Iteramos nuestros rangos
        for (RangeData range : ranges) {
            double min;
            double max;
            boolean reverse = false;
            if (initValue > range.getFinalValue()) {
                min = range.getFinalValue();
                max = initValue;
                // reverse result
                reverse = true;
            } else {
                max = range.getFinalValue();
                min = initValue;
            }
            // Lista de numeros
            List<Double> temporalValues = new ArrayList<>();
            for (double i = min; i < max; i++) {
                temporalValues.add(i);
            }
            List<Double> fixedNumberOfValues = new ArrayList<>();
            if (temporalValues.size() != 0) {
                Random r = new Random();
                for (int i = 0; i < range.getAffectedValues(); i++) {
                    Double randomElement = temporalValues.get(r.nextInt(temporalValues.size()));
                    fixedNumberOfValues.add(randomElement);
                }
            }
            Collections.sort(fixedNumberOfValues);
            if (reverse) {
                Collections.reverse(fixedNumberOfValues);
            }
            for (Double value : fixedNumberOfValues) {
                values.add(rand(value - valueDeviation, value + valueDeviation));
            }
            initValue = range.getFinalValue();
        }
        printValues(values);
        return values;
    }

    public ValuesGenerator withDerivation(int derivation) {
        this.valueDeviation = derivation;
        return this;
    }

    public ValuesGenerator withInitValue(double initValue) {
        this.initValue = initValue;
        return this;
    }

    public ValuesGenerator addRange(double finalValue, int affectedValues) {
        ranges.add(new RangeData(finalValue, affectedValues));
        return this;
    }

    private void printValues(List<Double> values) {
        int valuesNumber = values.size();
        int groupValuesSize = valuesNumber / 15;
        int count = 0;
        Double avg = 0d;
        Double o = 50f / Collections.max(values);
        for (Double value : values) {
            avg = avg + value;
            count++;
            if (count == groupValuesSize) {
                for (int i = 0; i < (o * (avg / count)); i++) {
                    log.info("█");
                    //System.out.print("█");
                }
                log.info(" (" + avg / count + ")");
                //System.out.println(" (" + avg / count + ")");
                avg = 0d;
                count = 0;
            }
        }

    }

    private double rand(double min, double max) {

        // Usually this can be a field rather than a method variable
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt(((int) max - (int) min) + 1) + (int) min;

        return (Double.valueOf(randomNum) < 0) ? 0 : Double.valueOf(randomNum);
    }

    private class RangeData {
        private final double finalValue;
        private final int affectedValues;

        public RangeData(double finalValue, int affectedValues) {
            this.finalValue = finalValue;
            this.affectedValues = affectedValues;
        }

        public double getFinalValue() {
            return finalValue;
        }

        public int getAffectedValues() {
            return affectedValues;
        }

    }
}


text:
package com.game.tools.mapeditor.ui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;
import javax.swing.UIManager;

import com.game.tools.mapeditor.SpriteMap;

@SuppressWarnings("serial")
public class SpriteBox extends JComboBox {

	protected static class SpriteBoxRenderer extends JLabel implements ListCellRenderer {
		protected final SpriteBox box;

		public SpriteBoxRenderer(SpriteBox box) {
			this.box = box;

			super.setBackground(Color.BLACK);
			super.setOpaque(true);
			super.setHorizontalAlignment(SwingConstants.CENTER);
			super.setVerticalAlignment(SwingConstants.CENTER);
		}

		@Override
		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
			super.setIcon((ImageIcon) value);
			super.setBorder(isSelected ? BorderFactory.createLineBorder(Color.RED) : null);

			return this;
		}
	}

	// Width needs to account for the scrollbar/dropdown arrow
	public SpriteBox(SpriteMap sprites, boolean addBlank) {
		super.setRenderer(new SpriteBoxRenderer(this));

		// Add a blank image at position 0 - 0 means no sprite
		if (addBlank) {
			BufferedImage blank = new BufferedImage(sprites.elementWidth, sprites.elementHeight, BufferedImage.TYPE_INT_ARGB);
			this.addItem(new ImageIcon(blank));
		}

		for (Image sprite : sprites)
			super.addItem(new ImageIcon(sprite));

		super.setPreferredSize(new Dimension(sprites.elementWidth + 2 + UIManager.getInt("ScrollBar.width"), sprites.elementHeight));
		super.setSelectedIndex(0);
	}
}


text:
<?php echo $question['name']; ?>

<?php
$chartWidth = get_option('wpsqt_chart_width');
$chartHeight = get_option('wpsqt_chart_height');
$chartTextColour = get_option('wpsqt_chart_text_colour');
$chartTextSize = get_option('wpsqt_chart_text_size');
$chartAbbreviations = get_option('wpsqt_chart_abbreviation');
$chartBackgroundColour = get_option('wpsqt_chart_bg');
$chartColour = get_option('wpsqt_chart_colour');
if (!isset($chartWidth) || $chartWidth == NULL)
	$chartWidth = 400;
if (!isset($chartHeight) || $chartHeight == NULL)
	$chartHeight = 185;
if (!isset($chartTextColour) || $chartTextColour == NULL)
	$chartTextColour = '000000';
if (!isset($chartTextSize) || $chartTextSize == NULL)
	$chartTextSize = 13;
if (!isset($chartBackgroundColour) || $chartBackgroundColour == NULL)
	$chartBackgroundColour='FFFFFF';
if (!isset($chartColour) || $chartColour == NULL)
	$chartColour='FF0000';
$chartSize = 'chs='.$chartWidth.'x'.$chartHeight;
//$googleChartUrl = 'http://chart.apis.google.com/chart?cht=bvs&'.$chartSize.'&chxs=0,'.$chartTextColour.','.$chartTextSize.',0,lt,'.$chartTextColour.'|1,'.$chartTextColour.','.$chartTextSize.',1,lt,'.$chartTextColour.'&cht=p&chf=bg,s,'.get_option("wpsqt_chart_bg").'&chco='.get_option("wpsqt_chart_colour");
$googleChartUrl = 'http://chart.apis.google.com/chart?cht=bvs&'.$chartSize.'&chxs=0,'.$chartTextColour.','.$chartTextSize.',0,lt,'.$chartTextColour.'|1,'.$chartTextColour.','.$chartTextSize.',1,lt,'.$chartTextColour.'&chf=bg,'.$chartBackgroundColour.'&chco='.$chartColour;
if ( $question['type'] == "Multiple Choice" ||
   	$question['type'] == "Dropdown" ) {
	//$googleChartUrl = 'http://chart.apis.google.com/chart?chs=400x185&cht=p';
	$valueArray    = array();
	$nameArray     = array();
	foreach ( $question['answers'] as $answer ) {
   		$nameArray[] = $answer['text'];
		$valueArray[] = $answer['count'];
   	}

	$googleChartUrl .= '&chd=t:'.implode(',', $valueArray);
	$googleChartUrl .= '&chl='.implode('|',$nameArray);
?>

	<img src="<?php echo $googleChartUrl; ?>" alt="<?php echo $question['name']; ?>" />
<?php

} else if ($question['type'] == "Free Text") {

	$i = 1; // Variable used to count answers - used later

	?> All answers for this question <?php

	foreach($uncachedresults as $uresult) {
		$usection = unserialize($uresult['sections']);

		foreach($usection as $result) {

			foreach($result['answers'] as $uanswerkey => $uanswer) {
				if($uanswerkey == $questonKey && in_array($uanswerkey, $freetextq)) {
					echo '
'.$i.') '.$uanswer['given'][0].'
';
					$i++;
				}

			}
		}

	}
} else if ($question['type'] == "Likert") {
	//$googleChartUrl = 'http://chart.apis.google.com/chart?&cht=bvs';
	$valueArray    = array();
	$nameArray     = array();
	$maxValue = 0;
	$numAnswers = count($question['answers']);

	// Populates data array
	foreach ( $question['answers'] as $key => $answer ) {
		$nameArray[] = $key;
		$valueArray[] = $answer['count'];
		// Gets the maximum value
		if ($answer['count'] > $maxValue)
			$maxValue = $answer['count'];
	}
	// Makes chart wider if its an agree/disagree question
	if (array_key_exists('Disagree', $question['answers'])) {
		$googleChartUrl .= '&chbh=r,70,10';
		$googleChartUrl .= '&chxt=x&chxl=0:|Strongly Disagree|Disagree|No Opinion|Agree|Strongly Agree'; // Sets labelling to x-axis only
	} else {
		//$googleChartUrl .= '&chs=350x250';
		$googleChartUrl .= '&chxt=x&chxl=0:|'.implode('|', $nameArray); // Sets labelling to x-axis only
	}
	$googleChartUrl .= '&chm=N,000000,0,,10|N,000000,1,,10|N,000000,2,,10'; // Adds the count above bars
	$googleChartUrl .= '&chds=0,'.(++$maxValue); // Sets scaling to a little bit more than max value
	$googleChartUrl .= '&chd=t:'.implode(',', $valueArray); // Chart data
?>
	<img src="<?php echo $googleChartUrl; ?>" alt="<?php echo $question['name']; ?>" />
<?php
} else if ($question['type'] == "Likert Matrix") {
  		if (isset($question['scale']) && $question['scale'] == 'disagree/agree') {
  			$wordScale = true;
  		} else {
  			$wordScale = false;
		}

		// Remove the 'other' answers if it isn't allowed
		$questionMeta = $wpdb->get_row('SELECT meta FROM '.WPSQT_TABLE_QUESTIONS.' WHERE id = "'.$questonKey.'"', ARRAY_A);
		$questionMeta = unserialize($questionMeta['meta']);
		if ($questionMeta['likertmatrixcustom'] == 'no'){
			unset($question['answers']['other']);
		}

  		foreach($question['answers'] as $optionkey => $matrixOption) {
  			$gcUrl = $googleChartUrl;
  			//$googleChartUrl = 'http://chart.apis.google.com/chart?&cht=bvs';
			$valueArray    = array();
			$nameArray     = array();
			$maxValue = 0;
			$numAnswers = count($question['answers']);

			foreach ($matrixOption as $key => $answer) {
				$nameArray[] = $key;
				$valueArray[] = $answer['count'];
				// Gets the maximum value
				if ($answer['count'] > $maxValue)
					$maxValue = $answer['count'];
			}

			//$googleChartUrl .= '&chs=350x250';

			if (isset($wordScale) && $wordScale == true) {
				$gcUrl .= '&chxt=x&chxl=0:|Strongly Disagree|Disagree|No Opinion|Agree|Strongly Agree'; // Sets labelling to x-axis only and labels with numbers
				$gcUrl .= '&chbh=r,70,10'; // Makes chart wider
			} else {
				$gcUrl .= '&chxt=x&chxl=0:|'.implode('|', $nameArray); // Sets labelling to x-axis only and labels with numbers
			}
			$gcUrl .= '&chm=N,000000,0,,10|N,000000,1,,10|N,000000,2,,10'; // Adds the count above bars
			$gcUrl .= '&chds=0,'.(++$maxValue); // Sets scaling to a little bit more than max value
			$gcUrl .= '&chd=t:'.implode(',', $valueArray); // Chart data

			echo '
'.$optionkey.'
';
			?><img src="<?php echo $gcUrl; ?>" alt="<?php echo $question['name']; ?>" /><?php
  		}
  } else {
		echo 'Something went really wrong, please report this bug to the GitHub Issues page. Here\'s a var dump which might make you feel better.
'; var_dump($question); echo '
';
  }
?>


text:
package shabingasplayground.world;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import shabingasplayground.block.BlockAir;
import shabingasplayground.block.BlockDirt;
import shabingasplayground.block.BlockGrass;
import shabingasplayground.gui.GameFrame;
import shabingasplayground.settings.Settings;
import shabingasplayground.world.block.BlockLayer;
import shabingasplayground.world.sprite.SpriteLayer;

public class World {
	private BlockLayer blockLayer;
	private SpriteLayer spriteLayer;
	public World(String fileLocation){
		blockLayer = new BlockLayer();
		try {
			BufferedImage img = ImageIO.read(new File(fileLocation));
			for(int r = 0; r < Settings.worldHeight; r++){
				for(int c = 0; c < Settings.worldWidth; c++){
					if(img.getRGB(c,r) ==-10960640){ //green
						blockLayer.setEntityAt(r,c, new BlockGrass());
					}else if(img.getRGB(c,r) == -16777216){ //black
						blockLayer.setEntityAt(r,c, new BlockAir());
					}else if(img.getRGB(c,r) == -65536){ //red
						blockLayer.setEntityAt(r,c, new BlockDirt());
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		spriteLayer = new SpriteLayer(blockLayer);

		 JFrame ex = new GameFrame(spriteLayer);
         ex.setVisible(true);
	}
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>CS171 - HW 6</title>

	<link rel="stylesheet" href="css/bootstrap.min.css">
	<link rel="stylesheet" href="css/font-awesome.min.css">
	<link rel="stylesheet" href="css/style.css">
	<link rel="stylesheet" href="css/colorbrewer.css">
	<link href='https://fonts.googleapis.com/css?family=Lato:400,300,400italic,700' rel='stylesheet' type='text/css'>

Global Fight Against Malaria in Africa

Malaria is both preventable and curable

What is Malaria?

Malaria is caused by the Plasmodium parasite and is transmitted by female Anopheles mosquitoes which bite between dusk and dawn.

Symptoms: People infected with malaria often experience fever, chills and flu-like illness at first.

Who's at risk: Young children, pregnant women and non-immune travellers from malaria-free areas are highly vulnerable.

The Numbers: Roughly 3.2 billion people are at risk of Malaria, with 214 million cases reported in 2015.

Malaria between 2000 & 2015

Globally reported cases of malaria declined between 2000 & 2015

37% decline in malaria cases

60% decline in global malaria mortality rates

Reported Cases

Funding

Toal Funding (ann.)

					<select class="form-control" id="request-type">
						<option value="Malaria_cases">Recorded Malaria Cases</option>
						<option value="Suspected_malaria_cases">Suspected Malaria Cases</option>
						<option value="At_risk">At Risk</option>
						<option value="At_high_risk">At High Risk</option>
					</select>


text:
import setuptools
import sys

from mungerator import info

REQUIRES = ['PyChef==0.2.2']

if sys.version_info < (2, 6, 0):
    sys.stderr.write("The Mungerator requires Python 2.6.0 or greater \n")
    raise SystemExit(
        '\nUpgrade python because you version of it is VERY deprecated\n'
    )
elif sys.version_info < (2, 7, 0):
    REQUIRES.append('argparse')

with open('README', 'rb') as r_file:
    LDINFO = r_file.read()

setuptools.setup(
    name=info.__appname__,
    version=info.__version__,
    author=info.__author__,
    author_email=info.__email__,
    description=info.__description__,
    long_description=LDINFO,
    license=info.__license__,
    packages=['mungerator',
              'mungerator.arguments',
              'mungerator.methods'],
    url=info.__url__,
    install_requires=REQUIRES,
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Information Technology',
        'Intended Audience :: System Administrators',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Utilities',
        'Topic :: Software Development :: Libraries :: Python Modules'],
    entry_points={
        "console_scripts": ["mungerator = mungerator.executable:execute"]}
)


text:
<?php
include "header-main.php";
?>

<?php
if(isset($_REQUEST['submit']))
{
	$email=$_REQUEST['email'];

	$equery="select * from emp_master where short_id='$email'";
	$eresult=mysql_query($equery);
	if(mysql_num_rows($eresult)==0)
	{
		echo "
No user with this userid! Go back and try again";
	}
	else
	{
		function generatePassword($length=8,$level=3)
		{
			list($usec, $sec) = explode(' ', microtime());
			srand((float) $sec + ((float) $usec * 100000));

			$validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
			$validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
			$validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/";

			$password  = "";
			$counter   = 0;

			while ($counter < $length)
			{
				$actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);
				// All character must be different
				if (!strstr($password, $actChar))
				{
					$password .= $actChar;
					$counter++;
				}
	   		}
			return $password;
		}
		$pass=generatePassword();
		$hpass=md5($pass);
		$uquery="update emp_master set password='$hpass' where short_id='$email'";
		$uresult=mysql_query($uquery);
		$headers = 'From: Idea Generation Tool <idea@coin.csc.com>'."\r\n".'Reply-To: jjanarthanan@csc.com';
		$subject="Idea Generation Tool: Password Reset";
		$to=$email;
		//$to="kboovaragan@csc.com";
		$name_query="select name from emp_master where short_id='$email'";
		$name_result=mysql_query($name_query) or die ("Could not execute query ($name_query) because ".mysql_error());
		$name_row=mysql_fetch_array($name_result);
		$name=$name_row['name'];
		$message="Dear $name,\n\nThis is is to notify that your password has been reset to: \"$pass\".\n\nRegards,\nThe Idea Generation Team.";
		mail($to, $subject, $message, $headers);
		echo "
Your password has been reset and emailed to you. Go to Home";
	}
}
else
{
	?>
	<form name="forgot-password" method="post" action="forgot-password.php" onsubmit="return checkform(this)">

Forgot Password

Enter User ID (Email)	<input type="text" name="email" size="32">

<input type="submit" name="submit" value="Submit">

	</form>

<?php
}
include "footer.php";
?>


text:
module Lotus
  module Routing
    class Resource
      # Helper class to calculate nested path
      #
      # @api private
      # @since 0.4.0
      class Nested
        # @api private
        # @since 0.4.0
        SEPARATOR = '/'.freeze

        # @api private
        # @since 0.4.0
        def initialize(resource_name, resource)
          @resource_name = resource_name.to_s.split(SEPARATOR)
          @resource      = resource
          @path          = []
          _calculate(@resource_name.dup, @resource)
        end

        # @api private
        # @since 0.4.0
        def to_path
          @path.reverse!.pop
          @resource_name.zip(@path).flatten.join
        end

        private

        def _calculate(param_wildcard, resource = nil)
          return if resource.nil?
          @path << resource.wildcard_param(param_wildcard.pop)
          _calculate(param_wildcard, resource.parent)
        end
      end
    end
  end
end


text:
package com.sri.ai.praise.other.application.praise.app.model;

import com.google.common.annotations.Beta;

@Beta
public class EarthquakeBurglaryAlarm extends ExamplePages {

	public EarthquakeBurglaryAlarm() {
		super("Earthquake/Burglary/Alarm",
			   getExamplePagesFromResource("earthquakeBurglaryAlarm.praise"));
	}
}