Need to edit the code "user info" for sdk ZKTeco device fb100 - zkteco

I have this code working 100% but with one device zkt fb100,This code is for set user name ,card number , with id to the device to register it:
public int sta_SetUserInfo(ListBox lblOutputInfo, TextBox txtUserID, TextBox txtName, ComboBox cbPrivilege, TextBox txtCardnumber, TextBox txtPassword)
{
if (GetConnectState() == false)
{
lblOutputInfo.Items.Add("*Please connect first!");
return -1024;
}
if (txtUserID.Text.Trim() == "" || cbPrivilege.Text.Trim() == "")
{
lblOutputInfo.Items.Add("*Please input data first!");
return -1023;
}
int iPrivilege = cbPrivilege.SelectedIndex;
bool bFlag = false;
if (iPrivilege == 5)
{
lblOutputInfo.Items.Add("*User Defined Role is Error! Please Register again!");
return -1023;
}
/*
if(iPrivilege == 4)
{
axCZKEM1.IsUserDefRoleEnable(iMachineNumber, 4, out bFlag);
if (bFlag == false)
{
lblOutputInfo.Items.Add("*User Defined Role is unable!");
return -1023;
}
}
*/
//lblOutputInfo.Items.Add("[func IsUserDefRoleEnable]Temporarily unsupported");
int iPIN2Width = 0;
int iIsABCPinEnable = 0;
int iT9FunOn = 0;
string strTemp = "";
axCZKEM1.GetSysOption(GetMachineNumber(), "~PIN2Width", out strTemp);
iPIN2Width = Convert.ToInt32(strTemp);
axCZKEM1.GetSysOption(GetMachineNumber(), "~IsABCPinEnable", out strTemp);
iIsABCPinEnable = Convert.ToInt32(strTemp);
axCZKEM1.GetSysOption(GetMachineNumber(), "~T9FunOn", out strTemp);
iT9FunOn = Convert.ToInt32(strTemp);
/*
axCZKEM1.GetDeviceInfo(iMachineNumber, 76, ref iPIN2Width);
axCZKEM1.GetDeviceInfo(iMachineNumber, 77, ref iIsABCPinEnable);
axCZKEM1.GetDeviceInfo(iMachineNumber, 78, ref iT9FunOn);
*/
if (txtUserID.Text.Length > iPIN2Width)
{
lblOutputInfo.Items.Add("*User ID error! The max length is " + iPIN2Width.ToString());
return -1022;
}
if (iIsABCPinEnable == 0 || iT9FunOn == 0)
{
if (txtUserID.Text.Substring(0,1) == "0")
{
lblOutputInfo.Items.Add("*User ID error! The first letter can not be as 0");
return -1022;
}
foreach (char tempchar in txtUserID.Text.ToCharArray())
{
if (!(char.IsDigit(tempchar)))
{
lblOutputInfo.Items.Add("*User ID error! User ID only support digital");
return -1022;
}
}
}
int idwErrorCode = 0;
string sdwEnrollNumber = txtUserID.Text.Trim();
string sName = txtName.Text.Trim();
string sCardnumber = txtCardnumber.Text.Trim();
string sPassword = txtPassword.Text.Trim();
bool bEnabled = true;
/*if (iPrivilege == 4)
{
bEnabled = false;
iPrivilege = 0;
}
else
{
bEnabled = true;
}*/
axCZKEM1.EnableDevice(iMachineNumber, false);
axCZKEM1.SetStrCardNumber(sCardnumber);//Before you using function SetUserInfo,set the card number to make sure you can upload it to the device
if (axCZKEM1.SSR_SetUserInfo(iMachineNumber, sdwEnrollNumber, sName, sPassword, iPrivilege, bEnabled))//upload the user's information(card number included)
{
lblOutputInfo.Items.Add("Set user information successfully");
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
lblOutputInfo.Items.Add("*Operation failed,ErrorCode=" + idwErrorCode.ToString());
}
axCZKEM1.RefreshData(iMachineNumber);//the data in the device should be refreshed
axCZKEM1.EnableDevice(iMachineNumber, true);
return 1;
}
But if I have two device what should I change here ? .
I tried to change iMachineNumber to make first device is 1 and second device is 2 but not working too !

