Example #1
0
 public void UpdateScreen(BitArray bitData)
 {
     for (int i = 0; i < pixelsObjects.Count; i++)
     {
         pixelsObjects[i].SetActive(bitData[i]);
     }
 }
    static void Main()
    {
        BitArray bits = new BitArray(100000);
        bits[99999] = 1;

        Console.WriteLine(bits.ToString());
    }
Example #3
0
 public static void And_EmptyArray()
 {
     BitArray bitArray1 = new BitArray(0);
     BitArray bitArray2 = new BitArray(0);
     
     Assert.Equal(0, bitArray1.And(bitArray2).Length);
 }
    private void renderCurrentState()
    {
        int i;
        BitArray stacks = new BitArray( brain.getKnownObjects().Count );

        foreach ( iThinkFact fact in brain.curState.getFactList() )
        {
            if ( fact.getName().Equals( "onTable" ) )
            {
                i = findNextFreeStack( stacks );
                fact.getObj( 0 ).transform.position = new Vector3( (float)( 1.5 - i * 1.5 ), 0, 0 );
                stacks.Set( i - 1, true );
            }
        }

        foreach ( iThinkFact fact in brain.curState.getFactList() )
        {
            if ( fact.getName().Equals( "on" ) )
            {
                fact.getObj( 0 ).transform.position = fact.getObj( 1 ).transform.position;
                fact.getObj( 0 ).transform.Translate( 0, (float)1.5, 0 );
            }

            else if ( fact.getName().Equals( "holding" ) )
            {
                fact.getObj( 0 ).transform.position = new Vector3( -15, 5, 0 );
            }
        }
    }
Example #5
0
    public BitArray GenerateSubset(
            int n, int k, BigInteger i, BitArray b, int offset)
    {
        BigInteger upperBound = Choose(n, k);
        if (i>=upperBound) {
            // There are only nCk possible subsets to return.
            return null;
        }

        int zeros = 0; // Count of zeros on the front before the first 1.
        BigInteger low = BigInteger.ZERO;
        BigInteger high = Choose(n-1, k-1);
        while (i>=high){
            zeros += 1;
            low = high;
            high = high+Choose(n-zeros-1, k-1);
        }

        if (zeros + k > n) {
            // Something is wrong! Not enough bits exist.
            throw new Exception("Too many zeros!");
        }

        b[offset+zeros] = true;

        if (k == 1) return b;
        else return GenerateSubset(
                n-zeros-1, k-1, i-low, b, offset+zeros+1);
    }
Example #6
0
    public BitArray GetBitsStuffed()
    {
        int nstuff = 0;
        bool last = false;
        BitArray ba = new BitArray();
        foreach (bool bit in GetBitsUnstuffed().Bits())
        {
            if (bit == last)
                nstuff++;
            else
            {
                nstuff = 1;
                last = bit;
            }

            if (nstuff > 5)
            {
                ba.AddBit(!last);
                nstuff = 1;
            }

            ba.AddBit(bit);
        }

        return ba;
    }
Example #7
0
 static void Main()
 {
     BitArray num = new BitArray(8);
     num[0] = 1;
     num[7] = 1;
     Console.WriteLine(num);
 }
Example #8
0
    public static LinkedList<Point> GetWalkingSteps(Point start, BitArray goals, bool walkInWater = false, bool nearbyOk = false)
    {
        Bb.ReadBoard();

        if (!goals.ToPoints().Any())
        {
            return null;
        }
        Point[] starts = { start };
        var passable = Solver.GetPassable(true);
        var aStarPassable = new BitArray(passable);
        aStarPassable.Set(start, true);
        if (nearbyOk)
        {
            aStarPassable.Or(goals);
        }
        Func<Point, Point, int> cost = (c, n) => (Bb.Water.Get(n) && !walkInWater) ? 10 : 1;
        var route = Pather.AStar(starts, p => goals.Get(p), aStarPassable, cost, p => 0);
        if (route == null)
        {
            return null;
        }
        var steps = new LinkedList<Point>(route);
        steps.RemoveFirst();
        if (steps.Count > 0 && !passable.Get(steps.Last.Value))
        {
            steps.RemoveLast();
        }
        return steps;
    }
        private static void TestSequentialInv(int count)
        {
            BitArray array = new BitArray(false, count);
            for (int x = 0; x < count; x++)
            {
                if (array.GetBit(x))
                    throw new Exception("each bit should be cleared");
            }

            array = new BitArray(true, count);
            for (int x = 0; x < count; x++)
            {
                if (!array.GetBit(x))
                    throw new Exception("each bit should be set");
            }
            for (int x = 0; x < count; x++)
            {
                array.ClearBit(x);
                if (array.GetBit(x))
                    throw new Exception("each bit should be cleared");
                array.SetBit(x);
                if (!array.GetBit(x))
                    throw new Exception("each bit should be cleared");
                array.ClearBit(x);

                if (array.FindSetBit() != (x == count - 1 ? -1 : x + 1))
                    throw new Exception();
            }
        }
Example #10
0
 public static string Read()
 {
     String xd;
     using(StreamReader reader = new StreamReader("Output.txt"))
     {
         xd = reader.ReadToEnd();
     }
     string[] c = xd.Split(' ');
     List<byte> outputs = new List<byte>();
     foreach(string x in c)
     {
         char[] d = x.ToCharArray();
         BitArray Out = new BitArray(8);
         if (d.Length != 8)
         {
             continue;
         }
         for(int i = 0; i < 8; i++)
         {
             Out[i] = d[i] == 'x';
         }
         outputs.Add(ConvertToByte(Out));
     }
     return Encoding.ASCII.GetString(outputs.ToArray());
 }
Example #11
0
	// Use this for initialization
	void Start () {
		
		
		
		object[] obj = GameObject.FindSceneObjectsOfType(typeof (GameObject));		
		foreach (object o in obj)
		{
			GameObject g = (GameObject) o;
			if(g.GetComponent<PhotoEye>()!=null)
			{
				if(g.GetComponent<PhotoEye>().IO_name_photoeye==IO_name_photoeye_trigger)
				{
					g.GetComponent<PhotoEye>().ConnectATR(gameObject);
				}
			}
		}
		encoding = new System.Text.ASCIIEncoding();		
		
		max_emu_to_plc_io = 1600; // 200 bytes
		emu_to_plc_bits = new BitArray(max_emu_to_plc_io);
		
		
		
		
		Logger.WriteLine("[INFO]","STARTUP AtrsCom on port " + ATR_PORT + " linked to photoeye " + IO_name_photoeye_trigger,"",true);
		Debug.Log("STARTUP AtrsCom on port " + ATR_PORT + " linked to photoeye " + IO_name_photoeye_trigger+".\r\n");
		ready = true;
		
		listenerThread = new Thread(new ThreadStart(DoListen));
        listenerThread.Start();
		
		
	}
	public void Load(int Index){
			MemoryMappedFileSecurity CustomSecurity = new MemoryMappedFileSecurity();
CustomSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType
.Allow));
			using(MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("bits", (long)Math.Ceiling(Length/8.0), MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileOptions.None, CustomSecurity, System.IO.HandleInheritability.Inheritable)){
			using (MemoryMappedViewStream stream = mmf.CreateViewStream())
           		{
				int Amount = (int)Math.Ceiling((double)(Length/Int32.MaxValue));
				int Remainder = (int)(Length%Int32.MaxValue);
				int length = (int)(Amount==Index?Math.Ceiling(Remainder/8.0):Math.Ceiling(Int32.MaxValue/8.0));
				byte[] buffer = BitArrayToByteArray(LoadedArray,0,LoadedArray.Length);
				stream.Position=(long)Math.Ceiling((Int32.MaxValue/8.0))*LoadedArrayIndex;
                		BinaryWriter writer = new BinaryWriter(stream);
				writer.Write(buffer);
				stream.Position=0;//(long)Math.Ceiling((Int32.MaxValue/8.0))*Index;
				BinaryReader reader = new BinaryReader(stream);
				buffer = new byte[(int)Math.Ceiling((Int32.MaxValue/8.0))];
				try{reader.Read(buffer,(int)Math.Ceiling((Int32.MaxValue/8.0))*Index,(int)Math.Ceiling((Int32.MaxValue/8.0)));} catch{LoadedArray = new BitArray((int)(length*8.0));}
           		}
			}
			//int ElementIndex = (int)Math.Floor((double)(T/Int32.MaxValue));
			//int Index = (int)(T%Int32.MaxValue);
			//Elements[ElementIndex][Index]=value;
		//}
	}
