How to escape HTML special characters in Solidity? - string

I am trying the approach below. It is based on some of Uniswap's code.
I am curious as to whether it will work at reasonable cost or whether there is a better way.
function escapeHTML(string memory input)
public
pure
returns (string memory)
{
bytes memory inputBytes = bytes(input);
uint extraCharsNeeded = 0;
for (uint i = 0; i < inputBytes.length; i++) {
bytes1 currentByte = inputBytes[i];
if (currentByte == "&") {
extraCharsNeeded += 4;
} else if (currentByte == "<") {
extraCharsNeeded += 3;
} else if (currentByte == ">") {
extraCharsNeeded += 3;
}
}
if (extraCharsNeeded > 0) {
bytes memory escapedBytes = new bytes(
inputBytes.length + extraCharsNeeded
);
uint256 index;
for (uint i = 0; i < inputBytes.length; i++) {
if (inputBytes[i] == "&") {
escapedBytes[index++] = "&";
escapedBytes[index++] = "a";
escapedBytes[index++] = "m";
escapedBytes[index++] = "p";
escapedBytes[index++] = ";";
} else if (inputBytes[i] == "<") {
escapedBytes[index++] = "&";
escapedBytes[index++] = "l";
escapedBytes[index++] = "t";
escapedBytes[index++] = ";";
} else if (inputBytes[i] == ">") {
escapedBytes[index++] = "&";
escapedBytes[index++] = "g";
escapedBytes[index++] = "t";
escapedBytes[index++] = ";";
} else {
escapedBytes[index++] = inputBytes[i];
}
}
return string(escapedBytes);
}
return input;
}

Related

How to increment and decrement AlphaNumeric string for a given range?

I need optimized solution to increment and decrement alphanumeric string value as we do in excel. When I specify alphanumeric string with range then it should give me both decremented n incremented list of values. For e.g I need range of +-10 of alphanumeric string as.
PN - Alpha character may come in start / middle /end
1. A2000018 -> A2000008 to A2000028
2. A39999 -> A39989 to A40009
3. A00005 -> A00001 to A00015
4. AZ00005 -> AZ00001 to AZ00015
5. A342S0004 -> A342S0001 to A342S0014
6. A342S9999 -> A342S9989 to A342S10009
7. 1234A -> 1224A to 1244A
8. 0003A -> 0001A to 0013A
public static List<String> getRangeList(String docNumber, int range) {
List<String> rangeList = new ArrayList<>();
System.out.println("Document Number Received " + docNumber);
/**
* REGEX checks for String value starting with 1 character as alpha and rest numeric
*/
boolean trailingAlphabet = false;
boolean leadingNtrailingAlphabet = false;
boolean leadingNtrailingNumber = false;
String patternStr = "";
if (docNumber.trim().matches("[a-zA-Z]{1,5}[0-9]{1,20}[a-zA-Z]{1,5}$")) { //String docNumber = "AD234SD1234 ";
patternStr = "(.*?)(\\d+)(.*?)$";
leadingNtrailingAlphabet = true;
} else if (docNumber.trim().matches("[0-9]{1,20}[a-zA-Z]{1,5}[0-9]{1,20}+$")) { //String docNumber = "1234AD1234 ";
patternStr = "(\\d+)(.*?)(\\d+)$";
leadingNtrailingNumber = true;
} else if (docNumber.trim().matches("[0-9]{1,20}[a-zA-Z]{1,4}+$")) { //String docNumber = "1234A ";
patternStr = "(\\d+)(.*?)$";
trailingAlphabet = true;
} else if (docNumber.trim().matches("[a-zA-Z]{1,5}[0-9]+$")
|| docNumber.trim().matches("[a-zA-Z]{1,5}[0-9]{1,20}[a-zA-Z]{1,4}[0-9]+$")) {
patternStr = "(.*?)(\\d+)$";
}
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(docNumber.trim());
if (matcher.find()) {
String firstAlpha = "";
String origNumber = "";
String lastAlpha = "";
if (trailingAlphabet) {
firstAlpha = matcher.group(2);
origNumber = matcher.group(1);
} else if (leadingNtrailingAlphabet) {
firstAlpha = matcher.group(1);
origNumber = matcher.group(2);
lastAlpha = matcher.group(3);
} else if (leadingNtrailingNumber) {
firstAlpha = matcher.group(1);
lastAlpha = matcher.group(2);
origNumber = matcher.group(3);
} else {
firstAlpha = matcher.group(1);
origNumber = matcher.group(2);
}
//System.out.println("1 Alpha : " + firstAlpha + " origNNum : " + origNumber + " lastAlpha : " + lastAlpha);
String incrNumStr = origNumber;
String dcrNumStr = origNumber;
for (int i = 0; i < range; i++) {
if (Integer.parseInt(dcrNumStr) - 1 <= 0) {
break;
}
dcrNumStr = String.format("%0" + dcrNumStr.length() + "d", Integer.parseInt(dcrNumStr) - 1);
if (leadingNtrailingNumber) {
rangeList.add(firstAlpha + lastAlpha + dcrNumStr);
} else if (leadingNtrailingAlphabet) {
rangeList.add(firstAlpha + dcrNumStr + lastAlpha);
} else if (trailingAlphabet) {
rangeList.add(dcrNumStr + firstAlpha);
} else {
rangeList.add(firstAlpha + dcrNumStr);
}
}
for (int i = 0; i < range; i++) {
incrNumStr = String.format("%0" + incrNumStr.length() + "d", Integer.parseInt(incrNumStr) + 1);
if (leadingNtrailingNumber) {
rangeList.add(firstAlpha + lastAlpha + incrNumStr);
} else if (leadingNtrailingAlphabet) {
rangeList.add(firstAlpha + incrNumStr + lastAlpha);
} else if (trailingAlphabet) {
rangeList.add(incrNumStr + firstAlpha);
} else {
rangeList.add(firstAlpha + incrNumStr);
}
}
Collections.sort(rangeList);
System.out.println(rangeList);
}
return rangeList;
}