Finally I found the solution : in the button connect to device need to insert the above code in loop for one device and then next device and so on .

Related

Expected a value of type 'string' but got one of type 'int' - Flutter

I have a function that returns a String, but when I call this function, the app screen goes red and I get this error: Expected a value of type 'string' but got one of type 'int'.
Here is my function that returns a String:
checkProportion(String predominantGamete, String resultado) {
var countBrown = 0;
var countBlack = 0;
var countWhite = 0;
var proportionCamundongo =
'Proporção: ${countBrown}:${countBlack}:${countWhite}';
if (predominantGamete == 'recessiva_aa' &&
resultado.contains('A') &&
resultado.contains('P')) {
return countBrown += 1;
} else if (predominantGamete == 'recessiva_aa' &&
resultado.contains('A') &&
resultado.contains('pp')) {
return countBlack += 1;
} else if (predominantGamete == 'recessiva_aa' &&
resultado.contains('aa')) {
return countWhite += 1;
}
return proportionCamundongo;
}
Here is how I call the function:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
title: Text(
checkProportion(widget.predominant, widget.result),
),
),
How to solve this error?
Here is an image that shows the colors of each result:
The issue here is that you are returning early, not breaking the if statement, when you do something like return countBrown += 1;;
Try incrementing the counters, then using string interpolation to display the value:
String checkProportion(String predominantGamete, String resultado) {
int countBrown = 0;
int countBlack = 0;
int countWhite = 0;
if (predominantGamete == 'recessiva_aa' &&
resultado.contains('A') &&
resultado.contains('P')) {
countBrown += 1;
} else if (predominantGamete == 'recessiva_aa' &&
resultado.contains('A') &&
resultado.contains('pp')) {
countBlack += 1;
} else if (predominantGamete == 'recessiva_aa' &&
resultado.contains('aa')) {
countWhite += 1;
}
return 'Proporção: ${countBrown}:${countBlack}:${countWhite}';
}
I'd also recommend specifing the return type of the function (String), using the correct types for counters (int). That will help your compiler catch the issues as well.
It isn't my best work, and there is probably a better way to check for if a string contains all occurrence of multiple substrings, but here you go:
bool isColorContained(String resultado, Set<String> requirements) {
for(String requirement in requirements) {
if (!resultado.contains(requirement)) {
return false;
}
}
return true;
}
 
String checkProportion(String predominantGamete, String resultado) {
Map<ColorType, Set<String>> colorType = {
ColorType.brown: {'A', 'P'},
ColorType.black: {'A', 'pp'},
ColorType.white: {'aa'},
};
Map<ColorType, int> colorTypeCount = {
ColorType.brown: 0,
ColorType.black: 0,
ColorType.white: 0,
};
for(MapEntry<ColorType, Set<String>> entry in colorType.entries ) {
if(predominantGamete != 'recessiva_aa') continue;
bool contained = isColorContained(resultado, entry.value);
if(contained) {
int count = colorTypeCount[entry.key] ?? 0;
colorTypeCount[entry.key] = count + 1;
}
}
return 'Proporção: ${colorTypeCount[ColorType.brown]}:${colorTypeCount[ColorType.black]}:${colorTypeCount[ColorType.white]}';
}
 
Also, declare the ColorType enum:
enum ColorType {
brown, black, white
}
This will scale with as many colors and requirements you have, by adding to the ColorType enum, the colorType map, and the colorTypeCount map.

EF Core 3.x: duplicate value