Example #13
0
        static void Main()
        {
            BitArray bits = new BitArray();

            //Random set of bits
            for (int i = 0; i < 64; i++)
            {
                Random random = new Random();
                StringBuilder getTime = new StringBuilder();
                
                int randomNumber = (int)DateTime.Now.Ticks;

                //Трябва ми време за да се получи добър random
                for (int j = 0; j < 100000; j++)
                {
                    Math.Sqrt(j + 1);
                }
                //Край на губенето на време

                if (randomNumber % 2 == 0)
                {
                    bits[i] = 1;
                }
            }

            Console.WriteLine(bits);

            //Print all Bits
            foreach (var item in bits)
            {
                Console.Write(item);
            }
            Console.WriteLine();
        }
    static void Main()
    {
        int maxNum = 10000000;

        BitArray primeNumbers = new BitArray(maxNum, true);

        for (int i = 2; i < Math.Sqrt(maxNum); i++)
        {
            if (primeNumbers[i] == true)
            {
                for (int j = i * i; j < maxNum; )
                {
                    primeNumbers[j] = false;
                    j += i;
                }
            }
        }

        for (int i = 0; i < primeNumbers.Count; i++)
        {
            if (primeNumbers[i] == true)
            {
                Console.Write("{0} ",i);
            }
        }
    }
	public static string Decode (Texture2D image){
		
		//Get the pixels for the image...
		Color[] imagePixels = image.GetPixels();
		
		//Go Through the First 32 Pixels and create a 4 byte array. 
		//This array should give us the message's length.	
		BitArray newBits = new BitArray(32);
		for (int i=0;i<32;i++){
			if(imagePixels[i].a == 1){
				newBits[i] = true;
			}
			else {
				newBits[i] = false;
			}
		}
		
		int total = System.BitConverter.ToInt32(ToByteArray(newBits), 0);
		BitArray messageBits = new BitArray(total);
		for (int j=32;j<total + 32;j++){
				if(imagePixels[j].a == 1){
					messageBits[j-32] = true;
				}
				else {
					messageBits[j-32] = false;
				}
		}
		
		return System.Text.Encoding.ASCII.GetString(ToByteArray(messageBits));
		
	}
Example #16
0
    // Update is called once per frame
    void Update()
    {
        if (ListenClient.ori != null && ListenClient.ori.Length > 4)
        {
            //Debug.Log (ListenClient.ori);
            string[] difPos = ListenClient.ori.Split('_');
            Debug.Log (difPos);
            string[] pos = difPos[0].Split(' ');

            double accel = double.Parse(difPos[1]);
            if (accel >= 7000 && !audio.isPlaying) {
                audio.Play ();
            }
            int button = int.Parse(difPos[2]);
            int trigger = int.Parse(difPos[3]);
            Debug.Log (button);
            b = new BitArray (new int[] { button });
            bool[] bits = new bool[32];
            if (button != 0) {
                b.CopyTo (bits, 0);

            }
            Debug.Log ("button " + bits[19]);
            if (bits [19]) {
                globalExtended = true;
            } else {
                globalExtended = false;
            }

            if (pos.Length >= 4)
            {
                Quaternion q = new Quaternion(float.Parse(pos[1]), float.Parse(pos[2]), float.Parse(pos[3]), float.Parse(pos[0]));
                //q = upInv * q;
                //q = Quaternion.Inverse(q);
                Vector3 e = q.eulerAngles;
                e.x *= -1;
                e.y *= -1;
                pivot.transform.rotation = Quaternion.Euler(e);
                //Debug.Log("transformed");
            }

        }

        if (ListenClient.pos != null && ListenClient.pos.Length > 5)
        {
            string[] strPos = ListenClient.pos.Split(';');
            for (int i = 0; i < strPos.Length; i++)
            {
                if (strPos[i].Contains("rwrist"))
                {
                    string[] headPos = strPos[i].Split(' ');
                    Debug.Log("POS: " + ListenClient.pos);
                    Debug.Log("i: " + strPos[i]);
                    transform.position =
                        new Vector3(float.Parse(headPos[1]) * 5, float.Parse(headPos[2]) * 5, 7 - float.Parse(headPos[3]) * 2);
                    break;
                }
            }
        }
    }
    static void Main()
    {
        int n = 10000000;
        int m = (int)Math.Sqrt(n);
        BitArray sieve = new BitArray(n);

        int i = 2;
        while (i <= m)
        {
            for (int j = 2 * i; j < n; j += i)
            {
                sieve[j] = true;
            }
            do
            {
                i++;
            }
            while (sieve[i] == true);
        }

        //print just the prime numbers up to 100
        for (int j = 2; j < 100; j++)
        {
            if (sieve[j] == false)
            {
                Console.WriteLine(j);
            }
        }
    }
Example #18
0
        public static void Not(int length)
        {
            BitArray bitArray = new BitArray(length, false);
            if (length > 0)
            {
                bitArray[0] = true;
                bitArray[1] = true;
                bitArray[length - 2] = true;
                bitArray[length - 1] = true;
            }

            BitArray bitArrayNot = bitArray.Not();
            Assert.Equal(bitArray.Length, bitArrayNot.Length);
            Assert.Same(bitArray, bitArrayNot);
            for (int i = 0; i < bitArray.Length; i++)
            {
                if (i <= 1 || i >= length - 2)
                {
                    Assert.False(bitArrayNot[i]);
                }
                else
                {
                    Assert.True(bitArrayNot[i]);
                }
            }
        }
Example #19
0
    public void loadSaveData(int id)
    {
        currentFlag.SetAll(false);

        //load file
        string filepath = string.Format("{0}/sav{1}", Application.persistentDataPath, id);
        Debug.Log(filepath);

        if (!File.Exists(filepath))
        {
            //show error
            return;
        }

        FileStream fs = File.Open(filepath, FileMode.Open);

        BinaryReader reader = new BinaryReader(fs);
        currentID = reader.ReadInt32();
        byte[] buf = reader.ReadBytes(10);
        currentFlag = new BitArray(buf);

        for (int i = (int)GameValueType.None; i < (int)GameValueType.Max; i++ )
        {
            values[(GameValueType)i] = reader.ReadInt32();
        }

        fs.Flush();
        fs.Close();

        startGame();
    }
Example #20
0
 static void Main()
 {
     BitArray bits = new BitArray(8);
     bits[0] = 1;
     bits[7] = 1;
     System.Console.WriteLine(bits);
 }
