I have the following sample code. A Map with (Foo) class items, and a Map with (Bar) struct items:
public class Maps {
Gee.Map<Foo?, int> map1 = new Gee.HashMap<Foo?, int> ();
Gee.Map<Bar?, int> map2 = new Gee.HashMap<Bar?, int> ();
public Maps () {
Foo a = new Foo ();
Foo b = new Foo ();
Foo c = new Foo ();
map1.set (a, 1);
map1.set (b, 2);
map1.set (c, 3);
stdout.printf ("Foo = %d %d %d %d\n", map1.get (a), map1.get (b), map1.get (c), map1.size);
Bar e = Bar ();
Bar d = Bar ();
Bar f = Bar ();
map2.set (d, 1);
map2.set (e, 2);
map2.set (f, 3);
stdout.printf ("Bar = %d %d %d %d\n", map2.get (d), map2.get (e), map2.get (f), map2.size);
}
}
public class Foo {
public string name;
public Foo () {
name = "foo";
}
}
public struct Bar {
public string name;
public Bar () {
name = "bar";
}
}
public static int main (string[] args) {
stdout.printf ("Start\n");
var a = new Maps ();
stdout.printf ("End\n");
return 0;
}
The output:
Start
Foo = 1 2 3 3
Bar = 0 0 0 3
End
What is it that I am doing wrong as to not being able to retrieve values from map2?
After trolling through the GNOME source, I found the following solution (from Geary):
i.e. Adding custom hash and equal functions.
Gee.Map<Bar?, int> map2 = new Gee.HashMap<Bar?, int> (bar_hash_func, bar_equal_func);
public static uint bar_hash_func (Bar? n) {
return hash_memory ((uint8 *) n, sizeof(Bar));
}
public static bool bar_equal_func (Bar? a, Bar? b) {
Bar *bia = (Bar *) a;
Bar *bib = (Bar *) b;
return (*bia) == (*bib);
}
/**
* A rotating-XOR hash that can be used to hash memory buffers of any size.
*/
public static uint hash_memory (void *ptr, size_t bytes) {
if (ptr == null || bytes == 0) {
return 0;
}
uint8 *u8 = (uint8 *) ptr;
// initialize hash to first byte value and then rotate-XOR from there
uint hash = *u8;
for (int ctr = 1; ctr < bytes; ctr++) {
hash = (hash << 4) ^ (hash >> 28) ^ (*u8++);
}
return hash;
}
Related
How to create a structure that already has default values?
Somehow like this:
struct First {
int data = 4;
int pos = 5;
}
void main () {
var a = First ();
assert(a.data == 4);
}
The response from AlThomas:
"Structs in Vala can have initializers (similar to a constructor for a class) and methods. So what I can extract from your second pastebin you could write that as:"
struct First {
int data;
int pos;
public First (int[] mass) {
data= 5;
pos = mass.length;
}
public int sas () {
return data + pos;
}
}
void main () {
int[] a = {1,3,0,1,2,3,2,1};
var b = First (a);
print (#"$(b.sas ())\n");
}
First you check undeniable signature scheme verifying algorithm.
Than in that there is first step telling to chose two random x1 and x2.
But the verifying algo works sometime and sometime failed depending on two randoms. ( algo implemented in java and correctly).
For the same input if we run that algo multiple time, sometime it signature is matched and sometime not, last comparison is failed.
Plz help me. Im stuck here ( lack of math).
Actually it is an signature scheme and in paper it was confusing but now i've figure out solution.
Solution code is: let me know if you need me to explain this code.
import java.lang.*;
import java.util.*;
import java.math.*;
import java.security.MessageDigest;
import java.nio.file.*;
import java.io.*;
import java.security.*;
class UndeniableSignature {
int Q; // prime
int P; // prime of form P = 2Q + 1
BigInteger G; // Generator of Z*P
int D; // private key belongs to [2 ... Q-1]
BigInteger Y; // G^D (mod P)
int invD; // D^-1 (mod Q)
Random rand = new SecureRandom(); // uniform random generator
public int[] extendedEuclidean(int a, int b) {
if(b==0) {
int[] arr=new int[3];
arr[0] = a;
arr[1] = 1;
arr[2] = 0;
return arr;
}
int[] subResult = extendedEuclidean(b,a%b);
int[] arr=new int[3];
arr[0] = subResult[0];
arr[1] = subResult[2];
arr[2] = subResult[1] - (a/b) * subResult[2];
return arr;
}
public int secureRandom(int max) {
return rand.nextInt(max);
}
public BigInteger getGenerator(BigInteger p, BigInteger q){
BigInteger generator = BigInteger.ZERO;
BigInteger exp = p.subtract(BigInteger.ONE).divide(q);
for(int i=2;i<p.intValue()-1;i++) {
generator = BigInteger.valueOf(i);
generator = generator.modPow(exp, p);
if(!generator.equals(BigInteger.ONE)) return generator;
}
// do {
// generator = BigInteger.valueOf(this.secureRandom(p.intValue()));
// generator = generator.modPow(exp, p);
// } while(generator.equals(BigInteger.ONE));
return generator;
// BigInteger generator = BigInteger.ZERO;
// for(long i = 2; i < p.intValue()-1; i++)
// {
// generator = BigInteger.valueOf(i);
// if(generator.modPow(BigInteger.valueOf(2), p).equals(BigInteger.ONE)) continue;
// if(generator.modPow(q, p).equals(BigInteger.ONE)) continue;
// else return generator;
// }
// return generator;
}
public String readMessageFile(String filename) {
try {
return new String(Files.readAllBytes(Paths.get(filename)));
} catch(Exception ex) {
System.out.println("ERR: Can't read file.");
}
return null;
}
public int[] readSignatureFile(String filename) {
InputStream is=null;
DataInputStream dis=null;
try {
is = new FileInputStream(filename);
dis = new DataInputStream(is);
ArrayList intList = new ArrayList();
int count = 0;
while(dis.available()>0) {
intList.add(dis.readInt());
}
int[] data = new int[intList.size()];
for(int i=0;i<data.length;i++) {
data[i] = (int)intList.get(i);
}
dis.close();
is.close();
return data;
} catch(Exception ex) {
System.out.println("ERR: Can't read file.");
}
return null;
}
public static void writeSignatureFile(String filename, int[] contents) {
FileOutputStream fos=null;
DataOutputStream dos=null;
try {
fos = new FileOutputStream(filename);
dos = new DataOutputStream(fos);
for(int i=0;i<contents.length;i++) {
dos.writeInt(contents[i]);
}
dos.flush();
dos.close();
fos.close();
} catch(Exception ex) {
System.out.println("ERR: Can't write to file.");
}
}
public void keyGeneration() {
System.out.println("UNDENIABLE SIGNATURE SCHEME");
System.out.println("- KEY GENERATION");
System.out.print("\tEnter prime P (such that P=2Q+1) : ");
this.P = new Scanner(System.in).nextInt();
this.Q = (this.P - 1)/2;
System.out.println("\tPrime Q is "+this.Q+".");
this.G = this.getGenerator(BigInteger.valueOf(this.P),BigInteger.valueOf(this.Q));
System.out.println("\tGenerator G of group Z*("+this.P+") is "+this.G+".");
System.out.print("\tEnter private key D (belongs to Z*P) :");
this.D = new Scanner(System.in).nextInt();
while(this.D <= 0 || this.D >= this.P) {
System.out.println("\tInvalid private key selected, please try again.");
System.out.print("\tEnter private key D (belongs to Z*P) :");
this.D = new Scanner(System.in).nextInt();
}
this.Y = this.G.modPow(BigInteger.valueOf(this.D), BigInteger.valueOf(this.P));
System.out.println("\tG^D(mod P) = "+this.Y+".");
System.out.println("\tPublic Key [P, G, Y] is ["+this.P+", "+this.G+", "+this.Y+"].");
System.out.println("\tPrivate Key [D] is ["+this.D+"].");
int[] g = this.extendedEuclidean(this.D, this.Q);
this.invD = g[1];
if(this.invD < 0) {
this.invD = this.Q - Math.abs(this.invD);
System.out.println("\tInverse was negative.");
}
System.out.println("\tInverse of D (mod Q) is "+this.invD+".");
}
public void messageSigning(String message) {
int[] signatureBytes = new int[message.length()];
for(int i=0;i<message.length();i++) {
BigInteger m = BigInteger.valueOf((int)message.charAt(i));//this.H(message.charAt(i)+"");
BigInteger s = m.pow(this.D).mod(BigInteger.valueOf(this.P));
signatureBytes[i] = s.intValue();
// System.out.println("\tchar:"+message.charAt(i)+", m:"+m+", s:"+s+", S:"+signatureBytes[i]);
}
System.out.print("\tEnter signature filename : ");
String signatureFilename = new Scanner(System.in).nextLine();
this.writeSignatureFile(signatureFilename, signatureBytes);
System.out.println("\tSignature is successfully generated.");
}
// see the condition proof for w=W for solution of problem
public boolean signatureVerification(String message, int[] signature) {
for(int i=0;i<message.length();i++) {
// rand=new Random();
// int x1 = this.secureRandom(this.Q-1);
// while(x1<=1) x1 = this.secureRandom(this.Q-1);
// int x2 = this.secureRandom(this.Q-1);
// while(x2<=1) x2 = this.secureRandom(this.Q-1);
int x1 = 38, x2 = 397;
BigInteger S = BigInteger.valueOf(signature[i]);
BigInteger s = S.pow(x1);
BigInteger y = this.Y.pow(x2);
BigInteger z = s.multiply(y).mod(BigInteger.valueOf(this.P));
BigInteger w = signerChallengeForVerification(z);
BigInteger M = BigInteger.valueOf((int)message.charAt(i));//this.H(message.charAt(i)+"");
BigInteger m = M.pow(x1);
BigInteger g = this.G.pow(x2);
BigInteger mg = m.multiply(g);
BigInteger W = mg.mod(BigInteger.valueOf(this.P));
// System.out.println("\ti:"+i+", char:"+message.charAt(i)+", m:"+M+", s:"+S);
// System.out.println("\t\tz:"+z+", w:"+w+" , W:"+W);
if(!w.equals(W)) {
return false;
}
}
return true;
}
public boolean disavowalProtocol(String message, int[] signature) {
int x1 = 38, x2 = 397;
BigInteger response1 = BigInteger.ZERO;
BigInteger response2 = BigInteger.ZERO;
// verification 1
for(int i=0;i<message.length();i++) {
BigInteger S = BigInteger.valueOf(signature[i]);
BigInteger s = S.pow(x1);
BigInteger y = this.Y.pow(x2);
BigInteger z = s.multiply(y).mod(BigInteger.valueOf(this.P));
BigInteger w = signerChallengeForVerification(z);
BigInteger M = BigInteger.valueOf((int)message.charAt(i));//this.H(message.charAt(i)+"");
BigInteger m = M.pow(x1);
BigInteger g = this.G.pow(x2);
BigInteger mg = m.multiply(g);
BigInteger W = mg.mod(BigInteger.valueOf(this.P));
// System.out.println("\ti:"+i+", char:"+message.charAt(i)+", m:"+M+", s:"+S);
// System.out.println("\t\tz:"+z+", w:"+w+" , W:"+W);
if(!w.equals(W)) {
response1 = w;
break;
}
}
if(response1.equals(BigInteger.ZERO)) {
return false; // signature is not forgery bcoz signature is matched
}
// verification 2
for(int i=0;i<message.length();i++) {
BigInteger S = BigInteger.valueOf(signature[i]);
BigInteger s = S.pow(x1);
BigInteger y = this.Y.pow(x2);
BigInteger z = s.multiply(y).mod(BigInteger.valueOf(this.P));
BigInteger w = signerChallengeForVerification(z);
BigInteger M = BigInteger.valueOf((int)message.charAt(i));//this.H(message.charAt(i)+"");
BigInteger m = M.pow(x1);
BigInteger g = this.G.pow(x2);
BigInteger mg = m.multiply(g);
BigInteger W = mg.mod(BigInteger.valueOf(this.P));
// System.out.println("\ti:"+i+", char:"+message.charAt(i)+", m:"+M+", s:"+S);
// System.out.println("\t\tz:"+z+", w:"+w+" , W:"+W);
if(!w.equals(W)) {
response2 = w;
break;
}
}
if(response2.equals(BigInteger.ZERO)) {
return false; // signature is not forgery bcoz signature is matched
}
// forgery validation now it comes here only when one of above validation is failed
BigInteger A = response1.divide(this.G.pow(x2)).pow(x1).mod(BigInteger.valueOf(this.P));
BigInteger B = response2.divide(this.G.pow(x1)).pow(x2).mod(BigInteger.valueOf(this.P));
return A.equals(B); // signature is forgery if A == B
}
public BigInteger signerChallengeForVerification(BigInteger z) {
// System.out.println("\tchallange: "+z+", invD:"+this.invD+", d:"+(z.pow(this.invD).mod(BigInteger.valueOf(this.P))));
return z.pow(this.invD).mod(BigInteger.valueOf(this.P));
}
}
class Program {
public static void main(String[] args) {
String msgFilename, signatureFilename, message;
UndeniableSignature scheme = new UndeniableSignature();
scheme.keyGeneration();
int choice = 0;
do {
System.out.println();
System.out.println("- OPERATIONS");
System.out.println("\t1. Sign message");
System.out.println("\t2. Verify signature");
System.out.println("\t3. Disavowal protocal");
System.out.println("\t4. Exit");
System.out.print("\tChoice : ");
choice = new Scanner(System.in).nextInt();
System.out.println();
switch(choice) {
case 1:
System.out.println("- MESSAGE SIGNING");
System.out.print("\tEnter message filename : ");
msgFilename = new Scanner(System.in).nextLine();
message = new String(scheme.readMessageFile(msgFilename));
scheme.messageSigning(message);
break;
case 2:
System.out.println("- SIGNATURE VERIFICATION");
System.out.print("\tEnter message filename : ");
msgFilename = new Scanner(System.in).nextLine();
System.out.print("\tEnter signature filename : ");
signatureFilename = new Scanner(System.in).nextLine();
message = scheme.readMessageFile(msgFilename);
int[] signatureBytes = scheme.readSignatureFile(signatureFilename);
if(scheme.signatureVerification(message, signatureBytes)) {
System.out.println("\tSignature IS valid.");
} else {
System.out.println("\tSignature is NOT valid.");
}
break;
case 3:
System.out.println("- DISAVOWAL VERIFICATION");
System.out.print("\tEnter message filename : ");
msgFilename = new Scanner(System.in).nextLine();
System.out.print("\tEnter signature filename : ");
signatureFilename = new Scanner(System.in).nextLine();
message = scheme.readMessageFile(msgFilename);
signatureBytes = scheme.readSignatureFile(signatureFilename);
if(scheme.disavowalProtocol(message, signatureBytes)) {
System.out.println("\tSignature IS forgery.");
} else {
System.out.println("\tSignature is NOT forgery.");
}
break;
case 4:
System.out.println("- BYE BYE");
break;
}
} while(choice!=4);
}
}
thanks :D
How would the Jaro–Winkler distance string comparison algorithm be implemented in C#?
public static class JaroWinklerDistance
{
/* The Winkler modification will not be applied unless the
* percent match was at or above the mWeightThreshold percent
* without the modification.
* Winkler's paper used a default value of 0.7
*/
private static readonly double mWeightThreshold = 0.7;
/* Size of the prefix to be concidered by the Winkler modification.
* Winkler's paper used a default value of 4
*/
private static readonly int mNumChars = 4;
/// <summary>
/// Returns the Jaro-Winkler distance between the specified
/// strings. The distance is symmetric and will fall in the
/// range 0 (perfect match) to 1 (no match).
/// </summary>
/// <param name="aString1">First String</param>
/// <param name="aString2">Second String</param>
/// <returns></returns>
public static double distance(string aString1, string aString2) {
return 1.0 - proximity(aString1,aString2);
}
/// <summary>
/// Returns the Jaro-Winkler distance between the specified
/// strings. The distance is symmetric and will fall in the
/// range 0 (no match) to 1 (perfect match).
/// </summary>
/// <param name="aString1">First String</param>
/// <param name="aString2">Second String</param>
/// <returns></returns>
public static double proximity(string aString1, string aString2)
{
int lLen1 = aString1.Length;
int lLen2 = aString2.Length;
if (lLen1 == 0)
return lLen2 == 0 ? 1.0 : 0.0;
int lSearchRange = Math.Max(0,Math.Max(lLen1,lLen2)/2 - 1);
// default initialized to false
bool[] lMatched1 = new bool[lLen1];
bool[] lMatched2 = new bool[lLen2];
int lNumCommon = 0;
for (int i = 0; i < lLen1; ++i) {
int lStart = Math.Max(0,i-lSearchRange);
int lEnd = Math.Min(i+lSearchRange+1,lLen2);
for (int j = lStart; j < lEnd; ++j) {
if (lMatched2[j]) continue;
if (aString1[i] != aString2[j])
continue;
lMatched1[i] = true;
lMatched2[j] = true;
++lNumCommon;
break;
}
}
if (lNumCommon == 0) return 0.0;
int lNumHalfTransposed = 0;
int k = 0;
for (int i = 0; i < lLen1; ++i) {
if (!lMatched1[i]) continue;
while (!lMatched2[k]) ++k;
if (aString1[i] != aString2[k])
++lNumHalfTransposed;
++k;
}
// System.Diagnostics.Debug.WriteLine("numHalfTransposed=" + numHalfTransposed);
int lNumTransposed = lNumHalfTransposed/2;
// System.Diagnostics.Debug.WriteLine("numCommon=" + numCommon + " numTransposed=" + numTransposed);
double lNumCommonD = lNumCommon;
double lWeight = (lNumCommonD/lLen1
+ lNumCommonD/lLen2
+ (lNumCommon - lNumTransposed)/lNumCommonD)/3.0;
if (lWeight <= mWeightThreshold) return lWeight;
int lMax = Math.Min(mNumChars,Math.Min(aString1.Length,aString2.Length));
int lPos = 0;
while (lPos < lMax && aString1[lPos] == aString2[lPos])
++lPos;
if (lPos == 0) return lWeight;
return lWeight + 0.1 * lPos * (1.0 - lWeight);
}
}
You can take a look on Lucene.Net ,
it implement Jaro–Winkler distance algorithm ,
and its score is different from which leebickmtu post ,
you can take it as reference
the url is below :
http://lucenenet.apache.org/docs/3.0.3/db/d12/_jaro_winkler_distance_8cs_source.html
You can use the below code which works very well for all the kind of strings.After getting the result you need to multiply with 100 to get the percentage of similarity. I hope it will solves your problem.
public class JaroWinkler
{
private const double defaultMismatchScore = 0.0;
private const double defaultMatchScore = 1.0;
/// <summary>
/// Gets the similarity between two strings by using the Jaro-Winkler algorithm.
/// A value of 1 means perfect match. A value of zero represents an absolute no match
/// </summary>
/// <param name="_firstWord"></param>
/// <param name="_secondWord"></param>
/// <returns>a value between 0-1 of the similarity</returns>
///
public static double RateSimilarity(string _firstWord, string _secondWord)
{
// Converting to lower case is not part of the original Jaro-Winkler implementation
// But we don't really care about case sensitivity in DIAMOND and wouldn't decrease security names similarity rate just because
// of Case sensitivity
_firstWord = _firstWord.ToLower();
_secondWord = _secondWord.ToLower();
if ((_firstWord != null) && (_secondWord != null))
{
if (_firstWord == _secondWord)
//return (SqlDouble)defaultMatchScore;
return defaultMatchScore;
else
{
// Get half the length of the string rounded up - (this is the distance used for acceptable transpositions)
int halfLength = Math.Min(_firstWord.Length, _secondWord.Length) / 2 + 1;
// Get common characters
StringBuilder common1 = GetCommonCharacters(_firstWord, _secondWord, halfLength);
int commonMatches = common1.Length;
// Check for zero in common
if (commonMatches == 0)
//return (SqlDouble)defaultMismatchScore;
return defaultMismatchScore;
StringBuilder common2 = GetCommonCharacters(_secondWord, _firstWord, halfLength);
// Check for same length common strings returning 0 if is not the same
if (commonMatches != common2.Length)
//return (SqlDouble)defaultMismatchScore;
return defaultMismatchScore;
// Get the number of transpositions
int transpositions = 0;
for (int i = 0; i < commonMatches; i++)
{
if (common1[i] != common2[i])
transpositions++;
}
int j = 0;
j += 1;
// Calculate Jaro metric
transpositions /= 2;
double jaroMetric = commonMatches / (3.0 * _firstWord.Length) + commonMatches / (3.0 * _secondWord.Length) + (commonMatches - transpositions) / (3.0 * commonMatches);
//return (SqlDouble)jaroMetric;
return jaroMetric;
}
}
//return (SqlDouble)defaultMismatchScore;
return defaultMismatchScore;
}
/// <summary>
/// Returns a string buffer of characters from string1 within string2 if they are of a given
/// distance seperation from the position in string1.
/// </summary>
/// <param name="firstWord">string one</param>
/// <param name="secondWord">string two</param>
/// <param name="separationDistance">separation distance</param>
/// <returns>A string buffer of characters from string1 within string2 if they are of a given
/// distance seperation from the position in string1</returns>
private static StringBuilder GetCommonCharacters(string firstWord, string secondWord, int separationDistance)
{
if ((firstWord != null) && (secondWord != null))
{
StringBuilder returnCommons = new StringBuilder(20);
StringBuilder copy = new StringBuilder(secondWord);
int firstWordLength = firstWord.Length;
int secondWordLength = secondWord.Length;
for (int i = 0; i < firstWordLength; i++)
{
char character = firstWord[i];
bool found = false;
for (int j = Math.Max(0, i - separationDistance); !found && j < Math.Min(i + separationDistance, secondWordLength); j++)
{
if (copy[j] == character)
{
found = true;
returnCommons.Append(character);
copy[j] = '#';
}
}
}
return returnCommons;
}
return null;
}
}
Use below class to use jaro winkler.
i have customized both algorithm jaro and jaro-winkler.
Visit on Github for DLL.
using System;
using System.Linq;
namespace Search
{
public static class EditDistance
{
private struct JaroMetrics
{
public int Matches;
public int Transpositions;
}
private static EditDistance.JaroMetrics Matches(string s1, string s2)
{
string text;
string text2;
if (s1.Length > s2.Length)
{
text = s1;
text2 = s2;
}
else
{
text = s2;
text2 = s1;
}
int num = Math.Max(text.Length / 2 - 1, 0);
int[] array = new int[text2.Length];
int i;
for (i = 0; i < array.Length; i++)
{
array[i] = -1;
}
bool[] array2 = new bool[text.Length];
int num2 = 0;
for (int j = 0; j < text2.Length; j++)
{
char c = text2[j];
int k = Math.Max(j - num, 0);
int num3 = Math.Min(j + num + 1, text.Length);
while (k < num3)
{
if (!array2[k] && c == text[k])
{
array[j] = k;
array2[k] = true;
num2++;
break;
}
k++;
}
}
char[] array3 = new char[num2];
char[] ms2 = new char[num2];
i = 0;
int num4 = 0;
while (i < text2.Length)
{
if (array[i] != -1)
{
array3[num4] = text2[i];
num4++;
}
i++;
}
i = 0;
num4 = 0;
while (i < text.Length)
{
if (array2[i])
{
ms2[num4] = text[i];
num4++;
}
i++;
}
int num5 = array3.Where((char t, int mi) => t != ms2[mi]).Count<char>();
EditDistance.JaroMetrics result;
result.Matches = num2;
result.Transpositions = num5 / 2;
return result;
}
public static float JaroWinkler(this string s1, string s2, float prefixScale, float boostThreshold)
{
prefixScale = ((prefixScale > 0.25f) ? 0.25f : prefixScale);
prefixScale = ((prefixScale < 0f) ? 0f : prefixScale);
float num = s1.Jaro(s2);
int num2 = 0;
for (int i = 0; i < Math.Min(s1.Length, s2.Length); i++)
{
if (s1[i] != s2[i])
{
break;
}
num2++;
}
return (num < boostThreshold) ? num : (num + prefixScale * (float)num2 * (1f - num));
}
public static float JaroWinkler(this string s1, string s2, float prefixScale)
{
return s1.JaroWinkler(s2, prefixScale, 0.7f);
}
public static float JaroWinkler(this string s1, string s2)
{
return s1.JaroWinkler(s2, 0.1f, 0.7f);
}
public static float Jaro(this string s1, string s2)
{
EditDistance.JaroMetrics jaroMetrics = EditDistance.Matches(s1, s2);
float num = (float)jaroMetrics.Matches;
int transpositions = jaroMetrics.Transpositions;
float result;
if (num == 0f)
{
result = 0f;
}
else
{
float num2 = (num / (float)s1.Length + num / (float)s2.Length + (num - (float)transpositions) / num) / 3f;
result = num2;
}
return result;
}
public static int LevenshteinDistance(this string source, string target)
{
int result;
if (string.IsNullOrEmpty(source))
{
if (string.IsNullOrEmpty(target))
{
result = 0;
}
else
{
result = target.Length;
}
}
else if (string.IsNullOrEmpty(target))
{
result = source.Length;
}
else
{
if (source.Length > target.Length)
{
string text = target;
target = source;
source = text;
}
int length = target.Length;
int length2 = source.Length;
int[,] array = new int[2, length + 1];
for (int i = 1; i <= length; i++)
{
array[0, i] = i;
}
int num = 0;
for (int j = 1; j <= length2; j++)
{
num = (j & 1);
array[num, 0] = j;
int num2 = num ^ 1;
for (int i = 1; i <= length; i++)
{
int num3 = (target[i - 1] == source[j - 1]) ? 0 : 1;
array[num, i] = Math.Min(Math.Min(array[num2, i] + 1, array[num, i - 1] + 1), array[num2, i - 1] + num3);
}
}
result = array[num, length];
}
return result;
}
}
}
I've been trying to create a program where it takes an array input through an object and passes the parameter (simulation of ArrayList).
I keep getting the java.lang.ArrayIndexOutOfBoundsException in which I'm guessing I'm not accessing the array properly..
What can I do to enhance the test object and/ or the constructor?
public class MyArrayList{
public int[] x;
public MyArrayList( ){
x = new int[0];
}
public MyArrayList(int[] k)
{
for (int i = 0; i < x.length; i++)
x[i] = k[i];
k = x;
}
public void add(int index).......
public int size().....
public int get(int index).....
public void set(int index, int value).......
public String toString( )........
Below is the class I am having trouble with.
public class TestMyArrayList
{
public static void main(String[] args)
{
MyArrayList test = new MyArrayList();
test.x[0] = 1;
test.x[1] = 2;
test.x[2] = 3;
test.x[3] = 4;
test.x[4] = 5;
test.add(2);
test.set(1,3);
int a, b;
String c;
a = test.size( );
b = test.get(5);
c = test.toString( );
System.out.println("The size of the array is" + a);
System.out.println("The value at that position is " + b);
System.out.println("The resulting string is: " + c);
}
}
This line from your constructor is the only location (in the code you've shown) where the array x is initialized:
x = new int[0];
And it creates a zero length array. Assuming you are not reinitializing the array somewhere else then all these lines will definitely fail:
test.x[0] = 1;
test.x[1] = 2;
test.x[2] = 3;
test.x[3] = 4;
test.x[4] = 5;
Because your array length is zero. So:
Initialize your array to a more sensible value
Consider encapsulating the array so that callers cannot directly access it. This will make it much easier to code up your application in the long run
Side note (aka bonus):
This other constructor of yours:
public MyArrayList(int[] k) {
for (int i = 0; i < x.length; i++)
x[i] = k[i];
k = x;
}
has some issues as well:
You should reinitialize your array x to be the same size as the supplied array, prior to copying over the values.
The assignment k = x is basically a no-op, because it doesn't actually change what k was pointing to outside of the method.
Overall, it should look more like this:
public MyArrayList(int[] k) {
super();
if(k != null) {
x = new int[k.length];
for (int i = 0; i < x.length; i++) {
x[i] = k[i];
}
} else {
x = null;
}
}
So, I've been playing with trying to create an AppBar program I'm making. Now, the program itself is actually quite simple but I had to borrow some code from a CodeProject project to make it an AppBar.
So, my code is the following:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
[StructLayout(LayoutKind.Sequential)]
struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential)]
struct APPBARDATA
{
public int cbSize;
public IntPtr hWnd;
public int uCallbackMessage;
public int uEdge;
public RECT rc;
public IntPtr lParam;
}
enum ABMsg : int
{
ABM_NEW = 0,
ABM_REMOVE,
ABM_QUERYPOS,
ABM_SETPOS,
ABM_GETSTATE,
ABM_GETTASKBARPOS,
ABM_ACTIVATE,
ABM_GETAUTOHIDEBAR,
ABM_SETAUTOHIDEBAR,
ABM_WINDOWPOSCHANGED,
ABM_SETSTATE
}
enum ABNotify : int
{
ABN_STATECHANGE = 0,
ABN_POSCHANGED,
ABN_FULLSCREENAPP,
ABN_WINDOWARRANGE
}
enum ABEdge : int
{
ABE_LEFT = 0,
ABE_TOP,
ABE_RIGHT,
ABE_BOTTOM
}
private bool fBarRegistered = false;
private int uCallBack;
private int whereToPin;
[DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);
[DllImport("USER32")]
static extern int GetSystemMetrics(int Index);
[DllImport("User32.dll", ExactSpelling = true,
CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool MoveWindow
(IntPtr hWnd, int x, int y, int cx, int cy, bool repaint);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern int RegisterWindowMessage(string msg);
private void RegisterBar()
{
APPBARDATA abd = new APPBARDATA();
abd.cbSize = Marshal.SizeOf(abd);
abd.hWnd = this.Handle;
if (!fBarRegistered)
{
uCallBack = RegisterWindowMessage("AppBarMessage");
abd.uCallbackMessage = uCallBack;
uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
fBarRegistered = true;
ABSetPos();
}
else
{
SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);
fBarRegistered = false;
}
}
private void ABSetPos()
{
APPBARDATA abd = new APPBARDATA();
abd.cbSize = Marshal.SizeOf(abd);
abd.hWnd = this.Handle;
abd.uEdge = whereToPin;
if (abd.uEdge == (int)ABEdge.ABE_LEFT || abd.uEdge == (int)ABEdge.ABE_RIGHT)
{
abd.rc.top = 0;
abd.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;
if (abd.uEdge == (int)ABEdge.ABE_LEFT)
{
abd.rc.left = 0;
abd.rc.right = Size.Width;
}
else
{
abd.rc.right = SystemInformation.PrimaryMonitorSize.Width;
abd.rc.left = abd.rc.right - Size.Width;
}
}
else
{
abd.rc.left = 0;
abd.rc.right = SystemInformation.PrimaryMonitorSize.Width;
if (abd.uEdge == (int)ABEdge.ABE_TOP)
{
abd.rc.top = 0;
abd.rc.bottom = Size.Height;
}
else
{
abd.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;
abd.rc.top = abd.rc.bottom - Size.Height;
}
}
SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref abd);
switch (abd.uEdge)
{
case (int)ABEdge.ABE_LEFT:
abd.rc.right = abd.rc.left + Size.Width;
break;
case (int)ABEdge.ABE_RIGHT:
abd.rc.left = abd.rc.right - Size.Width;
break;
case (int)ABEdge.ABE_TOP:
abd.rc.bottom = abd.rc.top + 100;
break;
case (int)ABEdge.ABE_BOTTOM:
abd.rc.top = abd.rc.bottom - Size.Height;
break;
}
SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref abd);
MoveWindow(abd.hWnd, abd.rc.left, abd.rc.top,
abd.rc.right - abd.rc.left, abd.rc.bottom - abd.rc.top, true);
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == uCallBack)
{
switch (m.WParam.ToInt32())
{
case (int)ABNotify.ABN_POSCHANGED:
ABSetPos();
break;
}
}
base.WndProc(ref m);
}
protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style &= (~0x00C00000); // WS_CAPTION
cp.Style &= (~0x00800000); // WS_BORDER
cp.ExStyle = 0x00000080 | 0x00000008; // WS_EX_TOOLWINDOW | WS_EX_TOPMOST
return cp;
}
}
private void button1_Click(object sender, EventArgs e)
{
whereToPin = (int)ABEdge.ABE_LEFT;
RegisterBar();
}
private void button2_Click(object sender, EventArgs e)
{
whereToPin = (int)ABEdge.ABE_RIGHT;
RegisterBar();
}
}
My two questions are:
What are the possible values cp.Style and how do those values effect the display of the AppBar? (The code to which I refer to is located in the System.Windows.Forms.CreateParams override)
I see they are values such as (~0x00C00000) but I have no idea how they work beyond those specific values and can't seem to find any enumeration of different values.
I'm a rather new, self teaching, programmer who does well by taking examples and molding them to my own uses. Thanks in advance for any help you can provide.
Here you go...
Window Styles
As per the OP's original query, there's also:
Window Class Styles