I have the following code:
public class DeviceVerizon
{
public int DeviceId { get; set; }
public string InternalDeviceId { get; set; }
}
and
public class DeviceVerizonMap : IEntityTypeConfiguration<DeviceVerizon>
{
public void Configure(EntityTypeBuilder<DeviceVerizon> builder)
{
builder.ToTable(nameof(DeviceVerizon));
builder.HasKey(d => d.DeviceId);
builder.HasIndex(v => v.InternalDeviceId).IsUnique();
builder.HasOne(o => o.Device)
.WithOne(o => o.VerizonData)
.HasForeignKey<DeviceVerizon>(a => a.DeviceId)
.OnDelete(DeleteBehavior.Cascade)
.IsRequired()
;
}
}
so, InternalDeviceId is just unique index.
some code change InternalDeviceId for existing record and add new record with the previous InternalDeviceId.
So, localDevice.VerizonData.InternalDeviceId = 1420531689
I update it for new (remoteDevice.VerizonData.InternalDeviceId = '111111111')
localDevice.VerizonData = remoteDevice.VerizonData;
_context.Devices.Update(localDevice);
then add new record with remoteDevice.VerizonData.InternalDeviceId = 1420531689:
_context.Devices.Add(remoteDevice);
and after it I call:
await _context.SaveChangesAsync();
but I get an exception:
Cannot insert duplicate key row in object 'dbo.DeviceVerizon' with
unique index 'IX_DeviceVerizon_InternalDeviceId'. The duplicate key
value is (1420531689).
The full code:
foreach (var remoteDevice in remoteVerizonDevices)
{
var localDevice = allLocalDevicesWithIMEI.Where(a =>
(string.IsNullOrWhiteSpace(remoteDevice.IMEI)
&& a.VerizonData != null
&& a.VerizonData.InternalDeviceId == remoteDevice.VerizonData.InternalDeviceId
&& a.IMSI == remoteDevice.IMSI && a.ICCID == remoteDevice.ICCID)
|| a.IMEI == remoteDevice.IMEI).FirstOrDefault();
if (localDevice != null) // device with such imei already exists or IMEI is empty on Verizon, but InternalDeviceId is the same and ICCID with IMSI are the same
{
var verizonStatus = remoteDevice.VerizonData.State.ConvertToDeviceStatusFromVerizonStatus();
var existingRequest = _context.VerizonRequests.Where(a => a.DeviceId == localDevice.Id && a.Result == VerizonRequestResult.Pending).FirstOrDefault();
if (verizonStatus == DeviceStatus.Active && remoteDevice.IsVerizonLastActiveMoreThanDays(60))
{
// existing request for this device does not exist, create new
if (existingRequest == null)
{
localDevice.Status = DeviceStatus.PendingSuspend;
localDevice.DateStatusChanging = DateTime.UtcNow;
localDevice.LastStatusChangeSource = DeviceStatusChangeSource.Verizon;
// create verizon request to change status, because device is offline more than 60 days
verizonSuspensionList.Add(localDevice.Id);
}
}
else
{
// Is Verizon status of device is different than locally?
if (localDevice.Status != verizonStatus)
{
// check whether we have active verizon request, if not, then
if (existingRequest == null)
{
// device is suspended on suremdm, we should suspend on Verizon
if (localDevice.Status == DeviceStatus.Suspended
&& verizonStatus == DeviceStatus.Active)
{
if (localDevice.Tablet != null && localDevice.Tablet.TabletGroup.GroupName == SpecialSureMdmGroups.Suspended)
verizonSuspensionList.Add(localDevice.Id);
}
else if (localDevice.Status != DeviceStatus.Suspended && verizonStatus == DeviceStatus.Suspended)
{
// if device is suspended on verizon, we need to suspend on SureMdm
localDevice.Status = DeviceStatus.PendingSuspend;
localDevice.DateStatusChanging = DateTime.UtcNow;
localDevice.LastStatusChangeSource = DeviceStatusChangeSource.Verizon;
if (localDevice.Tablet != null)
{
localDevice.Tablet.SuspensionDate = DateTime.UtcNow;
sureMdmSuspensionList.Add(new Core.Dto.DeviceManagement.SureMdm.SureMdmMoveDeviceToSuspendedGroupDto
{
TabletId = localDevice.Tablet.TabletId,
CurrentGroupId = localDevice.Tablet.TabletGroupId
});
}
}
else
{
// other cases that device on verizon has different status, that locally
VerizonStatusIsDifferentEvent?.Invoke(
remoteDevice: remoteDevice,
verizonStatus: remoteDevice.VerizonData.State.ConvertToDeviceStatusFromVerizonStatus(),
localStatus: localDevice.Status);
}
}
}
}
var changes = DeviceIsChanged(remoteDevice, localDevice);
if (changes != null && changes.Count > 0)
modifiedDevices.Add((localDevice, changes));
var continueToUpdate = true;
// if verizon data does not exist, add it
if (localDevice.VerizonData == null)
{
var existingInternalVerizonDeviceIdRecord = allDeviceVerizons.Where(a => a.InternalDeviceId == remoteDevice.VerizonData.InternalDeviceId).FirstOrDefault();
if (existingInternalVerizonDeviceIdRecord != null)
{
DeviceWithTheSameVerizonDeviceIdAlreadyExistsEvent?.Invoke(remoteDevice: remoteDevice,
localDevice: existingInternalVerizonDeviceIdRecord.Device,
verizonDeviceId: remoteDevice.VerizonData.InternalDeviceId);
continueToUpdate = false;
}
}
if (continueToUpdate)
{
localDevice.VerizonData = remoteDevice.VerizonData;
if (!string.IsNullOrWhiteSpace(remoteDevice.ICCID))
localDevice.ICCID = remoteDevice.ICCID;
localDevice.EID = remoteDevice.EID;
localDevice.ESN = remoteDevice.ESN;
if (!string.IsNullOrWhiteSpace(remoteDevice.IMSI))
localDevice.IMSI = remoteDevice.IMSI;
if (!string.IsNullOrWhiteSpace(remoteDevice.MDN))
localDevice.MDN = remoteDevice.MDN;
localDevice.MEID = remoteDevice.MEID;
localDevice.MIN = remoteDevice.MIN;
localDevice.MSISDN = remoteDevice.MSISDN;
localDevice.SKU = remoteDevice.SKU;
localDevice.SyncVerizon = true;
if (string.IsNullOrWhiteSpace(localDevice.Name))
localDevice.Name = localDevice.IMEI;
if (!localDevice.DeviceModelId.HasValue)
{
var verizonGroup = allVerizonGroups.Where(a => a.VerizonGroupName == remoteDevice.VerizonData.GroupName).FirstOrDefault();
if (!verizonGroup.DeviceModelId.HasValue)
VerizonGroupIsNotLinkedWithDeviceModelEvent?.Invoke(remoteDevice);
else
localDevice.DeviceModelId = verizonGroup.DeviceModelId;
}
_context.Devices.Update(localDevice);
}
}
else
{
// validate by Internal Verizon DeviceId
var existingInternalVerizonDeviceIdRecord = allDeviceVerizons.Where(a => a.InternalDeviceId == remoteDevice.VerizonData.InternalDeviceId).FirstOrDefault();
if (existingInternalVerizonDeviceIdRecord != null)
{
DeviceWithTheSameVerizonDeviceIdAlreadyExistsEvent?.Invoke(remoteDevice: remoteDevice,
localDevice: existingInternalVerizonDeviceIdRecord.Device,
verizonDeviceId: remoteDevice.VerizonData.InternalDeviceId);
}
else
{
// add new record
if (!string.IsNullOrWhiteSpace(remoteDevice.IMEI))
remoteDevice.Name = remoteDevice.IMEI;
else if (!string.IsNullOrWhiteSpace(remoteDevice.VerizonData.PrimaryPlaceOfUseFirstName) || !string.IsNullOrWhiteSpace(remoteDevice.VerizonData.PrimaryPlaceOfUseLastName))
remoteDevice.Name = $"{remoteDevice.VerizonData.PrimaryPlaceOfUseFirstName} {remoteDevice.VerizonData.PrimaryPlaceOfUseLastName}";
else
remoteDevice.Name = Core.Constants.Common.Undefined;
// set device Model
var verizonGroup = allVerizonGroups.Where(a => a.VerizonGroupName == remoteDevice.VerizonData.GroupName).FirstOrDefault();
if (!verizonGroup.DeviceModelId.HasValue)
VerizonGroupIsNotLinkedWithDeviceModelEvent?.Invoke(remoteDevice);
else
remoteDevice.DeviceModelId = verizonGroup.DeviceModelId;
// set device status
remoteDevice.Status = remoteDevice.VerizonData.State.ConvertToDeviceStatusFromVerizonStatus();
if (!string.IsNullOrWhiteSpace(remoteDevice.VerizonData.CarrierName))
{
var verizonCarrier = allVerizonCarriers.Where(a => a.VerizonCarrierName == remoteDevice.VerizonData.CarrierName).FirstOrDefault();
if (verizonCarrier.CarrierId.HasValue)
remoteDevice.CarrierId = verizonCarrier.CarrierId;
else
{
// notify that carrier is not found locally
LocalCarrierIsNotFoundForNewDeviceEvent?.Invoke(remoteDevice);
}
}
remoteDevice.SyncVerizon = true;
_context.Devices.Add(remoteDevice);
newDevices.Add(remoteDevice);
}
}
}
await _context.SaveChangesAsync();
why so? only one record has 1420531689, old was updated for new value (111111111) and it saved in the one transaction... How to do it correctly?