Example #21
0
    public static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            Bb.maxX = 5;
            Bb.maxY = 5;

            Point[] starts = { new Point() };
            Func<Point, bool> isGoal = p => p.x == 4 && p.y == 4;
            BitArray passable = new BitArray(new bool[] {
                true, false, true, true, true,
                true, true, true, false, true,
                true, true, true, false, true,
                true, false, false, false, true,
                true, true, true, true, true,
            });

            var path = Pather.AStar(starts, isGoal, passable, (c, n) => n.x == 0 ? 1 : 0, p => 0);
            foreach (Point p in path)
            {
                Console.WriteLine(p);
            }
        }

        if (args.Length < 1)
        {
            System.Console.WriteLine("Please enter a hostname");
            return;
        }

        IntPtr connection = Client.createConnection();

        AI ai = new AI(connection);
        if (Client.serverConnect(connection, args[0], "19000") == 0)
        {
            System.Console.WriteLine("Unable to connect to server");
            return;
        }

        if (Client.serverLogin(connection, ai.username(), ai.password()) == 0)
            return;

        if (args.Length < 2)
            Client.createGame(connection);
        else
            Client.joinGame(connection, Int32.Parse(args[1]), "player");

        while (Client.networkLoop(connection) != 0)
        {
            if (ai.startTurn())
                Client.endTurn(connection);
            else
                Client.getStatus(connection);
        }

        Client.networkLoop(connection); //Grab end game state
        Client.networkLoop(connection); //Grab log
        ai.end();
    }
    private BitArray b; // BinaryImage of the reference texture

    #endregion Fields

    #region Constructors

    public BinaryImage(int x, int y)
    {
        this.x = x;
        this.y = y;

        b = new BitArray(x*y);
        Length = b.Length;
    }
Example #23
0
 public object Clone()
 {
     BitArray anotherArray = new BitArray();
     anotherArray.bits = new BitValue[this.getLengthOfArray()];
     for (int i = 0; i < this.getLengthOfArray(); ++i)
         anotherArray.bits[i] = this.bits[i];
     return anotherArray;
 }
 public static Point Decode(int index)
 {
   var bits = new BitArray(new[] {index});
   var x = DecodeAxis(bits, 1);
   var y = DecodeAxis(bits, 0);
   var result = new Point(x, y);
   return result;
 }
    public BinaryImage(int x, int y, bool b)
    {
        this.x = x;
        this.y = y;

        this.b = new BitArray(x*y, b);
        Length = this.b.Length;
    }
        static void Main()
        {
            BitArray bitArray = new BitArray(4);
            bitArray[1] = 1;
            bitArray[8] = 1;

            System.Console.WriteLine(bitArray);
        }
	public bool runTest()
	{
		Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer);
		int iCountErrors = 0;
		int iCountTestcases = 0;
		String strLoc = "Loc_000oo";
		BitArray bitArr1;
		BitArray bitArr2;
		Boolean[] bolArr1;
		Int32 iNumOfElements;
		Random rnd1;
		try {
			do
			{
				iNumOfElements = 10;
				rnd1 = new Random();
				strLoc = "Loc_742dsf!";
				iCountTestcases++;
				bolArr1 = new Boolean[iNumOfElements];
				for(int i=0; i<iNumOfElements; i++){
					if(rnd1.Next(10)>5)
						bolArr1[i] = true;
					else
						bolArr1[i] = false;
				}
				bitArr1 = new BitArray(bolArr1);
				bitArr2 = (BitArray)bitArr1.Clone();
				for(int i=0; i<iNumOfElements; i++){
					if(bitArr1[i] != bitArr2[i]){
						iCountErrors++;
						Console.WriteLine("Err_36tdfg_" + i + "! Wrong value returned, ");
					}
				}
				iCountTestcases++;
				for(int i=0; i<iNumOfElements; i++)
					bitArr1[i] = !bitArr1[i];
				for(int i=0; i<iNumOfElements; i++){
					if(bitArr1[i] != !bitArr2[i]){
						iCountErrors++;
						Console.WriteLine("Err_394t7sg_" + i + "! Wrong value returned, ");
					}
				}
			} while (false);
			} catch (Exception exc_general ) {
			++iCountErrors;
			Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString());
		}
		if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
			return true;
		}
		else
		{
			Console.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
			return false;
		}
	}
Example #28
0
 public static IEnumerable<Point> GetNeededTrenches(Pump pump)
 {
     var digworthy = GetDiggableAndUnDug();
     var starts = new HashSet<Point>(pump.GetPoints());
     var goals = Bb.GlaciersSet.Where(g => Bb.tileLookup[g].WaterAmount > 5);
     var impassable = new BitArray(Bb.OurSpawns).Or(Bb.TheirSpawns).Or(Bb.OurPumps).Or(Bb.TheirPumps);
     var path = Pather.AStar(starts, p => goals.Contains(p), impassable.Not(), (c, n) => digworthy.Get(n) ? 1 : 0, p => 0);
     return path.Where(p => digworthy.Get(p));
 }
Example #29
0
 static void Main()
 {
     BitArray bitArr = new BitArray(16);
     bitArr[12] = 1;
     bitArr[14] = 1;
     bitArr[15] = 1;
     //bitArr[16] = 1;
     Console.WriteLine(bitArr.ToString());
 }
Example #30
0
 public static BitArray GetOurSpawnable()
 {
     // (spawns + pumps-not-under-seige) - units - spawning
     var spawns = Bb.OurSpawnSet.ToBitArray();
     var pumps = Bb.OurPumpSet.Where(p => p.station.SiegeAmount == 0).SelectMany(p => p.GetPoints()).ToBitArray();
     var units = new BitArray(Bb.OurUnits).Or(Bb.TheirUnits);
     var spawning = new BitArray(Bb.IsSpawning);
     return spawns.Or(pumps).And(units.Not()).And(spawning.Not());
 }
Example #31
0
 public static DataParameter Create(string name, BitArray value)
 {
     return(new DataParameter {
         DataType = DataType.BitArray, Name = name, Value = value,
     });
 }
    private static T CreateAssociateInternal<T>(Type originalForType, Type currentForType, out Type foundForType,
      string[] associateTypeSuffixes, object[] constructorParams, List<Pair<Assembly, string>> locations,
      bool exactTypeMatch)
      where T : class
    {
      if (currentForType==null) {
        foundForType = null;
        return null;
      }

      string associateTypePrefix;
      Type[] genericArguments;

      // Possible cases: generic type, array type, regular type
      if (currentForType.IsGenericType) {
        // Generic type
        associateTypePrefix = currentForType.Name;
        genericArguments = currentForType.GetGenericArguments();
      }
      else if (currentForType.IsArray) {
        // Array type
        Type elementType = currentForType.GetElementType();
        int rank = currentForType.GetArrayRank();
        if (rank==1)
          associateTypePrefix = "Array`1";
        else
          associateTypePrefix = string.Format("Array{0}D`1", rank);
        genericArguments = new Type[] {elementType};
      }
      else if (currentForType==typeof (Enum)) {
        // Enum type
        Type underlyingType = Enum.GetUnderlyingType(originalForType);
        associateTypePrefix = "Enum`2";
        genericArguments = new Type[] {originalForType, underlyingType};
      }
      else if (currentForType==typeof (Array)) {
        // Untyped Array type
        foundForType = null;
        return null;
      }
      else {
        // Regular type
        associateTypePrefix = currentForType.Name;
        genericArguments = null;
      }

      // Replacing 'I' at interface types
      if (currentForType.IsInterface && associateTypePrefix.StartsWith("I"))
        associateTypePrefix = AddSuffix(associateTypePrefix.Substring(1), "Interface");

      // Search for exact associate
      T result =
        CreateAssociateInternal<T>(originalForType, currentForType, out foundForType, associateTypePrefix,
          associateTypeSuffixes,
          locations, genericArguments, constructorParams);
      if (result!=null)
        return result;

      if (exactTypeMatch) {
        foundForType = null;
        return null;
      }

      // Nothing is found; tryng to find an associate for base type (except Object)
      Type forTypeBase = currentForType.BaseType;
      if (forTypeBase!=null)
        while (forTypeBase!=typeof (object)) {
          result = CreateAssociateInternal<T>(originalForType, forTypeBase, out foundForType,
            associateTypeSuffixes, constructorParams, locations, true);
          if (result!=null)
            return result;
          forTypeBase = forTypeBase.BaseType;
        }

      // Nothing is found; tryng to find an associate for implemented interface
      Type[] interfaces = currentForType.GetInterfaces();
      int interfaceCount = interfaces.Length;
      BitArray suppressed = new BitArray(interfaceCount);
      while (interfaceCount > 0) {
        // Suppressing all the interfaces inherited from others
        // to allow their associates to not conflict with each other
        for (int i = 0; i < interfaceCount; i++) {
          for (int j = 0; j < interfaceCount; j++) {
            if (i==j)
              continue;
            if (interfaces[i].IsAssignableFrom(interfaces[j])) {
              suppressed[i] = true;
              break;
            }
          }
        }
        Type lastGoodInterfaceType = null;
        // Scanning non-suppressed interfaces
        for (int i = 0; i < interfaceCount; i++) {
          if (suppressed[i])
            continue;
          T resultForInterface = CreateAssociateInternal<T>(originalForType, interfaces[i], out foundForType,
            associateTypeSuffixes, constructorParams, locations, true);
          if (resultForInterface!=null) {
            if (result!=null)
              throw new InvalidOperationException(string.Format(
                Strings.ExMultipleAssociatesMatch,
                GetShortName(currentForType),
                GetShortName(result.GetType()),
                GetShortName(resultForInterface.GetType())));
            result = resultForInterface;
            lastGoodInterfaceType = foundForType;
            foundForType = null;
          }
        }
        if (result!=null) {
          foundForType = lastGoodInterfaceType;
          return result;
        }
        // Moving suppressed interfaces to the beginning
        // to scan them on the next round
        int k = 0;
        for (int i = 0; i < interfaceCount; i++) {
          if (suppressed[i]) {
            interfaces[k] = interfaces[i];
            suppressed[k] = false;
            k++;
          }
        }
        interfaceCount = k;
      }

      // Nothing is found; tryng to find an associate for Object type
      if (currentForType!=typeof (object)) {
        result = CreateAssociateInternal<T>(originalForType, typeof (object), out foundForType,
          "Object", associateTypeSuffixes,
          locations, null, constructorParams);
        if (result!=null)
          return result;
      }

      // Nothing is found at all
      foundForType = null;
      return null;
    }
