language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class AssetFunction extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.AssetFunction;
if (null == bucket)
cim_data.AssetFunction = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.AssetFunction[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "AssetFunction";
base.parse_element (/<cim:AssetFunction.configID>([\s\S]*?)<\/cim:AssetFunction.configID>/g, obj, "configID", base.to_string, sub, context);
base.parse_element (/<cim:AssetFunction.firmwareID>([\s\S]*?)<\/cim:AssetFunction.firmwareID>/g, obj, "firmwareID", base.to_string, sub, context);
base.parse_element (/<cim:AssetFunction.hardwareID>([\s\S]*?)<\/cim:AssetFunction.hardwareID>/g, obj, "hardwareID", base.to_string, sub, context);
base.parse_element (/<cim:AssetFunction.password>([\s\S]*?)<\/cim:AssetFunction.password>/g, obj, "password", base.to_string, sub, context);
base.parse_element (/<cim:AssetFunction.programID>([\s\S]*?)<\/cim:AssetFunction.programID>/g, obj, "programID", base.to_string, sub, context);
base.parse_attribute (/<cim:AssetFunction.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context);
let bucket = context.parsed.AssetFunction;
if (null == bucket)
context.parsed.AssetFunction = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "AssetFunction", "configID", "configID", base.from_string, fields);
base.export_element (obj, "AssetFunction", "firmwareID", "firmwareID", base.from_string, fields);
base.export_element (obj, "AssetFunction", "hardwareID", "hardwareID", base.from_string, fields);
base.export_element (obj, "AssetFunction", "password", "password", base.from_string, fields);
base.export_element (obj, "AssetFunction", "programID", "programID", base.from_string, fields);
base.export_attribute (obj, "AssetFunction", "Asset", "Asset", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetFunction_collapse" aria-expanded="true" aria-controls="AssetFunction_collapse" style="margin-left: 10px;">AssetFunction</a></legend>
<div id="AssetFunction_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#configID}}<div><b>configID</b>: {{configID}}</div>{{/configID}}
{{#firmwareID}}<div><b>firmwareID</b>: {{firmwareID}}</div>{{/firmwareID}}
{{#hardwareID}}<div><b>hardwareID</b>: {{hardwareID}}</div>{{/hardwareID}}
{{#password}}<div><b>password</b>: {{password}}</div>{{/password}}
{{#programID}}<div><b>programID</b>: {{programID}}</div>{{/programID}}
{{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Asset}}");}); return false;'>{{Asset}}</a></div>{{/Asset}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetFunction_collapse" aria-expanded="true" aria-controls="{{id}}_AssetFunction_collapse" style="margin-left: 10px;">AssetFunction</a></legend>
<div id="{{id}}_AssetFunction_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_configID'>configID: </label><div class='col-sm-8'><input id='{{id}}_configID' class='form-control' type='text'{{#configID}} value='{{configID}}'{{/configID}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_firmwareID'>firmwareID: </label><div class='col-sm-8'><input id='{{id}}_firmwareID' class='form-control' type='text'{{#firmwareID}} value='{{firmwareID}}'{{/firmwareID}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_hardwareID'>hardwareID: </label><div class='col-sm-8'><input id='{{id}}_hardwareID' class='form-control' type='text'{{#hardwareID}} value='{{hardwareID}}'{{/hardwareID}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_password'>password: </label><div class='col-sm-8'><input id='{{id}}_password' class='form-control' type='text'{{#password}} value='{{password}}'{{/password}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_programID'>programID: </label><div class='col-sm-8'><input id='{{id}}_programID' class='form-control' type='text'{{#programID}} value='{{programID}}'{{/programID}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Asset'>Asset: </label><div class='col-sm-8'><input id='{{id}}_Asset' class='form-control' type='text'{{#Asset}} value='{{Asset}}'{{/Asset}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "AssetFunction" };
super.submit (id, obj);
temp = document.getElementById (id + "_configID").value; if ("" !== temp) obj["configID"] = temp;
temp = document.getElementById (id + "_firmwareID").value; if ("" !== temp) obj["firmwareID"] = temp;
temp = document.getElementById (id + "_hardwareID").value; if ("" !== temp) obj["hardwareID"] = temp;
temp = document.getElementById (id + "_password").value; if ("" !== temp) obj["password"] = temp;
temp = document.getElementById (id + "_programID").value; if ("" !== temp) obj["programID"] = temp;
temp = document.getElementById (id + "_Asset").value; if ("" !== temp) obj["Asset"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["Asset", "0..1", "0..*", "Asset", "AssetFunction"]
]
)
);
}
} |
JavaScript | class IECStandard extends base.Element
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.IECStandard;
if (null == bucket)
cim_data.IECStandard = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.IECStandard[obj.id];
}
parse (context, sub)
{
let obj = base.Element.prototype.parse.call (this, context, sub);
obj.cls = "IECStandard";
base.parse_attribute (/<cim:IECStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context);
base.parse_attribute (/<cim:IECStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context);
let bucket = context.parsed.IECStandard;
if (null == bucket)
context.parsed.IECStandard = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = [];
base.export_attribute (obj, "IECStandard", "standardEdition", "standardEdition", fields);
base.export_attribute (obj, "IECStandard", "standardNumber", "standardNumber", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#IECStandard_collapse" aria-expanded="true" aria-controls="IECStandard_collapse" style="margin-left: 10px;">IECStandard</a></legend>
<div id="IECStandard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.template.call (this) +
`
{{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}}
{{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["standardEditionIECStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in IECStandardEditionKind) obj["standardEditionIECStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)});
obj["standardNumberIECStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in IECStandardKind) obj["standardNumberIECStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["standardEditionIECStandardEditionKind"];
delete obj["standardNumberIECStandardKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_IECStandard_collapse" aria-expanded="true" aria-controls="{{id}}_IECStandard_collapse" style="margin-left: 10px;">IECStandard</a></legend>
<div id="{{id}}_IECStandard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionIECStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionIECStandardEditionKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberIECStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberIECStandardKind}}</select></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "IECStandard" };
super.submit (id, obj);
temp = IECStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#IECStandardEditionKind." + temp; else delete obj["standardEdition"];
temp = IECStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#IECStandardKind." + temp; else delete obj["standardNumber"];
return (obj);
}
} |
JavaScript | class DeploymentDate extends base.Element
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.DeploymentDate;
if (null == bucket)
cim_data.DeploymentDate = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.DeploymentDate[obj.id];
}
parse (context, sub)
{
let obj = base.Element.prototype.parse.call (this, context, sub);
obj.cls = "DeploymentDate";
base.parse_element (/<cim:DeploymentDate.inServiceDate>([\s\S]*?)<\/cim:DeploymentDate.inServiceDate>/g, obj, "inServiceDate", base.to_datetime, sub, context);
base.parse_element (/<cim:DeploymentDate.installedDate>([\s\S]*?)<\/cim:DeploymentDate.installedDate>/g, obj, "installedDate", base.to_datetime, sub, context);
base.parse_element (/<cim:DeploymentDate.notYetInstalledDate>([\s\S]*?)<\/cim:DeploymentDate.notYetInstalledDate>/g, obj, "notYetInstalledDate", base.to_datetime, sub, context);
base.parse_element (/<cim:DeploymentDate.outOfServiceDate>([\s\S]*?)<\/cim:DeploymentDate.outOfServiceDate>/g, obj, "outOfServiceDate", base.to_datetime, sub, context);
base.parse_element (/<cim:DeploymentDate.removedDate>([\s\S]*?)<\/cim:DeploymentDate.removedDate>/g, obj, "removedDate", base.to_datetime, sub, context);
let bucket = context.parsed.DeploymentDate;
if (null == bucket)
context.parsed.DeploymentDate = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = [];
base.export_element (obj, "DeploymentDate", "inServiceDate", "inServiceDate", base.from_datetime, fields);
base.export_element (obj, "DeploymentDate", "installedDate", "installedDate", base.from_datetime, fields);
base.export_element (obj, "DeploymentDate", "notYetInstalledDate", "notYetInstalledDate", base.from_datetime, fields);
base.export_element (obj, "DeploymentDate", "outOfServiceDate", "outOfServiceDate", base.from_datetime, fields);
base.export_element (obj, "DeploymentDate", "removedDate", "removedDate", base.from_datetime, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#DeploymentDate_collapse" aria-expanded="true" aria-controls="DeploymentDate_collapse" style="margin-left: 10px;">DeploymentDate</a></legend>
<div id="DeploymentDate_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.template.call (this) +
`
{{#inServiceDate}}<div><b>inServiceDate</b>: {{inServiceDate}}</div>{{/inServiceDate}}
{{#installedDate}}<div><b>installedDate</b>: {{installedDate}}</div>{{/installedDate}}
{{#notYetInstalledDate}}<div><b>notYetInstalledDate</b>: {{notYetInstalledDate}}</div>{{/notYetInstalledDate}}
{{#outOfServiceDate}}<div><b>outOfServiceDate</b>: {{outOfServiceDate}}</div>{{/outOfServiceDate}}
{{#removedDate}}<div><b>removedDate</b>: {{removedDate}}</div>{{/removedDate}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_DeploymentDate_collapse" aria-expanded="true" aria-controls="{{id}}_DeploymentDate_collapse" style="margin-left: 10px;">DeploymentDate</a></legend>
<div id="{{id}}_DeploymentDate_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_inServiceDate'>inServiceDate: </label><div class='col-sm-8'><input id='{{id}}_inServiceDate' class='form-control' type='text'{{#inServiceDate}} value='{{inServiceDate}}'{{/inServiceDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_installedDate'>installedDate: </label><div class='col-sm-8'><input id='{{id}}_installedDate' class='form-control' type='text'{{#installedDate}} value='{{installedDate}}'{{/installedDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_notYetInstalledDate'>notYetInstalledDate: </label><div class='col-sm-8'><input id='{{id}}_notYetInstalledDate' class='form-control' type='text'{{#notYetInstalledDate}} value='{{notYetInstalledDate}}'{{/notYetInstalledDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_outOfServiceDate'>outOfServiceDate: </label><div class='col-sm-8'><input id='{{id}}_outOfServiceDate' class='form-control' type='text'{{#outOfServiceDate}} value='{{outOfServiceDate}}'{{/outOfServiceDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_removedDate'>removedDate: </label><div class='col-sm-8'><input id='{{id}}_removedDate' class='form-control' type='text'{{#removedDate}} value='{{removedDate}}'{{/removedDate}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "DeploymentDate" };
super.submit (id, obj);
temp = document.getElementById (id + "_inServiceDate").value; if ("" !== temp) obj["inServiceDate"] = temp;
temp = document.getElementById (id + "_installedDate").value; if ("" !== temp) obj["installedDate"] = temp;
temp = document.getElementById (id + "_notYetInstalledDate").value; if ("" !== temp) obj["notYetInstalledDate"] = temp;
temp = document.getElementById (id + "_outOfServiceDate").value; if ("" !== temp) obj["outOfServiceDate"] = temp;
temp = document.getElementById (id + "_removedDate").value; if ("" !== temp) obj["removedDate"] = temp;
return (obj);
}
} |
JavaScript | class AnalyticScore extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.AnalyticScore;
if (null == bucket)
cim_data.AnalyticScore = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.AnalyticScore[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "AnalyticScore";
base.parse_element (/<cim:AnalyticScore.calculationDateTime>([\s\S]*?)<\/cim:AnalyticScore.calculationDateTime>/g, obj, "calculationDateTime", base.to_datetime, sub, context);
base.parse_element (/<cim:AnalyticScore.effectiveDateTime>([\s\S]*?)<\/cim:AnalyticScore.effectiveDateTime>/g, obj, "effectiveDateTime", base.to_datetime, sub, context);
base.parse_element (/<cim:AnalyticScore.value>([\s\S]*?)<\/cim:AnalyticScore.value>/g, obj, "value", base.to_float, sub, context);
base.parse_attribute (/<cim:AnalyticScore.AssetAggregateScore\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetAggregateScore", sub, context);
base.parse_attribute (/<cim:AnalyticScore.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context);
base.parse_attribute (/<cim:AnalyticScore.Analytic\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Analytic", sub, context);
base.parse_attribute (/<cim:AnalyticScore.AssetGroup\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetGroup", sub, context);
let bucket = context.parsed.AnalyticScore;
if (null == bucket)
context.parsed.AnalyticScore = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "AnalyticScore", "calculationDateTime", "calculationDateTime", base.from_datetime, fields);
base.export_element (obj, "AnalyticScore", "effectiveDateTime", "effectiveDateTime", base.from_datetime, fields);
base.export_element (obj, "AnalyticScore", "value", "value", base.from_float, fields);
base.export_attribute (obj, "AnalyticScore", "AssetAggregateScore", "AssetAggregateScore", fields);
base.export_attribute (obj, "AnalyticScore", "Asset", "Asset", fields);
base.export_attribute (obj, "AnalyticScore", "Analytic", "Analytic", fields);
base.export_attribute (obj, "AnalyticScore", "AssetGroup", "AssetGroup", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AnalyticScore_collapse" aria-expanded="true" aria-controls="AnalyticScore_collapse" style="margin-left: 10px;">AnalyticScore</a></legend>
<div id="AnalyticScore_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#calculationDateTime}}<div><b>calculationDateTime</b>: {{calculationDateTime}}</div>{{/calculationDateTime}}
{{#effectiveDateTime}}<div><b>effectiveDateTime</b>: {{effectiveDateTime}}</div>{{/effectiveDateTime}}
{{#value}}<div><b>value</b>: {{value}}</div>{{/value}}
{{#AssetAggregateScore}}<div><b>AssetAggregateScore</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetAggregateScore}}");}); return false;'>{{AssetAggregateScore}}</a></div>{{/AssetAggregateScore}}
{{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Asset}}");}); return false;'>{{Asset}}</a></div>{{/Asset}}
{{#Analytic}}<div><b>Analytic</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Analytic}}");}); return false;'>{{Analytic}}</a></div>{{/Analytic}}
{{#AssetGroup}}<div><b>AssetGroup</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetGroup}}");}); return false;'>{{AssetGroup}}</a></div>{{/AssetGroup}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AnalyticScore_collapse" aria-expanded="true" aria-controls="{{id}}_AnalyticScore_collapse" style="margin-left: 10px;">AnalyticScore</a></legend>
<div id="{{id}}_AnalyticScore_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_calculationDateTime'>calculationDateTime: </label><div class='col-sm-8'><input id='{{id}}_calculationDateTime' class='form-control' type='text'{{#calculationDateTime}} value='{{calculationDateTime}}'{{/calculationDateTime}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_effectiveDateTime'>effectiveDateTime: </label><div class='col-sm-8'><input id='{{id}}_effectiveDateTime' class='form-control' type='text'{{#effectiveDateTime}} value='{{effectiveDateTime}}'{{/effectiveDateTime}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_value'>value: </label><div class='col-sm-8'><input id='{{id}}_value' class='form-control' type='text'{{#value}} value='{{value}}'{{/value}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetAggregateScore'>AssetAggregateScore: </label><div class='col-sm-8'><input id='{{id}}_AssetAggregateScore' class='form-control' type='text'{{#AssetAggregateScore}} value='{{AssetAggregateScore}}'{{/AssetAggregateScore}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Asset'>Asset: </label><div class='col-sm-8'><input id='{{id}}_Asset' class='form-control' type='text'{{#Asset}} value='{{Asset}}'{{/Asset}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Analytic'>Analytic: </label><div class='col-sm-8'><input id='{{id}}_Analytic' class='form-control' type='text'{{#Analytic}} value='{{Analytic}}'{{/Analytic}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetGroup'>AssetGroup: </label><div class='col-sm-8'><input id='{{id}}_AssetGroup' class='form-control' type='text'{{#AssetGroup}} value='{{AssetGroup}}'{{/AssetGroup}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "AnalyticScore" };
super.submit (id, obj);
temp = document.getElementById (id + "_calculationDateTime").value; if ("" !== temp) obj["calculationDateTime"] = temp;
temp = document.getElementById (id + "_effectiveDateTime").value; if ("" !== temp) obj["effectiveDateTime"] = temp;
temp = document.getElementById (id + "_value").value; if ("" !== temp) obj["value"] = temp;
temp = document.getElementById (id + "_AssetAggregateScore").value; if ("" !== temp) obj["AssetAggregateScore"] = temp;
temp = document.getElementById (id + "_Asset").value; if ("" !== temp) obj["Asset"] = temp;
temp = document.getElementById (id + "_Analytic").value; if ("" !== temp) obj["Analytic"] = temp;
temp = document.getElementById (id + "_AssetGroup").value; if ("" !== temp) obj["AssetGroup"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["AssetAggregateScore", "0..1", "1..*", "AggregateScore", "AnalyticScore"],
["Asset", "0..1", "0..*", "Asset", "AnalyticScore"],
["Analytic", "0..1", "0..*", "Analytic", "AnalyticScore"],
["AssetGroup", "0..1", "0..*", "AssetGroup", "AnalyticScore"]
]
)
);
}
} |
JavaScript | class WEPStandard extends base.Element
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.WEPStandard;
if (null == bucket)
cim_data.WEPStandard = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.WEPStandard[obj.id];
}
parse (context, sub)
{
let obj = base.Element.prototype.parse.call (this, context, sub);
obj.cls = "WEPStandard";
base.parse_attribute (/<cim:WEPStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context);
base.parse_attribute (/<cim:WEPStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context);
let bucket = context.parsed.WEPStandard;
if (null == bucket)
context.parsed.WEPStandard = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = [];
base.export_attribute (obj, "WEPStandard", "standardEdition", "standardEdition", fields);
base.export_attribute (obj, "WEPStandard", "standardNumber", "standardNumber", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#WEPStandard_collapse" aria-expanded="true" aria-controls="WEPStandard_collapse" style="margin-left: 10px;">WEPStandard</a></legend>
<div id="WEPStandard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.template.call (this) +
`
{{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}}
{{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["standardEditionWEPStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in WEPStandardEditionKind) obj["standardEditionWEPStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)});
obj["standardNumberWEPStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in WEPStandardKind) obj["standardNumberWEPStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["standardEditionWEPStandardEditionKind"];
delete obj["standardNumberWEPStandardKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_WEPStandard_collapse" aria-expanded="true" aria-controls="{{id}}_WEPStandard_collapse" style="margin-left: 10px;">WEPStandard</a></legend>
<div id="{{id}}_WEPStandard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionWEPStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionWEPStandardEditionKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberWEPStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberWEPStandardKind}}</select></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "WEPStandard" };
super.submit (id, obj);
temp = WEPStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#WEPStandardEditionKind." + temp; else delete obj["standardEdition"];
temp = WEPStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#WEPStandardKind." + temp; else delete obj["standardNumber"];
return (obj);
}
} |
JavaScript | class CIGREStandard extends base.Element
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.CIGREStandard;
if (null == bucket)
cim_data.CIGREStandard = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.CIGREStandard[obj.id];
}
parse (context, sub)
{
let obj = base.Element.prototype.parse.call (this, context, sub);
obj.cls = "CIGREStandard";
base.parse_attribute (/<cim:CIGREStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context);
base.parse_attribute (/<cim:CIGREStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context);
let bucket = context.parsed.CIGREStandard;
if (null == bucket)
context.parsed.CIGREStandard = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = [];
base.export_attribute (obj, "CIGREStandard", "standardEdition", "standardEdition", fields);
base.export_attribute (obj, "CIGREStandard", "standardNumber", "standardNumber", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#CIGREStandard_collapse" aria-expanded="true" aria-controls="CIGREStandard_collapse" style="margin-left: 10px;">CIGREStandard</a></legend>
<div id="CIGREStandard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.template.call (this) +
`
{{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}}
{{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["standardEditionCIGREStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in CIGREStandardEditionKind) obj["standardEditionCIGREStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)});
obj["standardNumberCIGREStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in CIGREStandardKind) obj["standardNumberCIGREStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["standardEditionCIGREStandardEditionKind"];
delete obj["standardNumberCIGREStandardKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_CIGREStandard_collapse" aria-expanded="true" aria-controls="{{id}}_CIGREStandard_collapse" style="margin-left: 10px;">CIGREStandard</a></legend>
<div id="{{id}}_CIGREStandard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionCIGREStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionCIGREStandardEditionKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberCIGREStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberCIGREStandardKind}}</select></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "CIGREStandard" };
super.submit (id, obj);
temp = CIGREStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#CIGREStandardEditionKind." + temp; else delete obj["standardEdition"];
temp = CIGREStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#CIGREStandardKind." + temp; else delete obj["standardNumber"];
return (obj);
}
} |
JavaScript | class Analytic extends Common.Document
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.Analytic;
if (null == bucket)
cim_data.Analytic = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.Analytic[obj.id];
}
parse (context, sub)
{
let obj = Common.Document.prototype.parse.call (this, context, sub);
obj.cls = "Analytic";
base.parse_element (/<cim:Analytic.bestValue>([\s\S]*?)<\/cim:Analytic.bestValue>/g, obj, "bestValue", base.to_float, sub, context);
base.parse_attribute (/<cim:Analytic.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context);
base.parse_attribute (/<cim:Analytic.scaleKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "scaleKind", sub, context);
base.parse_element (/<cim:Analytic.worstValue>([\s\S]*?)<\/cim:Analytic.worstValue>/g, obj, "worstValue", base.to_float, sub, context);
base.parse_attributes (/<cim:Analytic.AssetGroup\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetGroup", sub, context);
base.parse_attributes (/<cim:Analytic.AssetHealthEvent\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetHealthEvent", sub, context);
base.parse_attributes (/<cim:Analytic.AnalyticScore\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AnalyticScore", sub, context);
base.parse_attributes (/<cim:Analytic.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context);
let bucket = context.parsed.Analytic;
if (null == bucket)
context.parsed.Analytic = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Common.Document.prototype.export.call (this, obj, false);
base.export_element (obj, "Analytic", "bestValue", "bestValue", base.from_float, fields);
base.export_attribute (obj, "Analytic", "kind", "kind", fields);
base.export_attribute (obj, "Analytic", "scaleKind", "scaleKind", fields);
base.export_element (obj, "Analytic", "worstValue", "worstValue", base.from_float, fields);
base.export_attributes (obj, "Analytic", "AssetGroup", "AssetGroup", fields);
base.export_attributes (obj, "Analytic", "AssetHealthEvent", "AssetHealthEvent", fields);
base.export_attributes (obj, "Analytic", "AnalyticScore", "AnalyticScore", fields);
base.export_attributes (obj, "Analytic", "Asset", "Asset", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Analytic_collapse" aria-expanded="true" aria-controls="Analytic_collapse" style="margin-left: 10px;">Analytic</a></legend>
<div id="Analytic_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Common.Document.prototype.template.call (this) +
`
{{#bestValue}}<div><b>bestValue</b>: {{bestValue}}</div>{{/bestValue}}
{{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}}
{{#scaleKind}}<div><b>scaleKind</b>: {{scaleKind}}</div>{{/scaleKind}}
{{#worstValue}}<div><b>worstValue</b>: {{worstValue}}</div>{{/worstValue}}
{{#AssetGroup}}<div><b>AssetGroup</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetGroup}}
{{#AssetHealthEvent}}<div><b>AssetHealthEvent</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetHealthEvent}}
{{#AnalyticScore}}<div><b>AnalyticScore</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AnalyticScore}}
{{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Asset}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["kindAnalyticKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in AnalyticKind) obj["kindAnalyticKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)});
obj["scaleKindScaleKind"] = [{ id: '', selected: (!obj["scaleKind"])}]; for (let property in ScaleKind) obj["scaleKindScaleKind"].push ({ id: property, selected: obj["scaleKind"] && obj["scaleKind"].endsWith ('.' + property)});
if (obj["AssetGroup"]) obj["AssetGroup_string"] = obj["AssetGroup"].join ();
if (obj["AssetHealthEvent"]) obj["AssetHealthEvent_string"] = obj["AssetHealthEvent"].join ();
if (obj["AnalyticScore"]) obj["AnalyticScore_string"] = obj["AnalyticScore"].join ();
if (obj["Asset"]) obj["Asset_string"] = obj["Asset"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["kindAnalyticKind"];
delete obj["scaleKindScaleKind"];
delete obj["AssetGroup_string"];
delete obj["AssetHealthEvent_string"];
delete obj["AnalyticScore_string"];
delete obj["Asset_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Analytic_collapse" aria-expanded="true" aria-controls="{{id}}_Analytic_collapse" style="margin-left: 10px;">Analytic</a></legend>
<div id="{{id}}_Analytic_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Common.Document.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_bestValue'>bestValue: </label><div class='col-sm-8'><input id='{{id}}_bestValue' class='form-control' type='text'{{#bestValue}} value='{{bestValue}}'{{/bestValue}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindAnalyticKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindAnalyticKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_scaleKind'>scaleKind: </label><div class='col-sm-8'><select id='{{id}}_scaleKind' class='form-control custom-select'>{{#scaleKindScaleKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/scaleKindScaleKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_worstValue'>worstValue: </label><div class='col-sm-8'><input id='{{id}}_worstValue' class='form-control' type='text'{{#worstValue}} value='{{worstValue}}'{{/worstValue}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetGroup'>AssetGroup: </label><div class='col-sm-8'><input id='{{id}}_AssetGroup' class='form-control' type='text'{{#AssetGroup}} value='{{AssetGroup_string}}'{{/AssetGroup}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Asset'>Asset: </label><div class='col-sm-8'><input id='{{id}}_Asset' class='form-control' type='text'{{#Asset}} value='{{Asset_string}}'{{/Asset}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "Analytic" };
super.submit (id, obj);
temp = document.getElementById (id + "_bestValue").value; if ("" !== temp) obj["bestValue"] = temp;
temp = AnalyticKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#AnalyticKind." + temp; else delete obj["kind"];
temp = ScaleKind[document.getElementById (id + "_scaleKind").value]; if (temp) obj["scaleKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#ScaleKind." + temp; else delete obj["scaleKind"];
temp = document.getElementById (id + "_worstValue").value; if ("" !== temp) obj["worstValue"] = temp;
temp = document.getElementById (id + "_AssetGroup").value; if ("" !== temp) obj["AssetGroup"] = temp.split (",");
temp = document.getElementById (id + "_Asset").value; if ("" !== temp) obj["Asset"] = temp.split (",");
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["AssetGroup", "0..*", "0..*", "AssetGroup", "Analytic"],
["AssetHealthEvent", "0..*", "1", "AssetHealthEvent", "Analytic"],
["AnalyticScore", "0..*", "0..1", "AnalyticScore", "Analytic"],
["Asset", "0..*", "0..*", "Asset", "Analytic"]
]
)
);
}
} |
JavaScript | class LaborelecStandard extends base.Element
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.LaborelecStandard;
if (null == bucket)
cim_data.LaborelecStandard = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.LaborelecStandard[obj.id];
}
parse (context, sub)
{
let obj = base.Element.prototype.parse.call (this, context, sub);
obj.cls = "LaborelecStandard";
base.parse_attribute (/<cim:LaborelecStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context);
base.parse_attribute (/<cim:LaborelecStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context);
let bucket = context.parsed.LaborelecStandard;
if (null == bucket)
context.parsed.LaborelecStandard = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = [];
base.export_attribute (obj, "LaborelecStandard", "standardEdition", "standardEdition", fields);
base.export_attribute (obj, "LaborelecStandard", "standardNumber", "standardNumber", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#LaborelecStandard_collapse" aria-expanded="true" aria-controls="LaborelecStandard_collapse" style="margin-left: 10px;">LaborelecStandard</a></legend>
<div id="LaborelecStandard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.template.call (this) +
`
{{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}}
{{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["standardEditionLaborelecStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in LaborelecStandardEditionKind) obj["standardEditionLaborelecStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)});
obj["standardNumberLaborelecStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in LaborelecStandardKind) obj["standardNumberLaborelecStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["standardEditionLaborelecStandardEditionKind"];
delete obj["standardNumberLaborelecStandardKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_LaborelecStandard_collapse" aria-expanded="true" aria-controls="{{id}}_LaborelecStandard_collapse" style="margin-left: 10px;">LaborelecStandard</a></legend>
<div id="{{id}}_LaborelecStandard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionLaborelecStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionLaborelecStandardEditionKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberLaborelecStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberLaborelecStandardKind}}</select></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "LaborelecStandard" };
super.submit (id, obj);
temp = LaborelecStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#LaborelecStandardEditionKind." + temp; else delete obj["standardEdition"];
temp = LaborelecStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#LaborelecStandardKind." + temp; else delete obj["standardNumber"];
return (obj);
}
} |
JavaScript | class AssetLocationHazard extends Common.Hazard
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.AssetLocationHazard;
if (null == bucket)
cim_data.AssetLocationHazard = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.AssetLocationHazard[obj.id];
}
parse (context, sub)
{
let obj = Common.Hazard.prototype.parse.call (this, context, sub);
obj.cls = "AssetLocationHazard";
base.parse_attribute (/<cim:AssetLocationHazard.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context);
base.parse_attributes (/<cim:AssetLocationHazard.Locations\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Locations", sub, context);
let bucket = context.parsed.AssetLocationHazard;
if (null == bucket)
context.parsed.AssetLocationHazard = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Common.Hazard.prototype.export.call (this, obj, false);
base.export_attribute (obj, "AssetLocationHazard", "kind", "kind", fields);
base.export_attributes (obj, "AssetLocationHazard", "Locations", "Locations", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetLocationHazard_collapse" aria-expanded="true" aria-controls="AssetLocationHazard_collapse" style="margin-left: 10px;">AssetLocationHazard</a></legend>
<div id="AssetLocationHazard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Common.Hazard.prototype.template.call (this) +
`
{{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}}
{{#Locations}}<div><b>Locations</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Locations}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["kindAssetHazardKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in AssetHazardKind) obj["kindAssetHazardKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)});
if (obj["Locations"]) obj["Locations_string"] = obj["Locations"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["kindAssetHazardKind"];
delete obj["Locations_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetLocationHazard_collapse" aria-expanded="true" aria-controls="{{id}}_AssetLocationHazard_collapse" style="margin-left: 10px;">AssetLocationHazard</a></legend>
<div id="{{id}}_AssetLocationHazard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Common.Hazard.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindAssetHazardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindAssetHazardKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Locations'>Locations: </label><div class='col-sm-8'><input id='{{id}}_Locations' class='form-control' type='text'{{#Locations}} value='{{Locations_string}}'{{/Locations}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "AssetLocationHazard" };
super.submit (id, obj);
temp = AssetHazardKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#AssetHazardKind." + temp; else delete obj["kind"];
temp = document.getElementById (id + "_Locations").value; if ("" !== temp) obj["Locations"] = temp.split (",");
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["Locations", "0..*", "0..*", "Location", "Hazards"]
]
)
);
}
} |
JavaScript | class Procedure extends Common.Document
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.Procedure;
if (null == bucket)
cim_data.Procedure = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.Procedure[obj.id];
}
parse (context, sub)
{
let obj = Common.Document.prototype.parse.call (this, context, sub);
obj.cls = "Procedure";
base.parse_element (/<cim:Procedure.instruction>([\s\S]*?)<\/cim:Procedure.instruction>/g, obj, "instruction", base.to_string, sub, context);
base.parse_attribute (/<cim:Procedure.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context);
base.parse_element (/<cim:Procedure.sequenceNumber>([\s\S]*?)<\/cim:Procedure.sequenceNumber>/g, obj, "sequenceNumber", base.to_string, sub, context);
base.parse_attributes (/<cim:Procedure.ProcedureDataSets\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ProcedureDataSets", sub, context);
base.parse_attributes (/<cim:Procedure.CompatibleUnits\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "CompatibleUnits", sub, context);
base.parse_attributes (/<cim:Procedure.Assets\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Assets", sub, context);
base.parse_attributes (/<cim:Procedure.Limits\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Limits", sub, context);
base.parse_attributes (/<cim:Procedure.Measurements\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Measurements", sub, context);
let bucket = context.parsed.Procedure;
if (null == bucket)
context.parsed.Procedure = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Common.Document.prototype.export.call (this, obj, false);
base.export_element (obj, "Procedure", "instruction", "instruction", base.from_string, fields);
base.export_attribute (obj, "Procedure", "kind", "kind", fields);
base.export_element (obj, "Procedure", "sequenceNumber", "sequenceNumber", base.from_string, fields);
base.export_attributes (obj, "Procedure", "ProcedureDataSets", "ProcedureDataSets", fields);
base.export_attributes (obj, "Procedure", "CompatibleUnits", "CompatibleUnits", fields);
base.export_attributes (obj, "Procedure", "Assets", "Assets", fields);
base.export_attributes (obj, "Procedure", "Limits", "Limits", fields);
base.export_attributes (obj, "Procedure", "Measurements", "Measurements", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Procedure_collapse" aria-expanded="true" aria-controls="Procedure_collapse" style="margin-left: 10px;">Procedure</a></legend>
<div id="Procedure_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Common.Document.prototype.template.call (this) +
`
{{#instruction}}<div><b>instruction</b>: {{instruction}}</div>{{/instruction}}
{{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}}
{{#sequenceNumber}}<div><b>sequenceNumber</b>: {{sequenceNumber}}</div>{{/sequenceNumber}}
{{#ProcedureDataSets}}<div><b>ProcedureDataSets</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ProcedureDataSets}}
{{#CompatibleUnits}}<div><b>CompatibleUnits</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/CompatibleUnits}}
{{#Assets}}<div><b>Assets</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Assets}}
{{#Limits}}<div><b>Limits</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Limits}}
{{#Measurements}}<div><b>Measurements</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Measurements}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["kindProcedureKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in ProcedureKind) obj["kindProcedureKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)});
if (obj["ProcedureDataSets"]) obj["ProcedureDataSets_string"] = obj["ProcedureDataSets"].join ();
if (obj["CompatibleUnits"]) obj["CompatibleUnits_string"] = obj["CompatibleUnits"].join ();
if (obj["Assets"]) obj["Assets_string"] = obj["Assets"].join ();
if (obj["Limits"]) obj["Limits_string"] = obj["Limits"].join ();
if (obj["Measurements"]) obj["Measurements_string"] = obj["Measurements"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["kindProcedureKind"];
delete obj["ProcedureDataSets_string"];
delete obj["CompatibleUnits_string"];
delete obj["Assets_string"];
delete obj["Limits_string"];
delete obj["Measurements_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Procedure_collapse" aria-expanded="true" aria-controls="{{id}}_Procedure_collapse" style="margin-left: 10px;">Procedure</a></legend>
<div id="{{id}}_Procedure_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Common.Document.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_instruction'>instruction: </label><div class='col-sm-8'><input id='{{id}}_instruction' class='form-control' type='text'{{#instruction}} value='{{instruction}}'{{/instruction}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindProcedureKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindProcedureKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_sequenceNumber'>sequenceNumber: </label><div class='col-sm-8'><input id='{{id}}_sequenceNumber' class='form-control' type='text'{{#sequenceNumber}} value='{{sequenceNumber}}'{{/sequenceNumber}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_CompatibleUnits'>CompatibleUnits: </label><div class='col-sm-8'><input id='{{id}}_CompatibleUnits' class='form-control' type='text'{{#CompatibleUnits}} value='{{CompatibleUnits_string}}'{{/CompatibleUnits}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Assets'>Assets: </label><div class='col-sm-8'><input id='{{id}}_Assets' class='form-control' type='text'{{#Assets}} value='{{Assets_string}}'{{/Assets}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Limits'>Limits: </label><div class='col-sm-8'><input id='{{id}}_Limits' class='form-control' type='text'{{#Limits}} value='{{Limits_string}}'{{/Limits}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Measurements'>Measurements: </label><div class='col-sm-8'><input id='{{id}}_Measurements' class='form-control' type='text'{{#Measurements}} value='{{Measurements_string}}'{{/Measurements}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "Procedure" };
super.submit (id, obj);
temp = document.getElementById (id + "_instruction").value; if ("" !== temp) obj["instruction"] = temp;
temp = ProcedureKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#ProcedureKind." + temp; else delete obj["kind"];
temp = document.getElementById (id + "_sequenceNumber").value; if ("" !== temp) obj["sequenceNumber"] = temp;
temp = document.getElementById (id + "_CompatibleUnits").value; if ("" !== temp) obj["CompatibleUnits"] = temp.split (",");
temp = document.getElementById (id + "_Assets").value; if ("" !== temp) obj["Assets"] = temp.split (",");
temp = document.getElementById (id + "_Limits").value; if ("" !== temp) obj["Limits"] = temp.split (",");
temp = document.getElementById (id + "_Measurements").value; if ("" !== temp) obj["Measurements"] = temp.split (",");
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["ProcedureDataSets", "0..*", "0..1", "ProcedureDataSet", "Procedure"],
["CompatibleUnits", "0..*", "0..*", "CompatibleUnit", "Procedures"],
["Assets", "0..*", "0..*", "Asset", "Procedures"],
["Limits", "0..*", "0..*", "Limit", "Procedures"],
["Measurements", "0..*", "0..*", "Measurement", "Procedures"]
]
)
);
}
} |
JavaScript | class Medium extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.Medium;
if (null == bucket)
cim_data.Medium = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.Medium[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "Medium";
base.parse_attribute (/<cim:Medium.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context);
base.parse_element (/<cim:Medium.volumeSpec>([\s\S]*?)<\/cim:Medium.volumeSpec>/g, obj, "volumeSpec", base.to_string, sub, context);
base.parse_attribute (/<cim:Medium.Specification\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Specification", sub, context);
base.parse_attributes (/<cim:Medium.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context);
let bucket = context.parsed.Medium;
if (null == bucket)
context.parsed.Medium = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_attribute (obj, "Medium", "kind", "kind", fields);
base.export_element (obj, "Medium", "volumeSpec", "volumeSpec", base.from_string, fields);
base.export_attribute (obj, "Medium", "Specification", "Specification", fields);
base.export_attributes (obj, "Medium", "Asset", "Asset", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Medium_collapse" aria-expanded="true" aria-controls="Medium_collapse" style="margin-left: 10px;">Medium</a></legend>
<div id="Medium_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}}
{{#volumeSpec}}<div><b>volumeSpec</b>: {{volumeSpec}}</div>{{/volumeSpec}}
{{#Specification}}<div><b>Specification</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Specification}}");}); return false;'>{{Specification}}</a></div>{{/Specification}}
{{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Asset}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["kindMediumKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in MediumKind) obj["kindMediumKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)});
if (obj["Asset"]) obj["Asset_string"] = obj["Asset"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["kindMediumKind"];
delete obj["Asset_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Medium_collapse" aria-expanded="true" aria-controls="{{id}}_Medium_collapse" style="margin-left: 10px;">Medium</a></legend>
<div id="{{id}}_Medium_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindMediumKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindMediumKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_volumeSpec'>volumeSpec: </label><div class='col-sm-8'><input id='{{id}}_volumeSpec' class='form-control' type='text'{{#volumeSpec}} value='{{volumeSpec}}'{{/volumeSpec}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Specification'>Specification: </label><div class='col-sm-8'><input id='{{id}}_Specification' class='form-control' type='text'{{#Specification}} value='{{Specification}}'{{/Specification}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Asset'>Asset: </label><div class='col-sm-8'><input id='{{id}}_Asset' class='form-control' type='text'{{#Asset}} value='{{Asset_string}}'{{/Asset}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "Medium" };
super.submit (id, obj);
temp = MediumKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#MediumKind." + temp; else delete obj["kind"];
temp = document.getElementById (id + "_volumeSpec").value; if ("" !== temp) obj["volumeSpec"] = temp;
temp = document.getElementById (id + "_Specification").value; if ("" !== temp) obj["Specification"] = temp;
temp = document.getElementById (id + "_Asset").value; if ("" !== temp) obj["Asset"] = temp.split (",");
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["Specification", "0..1", "0..*", "Specification", "Mediums"],
["Asset", "0..*", "0..*", "Asset", "Medium"]
]
)
);
}
} |
JavaScript | class IEEEStandard extends base.Element
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.IEEEStandard;
if (null == bucket)
cim_data.IEEEStandard = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.IEEEStandard[obj.id];
}
parse (context, sub)
{
let obj = base.Element.prototype.parse.call (this, context, sub);
obj.cls = "IEEEStandard";
base.parse_attribute (/<cim:IEEEStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context);
base.parse_attribute (/<cim:IEEEStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context);
let bucket = context.parsed.IEEEStandard;
if (null == bucket)
context.parsed.IEEEStandard = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = [];
base.export_attribute (obj, "IEEEStandard", "standardEdition", "standardEdition", fields);
base.export_attribute (obj, "IEEEStandard", "standardNumber", "standardNumber", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#IEEEStandard_collapse" aria-expanded="true" aria-controls="IEEEStandard_collapse" style="margin-left: 10px;">IEEEStandard</a></legend>
<div id="IEEEStandard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.template.call (this) +
`
{{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}}
{{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["standardEditionIEEEStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in IEEEStandardEditionKind) obj["standardEditionIEEEStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)});
obj["standardNumberIEEEStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in IEEEStandardKind) obj["standardNumberIEEEStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["standardEditionIEEEStandardEditionKind"];
delete obj["standardNumberIEEEStandardKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_IEEEStandard_collapse" aria-expanded="true" aria-controls="{{id}}_IEEEStandard_collapse" style="margin-left: 10px;">IEEEStandard</a></legend>
<div id="{{id}}_IEEEStandard_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionIEEEStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionIEEEStandardEditionKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberIEEEStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberIEEEStandardKind}}</select></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "IEEEStandard" };
super.submit (id, obj);
temp = IEEEStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#IEEEStandardEditionKind." + temp; else delete obj["standardEdition"];
temp = IEEEStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#IEEEStandardKind." + temp; else delete obj["standardNumber"];
return (obj);
}
} |
JavaScript | class LifecycleDate extends base.Element
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.LifecycleDate;
if (null == bucket)
cim_data.LifecycleDate = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.LifecycleDate[obj.id];
}
parse (context, sub)
{
let obj = base.Element.prototype.parse.call (this, context, sub);
obj.cls = "LifecycleDate";
base.parse_element (/<cim:LifecycleDate.installationDate>([\s\S]*?)<\/cim:LifecycleDate.installationDate>/g, obj, "installationDate", base.to_string, sub, context);
base.parse_element (/<cim:LifecycleDate.manufacturedDate>([\s\S]*?)<\/cim:LifecycleDate.manufacturedDate>/g, obj, "manufacturedDate", base.to_string, sub, context);
base.parse_element (/<cim:LifecycleDate.purchaseDate>([\s\S]*?)<\/cim:LifecycleDate.purchaseDate>/g, obj, "purchaseDate", base.to_string, sub, context);
base.parse_element (/<cim:LifecycleDate.receivedDate>([\s\S]*?)<\/cim:LifecycleDate.receivedDate>/g, obj, "receivedDate", base.to_string, sub, context);
base.parse_element (/<cim:LifecycleDate.removalDate>([\s\S]*?)<\/cim:LifecycleDate.removalDate>/g, obj, "removalDate", base.to_string, sub, context);
base.parse_element (/<cim:LifecycleDate.retiredDate>([\s\S]*?)<\/cim:LifecycleDate.retiredDate>/g, obj, "retiredDate", base.to_string, sub, context);
let bucket = context.parsed.LifecycleDate;
if (null == bucket)
context.parsed.LifecycleDate = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = [];
base.export_element (obj, "LifecycleDate", "installationDate", "installationDate", base.from_string, fields);
base.export_element (obj, "LifecycleDate", "manufacturedDate", "manufacturedDate", base.from_string, fields);
base.export_element (obj, "LifecycleDate", "purchaseDate", "purchaseDate", base.from_string, fields);
base.export_element (obj, "LifecycleDate", "receivedDate", "receivedDate", base.from_string, fields);
base.export_element (obj, "LifecycleDate", "removalDate", "removalDate", base.from_string, fields);
base.export_element (obj, "LifecycleDate", "retiredDate", "retiredDate", base.from_string, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#LifecycleDate_collapse" aria-expanded="true" aria-controls="LifecycleDate_collapse" style="margin-left: 10px;">LifecycleDate</a></legend>
<div id="LifecycleDate_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.template.call (this) +
`
{{#installationDate}}<div><b>installationDate</b>: {{installationDate}}</div>{{/installationDate}}
{{#manufacturedDate}}<div><b>manufacturedDate</b>: {{manufacturedDate}}</div>{{/manufacturedDate}}
{{#purchaseDate}}<div><b>purchaseDate</b>: {{purchaseDate}}</div>{{/purchaseDate}}
{{#receivedDate}}<div><b>receivedDate</b>: {{receivedDate}}</div>{{/receivedDate}}
{{#removalDate}}<div><b>removalDate</b>: {{removalDate}}</div>{{/removalDate}}
{{#retiredDate}}<div><b>retiredDate</b>: {{retiredDate}}</div>{{/retiredDate}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_LifecycleDate_collapse" aria-expanded="true" aria-controls="{{id}}_LifecycleDate_collapse" style="margin-left: 10px;">LifecycleDate</a></legend>
<div id="{{id}}_LifecycleDate_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_installationDate'>installationDate: </label><div class='col-sm-8'><input id='{{id}}_installationDate' class='form-control' type='text'{{#installationDate}} value='{{installationDate}}'{{/installationDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_manufacturedDate'>manufacturedDate: </label><div class='col-sm-8'><input id='{{id}}_manufacturedDate' class='form-control' type='text'{{#manufacturedDate}} value='{{manufacturedDate}}'{{/manufacturedDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_purchaseDate'>purchaseDate: </label><div class='col-sm-8'><input id='{{id}}_purchaseDate' class='form-control' type='text'{{#purchaseDate}} value='{{purchaseDate}}'{{/purchaseDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_receivedDate'>receivedDate: </label><div class='col-sm-8'><input id='{{id}}_receivedDate' class='form-control' type='text'{{#receivedDate}} value='{{receivedDate}}'{{/receivedDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_removalDate'>removalDate: </label><div class='col-sm-8'><input id='{{id}}_removalDate' class='form-control' type='text'{{#removalDate}} value='{{removalDate}}'{{/removalDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_retiredDate'>retiredDate: </label><div class='col-sm-8'><input id='{{id}}_retiredDate' class='form-control' type='text'{{#retiredDate}} value='{{retiredDate}}'{{/retiredDate}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "LifecycleDate" };
super.submit (id, obj);
temp = document.getElementById (id + "_installationDate").value; if ("" !== temp) obj["installationDate"] = temp;
temp = document.getElementById (id + "_manufacturedDate").value; if ("" !== temp) obj["manufacturedDate"] = temp;
temp = document.getElementById (id + "_purchaseDate").value; if ("" !== temp) obj["purchaseDate"] = temp;
temp = document.getElementById (id + "_receivedDate").value; if ("" !== temp) obj["receivedDate"] = temp;
temp = document.getElementById (id + "_removalDate").value; if ("" !== temp) obj["removalDate"] = temp;
temp = document.getElementById (id + "_retiredDate").value; if ("" !== temp) obj["retiredDate"] = temp;
return (obj);
}
} |
JavaScript | class AcceptanceTest extends base.Element
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.AcceptanceTest;
if (null == bucket)
cim_data.AcceptanceTest = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.AcceptanceTest[obj.id];
}
parse (context, sub)
{
let obj = base.Element.prototype.parse.call (this, context, sub);
obj.cls = "AcceptanceTest";
base.parse_element (/<cim:AcceptanceTest.dateTime>([\s\S]*?)<\/cim:AcceptanceTest.dateTime>/g, obj, "dateTime", base.to_datetime, sub, context);
base.parse_element (/<cim:AcceptanceTest.success>([\s\S]*?)<\/cim:AcceptanceTest.success>/g, obj, "success", base.to_boolean, sub, context);
base.parse_element (/<cim:AcceptanceTest.type>([\s\S]*?)<\/cim:AcceptanceTest.type>/g, obj, "type", base.to_string, sub, context);
let bucket = context.parsed.AcceptanceTest;
if (null == bucket)
context.parsed.AcceptanceTest = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = [];
base.export_element (obj, "AcceptanceTest", "dateTime", "dateTime", base.from_datetime, fields);
base.export_element (obj, "AcceptanceTest", "success", "success", base.from_boolean, fields);
base.export_element (obj, "AcceptanceTest", "type", "type", base.from_string, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AcceptanceTest_collapse" aria-expanded="true" aria-controls="AcceptanceTest_collapse" style="margin-left: 10px;">AcceptanceTest</a></legend>
<div id="AcceptanceTest_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.template.call (this) +
`
{{#dateTime}}<div><b>dateTime</b>: {{dateTime}}</div>{{/dateTime}}
{{#success}}<div><b>success</b>: {{success}}</div>{{/success}}
{{#type}}<div><b>type</b>: {{type}}</div>{{/type}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AcceptanceTest_collapse" aria-expanded="true" aria-controls="{{id}}_AcceptanceTest_collapse" style="margin-left: 10px;">AcceptanceTest</a></legend>
<div id="{{id}}_AcceptanceTest_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ base.Element.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_dateTime'>dateTime: </label><div class='col-sm-8'><input id='{{id}}_dateTime' class='form-control' type='text'{{#dateTime}} value='{{dateTime}}'{{/dateTime}}></div></div>
<div class='form-group row'><div class='col-sm-4' for='{{id}}_success'>success: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_success' class='form-check-input' type='checkbox'{{#success}} checked{{/success}}></div></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_type'>type: </label><div class='col-sm-8'><input id='{{id}}_type' class='form-control' type='text'{{#type}} value='{{type}}'{{/type}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "AcceptanceTest" };
super.submit (id, obj);
temp = document.getElementById (id + "_dateTime").value; if ("" !== temp) obj["dateTime"] = temp;
temp = document.getElementById (id + "_success").checked; if (temp) obj["success"] = true;
temp = document.getElementById (id + "_type").value; if ("" !== temp) obj["type"] = temp;
return (obj);
}
} |
JavaScript | class StructureSupport extends Asset
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.StructureSupport;
if (null == bucket)
cim_data.StructureSupport = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.StructureSupport[obj.id];
}
parse (context, sub)
{
let obj = Asset.prototype.parse.call (this, context, sub);
obj.cls = "StructureSupport";
base.parse_attribute (/<cim:StructureSupport.anchorKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "anchorKind", sub, context);
base.parse_element (/<cim:StructureSupport.anchorRodCount>([\s\S]*?)<\/cim:StructureSupport.anchorRodCount>/g, obj, "anchorRodCount", base.to_string, sub, context);
base.parse_element (/<cim:StructureSupport.anchorRodLength>([\s\S]*?)<\/cim:StructureSupport.anchorRodLength>/g, obj, "anchorRodLength", base.to_string, sub, context);
base.parse_element (/<cim:StructureSupport.direction>([\s\S]*?)<\/cim:StructureSupport.direction>/g, obj, "direction", base.to_string, sub, context);
base.parse_attribute (/<cim:StructureSupport.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context);
base.parse_element (/<cim:StructureSupport.length>([\s\S]*?)<\/cim:StructureSupport.length>/g, obj, "length", base.to_string, sub, context);
base.parse_element (/<cim:StructureSupport.size>([\s\S]*?)<\/cim:StructureSupport.size>/g, obj, "size", base.to_string, sub, context);
base.parse_attribute (/<cim:StructureSupport.SecuredStructure\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "SecuredStructure", sub, context);
let bucket = context.parsed.StructureSupport;
if (null == bucket)
context.parsed.StructureSupport = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Asset.prototype.export.call (this, obj, false);
base.export_attribute (obj, "StructureSupport", "anchorKind", "anchorKind", fields);
base.export_element (obj, "StructureSupport", "anchorRodCount", "anchorRodCount", base.from_string, fields);
base.export_element (obj, "StructureSupport", "anchorRodLength", "anchorRodLength", base.from_string, fields);
base.export_element (obj, "StructureSupport", "direction", "direction", base.from_string, fields);
base.export_attribute (obj, "StructureSupport", "kind", "kind", fields);
base.export_element (obj, "StructureSupport", "length", "length", base.from_string, fields);
base.export_element (obj, "StructureSupport", "size", "size", base.from_string, fields);
base.export_attribute (obj, "StructureSupport", "SecuredStructure", "SecuredStructure", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#StructureSupport_collapse" aria-expanded="true" aria-controls="StructureSupport_collapse" style="margin-left: 10px;">StructureSupport</a></legend>
<div id="StructureSupport_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.template.call (this) +
`
{{#anchorKind}}<div><b>anchorKind</b>: {{anchorKind}}</div>{{/anchorKind}}
{{#anchorRodCount}}<div><b>anchorRodCount</b>: {{anchorRodCount}}</div>{{/anchorRodCount}}
{{#anchorRodLength}}<div><b>anchorRodLength</b>: {{anchorRodLength}}</div>{{/anchorRodLength}}
{{#direction}}<div><b>direction</b>: {{direction}}</div>{{/direction}}
{{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}}
{{#length}}<div><b>length</b>: {{length}}</div>{{/length}}
{{#size}}<div><b>size</b>: {{size}}</div>{{/size}}
{{#SecuredStructure}}<div><b>SecuredStructure</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{SecuredStructure}}");}); return false;'>{{SecuredStructure}}</a></div>{{/SecuredStructure}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["anchorKindAnchorKind"] = [{ id: '', selected: (!obj["anchorKind"])}]; for (let property in InfAssets.AnchorKind) obj["anchorKindAnchorKind"].push ({ id: property, selected: obj["anchorKind"] && obj["anchorKind"].endsWith ('.' + property)});
obj["kindStructureSupportKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in InfAssets.StructureSupportKind) obj["kindStructureSupportKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["anchorKindAnchorKind"];
delete obj["kindStructureSupportKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_StructureSupport_collapse" aria-expanded="true" aria-controls="{{id}}_StructureSupport_collapse" style="margin-left: 10px;">StructureSupport</a></legend>
<div id="{{id}}_StructureSupport_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_anchorKind'>anchorKind: </label><div class='col-sm-8'><select id='{{id}}_anchorKind' class='form-control custom-select'>{{#anchorKindAnchorKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/anchorKindAnchorKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_anchorRodCount'>anchorRodCount: </label><div class='col-sm-8'><input id='{{id}}_anchorRodCount' class='form-control' type='text'{{#anchorRodCount}} value='{{anchorRodCount}}'{{/anchorRodCount}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_anchorRodLength'>anchorRodLength: </label><div class='col-sm-8'><input id='{{id}}_anchorRodLength' class='form-control' type='text'{{#anchorRodLength}} value='{{anchorRodLength}}'{{/anchorRodLength}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_direction'>direction: </label><div class='col-sm-8'><input id='{{id}}_direction' class='form-control' type='text'{{#direction}} value='{{direction}}'{{/direction}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindStructureSupportKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindStructureSupportKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_length'>length: </label><div class='col-sm-8'><input id='{{id}}_length' class='form-control' type='text'{{#length}} value='{{length}}'{{/length}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_size'>size: </label><div class='col-sm-8'><input id='{{id}}_size' class='form-control' type='text'{{#size}} value='{{size}}'{{/size}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_SecuredStructure'>SecuredStructure: </label><div class='col-sm-8'><input id='{{id}}_SecuredStructure' class='form-control' type='text'{{#SecuredStructure}} value='{{SecuredStructure}}'{{/SecuredStructure}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "StructureSupport" };
super.submit (id, obj);
temp = InfAssets.AnchorKind[document.getElementById (id + "_anchorKind").value]; if (temp) obj["anchorKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#AnchorKind." + temp; else delete obj["anchorKind"];
temp = document.getElementById (id + "_anchorRodCount").value; if ("" !== temp) obj["anchorRodCount"] = temp;
temp = document.getElementById (id + "_anchorRodLength").value; if ("" !== temp) obj["anchorRodLength"] = temp;
temp = document.getElementById (id + "_direction").value; if ("" !== temp) obj["direction"] = temp;
temp = InfAssets.StructureSupportKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#StructureSupportKind." + temp; else delete obj["kind"];
temp = document.getElementById (id + "_length").value; if ("" !== temp) obj["length"] = temp;
temp = document.getElementById (id + "_size").value; if ("" !== temp) obj["size"] = temp;
temp = document.getElementById (id + "_SecuredStructure").value; if ("" !== temp) obj["SecuredStructure"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["SecuredStructure", "0..1", "0..*", "Structure", "StructureSupports"]
]
)
);
}
} |
JavaScript | class ComMedia extends Asset
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ComMedia;
if (null == bucket)
cim_data.ComMedia = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ComMedia[obj.id];
}
parse (context, sub)
{
let obj = Asset.prototype.parse.call (this, context, sub);
obj.cls = "ComMedia";
let bucket = context.parsed.ComMedia;
if (null == bucket)
context.parsed.ComMedia = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Asset.prototype.export.call (this, obj, false);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ComMedia_collapse" aria-expanded="true" aria-controls="ComMedia_collapse" style="margin-left: 10px;">ComMedia</a></legend>
<div id="ComMedia_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.template.call (this) +
`
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ComMedia_collapse" aria-expanded="true" aria-controls="{{id}}_ComMedia_collapse" style="margin-left: 10px;">ComMedia</a></legend>
<div id="{{id}}_ComMedia_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ComMedia" };
super.submit (id, obj);
return (obj);
}
} |
JavaScript | class FACTSDevice extends Asset
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.FACTSDevice;
if (null == bucket)
cim_data.FACTSDevice = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.FACTSDevice[obj.id];
}
parse (context, sub)
{
let obj = Asset.prototype.parse.call (this, context, sub);
obj.cls = "FACTSDevice";
base.parse_attribute (/<cim:FACTSDevice.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context);
let bucket = context.parsed.FACTSDevice;
if (null == bucket)
context.parsed.FACTSDevice = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Asset.prototype.export.call (this, obj, false);
base.export_attribute (obj, "FACTSDevice", "kind", "kind", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#FACTSDevice_collapse" aria-expanded="true" aria-controls="FACTSDevice_collapse" style="margin-left: 10px;">FACTSDevice</a></legend>
<div id="FACTSDevice_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.template.call (this) +
`
{{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["kindFACTSDeviceKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in InfAssets.FACTSDeviceKind) obj["kindFACTSDeviceKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["kindFACTSDeviceKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_FACTSDevice_collapse" aria-expanded="true" aria-controls="{{id}}_FACTSDevice_collapse" style="margin-left: 10px;">FACTSDevice</a></legend>
<div id="{{id}}_FACTSDevice_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindFACTSDeviceKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindFACTSDeviceKind}}</select></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "FACTSDevice" };
super.submit (id, obj);
temp = InfAssets.FACTSDeviceKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#FACTSDeviceKind." + temp; else delete obj["kind"];
return (obj);
}
} |
JavaScript | class AssetContainer extends Asset
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.AssetContainer;
if (null == bucket)
cim_data.AssetContainer = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.AssetContainer[obj.id];
}
parse (context, sub)
{
let obj = Asset.prototype.parse.call (this, context, sub);
obj.cls = "AssetContainer";
base.parse_attributes (/<cim:AssetContainer.Seals\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Seals", sub, context);
base.parse_attributes (/<cim:AssetContainer.Assets\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Assets", sub, context);
base.parse_attributes (/<cim:AssetContainer.LandProperties\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "LandProperties", sub, context);
let bucket = context.parsed.AssetContainer;
if (null == bucket)
context.parsed.AssetContainer = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Asset.prototype.export.call (this, obj, false);
base.export_attributes (obj, "AssetContainer", "Seals", "Seals", fields);
base.export_attributes (obj, "AssetContainer", "Assets", "Assets", fields);
base.export_attributes (obj, "AssetContainer", "LandProperties", "LandProperties", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetContainer_collapse" aria-expanded="true" aria-controls="AssetContainer_collapse" style="margin-left: 10px;">AssetContainer</a></legend>
<div id="AssetContainer_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.template.call (this) +
`
{{#Seals}}<div><b>Seals</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Seals}}
{{#Assets}}<div><b>Assets</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Assets}}
{{#LandProperties}}<div><b>LandProperties</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/LandProperties}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["Seals"]) obj["Seals_string"] = obj["Seals"].join ();
if (obj["Assets"]) obj["Assets_string"] = obj["Assets"].join ();
if (obj["LandProperties"]) obj["LandProperties_string"] = obj["LandProperties"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["Seals_string"];
delete obj["Assets_string"];
delete obj["LandProperties_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetContainer_collapse" aria-expanded="true" aria-controls="{{id}}_AssetContainer_collapse" style="margin-left: 10px;">AssetContainer</a></legend>
<div id="{{id}}_AssetContainer_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_LandProperties'>LandProperties: </label><div class='col-sm-8'><input id='{{id}}_LandProperties' class='form-control' type='text'{{#LandProperties}} value='{{LandProperties_string}}'{{/LandProperties}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "AssetContainer" };
super.submit (id, obj);
temp = document.getElementById (id + "_LandProperties").value; if ("" !== temp) obj["LandProperties"] = temp.split (",");
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["Seals", "0..*", "0..1", "Seal", "AssetContainer"],
["Assets", "0..*", "0..1", "Asset", "AssetContainer"],
["LandProperties", "0..*", "0..*", "LandProperty", "AssetContainers"]
]
)
);
}
} |
JavaScript | class InterrupterUnit extends Asset
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.InterrupterUnit;
if (null == bucket)
cim_data.InterrupterUnit = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.InterrupterUnit[obj.id];
}
parse (context, sub)
{
let obj = Asset.prototype.parse.call (this, context, sub);
obj.cls = "InterrupterUnit";
base.parse_attributes (/<cim:InterrupterUnit.Bushing\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Bushing", sub, context);
base.parse_attribute (/<cim:InterrupterUnit.OperatingMechanism\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "OperatingMechanism", sub, context);
base.parse_attributes (/<cim:InterrupterUnit.Bushing\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Bushing", sub, context);
let bucket = context.parsed.InterrupterUnit;
if (null == bucket)
context.parsed.InterrupterUnit = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Asset.prototype.export.call (this, obj, false);
base.export_attributes (obj, "InterrupterUnit", "Bushing", "Bushing", fields);
base.export_attribute (obj, "InterrupterUnit", "OperatingMechanism", "OperatingMechanism", fields);
base.export_attributes (obj, "InterrupterUnit", "Bushing", "Bushing", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#InterrupterUnit_collapse" aria-expanded="true" aria-controls="InterrupterUnit_collapse" style="margin-left: 10px;">InterrupterUnit</a></legend>
<div id="InterrupterUnit_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.template.call (this) +
`
{{#Bushing}}<div><b>Bushing</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Bushing}}
{{#OperatingMechanism}}<div><b>OperatingMechanism</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{OperatingMechanism}}");}); return false;'>{{OperatingMechanism}}</a></div>{{/OperatingMechanism}}
{{#Bushing}}<div><b>Bushing</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Bushing}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["Bushing"]) obj["Bushing_string"] = obj["Bushing"].join ();
if (obj["Bushing"]) obj["Bushing_string"] = obj["Bushing"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["Bushing_string"];
delete obj["Bushing_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_InterrupterUnit_collapse" aria-expanded="true" aria-controls="{{id}}_InterrupterUnit_collapse" style="margin-left: 10px;">InterrupterUnit</a></legend>
<div id="{{id}}_InterrupterUnit_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_OperatingMechanism'>OperatingMechanism: </label><div class='col-sm-8'><input id='{{id}}_OperatingMechanism' class='form-control' type='text'{{#OperatingMechanism}} value='{{OperatingMechanism}}'{{/OperatingMechanism}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "InterrupterUnit" };
super.submit (id, obj);
temp = document.getElementById (id + "_OperatingMechanism").value; if ("" !== temp) obj["OperatingMechanism"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["Bushing", "0..*", "0..1", "Bushing", "MovingContact"],
["OperatingMechanism", "0..1", "0..*", "OperatingMechanism", "InterrupterUnit"],
["Bushing", "0..*", "0..1", "Bushing", "FixedContact"]
]
)
);
}
} |
JavaScript | class Facility extends AssetContainer
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.Facility;
if (null == bucket)
cim_data.Facility = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.Facility[obj.id];
}
parse (context, sub)
{
let obj = AssetContainer.prototype.parse.call (this, context, sub);
obj.cls = "Facility";
base.parse_element (/<cim:Facility.kind>([\s\S]*?)<\/cim:Facility.kind>/g, obj, "kind", base.to_string, sub, context);
let bucket = context.parsed.Facility;
if (null == bucket)
context.parsed.Facility = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AssetContainer.prototype.export.call (this, obj, false);
base.export_element (obj, "Facility", "kind", "kind", base.from_string, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Facility_collapse" aria-expanded="true" aria-controls="Facility_collapse" style="margin-left: 10px;">Facility</a></legend>
<div id="Facility_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetContainer.prototype.template.call (this) +
`
{{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Facility_collapse" aria-expanded="true" aria-controls="{{id}}_Facility_collapse" style="margin-left: 10px;">Facility</a></legend>
<div id="{{id}}_Facility_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetContainer.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><input id='{{id}}_kind' class='form-control' type='text'{{#kind}} value='{{kind}}'{{/kind}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "Facility" };
super.submit (id, obj);
temp = document.getElementById (id + "_kind").value; if ("" !== temp) obj["kind"] = temp;
return (obj);
}
} |
JavaScript | class Joint extends Asset
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.Joint;
if (null == bucket)
cim_data.Joint = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.Joint[obj.id];
}
parse (context, sub)
{
let obj = Asset.prototype.parse.call (this, context, sub);
obj.cls = "Joint";
base.parse_attribute (/<cim:Joint.configurationKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "configurationKind", sub, context);
base.parse_attribute (/<cim:Joint.fillKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "fillKind", sub, context);
base.parse_element (/<cim:Joint.insulation>([\s\S]*?)<\/cim:Joint.insulation>/g, obj, "insulation", base.to_string, sub, context);
let bucket = context.parsed.Joint;
if (null == bucket)
context.parsed.Joint = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Asset.prototype.export.call (this, obj, false);
base.export_attribute (obj, "Joint", "configurationKind", "configurationKind", fields);
base.export_attribute (obj, "Joint", "fillKind", "fillKind", fields);
base.export_element (obj, "Joint", "insulation", "insulation", base.from_string, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Joint_collapse" aria-expanded="true" aria-controls="Joint_collapse" style="margin-left: 10px;">Joint</a></legend>
<div id="Joint_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.template.call (this) +
`
{{#configurationKind}}<div><b>configurationKind</b>: {{configurationKind}}</div>{{/configurationKind}}
{{#fillKind}}<div><b>fillKind</b>: {{fillKind}}</div>{{/fillKind}}
{{#insulation}}<div><b>insulation</b>: {{insulation}}</div>{{/insulation}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["configurationKindJointConfigurationKind"] = [{ id: '', selected: (!obj["configurationKind"])}]; for (let property in InfAssets.JointConfigurationKind) obj["configurationKindJointConfigurationKind"].push ({ id: property, selected: obj["configurationKind"] && obj["configurationKind"].endsWith ('.' + property)});
obj["fillKindJointFillKind"] = [{ id: '', selected: (!obj["fillKind"])}]; for (let property in InfAssets.JointFillKind) obj["fillKindJointFillKind"].push ({ id: property, selected: obj["fillKind"] && obj["fillKind"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["configurationKindJointConfigurationKind"];
delete obj["fillKindJointFillKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Joint_collapse" aria-expanded="true" aria-controls="{{id}}_Joint_collapse" style="margin-left: 10px;">Joint</a></legend>
<div id="{{id}}_Joint_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Asset.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_configurationKind'>configurationKind: </label><div class='col-sm-8'><select id='{{id}}_configurationKind' class='form-control custom-select'>{{#configurationKindJointConfigurationKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/configurationKindJointConfigurationKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_fillKind'>fillKind: </label><div class='col-sm-8'><select id='{{id}}_fillKind' class='form-control custom-select'>{{#fillKindJointFillKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/fillKindJointFillKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_insulation'>insulation: </label><div class='col-sm-8'><input id='{{id}}_insulation' class='form-control' type='text'{{#insulation}} value='{{insulation}}'{{/insulation}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "Joint" };
super.submit (id, obj);
temp = InfAssets.JointConfigurationKind[document.getElementById (id + "_configurationKind").value]; if (temp) obj["configurationKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#JointConfigurationKind." + temp; else delete obj["configurationKind"];
temp = InfAssets.JointFillKind[document.getElementById (id + "_fillKind").value]; if (temp) obj["fillKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#JointFillKind." + temp; else delete obj["fillKind"];
temp = document.getElementById (id + "_insulation").value; if ("" !== temp) obj["insulation"] = temp;
return (obj);
}
} |
JavaScript | class Structure extends AssetContainer
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.Structure;
if (null == bucket)
cim_data.Structure = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.Structure[obj.id];
}
parse (context, sub)
{
let obj = AssetContainer.prototype.parse.call (this, context, sub);
obj.cls = "Structure";
base.parse_element (/<cim:Structure.fumigantAppliedDate>([\s\S]*?)<\/cim:Structure.fumigantAppliedDate>/g, obj, "fumigantAppliedDate", base.to_string, sub, context);
base.parse_element (/<cim:Structure.fumigantName>([\s\S]*?)<\/cim:Structure.fumigantName>/g, obj, "fumigantName", base.to_string, sub, context);
base.parse_element (/<cim:Structure.height>([\s\S]*?)<\/cim:Structure.height>/g, obj, "height", base.to_string, sub, context);
base.parse_attribute (/<cim:Structure.materialKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "materialKind", sub, context);
base.parse_element (/<cim:Structure.ratedVoltage>([\s\S]*?)<\/cim:Structure.ratedVoltage>/g, obj, "ratedVoltage", base.to_string, sub, context);
base.parse_element (/<cim:Structure.removeWeed>([\s\S]*?)<\/cim:Structure.removeWeed>/g, obj, "removeWeed", base.to_boolean, sub, context);
base.parse_element (/<cim:Structure.weedRemovedDate>([\s\S]*?)<\/cim:Structure.weedRemovedDate>/g, obj, "weedRemovedDate", base.to_string, sub, context);
base.parse_attributes (/<cim:Structure.WireSpacingInfos\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WireSpacingInfos", sub, context);
base.parse_attributes (/<cim:Structure.StructureSupports\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "StructureSupports", sub, context);
let bucket = context.parsed.Structure;
if (null == bucket)
context.parsed.Structure = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AssetContainer.prototype.export.call (this, obj, false);
base.export_element (obj, "Structure", "fumigantAppliedDate", "fumigantAppliedDate", base.from_string, fields);
base.export_element (obj, "Structure", "fumigantName", "fumigantName", base.from_string, fields);
base.export_element (obj, "Structure", "height", "height", base.from_string, fields);
base.export_attribute (obj, "Structure", "materialKind", "materialKind", fields);
base.export_element (obj, "Structure", "ratedVoltage", "ratedVoltage", base.from_string, fields);
base.export_element (obj, "Structure", "removeWeed", "removeWeed", base.from_boolean, fields);
base.export_element (obj, "Structure", "weedRemovedDate", "weedRemovedDate", base.from_string, fields);
base.export_attributes (obj, "Structure", "WireSpacingInfos", "WireSpacingInfos", fields);
base.export_attributes (obj, "Structure", "StructureSupports", "StructureSupports", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Structure_collapse" aria-expanded="true" aria-controls="Structure_collapse" style="margin-left: 10px;">Structure</a></legend>
<div id="Structure_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetContainer.prototype.template.call (this) +
`
{{#fumigantAppliedDate}}<div><b>fumigantAppliedDate</b>: {{fumigantAppliedDate}}</div>{{/fumigantAppliedDate}}
{{#fumigantName}}<div><b>fumigantName</b>: {{fumigantName}}</div>{{/fumigantName}}
{{#height}}<div><b>height</b>: {{height}}</div>{{/height}}
{{#materialKind}}<div><b>materialKind</b>: {{materialKind}}</div>{{/materialKind}}
{{#ratedVoltage}}<div><b>ratedVoltage</b>: {{ratedVoltage}}</div>{{/ratedVoltage}}
{{#removeWeed}}<div><b>removeWeed</b>: {{removeWeed}}</div>{{/removeWeed}}
{{#weedRemovedDate}}<div><b>weedRemovedDate</b>: {{weedRemovedDate}}</div>{{/weedRemovedDate}}
{{#WireSpacingInfos}}<div><b>WireSpacingInfos</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WireSpacingInfos}}
{{#StructureSupports}}<div><b>StructureSupports</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/StructureSupports}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["materialKindStructureMaterialKind"] = [{ id: '', selected: (!obj["materialKind"])}]; for (let property in InfAssets.StructureMaterialKind) obj["materialKindStructureMaterialKind"].push ({ id: property, selected: obj["materialKind"] && obj["materialKind"].endsWith ('.' + property)});
if (obj["WireSpacingInfos"]) obj["WireSpacingInfos_string"] = obj["WireSpacingInfos"].join ();
if (obj["StructureSupports"]) obj["StructureSupports_string"] = obj["StructureSupports"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["materialKindStructureMaterialKind"];
delete obj["WireSpacingInfos_string"];
delete obj["StructureSupports_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Structure_collapse" aria-expanded="true" aria-controls="{{id}}_Structure_collapse" style="margin-left: 10px;">Structure</a></legend>
<div id="{{id}}_Structure_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetContainer.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_fumigantAppliedDate'>fumigantAppliedDate: </label><div class='col-sm-8'><input id='{{id}}_fumigantAppliedDate' class='form-control' type='text'{{#fumigantAppliedDate}} value='{{fumigantAppliedDate}}'{{/fumigantAppliedDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_fumigantName'>fumigantName: </label><div class='col-sm-8'><input id='{{id}}_fumigantName' class='form-control' type='text'{{#fumigantName}} value='{{fumigantName}}'{{/fumigantName}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_height'>height: </label><div class='col-sm-8'><input id='{{id}}_height' class='form-control' type='text'{{#height}} value='{{height}}'{{/height}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_materialKind'>materialKind: </label><div class='col-sm-8'><select id='{{id}}_materialKind' class='form-control custom-select'>{{#materialKindStructureMaterialKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/materialKindStructureMaterialKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ratedVoltage'>ratedVoltage: </label><div class='col-sm-8'><input id='{{id}}_ratedVoltage' class='form-control' type='text'{{#ratedVoltage}} value='{{ratedVoltage}}'{{/ratedVoltage}}></div></div>
<div class='form-group row'><div class='col-sm-4' for='{{id}}_removeWeed'>removeWeed: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_removeWeed' class='form-check-input' type='checkbox'{{#removeWeed}} checked{{/removeWeed}}></div></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_weedRemovedDate'>weedRemovedDate: </label><div class='col-sm-8'><input id='{{id}}_weedRemovedDate' class='form-control' type='text'{{#weedRemovedDate}} value='{{weedRemovedDate}}'{{/weedRemovedDate}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WireSpacingInfos'>WireSpacingInfos: </label><div class='col-sm-8'><input id='{{id}}_WireSpacingInfos' class='form-control' type='text'{{#WireSpacingInfos}} value='{{WireSpacingInfos_string}}'{{/WireSpacingInfos}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "Structure" };
super.submit (id, obj);
temp = document.getElementById (id + "_fumigantAppliedDate").value; if ("" !== temp) obj["fumigantAppliedDate"] = temp;
temp = document.getElementById (id + "_fumigantName").value; if ("" !== temp) obj["fumigantName"] = temp;
temp = document.getElementById (id + "_height").value; if ("" !== temp) obj["height"] = temp;
temp = InfAssets.StructureMaterialKind[document.getElementById (id + "_materialKind").value]; if (temp) obj["materialKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#StructureMaterialKind." + temp; else delete obj["materialKind"];
temp = document.getElementById (id + "_ratedVoltage").value; if ("" !== temp) obj["ratedVoltage"] = temp;
temp = document.getElementById (id + "_removeWeed").checked; if (temp) obj["removeWeed"] = true;
temp = document.getElementById (id + "_weedRemovedDate").value; if ("" !== temp) obj["weedRemovedDate"] = temp;
temp = document.getElementById (id + "_WireSpacingInfos").value; if ("" !== temp) obj["WireSpacingInfos"] = temp.split (",");
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WireSpacingInfos", "0..*", "0..*", "WireSpacingInfo", "Structures"],
["StructureSupports", "0..*", "0..1", "StructureSupport", "SecuredStructure"]
]
)
);
}
} |
JavaScript | class DuctBank extends AssetContainer
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.DuctBank;
if (null == bucket)
cim_data.DuctBank = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.DuctBank[obj.id];
}
parse (context, sub)
{
let obj = AssetContainer.prototype.parse.call (this, context, sub);
obj.cls = "DuctBank";
base.parse_element (/<cim:DuctBank.circuitCount>([\s\S]*?)<\/cim:DuctBank.circuitCount>/g, obj, "circuitCount", base.to_string, sub, context);
base.parse_attributes (/<cim:DuctBank.WireSpacingInfos\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WireSpacingInfos", sub, context);
let bucket = context.parsed.DuctBank;
if (null == bucket)
context.parsed.DuctBank = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AssetContainer.prototype.export.call (this, obj, false);
base.export_element (obj, "DuctBank", "circuitCount", "circuitCount", base.from_string, fields);
base.export_attributes (obj, "DuctBank", "WireSpacingInfos", "WireSpacingInfos", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#DuctBank_collapse" aria-expanded="true" aria-controls="DuctBank_collapse" style="margin-left: 10px;">DuctBank</a></legend>
<div id="DuctBank_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetContainer.prototype.template.call (this) +
`
{{#circuitCount}}<div><b>circuitCount</b>: {{circuitCount}}</div>{{/circuitCount}}
{{#WireSpacingInfos}}<div><b>WireSpacingInfos</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WireSpacingInfos}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["WireSpacingInfos"]) obj["WireSpacingInfos_string"] = obj["WireSpacingInfos"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["WireSpacingInfos_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_DuctBank_collapse" aria-expanded="true" aria-controls="{{id}}_DuctBank_collapse" style="margin-left: 10px;">DuctBank</a></legend>
<div id="{{id}}_DuctBank_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetContainer.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_circuitCount'>circuitCount: </label><div class='col-sm-8'><input id='{{id}}_circuitCount' class='form-control' type='text'{{#circuitCount}} value='{{circuitCount}}'{{/circuitCount}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "DuctBank" };
super.submit (id, obj);
temp = document.getElementById (id + "_circuitCount").value; if ("" !== temp) obj["circuitCount"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["WireSpacingInfos", "0..*", "0..1", "WireSpacingInfo", "DuctBank"]
]
)
);
}
} |
JavaScript | class Cabinet extends AssetContainer
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.Cabinet;
if (null == bucket)
cim_data.Cabinet = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.Cabinet[obj.id];
}
parse (context, sub)
{
let obj = AssetContainer.prototype.parse.call (this, context, sub);
obj.cls = "Cabinet";
let bucket = context.parsed.Cabinet;
if (null == bucket)
context.parsed.Cabinet = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AssetContainer.prototype.export.call (this, obj, false);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Cabinet_collapse" aria-expanded="true" aria-controls="Cabinet_collapse" style="margin-left: 10px;">Cabinet</a></legend>
<div id="Cabinet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetContainer.prototype.template.call (this) +
`
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Cabinet_collapse" aria-expanded="true" aria-controls="{{id}}_Cabinet_collapse" style="margin-left: 10px;">Cabinet</a></legend>
<div id="{{id}}_Cabinet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetContainer.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "Cabinet" };
super.submit (id, obj);
return (obj);
}
} |
JavaScript | class AssetTestLab extends AssetOrganisationRole
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.AssetTestLab;
if (null == bucket)
cim_data.AssetTestLab = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.AssetTestLab[obj.id];
}
parse (context, sub)
{
let obj = AssetOrganisationRole.prototype.parse.call (this, context, sub);
obj.cls = "AssetTestLab";
base.parse_attributes (/<cim:AssetTestLab.LabTestDataSet\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "LabTestDataSet", sub, context);
let bucket = context.parsed.AssetTestLab;
if (null == bucket)
context.parsed.AssetTestLab = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AssetOrganisationRole.prototype.export.call (this, obj, false);
base.export_attributes (obj, "AssetTestLab", "LabTestDataSet", "LabTestDataSet", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetTestLab_collapse" aria-expanded="true" aria-controls="AssetTestLab_collapse" style="margin-left: 10px;">AssetTestLab</a></legend>
<div id="AssetTestLab_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetOrganisationRole.prototype.template.call (this) +
`
{{#LabTestDataSet}}<div><b>LabTestDataSet</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/LabTestDataSet}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["LabTestDataSet"]) obj["LabTestDataSet_string"] = obj["LabTestDataSet"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["LabTestDataSet_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetTestLab_collapse" aria-expanded="true" aria-controls="{{id}}_AssetTestLab_collapse" style="margin-left: 10px;">AssetTestLab</a></legend>
<div id="{{id}}_AssetTestLab_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetOrganisationRole.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "AssetTestLab" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["LabTestDataSet", "0..*", "0..1", "LabTestDataSet", "AssetTestLab"]
]
)
);
}
} |
JavaScript | class Maintainer extends AssetOrganisationRole
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.Maintainer;
if (null == bucket)
cim_data.Maintainer = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.Maintainer[obj.id];
}
parse (context, sub)
{
let obj = AssetOrganisationRole.prototype.parse.call (this, context, sub);
obj.cls = "Maintainer";
let bucket = context.parsed.Maintainer;
if (null == bucket)
context.parsed.Maintainer = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AssetOrganisationRole.prototype.export.call (this, obj, false);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Maintainer_collapse" aria-expanded="true" aria-controls="Maintainer_collapse" style="margin-left: 10px;">Maintainer</a></legend>
<div id="Maintainer_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetOrganisationRole.prototype.template.call (this) +
`
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Maintainer_collapse" aria-expanded="true" aria-controls="{{id}}_Maintainer_collapse" style="margin-left: 10px;">Maintainer</a></legend>
<div id="{{id}}_Maintainer_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetOrganisationRole.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "Maintainer" };
super.submit (id, obj);
return (obj);
}
} |
JavaScript | class AssetOwner extends AssetOrganisationRole
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.AssetOwner;
if (null == bucket)
cim_data.AssetOwner = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.AssetOwner[obj.id];
}
parse (context, sub)
{
let obj = AssetOrganisationRole.prototype.parse.call (this, context, sub);
obj.cls = "AssetOwner";
base.parse_attributes (/<cim:AssetOwner.Ownerships\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Ownerships", sub, context);
let bucket = context.parsed.AssetOwner;
if (null == bucket)
context.parsed.AssetOwner = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AssetOrganisationRole.prototype.export.call (this, obj, false);
base.export_attributes (obj, "AssetOwner", "Ownerships", "Ownerships", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetOwner_collapse" aria-expanded="true" aria-controls="AssetOwner_collapse" style="margin-left: 10px;">AssetOwner</a></legend>
<div id="AssetOwner_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetOrganisationRole.prototype.template.call (this) +
`
{{#Ownerships}}<div><b>Ownerships</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Ownerships}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["Ownerships"]) obj["Ownerships_string"] = obj["Ownerships"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["Ownerships_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetOwner_collapse" aria-expanded="true" aria-controls="{{id}}_AssetOwner_collapse" style="margin-left: 10px;">AssetOwner</a></legend>
<div id="{{id}}_AssetOwner_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetOrganisationRole.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "AssetOwner" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["Ownerships", "0..*", "0..1", "Ownership", "AssetOwner"]
]
)
);
}
} |
JavaScript | class AssetTestSampleTaker extends AssetOrganisationRole
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.AssetTestSampleTaker;
if (null == bucket)
cim_data.AssetTestSampleTaker = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.AssetTestSampleTaker[obj.id];
}
parse (context, sub)
{
let obj = AssetOrganisationRole.prototype.parse.call (this, context, sub);
obj.cls = "AssetTestSampleTaker";
base.parse_attributes (/<cim:AssetTestSampleTaker.Specimen\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Specimen", sub, context);
let bucket = context.parsed.AssetTestSampleTaker;
if (null == bucket)
context.parsed.AssetTestSampleTaker = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AssetOrganisationRole.prototype.export.call (this, obj, false);
base.export_attributes (obj, "AssetTestSampleTaker", "Specimen", "Specimen", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetTestSampleTaker_collapse" aria-expanded="true" aria-controls="AssetTestSampleTaker_collapse" style="margin-left: 10px;">AssetTestSampleTaker</a></legend>
<div id="AssetTestSampleTaker_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetOrganisationRole.prototype.template.call (this) +
`
{{#Specimen}}<div><b>Specimen</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Specimen}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["Specimen"]) obj["Specimen_string"] = obj["Specimen"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["Specimen_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetTestSampleTaker_collapse" aria-expanded="true" aria-controls="{{id}}_AssetTestSampleTaker_collapse" style="margin-left: 10px;">AssetTestSampleTaker</a></legend>
<div id="{{id}}_AssetTestSampleTaker_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetOrganisationRole.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "AssetTestSampleTaker" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["Specimen", "0..*", "0..1", "Specimen", "AssetTestSampleTaker"]
]
)
);
}
} |
JavaScript | class AssetUser extends AssetOrganisationRole
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.AssetUser;
if (null == bucket)
cim_data.AssetUser = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.AssetUser[obj.id];
}
parse (context, sub)
{
let obj = AssetOrganisationRole.prototype.parse.call (this, context, sub);
obj.cls = "AssetUser";
let bucket = context.parsed.AssetUser;
if (null == bucket)
context.parsed.AssetUser = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AssetOrganisationRole.prototype.export.call (this, obj, false);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetUser_collapse" aria-expanded="true" aria-controls="AssetUser_collapse" style="margin-left: 10px;">AssetUser</a></legend>
<div id="AssetUser_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetOrganisationRole.prototype.template.call (this) +
`
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetUser_collapse" aria-expanded="true" aria-controls="{{id}}_AssetUser_collapse" style="margin-left: 10px;">AssetUser</a></legend>
<div id="{{id}}_AssetUser_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AssetOrganisationRole.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "AssetUser" };
super.submit (id, obj);
return (obj);
}
} |
JavaScript | class TestDataSet extends ProcedureDataSet
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.TestDataSet;
if (null == bucket)
cim_data.TestDataSet = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.TestDataSet[obj.id];
}
parse (context, sub)
{
let obj = ProcedureDataSet.prototype.parse.call (this, context, sub);
obj.cls = "TestDataSet";
base.parse_element (/<cim:TestDataSet.conclusion>([\s\S]*?)<\/cim:TestDataSet.conclusion>/g, obj, "conclusion", base.to_string, sub, context);
base.parse_element (/<cim:TestDataSet.specimenID>([\s\S]*?)<\/cim:TestDataSet.specimenID>/g, obj, "specimenID", base.to_string, sub, context);
base.parse_element (/<cim:TestDataSet.specimenToLabDateTime>([\s\S]*?)<\/cim:TestDataSet.specimenToLabDateTime>/g, obj, "specimenToLabDateTime", base.to_datetime, sub, context);
let bucket = context.parsed.TestDataSet;
if (null == bucket)
context.parsed.TestDataSet = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ProcedureDataSet.prototype.export.call (this, obj, false);
base.export_element (obj, "TestDataSet", "conclusion", "conclusion", base.from_string, fields);
base.export_element (obj, "TestDataSet", "specimenID", "specimenID", base.from_string, fields);
base.export_element (obj, "TestDataSet", "specimenToLabDateTime", "specimenToLabDateTime", base.from_datetime, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#TestDataSet_collapse" aria-expanded="true" aria-controls="TestDataSet_collapse" style="margin-left: 10px;">TestDataSet</a></legend>
<div id="TestDataSet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ProcedureDataSet.prototype.template.call (this) +
`
{{#conclusion}}<div><b>conclusion</b>: {{conclusion}}</div>{{/conclusion}}
{{#specimenID}}<div><b>specimenID</b>: {{specimenID}}</div>{{/specimenID}}
{{#specimenToLabDateTime}}<div><b>specimenToLabDateTime</b>: {{specimenToLabDateTime}}</div>{{/specimenToLabDateTime}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_TestDataSet_collapse" aria-expanded="true" aria-controls="{{id}}_TestDataSet_collapse" style="margin-left: 10px;">TestDataSet</a></legend>
<div id="{{id}}_TestDataSet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ProcedureDataSet.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_conclusion'>conclusion: </label><div class='col-sm-8'><input id='{{id}}_conclusion' class='form-control' type='text'{{#conclusion}} value='{{conclusion}}'{{/conclusion}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_specimenID'>specimenID: </label><div class='col-sm-8'><input id='{{id}}_specimenID' class='form-control' type='text'{{#specimenID}} value='{{specimenID}}'{{/specimenID}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_specimenToLabDateTime'>specimenToLabDateTime: </label><div class='col-sm-8'><input id='{{id}}_specimenToLabDateTime' class='form-control' type='text'{{#specimenToLabDateTime}} value='{{specimenToLabDateTime}}'{{/specimenToLabDateTime}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "TestDataSet" };
super.submit (id, obj);
temp = document.getElementById (id + "_conclusion").value; if ("" !== temp) obj["conclusion"] = temp;
temp = document.getElementById (id + "_specimenID").value; if ("" !== temp) obj["specimenID"] = temp;
temp = document.getElementById (id + "_specimenToLabDateTime").value; if ("" !== temp) obj["specimenToLabDateTime"] = temp;
return (obj);
}
} |
JavaScript | class InspectionDataSet extends ProcedureDataSet
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.InspectionDataSet;
if (null == bucket)
cim_data.InspectionDataSet = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.InspectionDataSet[obj.id];
}
parse (context, sub)
{
let obj = ProcedureDataSet.prototype.parse.call (this, context, sub);
obj.cls = "InspectionDataSet";
base.parse_element (/<cim:InspectionDataSet.locationCondition>([\s\S]*?)<\/cim:InspectionDataSet.locationCondition>/g, obj, "locationCondition", base.to_string, sub, context);
base.parse_attributes (/<cim:InspectionDataSet.AccordingToSchedules\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AccordingToSchedules", sub, context);
let bucket = context.parsed.InspectionDataSet;
if (null == bucket)
context.parsed.InspectionDataSet = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ProcedureDataSet.prototype.export.call (this, obj, false);
base.export_element (obj, "InspectionDataSet", "locationCondition", "locationCondition", base.from_string, fields);
base.export_attributes (obj, "InspectionDataSet", "AccordingToSchedules", "AccordingToSchedules", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#InspectionDataSet_collapse" aria-expanded="true" aria-controls="InspectionDataSet_collapse" style="margin-left: 10px;">InspectionDataSet</a></legend>
<div id="InspectionDataSet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ProcedureDataSet.prototype.template.call (this) +
`
{{#locationCondition}}<div><b>locationCondition</b>: {{locationCondition}}</div>{{/locationCondition}}
{{#AccordingToSchedules}}<div><b>AccordingToSchedules</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AccordingToSchedules}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["AccordingToSchedules"]) obj["AccordingToSchedules_string"] = obj["AccordingToSchedules"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["AccordingToSchedules_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_InspectionDataSet_collapse" aria-expanded="true" aria-controls="{{id}}_InspectionDataSet_collapse" style="margin-left: 10px;">InspectionDataSet</a></legend>
<div id="{{id}}_InspectionDataSet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ProcedureDataSet.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_locationCondition'>locationCondition: </label><div class='col-sm-8'><input id='{{id}}_locationCondition' class='form-control' type='text'{{#locationCondition}} value='{{locationCondition}}'{{/locationCondition}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "InspectionDataSet" };
super.submit (id, obj);
temp = document.getElementById (id + "_locationCondition").value; if ("" !== temp) obj["locationCondition"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["AccordingToSchedules", "0..*", "1", "ScheduledEventData", "InspectionDataSet"]
]
)
);
}
} |
JavaScript | class DiagnosisDataSet extends ProcedureDataSet
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.DiagnosisDataSet;
if (null == bucket)
cim_data.DiagnosisDataSet = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.DiagnosisDataSet[obj.id];
}
parse (context, sub)
{
let obj = ProcedureDataSet.prototype.parse.call (this, context, sub);
obj.cls = "DiagnosisDataSet";
base.parse_element (/<cim:DiagnosisDataSet.effect>([\s\S]*?)<\/cim:DiagnosisDataSet.effect>/g, obj, "effect", base.to_string, sub, context);
base.parse_element (/<cim:DiagnosisDataSet.failureMode>([\s\S]*?)<\/cim:DiagnosisDataSet.failureMode>/g, obj, "failureMode", base.to_string, sub, context);
base.parse_element (/<cim:DiagnosisDataSet.finalCause>([\s\S]*?)<\/cim:DiagnosisDataSet.finalCause>/g, obj, "finalCause", base.to_string, sub, context);
base.parse_element (/<cim:DiagnosisDataSet.finalCode>([\s\S]*?)<\/cim:DiagnosisDataSet.finalCode>/g, obj, "finalCode", base.to_string, sub, context);
base.parse_element (/<cim:DiagnosisDataSet.finalOrigin>([\s\S]*?)<\/cim:DiagnosisDataSet.finalOrigin>/g, obj, "finalOrigin", base.to_string, sub, context);
base.parse_element (/<cim:DiagnosisDataSet.finalRemark>([\s\S]*?)<\/cim:DiagnosisDataSet.finalRemark>/g, obj, "finalRemark", base.to_string, sub, context);
base.parse_attribute (/<cim:DiagnosisDataSet.phaseCode\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "phaseCode", sub, context);
base.parse_element (/<cim:DiagnosisDataSet.preliminaryCode>([\s\S]*?)<\/cim:DiagnosisDataSet.preliminaryCode>/g, obj, "preliminaryCode", base.to_string, sub, context);
base.parse_element (/<cim:DiagnosisDataSet.preliminaryDateTime>([\s\S]*?)<\/cim:DiagnosisDataSet.preliminaryDateTime>/g, obj, "preliminaryDateTime", base.to_datetime, sub, context);
base.parse_element (/<cim:DiagnosisDataSet.preliminaryRemark>([\s\S]*?)<\/cim:DiagnosisDataSet.preliminaryRemark>/g, obj, "preliminaryRemark", base.to_string, sub, context);
base.parse_element (/<cim:DiagnosisDataSet.rootCause>([\s\S]*?)<\/cim:DiagnosisDataSet.rootCause>/g, obj, "rootCause", base.to_string, sub, context);
base.parse_element (/<cim:DiagnosisDataSet.rootOrigin>([\s\S]*?)<\/cim:DiagnosisDataSet.rootOrigin>/g, obj, "rootOrigin", base.to_string, sub, context);
base.parse_element (/<cim:DiagnosisDataSet.rootRemark>([\s\S]*?)<\/cim:DiagnosisDataSet.rootRemark>/g, obj, "rootRemark", base.to_string, sub, context);
let bucket = context.parsed.DiagnosisDataSet;
if (null == bucket)
context.parsed.DiagnosisDataSet = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ProcedureDataSet.prototype.export.call (this, obj, false);
base.export_element (obj, "DiagnosisDataSet", "effect", "effect", base.from_string, fields);
base.export_element (obj, "DiagnosisDataSet", "failureMode", "failureMode", base.from_string, fields);
base.export_element (obj, "DiagnosisDataSet", "finalCause", "finalCause", base.from_string, fields);
base.export_element (obj, "DiagnosisDataSet", "finalCode", "finalCode", base.from_string, fields);
base.export_element (obj, "DiagnosisDataSet", "finalOrigin", "finalOrigin", base.from_string, fields);
base.export_element (obj, "DiagnosisDataSet", "finalRemark", "finalRemark", base.from_string, fields);
base.export_attribute (obj, "DiagnosisDataSet", "phaseCode", "phaseCode", fields);
base.export_element (obj, "DiagnosisDataSet", "preliminaryCode", "preliminaryCode", base.from_string, fields);
base.export_element (obj, "DiagnosisDataSet", "preliminaryDateTime", "preliminaryDateTime", base.from_datetime, fields);
base.export_element (obj, "DiagnosisDataSet", "preliminaryRemark", "preliminaryRemark", base.from_string, fields);
base.export_element (obj, "DiagnosisDataSet", "rootCause", "rootCause", base.from_string, fields);
base.export_element (obj, "DiagnosisDataSet", "rootOrigin", "rootOrigin", base.from_string, fields);
base.export_element (obj, "DiagnosisDataSet", "rootRemark", "rootRemark", base.from_string, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#DiagnosisDataSet_collapse" aria-expanded="true" aria-controls="DiagnosisDataSet_collapse" style="margin-left: 10px;">DiagnosisDataSet</a></legend>
<div id="DiagnosisDataSet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ProcedureDataSet.prototype.template.call (this) +
`
{{#effect}}<div><b>effect</b>: {{effect}}</div>{{/effect}}
{{#failureMode}}<div><b>failureMode</b>: {{failureMode}}</div>{{/failureMode}}
{{#finalCause}}<div><b>finalCause</b>: {{finalCause}}</div>{{/finalCause}}
{{#finalCode}}<div><b>finalCode</b>: {{finalCode}}</div>{{/finalCode}}
{{#finalOrigin}}<div><b>finalOrigin</b>: {{finalOrigin}}</div>{{/finalOrigin}}
{{#finalRemark}}<div><b>finalRemark</b>: {{finalRemark}}</div>{{/finalRemark}}
{{#phaseCode}}<div><b>phaseCode</b>: {{phaseCode}}</div>{{/phaseCode}}
{{#preliminaryCode}}<div><b>preliminaryCode</b>: {{preliminaryCode}}</div>{{/preliminaryCode}}
{{#preliminaryDateTime}}<div><b>preliminaryDateTime</b>: {{preliminaryDateTime}}</div>{{/preliminaryDateTime}}
{{#preliminaryRemark}}<div><b>preliminaryRemark</b>: {{preliminaryRemark}}</div>{{/preliminaryRemark}}
{{#rootCause}}<div><b>rootCause</b>: {{rootCause}}</div>{{/rootCause}}
{{#rootOrigin}}<div><b>rootOrigin</b>: {{rootOrigin}}</div>{{/rootOrigin}}
{{#rootRemark}}<div><b>rootRemark</b>: {{rootRemark}}</div>{{/rootRemark}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["phaseCodePhaseCode"] = [{ id: '', selected: (!obj["phaseCode"])}]; for (let property in Core.PhaseCode) obj["phaseCodePhaseCode"].push ({ id: property, selected: obj["phaseCode"] && obj["phaseCode"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["phaseCodePhaseCode"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_DiagnosisDataSet_collapse" aria-expanded="true" aria-controls="{{id}}_DiagnosisDataSet_collapse" style="margin-left: 10px;">DiagnosisDataSet</a></legend>
<div id="{{id}}_DiagnosisDataSet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ProcedureDataSet.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_effect'>effect: </label><div class='col-sm-8'><input id='{{id}}_effect' class='form-control' type='text'{{#effect}} value='{{effect}}'{{/effect}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_failureMode'>failureMode: </label><div class='col-sm-8'><input id='{{id}}_failureMode' class='form-control' type='text'{{#failureMode}} value='{{failureMode}}'{{/failureMode}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_finalCause'>finalCause: </label><div class='col-sm-8'><input id='{{id}}_finalCause' class='form-control' type='text'{{#finalCause}} value='{{finalCause}}'{{/finalCause}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_finalCode'>finalCode: </label><div class='col-sm-8'><input id='{{id}}_finalCode' class='form-control' type='text'{{#finalCode}} value='{{finalCode}}'{{/finalCode}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_finalOrigin'>finalOrigin: </label><div class='col-sm-8'><input id='{{id}}_finalOrigin' class='form-control' type='text'{{#finalOrigin}} value='{{finalOrigin}}'{{/finalOrigin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_finalRemark'>finalRemark: </label><div class='col-sm-8'><input id='{{id}}_finalRemark' class='form-control' type='text'{{#finalRemark}} value='{{finalRemark}}'{{/finalRemark}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_phaseCode'>phaseCode: </label><div class='col-sm-8'><select id='{{id}}_phaseCode' class='form-control custom-select'>{{#phaseCodePhaseCode}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/phaseCodePhaseCode}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_preliminaryCode'>preliminaryCode: </label><div class='col-sm-8'><input id='{{id}}_preliminaryCode' class='form-control' type='text'{{#preliminaryCode}} value='{{preliminaryCode}}'{{/preliminaryCode}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_preliminaryDateTime'>preliminaryDateTime: </label><div class='col-sm-8'><input id='{{id}}_preliminaryDateTime' class='form-control' type='text'{{#preliminaryDateTime}} value='{{preliminaryDateTime}}'{{/preliminaryDateTime}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_preliminaryRemark'>preliminaryRemark: </label><div class='col-sm-8'><input id='{{id}}_preliminaryRemark' class='form-control' type='text'{{#preliminaryRemark}} value='{{preliminaryRemark}}'{{/preliminaryRemark}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_rootCause'>rootCause: </label><div class='col-sm-8'><input id='{{id}}_rootCause' class='form-control' type='text'{{#rootCause}} value='{{rootCause}}'{{/rootCause}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_rootOrigin'>rootOrigin: </label><div class='col-sm-8'><input id='{{id}}_rootOrigin' class='form-control' type='text'{{#rootOrigin}} value='{{rootOrigin}}'{{/rootOrigin}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_rootRemark'>rootRemark: </label><div class='col-sm-8'><input id='{{id}}_rootRemark' class='form-control' type='text'{{#rootRemark}} value='{{rootRemark}}'{{/rootRemark}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "DiagnosisDataSet" };
super.submit (id, obj);
temp = document.getElementById (id + "_effect").value; if ("" !== temp) obj["effect"] = temp;
temp = document.getElementById (id + "_failureMode").value; if ("" !== temp) obj["failureMode"] = temp;
temp = document.getElementById (id + "_finalCause").value; if ("" !== temp) obj["finalCause"] = temp;
temp = document.getElementById (id + "_finalCode").value; if ("" !== temp) obj["finalCode"] = temp;
temp = document.getElementById (id + "_finalOrigin").value; if ("" !== temp) obj["finalOrigin"] = temp;
temp = document.getElementById (id + "_finalRemark").value; if ("" !== temp) obj["finalRemark"] = temp;
temp = Core.PhaseCode[document.getElementById (id + "_phaseCode").value]; if (temp) obj["phaseCode"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#PhaseCode." + temp; else delete obj["phaseCode"];
temp = document.getElementById (id + "_preliminaryCode").value; if ("" !== temp) obj["preliminaryCode"] = temp;
temp = document.getElementById (id + "_preliminaryDateTime").value; if ("" !== temp) obj["preliminaryDateTime"] = temp;
temp = document.getElementById (id + "_preliminaryRemark").value; if ("" !== temp) obj["preliminaryRemark"] = temp;
temp = document.getElementById (id + "_rootCause").value; if ("" !== temp) obj["rootCause"] = temp;
temp = document.getElementById (id + "_rootOrigin").value; if ("" !== temp) obj["rootOrigin"] = temp;
temp = document.getElementById (id + "_rootRemark").value; if ("" !== temp) obj["rootRemark"] = temp;
return (obj);
}
} |
JavaScript | class LabTestDataSet extends ProcedureDataSet
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.LabTestDataSet;
if (null == bucket)
cim_data.LabTestDataSet = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.LabTestDataSet[obj.id];
}
parse (context, sub)
{
let obj = ProcedureDataSet.prototype.parse.call (this, context, sub);
obj.cls = "LabTestDataSet";
base.parse_element (/<cim:LabTestDataSet.conclusion>([\s\S]*?)<\/cim:LabTestDataSet.conclusion>/g, obj, "conclusion", base.to_string, sub, context);
base.parse_element (/<cim:LabTestDataSet.conclusionConfidence>([\s\S]*?)<\/cim:LabTestDataSet.conclusionConfidence>/g, obj, "conclusionConfidence", base.to_string, sub, context);
base.parse_attribute (/<cim:LabTestDataSet.reasonForTest\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "reasonForTest", sub, context);
base.parse_element (/<cim:LabTestDataSet.testEquipmentID>([\s\S]*?)<\/cim:LabTestDataSet.testEquipmentID>/g, obj, "testEquipmentID", base.to_string, sub, context);
base.parse_attribute (/<cim:LabTestDataSet.Specimen\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Specimen", sub, context);
base.parse_attribute (/<cim:LabTestDataSet.AssetTestLab\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetTestLab", sub, context);
let bucket = context.parsed.LabTestDataSet;
if (null == bucket)
context.parsed.LabTestDataSet = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ProcedureDataSet.prototype.export.call (this, obj, false);
base.export_element (obj, "LabTestDataSet", "conclusion", "conclusion", base.from_string, fields);
base.export_element (obj, "LabTestDataSet", "conclusionConfidence", "conclusionConfidence", base.from_string, fields);
base.export_attribute (obj, "LabTestDataSet", "reasonForTest", "reasonForTest", fields);
base.export_element (obj, "LabTestDataSet", "testEquipmentID", "testEquipmentID", base.from_string, fields);
base.export_attribute (obj, "LabTestDataSet", "Specimen", "Specimen", fields);
base.export_attribute (obj, "LabTestDataSet", "AssetTestLab", "AssetTestLab", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#LabTestDataSet_collapse" aria-expanded="true" aria-controls="LabTestDataSet_collapse" style="margin-left: 10px;">LabTestDataSet</a></legend>
<div id="LabTestDataSet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ProcedureDataSet.prototype.template.call (this) +
`
{{#conclusion}}<div><b>conclusion</b>: {{conclusion}}</div>{{/conclusion}}
{{#conclusionConfidence}}<div><b>conclusionConfidence</b>: {{conclusionConfidence}}</div>{{/conclusionConfidence}}
{{#reasonForTest}}<div><b>reasonForTest</b>: {{reasonForTest}}</div>{{/reasonForTest}}
{{#testEquipmentID}}<div><b>testEquipmentID</b>: {{testEquipmentID}}</div>{{/testEquipmentID}}
{{#Specimen}}<div><b>Specimen</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Specimen}}");}); return false;'>{{Specimen}}</a></div>{{/Specimen}}
{{#AssetTestLab}}<div><b>AssetTestLab</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetTestLab}}");}); return false;'>{{AssetTestLab}}</a></div>{{/AssetTestLab}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["reasonForTestTestReason"] = [{ id: '', selected: (!obj["reasonForTest"])}]; for (let property in TestReason) obj["reasonForTestTestReason"].push ({ id: property, selected: obj["reasonForTest"] && obj["reasonForTest"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["reasonForTestTestReason"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_LabTestDataSet_collapse" aria-expanded="true" aria-controls="{{id}}_LabTestDataSet_collapse" style="margin-left: 10px;">LabTestDataSet</a></legend>
<div id="{{id}}_LabTestDataSet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ProcedureDataSet.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_conclusion'>conclusion: </label><div class='col-sm-8'><input id='{{id}}_conclusion' class='form-control' type='text'{{#conclusion}} value='{{conclusion}}'{{/conclusion}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_conclusionConfidence'>conclusionConfidence: </label><div class='col-sm-8'><input id='{{id}}_conclusionConfidence' class='form-control' type='text'{{#conclusionConfidence}} value='{{conclusionConfidence}}'{{/conclusionConfidence}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_reasonForTest'>reasonForTest: </label><div class='col-sm-8'><select id='{{id}}_reasonForTest' class='form-control custom-select'>{{#reasonForTestTestReason}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/reasonForTestTestReason}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testEquipmentID'>testEquipmentID: </label><div class='col-sm-8'><input id='{{id}}_testEquipmentID' class='form-control' type='text'{{#testEquipmentID}} value='{{testEquipmentID}}'{{/testEquipmentID}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Specimen'>Specimen: </label><div class='col-sm-8'><input id='{{id}}_Specimen' class='form-control' type='text'{{#Specimen}} value='{{Specimen}}'{{/Specimen}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetTestLab'>AssetTestLab: </label><div class='col-sm-8'><input id='{{id}}_AssetTestLab' class='form-control' type='text'{{#AssetTestLab}} value='{{AssetTestLab}}'{{/AssetTestLab}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "LabTestDataSet" };
super.submit (id, obj);
temp = document.getElementById (id + "_conclusion").value; if ("" !== temp) obj["conclusion"] = temp;
temp = document.getElementById (id + "_conclusionConfidence").value; if ("" !== temp) obj["conclusionConfidence"] = temp;
temp = TestReason[document.getElementById (id + "_reasonForTest").value]; if (temp) obj["reasonForTest"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#TestReason." + temp; else delete obj["reasonForTest"];
temp = document.getElementById (id + "_testEquipmentID").value; if ("" !== temp) obj["testEquipmentID"] = temp;
temp = document.getElementById (id + "_Specimen").value; if ("" !== temp) obj["Specimen"] = temp;
temp = document.getElementById (id + "_AssetTestLab").value; if ("" !== temp) obj["AssetTestLab"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["Specimen", "0..1", "0..*", "Specimen", "LabTestDataSet"],
["AssetTestLab", "0..1", "0..*", "AssetTestLab", "LabTestDataSet"]
]
)
);
}
} |
JavaScript | class MaintenanceDataSet extends ProcedureDataSet
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.MaintenanceDataSet;
if (null == bucket)
cim_data.MaintenanceDataSet = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.MaintenanceDataSet[obj.id];
}
parse (context, sub)
{
let obj = ProcedureDataSet.prototype.parse.call (this, context, sub);
obj.cls = "MaintenanceDataSet";
base.parse_element (/<cim:MaintenanceDataSet.conditionAfter>([\s\S]*?)<\/cim:MaintenanceDataSet.conditionAfter>/g, obj, "conditionAfter", base.to_string, sub, context);
base.parse_element (/<cim:MaintenanceDataSet.conditionBefore>([\s\S]*?)<\/cim:MaintenanceDataSet.conditionBefore>/g, obj, "conditionBefore", base.to_string, sub, context);
base.parse_element (/<cim:MaintenanceDataSet.maintCode>([\s\S]*?)<\/cim:MaintenanceDataSet.maintCode>/g, obj, "maintCode", base.to_string, sub, context);
let bucket = context.parsed.MaintenanceDataSet;
if (null == bucket)
context.parsed.MaintenanceDataSet = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ProcedureDataSet.prototype.export.call (this, obj, false);
base.export_element (obj, "MaintenanceDataSet", "conditionAfter", "conditionAfter", base.from_string, fields);
base.export_element (obj, "MaintenanceDataSet", "conditionBefore", "conditionBefore", base.from_string, fields);
base.export_element (obj, "MaintenanceDataSet", "maintCode", "maintCode", base.from_string, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#MaintenanceDataSet_collapse" aria-expanded="true" aria-controls="MaintenanceDataSet_collapse" style="margin-left: 10px;">MaintenanceDataSet</a></legend>
<div id="MaintenanceDataSet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ProcedureDataSet.prototype.template.call (this) +
`
{{#conditionAfter}}<div><b>conditionAfter</b>: {{conditionAfter}}</div>{{/conditionAfter}}
{{#conditionBefore}}<div><b>conditionBefore</b>: {{conditionBefore}}</div>{{/conditionBefore}}
{{#maintCode}}<div><b>maintCode</b>: {{maintCode}}</div>{{/maintCode}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_MaintenanceDataSet_collapse" aria-expanded="true" aria-controls="{{id}}_MaintenanceDataSet_collapse" style="margin-left: 10px;">MaintenanceDataSet</a></legend>
<div id="{{id}}_MaintenanceDataSet_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ProcedureDataSet.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_conditionAfter'>conditionAfter: </label><div class='col-sm-8'><input id='{{id}}_conditionAfter' class='form-control' type='text'{{#conditionAfter}} value='{{conditionAfter}}'{{/conditionAfter}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_conditionBefore'>conditionBefore: </label><div class='col-sm-8'><input id='{{id}}_conditionBefore' class='form-control' type='text'{{#conditionBefore}} value='{{conditionBefore}}'{{/conditionBefore}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_maintCode'>maintCode: </label><div class='col-sm-8'><input id='{{id}}_maintCode' class='form-control' type='text'{{#maintCode}} value='{{maintCode}}'{{/maintCode}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "MaintenanceDataSet" };
super.submit (id, obj);
temp = document.getElementById (id + "_conditionAfter").value; if ("" !== temp) obj["conditionAfter"] = temp;
temp = document.getElementById (id + "_conditionBefore").value; if ("" !== temp) obj["conditionBefore"] = temp;
temp = document.getElementById (id + "_maintCode").value; if ("" !== temp) obj["maintCode"] = temp;
return (obj);
}
} |
JavaScript | class AggregateScore extends AnalyticScore
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.AggregateScore;
if (null == bucket)
cim_data.AggregateScore = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.AggregateScore[obj.id];
}
parse (context, sub)
{
let obj = AnalyticScore.prototype.parse.call (this, context, sub);
obj.cls = "AggregateScore";
base.parse_attributes (/<cim:AggregateScore.AnalyticScore\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AnalyticScore", sub, context);
let bucket = context.parsed.AggregateScore;
if (null == bucket)
context.parsed.AggregateScore = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AnalyticScore.prototype.export.call (this, obj, false);
base.export_attributes (obj, "AggregateScore", "AnalyticScore", "AnalyticScore", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AggregateScore_collapse" aria-expanded="true" aria-controls="AggregateScore_collapse" style="margin-left: 10px;">AggregateScore</a></legend>
<div id="AggregateScore_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AnalyticScore.prototype.template.call (this) +
`
{{#AnalyticScore}}<div><b>AnalyticScore</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AnalyticScore}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["AnalyticScore"]) obj["AnalyticScore_string"] = obj["AnalyticScore"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["AnalyticScore_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AggregateScore_collapse" aria-expanded="true" aria-controls="{{id}}_AggregateScore_collapse" style="margin-left: 10px;">AggregateScore</a></legend>
<div id="{{id}}_AggregateScore_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AnalyticScore.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "AggregateScore" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["AnalyticScore", "1..*", "0..1", "AnalyticScore", "AssetAggregateScore"]
]
)
);
}
} |
JavaScript | class RiskScore extends AggregateScore
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.RiskScore;
if (null == bucket)
cim_data.RiskScore = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.RiskScore[obj.id];
}
parse (context, sub)
{
let obj = AggregateScore.prototype.parse.call (this, context, sub);
obj.cls = "RiskScore";
base.parse_attribute (/<cim:RiskScore.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context);
base.parse_attributes (/<cim:RiskScore.AssetHealthScore\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetHealthScore", sub, context);
let bucket = context.parsed.RiskScore;
if (null == bucket)
context.parsed.RiskScore = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AggregateScore.prototype.export.call (this, obj, false);
base.export_attribute (obj, "RiskScore", "kind", "kind", fields);
base.export_attributes (obj, "RiskScore", "AssetHealthScore", "AssetHealthScore", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#RiskScore_collapse" aria-expanded="true" aria-controls="RiskScore_collapse" style="margin-left: 10px;">RiskScore</a></legend>
<div id="RiskScore_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AggregateScore.prototype.template.call (this) +
`
{{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}}
{{#AssetHealthScore}}<div><b>AssetHealthScore</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetHealthScore}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["kindRiskScoreKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in RiskScoreKind) obj["kindRiskScoreKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)});
if (obj["AssetHealthScore"]) obj["AssetHealthScore_string"] = obj["AssetHealthScore"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["kindRiskScoreKind"];
delete obj["AssetHealthScore_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_RiskScore_collapse" aria-expanded="true" aria-controls="{{id}}_RiskScore_collapse" style="margin-left: 10px;">RiskScore</a></legend>
<div id="{{id}}_RiskScore_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AggregateScore.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindRiskScoreKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindRiskScoreKind}}</select></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "RiskScore" };
super.submit (id, obj);
temp = RiskScoreKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#RiskScoreKind." + temp; else delete obj["kind"];
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["AssetHealthScore", "0..*", "0..1", "HealthScore", "AssetRiskScore"]
]
)
);
}
} |
JavaScript | class HealthScore extends AggregateScore
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.HealthScore;
if (null == bucket)
cim_data.HealthScore = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.HealthScore[obj.id];
}
parse (context, sub)
{
let obj = AggregateScore.prototype.parse.call (this, context, sub);
obj.cls = "HealthScore";
base.parse_attribute (/<cim:HealthScore.AssetRiskScore\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetRiskScore", sub, context);
let bucket = context.parsed.HealthScore;
if (null == bucket)
context.parsed.HealthScore = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = AggregateScore.prototype.export.call (this, obj, false);
base.export_attribute (obj, "HealthScore", "AssetRiskScore", "AssetRiskScore", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#HealthScore_collapse" aria-expanded="true" aria-controls="HealthScore_collapse" style="margin-left: 10px;">HealthScore</a></legend>
<div id="HealthScore_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AggregateScore.prototype.template.call (this) +
`
{{#AssetRiskScore}}<div><b>AssetRiskScore</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetRiskScore}}");}); return false;'>{{AssetRiskScore}}</a></div>{{/AssetRiskScore}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_HealthScore_collapse" aria-expanded="true" aria-controls="{{id}}_HealthScore_collapse" style="margin-left: 10px;">HealthScore</a></legend>
<div id="{{id}}_HealthScore_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ AggregateScore.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetRiskScore'>AssetRiskScore: </label><div class='col-sm-8'><input id='{{id}}_AssetRiskScore' class='form-control' type='text'{{#AssetRiskScore}} value='{{AssetRiskScore}}'{{/AssetRiskScore}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "HealthScore" };
super.submit (id, obj);
temp = document.getElementById (id + "_AssetRiskScore").value; if ("" !== temp) obj["AssetRiskScore"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["AssetRiskScore", "0..1", "0..*", "RiskScore", "AssetHealthScore"]
]
)
);
}
} |
JavaScript | class WTSQS {
/**
* Constructs WTSQS object.
* @param {Object} options Options object.
* @param {String} options.url SQS queue url.
* @param {String} [options.accessKeyId] AWS access key id.
* @param {String} [options.secretAccessKey] AWS secret access key.
* @param {String} [options.region=us-east-1] AWS regions where queue exists.
* @param {String} [options.defaultMessageGroupId] FIFO queues only. Default tag assigned to a message that specifies it belongs to a specific message group. If not provided random uuid is assigned to each message which doesn't guarantee order but allows parallelism.
* @param {Integer} [options.defaultVisibilityTimeout=60] Default duration (in seconds) that the received messages are hidden from subsequent retrieve requests.
* @param {Integer} [options.defaultPollWaitTime=10] Default duration (in seconds) for which read calls wait for a message to arrive in the queue before returning.
* @param {Object} [options.sqsOptions] Additional options to extend/override the underlying SQS object creation.
*/
constructor ({
url, accessKeyId, secretAccessKey, region,
defaultMessageGroupId, defaultVisibilityTimeout, defaultPollWaitTime,
sqsOptions
}) {
if (url === undefined) throw new InvalidArgument('url required')
this.url = url
this.accessKeyId = accessKeyId
this.secretAccessKey = secretAccessKey
this.region = region || 'us-east-1'
this.defaultMessageGroupId = defaultMessageGroupId
this.defaultVisibilityTimeout = defaultVisibilityTimeout || 60
this.defaultPollWaitTime = defaultPollWaitTime || 10
this.isFIFO = this.url.endsWith('.fifo')
this.apiVersion = '2012-11-05'
this.sqs = new SQS({
accessKeyId: this.accessKeyId,
secretAccessKey: this.secretAccessKey,
region: this.region,
apiVersion: this.apiVersion,
...sqsOptions
})
}
/**
* Get approximate total number of messages in the queue.
* @return {Promise<integer>}
*
* @example
* const size = await wtsqs.size()
* console.log(size) // output: 2
*/
async size () {
const params = {
QueueUrl: this.url,
AttributeNames: ['ApproximateNumberOfMessages',
'ApproximateNumberOfMessagesNotVisible']
}
const resp = await this.sqs.getQueueAttributes(params).promise()
const size = parseInt(resp.Attributes.ApproximateNumberOfMessages) +
parseInt(resp.Attributes.ApproximateNumberOfMessagesNotVisible, 10)
return size
}
/**
* Enqueue single payload in the queue.
* @param {Object} payload JSON serializable object.
* @param {Object} [options] Options.
* @param {String} [options.messageGroupId] Message group id to override default id.
* @param {Object} [sqsOptions={}] Additional options to extend/override the underlying SQS sendMessage request.
* @return {Promise}
*
* @see {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#sendMessage-property|SQS#sendMessage}
*
* @example
* const myObj = { a: 1 }
* await wtsqs.enqueueOne(myObj)
*/
async enqueueOne (payload, { messageGroupId } = {}, sqsOptions = {}) {
if (payload === undefined) throw new InvalidArgument('payload is required')
const jsonPayload = safeJsonStringify(payload)
const groupId = this.isFIFO
? messageGroupId || this.defaultMessageGroupId || UUIDv4() : undefined
const deduplicationId = this.isFIFO ? UUIDv4() : undefined
const params = {
QueueUrl: this.url,
MessageBody: jsonPayload,
MessageGroupId: groupId,
MessageDeduplicationId: deduplicationId,
...sqsOptions
}
return this.sqs.sendMessage(params).promise()
}
/**
* Enqueue batch of payloads in the queue.
* @param {Array<Object>} payloads Array of JSON serializable objects.
* @param {Object} [options] Options object.
* @param {String} [options.messageGroupId] Message group id to override default id.
* @param {Object} [sqsOptions={}] Additional options to extend/override the underlying SQS sendMessageBatch request.
* @return {Promise}
*
* @see {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#sendMessageBatch-property|SQS#sendMessageBatch}
*
* @example
* const myObjList = [{ a: 1 }, { b: 3 }]
* await wtsqs.enqueueMany(myObjList)
*/
async enqueueMany (payloads, { messageGroupId } = {}, sqsOptions = {}) {
if (!(payloads instanceof Array)) throw new InvalidArgument('payloads must be of type array')
if (payloads.length === 0) return
if (payloads.length > 10) {
const chunks = chunk(payloads, 10)
return Promise.all(chunks.map(
chunk => this.enqueueMany(chunk, { messageGroupId }, sqsOptions)
))
}
const entries = payloads.map((payload) => {
const jsonPayload = safeJsonStringify(payload)
const id = UUIDv4()
const groupId = this.isFIFO
? messageGroupId || this.defaultMessageGroupId || id : undefined
return {
Id: id,
MessageBody: jsonPayload,
MessageGroupId: groupId,
MessageDeduplicationId: id,
...sqsOptions
}
})
const params = {
QueueUrl: this.url,
Entries: entries
}
return this.sqs.sendMessageBatch(params).promise()
}
/**
* Retrieve single message without deleting it.
* @param {Object} [options] Options object.
* @param {Integer} [options.pollWaitTime] Duration (in seconds) for which read call waits for a message to arrive in the queue before returning. If no messages are available and the wait time expires, the call returns successfully with an empty list of messages.
* @param {Integer} [options.visibilityTimeout] Duration (in seconds) that the received messages are hidden from subsequent retrieve requests.
* @param {Object} [sqsOptions={}] Additional options to extend/override the underlying SQS receiveMessage request.
* @return {Promise<Message|null>} Message object or null if queue is empty.
*
* @example
* const myMessage = await wtsqs.peekOne()
* console.log(myMessage)
* // output:
* {
* id: 'messageId',
* receiptHandle: 'messageReceiptHandle'
* md5: 'messageMD5',
* body: { a: 1 }
* }
*/
async peekOne ({ pollWaitTime, visibilityTimeout } = {}, sqsOptions = {}) {
const messages =
await this.peekMany(1, { pollWaitTime, visibilityTimeout }, sqsOptions)
return messages[0] || null
}
/**
* Retrieve batch of messages without deleting them.
* @param {Number} [maxNumberOfMessages=10] Maximum number of messages to retrieve. Must be between 1 and 10.
* @param {Object} [options] Options object.
* @param {Integer} [options.pollWaitTime] Duration (in seconds) for which read call waits for a message to arrive in the queue before returning. If no messages are available and the wait time expires, the call returns successfully with an empty list of messages.
* @param {Integer} [options.visibilityTimeout] Duration (in seconds) that the received messages are hidden from subsequent retrieve requests.
* @param {Object} [sqsOptions={}] Additional options to extend/override the underlying SQS receiveMessage request.
* @return {Promise<Array<Message>>} Array of retrieved messages.
*
* @see {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#receiveMessage-property|SQS#receiveMessage}
*
* @example
* const myMessageList = await wtsqs.peekMany(2)
* console.log(myMessageList)
* // output:
* [
* {
* id: 'messageId',
* receiptHandle: 'messageReceiptHandle'
* md5: 'messageMD5',
* body: { a: 1 }
* },
* {
* id: 'messageId',
* receiptHandle: 'messageReceiptHandle'
* md5: 'messageMD5',
* body: { b: 3 }
* }
* ]
*/
async peekMany (maxNumberOfMessages = 10, { pollWaitTime, visibilityTimeout } = {}, sqsOptions = {}) {
if (maxNumberOfMessages > 10) {
const lengths = chunkNumber(maxNumberOfMessages, 10)
const results = await Promise.all(lengths.map(
l => this.peekMany(l, { pollWaitTime, visibilityTimeout }, sqsOptions)
))
return flatten(results)
}
const params = {
QueueUrl: this.url,
MaxNumberOfMessages: maxNumberOfMessages,
WaitTimeSeconds: pollWaitTime || this.defaultPollWaitTime,
VisibilityTimeout: visibilityTimeout || this.defaultVisibilityTimeout,
MessageAttributeNames: ['All'],
...sqsOptions
}
const receiveResp = await this.sqs.receiveMessage(params).promise()
if (!receiveResp.Messages) return []
return receiveResp.Messages.map((msg) => ({
id: msg.MessageId,
receiptHandle: msg.ReceiptHandle,
md5: msg.MD5OfBody,
body: JSON.parse(msg.Body)
}))
}
/**
* Delete single message from queue.
* @param {Message} message Message to be deleted
* @return {Promise}
*
* @see {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#deleteMessage-property|SQS#deleteMessage}
*
* @example
* const myMessage = await wtsqs.peekOne()
* await wtsqs.deleteOne(myMessage)
*/
async deleteOne (message) {
const params = {
QueueUrl: this.url,
ReceiptHandle: message.receiptHandle
}
return this.sqs.deleteMessage(params).promise()
}
/**
* Delete batch of messages from queue.
* @param {Array<Message>} messages Messages to be deleted
* @return {Promise}
*
* @see {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#deleteMessageBatch-property|SQS#deleteMessageBatch}
*
* @example
* const myMessageList = await wtsqs.peekMany(2)
* await wtsqs.deleteMany(myMessageList)
*/
async deleteMany (messages) {
if (messages.length > 10) {
const chunks = chunk(messages, 10)
return Promise.all(chunks.map(
chunk => this.deleteMany(chunk)
))
}
const entries = messages.map((msg) => ({
Id: msg.id,
ReceiptHandle: msg.receiptHandle
}))
const params = {
QueueUrl: this.url,
Entries: entries
}
return this.sqs.deleteMessageBatch(params).promise()
}
/**
* Delete ALL messages in the queue.
*
* NOTE: Can only be called once every 60 seconds.
*
* @return {Promise}
*
* @see {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#purgeQueue-property|SQS#purgeQueue}
*
* @example
* await wtsqs.deleteAll()
*/
async deleteAll () {
const params = {
QueueUrl: this.url
}
await this.sqs.purgeQueue(params).promise()
}
/**
* Retrieve single message and immediately delete it.
* @param {Object} [options] Options object.
* @param {Integer} [options.pollWaitTime] Duration (in seconds) for which read call waits for a message to arrive in the queue before returning. If no messages are available and the wait time expires, the call returns successfully with an empty list of messages.
* @param {Integer} [options.visibilityTimeout] Duration (in seconds) that the received messages are hidden from subsequent retrieve requests.
* @param {Object} [sqsOptions={}] Additional options to extend/override the underlying SQS receiveMessage request.
* @return {Promise<Message|null>} Message object or null if queue is empty.
*
* @example
* const myMessage = await wtsqs.popOne()
* // The message no longer exists in queue
* console.log(myMessage)
* // output:
* {
* id: 'messageId',
* receiptHandle: 'messageReceiptHandle'
* md5: 'messageMD5',
* body: { a: 1 }
* }
*/
async popOne ({ pollWaitTime, visibilityTimeout } = {}, sqsOptions = {}) {
const message = await this.peekOne({ pollWaitTime, visibilityTimeout }, sqsOptions)
if (!message) return null
await this.deleteOne(message)
return message
}
/**
* Retrieve batch of messages and immediately delete them.
* @param {Number} [maxNumberOfMessages=10] Maximum number of messages to retrieve. Must be between 1 and 10.
* @param {Object} [options] Options object.
* @param {Integer} [options.pollWaitTime] Duration (in seconds) for which read call waits for a message to arrive in the queue before returning. If no messages are available and the wait time expires, the call returns successfully with an empty list of messages.
* @param {Integer} [options.visibilityTimeout] Duration (in seconds) that the received messages are hidden from subsequent retrieve requests.
* @param {Object} [sqsOptions={}] Additional options to extend/override the underlying SQS receiveMessage request.
* @return {Promise<Array<Message>>} Array of retrieved messages.
*
* @example
* const myMessageList = await wtsqs.popMany(2)
* // Messages no longer exist in queue
* console.log(myMessageList)
* // output:
* [
* {
* id: 'messageId',
* receiptHandle: 'messageReceiptHandle'
* md5: 'messageMD5',
* body: { a: 1 }
* },
* {
* id: 'messageId',
* receiptHandle: 'messageReceiptHandle'
* md5: 'messageMD5',
* body: { b: 3 }
* }
* ]
*/
async popMany (maxNumberOfMessages = 10, { pollWaitTime, visibilityTimeout } = {}, sqsOptions = {}) {
const messages = await this.peekMany(maxNumberOfMessages, { pollWaitTime, visibilityTimeout }, sqsOptions)
if (messages.length === 0) return []
await this.deleteMany(messages)
return messages
}
} |
JavaScript | class OAuth2Guild extends BaseGuild {
constructor(client, data) {
super(client, data);
/**
* Whether the client user is the owner of the guild
* @type {boolean}
*/
this.owner = data.owner;
/**
* The permissions that the client user has in this guild
* @type {Readonly<PermissionsBitField>}
*/
this.permissions = new PermissionsBitField(BigInt(data.permissions)).freeze();
}
} |
JavaScript | class IORouterRegistry {
constructor() {
this.saveRouters = [];
this.loadRouters = [];
}
static getInstance() {
if (IORouterRegistry.instance == null) {
IORouterRegistry.instance = new IORouterRegistry();
}
return IORouterRegistry.instance;
}
/**
* Register a save-handler router.
*
* @param saveRouter A function that maps a URL-like string onto an instance
* of `IOHandler` with the `save` method defined or `null`.
*/
static registerSaveRouter(saveRouter) {
IORouterRegistry.getInstance().saveRouters.push(saveRouter);
}
/**
* Register a load-handler router.
*
* @param loadRouter A function that maps a URL-like string onto an instance
* of `IOHandler` with the `load` method defined or `null`.
*/
static registerLoadRouter(loadRouter) {
IORouterRegistry.getInstance().loadRouters.push(loadRouter);
}
/**
* Look up IOHandler for saving, given a URL-like string.
*
* @param url
* @returns If only one match is found, an instance of IOHandler with the
* `save` method defined. If no match is found, `null`.
* @throws Error, if more than one match is found.
*/
static getSaveHandlers(url) {
return IORouterRegistry.getHandlers(url, 'save');
}
/**
* Look up IOHandler for loading, given a URL-like string.
*
* @param url
* @param loadOptions Optional, custom load options.
* @returns All valid handlers for `url`, given the currently registered
* handler routers.
*/
static getLoadHandlers(url, loadOptions) {
return IORouterRegistry.getHandlers(url, 'load', loadOptions);
}
static getHandlers(url, handlerType, loadOptions) {
const validHandlers = [];
const routers = handlerType === 'load' ?
IORouterRegistry.getInstance().loadRouters :
IORouterRegistry.getInstance().saveRouters;
routers.forEach(router => {
const handler = router(url, loadOptions);
if (handler !== null) {
validHandlers.push(handler);
}
});
return validHandlers;
}
} |
JavaScript | class CanvasThumbnailCache {
/**
* Creates an instance of CanvasThumbnailCache.
* @param {Options} [options={}]
*/
constructor({
context = canvasContext("2d", { offscreen: true }).context,
slotSize = 64,
size = 2,
} = {}) {
this.context = context;
this.slotSize = slotSize;
this.initSize = size;
this.reset();
}
// Public
/**
* Reset and clear the canvas size and empty the thumbnails cache.
*/
reset() {
this.size = this.initSize;
this.indices = this.getIndexArray(this.size * this.size);
this.slots = new Map();
this.updateCanvas(true);
}
/**
* Add an image (or anything that can be draw into a 2D canvas) to the cache and return its slot.
* @param {string} key Slots map key
* @param {CanvasImageSource} source HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas
* @returns {Slot}
*/
add(key, source) {
const slot = this.getSlot();
this.drawSource(source, slot);
this.slots.set(key, slot);
return slot;
}
/**
* Get a slot
*
* The slot can also be retrieved with get and the key passed when calling `thumbnailsCache.add(key, source)`.
* @param {string} key
* @returns {Slot}
*/
get(key) {
return this.slots.get(key);
}
/**
* Remove the specified image from the cache and clear its slot.
* @param {string} key
*/
remove(key) {
const slot = this.slots.get(key);
this.clearSlot(slot);
this.indices[slot.x + this.size * slot.y] = null;
this.slots.delete(key);
}
// Data
/**
* @private
*/
getIndexArray(size) {
return new Array(size).fill(null);
}
/**
* @private
*/
getSlot() {
let index = this.indices.findIndex((index) => index === null);
if (index === -1) {
index = this.size;
for (let y = 0; y < this.size; y++) {
this.indices.splice(
y * this.size * 2 + this.size,
0,
...this.getIndexArray(this.size)
);
this.indices.push(...this.getIndexArray(this.size * 2));
}
this.size = this.size * 2;
this.updateCanvas();
}
this.indices[index] = 1;
return {
x: index % this.size,
y: Math.floor(index / this.size),
};
}
// Canvas operations
/**
* @private
*/
updateCanvas(clear) {
const newSize = this.size * this.slotSize;
if (clear) {
this.context.canvas.width = newSize;
this.context.canvas.height = newSize;
} else {
const imageData = this.context.getImageData(
0,
0,
newSize / 2,
newSize / 2
);
this.context.canvas.width = newSize;
this.context.canvas.height = newSize;
this.context.putImageData(imageData, 0, 0);
}
}
/**
* @private
*/
drawSource(image, slot) {
const ratio = image.naturalWidth / image.naturalHeight;
try {
if (ratio > 1) {
this.context.drawImage(
image,
slot.x * this.slotSize,
slot.y * this.slotSize +
this.slotSize / 2 -
this.slotSize / ratio / 2,
this.slotSize,
this.slotSize / ratio
);
} else {
this.context.drawImage(
image,
slot.x * this.slotSize +
this.slotSize / 2 -
(this.slotSize * ratio) / 2,
slot.y * this.slotSize,
this.slotSize * ratio,
this.slotSize
);
}
} catch (error) {
console.error(error);
}
}
/**
* @private
*/
clearSlot(slot) {
this.context.clearRect(slot.x, slot.y, this.slotSize, this.slotSize);
}
} |
JavaScript | class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {term: '' };
}
render() {
return (
<div>
<input
value={this.state.term}
onChange={event => this.setState({term: event.target.value}) } />;
</div>
);
}
} |
JavaScript | class MyElement extends LitElement {
render() {
return html`
<p>Hello world! From my-element</p>
`;
}
} |
JavaScript | class Walker {
// TODO: docs
constructor(walkerFuncs = walkers) {
this._walkers = walkerFuncs;
}
// TODO: docs
_recurse(filename, ast) {
const self = this;
const state = {
filename: filename,
nodes: [],
scopes: [],
};
function logUnknownNodeType({ type }) {
log.debug(
`Found a node with unrecognized type ${type}. Ignoring the node and its descendants.`
);
}
function cb(node, parent, cbState) {
let currentScope;
const isScope = astNode.isScope(node);
astNode.addNodeProperties(node);
node.parent = parent || null;
currentScope = getCurrentScope(cbState.scopes);
if (currentScope) {
node.enclosingScope = currentScope;
}
if (isScope) {
cbState.scopes.push(node);
}
cbState.nodes.push(node);
if (!self._walkers[node.type]) {
logUnknownNodeType(node);
} else {
self._walkers[node.type](node, parent, cbState, cb);
}
if (isScope) {
cbState.scopes.pop();
}
}
cb(ast, null, state);
return state;
}
// TODO: docs
recurse(ast, visitor, filename) {
let shouldContinue;
const state = this._recurse(filename, ast);
if (visitor) {
for (let node of state.nodes) {
shouldContinue = visitor.visit(node, filename);
if (!shouldContinue) {
break;
}
}
}
return ast;
}
} |
JavaScript | class MainLayout extends React.Component {
goto = (pathname) => () => {
const location = this.props.location;
const link = createLink({ location, pathname });
this.props.history.push(link);
}
render() {
return (
<div>
<div className="flex ml3 mr3 mt2">
<div><img src={logo} alt="ClinGen Logo" style={{ width: '80px', height: '60'}}/></div>
<Header className="ml2 mt2 flex-auto" as="h3" color="blue">Variant Prioritization
<Header.Subheader><a href="/" target="_blank" rel="noopener noreferrer">Learn more about this tool</a> <Icon name="external" size="small" /></Header.Subheader>
</Header>
<div>
{ this.renderUserDropdown() }
</div>
</div>
<Divider className="mb0 mt0"/>
{ this.props.children }
<div style={{ height: '100px' }}></div>
</div>);
}
renderUserDropdown() {
const { auth } = this.props;
const isAdmin = auth && auth.groups && auth.groups.length
? auth.groups[0] === 'admin'
: null;
return (
<div className="mt1">
{ isAdmin && <Icon name="user" color="red"/> }
{ !isAdmin && <Icon name="user"/> }
<Dropdown direction="left">
<Dropdown.Menu>
<Dropdown.Item icon="list alternate outline" text="My Exports" onClick={this.goto('/vp/exports')} />
<Dropdown.Item icon="search" disabled text="My Saves Searches" onClick={this.goto('/vp/saves')} />
</Dropdown.Menu>
</Dropdown>
</div>
);
}
} |
JavaScript | class Status {
constructor() {
/** List of allowed values as per Roborock.STATUS_MAP */
this.state = "UNKNOWN";
this.error_code = null;
this.battery = null;
this.clean_time = null; // Seconds?
this.clean_area = null; // mm²
this.error_code = null; // TODO
this.map_present = false; // TODO
this.in_cleaning = 0; // TODO
this.fan_power = null;
this.dnd_enabled = false;
this.lab_status = 0; // 1 = persistent data enabled, else persistent data disabled
this.is_charging = false; // currently only populated for Viomi
this.has_mop = false; // currently only populated for Viomi
this.human_state = "Unknown";
this.human_error = null;
}
} |
JavaScript | class ProductsTable extends React.Component {
static contextType = Context;
constructor(props) {
super(props);
this.products = [];
this.state = this.props.state != null ? this.props.state : {
selectedItems: [],
queryValue: null,
query: null,
sortKey: "TITLE",
reverse: false,
sortDirection: "ascending",
sortColumnIndex: 2,
showDescriptions: true
};
this.queryTimerID = null;
}
/*** RENDER METHOD ***/
render() {
const app = this.context;
const redirectToProduct = (gid) => {
const redirect = Redirect.create(app);
const id = gid.substring(gid.lastIndexOf("/")+1);
redirect.dispatch(
Redirect.Action.ADMIN_SECTION,
{
name: Redirect.ResourceType.Product,
resource: {
id: id
}
}
);
};
return (
<Card>
<Card.Section>
<Filters
queryValue={this.state.queryValue}
filters={[]}
onQueryChange={this.handleFiltersQueryChange}
onQueryClear={this.handleQueryValueRemove}
/>
</Card.Section>
<Query
query={GET_ALL_PRODUCTS}
variables={{
query: this.state.query,
sortKey: this.state.sortKey,
reverse: this.state.reverse
}}
>
{({ data, loading, error }) => {
if (loading) return this.loadingLayout();
if (error) { console.log(error); return <div>{error.message}</div> };
//console.log(data);
this.products = data.products.edges.map(edge => edge.node);
const rows = this.products.map(product => [
<Checkbox
label={`Select ${product.title}`}
labelHidden={true}
id={product.id}
checked={this.state.selectedItems.includes(product.id)}
onChange={this.handleSelection}
/>,
<Thumbnail
source={
product.images.edges[0]
? product.images.edges[0].node.originalSrc
: ''
}
alt={
product.images.edges[0]
? product.images.edges[0].node.altText
: ''
}
size="small"
/>,
<Button plain onClick={() => redirectToProduct(product.id)}><TextStyle variation="strong">{product.title}</TextStyle></Button>,
<span>
{product.totalInventory > 0 ? product.totalInventory : <TextStyle variation="negative">{product.totalInventory}</TextStyle>} in stock
{product.totalVariants > 1 ? ` for ${product.totalVariants} variants` : null}
</span>,
product.productType,
product.vendor,
product.tags.length > 0 ? product.tags.join(', ') : ''
]);
const descriptions = this.products.map(product => product.descriptionHtml);
return this.dataTableLayout(rows, descriptions);
}}
</Query>
</Card>
);
}
/*** STATE/LAYOUT METHODS */
loadingLayout() {
return (
<Fragment>
<Loading />
<Card.Section>
<SkeletonBodyText lines={2} />
</Card.Section>
<Card.Section>
<SkeletonBodyText lines={2} />
</Card.Section>
<Card.Section>
<SkeletonBodyText lines={2} />
</Card.Section>
</Fragment>
);
}
dataTableLayout(rows, descriptions) {
return (
<div className="data-table">
<SettingToggle
action={{
content: this.state.showDescriptions ? 'Hide Descriptions' : 'Show Descriptions',
onAction: this.toggleShowDescriptions,
}}
enabled={this.state.showDescriptions}
>
{this.state.selectedItems.length == 0 ?
`Showing ${descriptions.length} ${descriptions.length > 1 ? 'products' : 'product'}.` :
`${this.state.selectedItems.length} of ${descriptions.length} ${descriptions.length > 1 ? 'products' : 'product'} selected.`
}<br/>
Product descriptions are {this.state.showDescriptions ? 'being displayed below each product row' : 'hidden'}.
</SettingToggle>
<DataTableWithProductDescription
columnContentTypes={[
'text',
'text',
'text',
'text',
'text',
'text',
'text'
]}
headings={[
<Tooltip content="Select all products" preferredPosition="above">
<Button
size="slim"
disclosure
onClick={() => this.handleSelectAll(!(this.state.selectedItems.length == this.products.length))}
>
<Checkbox
label="Select all Products"
labelHidden={true}
id="selectAllProducts"
checked={this.isSelectAll()}
onChange={this.handleSelectAll}
/>
</Button>
</Tooltip>,
'',
'Product',
'Inventory',
'Type',
'Vendor',
'Tags'
]}
rows={rows}
descriptions={descriptions}
verticalAlign="middle"
sortable={[false, false, true, true, true, true, false]}
defaultSortDirection={this.state.sortDirection}
initialSortColumnIndex={this.state.sortColumnIndex}
showDescriptions={this.state.showDescriptions}
onSort={this.handleSort}
/>
<Card.Section>
<Stack>
<Stack.Item fill>
{this.state.selectedItems.length == 0 ?
'Please select some products to continue' :
`${this.state.selectedItems.length} of ${descriptions.length} ${descriptions.length > 1 ? 'products' : 'product'} selected`
}
</Stack.Item>
<Stack.Item>
<Button primary disabled={this.state.selectedItems.length == 0} onClick={this.handleContinue}>Continue ></Button>
</Stack.Item>
</Stack>
</Card.Section>
</div>
);
}
isSelectAll() {
if (this.state.selectedItems.length == 0) {
return false;
} else if (this.state.selectedItems.length == this.products.length) {
return true;
} else {
return "indeterminate";
}
}
updateQuery() {
this.setState({ query: this.state.queryValue });
}
/*** EVENT HANDLERS ***/
handleFiltersQueryChange = (value) => {
if (this.queryTimerID != null) {
clearTimeout(this.queryTimerID);
this.queryTimerID = null;
}
this.queryTimerID = setTimeout(
() => {
this.queryTimerID = null;
this.updateQuery();
},
500
);
this.setState({ queryValue: value });
};
handleQueryValueRemove = () => {
this.setState({ queryValue: null });
setTimeout(() => this.updateQuery(), 100);
};
handleSort = (index, direction) => {
let sortKey = "TITLE";
switch (index) {
case 3:
sortKey = "INVENTORY_TOTAL";
break;
case 4:
sortKey = "PRODUCT_TYPE";
break;
case 5:
sortKey = "VENDOR";
break;
default:
sortKey = "TITLE";
}
const reverse = (direction == "descending");
this.setState({
sortKey: sortKey,
reverse: reverse,
sortColumnIndex: index,
sortDirection: direction
});
};
handleSelection = (newChecked, id) => {
if (newChecked) {
this.setState({ selectedItems: this.state.selectedItems.concat([id]) });
} else {
this.setState({ selectedItems: this.state.selectedItems.filter(item => item != id) });
}
};
handleSelectAll = (newChecked) => {
if (newChecked) {
this.setState({ selectedItems: this.products.map(product => product.id) });
} else {
this.setState({ selectedItems: [] });
}
};
toggleShowDescriptions = () => {
this.setState({ showDescriptions: !this.state.showDescriptions });
}
handleContinue = () => {
if (this.props.onProductsSelected) {
const selectedProducts = this.products.filter((product) => this.state.selectedItems.indexOf(product.id) != -1);
this.props.onProductsSelected(selectedProducts, this.state);
}
}
} |
JavaScript | class EvpKDF extends BaseKDFModule {
constructor(props) {
super(props);
this._keySize = 128 / 32;
this._Hasher = MD5;
this._iterations = 1;
if (props) {
this._keySize = typeof props.keySize !== "undefined" ? props.keySize : this._keySize;
this._Hasher = typeof props.Hasher !== "undefined" ? props.Hasher : this._Hasher;
this._iterations = typeof props.iterations !== "undefined" ? props.iterations : this._iterations;
}
}
/**
* Derives a key from a password.
*
* @param {Word32Array|string} password The password.
* @param {Word32Array|string} salt A salt.
* @return {Word32Array} The derived key.
* @example
* var kdf = new EvpKDF();
* var key = kdf.compute(password, salt);
*/
compute(password, salt) {
let block;
// Init hasher
const hasher = new this._Hasher();
// Initial values
const derivedKey = new Word32Array();
// Shortcuts
const derivedKeyWords = derivedKey.words;
const keySize = this._keySize;
const iterations = this._iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (let i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.nSigBytes = keySize * 4;
return derivedKey;
}
/**
* Derives a key from a password.
*
* @param {Word32Array|string} password The password.
* @param {Word32Array|string} salt A salt.
* @param {Partial<EvpKDFProps>?} props (Optional) The configuration options to use for this computation.
* @return {Word32Array} The derived key.
* @static
* @example
*
* var key = EvpKDF.getKey(password, salt);
* var key = EvpKDF.getKey(password, salt, { keySize: 8 });
* var key = EvpKDF.getKey(password, salt, { keySize: 8, iterations: 1000 });
*/
static getKey(password, salt, props) {
return new EvpKDF(props).compute(password, salt);
}
} |
JavaScript | class Collection {
constructor(db, collectionName) {
this.db = db; // parent DB object
this.name = collectionName;
this._method = '';
this._action = '';
this._debug = this.db._debug;
this._debugData = [];
this.resetQuery();
this._transactionID = null;
}
beginTransaction() {
var that = this;
this._method = 'POST';
this._action = '/_query';
return Promise.resolve(that._execute('BEGIN_TRANSACTION'))
.then(response => {
that._transactionID = response.transactionId();
return that;
});
}
commit() {
var that = this;
this._method = 'POST';
this._action = '/_query';
return Promise.resolve(that._execute('COMMIT'))
.then(response => {
that._transactionID = null;
return that;
});
}
rollback() {
var that = this;
this._method = 'POST';
this._action = '/_query';
return Promise.resolve(that._execute('ROLLBACK'))
.then(response => {
that._transactionID = null;
return that;
});
}
resetQuery() {
this._queryPieces = {};
this._queryPieces.prepend = '';
this._queryPieces.select = ' * ';
this._queryPieces.where = '';
this._queryPieces.orderBy = [];
this._queryPieces.groupBy = [];
this._queryPieces.offset = 0;
this._queryPieces.limit = 20;
this._queryPieces.listWords = false;
this._queryPieces.alternatives = false;
return this;
}
get() {
var from = this.name;
if (this._queryPieces.listWords !== false) {
if (this._queryPieces.listWords === '') {
from = 'LIST_WORDS(' + from + ')';
} else {
from = 'LIST_WORDS(' + from + '.' + this._queryPieces.listWords + ')';
}
}
if (this._queryPieces.alternatives !== false) {
if (this._queryPieces.alternatives === '') {
from = 'ALTERNATIVES(' + from + ')';
} else {
from = 'ALTERNATIVES(' + from + '.' + this._queryPieces.alternatives + ')';
}
}
var where = '';
if (this._queryPieces.where.length > 0) {
where = ' WHERE ' + this._queryPieces.where;
}
var groupBy = '';
if (this._queryPieces.groupBy.length > 0) {
groupBy = ' GROUP BY ' + this._queryPieces.groupBy.join(', ');
}
var orderBy = '';
if (this._queryPieces.orderBy.length > 0) {
orderBy = ' ORDER BY ' + this._queryPieces.orderBy.join(', ');
}
var sql = (this._queryPieces.prepend.length > 0 ? this._queryPieces.prepend + ' ' : '') + 'SELECT ' + this._queryPieces.select.trim() + ' FROM ' + from + where + groupBy + orderBy + ' LIMIT ' + (this._queryPieces.offset > 0 ? this._queryPieces.offset + ', ' : '') + this._queryPieces.limit;
this._method = 'POST';
this._action = '/_query';
return this._execute(sql);
}
listWords(word, field) {
if (typeof(field) === 'undefined') field = false;
this.where('word', '==', word);
this._queryPieces.listWords = '';
if (field !== false) {
this._queryPieces.listWords = field;
}
return this;
}
alternatives(word, field) {
if (typeof(field) === 'undefined') field = false;
this.where('word', '==', word);
this._queryPieces.alternatives = '';
if (field !== false) {
this._queryPieces.alternatives = field;
}
return this;
}
first() {
this._method = 'POST';
this._action = '/_query';
this.limit(1);
this.offset(0);
return this.get('');
}
/**
* @param data {string}
* @returns {Collection}
*/
prepend(data) {
this._queryPieces.prepend += data;
return this;
}
/**
* @param data {string}
* @returns {Collection}
*/
select(data) {
if (typeof data === 'string') {
this._queryPieces.select = data;
}
if (Array.isArray(data)) {
this._queryPieces.select = data.join(', ');
return this; // array is an object in JS, we need to return now!
}
if (typeof data === 'object') {
var tmp = [];
for (var i = 0, k = Object.keys(data), l = k.length; i < l; i++) {
tmp.push(k[i] + ' AS ' + data[k[i]]);
}
this._queryPieces.select = tmp.join(', ');
}
return this;
}
/**
*
* @param field {string}
* @param operator {string}
* @param value {string}
* @param logical {string}
* @returns {Collection}
*/
where(field, operator, value, logical) {
if (typeof(logical) === 'undefined') logical = '&&';
if (this._queryPieces.where.length > 0) {
this._queryPieces.where += ' ' + logical + ' ';
}
if (typeof operator === 'undefined' && typeof value === 'undefined') {
// raw
this._queryPieces.where += field;
return this;
}
if (typeof value === 'undefined') {
// default operator
this._queryPieces.where += field + ' == ' + this.db.cp.escape(operator);
return this;
}
this._queryPieces.where += field + ' ' + operator + ' ' + this.db.cp.escape(value);
return this;
}
/**
*
* @param field {string}
* @param operator {string}
* @param value {string}
* @returns {Collection}
*/
orWhere(field, operator, value) {
return this.where(field, operator, value, '||');
}
/**
*
* @param field {string}
* @param [order=ASC] {string}
* @returns {Collection}
*/
orderBy(field, order) {
if (typeof(order) === 'undefined') order = 'DESC';
this._queryPieces.orderBy.push(field + ' ' + order);
return this;
}
/**
*
* @param field {string}
* @returns {Collection}
*/
groupBy(field) {
this._queryPieces.groupBy.push(field);
return this;
}
/**
*
* @param limit {int}
* @returns {Collection}
*/
limit(limit) {
this._queryPieces.limit = limit;
return this;
}
/**
*
* @param offset {int}
* @returns {Collection}
*/
offset(offset) {
this._queryPieces.offset = offset;
return this;
}
/**
*
* @param doc mixed
* @returns {Response}
*/
insertOne(doc) {
this._method = 'POST';
this._action = '';
return this._execute(doc);
}
/**
*
* @param docsArr {array}
* @returns {Response}
*/
insertMany(docsArr) {
this._method = 'POST';
this._action = '';
return this._execute(docsArr);
}
/**
*
* @param id {string}
* @returns {Response}
*/
deleteOne(id) {
return this.deleteMany([id]);
}
/**
*
* @param ids {array}
* @returns {Response}
*/
deleteMany(ids) {
this._action = '';
this._method = 'DELETE';
// force strings! REST hates DELETE with ints for now...
for (var i = 0, l = ids.length; i < l; i++) {
ids[i] = ids[i] + '';
}
return this._execute(ids);
}
/**
*
* @param id {string}
* @returns {Document}
*/
find(id) {
this._method = 'GET';
this._action = '[' + encodeURIComponent(id) + ']';
return this._execute('', true);
}
/**
* Replace single document
* @param id {string}
* @param doc {mixed}
* @returns {Response}
*/
replace(id, doc) {
this._method = 'PUT';
this._action = '[' + encodeURIComponent(id) + ']';
return this._execute(doc);
}
/**
* Update single document
* @param id {string}
* @param data {mixed}
* @returns {Response}
*/
update(id, data) {
this._method = 'POST';
this._action = '/_query';
var query = 'UPDATE ' + this.name + '["' + encodeURIComponent(id) + '"] SET { ';
if (typeof data === 'string') {
query += data;
}
else {
// object
query += this._prepareDeepFieldUpdate(data, '').join(', ');
}
query += ' }';
return this._execute(query);
}
/**
* Execute raw query
* @param query {string}
* @returns {Response}
*/
raw(query) {
this._method = 'POST';
this._action = '/_query';
return this._execute(query);
}
/**
* Get status about collection
* @returns {Response}
*/
getStatus() {
this._method = 'GET';
this._action = '/_status';
return this._execute('');
}
/**
* Enable/disable debug data collecting
* @param [debug=true] {boolean}
*/
setDebug(debug) {
if (typeof(debug) === 'undefined') debug = true;
this._debug = debug;
}
getDebug() {
return this._debugData;
}
describe() {
var data = 'DESCRIBE COLLECTION ' + this.db.name + '.' + this.name;
var tmpConfig = this.db.cp._config;
var options = {
hostname: tmpConfig.host,
port : tmpConfig.port ? tmpConfig.port : 443,
path : '/v4/' + tmpConfig.account_id,
method : 'POST',
auth : tmpConfig.username + ':' + tmpConfig.password
};
return new Transporter({
'that' : this,
'options': options,
'data' : data
});
}
reindex(options) {
if (typeof(options) === 'undefined') options = {};
var data = 'REINDEX COLLECTION ' + this.db.name + '.' + this.name;
if (typeof options.inBackground !== 'undefined') {
data += ' IN BACKGROUND ';
}
if (typeof options.shard !== 'undefined') {
data += ' SHARD ' + options.shard;
}
if (typeof options.node !== 'undefined') {
data += ' NODE ' + options.node;
}
var tmpConfig = this.db.cp._config;
var options = {
hostname: tmpConfig.host,
port : tmpConfig.port ? tmpConfig.port : 443,
path : '/v4/' + tmpConfig.account_id,
method : 'POST',
auth : tmpConfig.username + ':' + tmpConfig.password
};
return new Transporter({
'that' : this,
'options': options,
'data' : data
});
}
clear() {
var data = 'CLEAR COLLECTION ' + this.db.name + '.' + this.name;
var tmpConfig = this.db.cp._config;
var options = {
hostname: tmpConfig.host,
port : tmpConfig.port ? tmpConfig.port : 443,
path : '/v4/' + tmpConfig.account_id,
method : 'POST',
auth : tmpConfig.username + ':' + tmpConfig.password
};
return new Transporter({
'that' : this,
'options': options,
'data' : data
});
}
_prepareDeepFieldUpdate(obj, stack) {
var output = [];
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
switch (typeof obj[property]) {
case 'object':
if (!obj[property]) { // check for null which is object
output.push((stack == '' ? '' : stack + '.') + property + ' = null');
}
else {
if( Object.prototype.toString.call( obj[property] ) === '[object Array]' ) {
output.push((stack == '' ? '' : stack + '.') + property + ' = ' + JSON.stringify(obj[property]));
}
else{
output = output.concat(this._prepareDeepFieldUpdate(obj[property], (stack == '' ? '' : stack + '.') + property));
}
}
break;
default:
output.push((stack == '' ? '' : stack + '.') + property + ' = ' + this.db.cp.escape(obj[property]));
break;
}
}
}
return output;
}
_execute(data, returnAsDocument) {
if (typeof(returnAsDocument) === 'undefined') returnAsDocument = false;
if (typeof data !== 'string') {
data = JSON.stringify(data);
}
var tmpConfig = this.db.cp._config;
var options = {
hostname: tmpConfig.host,
port : tmpConfig.port ? tmpConfig.port : 443,
path : '/v4/' + tmpConfig.account_id + '/' + this.db.name + '.' + this.name + this._action + (this._transactionID !== null ? '?transaction_id=' + this._transactionID : ''),
method : this._method,
auth : tmpConfig.username + ':' + tmpConfig.password
};
//Nodejs adds Transfer-Encoding: chunked header to such DELETE request. And this header was causing "data not received on the REST side"
if (this._method === 'DELETE') {
options.headers = {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length': data.length
}
}
this.resetQuery();
return new Transporter({
'that' : this,
'options' : options,
'data' : data,
'returnAsDocument': returnAsDocument
});
}
} |
JavaScript | class AddMoney extends Command {
/**
* Creates an instance of AddMoney
*
* @param {string} file
*/
constructor(file) {
super(file);
}
/**
* Give money to a member
*
* @param {Message} message
* @param {string[]} args
*/
async run(message, args) {
let amount = Number(args.pop());
if (!Number.isInteger(amount) || amount <= 0) {
message.reply(bot.lang.invalidArguments);
return;
}
let member = message.mentions.members.first() || message.member;
if (!member) {
message.reply(bot.lang.cantFindUser);
return;
}
member.giveMoney(amount);
let { addMoney: format } = bot.lang,
embed = new MessageEmbed()
.setTitle(format.title)
.setAuthor(message.author.tag, message.author.displayAvatarURL())
.setThumbnail(member.user.displayAvatarURL())
.setColor(bot.consts.COLOR.ADDMONEY_EMBED)
.addFields(
{
name: format.amount.name,
value: amount,
inline: true
},
{
name: format.balance.name,
value: member.info.money,
inline: true
}
);
message.channel.send(embed);
}
} |
JavaScript | class Balance extends React.PureComponent {
static propTypes = {
/** Should component show overall balance by default */
summary: PropTypes.bool,
/** Current account index, where -1 is total balance */
index: PropTypes.number,
/** Switch Balance account
* @param {number} index - target account index
*/
switchAccount: PropTypes.func,
/** @ignore */
seedIndex: PropTypes.number.isRequired,
/** @ignore */
accounts: PropTypes.object.isRequired,
/** Wallet account names */
accountNames: PropTypes.array.isRequired,
/** @ignore */
settings: PropTypes.object.isRequired,
/** @ignore */
marketData: PropTypes.object.isRequired,
/** @ignore */
t: PropTypes.func.isRequired,
};
state = {
balanceIsShort: true,
};
componentWillReceiveProps(newProps) {
if (newProps.index !== this.props.index || newProps.seedIndex !== this.props.seedIndex) {
this.setState({ balanceIsShort: true });
}
}
getDecimalPlaces(n) {
const s = `+${n}`;
const match = /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(s);
if (!match) {
return 0;
}
return Math.max(0, (match[1] === '0' ? 0 : (match[1] || '').length) - (match[2] || 0));
}
render() {
const {
summary,
index,
accounts,
accountNames,
switchAccount,
seedIndex,
settings,
marketData,
t,
} = this.props;
const { balanceIsShort } = this.state;
const accountName = summary && index === -1 ? t('totalBalance') : accountNames[summary ? index : seedIndex];
const accountBalance =
summary && index === -1
? Object.entries(accounts.accountInfo).reduce((total, account) => total + account[1].balance, 0)
: accounts.accountInfo[accountName].balance;
const currencySymbol = getCurrencySymbol(settings.currency);
const fiatBalance = round(accountBalance * marketData.usdPrice / 1000000 * settings.conversionRate, 2).toFixed(
2,
);
const balance = !balanceIsShort
? formatValue(accountBalance)
: roundDown(formatValue(accountBalance), 1) +
(accountBalance < 1000 || this.getDecimalPlaces(formatValue(accountBalance)) <= 1 ? '' : '+');
return (
<div className={css.balance}>
<h3>{accountName}</h3>
{summary && (
<React.Fragment>
<a onClick={() => switchAccount(index + 1)}>
<Icon icon="chevronLeft" size={18} />
</a>
<a onClick={() => switchAccount(index - 1)}>
<Icon icon="chevronRight" size={18} />
</a>
</React.Fragment>
)}
<h1 onClick={() => this.setState({ balanceIsShort: !balanceIsShort })}>
{`${balance}`}
<small>{`${formatUnit(accountBalance)}`}</small>
</h1>
<h2>{`${currencySymbol} ${fiatBalance}`}</h2>
</div>
);
}
} |
JavaScript | class NetworkHandler {
/**
* Constructor
*
* @param {Object} declaration - Parsed declaration.
* @param {Object} bigIp - BigIp object.
* @param {EventEmitter} - DO event emitter.
* @param {State} - The doState.
*/
constructor(declaration, bigIp, eventEmitter, state) {
this.declaration = declaration;
this.bigIp = bigIp;
this.eventEmitter = eventEmitter;
this.state = state;
}
/**
* Starts processing.
*
* @returns {Promise} A promise which is resolved when processing is complete
* or rejected if an error occurs.
*/
process() {
logger.fine('Proessing network declaration.');
logger.fine('Checking Trunks.');
return handleTrunk.call(this)
.then(() => {
logger.fine('Checking VLANs.');
return handleVlan.call(this);
})
.then(() => {
logger.fine('Checking RouteDomains.');
return handleRouteDomain.call(this);
})
.then(() => {
logger.fine('Checking SelfIps.');
return handleSelfIp.call(this);
})
.then(() => {
logger.fine('Checking Routes.');
return handleRoute.call(this);
})
.then(() => {
logger.fine('Checking DagGlobals');
return handleDagGlobals.call(this);
})
.then(() => {
logger.info('Done processing network declartion.');
return Promise.resolve();
})
.catch((err) => {
logger.severe(`Error processing network declaration: ${err.message}`);
return Promise.reject(err);
});
}
} |
JavaScript | class DialogResponse {
/**
* Create a DialogResponse.
* @member {string} [prompt] Prompt that should be asked.
* @member {string} [parameterName] Name of the parameter.
* @member {string} [parameterType] Type of the parameter.
* @member {string} [contextId] The context id for dialog.
* @member {string} [status] The dialog status. Possible values include:
* 'Question', 'Finished'
*/
constructor() {
}
/**
* Defines the metadata of DialogResponse
*
* @returns {object} metadata of DialogResponse
*
*/
mapper() {
return {
required: false,
serializedName: 'DialogResponse',
type: {
name: 'Composite',
className: 'DialogResponse',
modelProperties: {
prompt: {
required: false,
serializedName: 'prompt',
type: {
name: 'String'
}
},
parameterName: {
required: false,
serializedName: 'parameterName',
type: {
name: 'String'
}
},
parameterType: {
required: false,
serializedName: 'parameterType',
type: {
name: 'String'
}
},
contextId: {
required: false,
serializedName: 'contextId',
type: {
name: 'String'
}
},
status: {
required: false,
serializedName: 'status',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class ChatFrame extends React.Component{
componentDidUpdate(){
// scroll message container div to the bottom
this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
}
render(){
return (
<div className="card h-100">
<div className="card-header text-center">
<h5 className="m-0" >{this.props.activeChat}</h5>
</div>
<div className="card-body scrollable w-100" ref={(node) => {this.messageContainer = node}} >
{
this.props.messageList.map((msg, i) =>
<ChatBubble {...msg} key={i.toString()} />)
}
</div>
<div className="card-footer">
<ChatMessageForm />
</div>
</div>
)
}
} |
JavaScript | class DepthCalculator {
calculateDepth( arr ) {
let result= 1;
for (let i=0; i< arr.length; i++) {
if (Array.isArray(arr[i])) {
let chejk = this.calculateDepth(arr[i]);
if (result <chejk+1) result=chejk+1;
}
}
return result;
}
} |
JavaScript | class XmlNode {
constructor() {
/**
Parent node of this node, or `null` if this node has no parent.
@type {XmlDocument|XmlElement|null}
@public
*/
this.parent = null;
}
/**
Document that contains this node, or `null` if this node is not associated
with a document.
@type {XmlDocument?}
@public
*/
get document() {
return this.parent
? this.parent.document
: null;
}
/**
Whether this node is the root node of the document.
@returns {boolean}
@public
*/
get isRootNode() {
return this.parent
? this.parent === this.document
: false;
}
/**
Whether whitespace should be preserved in the content of this element and
its children.
This is influenced by the value of the special `xml:space` attribute, and
will be `true` for any node whose `xml:space` attribute is set to
"preserve". If a node has no such attribute, it will inherit the value of
the nearest ancestor that does (if any).
@type {boolean}
@see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-white-space
@public
*/
get preserveWhitespace() {
return Boolean(this.parent && this.parent.preserveWhitespace);
}
/**
Type of this node.
The value of this property is a string that matches one of the static `TYPE_*`
properties on the `XmlNode` class (e.g. `TYPE_ELEMENT`, `TYPE_TEXT`, etc.).
The `XmlNode` class itself is a base class and doesn't have its own type name.
@type {string}
@public
*/
get type() {
return '';
}
/**
Returns a JSON-serializable object representing this node, minus properties
that could result in circular references.
@returns {{[key: string]: any}}
@public
*/
toJSON() {
/** @type {{[key: string]: any}} */
let json = {
type: this.type
};
if (this.isRootNode) {
json.isRootNode = true;
}
if (this.preserveWhitespace) {
json.preserveWhitespace = true;
}
return json;
}
} |
JavaScript | class Validator extends objection.Validator {
constructor({ options, keywords, formats } = {}) {
super()
this.options = {
...defaultOptions,
...options
}
this.keywords = {
...schema.keywords,
...keywords
}
this.formats = {
...schema.formats,
...formats
}
this.schemas = []
// Dictionary to hold all created Ajv instances, using the stringified
// options with which they were created as their keys.
this.ajvCache = Object.create(null)
}
createAjv(options) {
// Split options into native Ajv options and our additions (async, patch):
const { async, patch, ...opts } = options
const ajv = new Ajv({
...this.options,
...opts,
// Patch-validators don't use default values:
...(patch && { useDefaults: false })
})
addFormats(ajv, { mode: 'full' })
const addSchemas = (schemas, callback) => {
for (const [name, schema] of Object.entries(schemas)) {
if (schema) {
// Remove leading '_' to simplify special keywords (e.g. instanceof)
callback(name.replace(/^_/, ''), schema)
}
}
}
addSchemas(this.keywords, (keyword, schema) => ajv.addKeyword({
keyword,
...schema
}))
addSchemas(this.formats, (format, schema) => ajv.addFormat(format, {
...schema
}))
// Also add all model schemas that were already compiled so far.
for (const schema of this.schemas) {
ajv.addSchema(this.processSchema(schema, options))
}
return ajv
}
getAjv(options = {}) {
// Cache Ajv instances by keys that represent their options. For improved
// matching, convert options to a version with all default values missing:
const opts = Object.entries(options).reduce((opts, [key, value]) => {
if (key in validatorOptions && value !== validatorOptions[key]) {
opts[key] = value
}
return opts
}, {})
const cacheKey = JSON.stringify(opts)
const { ajv } = this.ajvCache[cacheKey] || (this.ajvCache[cacheKey] = {
ajv: this.createAjv(opts),
options
})
return ajv
}
compile(jsonSchema, options = {}) {
const ajv = this.getAjv(options)
const validator = ajv.compile(this.processSchema(jsonSchema, options))
// Assume `options.throw = true` as the default.
const dontThrow = options.throw === false
return options.async
// For async:
? dontThrow
? async function validate(data) {
// Emulate `options.throw == false` behavior for async validation:
// Return `true` or `false`, and store errors on `validate.errors`
// if validation failed.
let result
try {
// Use `call()` to pass `this` as context to Ajv, see passContext:
result = await validator.call(this, data)
} catch (error) {
if (error.errors) {
validate.errors = error.errors
result = false
} else {
throw error
}
}
return result
}
: validator // The default for async is to throw.
// For sync:
: dontThrow
? validator // The default for sync is to not throw.
: function(data) {
// Emulate `options.throw == true` behavior for sync validation:
// Return `true` if successful, throw `Ajv.ValidationError` otherwise.
// Use `call()` to pass `this` as context to Ajv, see passContext:
const result = validator.call(this, data)
if (!result) {
throw new Ajv.ValidationError(validator.errors)
}
return result
}
}
getKeyword(keyword) {
return this.keywords[keyword]
}
getFormat(format) {
return this.formats[format]
}
addSchema(jsonSchema) {
this.schemas.push(jsonSchema)
// Add schema to all previously created Ajv instances, so they can reference
// the models.
for (const { ajv, options } of Object.values(this.ajvCache)) {
ajv.addSchema(this.processSchema(jsonSchema, options))
}
}
processSchema(jsonSchema, options = {}) {
const { patch, async } = options
const schema = clone(jsonSchema, value => {
if (isObject(value)) {
if (patch) {
// Remove all required keywords and formats from schema for patch
// validation.
delete value.required
if (value.format === 'required') {
delete value.format
}
}
// Convert async `validate()` keywords to `validateAsync()`:
if (isAsync(value.validate)) {
value.validateAsync = value.validate
delete value.validate
}
if (!async) {
// Remove all async keywords for synchronous validation.
for (const key in value) {
const keyword = this.getKeyword(key)
if (keyword?.async) {
delete value[key]
}
}
}
}
})
if (async) {
schema.$async = true
}
return schema
}
parseErrors(errors, options = {}) {
// Convert from Ajv errors array to Objection-style errorHash,
// with additional parsing and processing.
const errorHash = {}
const duplicates = {}
for (const error of errors) {
// Adjust dataPaths to reflect nested validation in Objection.
const dataPath = `${options?.dataPath || ''}${error.dataPath}`
// Unknown properties are reported in `['propertyName']` notation,
// so replace those with dot-notation, see:
// https://github.com/epoberezkin/ajv/issues/671
const key = dataPath.replace(/\['([^']*)'\]/g, '.$1').slice(1)
const { message, keyword, params } = error
const definition = keyword === 'format'
? this.getFormat(params.format)
: this.getKeyword(keyword)
const identifier = `${key}_${keyword}`
if (
// Ajv produces duplicate validation errors sometimes, filter them out.
!duplicates[identifier] &&
// Skip keywords that start with $ such as $merge and $patch.
!/^\$/.test(keyword) &&
// Skip macro keywords that are only delegating to other keywords.
!definition?.macro &&
// Filter out all custom keywords and formats that want to be silent.
!definition?.silent
) {
const array = errorHash[key] || (errorHash[key] = [])
array.push({
// Allow custom formats and keywords to override error messages.
message: definition?.message || message,
keyword,
params
})
duplicates[identifier] = true
}
}
// Now filter through the resulting errors and perform some post-processing:
for (const [dataPath, errors] of Object.entries(errorHash)) {
// When we get these errors (caused by `nullable: true`), it means that we
// have data that isn't null and is causing other errors, and we shouldn't
// display the 'null' path:
// [dataPath]: [
// {
// message: 'should be null',
// keyword: 'type',
// params: { type: 'null' }
// },
// {
// message: 'should match exactly one schema in oneOf',
// keyword: 'oneOf'
// }
// ]
if (errors.length === 2) {
const [error1, error2] = errors
if (
error1.keyword === 'type' && error1.params.type === 'null' &&
error2.keyword === 'oneOf'
) {
delete errorHash[dataPath]
}
}
}
return errorHash
}
prefixDataPaths(errors, dataPathPrefix) {
return errors.map(error => ({
...error,
dataPath: error.dataPath
? `${dataPathPrefix}${error.dataPath}`
: dataPathPrefix
}))
}
// @override
beforeValidate({ json, model, ctx, options }) {
// Add validator instance, app and options to context
ctx.validator = this
ctx.app = this.app
ctx.options = options
ctx.jsonSchema = model.constructor.getJsonSchema()
const { $beforeValidate } = model
if ($beforeValidate !== objection.Model.prototype.$beforeValidate) {
// TODO: Consider adding hooks for 'before:validate' and 'after:validate',
// and if so, decide what to do about modifying / returning json-schema.
// Probably we shouldn't allow it there.
// Only clone jsonSchema if the handler actually receives it.
if ($beforeValidate.length > 0) {
ctx.jsonSchema = clone(ctx.jsonSchema)
}
const ret = model.$beforeValidate(ctx.jsonSchema, json, options)
if (ret !== undefined) {
ctx.jsonSchema = ret
}
}
}
// @override
validate({ json, model, ctx, options }) {
const { jsonSchema } = ctx
if (jsonSchema) {
// We need to clone the input json if we are about to set default values.
if (
!options.mutable &&
!options.patch &&
hasDefaults(jsonSchema.properties)
) {
json = clone(json)
}
// Get the right Ajv instance for the given patch and async options
const validate = this.getAjv(options).getSchema(jsonSchema.$id)
// Use `call()` to pass ctx as context to Ajv, see passContext:
const res = validate.call(ctx, json)
const handleErrors = errors => {
if (errors) {
// NOTE: The conversion from Ajv errors to Objection errors happen in
// Model.createValidationError(), which calls Validator.parseError()
throw model.constructor.createValidationError({
type: 'ModelValidation',
errors,
options,
json
})
}
}
// Handle both async and sync validation here:
if (isPromise(res)) {
return res
.catch(error => handleErrors(error.errors))
.then(() => json)
} else {
handleErrors(validate.errors)
return json
}
}
}
} |
JavaScript | class Vmmigration {
constructor(options, google) {
this.context = {
_options: options || {},
google,
};
this.projects = new Resource$Projects(this.context);
}
} |
JavaScript | class StateError extends ExtendableError {
/**
* Constructor
*
* @param {String} message
*/
constructor(message) {
super(message);
}
} |
JavaScript | class DecimalFraction {
/**constructor of DecimalFraction
* @constructor
* @param {object|string}
*/
constructor(array, input) {
this.ref = array;
this.df = input;
}
/**convert function
* @function -to convert decimal and fraction respectively.
*/
convert() {
let obj = new NumberToWord(this.ref);
let text = this.df;
let b = [];
if (text.match(/\d+[.]\d+/g)) {
let arr = text.split(".");
b.push(obj.number_to_word(arr[0]));
b.push(" ");
b.push(" point ");
b.push(" ");
b.push(obj.number_to_word(arr[1]));
b=b.join(" ");
let obj2=new Replace(this.ref);
obj2.replacer(this.df,b);
}else if (text.match(/\d+[/]\d+/g)) {
let arr = text.split("/");
b.push(obj.number_to_word(arr[0]));
b.push(" ");
b.push(" by ");
b.push(" ");
b.push(obj.number_to_word(arr[1]));
b=b.join(" ");
let obj2=new Replace(this.ref);
obj2.replacer(this.df,b);
}
}
/** function to return output
* @function
* @return {string} -decimal/fraction in word format.
*/
output(){
let obj = new NumberToWord(this.ref);
let text = this.df;
let b = [];
if (text.match(/\d+[.]\d+/g)) {
let arr = text.split(".");
b.push(obj.number_to_word(arr[0]));
b.push(".");
b.push(obj.number_to_word(arr[1]));
b=b.join(" ");
b=b.replace(/\s+/g,"");
return b;
}else if (text.match(/\d+[/]\d+/g)) {
let arr = text.split("/");
b.push(obj.number_to_word(arr[0]));
b.push("/");
b.push(obj.number_to_word(arr[1]));
b=b.join(" ");
b=b.replace(/\s+/g,"");
return b;
}
}
} |
JavaScript | class QueryManager {
/**
* Creates a new QueryManager.
*/
constructor () {
this.queries = new Set()
this.running = false
}
/**
* Called when a query is started.
*
* @param {Query} query
*/
queryStarted (query) {
this.queries.add(query)
}
/**
* Called when a query completes.
*
* @param {Query} query
*/
queryCompleted (query) {
this.queries.delete(query)
}
/**
* Starts the query manager.
*/
start () {
this.running = true
}
/**
* Stops all queries.
*/
stop () {
this.running = false
for (const query of this.queries) {
query.stop()
}
this.queries.clear()
}
} |
JavaScript | class RemotePlayerController{
/**
* creates a new remote player controller
* @constructor
* @param {World} world the world to which to add the players
*/
constructor(world, packetManager, runner){
this.players = {};
this.world = world;
this.packetManager = packetManager;
this.runner = runner;
this.listeners = [];
this.added = true;
let self = this;
this.world.addEventListener(this);
window.remotePlayerController = this;
this.packetManager.addListener(PacketTypes.runnerCreation, {onPacket:function(e){
self.addPlayer(e.data);
}});
this.packetManager.addListener(PacketTypes.runnerUpdated, {onPacket:function(e){
self.updatePlayer(e.data);
}});
this.packetManager.addListener(PacketTypes.murderDamage, {onPacket:function(e){
self.hurt(e.data);
}});
this.packetManager.addListener(PacketTypes.runnerStateChange, {onPacket:function(e){
self.handlePlayer(e.data);
}});
this.update();
this.hasSentDeadOrGhost = false;
this.disable = false;
}
/**
* creates a new player based on the event comming from the WebRTCConnection
* @param {Object} playerCreationEvent the event fired for creation
*/
addPlayer(playerCreationEvent){
let x = playerCreationEvent.x;
let y = playerCreationEvent.y;
let remoteRunner = new RemoteRunner(64, 108, x, y, playerCreationEvent.clientName, playerCreationEvent.murderer);
this.players[playerCreationEvent.playerId] = remoteRunner;
this.world.addEntity(remoteRunner);
}
/**
* called when the world sends an event
*/
onEvent(type){
if(type === "Reset"){
this.added = false;
}
if(type === "Entity Added" && !this.added){
this.added = true;
for(let playerId in this.players){
let player = this.players[playerId];
this.world.addEntity(player);
}
}
}
/**
* updates the remote players based on the events fired
* @param {Object} playerUpdateEvent the update event
*/
updatePlayer(playerUpdateEvent){
let runner = this.players[playerUpdateEvent.playerId];
if(runner){
runner.remoteUpdate(playerUpdateEvent.pos, playerUpdateEvent.vel,
playerUpdateEvent.crouching, playerUpdateEvent.state,
playerUpdateEvent.health, playerUpdateEvent.frozen, playerUpdateEvent.dead);
}
}
/**
* adds a remote player listenr of the given id
* @param {String} id the id of the listener
*/
addRemotePlayerListener(id, name){
this.listeners.push(id);
let data = {x: this.runner.pos.x, y:this.runner.pos.y, playerId:flucht.networkConnection.id, clientName: name, murderer:!!this.runner.murderer};
let packet = new Packet(false, id, PacketTypes.runnerCreation, data);
this.packetManager.send(packet);
}
/**
* hurts this runner by the amount specified in the data
* @param {Object} data the data
* @param {Number} data.damage the damage dealt
*/
hurt(data){
if(data.damage && this.runner){
this.runner.hurt(data.damage);
}
}
/**
* handles a change in the player, eithr death or winning
* @param {Object} data the data
*/
handlePlayer(data){
if(this.players[data.id]){
if(data.death){
let player = this.players[data.id];
player.dead = true;
player.hidden = true;
} else {
let player = this.players[data.id];
player.hidden = true;
player.won = true;
}
} else {
return;
}
for(let playerId in this.players){
if(!this.players[playerId].hidden){
return;
}
}
if(!window.done){
flucht.allDone();
}
}
/**
* sends and update to all listeners
*/
update(){
let self = this;
window.setTimeout(function(){self.update()}, 100);
if(!window.flucht || !this.runner){
return;
}
if(this.runner.ghost && !this.hasSentDeadOrGhost && (this.runner.won || this.runner.dead)){
let data = {
death : this.runner.dead,
id : flucht.networkConnection.id
}
for(let listener of this.listeners) {
let packet = new Packet(false, listener, PacketTypes.runnerStateChange, data);
this.packetManager.send(packet);
}
this.hasSentDeadOrGhost = true;
}
let data = {pos: this.runner.pos,
vel:this.runner.vel,
crouching:this.runner.crouching,
state:this.runner.state,
playerId:flucht.networkConnection.id,
health:flucht.runner.health,
frozen: flucht.runner.frozen,
dead: flucht.runner.dead
};
if(this.runner.frozen){
data.vel.x = 0;
data.vel.y = 0;
}
for(let listener of this.listeners) {
let packet = new Packet(false, listener, PacketTypes.runnerUpdated, data);
this.packetManager.send(packet);
}
for(let playerID in this.players){
let runner = this.players[playerID];
if(runner.healthDelta !== 0){
let data = {
damage: runner.healthDelta
}
let packet = new Packet(false, playerID, PacketTypes.murderDamage, data);
this.packetManager.send(packet);
runner.healthDelta = 0;
}
}
}
/**
* resets this
*/
reset(){
this.runner = false;
this.listeners = [];
this.players = {};
this.hasSentDeadOrGhost = false;
}
} |
JavaScript | class ModelSchemas {
/**
* @param {Object} options
* @param {Framework} options.framework
* @param {[ModelSchema]} options.schemas
*/
constructor({
framework = null,
schemas = []
} = {}) {
/** @type {Framework} */
this.framework = framework;
/** @type {[ModelSchema]} */
this.schemas = schemas;
}
/**
* Returns an array of translatable attribute paths derived from the schemas.
* @returns {[string]}
*/
getTranslatablePaths() {
return _.uniq(this.schemas.reduce((paths, modelSchema) => {
paths.push(...modelSchema.getTranslatablePaths());
return paths;
}, []));
}
} |
JavaScript | class Templater {
/**
* Create a templater
* @param {string} template - A {{ }} tagged string
*/
constructor(template) {
this.template = template;
}
/**
* Apply map to template to generate string
* @param {object} map Object with propeties matching tags in template
* @param {boolean} strict Throw an Error if any tags in template are
* not found in map
* @return {string} template with all tags replaced
* @throws An Error if strict is set and any tags in template are not
* found in map
*/
apply(map, strict) {
// alias
let template = this.template;
// base cases
if (template == undefined) {
return undefined;
} else if (template === '') {
return '';
}
let templateModified = true;
while (templateModified) {
const oldTemplate = template;
/*
* /{{([^}]+)}}/g :
* finds global occurrences of substrings starting with {{,
* some char (not a }), then ends with a }}
*/
template = template.replace(/{{([^}]+)}}/g, (tag, key) => {
// eliminate spaces around key with .trim
const value = map[key.trim()];
if (value === undefined) {
if (strict) {
throw new Error('Error: tag is undefined');
}
// replace with dummy tag
return '<>';
} else {
return value;
}
});
/*
* delete dummy tag and surrounding space accordingly
* for both beginning and end tag edge cases
*/
// some non-space then the tag
// let replacedAll = false;
// while(!replacedAll){
// }
template = template.replace(/(<>)+[^ <\n]/g, (match, key) => {
return match[match.length - 1];
});
// the tag then some non-space
template = template.replace(/[^ >](<>)+/g, (match, key) => {
return match[0];
});
// tags with spaces
template = template.replace(/ (<>)+/g, '');
template = template.replace(/(<>)+ /g, '');
template = template.replace('<>', '');
templateModified = template !== oldTemplate;
}
return template;
}
} |
JavaScript | class BeeldSliderFilter extends PIXI.Filter {
/**
* Creates an instance of DisplacementFilter.
* @param {*} speed
* @param {*} resolution
* @memberof DisplacementFilter
*/
constructor(textures = [] ,resolution)
{
super();
/* defaullt pixi implementation
Object.assign(this.uniforms,{
dimensions:new Float32Array(4),
scale:0.015,
offet:0,
mapDimensions:new Float32Array(2),
focus:.5,
iTime:0,
displacementMap:texture,
});
*/
this.padding = 200;
this.passes = 0;
this.resolution = resolution || PIXI.settings.RESOLUTION;
this.autoFit = false;
/* Bypassing fucking pixi check if webgl input is in use */
const uniforms = {
iResolution: {type: '2f', value:[0,0]},
direction: {tyoe: '2f', value:[1,0]},
prevCol: {type: '3f', value:[0,0,0]},
currCol: {type: '3f', value:[0,0,0]},
prev: {type: 'sampler2D', value: new EMPTY()},
curr: {type: 'sampler2D', value: new EMPTY()},
scale_prev: {type: '2f', value:[0,0]},
scale_curr: {type: '2f', value:[1,1]},
transform_prev: {type: '2f', value:[0,0]},
transform_curr: {type: '2f', value:[0,0]},
progress: {type: '1f', value:0},
parabola: {type: '1f', value:1},
effectFactor: {type: '1f', value:0},
scale: {type: '2f', value:[1,1]},
tension: {type: '1f', value: 0},
padding: {type: '1f', value: this.padding},
offset: {type: '2f', value:{x:1, y:1}},
mapDimensions: {type: '2f', value:{x:1, y:5112}},
dimensions: {type: '4fv', value:[0,0,window.innerWidth,window.innerHeight]},
focus: {type: '1f', value:0.1},
iTime: {type: '1f', value:0.0},
iMouse: {type: '3f', value:[.5,.5,0]},
noise: {type: '3f', value:[0,0,0]},
};
this.loader = new TextureLoader(textures,uniforms,this)
const filter = PIXI.Filter.call(this,
Vertext,
Fragment,
uniforms
);
/* end hack */
this.animation = animate(this.update, 24)
this.animate = true;
}
/**
* Applies the filter.
*
* @param {PIXI.FilterManager} filterManager - The manager.
* @param {PIXI.RenderTarget} input - The input target.
* @param {PIXI.RenderTarget} output - The output target.
*/
apply(filterManager, input, output,clear)
{
this.renderer = filterManager.renderer;
const width = input.sourceFrame.width
const height = input.sourceFrame.height
const x = input.sourceFrame.x;
const y = input.sourceFrame.y;
this.uniforms.dimensions[1] = x;
this.uniforms.dimensions[2] = y;
this.uniforms.dimensions[2] = input.size.width;
this.uniforms.dimensions[3] = input.size.height;
this.uniforms.aspect = height / width;
this.uniforms.padding = this.padding ;
this.uniforms.iResolution[0] = width;
this.uniforms.iResolution[1] = height;
// MOUSE IS NOT NORMALISED !!!!!;
const mx = (this.mouse.x - x);
const my = (this.mouse.y - y);
const mz = this.mouse.z;
this.uniforms.iMouse = [0,0,0];
// this.uniforms.iMouse = [mx,my,mz]
filterManager.applyFilter(this, input, output, clear);
}
update = (t)=>{
this.uniforms.iTime = performance.now()/1000;
}
set prev(texture){
console.log('texture:',texture)
if(!texture || JSON.stringify(texture) == JSON.stringify(this._prev)) return;
// this.uniforms.prevCol = col[texture.url.match(/\d+/g)[0]];
this.loader.addTextTures(this.uniforms,texture,'prev');
this._prev = texture;
}
set curr(texture){
console.log('texture:',texture)
if(!texture || JSON.stringify(texture) == JSON.stringify(this._curr) ) return;
// this.uniforms.currCol = col[texture.url.match(/\d+/g)[0]];
this.loader.addTextTures(this.uniforms,texture,'curr');
this._curr = texture;
}
get mouse() {
return this._mouse || {x:0,y:0, z:0};
}
set mouse(value) {
this._mouse = value
}
get noise() {
return this._noise || {x:0,y:0};
}
set noise(value) {
this.uniforms.noise = [value.x,value.y,value.z];
this._noise = value
}
get scale() {
return {x:this.uniforms.scale[0],y:this.uniforms.scale[1]};
}
set scale(value) {
this.uniforms.scale = [value.x,value.y];
}
get progress (){
return this._progress || 0;
}
x = 0
set progress (value){
this.uniforms.progress = value;
this._progress = value;
}
get direction (){
return this._direction;
}
set direction (value){
this.uniforms.direction = value;
this._direction = value;
}
get offset() {
return this.uniforms.offset;
}
set offset(value) {
this.uniforms.offset = value
}
get time() {
return this.uniforms.iTime;
}
set time(value) {
this.uniforms.iTime = value
}
set animate (bool) {
this._animate = bool;
bool ? this.animation.resume() : this.animation.pause()
}
get animate () {
return this._animate;
}
set tension(value){
this.uniforms.tension = value
}
get tension(){
return this.uniforms.tension;
}
} |
JavaScript | class CustomMarker extends Component {
static propTypes = {
...createListenersPropTypes(eventTypes),
hit: GeoPointHitPropType.isRequired,
children: PropTypes.node.isRequired,
google: PropTypes.object.isRequired,
googleMapsInstance: PropTypes.object.isRequired,
className: PropTypes.string,
anchor: PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
}),
};
static defaultProps = {
className: '',
anchor: {
x: 0,
y: 0,
},
};
static isReact16() {
return typeof ReactDOM.createPortal === 'function';
}
state = {
marker: null,
};
componentDidMount() {
const { hit, google, googleMapsInstance, className, anchor } = this.props;
// Not the best way to create the reference of the CustomMarker
// but since the Google object is required didn't find another
// solution. Ideas?
const Marker = createHTMLMarker(google);
const marker = new Marker({
map: googleMapsInstance,
position: {
lat: hit._geoPoint.lat,
lng: hit._geoPoint.lon,
},
className,
anchor,
});
this.removeListeners = registerEvents(eventTypes, this.props, marker);
this.setState(() => ({
marker,
}));
}
componentDidUpdate() {
const { children } = this.props;
const { marker } = this.state;
this.removeListeners();
this.removeListeners = registerEvents(eventTypes, this.props, marker);
if (!CustomMarker.isReact16()) {
ReactDOM.unstable_renderSubtreeIntoContainer(
this,
children,
marker.element
);
}
}
componentWillUnmount() {
const { marker } = this.state;
if (!CustomMarker.isReact16()) {
ReactDOM.unmountComponentAtNode(marker.element);
}
marker.setMap(null);
}
render() {
const { children } = this.props;
const { marker } = this.state;
if (!marker || !CustomMarker.isReact16()) {
return null;
}
return ReactDOM.createPortal(children, marker.element);
}
} |
JavaScript | class AtomProjectWorkspaceSaveView {
/**
* ProjectWorkspace View Constructor
* @param {[type]} serializedState not used, but can be to reinstate the view
*/
constructor() {
this.disposables = new CompositeDisposable();
// Create root element
this.element = document.createElement('div');
this.element.classList.add('atom-project-workspace');
// Create container element
const container = document.createElement('div');
container.classList.add('container');
this.element.appendChild(container);
this.mini = new TextEditor({ mini: true });
this.mini.element.classList.add('input');
const handler = (e) => {
this.mini.element.classList.remove('clean');
if (e.keyCode === 13) {
this.submit();
} else if (e.keyCode === 27) {
this.modal.hide();
}
console.log();
};
this.mini.element.addEventListener('keydown', handler);
this.disposables.add(new Disposable(() => {
this.mini.element.removeEventListener('keydown', handler);
}));
// TODO: On open, focus on input
// TODO: On lose focus hide modal
container.appendChild(this.mini.element);
// Create Button
const button = document.createElement('span');
button.classList.add('saveBtn');
container.appendChild(button);
button.textContent = 'Save';
// Wire button to submit function
button.onclick = this.submit.bind(this);
}
/**
* Tear down any state and detach
* @return {void}
*/
destroy() {
this.element.remove();
this.disposables.dispose();
this.mini.destroy();
const activePane = atom.workspace.getCenter().getActivePane();
if (!activePane && !activePane.isDestroyed()) {
activePane.activate();
}
}
/**
* gets the element containing the view components
* @return {void}
*/
getElement() {
return this.element;
}
/**
* Shows the package modal view
* @return {void}
*/
show() {
const prompt = 'Enter Workspace Name';
this.mini.element.classList.add('clean');
this.mini.setText(prompt);
this.mini.element.focus();
this.mini.setSelectedBufferRange(Range(Point(0, 0), Point(0, prompt.length)));
}
/**
* Get name from the input and pass to Workspace.create then save the state to disk and hide the modal
* @return {void}
*/
submit() {
const name = this.mini.getText();
const state_obj = Workspace.create(name);
// TODO: Save state to file/db
console.log(state_obj.toString());
const path_name = name.replace(' ', '-');
const project_directory = atom.project.getPaths()[0];
if (!fs.existsSync(`${project_directory}/.workspace/`)) {
fs.mkdirSync(`${project_directory}/.workspace/`);
}
fs.writeFile(`${project_directory}/.workspace/${path_name}`, state_obj.toString(), (err) => {
if (err) {
return console.log(err);
}
});
this.modal.hide();
}
/**
* Sets the modal (used by package setup)
* @param {Modal} modal modal to use for the atom package
* @return {void}
*/
setModal(modal) {
this.modal = modal;
}
} |
JavaScript | class ServiceLocation {
/**
* Constructs a new <code>ServiceLocation</code>.
* Information about the location of the service job.
* @alias module:client/models/ServiceLocation
* @class
*/
constructor() {
}
/**
* Constructs a <code>ServiceLocation</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:client/models/ServiceLocation} obj Optional instance to populate.
* @return {module:client/models/ServiceLocation} The populated <code>ServiceLocation</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ServiceLocation();
if (data.hasOwnProperty('serviceLocationType')) {
obj['serviceLocationType'] = ApiClient.convertToType(data['serviceLocationType'], 'String');
}
if (data.hasOwnProperty('address')) {
obj['address'] = Address.constructFromObject(data['address']);
}
}
return obj;
}
/**
* The location of the service job.
* @member {module:client/models/ServiceLocation.ServiceLocationTypeEnum} serviceLocationType
*/
'serviceLocationType' = undefined;
/**
* @member {module:client/models/Address} address
*/
'address' = undefined;
/**
* Allowed values for the <code>serviceLocationType</code> property.
* @enum {String}
* @readonly
*/
static ServiceLocationTypeEnum = {
/**
* value: "IN_HOME"
* @const
*/
"IN_HOME": "IN_HOME",
/**
* value: "IN_STORE"
* @const
*/
"IN_STORE": "IN_STORE",
/**
* value: "ONLINE"
* @const
*/
"ONLINE": "ONLINE" };
} |
JavaScript | class BadRequestException extends ApplicationException_1.ApplicationException {
/**
* Creates an error instance and assigns its values.
*
* @param correlation_id (optional) a unique transaction id to trace execution through call chain.
* @param code (optional) a unique error code. Default: "UNKNOWN"
* @param message (optional) a human-readable description of the error.
*
* @see [[ErrorCategory]]
*/
constructor(correlation_id = null, code = null, message = null) {
super(ErrorCategory_1.ErrorCategory.BadRequest, correlation_id, code, message);
// Set the prototype explicitly.
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
this.__proto__ = BadRequestException.prototype;
this.status = 400;
}
} |
JavaScript | class Aes256Gcm {
/**
* Encrypts text with AES 256 GCM.
* @param {string} text - Cleartext to encode.
* @param {string} secret - Shared secret key, must be 32 bytes.
* @returns {object}
*/
static encrypt(text, secret) {
const iv = crypto.randomBytes(BLOCK_SIZE_BYTES)
const cipher = crypto.createCipheriv(ALGORITHM, secret, iv)
let ciphertext = cipher.update(text, CODING, 'base64')
ciphertext += cipher.final('base64')
let tag = cipher.getAuthTag()
return {
ciphertext,
iv: iv.toString('base64'),
tag: tag.toString('base64')
}
}
/**
* Decrypts AES 256 CGM encrypted text.
* @param {string} ciphertext - Base64-encoded ciphertext.
* @param {string} iv - The base64-encoded initialization vector.
* @param {string} tag - The base64-encoded authentication tag generated by getAuthTag().
* @param {string} secret - Shared secret key, must be 32 bytes.
* @returns {string}
*/
static decrypt(ciphertext, iv, tag, secret) {
const decipher = crypto.createDecipheriv(ALGORITHM, secret, Buffer.from(iv, 'base64'))
decipher.setAuthTag(Buffer.from(tag, 'base64'))
let cleartext = decipher.update(ciphertext, 'base64', CODING)
cleartext += decipher.final(CODING)
return cleartext
}
} |
JavaScript | class FSAImporter extends SessionImporter
{
constructor(fileTypes = [])
{
super();
this._prevGraphHash = 0;
this._fileTypes = fileTypes;
}
/** @override */
onParseSession(session, fileData)
{
return JSON.parse(fileData);
}
/** @override */
onPreImportSession(session)
{
const graphController = session.graphService.graphController;
const graph = graphController.getGraph();
this._prevGraphHash = graph.getHashCode(true);
// TODO: this should not be here, this should exist somewhere in graphController
if (!graph.isEmpty())
{
session.undoManager.captureEvent();
}
}
/** @override */
onImportSession(session, sessionData)
{
const graphController = session.graphService.graphController;
const machineController = session.machineService.machineController;
const graph = graphController.getGraph();
if ('graphData' in sessionData)
{
FSA_PARSER.parse(sessionData['graphData'], graph);
}
if ('machineData' in sessionData)
{
loadMachineFromData(graphController, machineController, sessionData['machineData']);
}
}
/** @override */
onPostImportSession(session)
{
const graphController = session.graphService.graphController;
const graph = graphController.getGraph();
// Compares the graph hash before and after import, captures event if they are not equal
const nextGraphHash = graph.getHashCode(true);
if (this._prevGraphHash !== nextGraphHash)
{
// TODO: this should not be here
session.undoManager.captureEvent();
}
}
/** @override */
getFileTypes()
{
return this._fileTypes;
}
} |
JavaScript | class TestResult
{
/**
* Create test results container.
* @param {TestSuite} suite Test suite we create results for.
* @param {*} logger Logger handler class.
*/
constructor(suite, logger)
{
this._suite = suite;
this._results = new Map();
this._caseStartTime = {};
this._errors = 0;
this._success = 0;
this._casesCount = 0;
this.logger = logger;
}
/**
* Check if a given test case have results or if its still waiting.
* @param {String} name Test case name to check.
* @returns True if have any result for test, false otherwise.
*/
hasResultFor(name)
{
return Boolean(this._results.get(name));
}
/**
* Check if a given test case has an error.
* @param {String} name Test case name to check.
* @returns True if have an error, false otherwise.
*/
isError(name)
{
return this.hasResultFor(name) && this._results.get(name).success === false;
}
/**
* Check if a given test case is a success.
* @param {String} name Test case name to check.
* @returns True if done and have no errors, false otherwise.
*/
isSuccess(name)
{
return this.hasResultFor(name) && this._results.get(name).success === true;
}
/**
* Get test suite name.
*/
get testName()
{
return this._suite.name;
}
/**
* Get test suite description.
*/
get testDescription()
{
return this._suite.description;
}
/**
* Get test results.
*/
get results()
{
return this._results.entries();
}
/**
* Get errors count.
*/
get errorsCount()
{
return this._errors;
}
/**
* Get success count.
*/
get successCount()
{
return this._success;
}
/**
* Get total results count.
*/
get totalCount()
{
return this._casesCount;
}
/**
* Start a test case.
* @private
* @param {String} caseName Test case name.
*/
_startCase(caseName)
{
this._casesCount++;
this._caseStartTime[caseName] = accurateTimestamp();
}
/**
* Add error to test.
* @private
* @param {String} caseName Test case name.
* @param {String} reason Reason for failure.
* @param {Array<String>} stackTrace Error stack trace.
*/
_addError(caseName, reason, stackTrace)
{
if (!this._results.get(caseName)) {
let testTime = Math.round((accurateTimestamp() - this._caseStartTime[caseName]) * 1000) / 1000;
this._results.set(caseName, {success: false, reason: reason, time: testTime, stackTrace: stackTrace || []});
this.logger.warn(`[Testizy] [${this._suite.name}] Failed: '${reason}'.`);
this._errors++;
}
}
/**
* Add success to test case unless there was an error.
* @private
* @param {String} caseName Test case name.
*/
_addSuccessIfDidntFail(caseName)
{
if (!this._results.get(caseName)) {
let testTime = Math.round((accurateTimestamp() - this._caseStartTime[caseName]) * 1000) / 1000;
this._results.set(caseName, {success: true, time: testTime, reason: null});
this.logger.debug(`[Testizy] [${this._suite.name}] Success.`);
this._success++;
}
}
} |
JavaScript | class Client {
/**
* @param {String} token - Access token
* @param {String} baseUrl - Base URL for Media Content Service, i.e. /v1/Services/{serviceSid}/Media
* @param {Client#ClientOptions} [options] - Options to customize the Client
*/
constructor(token, baseUrl, options = {}) {
this.options = options;
this.options.logLevel = this.options.logLevel || 'silent';
this.config = new configuration_1.Configuration(token, baseUrl, this.options);
if (!token) {
throw new Error(MSG_NO_TOKEN);
}
log.setLevel(this.options.logLevel);
this.options.transport = this.options.transport || new transport_1.Transport();
this.transport = this.options.transport;
this.network = new network_1.Network(this.config, this.transport);
}
/**
* These options can be passed to Client constructor
* @typedef {Object} Client#ClientOptions
* @property {String} [logLevel='error'] - The level of logging to enable. Valid options
* (from strictest to broadest): ['silent', 'error', 'warn', 'info', 'debug', 'trace']
*/
/**
* Update the token used for Client operations
* @param {String} token - The JWT string of the new token
* @public
* @returns {void}
*/
updateToken(token) {
log.info('updateToken');
if (!token) {
throw new Error(MSG_NO_TOKEN);
}
this.config.updateToken(token);
}
/**
* Gets media from media service
* @param {String} sid - Media's SID
* @public
* @returns {Promise<Media>}
*/
async get(sid) {
let response = await this.network.get(`${this.config.baseUrl}/${sid}`);
return new media_1.Media(this.config, this.network, response.body);
}
/**
* Posts raw content to media service
* @param {String} contentType - content type of media
* @param {String|Buffer} media - content to post
* @public
* @returns {Promise<Media>}
*/
async post(contentType, media) {
let response = await this.network.post(this.config.baseUrl, media, contentType);
return new media_1.Media(this.config, this.network, response.body);
}
/**
* Posts FormData to media service. Can be used only with browser engine's FormData.
* In non-browser FormData case the method will do promise reject with
* new TypeError("Posting FormData supported only with browser engine's FormData")
* @param {FormData} formData - form data to post
* @public
* @returns {Promise<Media>}
*/
async postFormData(formData) {
let response = await this.network.post(this.config.baseUrl, formData);
return new media_1.Media(this.config, this.network, response.body);
}
} |
JavaScript | class CommandManager extends events {
/**
* @constructor
*/
constructor () {
super()
this.commandsRegistery = new Map()
}
/**
* @public
* @method addCommand
* @desc Add a new command to the bot
* @memberof CommandManager#
*
* @param {!String} commandName commandName
* @param {!Function} callback callback to execute
*
* @return {void}
* @throws {TypeError}
*/
addCommand (commandName, callback) {
if (is(commandName) !== 'string') {
throw new TypeError('commandName should be typeof String')
}
if (is(callback) !== 'Function') {
throw new TypeError('callback should be instanceof Function')
}
const fullCMDName = `command_${commandName}`
this.commandsRegistery.set(commandName, fullCMDName)
this.on(fullCMDName, callback)
}
/**
* @public
* @method getRegisteredCommands
* @desc Get the list of all commands registered
* @memberof CommandManager#
*
* @return {String[]}
*/
getRegisteredCommands () {
return this.commandsRegistery.keys()
}
/**
* @public
* @method getRegisteredCommands
* @desc Get the list of all commands registered
* @memberof CommandManager#
*
* @param {!Object} message message to handle
* @param {!String} commandName commandName (str) to find
* @param {!any} args commands arguments for the callback
*
* @return {void}
*/
handle (message, commandName, args) {
this.emit(`command_${commandName}`, { message, args })
}
} |
JavaScript | class FireDAX {
/**
* Create a FireDAX.
*/
constructor() {
this.initializeFirebase();
this.OrderBook = new Gdax.OrderbookSync();
}
/**
* Connect to Firebase
* {@link https://firebase.google.com/docs/database/server/start Firebase Server API}.
*/
initializeFirebase() {
this.config = {
firebase: {
serviceAccount: {
projectId: process.env.FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_PRIVATE_KEY
},
databaseURL: process.env.FIREBASE_DATABASE_URL
}
};
firebase.initializeApp(this.config.firebase);
}
} |
JavaScript | class MNIST {
constructor(folder_path) {
this.data_img_elts = [];
this.img_data = [];
this.loaded = [];
for (var i=0; i<20; i++) {
this.data_img_elts.push(null);
this.img_data.push(null);
this.loaded.push(null);
};
this.folder_path = folder_path;
}
load_data_batch(batch_num, verbose) {
this.data_img_elts[batch_num] = new Image();
var data_img_elt = this.data_img_elts[batch_num];
var self = this;
data_img_elt.onload = function() {
//var data_canvas = document.getElementById('datacanvas');
var data_canvas = document.createElement('canvas');
data_canvas.width = data_img_elt.width;
data_canvas.height = data_img_elt.height;
var data_ctx = data_canvas.getContext("2d");
data_ctx.drawImage(data_img_elt, 0, 0); // copy it over... bit wasteful :(
self.img_data[batch_num] = data_ctx.getImageData(0, 0, data_canvas.width, data_canvas.height);
// WARNING : the data array length is equal to 4*width*height
self.loaded[batch_num] = true;
if (verbose) {
console.log('finished loading data batch ' + batch_num);
console.log('WARNING : should remove the new canvas?');
}
};
data_img_elt.src = this.folder_path + "/mnist_batch_" + batch_num + ".png";
}
mnistitem(batch_num, row) {
// var batch_num = 1;
var p = this.img_data[batch_num].data;
//var row = 15; // any number from 0 to 2999, each row correspond to a digit image
var W = 28*28;
var vec = [];
for(var i=0; i<W; i++) {
var ix = ((W * row) + i) * 4; // WARNING : the data array length is equal to 4*width*height
vec.push( p[ix]/255.0 ); // scale the data
}
return vec;
}
} |
JavaScript | class Services extends Component {
render() {
return (
<div className="Services">
{/* Titulo da pagina */}
<div className="divTitle">
<h1 className="H1Services">Nossas Soluções</h1>
<div className="linhaGradiente"> </div>
{/* <div className="linhaGradiente" > </div> */}
</div>
{/* Subtitulo da pagina */}
<div className="subTitle">
<p className="text"> Nossa empresa trabalha para que a doação de sangue intensifique-se e cada vez mais vidas possam ser salvas no país. Visando isto, nós fornecemos todas as informações e caminhos que você precisa!</p>
</div>
{/*Inicio da Main */}
<div className="divMain">
<div className="subDiv" style={{ width: '40%' }}>
<img src={IconPrincipal} style={{ height: '12vh' }} />
</div>
<div className="subDiv" style={{ width: '45%' }}>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut Lorem ipsum dolor sit </p>
</div>
</div>
{/* Cards de solucoes */}
<div className="divCards">
<div className="card">
<img src={IconHospital} className="inCard" />
<div className="miniCard">
{/* <Link to="/Mapa" style={{textDecoration:"none"}}><h4>Buscar Hemocentro</h4></Link> */}
<a href="/Mapa" style={{textDecoration:"none"}}><h4>Buscar Hemocentro</h4></a>
<p>Veja dados e localizações de todos os hemocentros cadastrados na plataforma</p>
</div>
</div>
<div className="card">
<img src={IconTipoSanguineo} className="inCard" />
<div className="miniCard">
{/* <Link to="/CadastroHemocentro" style={{textDecoration:"none"}}><h4>Cadastrar Hemocentro</h4></Link> */}
<a href="/CadastroHemocentro" style={{textDecoration:"none"}}> <h4>Cadastrar Hemocentro</h4> </a>
<p>Cadastre os dados do hemocentros na plataforma</p>
</div>
</div>
<div className="card">
<img src={IconBolsaDeSangue} className="inCard" />
<div className="miniCard">
{/* <Link to="/Campanha" style={{textDecoration:"none"}}><h4>Listar Campanhas</h4></Link> */}
<a href="/Campanha" style={{textDecoration:"none"}}><h4>Listar Campanhas</h4> </a>
<p>Cadastre novas campanhas e liste todas as já cadastradas na plataforma </p>
</div>
</div>
<div className="card">
<img src={IconDash} className="inCard" />
<div className="miniCard">
{/* <Link to="/Dashboard" style={{textDecoration:"none"}}><h4>Dashboard</h4></Link> */}
<a href="/Dashboard" style={{textDecoration:"none"}}><h4>Dashboard</h4></a>
<p>Veja todas as informações da plataforma detalhadamente através de gráficos e tabelas.</p>
</div>
</div>
</div>
</div>
);
}
} |
JavaScript | class SkillAndHistory extends Component {
state = { dialogOpen: false, index: 0 };
constructor(props) {
super(props);
Moment.locale("en");
}
linkDecorator = (href, text, key) => (
<a
href={href}
key={key}
target="_blank"
rel="noopener noreferrer"
style={{ color: this.props.colors.background }}
>
{text}
</a>
);
openDialog = (event, index) => {
event.stopPropagation();
this.setState({ dialogOpen: true, index });
};
closeDialog = event => {
event.stopPropagation();
this.setState({ dialogOpen: false });
};
renderDialog(item) {
return (
<Dialog
open={this.state.dialogOpen}
onClose={this.closeDialog}
fullWidth={true}
maxWidth="lg"
>
<DialogTitle id="alert-dialog-title">
<div
style={{
display: "flex",
justifyContent: "space-between"
}}
>
{item.title}
{item.position ? `, ${item.position}` : ""}
{this.renderSubItem(item, true)}
</div>
</DialogTitle>
<DialogContent>
<DialogContentText
id="alert-dialog-description"
style={{ whiteSpace: "pre-line" }}
>
<Linkify componentDecorator={this.linkDecorator}>
{item.description}
</Linkify>
</DialogContentText>
</DialogContent>
</Dialog>
);
}
renderSubItem(item, isDialog) {
if (item.level) {
return (
<img
src={require(`../../../../assets/icons/${this.props.template}_${item.level}_star.png`)}
alt={`Level: ${item.level}`}
style={
isDialog
? {
height: 30,
margin: "auto 0px"
}
: { marginTop: 10, width: "70%" }
}
/>
);
} else {
var startDate = item.startDate
var endDate = item.endDate
if (startDate) {
startDate = Moment(startDate).format("MM/YY")
} else {
startDate = ""
}
if (endDate) {
endDate = Moment(endDate).format("MM/YY")
} else {
endDate = "Current";
}
return (
<Typography
variant="body1"
style={
isDialog
? {
height: 30,
width: 150,
textAlign: "end",
color: this.props.colors.primary
}
: {
marginTop: 10,
textAlign: "center",
color: this.props.colors.primary
}
}
>{`${startDate}-${endDate}`}</Typography>
);
}
}
render() {
const {
parentProps: { classes },
scrollNext,
offset,
items,
subTitle,
colors,
template
} = this.props;
return (
<>
<ParallaxLayer
offset={offset}
speed={0.5}
style={{
backgroundColor: colors.light,
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
onClick={() => scrollNext()}
/>
<ParallaxLayer
offset={offset + 0.1}
speed={1}
onClick={() => scrollNext()}
>
<div
style={{
display: "flex",
flexDirection: "column",
marginLeft: "10%",
marginRight: "10%"
}}
>
<SubTitle template={template}>{subTitle}</SubTitle>
<Grid
container
spacing={isMobile ? 1 : 4}
style={{ flexGrow: 1 }}
>
{items.map((item, index) => {
if (isMobile) {
return (
<Grid
item
xs="auto"
key={index}
onClick={event =>
this.openDialog(event, index)
}
style={{ width: "100%" }}
>
<Paper
className={
classes.mobileSkillContainer
}
>
<Typography variant="h6">
<Box
fontWeight="bold"
lineHeight="1em"
maxHeight="5em"
>
{item.title}
</Box>
</Typography>
</Paper>
</Grid>
);
} else {
return (
<Grid
item
xs="auto"
key={index}
onClick={event =>
this.openDialog(event, index)
}
>
<Paper
className={
classes.skillContainer
}
>
<Typography variant="h6">
<Box fontWeight="bold">
{index < 9
? `0${index + 1}`
: index + 1}
.
</Box>
</Typography>
<Typography
variant="h6"
style={{
marginTop: 10,
textAlign: "center",
display: "box",
height: 50
}}
>
<Box
fontWeight="bold"
lineHeight="1em"
maxHeight="5em"
>
{item.title}
</Box>
</Typography>
<div
style={{
display: "flex",
justifyContent: "center"
}}
>
{this.renderSubItem(
item,
false
)}
</div>
<Typography
style={{
color: colors.primary,
margin:
"40px 0px 20px 50%",
textAlign: "center",
borderRadius: 26,
borderWidth: 2,
borderColor:
colors.primary,
borderStyle: "solid",
width: "40%",
padding: 5,
fontWeight: "bold"
}}
>
DETAILS
</Typography>
</Paper>
</Grid>
);
}
})}
</Grid>
</div>
</ParallaxLayer>
{this.renderDialog(items[this.state.index])}
</>
);
}
} |
JavaScript | class GrPermission extends mixinBehaviors( [
AccessBehavior,
], GestureEventListeners(
LegacyElementMixin(
PolymerElement))) {
static get template() { return htmlTemplate; }
static get is() { return 'gr-permission'; }
static get properties() {
return {
labels: Object,
name: String,
/** @type {?} */
permission: {
type: Object,
observer: '_sortPermission',
notify: true,
},
groups: Object,
section: String,
editing: {
type: Boolean,
value: false,
observer: '_handleEditingChanged',
},
_label: {
type: Object,
computed: '_computeLabel(permission, labels)',
},
_groupFilter: String,
_query: {
type: Function,
value() {
return this._getGroupSuggestions.bind(this);
},
},
_rules: Array,
_groupsWithRules: Object,
_deleted: {
type: Boolean,
value: false,
},
_originalExclusiveValue: Boolean,
};
}
static get observers() {
return [
'_handleRulesChanged(_rules.splices)',
];
}
/** @override */
created() {
super.created();
this.addEventListener('access-saved',
() => this._handleAccessSaved());
}
/** @override */
ready() {
super.ready();
this._setupValues();
}
_setupValues() {
if (!this.permission) { return; }
this._originalExclusiveValue = !!this.permission.value.exclusive;
flush();
}
_handleAccessSaved() {
// Set a new 'original' value to keep track of after the value has been
// saved.
this._setupValues();
}
_permissionIsOwnerOrGlobal(permissionId, section) {
return permissionId === 'owner' || section === 'GLOBAL_CAPABILITIES';
}
_handleEditingChanged(editing, editingOld) {
// Ignore when editing gets set initially.
if (!editingOld) { return; }
// Restore original values if no longer editing.
if (!editing) {
this._deleted = false;
delete this.permission.value.deleted;
this._groupFilter = '';
this._rules = this._rules.filter(rule => !rule.value.added);
for (const key of Object.keys(this.permission.value.rules)) {
if (this.permission.value.rules[key].added) {
delete this.permission.value.rules[key];
}
}
// Restore exclusive bit to original.
this.set(['permission', 'value', 'exclusive'],
this._originalExclusiveValue);
}
}
_handleAddedRuleRemoved(e) {
const index = e.model.index;
this._rules = this._rules.slice(0, index)
.concat(this._rules.slice(index + 1, this._rules.length));
}
_handleValueChange() {
this.permission.value.modified = true;
// Allows overall access page to know a change has been made.
this.dispatchEvent(
new CustomEvent('access-modified', {bubbles: true, composed: true}));
}
_handleRemovePermission() {
if (this.permission.value.added) {
this.dispatchEvent(new CustomEvent(
'added-permission-removed', {bubbles: true, composed: true}));
}
this._deleted = true;
this.permission.value.deleted = true;
this.dispatchEvent(
new CustomEvent('access-modified', {bubbles: true, composed: true}));
}
_handleRulesChanged(changeRecord) {
// Update the groups to exclude in the autocomplete.
this._groupsWithRules = this._computeGroupsWithRules(this._rules);
}
_sortPermission(permission) {
this._rules = this.toSortedArray(permission.value.rules);
}
_computeSectionClass(editing, deleted) {
const classList = [];
if (editing) {
classList.push('editing');
}
if (deleted) {
classList.push('deleted');
}
return classList.join(' ');
}
_handleUndoRemove() {
this._deleted = false;
delete this.permission.value.deleted;
}
_computeLabel(permission, labels) {
if (!labels || !permission ||
!permission.value || !permission.value.label) { return; }
const labelName = permission.value.label;
// It is possible to have a label name that is not included in the
// 'labels' object. In this case, treat it like anything else.
if (!labels[labelName]) { return; }
const label = {
name: labelName,
values: this._computeLabelValues(labels[labelName].values),
};
return label;
}
_computeLabelValues(values) {
const valuesArr = [];
const keys = Object.keys(values)
.sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
for (const key of keys) {
let text = values[key];
if (!text) { text = ''; }
// The value from the server being used to choose which item is
// selected is in integer form, so this must be converted.
valuesArr.push({value: parseInt(key, 10), text});
}
return valuesArr;
}
/**
* @param {!Array} rules
* @return {!Object} Object with groups with rues as keys, and true as
* value.
*/
_computeGroupsWithRules(rules) {
const groups = {};
for (const rule of rules) {
groups[rule.id] = true;
}
return groups;
}
_computeGroupName(groups, groupId) {
return groups && groups[groupId] && groups[groupId].name ?
groups[groupId].name : groupId;
}
_getGroupSuggestions() {
return this.$.restAPI.getSuggestedGroups(
this._groupFilter,
MAX_AUTOCOMPLETE_RESULTS)
.then(response => {
const groups = [];
for (const key in response) {
if (!response.hasOwnProperty(key)) { continue; }
groups.push({
name: key,
value: response[key],
});
}
// Does not return groups in which we already have rules for.
return groups
.filter(group => !this._groupsWithRules[group.value.id]);
});
}
/**
* Handles adding a skeleton item to the dom-repeat.
* gr-rule-editor handles setting the default values.
*/
_handleAddRuleItem(e) {
// The group id is encoded, but have to decode in order for the access
// API to work as expected.
const groupId = decodeURIComponent(e.detail.value.id)
.replace(/\+/g, ' ');
// We cannot use "this.set(...)" here, because groupId may contain dots,
// and dots in property path names are totally unsupported by Polymer.
// Apparently Polymer picks up this change anyway, otherwise we should
// have looked at using MutableData:
// https://polymer-library.polymer-project.org/2.0/docs/devguide/data-system#mutable-data
this.permission.value.rules[groupId] = {};
// Purposely don't recompute sorted array so that the newly added rule
// is the last item of the array.
this.push('_rules', {
id: groupId,
});
// Add the new group name to the groups object so the name renders
// correctly.
if (this.groups && !this.groups[groupId]) {
this.groups[groupId] = {name: this.$.groupAutocomplete.text};
}
// Wait for new rule to get value populated via gr-rule-editor, and then
// add to permission values as well, so that the change gets propogated
// back to the section. Since the rule is inside a dom-repeat, a flush
// is needed.
flush();
const value = this._rules[this._rules.length - 1].value;
value.added = true;
// See comment above for why we cannot use "this.set(...)" here.
this.permission.value.rules[groupId] = value;
this.dispatchEvent(
new CustomEvent('access-modified', {bubbles: true, composed: true}));
}
_computeHasRange(name) {
if (!name) { return false; }
return RANGE_NAMES.includes(name.toUpperCase());
}
} |
JavaScript | class PlayerEventObserver {
// Called when a player has died, potentially by another player. |killer| may be NULL.
onPlayerDeath(player, killer, reason) {}
// Called when the |target| has just streamed in for the given |player|.
onPlayerStreamIn(player, target) {}
// Called when a player has reported taking damage by the |issuer|. Both are guaranteed to be
// valid Player instances. The other information is meta-data.
onPlayerTakeDamage(player, issuer, amount, weaponId, bodyPart) {}
// Called when a player has shot their weapon, and potentially hit something. The parameters are
// documented here: https://wiki.sa-mp.com/wiki/OnPlayerWeaponShot
onPlayerWeaponShot(player, weaponId, hitType, hitId, hitPosition) {}
} |
JavaScript | class MapView extends React.Component {
// Only change markers if there is a change in data
componentWillReceiveProps(nextProps) {
const { dispatch, googleScript, locations, infoMarker } = this.props;
let updateLocation = nextProps.locations;
if (!locations || !googleScript) return;
if (equals(locations, updateLocation)) mapActions.fetchGoogleMap(googleScript, dispatch, updateLocation, this.refs.gmap, infoMarker);
}
// Fetch data every 5 seconds
startPoll() {
this.timeout = setTimeout(() => {
const { dispatch, googleScript, fetching } = this.props;
if (!googleScript) return;
if (!fetching) dispatch(mapActions.fetchLocations(this.refs.gmap, false));
this.startPoll();
}, 2500);
}
componentWillUnmount() {
clearTimeout(this.timeout);
}
componentDidMount() {
const { dispatch, fetchedGoogle, fetchedLoc, googleScript, locations, infoMarker } = this.props;
const { gmap } = this.refs;
if (!fetchedGoogle) dispatch(mapActions.fetchLocations(gmap, true));
if (fetchedGoogle) mapActions.fetchGoogleMap(googleScript, dispatch, locations, gmap, infoMarker);
this.startPoll();
}
render() {
const { infoMarker } = this.props;
return (
<div class="page-wrapper" ref="mapView">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<h3 class="page-header">Map View</h3>
</div>
</div>
<div class="row">
<div class="col-lg-12 .col-xs-12">
<div class="table-responsive">
<h4>Company names & employees</h4>
<div class="map" ref="gmap"></div>
<InfoTable infoMarker={infoMarker}/>
</div>
</div>
</div>
</div>
</div>
);
}
} |
JavaScript | class PlayControl extends masters.PlayControl {
constructor(engine, options = {}) {
const audioContext = options.audioContext || defaultAudioContext;
const scheduler = getScheduler(audioContext);
super(scheduler, engine, options);
this.audioContext = audioContext;
}
} |
JavaScript | class AJAXPromise extends Promise {
/**
* Overriding `.then` to add XHR to child promise
*
* @public
* @return {AJAXPromise} child promise
*/
then() {
const child = super.then(...arguments);
child.xhr = this.xhr;
return child;
}
} |
JavaScript | class DefaultBlock extends AbstractBlock
{
init() {
super.init();
}
// initEvents(){
// super.initEvents();
// }
// destroyEvents(){
// super.destroyEvents();
// }
} |
JavaScript | class Controller {
constructor() {
this.api = new FlickrAPI();
this.udb = new UserDatabase();
this.idb = new ImageDatabase();
this.idb.bindUDB(this.udb);
this._processed_images = new Set();
this._excluded = new Set();
this._hidden = new Set();
this.r = new Renderer(this);
}
/**
* Takes a list of photo ids and queries which users have favorited them,
* then records those users into the udb, keeping track of which and how many
* photos were favorited for each user.
* Uses api.getImageFavorites() (flickr.photos.getFavorites)
* @param {(string[]|string)} photo_ids - an array of photo ids or a single photo id
*/
async processPhotos(photo_ids) {
if (typeof photo_ids === "string") {
photo_ids = [photo_ids]
}
const progress = new Progress().renderWith(this.r);
for (const photo_id of photo_ids) {
if (this._processed_images.has(photo_id)) {
progress.duplicate(photo_id);
continue;
}
this._processed_images.add(photo_id);
//Load the first page of faves for each image, get total number of pages
progress.await(this.api.getImageFavorites(photo_id).then((response) => {
const pages = response.pages;
// Load each subpage
for (let p = 2; p <= pages; p++) {
progress.awaitSub(this.api.getImageFavorites(photo_id, p).then(response => this.udb.add(response)));
}
this.udb.add(response);
})).catch(error => {
this._processed_images.delete(photo_id)
progress.error(photo_id, error)
});
}
progress.log()
// Wait for all the api call promises to settle
await progress.allSettled()
progress.done();
}
/**
* Take a list of user ids and queries their favorite photos, recording that data in the idb
* Uses api.getUserFavorites() (flickr.favorites.getPublicList)
* @param {(string[]|string)} user_ids - an array of user ids or a single user id
*/
async processUsers(user_ids) {
if (typeof user_ids === "string") {
user_ids = [user_ids]
}
const progress = new Progress().renderWith(this.r);
for (const user_id of user_ids) {
progress.await(this.loadUserFavorites(user_id, {progress: progress}))
}
progress.log()
// Wait for all the api call promises to settle
await progress.allSettled();
progress.done();
}
/**
* Load all pages of favorites for a user and add them to the db, returning a list of favorites
* @param {string} user_id
* @param {Object} [opts]
* @param {Object} [opts.discard] - do not add responses to database, only add to return value
* @param {Object} [opts.progress] - progress object to pass in
* @param {Object} [opts.max_pages] - max pages of faves to process per user
* @returns {string[]} - array of photo ids that the user has favorited
*/
async loadUserFavorites(user_id, opts = {}) {
const progress = opts.progress || new Progress()
const id_list = [];
// If "discard" opt is set, change idb to a dummy object that discards the response
const idb = opts.discard ? {add: () => null} : this.idb;
// Load the first page of faves for each user, get the total number of pages
progress.log()
await this.api.getUserFavorites(user_id).then((response) => {
const user = this.udb.get(user_id)
if (user) {
user.pages = response.pages
user.pages_processed = user.pages_processed || 0
}
const pages = Math.min(response.pages, opts.max_pages || 50);
if (response.pages > 50) {
console.warn(`user ${user_id} has more than 50 pages of favorites`)
}
const handleResponse = (response) => {
id_list.push(...response.photo.map(photo=>photo.id))
idb.add(response, { user_id: user_id });
if (user) {
user.pages_processed += 1
}
}
// Load each subpage
for (let i = 2; i <= pages; i++) {
progress.awaitSub(this.api.getUserFavorites(user_id, i).then(handleResponse))
}
handleResponse(response)
}).catch(error => {
progress.error(user_id, error)
})
if (!opts.progress) {
progress.done()
}
return id_list;
}
/**
* Query the favorite photos of the given user and then process them
* Uses api.getUserFavorites() (flickr.favorites.getPublicList)
* Uses api.getImageFavorites() (flickr.photos.getFavorites)
* @param {string} user_id
*/
async processPhotosFromUser(user_id) {
const photo_ids = await this.loadUserFavorites(user_id, {discard: true})
await this.processPhotos(photo_ids)
}
/**
* Process the favorites of the top num users in the database by score
* @param {number} num - number of users to process
* @param {number} starting_from - start from the nth user
*/
async processUsersFromDB(num = 20, starting_from = 0) {
if (this.udb.size() == 0) {
this.r.warnMessage("You have to find some twins first!");
return Promise.reject("UserDatabase was empty")
}
const users = this.udb.sortedList(num, starting_from).map(user => user.nsid)
await this.processUsers(users);
}
async processUsersFromDBSmart(max_requests = 1000) {
if (this.udb.size() == 0) {
this.r.warnMessage("You have to find some twins first!");
return Promise.reject("UserDatabase was empty")
}
let resources_remaining = Math.min(this.api.getRemainingAPICalls(), max_requests)
const maxUsers = Math.min(Math.floor(resources_remaining/5), 100)
const sortedUsers = this.udb.sortedList(resources_remaining)
let currentUsers = sortedUsers.slice(0, maxUsers)
const userqueue = sortedUsers.slice(maxUsers)
const scoremult = {}
const progress = new Progress().renderWith(this.r)
console.log({resources_remaining:resources_remaining, maxUsers:maxUsers, sortedUsers:sortedUsers, currentUsers:currentUsers, userqueue:userqueue, scoremult:scoremult, progress:progress}) //TODO
const compareScores = (a, b) => b.score * scoremult[b.nsid] - a.score * scoremult[a.nsid];
const notExhausted = user => user.pages !== undefined && user.pages > user.current_page;
//request the initial page for user when first processed
const getInitialPage = (user) => {
const user_id = user.nsid
user.pages = undefined;
user.pages_processed = undefined;
user.current_page = 1
scoremult[user_id] = 0
resources_remaining -= 1
console.log(`getInitialpage(${user_id})`)
progress.await(this.api.getUserFavorites(user_id).then(response => {
this.idb.add(response, { user_id: user_id })
user.pages = response.pages;
user.pages_processed = 1
user.faves_processed = response.photo?.length || 0
user.faves_total = response.total
user.score = this.udb.scorer(user)
scoremult[user_id] = 1
console.log(`${user_id}: ${user.name}'s score is ${user.score} * ${scoremult[user_id]} = ${user.score * scoremult[user_id]}`) //TODO
})).catch(error => {
progress.error(user_id, error)
user.pages = 0;
user.pages_processed = 0
user.faves_processed = 0
user.total = 0
scoremult[user_id] = 0
})
}
//request the next page of user's favorites
const getNextPage = (user) => {
const user_id = user.nsid
resources_remaining -= 1
user.current_page += 1
progress.awaitSub(this.api.getUserFavorites(user_id, user.current_page).then(response => {
this.idb.add(response, { user_id: user_id })
user.pages_processed += 1
user.faves_processed += response.photo?.length || 0
user.score = this.udb.scorer(user)
console.log(`${user_id}: ${user.name}'s score is ${user.score} * ${scoremult[user_id]} = ${user.score * scoremult[user_id]}`) //TODO
})).catch(error => {
progress.error(user_id, error)
user.pages = 0;
user.pages_processed = 0
scoremult[user_id] = 0
})
//bump user's score down by 10% for sorting purposes
scoremult[user_id] = scoremult[user_id] * 0.90
if (!notExhausted(user)) {
scoremult[user_id] = 0;
}
}
// // logic // //
//get those initial pages
for (const user of currentUsers) {
getInitialPage(user);
}
progress.log()
//wait until 75% of requests have been processed
await progress.waitForProgress(Math.ceil(maxUsers / 4))
//main loop
while(resources_remaining > 0 && currentUsers.length + userqueue.length > 0) {
//remove users with no pages left to query
currentUsers = currentUsers.filter(notExhausted);
//fill the working set of users back up from the queue
while (currentUsers.length < Math.min(maxUsers * 0.75, resources_remaining / 2) && userqueue.length > 0) {
const userToAdd = userqueue.shift();
getInitialPage(userToAdd);
currentUsers.push(userToAdd);
if (resources_remaining <= 0) {
break;
}
}
//wait until 75% of requests have been processed
await progress.waitForProgress(Math.ceil(maxUsers / 4))
//sort users by modified score
currentUsers.sort(compareScores)
//grab the user at the top of the list
const user = currentUsers[0]
if (!(notExhausted(user))){
continue; //need to go to filter step early
}
//grab the next page of faves and bump user's score down by 10% for sorting purposes
getNextPage(user);
}
// Wait for all the api call promises to settle
await progress.allSettled();
progress.done();
console.log({resources_remaining:resources_remaining, maxUsers:maxUsers, sortedUsers:sortedUsers, currentUsers:currentUsers, userqueue:userqueue, scoremult:scoremult, progress:progress}) //TODO
}
/**
* Make sure the specified photos are loaded into idb so you can display them
* Uses api.getPhotoInfo() (flickr.photos.getInfo)
* @param {Array} photo_ids - List of photo ids to load
*/
async loadPhotos(photo_ids) {
if (typeof photo_ids === "string") {
photo_ids = [photo_ids]
}
const progress = new Progress()
for (const photo_id of photo_ids) {
if (!this.idb.has(photo_id)) {
progress.await(this.api.getPhotoInfo(photo_id).then(response => {
this.idb.add(response)
})).catch(error => {
progress.error(photo_id, error)
})
} else {
progress.duplicate()
}
}
progress.log()
await progress.allSettled()
progress.done()
}
/**
* Exclude ids from the process
* @param {Iterable} list - List of ids to exclude
*/
exclude(list) {
if (typeof list === "string") {
list = [list]
}
for (const i of list) {
this._excluded.add(i);
}
}
/**
* Hide ids from being displayed by the renderer
* @param {Iterable} list - List of ids to hide
*/
hide(list) {
if (typeof list === "string") {
list = [list]
}
for (const i of list) {
this._hidden.add(i);
}
}
/**
* @returns {Set} - Set of all the ids which should be hidden
*/
getHidden() {
return new Set([...this._processed_images, ...this._excluded, ...this._hidden])
}
/**
* Returns true if the given id should be hidden
* @param {string} id - Photo id to check
* @returns {boolean}
*/
isHidden(id) {
return this._processed_images.has(id) || this._excluded.has(id) || this._hidden.has(id)
}
} |
JavaScript | class FAConst extends _node.Node {
// Provide a node instance
/**
* Construct a new FAConst node
*/
constructor() {
super("FAConst");
this.functional = true;
this.inputs = [new _socket.InputSocket("Val", this, _type.Types.STRING, "[0, 1, 2]")];
this.outputs = [new _socket.OutputSocket("Val", this, _type.Types.ARRAY, [], false)];
this.nexts = [];
this.prev = null;
}
/**
* Clone this node
* @param {Function} factory The factory class function
*/
clone(factory = FAConst.instance) {
return super.clone(factory);
}
/**
* The process function
*/
async process() {
await this.evaluateInputs(); // Convert the constant/input value to an array
try {
this.output("Val").value = JSON.parse(this.input("Val").value);
if (!Array.isArray(this.output("Val").value)) {
throw new Error(`The input value (${this.output("Val").value}) is not an array`);
}
} catch (error) {
// TODO: Manage error
console.log(error);
}
}
} |
JavaScript | class LoginForm extends Component {
constructor(props) {
super(props);
/**
* @typedef {Object} ComponentState
* @property {string} email - The user email.
* @property {string} password - The user password.
* @property {string} error - Login error message.
* @property {boolean} loading - Indicates whether loading is visible
* (Loader should be visible when the app is sending data to the server).
*/
/** @type {ComponentState} */
this.state = {
email: '',
password: '',
error: '',
loading: false
};
}
/**
* @description Callback executed when login button is pressed.
*/
onButtonPress() {
const { email, password } = this.state;
// Validate inputs
if (!email) {
this.setState({ error: 'Email field is required.' });
return;
} else if (!/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/.test(email)) {
this.setState({ error: 'Invalid email.' });
return;
} else if (!password) {
this.setState({ error: 'Password field is required.' });
return;
}
this.setState({ error: '', loading: true });
firebase.auth().signInWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(this.onLoginFail.bind(this));
}
/**
* @description Callback executed when the user login is successful.
*/
onLoginSuccess() {
this.setState({
email: '',
password: '',
loading: false,
error: ''
});
}
/**
* @description Callback executed when the user login fails.
* @param {string} error - Login error message.
*/
onLoginFail(error) {
console.log(error);
let errorMessage = '\nAuthentication Failed.\n';
errorMessage += (error.message) ? error.message : '';
this.setState({
error: errorMessage,
loading: false
});
}
/**
* @description Render the Login button based on the loading state.
*/
renderButton() {
if (this.state.loading) {
return <Spinner size="small" />;
}
return (
<Button onPress={this.onButtonPress.bind(this)}>
Sign In
</Button>
);
}
render() {
const { errorTextStyle, linkStyle } = styles;
return (
<Card>
<CardSection>
<TextField
placeholder="[email protected]"
label="Email"
value={this.state.email}
onChangeText={email => this.setState({ email })}
/>
</CardSection>
<CardSection>
<TextField
secureTextEntry
placeholder="password"
label="Password"
value={this.state.password}
onChangeText={password => this.setState({ password })}
/>
</CardSection>
<Text style={errorTextStyle}>
{this.state.error}
</Text>
<CardSection>
{this.renderButton()}
</CardSection>
<CardSection>
<Text>Don{'\''}t have an account? </Text>
<TouchableOpacity onPress={this.props.onSignUpPressed}>
<Text style={linkStyle}>
Sign Up
</Text>
</TouchableOpacity>
</CardSection>
</Card>
);
}
} |
JavaScript | class RemoteContent extends Component {
state = {
showSidebar: false
}
static propTypes = {
className: PropTypes.string,
}
static defaultProps = {
className: "wp-content",
}
initVideos() {
const videos = document.querySelectorAll(".video video.mejs__player")
videos.forEach((video) => {
new window.MediaElementPlayer(video, {
renderers: ["html5"],
stretching: "responsive",
})
})
}
initLightbox() {
const getSrc = (elem) => elem.getAttribute('data-src')
const getPrev = (elem) => document.getElementById(elem.getAttribute('data-prev'))
const getNext = (elem) => document.getElementById(elem.getAttribute('data-next'))
const open = function(elem) {
// elem = img
const init = (instance) => {
// instance.element() = basicLightbox
instance.element().querySelector('img').src = ''
instance.element().querySelector('img').src = getSrc(elem)
const close = instance.element().querySelector('#close')
const prev = instance.element().querySelector('#prev')
const next = instance.element().querySelector('#next')
prev.onclick = (e) => {
elem = getPrev(elem)
init(instance)
}
next.onclick = (e) => {
elem = getNext(elem)
init(instance)
}
close.onclick = (e) => {
instance.close()
}
}
basicLightbox.create('<img>', {
beforePlaceholder: '<button id="prev" class="icon icon-prev">←</button><button id="close" class="icon icon-quiz-fail-box"></button>',
afterPlaceholder : '<button id="next" class="icon icon-next">→</button>',
beforeShow: (instance) => {
let closer = instance.element().querySelector('#close');
let prev = instance.element().querySelector('#prev');
let next = instance.element().querySelector('#next');
let imgcontainer = instance.element().querySelector('.basicLightbox__placeholder');
imgcontainer.appendChild(closer);
imgcontainer.appendChild(prev);
imgcontainer.appendChild(next);
document.body.classList.add('noScroll');
init(instance)
// swipe feature
let touchstartX = 0;
let touchendX = 0;
const gestureZone = instance.element().querySelector('img')
gestureZone.addEventListener('touchstart', function (event) {
touchstartX = event.changedTouches[0].screenX;
}, false);
gestureZone.addEventListener('touchend', function (event) {
touchendX = event.changedTouches[0].screenX;
if (touchendX < touchstartX) {
// console.log('Swiped left');
next.click()
}
if (touchendX > touchstartX) {
// console.log('Swiped right');
prev.click()
}
// if (touchendY === touchstartY) {
// console.log('Tap');
// }
}, false);
},
beforeClose: (instance) => {
document.body.classList.remove('noScroll');
}
}).show()
}
Array.prototype.forEach.call(document.querySelectorAll('a.gallery__link'), function(elem) {
elem.onclick = function(e) {
e.preventDefault()
open(elem.querySelector('img'))
}
})
document.querySelectorAll("a.image__link").forEach(function(elem) {
const href = elem.getAttribute("href")
const instance = basicLightbox.create(`<img src="${href}">`,{
beforeShow: (instance) => {
let closer = instance.element().querySelector('#close');
let imgcontainer = instance.element().querySelector('.basicLightbox__placeholder');
imgcontainer.appendChild(closer);
closer.onclick = (e) => {
instance.close()
}
},
beforePlaceholder: '<button id="close" class="icon icon-quiz-fail-box"></button>',
})
elem.onclick = function(e) {
e.preventDefault()
instance.show()
}
})
}
initAccordion() {
let toggler = document.querySelectorAll(".accordion__panel-heading")
;[].forEach.call(toggler, function(el) {
el.onclick = function(e) {
if (e.target && e.target.nodeName === "H3") {
if (e.target.classList.contains("active")) {
e.target.classList.remove("active")
} else {
for (var i = 0; i < toggler.length; i++) {
toggler[i].classList.remove("active")
}
e.target.classList.add("active")
}
}
}
})
}
componentDidMount() {
this.initVideos()
this.initLightbox()
this.initAccordion()
}
componentDidUpdate() {
this.initVideos()
this.initLightbox()
this.initAccordion()
}
shouldComponentUpdate() {
return true
}
componentWillReceiveProps() {
this.initAccordion()
}
render() {
return (
<div>
<div className={this.props.className} dangerouslySetInnerHTML={{__html: this.props.children}} />
</div>
)
}
} |
JavaScript | class Validate {
constructor(disable) {
this.disabled = disable;
}
validate(result) {
const errors = [];
const logPrepend = `Year ${result.year} - Place ${result.place_overall}`;
if (!this.disabled.place_overall) {
if (!this._isPlace(result.place_overall)) {
errors.push(
`Missing or invalid place overall founrdin year ${result.year}.`
);
return { isValid: false, errors };
}
}
if (!this.disabled.gender) {
if (!this._isGender(result.gender)) {
errors.push(`${logPrepend}: Missing or invalid gender.`);
}
}
if (!this.disabled.place_gender) {
if (!this._isPlace(result.place_gender)) {
errors.push(`${logPrepend}: Missing or invalid place in gender.`);
}
}
if (!this.disabled.place_in_age_group) {
if (!this._isPlace(result.place_in_age_group)) {
errors.push(`${logPrepend}: Missing or invalid place in age group.`);
}
}
if (!this.disabled.age_group) {
if (!this._isAgeGroup(result.age_group)) {
errors.push(`${logPrepend}: Missing or invalid age group.`);
}
}
if (!this.disabled.gun_pace) {
if (!this._isPaceOrTime(result.gun_pace)) {
errors.push(`${logPrepend}: Missing or invalid gun pace.`);
}
}
if (!this.disabled.gun_time) {
if (!this._isPaceOrTime(result.gun_time)) {
errors.push(`${logPrepend}: Missing or invalid gun time.`);
}
}
if (!this.disabled.net_pace) {
if (!this._isPaceOrTime(result.net_pace)) {
errors.push(`${logPrepend}: Missing or invalid net pace.`);
}
}
if (!this.disabled.net_time) {
if (!this._isPaceOrTime(result.net_time)) {
errors.push(`${logPrepend}: Missing or invalid net time.`);
}
}
if (!this.disabled.first_name) {
if (!this._isName(result.first_name)) {
errors.push(`${logPrepend}: Missing or invalid first name.`);
}
}
if (!this.disabled.last_name) {
if (!this._isName(result.last_name)) {
errors.push(`${logPrepend}: Missing or invalid last name.`);
}
}
if (!this.disabled.state) {
if (!this._isState(result.state)) {
errors.push(`${logPrepend}: Missing or invalid state.`);
}
}
if (!this.disabled.city) {
if (!this._isCity(result.city)) {
errors.push(`${logPrepend}: Missing or invalid city.`);
}
}
if (!this.disabled.country) {
if (!this._isCountry(result.country)) {
errors.push(`${logPrepend}: Missing or invalid country.`);
}
}
return {
isValid: errors.length > 0 ? false : true,
errors,
};
}
_isPlace(place) {
return typeof place === `number` && place > 0;
}
_isGender(gender) {
return typeof gender === `string` && [`MALE`, `FEMALE`].includes(gender);
}
_isAgeGroup(group) {
// TODO: Check against regexp
return typeof group === `string` && group.length > 0;
}
_isPlaceOverall(place) {
return typeof place === `number` && place > 0;
}
_isPaceOrTime(time) {
// TODO: Check against regexp
return typeof time === `string` && time.length > 0;
}
_isName(name) {
return typeof name === `string` && name.length > 0;
}
_isCity(city) {
// TODO: Check with a city list
return typeof city === `string` && city.length > 0;
}
_isState(state) {
// TODO: Check with a state list
return typeof state === `string` && state.length > 0;
}
_isCountry(country) {
// TODO: Check with a country list
return typeof country === `string` && country.length > 0;
}
} |
JavaScript | class DistributionBuilder extends ConfigBuilder {
/**
* Creates the distribution builder.
* @param {Object} [config={}] - The initial configuration values
*/
constructor(config = {}) {
super(merge(configDefaults, config));
}
/**
* Factory method to create a new `DistributionBuilder` from an existing
* configuration.
* @param {ConfigBuilder} configBuilder - The builder to extend
* @returns {DistributionBuilder} - The new distribution builder
*/
static extends(configBuilder) {
return new DistributionBuilder(configBuilder.config);
}
/**
* Specifies that the output should be minified.
* @param {boolean} [use=true] - If true, turns on minification
* @returns {DistributionBuilder} - The 'this' to chain builder methods
*/
minimize(use = true) {
this.config.minimize = use;
return this;
}
/**
* Runs the build, transpiling and bundling the input
* sources.
* @param {function(err, stats)} callback - Callback to run on build completion
*/
build(callback) {
const compiler = webpack(this.getConfig());
compiler.run(callback);
}
} |
JavaScript | class InfoDialogCommand {
static create(filename) {
const commandData = JSON.parse(readFile(filename));
if (typeof commandData !== 'object' || !commandData.hasOwnProperty('type'))
throw new Error('Invalid format for the command file: ' + filename);
let command = null;
switch (commandData.type) {
case 'message':
command = new MessageCommand(commandData.data);
break;
case 'message-menu':
command = new MessageMenuCommand(commandData.data, commandData.title);
break;
default:
throw new Error('Invalid command type: ' + commandData.type);
}
return command.__proto__.show.bind(command);
}
} |
JavaScript | class MessageCommand {
constructor(message) {
if (Array.isArray(message))
message = message.join('\n');
this.message_ = new MessageBox(message);
}
// Displays the message to the |player|. The |parameters| are ignored.
show(player, parameters) {
this.message_.displayForPlayer(player);
}
} |
JavaScript | class MessageMenuCommand {
constructor(messages, title) {
this.menu_ = new Menu(title);
Object.keys(messages).forEach(subject => {
const message = new MessageBox(messages[subject].join('\n'));
this.menu_.addItem(subject, player => message.displayForPlayer(player));
});
}
// Displays the menu to the |player|. The |parameters| are ignored.
show(player, parameters) {
this.menu_.displayForPlayer(player);
}
} |
JavaScript | class GameObject extends PIXI.Sprite {
/**
* Creates a new GameObject.
* @param {PIXI.Texture} texture The texture associated with this sprite
* @param {string} id Unique identifier- for example, socket ID for players, numerical ID for atoms
* @param {number} x Global x-coordinate
* @param {number} y Global y-coordinate
* @param {number} vx Horizontal velocity
* @param {number} vy Vertical velocity
*/
constructor (texture, id, x, y, vx, vy) {
super(texture)
this.id = id
this.posX = x
this.posY = y
this.vx = vx
this.vy = vy
this.destroyed = false
app.stage.addChild(this)
}
/**
* Sets global coordinates of this player
* @param {number} newX New x-coordinate to move to
* @param {number} newY New y-coordinate to move to
*/
setCoordinates (newX, newY) {
this.posX = newX
this.posY = newY
}
/**
* Sets global coordinates and speeds of this player
* @param {number} newX New x-coordinate to move to
* @param {number} newY New y-coordinate to move to
* @param {number} vx New x velocity
* @param {number} vy New y velocity
*/
setData (newX, newY, vx, vy) {
this.setCoordinates(newX, newY)
this.vx = vx
this.vy = vy
}
/**
* Call during tick() if necessary.
* Draws object in the correct position on the player screen.
*/
draw () {
if (player !== undefined && !this.destroyed) {
this.x = screenCenterX + this.posX - player.posX
this.y = screenCenterY + player.posY - this.posY
}
}
/** TEMP
* Moves this object to (9999, 9999) on local screen space, effectively
* hiding it from view.
*/
hide () {
// console.warn('hide() is called');
if (this.transform === null || this.transform === undefined) {
console.warn('hide() function exception. THIS IS ABNORMAL. The following object contains invalid transform object:')
console.warn(this)
return 1
}
this.x = 9999
this.y = 9999
}
/**
* Override optional. Called once, during game setup phase.
*/
setup () {
}
/**
* Override optional. Default behavior: handles movement. Call super.tick() from child class if movable.
* @param {boolean} noDraw - true if tick() should only process movement, not drawing.
*/
tick (noDraw) {
// Prevent drifting due to minimal negative values
if (this.destroyed) {
return
}
if (Math.abs(this.vx) < GLOBAL.DEADZONE) {
this.vx = 0
}
if (Math.abs(this.vy) < GLOBAL.DEADZONE) {
this.vy = 0
}
// Change position based on speed and direction. Don't allow objects to go out of bounds
if ((this.vx > 0 && this.posX < MAP_LAYOUT[0].length * GLOBAL.GRID_SPACING * 2 - GLOBAL.GRID_SPACING) || (this.vx < 0 && this.posX > 0)) {
this.posX += this.vx
}
if ((this.vy > 0 && this.posY < (MAP_LAYOUT.length - 1) * GLOBAL.GRID_SPACING * 2) || (this.vy < 0 && this.posY > -GLOBAL.GRID_SPACING)) {
this.posY += this.vy
}
if (this.ignited) {
this.texture = spritesheet.textures[GLOBAL.IGNITE_SPRITE]
}
if (!noDraw) {
this.draw()
}
}
/**
* Destroyes the Sprite
*/
destroy () {
this.destroyed = true
super.destroy()
}
} |
JavaScript | class sfx {
constructor(root){
this.alert = [new p5.MonoSynth(), new p5.MonoSynth(), new p5.MonoSynth(), new p5.MonoSynth()];
for (var i = 0; i < 4; i++)
this.alert[i].setADSR(0.001, 0.3, 0.9, 0.08);
this.root = root;
this.volMain = 1;
}
playAlert(nVel, volMain) {
this.alert[0].play(this.root * (1.06 / 2));
this.alert[1].play(this.root * (1.06), this.volMain * this.nVel / 3);
this.alert[2].play(this.root * (2 * 1.06), this.volMain * this.nVel / 6);
this.alert[3].play(this.root * (4 * 1.06), this.volMain * this.nVel / 8);
}
setVolume(volMain, nVel){
this.alert[0].amp(this.volMain * this.nVel, 0.01);
this.alert[1].amp(volMain * this.nVel / 3, 0.01)
this.alert[2].amp(this.volMain * this.nVel / 6, 0.01);
this.alert[3].amp(this.volMain * this.nVel / 8, 0.01);
}
} |
JavaScript | class Tax extends Tile {
/**
* Adds tax graphic and price text to the tile.
*
* @param {Phaser.Scene} scene The scene this belongs to.
* @param {Board} board The board this tile belongs to.
* @param {TileConfig} config The tile configuration to observe.
*/
constructor(scene, board, config) {
super(scene, board, config);
const x = this.background.x + (this.background.width / 2);
const y = this.background.y + (this.background.height / 2);
const graphic = new Phaser.GameObjects.Sprite(this.scene, x, y, "tiles", config.graphic);
this.cost = config.cost;
this.text.setY(this.y + 10);
const string = `Pay £${this.cost}`;
const costText = new Phaser.GameObjects.Text(this.board.scene, this.x, this.y + 80, string, CashTextStyle);
costText.setStyle({
fixedWidth: this.background.width,
});
this.add([graphic, costText]);
}
/**
* Withdraws tax fee from player and deposits fee
* onto the Free Parking tile.
*
* @param {Player} player The player to charge tax on.
* @override
*/
onLanded(player) {
super.onLanded(player);
player.charge(this.cost, this.game.bank, () => this.game.showSaleInterface(player));
}
} |
JavaScript | class ReadBuffer {
constructor(buffer) {
this.buffer = buffer;
this.read_offset = 0;
}
remaining() {
if (this.read_offset >= this.buffer.length) return null;
return this.buffer.slice(this.read_offset);
}
readInt8() {
const result = this.buffer.readInt8(this.read_offset);
this.read_offset += 1;
return result;
}
readInt16BE() {
const result = this.buffer.readInt16BE(this.read_offset);
this.read_offset += 2;
return result;
}
readUInt16BE() {
const result = this.buffer.readUInt16BE(this.read_offset);
this.read_offset += 2;
return result;
}
readInt32BE() {
const result = this.buffer.readInt32BE(this.read_offset);
this.read_offset += 4;
return result;
}
readUInt32BE() {
const result = this.buffer.readUInt32BE(this.read_offset);
this.read_offset += 4;
return result;
}
readInt64BE() {
const result = (new Int64BE(this.buffer, this.read_offset)).toNumber();
this.read_offset += 8;
return result;
}
readUInt64BE() {
const result = (new Uint64BE(this.buffer, this.read_offset)).toNumber();
this.read_offset += 8;
return result;
}
readDoubleBE() {
const result = this.buffer.readDoubleBE(this.read_offset);
this.read_offset += 8;
return result;
}
slice(size) {
const result = this.buffer.slice(this.read_offset, this.read_offset + size);
this.read_offset += size;
return result;
}
} |
JavaScript | class Modal extends Component {
static displayName = 'Modal';
state = {
animationClass: '',
};
componentWillReceiveProps(nextProps) {
this.props.show !== nextProps.show &&
nextProps.show &&
setTimeout(() => {
this.setState({ animationClass: 'in' });
}, 0);
}
closeModal = () => {
this.setState({ animationClass: '' });
return setTimeout(() => {
this.props.onHide();
}, 300);
}
render() {
const {
show,
className,
size,
backdrop,
backdropClickExit,
escapeExits,
htmlId,
headerLabel,
showCloseButton,
applicationId,
icon,
focusDialog
} = this.props;
const getIcon = () => {
if (icon.type.displayName === 'Icon') {
return icon;
}
throw new Error(`icon prop needs to be of type Icon.`);
};
const modalContent = (
<div className={`cui-modal__content`}>
{icon && size === 'dialog' && getIcon() && (
<div className="cui-modal__left-pane">
{icon}
</div>
)}
<div className="cui-modal__right-pane">
{headerLabel && (
<ModalHeader
showCloseButton={showCloseButton}
headerLabel={headerLabel}
onHide={this.closeModal}
/>
)}
{this.props.children}
</div>
</div>
);
const renderModal = () => {
return (
show && (
<AriaModal
onExit={this.closeModal}
getApplicationNode={() => document.querySelector(`#${applicationId}`)}
dialogClass={
`cui-modal` +
` cui-modal--${size}` +
` ${this.state.animationClass}` +
`${(className && ` ${className}`) || ''}`
}
includeDefaultStyles={false}
titleId={htmlId}
underlayClass={
backdrop
? `cui-modal__backdrop fade` + ` ${this.state.animationClass}`
: ''
}
underlayClickExits={backdropClickExit}
escapeExits={escapeExits}
focusDialog={focusDialog}
>
{modalContent}
</AriaModal>
)
);
};
return renderModal();
}
} |
JavaScript | class CubeFacade extends MeshFacade {
get geometry() {
return getBoxGeometry()
}
set size(size) {
this.scale = size
}
get size() {
return this.scale
}
} |
JavaScript | class DiscussionHero extends Component {
view() {
return (
<header className="Hero DiscussionHero">
<div className="container">
<ul className="DiscussionHero-items">{listItems(this.items().toArray())}</ul>
</div>
</header>
);
}
/**
* Build an item list for the contents of the discussion hero.
*
* @return {ItemList}
*/
items() {
const items = new ItemList();
const discussion = this.props.discussion;
const badges = discussion.badges().toArray();
if (badges.length) {
items.add('badges', <ul className="DiscussionHero-badges badges">{listItems(badges)}</ul>, 10);
}
items.add('title', <h2 className="DiscussionHero-title">{discussion.title()}</h2>);
return items;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.