E4X to JSON conversion fails for duplicate xml elements

Kindly see below code I am using to convert Mirth xml to JSON.
function E4XtoJSON(xml, ignored) {
var r, children = xml.*, attributes = xml.#*, length = children.length();
if(length == 0) {
r = xml.toString();
} else if(length == 1) {
var text = xml.text().toString();
if(text) {
r = text;
}
}
if(r == undefined) {
r = {};
for each (var child in children) {
var name = child.localName();
var json = E4XtoJSON(child, ignored);
var value = r[name];
if(value) {
if(value.length) {
value.push(json);
} else {
r[name] = [value, json]
}
} else {
r[name] = json;
}
}
}
if(attributes.length()) {
var a = {}, c = 0;
for each (var attribute in attributes) {
var name = attribute.localName();
if(ignored && ignored.indexOf(name) == -1) {
a["_" + name] = attribute.toString();
c ++;
}
}
if(c) {
if(r) a._ = r;
return a;
}
}
return r;
}
My concern is
<AdditionalMessageInformationCount AdditionalMessageInformationCount="02"><AdditionalMessageInformationQualifier>01</AdditionalMessageInformationQualifier><AdditionalMessageInformation>MEMBER MUST USE MAIL ORDER.</AdditionalMessageInformation><AdditionalMessageInformationQualifier>02</AdditionalMessageInformationQualifier><AdditionalMessageInformation>PLAN LIMITATIONS EXCEEDED</AdditionalMessageInformation></AdditionalMessageInformationCount>
Here AdditionalMessageInformation elemt is used two times so function fails to create JSON.
Kindly help if anyone have converted XML in json usingg javascript code not any API
We've had success with this version:
function E4XtoJSON(xml, ignored){
var r, children = xml.*,
attributes = xml.# * ,
length = children.length();
if (length == 0)
{
r = xml.toString();
}
else if (length == 1)
{
var text = xml.text().toString();
if (text)
{
r = text;
}
}
if (r == undefined)
{
r = {};
for each(var child in children)
{
var name = child.localName();
var json = E4XtoJSON(child, ignored);
var value = r[name];
if (value)
{
if (value instanceof Array)
{
value.push(json);
}
else
{
r[name] = [value, json]
}
}
else
{
r[name] = json;
}
}
}
if (attributes.length())
{
var a = {},
c = 0;
for each(var attribute in attributes)
{
var name = attribute.localName();
if (ignored && ignored.indexOf(name) == -1)
{
a["_" + name] = attribute.toString();
c++;
}
}
if (c)
{
if (r) a._ = r;
return a;
}
}
return r;
}
With the release of Mirth Connect version 3.3.0, you can use Mirth Connect to set your channel's interior data type to JSON. This will all be done for you.