Example #33
0
        public void OnLeaveBitArray(object obj = null)
        {
            BitArray bitArray = (BitArray)obj;

            OnLeaveList((bitArray.Count == 0), true);
        }
Example #34
0
 /// <summary> Subclasses override this to decode the portion of a barcode between the start
 /// and end guard patterns.
 ///
 /// </summary>
 /// <param name="row">row of black/white values to search
 /// </param>
 /// <param name="startRange">start/end offset of start guard pattern
 /// </param>
 /// <param name="resultString">{@link StringBuffer} to append decoded chars to
 /// </param>
 /// <returns> horizontal offset of first pixel after the "middle" that was decoded
 /// </returns>
 /// <throws>  ReaderException if decoding could not complete successfully </throws>
 protected internal abstract int?decodeMiddle(BitArray row, int[] startRange, System.Text.StringBuilder resultString);
Example #35
0
 public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints)
 {
     return(decodeRow(rowNumber, row, findStartGuardPattern(row), hints));
 }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            uint parsedValue;

            if ((series_length.Text).ToString().Length == 0)
            {
                MessageBox.Show("Podaj długość ciągu do wygenerowania.");
                return;
            }
            else if (!uint.TryParse(series_length.Text, out parsedValue))
            {
                MessageBox.Show("Długość ciągu do wygenerowania musi być dodatnią liczbą całkowitą.");
                return;
            }

            uint parsed;

            if (!uint.TryParse(lfsr1.Text, out parsed))
            {
                MessageBox.Show("Wartości początkowe rejestrów muszą być dodatnią liczbą całkowitą.");
                return;
            }
            else if ((lfsr1.Text).ToString().Length == 0)
            {
                MessageBox.Show("Uzupełnij pola z wartościami początkowymi rejestrów.");
                return;
            }

            var registersLength = Convert.ToInt32(RegisterLength_ComboBox.SelectedItem);

            var boolArray = Convert.ToString(parsed, 2).Select(str => str.Equals('1')).Take(registersLength).ToArray();
            var bitArray  = new BitArray(registersLength);

            for (int j = 0; j < boolArray.Length; j++)
            {
                bitArray[j] = boolArray[j];
            }

            int numOfLfsr = 1;

            Lfsr[] lfsr = new Lfsr[numOfLfsr];
            lfsr[0] = new Lfsr(registersLength);
            TextBox tb = (TextBox)this.FindName("lfsr1");

            lfsr[0].SetRegisterValues(bitArray);


            wynik.Clear();
            LfsrGenerator generator = new SelfShrinkingGenerator(lfsr);

            if (typ.SelectedIndex == 0)
            {
                var gen = generator.GenerateBitsAsChars(Convert.ToInt32(series_length.Text));
                wynik.Text = new string(gen);
            }
            else if (typ.SelectedIndex == 1)
            {
                var gen1 = generator.GenerateBytes(Convert.ToInt32(series_length.Text));
                wynik.Text = BitConverter.ToString(gen1);
            }
            else if (typ.SelectedIndex == 2)
            {
                var gen1 = generator.GenerateIntegers(Convert.ToInt32(series_length.Text));
                wynik.Text = String.Join(" ", gen1.Select(p => p.ToString()).ToArray());
            }
        }