hungarian BBAN validation

can anybody tell me how to validate Hungarian BBAN account numbres ?
on the internet i have only found that it is 24 numbers length
And in format
bbbs sssk cccc cccc cccc cccx
b = National bank code
s = Branch code
c = Account number
x = National check digit
but how to calculate x = National check digit ?
I have tried to remove last char and modulo rest by 97 but it does not work
(the result is not 1 for valid account numbers)
thanks in advance for any help
I just finished Hungarian account validation function. This is the first version of this function but it's work well.
public string sprawdzWegierskitempAccountNumber(string _accountNumberToCheck, bool _iban) //if iban is true then function result will be always IBAN (even if _accountNumberToCheck will be BBAN)
{
string _accountNumberCorrected = _accountNumberToCheck.Replace(" ", "");
_accountNumberCorrected = _accountNumberCorrected.Replace("-", "");
_accountNumberCorrected = _accountNumberCorrected.Replace("//", "");
_accountNumberCorrected = _accountNumberCorrected.Replace("\", "");
string _accountNumberCorrectedFirst = _accountNumberCorrected;
if (_accountNumberCorrected.Length == 16 || _accountNumberCorrected.Length == 24 || _accountNumberCorrected.Length == 28)
{
if (_accountNumberCorrected.Length == 28) //IBAN Account number
{
_accountNumberCorrected = _accountNumberCorrected.Substring(4, _accountNumberCorrected.Length - 4); //we don't need first four digits (HUxx)
}
string digitToMultiply = "9731";
int checkResult = 0;
//checking first part of account number
for (int i = 0; i <= 6; i++)
{
checkResult = checkResult + int.Parse(_accountNumberCorrected.ToCharArray()[i].ToString()) * int.Parse(digitToMultiply.ToCharArray()[i % 4].ToString());
}
checkResult = checkResult % 10;
checkResult = 10 - checkResult;
if (checkResult == 10)
{
checkResult = 0;
}
if (checkResult.ToString() != _accountNumberCorrected.ToCharArray()[7].ToString())
{
throw new Exception("Wrong account number");
}
else
{
//if first part it's ok then checking second part of account number
checkResult = 0;
for (int i = 8; i <= _accountNumberCorrected.Length-2; i++)
{
checkResult = checkResult + int.Parse(_accountNumberCorrected.ToCharArray()[i].ToString()) * int.Parse(digitToMultiply.ToCharArray()[i % 4].ToString());
}
checkResult = checkResult % 10;
checkResult = 10 - checkResult;
if (checkResult == 10)
{
checkResult = 0;
}
if (checkResult.ToString() != _accountNumberCorrected.ToCharArray()[_accountNumberCorrected.Length-1].ToString())
{
throw new Exception("Wrong account number");
}
}
string tempAccountNumber = _accountNumberCorrected + "173000";
var db = 0; var iban = 0;
var maradek = 0;
string resz = "", ibanstr = "", result = "";
while (true)
{
if (db == 0)
{
resz = tempAccountNumber.Substring(0, 9);
tempAccountNumber = tempAccountNumber.Substring(9, (tempAccountNumber.Length - 9));
}
else
{
resz = maradek.ToString();
resz = resz + tempAccountNumber.Substring(0, (9 - db));
tempAccountNumber = tempAccountNumber.Substring((9 - db), (tempAccountNumber.Length - 9 + db));
}
maradek = int.Parse(resz) % 97;
if (maradek == 0)
db = 0;
else
if (maradek < 10)
db = 1;
else
db = 2;
if ((tempAccountNumber.Length + db) <= 9)
break;
}
if (maradek != 0)
{
resz = maradek.ToString();
resz = resz + tempAccountNumber;
}
else
resz = tempAccountNumber;
maradek = int.Parse(resz) % 97; ;
iban = 98 - maradek;
if (iban < 10)
ibanstr = "0" + iban.ToString();
else ibanstr = iban.ToString();
if (_accountNumberCorrected.Length == 16)
{
_accountNumberCorrected = _accountNumberCorrected + "00000000";
_accountNumberCorrectedFirst = _accountNumberCorrectedFirst + "00000000";
}
if (_iban)
{
result = "HU" + ibanstr + _accountNumberCorrected;
}
else
{
result = _accountNumberCorrectedFirst;
}
return result;
}
else
{
throw new Exception("Wrong length of account number");
}
}

Linux Kernel Error

I got the same errors on these lines
error: lvalue required as left operand of assignment
line 49: for (current = root; current != NULL; ptr = current) {
line 50: current =current->link[res];
line 75: for (current = bf; current != newnode; res = link_dir[++i]) {
line 80: current = current->link[res];
line 167: current = root;
line 192: current = current->link[res];
How can I fix this?
I am using kernel version 2.6.32-24-generic
It is my one of function and above four errors are from this function...
It is an insertion function of AVL tree.
static void insertion (char value[]) {
struct AVLTree_Node *bf, *parent_bf, *subtree, *temp;
struct AVLTree_Node *current, *parent, *newnode, *ptr;
int res = 0,i=0 ,num=100, compareLimit = 100;
char link_dir[32];
if (!root) {
root = createNode(value);
return;
}
bf = parent_bf;
parent_bf = root;
// find the location for inserting the new node
for (current = root; current != NULL; ptr = current) {
current =current->link[res];
num = strcmp(value,current->data);
if (num == 0) {
printk(KERN_INFO "Cannot insert duplicates!!\n");
return;
}
int result = strncmp(value,current->data, compareLimit);
if(result > 0)
res = 1;
else if(result <= 0)
res =0;
parent = current;
if (current->bfactor != 0) {
bf = current;
parent_bf = ptr;
i = 0;
}
link_dir[i++] = res;
}
// create the new node
newnode = createNode(value);
parent->link[res] = newnode;
res = link_dir[i = 0];
// updating the height balance after insertion
for (current = bf; current != newnode; res = link_dir[++i]) {
if (res == 0)
current->bfactor--;
else
current->bfactor++;
current = current->link[res];
}
// right sub-tree
if (bf->bfactor == 2) {
printk(KERN_INFO "bfactor = 2\n");
temp = bf->link[1];
if (temp->bfactor == 1) {
subtree = temp;
bf->link[1] = temp->link[0];
temp->link[0] = bf;
temp->bfactor = bf->bfactor = 0;
} else {
subtree = temp->link[0];
temp->link[0] = subtree->link[1];
subtree->link[1] = temp;
bf->link[1] = subtree->link[0];
subtree->link[0] = bf;
// update balance factors
if (subtree->bfactor == -1) {
bf->bfactor = 0;
temp->bfactor = 1;
} else if (subtree->bfactor == 0) {
bf->bfactor = 0;
temp->bfactor = 0;
} else if (subtree->bfactor == 1) {
bf->bfactor = -1;
temp->bfactor = 0;
}
subtree->bfactor = 0;
}
// left sub-tree
} else if (bf->bfactor == -2) {
temp = bf->link[0];
if (temp->bfactor == -1) {
// single rotation(SR) right
subtree = temp;
bf->link[0] = temp->link[1];
temp->link[1] = bf;
temp->bfactor = bf->bfactor = 0;
} else {
// double rotation - (SR left + SR right)
subtree = temp->link[1];
temp->link[1] = subtree->link[0];
subtree->link[0] = temp;
bf->link[0] = subtree->link[1];
subtree->link[1] = bf;
// update balance factors
if (subtree->bfactor == -1) {
bf->bfactor = 1;
temp->bfactor = 0;
} else if (subtree->bfactor == 0) {
bf->bfactor = 0;
temp->bfactor = 0;
} else if (subtree->bfactor == 1) {
bf->bfactor = 0;
temp->bfactor = -1;
}
subtree->bfactor = 0;
}
} else {
return;
}
if (bf == root) {
root = subtree;
return;
}
if (bf != parent_bf->link[0]) {
parent_bf->link[1] = subtree;
} else {
parent_bf->link[0] = subtree;
}
return;
}
current is a macro that expands into a function call:
static __always_inline struct task_struct *get_current(void)
{
return this_cpu_read_stable(current_task);
}
#define current get_current()
Use some other variable name.

Text version compare in FCKEditor

Am using Fck editor to write content. Am storing the text as versions in db. I want to highlight those changes in versions when loading the text in FCK Editor.
How to compare the text....
How to show any text that has been deleted in strike through mode.
Please help me/...
Try google's diff-patch algorithm http://code.google.com/p/google-diff-match-patch/
Take both previous and current version of the text and store it into two parameters. Pass the two parameters to the following function.
function diffString(o, n) {
o = o.replace(/<[^<|>]+?>| /gi, '');
n = n.replace(/<[^<|>]+?>| /gi, '');
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
var str = "";
var oSpace = o.match(/\s+/g);
if (oSpace == null) {
oSpace = ["\n"];
} else {
oSpace.push("\n");
}
var nSpace = n.match(/\s+/g);
if (nSpace == null) {
nSpace = ["\n"];
} else {
nSpace.push("\n");
}
if (out.n.length == 0) {
for (var i = 0; i < out.o.length; i++) {
str += '<span style="background-color:#F00;"><del>' + escape(out.o[i]) + oSpace[i] + "</del></span>";
}
} else {
if (out.n[0].text == null) {
for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
str += '<span style="background-color:#F00;"><del>' + escape(out.o[n]) + oSpace[n] + "</del></span>";
}
}
for (var i = 0; i < out.n.length; i++) {
if (out.n[i].text == null) {
str += '<span style="background-color:#0C0;"><ins>' + escape(out.n[i]) + nSpace[i] + "</ins></span>";
} else {
var pre = "";
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
pre += '<span style="background-color:#F00;"><del>' + escape(out.o[n]) + oSpace[n] + "</del></span>";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
return str;
}
this returns an html in which new text is marked green and deleted text as red + striked out.

how to extract Paragraph text color from ms word using apache poi

i am using apache POI , is it possible to read text background and foreground color from ms word paragraph
I got the solution
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(doc);
Range range = doc.getRange();
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
System.out.println(pr.getEndOffset());
int j=0;
while (true) {
CharacterRun run = pr.getCharacterRun(j++);
System.out.println("-------------------------------");
System.out.println("Color---"+ run.getColor());
System.out.println("getFontName---"+ run.getFontName());
System.out.println("getFontSize---"+ run.getFontSize());
if( run.getEndOffset()==pr.getEndOffset()){
break;
}
}
}
I found it in :
CharacterRun run = para.getCharacterRun(i)
i should be integer and should be incremented so the code will be as follow :
int c=0;
while (true) {
CharacterRun run = para.getCharacterRun(c++);
int x = run.getPicOffset();
System.out.println("pic offset" + x);
if (run.getEndOffset() == para.getEndOffset()) {
break;
}
}
if (paragraph != null)
{
int numberOfRuns = paragraph.NumCharacterRuns;
for (int runIndex = 0; runIndex < numberOfRuns; runIndex++)
{
CharacterRun run = paragraph.GetCharacterRun(runIndex);
string color = getColor24(run.GetIco24());
}
}
GetColor24 Function to Convert Color in Hex Format for C#
public static String getColor24(int argbValue)
{
if (argbValue == -1)
return "";
int bgrValue = argbValue & 0x00FFFFFF;
int rgbValue = (bgrValue & 0x0000FF) << 16 | (bgrValue & 0x00FF00)
| (bgrValue & 0xFF0000) >> 16;
StringBuilder result = new StringBuilder("#");
String hex = rgbValue.ToString("X");
for (int i = hex.Length; i < 6; i++)
{
result.Append('0');
}
result.Append(hex);
return result.ToString();
}
if you are working on docx(OOXML), you may want to take a look on this:
import java.io.*
import org.apache.poi.xwpf.usermodel.XWPFDocument
fun test(){
try {
val file = File("file.docx")
val fis = FileInputStream(file.absolutePath)
val document = XWPFDocument(fis)
val paragraphs = document.paragraphs
for (para in paragraphs) {
println("-- ("+para.alignment+") " + para.text)
para.runs.forEach { it ->
println(
"text:" + it.text() + " "
+ "(color:" + it.color
+ ",fontFamily:" + it.fontFamily
+ ")"
)
}
}
fis.close()
} catch (e: Exception) {
e.printStackTrace()
}
}

Resources