Change label's text with using property

I am working on my C# ADO.NET app. I have connected my SQL Server database with C# app, and I can perform simple CRUD operations. I want to make that my app open my reminder form when someone in my database have birthday, so I made my query and all persons who have birthday on today's day are in my query, and with using property from my reminder form I change label's text with name and surname of person who have birthday. Now I just dont know how to change next label's text when more than one person have birthday in my query... I dont know how to get next element in my foreach loop...
Here is my code:
Form2 forma = new Form2();
TBirthDayEntities today_born = new TBirthDayEntities();
public Form1()
{
InitializeComponent();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Start();
}
private Boolean provjera_rodj()
{
Boolean flag = false;
int cnt = 0;
IQueryable<TBD> query;
using (var data = new TBirthDayEntities())
{
query = (from x in data.TBD
where x.BirthDay.Day == System.DateTime.Now.Day && x.BirthDay.Month == System.DateTime.Now.Month
select x);
foreach (var x in query)
{
today_born.TBD.Add(x);
cnt += 1;
flag = true;
}
}
switch (cnt)
{
case 1:
{
foreach (var x in today_born.TBD)
{
forma.p_label2 = x.FName + " " + x.LName;
}
break;
}
case 2:
{
foreach (var x in today_born.TBD)
{
forma.p_label2 = x.FName + x.LName;
forma.p_label3 = x.FName + x.LName; //wrong
}
break;
}
}
return flag;
}
private void timer1_Tick(object sender, EventArgs e)
{
Boolean flag = provjera_rodj();
if (flag == true)
{
forma.Show();
timer1.Stop();
}
}
switch (cnt)
{
case 1:
case 2:
{
var lstLabel = new List<Label>()
{
forma.p_label2
, forma.p_label3
};
for(int i = 0; i < today_born.TBD.Count; i++)
{
var x in today_born.TBD[i];
lstLabel[x].Text = x.FName + x.LName;
}
break;
}
}
EDIT:
switch (cnt)
{
case 1:
case 2:
{
var lstLabel = new List<Action<string>>()
{
new Action<string>(s =>forma.p_label2 = s)
, new Action<string>(s =>forma.p_label3 = s)
};
for(int i = 0; i < today_born.TBD.Count; i++)
{
var x = today_born.TBD[i];
lstLabel[x](x.FName + x.LName);
}
break;
}
}