Example #37
0
        static void Main(string[] args)
        {
            HashSet <string> U = new HashSet <string>();
            HashSet <string> A = new HashSet <string>();
            HashSet <string> B = new HashSet <string>();
            HashSet <string> C = new HashSet <string>();

            Console.Write("Введите количество множеств (2 или 3):");
            int s = int.Parse(Console.ReadLine());

            Console.Write("Элементы множества U: ");
            string[] strU = Console.ReadLine().Split(new char[] { ' ', '\n', '\t', ',' }, StringSplitOptions.RemoveEmptyEntries);
            Console.Write("Элементы множества U без дубликатов: ");
            Hash(ref strU, U);
            foreach (string el in U)
            {
                Console.Write(el + " ");
            }
            Console.WriteLine();
            Console.Write("Элементы множества A: ");
            string[] strA = Console.ReadLine().Split(new char[] { ' ', '\n', '\t', ',' }, StringSplitOptions.RemoveEmptyEntries);
            Console.Write("Элементы множества A, принадлежащие универсуму: ");
            Hash(ref strA, A);
            Intersect(U, ref A);
            Console.WriteLine();
            Console.Write("Элементы множества B: ");
            string[] strB = Console.ReadLine().Split(new char[] { ' ', '\n', '\t', ',' }, StringSplitOptions.RemoveEmptyEntries);
            Console.Write("Элементы множества B, принадлежащие универсуму: ");
            Hash(ref strB, B);
            Intersect(U, ref B);
            Console.WriteLine();
            Array.Resize(ref strA, U.Count);
            Array.Resize(ref strB, U.Count);
            BitArray mybU = new BitArray(U.Count);
            BitArray mybA = new BitArray(strA.Length);
            BitArray mybB = new BitArray(strB.Length);

            mybU.SetAll(true);
            mybA.SetAll(false);
            mybB.SetAll(false);
            for (int i = 0; i < U.Count; i++)
            {
                if (strA.Contains(U.ElementAt(i)))
                {
                    mybA[i] = true;
                }
                else
                {
                    mybA[i] = false;
                }
            }
            for (int i = 0; i < U.Count; i++)
            {
                if (strB.Contains(U.ElementAt(i)))
                {
                    mybB[i] = true;
                }
                else
                {
                    mybB[i] = false;
                }
            }
            BitArray newbA   = new BitArray(mybA);
            BitArray newbAA  = new BitArray(mybA);
            BitArray newbAAa = new BitArray(mybA);
            BitArray newbBB  = new BitArray(mybB);
            BitArray newbB   = new BitArray(mybB);
            BitArray mybAa   = new BitArray(mybA);
            BitArray forA    = new BitArray(mybA);
            BitArray forA1   = new BitArray(mybA);
            BitArray forB    = new BitArray(mybB);
            BitArray forB1   = new BitArray(mybB);

            Console.Write("Элементы множества А: ");
            WriteBy(newbAA, U);
            Console.WriteLine();
            Console.Write("Элементы множества B: ");
            WriteBy(mybB, U);
            Console.WriteLine();
            Console.Write("Пересечение множеств А и В: ");
            And(ref newbAA, ref newbBB, U);
            Console.Write("Объединение множеств А и В: ");
            Or(ref newbA, ref newbBB, U);
            Console.Write("Разность множеств А и В: ");
            Xor(ref newbA, ref newbBB, U);
            Console.Write("Разность множеств B и A: ");
            Xor(ref newbBB, ref newbAAa, U);
            Console.Write("Дополнение множества А до U: ");
            Not(ref mybAa, U);
            Console.Write("Дополнение множества B до U: ");
            Not(ref newbB, U);
            if (s == 3)
            {
                Console.Write("Элементы множества C: ");
                string[] strC = Console.ReadLine().Split(new char[] { ' ', '\n', '\t', ',' }, StringSplitOptions.RemoveEmptyEntries);
                Console.Write("Элементы множества C, принадлежащие универсуму: ");
                Hash(ref strC, C);
                Intersect(U, ref C);
                Console.WriteLine();
                Array.Resize(ref strC, U.Count);
                BitArray mybC = new BitArray(strC.Length);
                mybC.SetAll(false);
                for (int i = 0; i < U.Count; i++)
                {
                    if (strC.Contains(U.ElementAt(i)))
                    {
                        mybC[i] = true;
                    }
                    else
                    {
                        mybC[i] = false;
                    }
                }
                BitArray newbCa = new BitArray(mybC);                                                                                                                   BitArray myB = new BitArray(mybB); BitArray myA = new BitArray(mybA);
                BitArray newbCca  = new BitArray(mybC);
                BitArray mybCcc   = new BitArray(mybC);
                BitArray newbCb   = new BitArray(mybC);
                BitArray newbCccb = new BitArray(mybC);
                BitArray myAc     = new BitArray(mybA);
                BitArray myBc     = new BitArray(mybB);
                Console.Write("Элементы множества C: ");
                WriteBy(mybC, U);
                Console.WriteLine();
                Console.Write("Пересечение множеств C и A: ");
                And(ref newbCa, ref myAc, U);
                Console.Write("Пересечение множеств C и B: ");
                And(ref newbCb, ref myBc, U);
                Console.Write("Объединение множеств C и A: ");
                Or(ref newbCca, ref myA, U);
                Console.Write("Объединение множеств C и B: ");
                Or(ref newbCccb, ref myB, U);
                Console.Write("Разность множеств C и A: ");
                Xor(ref newbCca, ref mybA, U);
                Console.Write("Разность множеств C и B: ");
                Xor(ref newbCccb, ref mybB, U);
                Console.Write("Разность множеств A и C: ");
                BitArray newbCcc = new BitArray(mybC);
                Xor(ref mybA, ref newbCcc, U);
                Console.Write("Разность множеств B и C: ");
                Xor(ref mybB, ref newbCcc, U);
                Console.Write("Дополнение множества C до U: ");
                Not(ref mybCcc, U);
                BitArray forC  = new BitArray(mybC);
                BitArray forC1 = new BitArray(mybC);
                Console.Write("Укажите номер задания(1,2 или 3):");
                int q = int.Parse(Console.ReadLine());
                if (q == 1)
                {
                    SpecialOp1(ref forA, ref forA1, ref forB, ref forC, U);
                }
                else if (q == 2)
                {
                    SpecialOp2(ref forB, ref forB1, ref forC, ref forC1, U);
                }
                else
                {
                    SpecialOp3(ref forA, ref forA1, ref forC, ref forC1, U);
                }
            }
            Console.ReadKey();
        }
Example #38
0
 // Emulates the Java BitSet.Get() method.
 // Prevents exceptions from being thrown when the index is too high.
 public static bool SafeGet(this BitArray a, int loc)
 {
     return(loc < a.Length && a.Get(loc));
 }
Example #39
0
 /// <summary>
 ///
 /// </summary>
 internal UserRights()
 {
     _rights       = new BitArray(0);
     _rightsTab    = new Hashtable();
     RightsHashKey = "";
 }
Example #40
0
 protected override void SetStorage(object store, BitArray nullbits)
 {
     _values = (byte[])store;
     SetNullStorage(nullbits);
 }
Example #41
0
 protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex)
 {
     byte[] typedStore = (byte[])store;
     typedStore[storeIndex] = _values[record];
     nullbits.Set(storeIndex, IsNull(record));
 }