how to highlight user selected text within a piece of text which has already been highlighted?

I have a page where I am displaying some text in a div and I need to highlight this text in certain parts. I have done this by surrounding the text I need to highlight with a tag and appropriate css styling.
E.g.
<div>
My text will look like this with <span class="highlight">highlighted bits</span> in it.
</div>
This works fine. However, another requirement for this page is that the user must be able to select texts, click a button, and the selected text must be highlighted too.
The problem I have is when trying to identify the range of the selected text to grab (using window.getSelection.getRangeAt(0)), this gives me the range which resets after every <span> tag in the text, not from the beginning of the text.
For those who would like to know in the future this is how I did it:
jQuery.fn.highlight = function(startOffset,endOffset,type) {
function innerHighlight(node, startOffset,endOffset) {
var calledStartOffset = parseInt(startOffset);
var startOffsetNode=getChildNodeForOffset(node,parseInt(startOffset));
var endOffsetNode=getChildNodeForOffset(node,parseInt(endOffset));
startOffset = resizeOffsetForNode(startOffsetNode,parseInt(startOffset));
if (startOffsetNode == endOffsetNode){
endOffset = resizeOffsetForNode(endOffsetNode,parseInt(endOffset));
highlightSameNode(startOffsetNode, parseInt(startOffset),parseInt(endOffset),type,calledStartOffset);
} else {
highlightDifferentNode(startOffsetNode,endOffsetNode,parseInt(startOffset),parseInt(endOffset),type,calledStartOffset);
}
}
return this.each(function() {
innerHighlight(this, startOffset,endOffset);
});
};
function resizeOffsetForNode(offsetNode,offset){
if (offsetNode.id >= 0){
offset = parseInt(offset)-parseInt(offsetNode.id);
} else if (offsetNode.previousSibling != null && offsetNode.previousSibling.id > 0){
offset = parseInt(offset)-parseInt(offsetNode.previousSibling.id)-parseInt(offsetNode.previousSibling.textContent.length);
}
return offset;
}
function getChildNodeForOffset(testNode,offset) {
if (testNode.nodeType == 1 && testNode.childNodes && !/(script|style)/i.test(testNode.tagName)) {
var offsetNode=null;
var currentNode;
for (var i = 0; i < testNode.childNodes.length; ++i) {
currentNode=testNode.childNodes[i];
if (currentNode.id >= 0 && parseInt(currentNode.id) <= parseInt(offset) && ((parseInt(currentNode.id) + parseInt(currentNode.textContent.length)) >= parseInt(offset))){
offsetNode = currentNode;
break;
} else if (currentNode.id >= 0 && parseInt(currentNode.id) > parseInt(offset)){
offsetNode = currentNode.previousSibling;
break;
}
}
if (offsetNode==null){
offsetNode = testNode.childNodes[testNode.childNodes.length-1];
}
return offsetNode;
}
}
function highlightSameNode(node, startOffset,endOffset,type,calledStartOffset) {
var skip = 0;
if (node.nodeType == 3) {
if (startOffset >= 0) {
var spannode = document.createElement('span');
spannode.className = 'entity '+ type;
spannode.id=calledStartOffset;
var middlebit = node.splitText(startOffset);
var endbit = middlebit.splitText(endOffset-startOffset);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
}
} else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
var childnode = node.childNodes[0];
highlightSameNode(childnode, startOffset,endOffset,type,calledStartOffset);
}
}
function highlightDifferentNode(startnode, endnode, startOffset,endOffset,type,calledStartOffset) {
var skip = 0;
if (startnode.nodeName == "#text") {
if (startOffset >= 0) {
var spannode = document.createElement('span');
spannode.className = 'entity '+ type;
spannode.id=calledStartOffset;
var endbit = node.splitText(startOffset);
var endclone = endbit.cloneNode(true);
spannode.appendChild(endclone);
endbit.parentNode.replaceChild(spannode, endbit);
}
} else if (startnode.nodeName == "SPAN") {
if (startOffset >= 0) {
var spannode = document.createElement('span');
spannode.className = 'entity '+ type;
spannode.id=calledStartOffset;
var endTextbit = startnode.childNodes[0].splitText(startOffset);
spannode.appendChild(endTextbit);
startnode.parentNode.insertBefore(spannode, startnode.nextSibling);
}
}
var currentTestNode=startnode.nextSibling;
while (currentTestNode!=endnode){
if (currentTestNode.nodeName == "#text") {
var spannode = document.createElement('span');
spannode.className = 'entity '+ type;
spannode.id=parseInt(currentTestNode.previousSibling.id)+parseInt(currentTestNode.previousSibling.textContent.length);
var currentNodeClone=currentTestNode.cloneNode(true);
spannode.appendChild(currentNodeClone);
endbit.parentNode.replaceChild(spannode, currentTestNode);
} else if (currentTestNode.nodeName == "SPAN") {
currentTestNode.className = 'entity overlap';
}
currentTestNode=currentTestNode.nextSibling;
}
var previousNodeEnd = parseInt(endnode.previousSibling.id)+parseInt(endnode.previousSibling.textContent.length);
var spannode = document.createElement('span');
spannode.className = 'entity '+ type;
spannode.id=previousNodeEnd;
if (endnode.nodeName == "#text") {
if (endOffset >= 0) {
//end offset here is the original end offset from the beginning of the text, not node
var unwantedbit = endnode.splitText(parseInt(endOffset)-parseInt(previousNodeEnd));
var endclone = endnode.cloneNode(true);
spannode.appendChild(endclone);
endnode.parentNode.replaceChild(spannode, endnode);
}
} else if (endnode.nodeName == "SPAN") {
if (endOffset >= 0) {
var wantTextbit = endnode.childNodes[0].splitText(parseInt(endOffset)-parseInt(previousNodeEnd));
spannode.appendChild(wantTextbit);
wantTextbit.parentNode.parentNode.insertBefore(spannode, endnode);
}
}
if (startnode.textContent.length < 1){
startnode.parentNode.removeChild(startnode);
}
if (endnode.textContent.length < 1){
endnode.parentNode.removeChild(endnode);
}
}
jQuery.fn.removeHighlight = function() {
return this.find("span.entity").each(function() {
this.parentNode.firstChild.nodeName;
with (this.parentNode) {
replaceChild(this.firstChild, this);
normalize();
}
}).end();
};
function contains(a, b){
return a.contains ? a != b && a.contains(b) : !!(a.compareDocumentPosition(b) & 16);
}