Example #42
0
        /// <summary>
        /// Adjust received data and build response
        /// </summary>
        /// <param name="send_buffer">Send buffer</param>
        /// <param name="receive_buffer">Receive buffer</param>
        /// <param name="flux">Object for flux gest</param>
        /// <param name="unit_id">Slave id</param>
        /// <param name="transaction_id">Transaction id of TCP slave</param>
        void AdjAndReply(List <byte> send_buffer, List <byte> receive_buffer, object flux, byte unit_id, ushort transaction_id)
        {
            ushort sa, sa1, qor, qor1, bc, val, and_mask, or_mask;
            int    bytes;
            bool   cv;

            bool[]      ret_vals;
            ModbusCodes mdbcode;

            // Empting reception buffer
            send_buffer.Clear();
            // Adjust data
            mdbcode = (ModbusCodes)receive_buffer[0];
            switch (mdbcode)
            {
            case ModbusCodes.READ_COILS:
                // Read received commands
                sa  = ToUInt16(receive_buffer.ToArray(), 1);
                qor = ToUInt16(receive_buffer.ToArray(), 3);
                if (ModbusDatabase.Single(x => x.UnitID == unit_id).Coils.Length == 0)
                {
                    Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!((qor >= 1) && (qor <= MAX_COILS_IN_READ_MSG)))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_VALUE;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!IsAllRegistersPresent(unit_id, ModbusDBTables.COIL_REGISTERS, sa, qor))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_ADDRESS;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                // Reply
                send_buffer.Add((byte)ModbusCodes.READ_COILS);
                bytes = (qor / 8) + (qor % 8 == 0 ? 0 : 1);
                send_buffer.Add((byte)bytes);
                ret_vals = new bool[bytes * 8];
                try
                {
                    ModbusDatabase.Single(x => x.UnitID == unit_id).Coils.ToList().GetRange(sa, qor).CopyTo(ret_vals);
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                for (int ii = 0; ii < bytes; ii++)
                {
                    send_buffer.Add(EightBitToByte(ret_vals, ii * 8));
                }
                break;

            case ModbusCodes.READ_DISCRETE_INPUTS:
                // Read received commands
                sa  = ToUInt16(receive_buffer.ToArray(), 1);
                qor = ToUInt16(receive_buffer.ToArray(), 3);
                if (ModbusDatabase.Single(x => x.UnitID == unit_id).DiscreteInputs.Length == 0)
                {
                    Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!((qor >= 1) && (qor <= MAX_DISCRETE_INPUTS_IN_READ_MSG)))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_VALUE;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!IsAllRegistersPresent(unit_id, ModbusDBTables.DISCRETE_INPUTS_REGISTERS, sa, qor))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_ADDRESS;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                // Reply
                send_buffer.Add((byte)ModbusCodes.READ_DISCRETE_INPUTS);
                bytes = (qor / 8) + (qor % 8 == 0 ? 0 : 1);
                send_buffer.Add((byte)bytes);
                ret_vals = new bool[bytes * 8];
                try
                {
                    ModbusDatabase.Single(x => x.UnitID == unit_id).DiscreteInputs.ToList().GetRange(sa, qor).CopyTo(ret_vals);
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                for (int ii = 0; ii < bytes; ii++)
                {
                    send_buffer.Add(EightBitToByte(ret_vals, ii * 8));
                }
                break;

            case ModbusCodes.READ_HOLDING_REGISTERS:
                // Read received commands
                sa  = ToUInt16(receive_buffer.ToArray(), 1);
                qor = ToUInt16(receive_buffer.ToArray(), 3);
                if (ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters.Length == 0)
                {
                    Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!((qor >= 1) && (qor <= MAX_HOLDING_REGISTERS_IN_READ_MSG)))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_VALUE;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!IsAllRegistersPresent(unit_id, ModbusDBTables.HOLDING_REGISTERS, sa, qor))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_ADDRESS;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                // Reply
                send_buffer.Add((byte)ModbusCodes.READ_HOLDING_REGISTERS);
                send_buffer.Add((byte)(2 * qor));
                try
                {
                    for (int ii = 0; ii < (qor * 2); ii += 2)
                    {
                        send_buffer.AddRange(GetBytes(ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters[sa + (ii / 2)]));
                    }
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                break;

            case ModbusCodes.READ_INPUT_REGISTERS:
                // Read received commands
                sa  = ToUInt16(receive_buffer.ToArray(), 1);
                qor = ToUInt16(receive_buffer.ToArray(), 3);
                if (ModbusDatabase.Single(x => x.UnitID == unit_id).InputRegisters.Length == 0)
                {
                    Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!((qor >= 1) && (qor <= MAX_INPUT_REGISTERS_IN_READ_MSG)))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_VALUE;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!IsAllRegistersPresent(unit_id, ModbusDBTables.INPUT_REGISTERS, sa, qor))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_ADDRESS;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                // Reply
                send_buffer.Add((byte)ModbusCodes.READ_INPUT_REGISTERS);
                send_buffer.Add((byte)(2 * qor));
                try
                {
                    for (int ii = 0; ii < (qor * 2); ii += 2)
                    {
                        send_buffer.AddRange(GetBytes(ModbusDatabase.Single(x => x.UnitID == unit_id).InputRegisters[sa + (ii / 2)]));
                    }
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                break;

            case ModbusCodes.WRITE_SINGLE_COIL:
                // Adjusting
                sa  = ToUInt16(receive_buffer.ToArray(), 1);
                val = ToUInt16(receive_buffer.ToArray(), 3);
                switch (val)
                {
                case 0x0000:
                    cv = false;
                    break;

                case 0xFF00:
                    cv = true;
                    break;

                default:
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_VALUE;
                    cv    = false;                                  // Dummy
                    break;
                }
                if (ModbusDatabase.Single(x => x.UnitID == unit_id).Coils.Length == 0)
                {
                    Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (Error == Errors.EXCEPTION_ILLEGAL_DATA_VALUE)
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!IsAllRegistersPresent(unit_id, ModbusDBTables.COIL_REGISTERS, sa, 1))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_ADDRESS;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (Error == Errors.WRONG_WRITE_SINGLE_COIL_VALUE)
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_ILLEGAL_DATA_VALUE);
                    break;
                }
                try
                {
                    ModbusDatabase.Single(x => x.UnitID == unit_id).Coils[sa] = cv;
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                // Reply
                send_buffer.Add((byte)ModbusCodes.WRITE_SINGLE_COIL);
                send_buffer.AddRange(GetBytes(sa));
                send_buffer.AddRange(GetBytes(val));
                break;

            case ModbusCodes.WRITE_SINGLE_REGISTER:
                // Adjusting
                sa  = ToUInt16(receive_buffer.ToArray(), 1);
                val = ToUInt16(receive_buffer.ToArray(), 3);
                if (ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters.Length == 0)
                {
                    Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!((val >= 0x0000) && (val <= 0xFFFF)))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_VALUE;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!IsAllRegistersPresent(unit_id, ModbusDBTables.HOLDING_REGISTERS, sa, 1))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_ADDRESS;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                try
                {
                    ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters[sa] = val;
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                // Reply
                send_buffer.Add((byte)ModbusCodes.WRITE_SINGLE_REGISTER);
                send_buffer.AddRange(GetBytes(sa));
                send_buffer.AddRange(GetBytes(val));
                break;

            case ModbusCodes.WRITE_MULTIPLE_COILS:
                // Adjusting
                sa  = ToUInt16(receive_buffer.ToArray(), 1);
                qor = ToUInt16(receive_buffer.ToArray(), 3);
                if (ModbusDatabase.Single(x => x.UnitID == unit_id).Coils.Length == 0)
                {
                    Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!((qor >= 1) && (qor <= MAX_COILS_IN_WRITE_MSG)))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_VALUE;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!IsAllRegistersPresent(unit_id, ModbusDBTables.COIL_REGISTERS, sa, qor))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_ADDRESS;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                bc = receive_buffer[5];
                byte[]   buffer = receive_buffer.GetRange(6, bc).ToArray();
                BitArray ba     = new BitArray(buffer);
                try
                {
                    ba.CopyTo(ModbusDatabase.Single(x => x.UnitID == unit_id).Coils, sa);
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                // Reply
                send_buffer.Add((byte)ModbusCodes.WRITE_MULTIPLE_COILS);
                send_buffer.AddRange(GetBytes(sa));
                send_buffer.AddRange(GetBytes(qor));
                break;

            case ModbusCodes.WRITE_MULTIPLE_REGISTERS:
                // Adjusting
                sa  = ToUInt16(receive_buffer.ToArray(), 1);
                qor = ToUInt16(receive_buffer.ToArray(), 3);
                if (ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters.Length == 0)
                {
                    Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!((qor >= 1) && (qor <= MAX_HOLDING_REGISTERS_IN_WRITE_MSG)))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_VALUE;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!IsAllRegistersPresent(unit_id, ModbusDBTables.HOLDING_REGISTERS, sa, qor))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_ADDRESS;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                bc = receive_buffer[5];
                try
                {
                    for (int ii = 0; ii < bc; ii += 2)
                    {
                        ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters[sa + (ii / 2)] = ToUInt16(receive_buffer.ToArray(), 6 + ii);
                    }
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                // Reply
                send_buffer.Add((byte)ModbusCodes.WRITE_MULTIPLE_REGISTERS);
                send_buffer.AddRange(GetBytes(sa));
                send_buffer.AddRange(GetBytes(qor));
                break;

            case ModbusCodes.MASK_WRITE_REGISTER:
                // Adjusting
                sa       = ToUInt16(receive_buffer.ToArray(), 1);
                and_mask = ToUInt16(receive_buffer.ToArray(), 3);
                or_mask  = ToUInt16(receive_buffer.ToArray(), 5);
                if (ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters.Length == 0)
                {
                    Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!(((and_mask >= 0x0000) && (and_mask <= 0xFFFF)) || ((and_mask >= 0x0000) && (and_mask <= 0xFFFF))))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_VALUE;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!IsAllRegistersPresent(unit_id, ModbusDBTables.HOLDING_REGISTERS, sa, 1))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_ADDRESS;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                try
                {
                    ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters[sa] =
                        (ushort)((ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters[sa] & and_mask) | (or_mask & (~and_mask)));
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                // Reply
                send_buffer.Add((byte)ModbusCodes.MASK_WRITE_REGISTER);
                send_buffer.AddRange(GetBytes(sa));
                send_buffer.AddRange(GetBytes(and_mask));
                send_buffer.AddRange(GetBytes(or_mask));
                break;

            case ModbusCodes.READ_WRITE_MULTIPLE_REGISTERS:
                // Adjusting
                sa   = ToUInt16(receive_buffer.ToArray(), 1);
                qor  = ToUInt16(receive_buffer.ToArray(), 3);
                sa1  = ToUInt16(receive_buffer.ToArray(), 5);
                qor1 = ToUInt16(receive_buffer.ToArray(), 7);
                if (ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters.Length == 0)
                {
                    Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if (!(((qor >= 1) && (qor <= MAX_HOLDING_REGISTERS_TO_READ_IN_READWRITE_MSG)) ||
                      ((qor1 >= 1) && (qor1 <= MAX_HOLDING_REGISTERS_TO_WRITE_IN_READWRITE_MSG))))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_VALUE;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                if ((!IsAllRegistersPresent(unit_id, ModbusDBTables.HOLDING_REGISTERS, sa, qor)) ||
                    (!IsAllRegistersPresent(unit_id, ModbusDBTables.HOLDING_REGISTERS, sa1, qor1)))
                {
                    Error = Errors.EXCEPTION_ILLEGAL_DATA_ADDRESS;
                    BuildExceptionMessage(send_buffer, mdbcode, Error);
                    break;
                }
                bc = receive_buffer[9];
                // First: Exec writing...
                try
                {
                    for (int ii = 0; ii < bc; ii += 2)
                    {
                        ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters[sa1 + (ii / 2)] = ToUInt16(receive_buffer.ToArray(), 10 + ii);
                    }
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                // Second: Exec reading and prepare the reply
                send_buffer.Add((byte)ModbusCodes.READ_WRITE_MULTIPLE_REGISTERS);
                send_buffer.AddRange(GetBytes((ushort)(qor * 2)));
                try
                {
                    for (int ii = 0; ii < (qor * 2); ii += 2)
                    {
                        send_buffer.AddRange(GetBytes(ModbusDatabase.Single(x => x.UnitID == unit_id).HoldingRegisters[sa + (ii / 2)]));
                    }
                }
                catch
                {
                    BuildExceptionMessage(send_buffer, mdbcode, Errors.EXCEPTION_SLAVE_DEVICE_FAILURE);
                    break;
                }
                break;

            default:
                Error = Errors.EXCEPTION_ILLEGAL_FUNCTION;
                BuildExceptionMessage(send_buffer, mdbcode, Error);
                break;
            }
            // Send response
            SendReply(send_buffer, flux, unit_id, transaction_id);
        }
Example #43
0
 public static byte[] BitArrayToByteArray(BitArray bits)
 {
     byte[] ret = new byte[(bits.Length - 1) / 8 + 1];
     bits.CopyTo(ret, 0);
     return(ret);
 }
        /// <summary>
        /// Writes a byte of data to a specified port address
        /// </summary>
        public override void WritePort(ushort port, byte value)
        {
            if (port == 0x7ffd)
            {
                Last7ffd = value;
            }
            else if (port == 0x1ffd)
            {
                Last1ffd = value;
            }
            else if ((port & 0x01) == 0)
            {
                LastFe = value;
            }

            // get a BitArray of the port
            BitArray portBits = new BitArray(BitConverter.GetBytes(port));
            // get a BitArray of the value byte
            BitArray bits = new BitArray(new byte[] { value });

            // Check whether the low bit is reset
            bool lowBitReset = !portBits[0]; // (port & 0x01) == 0;

            AYDevice.WritePort(port, value);

            UPDDiskDevice.WritePort(port, value);

            // port 0x7ffd - hardware should only respond when bits 1 & 15 are reset and bit 14 is set
            if (!portBits[1] && !portBits[15] && portBits[14])
            {
                if (!PagingDisabled)
                {
                    // bits 0, 1, 2 select the RAM page
                    var rp = value & 0x07;
                    if (rp < 8)
                    {
                        RAMPaged = rp;
                    }

                    // bit 3 controls shadow screen
                    SHADOWPaged = bits[3];

                    // Bit 5 set signifies that paging is disabled until next reboot
                    PagingDisabled = bits[5];

                    // portbit 4 is the LOW BIT of the ROM selection
                    ROMlow = bits[4];
                }
            }
            // port 0x1ffd - hardware should only respond when bits 1, 13, 14 & 15 are reset and bit 12 is set
            if (!portBits[1] && portBits[12] && !portBits[13] && !portBits[14] && !portBits[15])
            {
                if (!PagingDisabled)
                {
                    if (!bits[0])
                    {
                        // special paging is not enabled - get the ROMpage high byte
                        ROMhigh = bits[2];

                        // set the special paging mode flag
                        SpecialPagingMode = false;
                    }
                    else
                    {
                        // special paging is enabled
                        // this is decided based on combinations of bits 1 & 2
                        // Config 0 = Bit1-0 Bit2-0
                        // Config 1 = Bit1-1 Bit2-0
                        // Config 2 = Bit1-0 Bit2-1
                        // Config 3 = Bit1-1 Bit2-1
                        BitArray confHalfNibble = new BitArray(2);
                        confHalfNibble[0] = bits[1];
                        confHalfNibble[1] = bits[2];

                        // set special paging configuration
                        PagingConfiguration = ZXSpectrum.GetIntFromBitArray(confHalfNibble);

                        // set the special paging mode flag
                        SpecialPagingMode = true;
                    }
                }

                // bit 4 is the printer port strobe
                PrinterPortStrobe = bits[4];
            }

            // Only even addresses address the ULA
            if (lowBitReset)
            {
                // store the last OUT byte
                LastULAOutByte = value;

                /*
                 *  Bit   7   6   5   4   3   2   1   0
                 +-------------------------------+
                 |   |   |   | E | M |   Border  |
                 +-------------------------------+
                 */

                // Border - LSB 3 bits hold the border colour
                if (ULADevice.BorderColor != (value & BORDER_BIT))
                {
                    //ULADevice.RenderScreen((int)CurrentFrameCycle);
                    ULADevice.BorderColor = value & BORDER_BIT;
                }

                // Buzzer
                BuzzerDevice.ProcessPulseValue((value & EAR_BIT) != 0, _renderSound);

                // Tape
                TapeDevice.WritePort(port, value);

                // Tape
                //TapeDevice.ProcessMicBit((value & MIC_BIT) != 0);
            }


            LastULAOutByte = value;
        }
Example #45
0
        override public Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
        {
            if (!setCounters(row))
            {
                return(null);
            }

            int startOffset = findStartPattern();

            if (startOffset < 0)
            {
                return(null);
            }

            int nextStart = startOffset;

            decodeRowResult.Length = 0;
            do
            {
                int charOffset = toNarrowWidePattern(nextStart);
                if (charOffset == -1)
                {
                    return(null);
                }
                // Hack: We store the position in the alphabet table into a
                // StringBuilder, so that we can access the decoded patterns in
                // validatePattern. We'll translate to the actual characters later.
                decodeRowResult.Append((char)charOffset);
                nextStart += 8;
                // Stop as soon as we see the end character.
                if (decodeRowResult.Length > 1 &&
                    arrayContains(STARTEND_ENCODING, ALPHABET[charOffset]))
                {
                    break;
                }
            } while (nextStart < counterLength); // no fixed end pattern so keep on reading while data is available

            // Look for whitespace after pattern:
            int trailingWhitespace = counters[nextStart - 1];
            int lastPatternSize    = 0;

            for (int i = -8; i < -1; i++)
            {
                lastPatternSize += counters[nextStart + i];
            }

            // We need to see whitespace equal to 50% of the last pattern size,
            // otherwise this is probably a false positive. The exception is if we are
            // at the end of the row. (I.e. the barcode barely fits.)
            if (nextStart < counterLength && trailingWhitespace < lastPatternSize / 2)
            {
                return(null);
            }

            if (!validatePattern(startOffset))
            {
                return(null);
            }

            // Translate character table offsets to actual characters.
            for (int i = 0; i < decodeRowResult.Length; i++)
            {
                decodeRowResult[i] = ALPHABET[decodeRowResult[i]];
            }
            // Ensure a valid start and end character
            char startchar = decodeRowResult[0];

            if (!arrayContains(STARTEND_ENCODING, startchar))
            {
                return(null);
            }
            char endchar = decodeRowResult[decodeRowResult.Length - 1];

            if (!arrayContains(STARTEND_ENCODING, endchar))
            {
                return(null);
            }

            // remove stop/start characters character and check if a long enough string is contained
            if (decodeRowResult.Length <= MIN_CHARACTER_LENGTH)
            {
                // Almost surely a false positive ( start + stop + at least 1 character)
                return(null);
            }

            decodeRowResult.Remove(decodeRowResult.Length - 1, 1);
            decodeRowResult.Remove(0, 1);

            int runningCount = 0;

            for (int i = 0; i < startOffset; i++)
            {
                runningCount += counters[i];
            }
            float left = (float)runningCount;

            for (int i = startOffset; i < nextStart - 1; i++)
            {
                runningCount += counters[i];
            }
            float right = (float)runningCount;

            return(new Result(
                       decodeRowResult.ToString(),
                       null,
                       new ResultPoint[]
            {
                new ResultPoint(left, (float)rowNumber),
                new ResultPoint(right, (float)rowNumber)
            },
                       BarcodeFormat.CODABAR));
        }
Example #46
0
 public override void UpdateImage(ImageData img) => _data = new BitArray(img.Data.ToByteArray());
Example #47
0
 /// <summary>
 /// Sets all bits to false
 /// </summary>
 /// <param name="bits">The BitArray object.</param>
 public static void Clear(this BitArray bits)
 {
     bits.SetAll(false);
 }
Example #48
0
        public static bool[] ToBoolArray(this BitArray bitArray)
        {
            var boolArray = bitArray.Cast <bool>().ToArray();

            return(boolArray);
        }
 public GenomeBinaryString(int size)
 {
     bits = new BitArray(size);
 }
Example #50
0
 /// <summary>
 /// Sets the bit at the given <paramref name="index"/> to false.
 /// </summary>
 /// <param name="bits">The BitArray object.</param>
 /// <param name="index">The position to set to false.</param>
 public static void Clear(this BitArray bits, int index)
 {
     bits.SafeSet(index, false);
 }
Example #51
0
        static void SpecialOp1(ref BitArray forA, ref BitArray forA1, ref BitArray B, ref BitArray C, HashSet <string> U)
        {
            BitArray notA        = forA.Not();
            BitArray unionAB     = forA1.Or(B);
            BitArray unionNotAB  = notA.Or(B);
            BitArray unionNotABC = unionNotAB.Or(C);                                                                                                                                                         //BitArray total = unionNotABC.Xor(unionAB);
            BitArray total       = unionAB.Not();

            Console.Write("Задание №1:");
            for (int i = 0; i < U.Count; i++)
            {
                if (total[i] == true)
                {
                    foreach (char el in U.ElementAt(i))
                    {
                        Console.Write(el + " ");
                    }
                }
            }
            Console.WriteLine();
        }
Example #52
0
 /// <summary>
 /// Sets the bit at the given <paramref name="index"/> to true.
 /// </summary>
 /// <param name="bits">The BitArray object.</param>
 /// <param name="index">The position to set to true.</param>
 public static void Set(this BitArray bits, int index)
 {
     bits.SafeSet(index, true);
 }
Example #53
0
        public BitArray GetBitArray()
        {
            BitArray modifiersBits = new BitArray(16);

            //Difficulty
            //Easy      = 000
            //Normal    = 001
            //Hard      = 010
            //Expert    = 011
            //Expert+   = 100
            modifiersBits[0] = difficulty == BeatmapDifficulty.Normal || difficulty == BeatmapDifficulty.Expert; //First bit
            modifiersBits[1] = difficulty == BeatmapDifficulty.Hard || difficulty == BeatmapDifficulty.Expert;   //Second bit
            modifiersBits[2] = difficulty == BeatmapDifficulty.ExpertPlus;                                       //Third bit

            //Song speed modifier
            //Normal speed = 00
            //Faster speed = 01
            //Slower Speed = 10
            //Reserved =     11
            modifiersBits[3] = modifiers.songSpeed == GameplayModifiers.SongSpeed.Faster; //First bit
            modifiersBits[4] = modifiers.songSpeed == GameplayModifiers.SongSpeed.Slower; //Second bit

            //Other modifiers
            modifiersBits[5]  = modifiers.noFail;
            modifiersBits[6]  = modifiers.noObstacles;
            modifiersBits[7]  = modifiers.noBombs;
            modifiersBits[8]  = modifiers.noArrows;
            modifiersBits[9]  = modifiers.instaFail;
            modifiersBits[10] = modifiers.batteryEnergy;
            modifiersBits[11] = modifiers.disappearingArrows;
            modifiersBits[12] = modifiers.ghostNotes;


            //Beatmap characteristic
            //Standard = 00
            //No arrows = 01
            //One saber = 10
            //Custom = 11
            switch (characteristicName)
            {
            case "Standard":
                modifiersBits[13] = false;
                modifiersBits[14] = false;
                break;

            case "NoArrows":
                modifiersBits[13] = false;
                modifiersBits[14] = true;
                break;

            case "OneSaber":
                modifiersBits[13] = true;
                modifiersBits[14] = false;
                break;

            default:
                modifiersBits[13] = true;
                modifiersBits[14] = true;
                break;
            }

            //Reserved
            modifiersBits[15] = false;

            return(modifiersBits);
        }
Example #54
0
 /// <summary>
 /// convert total BitArray
 /// </summary>
 /// <param name="bitArr">source BitArray</param>
 public static int ReadUInt32(BitArray bitArr)
 {
     return(ReadUInt32(bitArr, 0, bitArr.Length));
 }
Example #55
0
 //UPGRADE_NOTE: Access modifiers of method 'decodeEnd' were changed to 'protected'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1204'"
 protected internal virtual int[] decodeEnd(BitArray row, int endStart)
 {
     return(findGuardPattern(row, endStart, false, START_END_PATTERN));
 }
Example #56
0
 /// <summary>
 /// start at index 0
 /// </summary>
 /// <param name="bitArr">source BitArray</param>
 /// <param name="length">bit count</param>
 public static int ReadUInt32(BitArray bitArr, int length)
 {
     return(ReadUInt32(bitArr, 0, length));
 }
Example #57
0
        public static string BitsToString(this BitArray a, uint start, uint end)
        {
            BitArray ret = Range(a, start, end);

            return(ret.BitsToString());
        }
Example #58
0
        public static string ToStr(this BitArray bitArray)
        {
            var result = string.Join("", bitArray.Cast <bool>().Select(Convert.ToInt32));

            return(result);
        }
Example #59
0
 internal void Init(byte ownerIdx, Note note, ADSR env, NoisePattern pattern)
 {
     Init(ownerIdx, note, env);
     pat = (pattern == NoisePattern.Fine ? fine : rough);
 }
Example #60
0
 override protected void SetStorage(object store, BitArray nullbits)
 {
     values = (SqlGuid[])store;
     //SetNullStorage(nullbits);
 }