Exemplo n.º 1
1
 public void TestArray_Scenario_Result()
 {
     var strings = new[] { "Acme", "WB", "Universal" };
     Console.WriteLine(strings.Length);
     Console.WriteLine(strings.Rank);
     Console.WriteLine(strings.GetLength(0));
     Console.WriteLine(strings.GetUpperBound(0));
     Console.WriteLine(strings.Count());
 }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            var grid = new[,]
                {
                    {08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08},
                    {49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00},
                    {81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65},
                    {52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91},
                    {22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80},
                    {24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50},
                    {32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70},
                    {67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21},
                    {24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72},
                    {21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95},
                    {78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92},
                    {16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57},
                    {86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58},
                    {19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40},
                    {04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66},
                    {88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69},
                    {04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36},
                    {20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16},
                    {20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54},
                    {01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48}
                };

            var width = grid.GetLength(0);
            var height = grid.GetLength(1);
            var lines = new List<List<int>>();

            for (var y = 0; y < height; y++)
            {
                var horizontal = new List<int>();

                for (var x = 0; x < width; x++)
                    horizontal.Add(grid[y, x]);

                lines.Add(horizontal);
            }

            for (var x = 0; x < width; x++)
            {
                var vertical = new List<int>();

                for (var y = 0; y < height; y++)
                    vertical.Add(grid[y, x]);

                lines.Add(vertical);
            }

            //TODO:斜めの走査
            #if DEBUG
            Console.ReadLine();
            #endif
        }
Exemplo n.º 3
0
        public void AccessToOutOfRangeElements()
        {
            // Arrange
            var element = new[,] { { 0 } };

            // Act
            var matrix = new Matrix<int>(element);
            Func<int> accessToInvalidIndex = () => matrix[element.GetLength(0) + 1, element.GetLength(1) + 1];

            accessToInvalidIndex();
        }
Exemplo n.º 4
0
        public void WriteArray(System.Array _array)
        {
            // Initialise with symbol to indicate start of array
            StringBuilder.Append('[');

            switch (_array.Rank)
            {
            case 1:
                int _1DArrayLength				= _array.Length;

                for (int _iter = 0; _iter < _1DArrayLength; _iter++)
                {
                    if (_iter != 0)
                        StringBuilder.Append(',');

                    WriteObjectValue(_array.GetValue(_iter));
                }

                break;

            case 2:
                int _outerArrayLength				= _array.GetLength(0);
                int _innerArrayLength				= _array.GetLength(1);

                for (int _outerIter = 0; _outerIter < _outerArrayLength; _outerIter++)
                {
                    if (_outerIter != 0)
                        StringBuilder.Append(',');

                    // Append symbol to indicate start of json string representation of inner array
                    StringBuilder.Append('[');

                    for (int _innerIter = 0; _innerIter < _innerArrayLength; _innerIter++)
                    {
                        if (_innerIter != 0)
                            StringBuilder.Append(',');

                        WriteObjectValue(_array.GetValue(_outerIter, _innerIter));
                    }

                    // Append symbol to indicate end of json string representation of inner array
                    StringBuilder.Append(']');
                }

                break;
            }

            // Append symbol to indicate end of json string representation of array
            StringBuilder.Append(']');
            return;
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            int SelectItem;
            RegistryKey[] regs = new[] {
            Registry.ClassesRoot,
            Registry.CurrentUser,
            Registry.LocalMachine,
            Registry.Users,
            Registry.CurrentConfig,
            };

            do
            {
                int i = 1;
                Console.WriteLine("Choose part system registry");
                foreach(RegistryKey reg in regs)
                {
                    Console.WriteLine("{0}. {1}" ,i++,reg.Name);
                }
                Console.WriteLine("0.Exit");
                Console.Write("> ");
                SelectItem = Convert.ToInt32(Console.ReadLine()[0]) - 48;
                Console.WriteLine();
                if (SelectItem > 0 && SelectItem <= regs.GetLength(0))
                    PrintRegKeys(regs[SelectItem - 1]);
            } while (SelectItem != 0);
        }
Exemplo n.º 6
0
 public void SingleDimensionalArrayTest()
 {
     var items = new[] {1, 2, 3};
     Assert.AreEqual(3, items.Length);
     Assert.AreEqual(1, items.Rank);
     Assert.AreEqual(3, items.GetLength(0));
 }
Exemplo n.º 7
0
        /// <summary>
        /// By default return False, i.e. the control is disabled.
        /// And, then loop through the permission matrix and enable/disable accordingly
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            const bool controlEnabledState = false;
            var thisTask = (TaskItem)value;


            /*
             * The following array represents the permission matrix for a control to be enabled.
             * <control name>,<1=enabled for assigned user>,<1=enabled for manager >
             * <control name>,<0=enabled for assigned user>,<0=enabled for manager >
             */
            var widgetPermissionMatrix= new[,] 
            {
                {"Status","1","0"},
                {"ManagementSignOff","0","1"},
                {"DueTime","0","1"},
                {"AlertTime","1","1"},//Sep 21, Alertime shoudl be controllable by manager/assignedto. Helps when manager is changing the due time.Avoids unrealistic timings
                {"EscalationTime","0","1"},
                {"LinkToProcess","0","1"},
                {"KriDefinition","0","1"},
                {"TaskDescription","0","0"},
                {"TaskName","0","0"},
                {"Manager","0","0"}

            }; 

            int  currenttaskperm=0x0;
            if (TaskItem.IsUserInAssignedTo(ViewModel.Current.WssUserId, thisTask))
            {
                currenttaskperm = currenttaskperm | 0x1;
            }

            if (TaskItem.IsUserManager (ViewModel.Current.WssUserId, thisTask))
            {
                currenttaskperm = currenttaskperm | 0x2;
            }

            int controlindex = 0;
            var controlname = (string)parameter;

            for (controlindex = 0; controlindex < widgetPermissionMatrix.GetLength(0); controlindex++)
            {
                if (!controlname.Equals(widgetPermissionMatrix[controlindex, 0])) continue;
                

                System.Diagnostics.Debug.WriteLine("{0}\r\n",widgetPermissionMatrix[controlindex,0]);
                System.Diagnostics.Debug.WriteLine ("\tA:{0},M:{1}\r\n",widgetPermissionMatrix[controlindex,1],widgetPermissionMatrix[controlindex,2] );
                int allowedroleaccess = 0;
                if (widgetPermissionMatrix[controlindex, 1].Equals("1")) allowedroleaccess = allowedroleaccess | 0x1;
                if (widgetPermissionMatrix[controlindex, 2].Equals("1")) allowedroleaccess = allowedroleaccess | 0x2;
                System.Diagnostics.Debug.WriteLine("\t\taccess:{0}", allowedroleaccess);
                return (currenttaskperm & allowedroleaccess) > 0;
            }
            

            return controlEnabledState;
        }
Exemplo n.º 8
0
        public void ShouldWorkForEnumeration()
        {
            var list = new []{ "a", "b", "c" };
            var blk = new ValueBlock(list);

            Assert.AreEqual("[\"a\", \"b\", \"c\"]", blk.GetMessage());

            blk.WithEnumerableCount(list.GetLength(0));
            Assert.AreEqual("[\"a\", \"b\", \"c\"] (3 items)", blk.GetMessage());
        }
        static void Main(string[] args)
        {
            var int_array = new int[] { 1, 2, 4 };
            var str_array = new string[] { "Hello", "Array", null };
            var nullable_array = new[] { 0, (int?)1, 2};

            Console.WriteLine(int_array.GetType());
            Console.WriteLine(str_array.GetType());
            Console.WriteLine(nullable_array.GetType());
            Console.WriteLine(nullable_array.GetLength(0));
        }
Exemplo n.º 10
0
        public void AccessTheElements()
        {
            // Arrange
            var predefinedElements = new[,]
            {
                {1, 0, 0},
                {0, 1, 0},
                {0, 0, 1}
            };

            // Act
            var matrix = new Matrix<int>(predefinedElements);

            // Assert
            for (int i = 0; i < predefinedElements.GetLength(0); i++)
            {
                for (int j = 0; j < predefinedElements.GetLength(1); j++)
                {
                    Assert.AreEqual(predefinedElements[i, j], matrix[i, j], "An element is not equal to the original value used to create the matrix.");
                }
            }
        }
Exemplo n.º 11
0
        public void JaggedArrayTest()
        {
            var items = new []
            {
                new [] {1, 2, 3},
                new [] {5},
                new [] {3, 4}
            };

            Assert.AreEqual(3, items[0][2]);
            Assert.AreEqual(3, items.Length);
            Assert.AreEqual(1, items.Rank);
            Assert.AreEqual(3, items.GetLength(0));
        }
Exemplo n.º 12
0
 public void DrawPolylineFeature(Graphics g, System.Drawing.Point[] Points_array,
     int LinePattern, System.Drawing.Color LineColor, int LineWidth)
 {
     if (LinePattern == 2)
     {
         if (Points_array.GetLength(0) > 1)
         {
             g.DrawLines(new Pen(LineColor), Points_array);
         }
     }
     else
     {
         DrawDashedPolyline(g, Points_array, LinePattern, LineColor, LineWidth, 0);
     }
 }
Exemplo n.º 13
0
        internal void DrawPolylineFeature(Graphics g, System.Drawing.Point[] Points_array,
            int LinePattern, System.Drawing.Color LineColor, int LineWidth)
        {
            IntPtr drawPen;		// gdi pen
            IntPtr drawPen_old;		// gdi pen

            if (LinePattern == 2)
            {
                drawPen = (IntPtr)Win32.GDI.CreatePen(Win32.GDI.PS_GEOMETRIC, LineWidth, LineColor.ToArgb());
                drawPen_old = (IntPtr)Win32.GDI.SelectObject(m_hdc, drawPen);

                int count = Points_array.GetLength(0);
                Win32.GDI.Polyline(m_hdc, ref Points_array[0], count);

                Win32.GDI.SelectObject(m_hdc, drawPen_old);
                Win32.GDI.DeleteObject(drawPen);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Return a random race number based on a group type.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static int GetRandomRace( int type )
        {
            int race;
            int[] animals = new[] {
                RACE_WORM, RACE_BIRD, RACE_HERBIVORE, RACE_RAT, RACE_FISH, RACE_BAT,
                RACE_SNAKE, RACE_BOAR, RACE_BEAR, RACE_HORSE, RACE_PRIMATE, RACE_INSECT
            };

            Random rand = new Random();

            switch( type )
            {
                case RACE_RANGE_ANY:
                    race = rand.Next(0, RaceList.Length - 1);
                    break;
                case RACE_RANGE_PLAYER:
                    race = rand.Next(0, Limits.MAX_PC_RACE - 1);
                    break;
                case RACE_RANGE_HUMANOID:
                    race = rand.Next(RACE_HUMAN, RACE_HUMANOID);
                    break;
                case RACE_RANGE_ANIMAL:
                    {
                        int index = rand.Next(0, animals.GetLength(0) / sizeof(int) - 1);
                        race = animals[ index ];
                    }
                    break;
                default:
                    throw new Exception("Race.GetRandomRace: invalid type");
            }
            if (race == RACE_GOD)
            {
                race = GetRandomRace(type);
            }

            return race;
        }
Exemplo n.º 15
0
        public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
        {
            // According to MS documentation, any implementation of the IO.Stream.Read function must:
            // (a) throw an exception if offset & count reference an invalid part of the buffer,
            //     or if count < 0, or if buffer is null
            // (b) return 0 only upon EOF, or if count = 0
            // (c) if not EOF, then return at least 1 byte, up to <count> bytes

            if (_streamMode == StreamMode.Undefined)
            {
                if (!this._stream.CanRead) throw new ZlibException("The stream is not readable.");
                // for the first read, set up some controls.
                _streamMode = StreamMode.Reader;
                // (The first reference to _z goes through the private accessor which
                // may initialize it.)
                z.AvailableBytesIn = 0;
                if (_flavor == ZlibStreamFlavor.GZIP)
                {
                    _gzipHeaderByteCount = _ReadAndValidateGzipHeader();
                    // workitem 8501: handle edge case (decompress empty stream)
                    if (_gzipHeaderByteCount == 0)
                        return 0;
                }
            }

            if (_streamMode != StreamMode.Reader)
                throw new ZlibException("Cannot Read after Writing.");

            if (count == 0) return 0;
            // workitem 10562
            // this quits too early if the input buffer has been consumed but
            // there's still output which hasn't been created yet (e.g. block
            // data for tables / tree, or the trailing adler32 data). we
            // need to wait for a Z_STREAM_END from Deflate instead.
            //if (nomoreinput && _wantCompress) return 0;  // workitem 8557
            if (buffer == null) throw new ArgumentNullException("buffer");
            if (count < 0) throw new ArgumentOutOfRangeException("count");
            if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset");
            if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count");

            int rc = 0;

            // set up the output of the deflate/inflate codec:
            _z.OutputBuffer = buffer;
            _z.NextOut = offset;
            _z.AvailableBytesOut = count;

            // This is necessary in case _workingBuffer has been resized. (new byte[])
            // (The first reference to _workingBuffer goes through the private accessor which
            // may initialize it.)
            _z.InputBuffer = workingBuffer;

            do
            {
                // need data in _workingBuffer in order to deflate/inflate.  Here, we check if we have any.
                if ((_z.AvailableBytesIn == 0) && (!nomoreinput))
                {
                    // No data available, so try to Read data from the captive stream.
                    _z.NextIn = 0;
                    _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length);
                    if (_z.AvailableBytesIn == 0)
                        nomoreinput = true;

                }
                // workitem 10562
                // if we've consumed all the input then we need to generate any
                // remaining block data and checksums and put them in the pending array
                if (nomoreinput) _flushMode = FlushType.Finish;
                // we have data in InputBuffer; now compress or decompress as appropriate
                rc = (_wantCompress)
                    ? _z.Deflate(_flushMode)
                    : _z.Inflate(_flushMode);

                if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR))
                    return 0;

                if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
                    throw new ZlibException(String.Format("{0}flating:  rc={1}  msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message));

                if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count))
                {
                    // workitem 10562
                    // we've genuinely reached the end of the output stream now,
                    // including any block data and adler32 which appears after
                    // the compressed input data. we don't have any more bytes
                    // to return so we can stop processing
                    return 0; // nothing more to read
                };
            }
            //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK);
            //while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK);
            while (_z.AvailableBytesOut > 0 && rc == ZlibConstants.Z_OK);

            // workitem 10562
            // the following is no longer required as we now call _z.Deflate
            // in the main loop above instead
            //// workitem 8557
            //// is there more room in output?
            //if (_z.AvailableBytesOut > 0)
            //{
            //    if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0)
            //    {
            //        // deferred
            //    }
            //
            //    // are we completely done reading?
            //    if (nomoreinput)
            //    {
            //        // and in compression?
            //        if (_wantCompress)
            //        {
            //            // no more input data available; therefore we flush to
            //            // try to complete the read
            //            rc = _z.Deflate(FlushType.Finish);
            //
            //            if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
            //                throw new ZlibException(String.Format("Deflating:  rc={0}  msg={1}", rc, _z.Message));
            //        }
            //    }
            //}

            rc = (count - _z.AvailableBytesOut);

            // calculate CRC after reading
            if (crc != null)
                crc.SlurpBlock(buffer, offset, rc);

            return rc;
        }
Exemplo n.º 16
0
        private void CreateVertexBuffer()
        {
            var vertices = new[,]
            {
                {  0.0f, -0.5f,  0.5f, 1.0f, 0.0f, 0.0f },
                {  0.5f,  0.5f,  0.5f, 0.0f, 1.0f, 0.0f },
                { -0.5f,  0.5f,  0.5f, 0.0f, 0.0f, 1.0f },
            };

            var createInfo = new BufferCreateInfo
            {
                StructureType = StructureType.BufferCreateInfo,
                Usage = BufferUsageFlags.VertexBuffer,
                Size = (ulong)(sizeof(float) * vertices.Length)
            };
            vertexBuffer = device.CreateBuffer(ref createInfo);

            MemoryRequirements memoryRequirements;
            device.GetBufferMemoryRequirements(vertexBuffer, out memoryRequirements);

            if (memoryRequirements.Size == 0)
                return;

            var allocateInfo = new MemoryAllocateInfo
            {
                StructureType = StructureType.MemoryAllocateInfo,
                AllocationSize = memoryRequirements.Size,
                MemoryTypeIndex = MemoryTypeFromProperties(memoryRequirements.MemoryTypeBits, MemoryPropertyFlags.HostVisible)
            };
            vertexBufferMemory = device.AllocateMemory(ref allocateInfo);

            var mapped = device.MapMemory(vertexBufferMemory, 0, (ulong)createInfo.Size, MemoryMapFlags.None);
            fixed (float* source = &vertices[0, 0]) Utilities.CopyMemory(mapped, new IntPtr(source), (int)createInfo.Size);
            device.UnmapMemory(vertexBufferMemory);

            device.BindBufferMemory(vertexBuffer, vertexBufferMemory, 0);

            vertexAttributes = new []
            {
                new VertexInputAttributeDescription { Binding = 0, Location = 0, Format = Format.R32G32B32SFloat, Offset = 0 },
                new VertexInputAttributeDescription { Binding = 0, Location = 1, Format = Format.R32G32B32SFloat, Offset = sizeof(float) * 3 },
            };

            vertexBindings = new []
            {
                new VertexInputBindingDescription { Binding = 0, InputRate = VertexInputRate.Vertex, Stride = (uint)(sizeof(float) * vertices.GetLength(1)) }
            };
        }
        private void PopulateCommandList()
        {
            commandAllocator.Reset();
            commandList.Reset(commandAllocator, pipelineState);
            commandList.SetGraphicsRootSignature(rootSignature);

            commandList.SetViewport(viewport);
            commandList.SetScissorRectangles(scissorRect);
            commandList.ResourceBarrierTransition(renderTargets[frameIndex], ResourceStates.Present, ResourceStates.RenderTarget);
            var rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            rtvHandle += frameIndex * rtvDescriptorSize;

            commandList.ClearDepthStencilView(handleDSV, ClearFlags.FlagsDepth, 1.0f, 0);
            commandList.ClearRenderTargetView(rtvHandle, new Color4(0, 0.2F, 0.4f, 1), 0, null);
            commandList.SetRenderTargets(1, rtvHandle, false, handleDSV);

            DescriptorHeap[] descHeaps = new[] { samplerViewHeap, shaderRenderViewHeap }; // shaderRenderViewHeap,
            commandList.SetDescriptorHeaps(descHeaps.GetLength(0), descHeaps);
            commandList.SetGraphicsRootDescriptorTable(0, shaderRenderViewHeap.GPUDescriptorHandleForHeapStart);
            commandList.SetGraphicsRootDescriptorTable(3, samplerViewHeap.GPUDescriptorHandleForHeapStart);
            commandList.PipelineState = pipelineState;

            commandList.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;

            foreach (BufferView b in bufferViews)
            {
                commandList.SetGraphicsRoot32BitConstant(1, b.TexsCount, 0);
                commandList.SetGraphicsRootDescriptorTable(2, shaderRenderViewHeap.GPUDescriptorHandleForHeapStart + b.ViewStep);
                commandList.SetVertexBuffer(0, b.vertexBufferView);
                commandList.SetIndexBuffer(b.indexBufferView);
                commandList.DrawIndexedInstanced(b.IndexCount, 1, 0, 0, 0);
            }

            commandList.SetGraphicsRootSignature(terrainRootSignature);
            commandList.PipelineState = pipelineState2;
            descHeaps = new[] { samplerViewHeap, terrainHeap };
            commandList.SetDescriptorHeaps(descHeaps.GetLength(0), descHeaps);
            commandList.SetGraphicsRootDescriptorTable(0, terrainHeap.GPUDescriptorHandleForHeapStart + device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView) * 2);
            commandList.SetGraphicsRootDescriptorTable(1, terrainHeap.GPUDescriptorHandleForHeapStart);
            commandList.SetGraphicsRootDescriptorTable(2, samplerViewHeap.GPUDescriptorHandleForHeapStart);
            commandList.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            commandList.SetVertexBuffer(0, TerrainVertexBufferView);
            commandList.DrawInstanced(100 * 100, 1, 0, 0);

            commandList.ResourceBarrierTransition(renderTargets[frameIndex], ResourceStates.RenderTarget, ResourceStates.Present);

            commandList.Close();
        }
        private async Task MLPTrainFFTest(ComputationContext ctx, params LayerBehavior[] rules)
        {
            var trainingData =
                new[,]
                {
                    { -4.0f, 16.0f },
                    { -3.0f, 9.0f },
                    { -2.0f, 4.0f },
                    { -1.0f, 1.0f },
                    { 0.0f, 0.0f },
                    { 1.0f, 1.0f },
                    { 2.0f, 4.0f },
                    { 3.0f, 9.0f },
                    { 4.0f, 16.0f },
                };

            const float maxInput = 4.0f;
            const float minInput = -4.0f;
            const float maxOutput = 16.0f;
            const float minOutput = 0.0f;

            const int inputSize = 1;
            const int hiddenSize = 16;
            const int outputSize = 1;

            const int maxIterations = 1000;

            var layers = NNTestHelpers.CreateGDMLPLayers(true, inputSize, hiddenSize, outputSize, rules);

            using (var nn = ctx.NeuralNetworkFactory.CreateMultilayerPerceptron(layers, new MultilayerPerceptronProperties { GradientComputationMethod = GradientComputationMethod.FeedForward }))
            using (var batch = new SupervisedBatch())
            using (var errors = ctx.DataArrayFactory.Create(maxIterations))
            {
                for (int i = 0; i < trainingData.GetLength(0); i++)
                {
                    batch.Add(
                        ctx.DataArrayFactory.Create(new[] { NNTestHelpers.Normalize(trainingData[i, 0], minInput, maxInput) }),
                        ctx.DataArrayFactory.Create(new[] { NNTestHelpers.Normalize(trainingData[i, 1], minOutput, maxOutput) }),
                        ctx.DataArrayFactory.Create(1));
                }

                bool first = true;
                var sw = new Stopwatch();
                sw.Start();
                for (int it = 0; it < maxIterations; it++)
                {
                    nn.Train(batch);

                    if (first)
                    {
                        using (var weights = ctx.DataArrayFactory.Create(nn.NumberOfWeights))
                        {
                            nn.GetWeights(weights);
                            float[] wa = new float[weights.Size];
                            await weights.Read(wa);

                            // It must be randomized:
                            Assert.IsTrue(wa.Sum() != 0.0f);
                        }
                        first = false;
                    }

                    ctx.VectorUtils.CalculateMSE(batch, errors, it);
                }

                float[] mses = new float[maxIterations];
                await errors.Read(mses);

                sw.Stop();

                foreach (var mse in mses) Console.WriteLine("Error: {0}", mse.ToString("0.00000000"));

                Console.WriteLine("Ellapsed: {0} ms", sw.Elapsed.TotalMilliseconds);
            }
        }
        /// <summary>
        /// Creates a MapTile.
        /// </summary>
        /// <returns></returns>
        public static MapTile CreateMapTile(SwordeningGame game,InGame gameState, int x, int z)
        {
            int[,] grid = new[,]
            {
                 {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                 {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0},
                 {0,0,0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,1,1,0},
                 {1,0,0,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0},
                 {0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0},
                 {0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0},
                 {0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0},
                 {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0},
                 {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                 {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                 {0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0},
                 {0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0},
                 {0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0},
                 {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0},
                 {1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                 {0,0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0},
                 {0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0},
                 {0,0,1,1,0,0,0,0,1,1,0,0,0,1,1,1,1,0,0,0},
                 {1,1,0,0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0},
                 {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
            };

            if (RANDOM_TILES)
            {
                var rand = new Random();

                for (int i = 0; i < grid.GetLength(0); i++)
                {
                    for (int j = 0; j < grid.GetLength(1); j++)
                    {
                        if (rand.Next() % 4 == 0)
                            grid[i,j] = 1;
                        else
                            grid[i,j] = 0;
                    }
                }
            }

            MapTile newTile = new MapTile(game,gameState,x,z,grid);

            /*
            int objectAmount = 5 + rand.Next() % 3;
            var takenSpots = new bool[objectAmount, objectAmount];
            int differenceX = MapTile.Width / (objectAmount + 2);
            int differenceY = MapTile.Length / (objectAmount + 2);

            for (int i = 0; i < objectAmount; i++)
            {
                int x = rand.Next() % objectAmount;
                int y = rand.Next() % objectAmount;
                while (!takenSpots[x,y])
                {
                    x = rand.Next() % objectAmount;
                    y = rand.Next() % objectAmount;
                }
                takenSpots[x,y] = true;
                x++;
                y++;
                x *= differenceX;
                y *= differenceY;

                var size = (StationaryObject.Size)(rand.Next() % 3 + 1);

                StationaryObject stationary = new StationaryRockSmall(game);
                stationary.SetPosition(x,y);
                stationary.Theme = theme;
                stationary.Name = StationaryObject.NewStationaryID();

                newTile.AddStationary(stationary);
            }*/

            return newTile;
        }
Exemplo n.º 20
0
        public void SelfContained()
        {
            var data = new[,] { { 0, 0, 1, 1, 1 }, { 0, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1 } };
            var numrows = data.GetLength(0);
            var numcols = data.GetLength(1);
            var indexes = from y in Enumerable.Range(-1, 2 + numrows)
                          from x in Enumerable.Range(-1, 2 + numcols)
                          select new
                                     {
                                         Row = y,
                                         Column = x
                                     };
            const int leftEdge = -1;
            const int bottomEdge = -1;
            var rightEdge = numcols;
            var topEdge = numrows;
            Func<int, int, bool> isEdge = (row, column) => column == leftEdge || row == bottomEdge || column == rightEdge || row == topEdge;
            Func<int, int, bool> hasAdjacentColumn = (row, column) => !isEdge(row, column) && (column > 0 && data[row, column - 1] == 1 || column < numcols && data[row, column + 1] == 1);
            Func<int, int, bool> hasAdjacentRow = (row, column) => !isEdge(row, column) && (row > 0 && data[row - 1, column] == 1 || row < numrows && data[row + 1, column] == 1);
            var potentialCorners = indexes
                .Where(x => isEdge(x.Row, x.Column) || data[x.Row, x.Column] == 0)
                .Select(x => new
                                 {
                                     IsEdge = isEdge(x.Row, x.Column),
                                     HasAdjacentColumn = hasAdjacentColumn(x.Row, x.Column),
                                     HasAdjacentRow = hasAdjacentRow(x.Row, x.Column),
                                     x.Row,
                                     x.Column
                                 })
                .Where(x => x.IsEdge || x.HasAdjacentColumn || x.HasAdjacentRow)
                .ToList();

            var xPairs = potentialCorners
                .Where(x => x.HasAdjacentColumn || x.IsEdge)
                .GroupBy(x => x.Column)
                .Where(x => x.Key > leftEdge && x.Key < rightEdge)
                .SelectMany(g =>
                    {
                        var sorted = g.OrderBy(x => x.Row).ToArray();
                        return sorted.Where(x => x.Row < topEdge)
                                     .Select(x =>
                                         {
                                             var first = sorted.First(y => y.Row > x.Row);
                                             return new
                                                        {
                                                            Column = g.Key,
                                                            BottomEdge = x.Row,
                                                            TopEdge = first.Row,
                                                            HasAdjacentRow = data[x.Row + 1, g.Key] == 1
                                                        };
                                         })
                                     .Where(x => x.HasAdjacentRow)
                                     .Where(x => x.TopEdge - x.BottomEdge > 0);
                    })
                .ToList();

            var yPairs = potentialCorners
                .Where(x => x.HasAdjacentRow || x.IsEdge)
                .GroupBy(x => x.Row)
                .Where(x => x.Key > bottomEdge && x.Key < topEdge)
                .SelectMany(g =>
                    {
                        var sorted = g.OrderBy(x => x.Column).ToArray();
                        return sorted.Where(x => x.Column < rightEdge)
                                     .Select(x =>
                                         {
                                             var first = sorted.First(y => y.Column > x.Column);
                                             return new
                                                        {
                                                            Row = g.Key,
                                                            LeftEdge = x.Column,
                                                            RightEdge = first.Column,
                                                            HasAdjacentColumn = data[g.Key, x.Column + 1] == 1
                                                        };
                                         })
                                     .Where(x => x.HasAdjacentColumn)
                                     .Where(x => x.RightEdge - x.LeftEdge > 0);
                    })
                .ToList();

            var rectangles = xPairs
                .Select(x =>
                    {
                        var yPairsInBounds = yPairs.Where(y => y.Row > x.BottomEdge && y.Row < x.TopEdge).ToList();
                        var before = yPairsInBounds.OrderByDescending(y => y.LeftEdge).First(y => y.LeftEdge < x.Column);
                        var after = yPairsInBounds.OrderBy(y => y.RightEdge).First(y => y.RightEdge > x.Column);
                        return new
                                   {
                                       x.TopEdge,
                                       x.BottomEdge,
                                       before.LeftEdge,
                                       after.RightEdge,
                                   };
                    })
                .Select(x => new
                                 {
                                     TopLeft = new Point(x.LeftEdge, x.TopEdge),
                                     BottomRight = new Point(x.RightEdge, x.BottomEdge)
                                 })
                .ToList();

            foreach (var potentialCorner in potentialCorners.Where(x => !x.IsEdge).OrderBy(x => x.Row).ThenBy(x => x.Column))
            {
                Console.WriteLine(potentialCorner.Row + "," + potentialCorner.Column);
            }

            Func<Point, Point, int> getArea = (tl, br) => (tl.X + 1 - (br.X + 1)) * (br.Y - 1 - (tl.Y + 1));
            foreach (var rectangle in rectangles.OrderByDescending(x => getArea(x.TopLeft, x.BottomRight)))
            {
                Console.WriteLine("(" + rectangle.TopLeft + ") to (" + rectangle.BottomRight + ") -- area " + getArea(rectangle.TopLeft, rectangle.BottomRight));
            }
        }
Exemplo n.º 21
0
        public void MaskPasswordTest()
        {
            var tests = new[,]
            {
                { "Data Source=myOracleDB;User Id=SYS;Password=SYS;DBA Privilege=SYSDBA;", "Data Source=myOracleDB;User Id=SYS;Password=*;DBA Privilege=SYSDBA;" },
                { "password=asd;", "password=*;" },
                { "PASSWORD=asd;", "PASSWORD=*;" },
                { "pwd=asd;", "pwd=*;" },
                { "PWD=asd;", "PWD=*;" },
                { "pwd=", "pwd=*" },
                { "pwd=;", "pwd=*;" },

                { "pwd=asdf asdf asddfas fasd asdf asdfas dfas ", "pwd=*" },
                { "pwd=asdf asdf asddfas fasd asdf asdfas dfas; ", "pwd=*; " },

                { "user = password asdf asdf ; pwd = 123; asdf = pwd; password=pwd;", "user = password asdf asdf ; pwd =*; asdf = pwd; password=*;" },

                { "mypwd=pwd;a=2", "mypwd=pwd;a=2" },

                { "Data Source=username/password@//myserver:1521/my.service.com;", "Data Source=username/*@//myserver:1521/my.service.com;" },
                { "Data Source=username/xx+-*@//myserver:1521/my.service.com;", "Data Source=username/*@//myserver:1521/my.service.com;" },
                { "Data Source=username/@//myserver:1521/my.service.com;", "Data Source=username/*@//myserver:1521/my.service.com;" }
            };

            for (int i = 0; i < tests.GetLength(0); i++)
            {
                Assert.AreEqual(tests[i, 1], SqlUtility.MaskPassword(tests[i, 0]));
                Console.WriteLine("OK: " + tests[i, 1]);
            }
        }
Exemplo n.º 22
0
        static async Task MLPTrainBPOnlineTest(ComputationContext ctx)
        {
            var trainingData =
                 new[,]
                {
                    { -4.0f, 16.0f },
                    { -3.0f, 9.0f },
                    { -2.0f, 4.0f },
                    { -1.0f, 1.0f },
                    { 0.0f, 0.0f },
                    { 1.0f, 1.0f },
                    { 2.0f, 4.0f },
                    { 3.0f, 9.0f },
                    { 4.0f, 16.0f },
                };

            const float maxInput = 4.0f;
            const float minInput = -4.0f;
            const float maxOutput = 16.0f;
            const float minOutput = 0.0f;

            const int inputSize = 1;
            const int hidden1Size = 512;
            const int hidden2Size = 256;
            const int outputSize = 1;

            const int maxIterations = 1000;

            var init = new UniformRandomizeWeights(.3f);

            var algo = new GradientDescentLearningRule
            {
                LearningRate = 0.01f,
                Momentum = 0.25f,
                WeightUpdateMode = WeigthUpdateMode.Online,
                Smoothing = false
            };

            //var algo = new CrossEntropyLearningRule
            //{
            //    NarrowingRate = 0.85f,
            //    MutationChance = 0.001f,
            //    MeanMutationStrength = 0.05f,
            //    StdDevMutationStrength = 1.0f,
            //    PopulationSize = 10
            //};

            //var algo = new AlopexBLearningRule();
            //algo.StepSizeB = 0.001f;
            //algo.StepSizeA = 0.0001f;
            //algo.ForgettingRate = 0.35f;

            var layers = new[]
            {
                new Layer(inputSize),
                new Layer(hidden1Size)
                {
                    Behaviors =
                    {
                        init,
                        algo
                    },
                    Descriptions =
                    {
                        new ActivationDescription(ActivationFunction.Sigmoid)
                    }
                },
                new Layer(hidden2Size)
                {
                    Behaviors =
                    {
                        init,
                        algo
                    },
                    Descriptions =
                    {
                        new ActivationDescription(ActivationFunction.Sigmoid)
                    }
                },
                new Layer(outputSize)
                {
                    Behaviors =
                    {
                        init,
                        algo
                    },
                    Descriptions =
                    {
                        new ActivationDescription(ActivationFunction.Linear)
                    }
                },
            };

            layers[0].OutputConnections.AddOneWay(layers[1]);
            layers[1].OutputConnections.AddOneWay(layers[2]);
            layers[2].OutputConnections.AddOneWay(layers[3]);

            using (var nn = ctx.NeuralNetworkFactory.CreateMultilayerPerceptron(layers, new MultilayerPerceptronProperties { GradientComputationMethod = GradientComputationMethod.FeedForward }))
            using (var batch = new SupervisedBatch())
            using (var errors = ctx.DataArrayFactory.Create(maxIterations))
            {
                for (int i = 0; i < trainingData.GetLength(0); i++)
                {
                    batch.Add(
                        ctx.DataArrayFactory.Create(new[] { Normalize(trainingData[i, 0], minInput, maxInput) }),
                        ctx.DataArrayFactory.Create(new[] { Normalize(trainingData[i, 1], minOutput, maxOutput) }),
                        ctx.DataArrayFactory.Create(1));
                }

                bool first = true;
                var sw = new Stopwatch();
                for (int it = 0; it < maxIterations; it++)
                {
                    nn.Train(batch);

                    ctx.VectorUtils.CalculateMSE(batch, errors, it);

                    if (first)
                    {
                        sw.Start();
                        first = false;
                    }
                }

                float[] mses = new float[maxIterations];
                await errors.Read(mses);

                sw.Stop();

                //foreach (var mse in mses) Console.WriteLine("Error: {0}", mse.ToString("0.00000000"));

                Console.WriteLine("MSE: {0}", mses.Last());

                Console.WriteLine("Ellapsed: {0} ms", sw.Elapsed.TotalMilliseconds);
            }
        }
Exemplo n.º 23
0
        public void ThreeDimensionalArrayTest()
        {
            var items = new [,]
            {
                {1, 2},
                {2, 3},
                {3, 4}
            };
            Assert.AreEqual(6, items.Length);
            Assert.AreEqual(2, items.Rank);

            Assert.AreEqual(3, items.GetLength(0));
            Assert.AreEqual(2, items.GetLength(1));
        }
Exemplo n.º 24
0
        private Winner checkForThreeIdenticalValueInRows()
        {
            var rowIndex = new[,]
            {
                {0, 1, 2},
                {3, 4, 5},
                {6, 7, 8}
            };

            for (int i = 0; i < rowIndex.GetLength(0); i++)
            {
                int firstIndex = rowIndex[i, 0], secondIndex = rowIndex[i, 1], thirdIndex = rowIndex[i, 2];

                var winner = checkWinner(firstIndex, secondIndex, thirdIndex);
                if (winner != noWinner)
                    return winner;
            }

            return noWinner;
        }
Exemplo n.º 25
0
        public void TestUniquePrefix()
        {
            var testSequences = new[,]
            {
                // Original name on left, expected result on right.
                {null, null},
                {"", ""},
                {"A", "A"},
                {"A", "A"}, // duplicate name (on purpose)
                {"AB", "AB"},
                {"ABC", "ABC"},
                {"ABCD", "ABCD"},
                {"ABCDE", "ABCDE"},
                {"ABCDEF", "ABCDEF"},
                {"ABCDEFG", "ABCDEFG"},
                {"ABCDEFG", "ABCDEFG"}, // duplicate name (on purpose)
                {"ABCDEFGH", "ABC…FGH"},
                {"ABCDEFGHI", "ABC…GHI"},

                {"ABCE", "ABCE"},

                {"ABDEFGHI", "ABD…"},

                {"ABEFGHI", "ABEFGHI"},
                {"ABEFGHIJ", "ABE…HIJ"},
                {"ABEFHI", "ABEFHI"},

                {"ABFFFGHI", "ABF(5)"},
                {"ABFFFFGHI", "ABF(6)"},
                {"ABFFFFAFGHI", "ABF…FA…"},
                {"ABFFFAFFGHI", "ABF…A…"},

                {"ABGAABAABAGHI", "ABG…B…B…"},
                {"ABGAAbAABAGHI", "ABG…b…B…"},
                {"ABGAABAAbAGHI", "ABG…B…b…"},
                {"ABGAAB[80]AAB[99]AGHI", "ABG…b…b…"}
            };
            var testCustomIons = new[,]
            {
                // Original name on left, expected result on right.
                {"C32:0", "C32:0"},
                {"C32:1", "C32:1"},
                {"C32:2", "C32:2"},
                {"C32:2", "C32:2"}, // Duplicated on purpose
                {"C30:0", "C30:0"},
                {"C[30]:0", "C[30]:0"},
                {"C[400]:0", "C[4…"},
                {"C12:0 fish breath", "C12…"},
                {"C15:0 fish breath", "C15(14)"},
                {"C15:0 doggy breath", "C15(15)"},
                {"C16:0 fishy breath", "C16…f…"},
                {"C16:0 doggy breath", "C16…d…"},
                {"C14", "C14"},
                {"C14:1", "C14:1"},
                {"C14:1-OH", "C14:1…"},
                {"C14:2", "C14:2"},
                {"C14:2-OH", "C14:2…"}
            };

            for (var loop = 2; loop > 0; loop--)
            {
                var strings = new List<Tuple<string, bool>>();
                var commontext = (loop == 1) ? String.Empty : "Delta Niner Foxtrot "; // non-peptides should strip leading common text

                for (int i = 0; i < testSequences.GetLength(0); i++)
                {
                    strings.Add(new Tuple<string, bool>(testSequences[i, 0], true));
                }
                for (int i = 0; i < testCustomIons.GetLength(0); i++)
                {
                    strings.Add(new Tuple<string, bool>(commontext + testCustomIons[i, 0], false));
                }
                var prefixGenerator = new UniquePrefixGenerator(strings, 3);
                for (int i = 0; i < testSequences.GetLength(0); i++)
                {
                    var expected = testSequences[i, 1];
                    var uniquePrefix = prefixGenerator.GetUniquePrefix(testSequences[i, 0], true);
                    Assert.AreEqual(expected, uniquePrefix);
                }
                for (int i = 0; i < testCustomIons.GetLength(0); i++)
                {
                    var expected = testCustomIons[i, 1];
                    var uniquePrefix = prefixGenerator.GetUniquePrefix(commontext + testCustomIons[i, 0], false);
                    Assert.AreEqual(expected, uniquePrefix);
                }
            }
        }
Exemplo n.º 26
0
 //
 //**********************************************************************************************
 //
 private Int32[,] ConvertToIntArray(System.Array values)
 {
     // create a new array
       Int32[,] theArray = new Int32[values.GetLength(0), values.GetLength(1)];
       for (int i = 1; i <= values.GetLength(0); i++)
       {
     for (int j = 1; j <= values.GetLength(1); j++)
     {
       if (values.GetValue(i, j) == null)
     theArray[i - 1, j - 1] = -1;
       else
     theArray[i - 1, j - 1] = Convert.ToInt32((string)values.GetValue(i, j).ToString());
     }
       }
       return theArray;
 }
		public void SetDesc(System.Array sourceArray)
		{
			this.descriptor.Dimensions = (short)sourceArray.Rank;

			for (int i = 0; i < sourceArray.Rank; i++)
			{
				int lb = this.descriptor.Bounds[i].LowerBound;
				int ub = sourceArray.GetLength(i) - 1 + lb;

				this.descriptor.Bounds[i].UpperBound = ub;
			}
		}
Exemplo n.º 28
0
 //
 //**********************************************************************************************
 //
 private String[,] ConvertToStringArray(System.Array values)
 {
     // create a new array
       String[,] theArray = new String[values.GetLength(0), values.GetLength(1)];
       for (int i = 1; i <= values.GetLength(0); i++)
       {
     for (int j = 1; j <= values.GetLength(1); j++)
     {
       if (values.GetValue(i, j) == null)
     theArray[i - 1, j - 1] = "0.0";
       else
     theArray[i - 1, j - 1] = values.GetValue(i, j).ToString();
     }
       }
       return theArray;
 }
Exemplo n.º 29
0
        public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
        {
            // According to MS documentation, any implementation of the IO.Stream.Read function must:
            // (a) throw an exception if offset & count reference an invalid part of the buffer,
            //     or if count < 0, or if buffer is null
            // (b) return 0 only upon EOF, or if count = 0
            // (c) if not EOF, then return at least 1 byte, up to <count> bytes

            if (_streamMode == StreamMode.Undefined)
            {
                if (!this._stream.CanRead) throw new ZlibException("The stream is not readable.");
                // for the first read, set up some controls.
                _streamMode = StreamMode.Reader;
                // (The first reference to _z goes through the private accessor which
                // may initialize it.)
                z.AvailableBytesIn = 0;
                if (_flavor == ZlibStreamFlavor.GZIP)
                {
                    _gzipHeaderByteCount = _ReadAndValidateGzipHeader();
                    // workitem 8501: handle edge case (decompress empty stream)
                    if (_gzipHeaderByteCount == 0)
                        return 0;
                }
            }

            if (_streamMode != StreamMode.Reader)
                throw new ZlibException("Cannot Read after Writing.");

            if (count == 0) return 0;
            if (nomoreinput && _wantCompress) return 0;  // workitem 8557
            if (buffer == null) throw new ArgumentNullException("buffer");
            if (count < 0) throw new ArgumentOutOfRangeException("count");
            if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset");
            if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count");

            int rc = 0;

            // set up the output of the deflate/inflate codec:
            _z.OutputBuffer = buffer;
            _z.NextOut = offset;
            _z.AvailableBytesOut = count;

            // This is necessary in case _workingBuffer has been resized. (new byte[])
            // (The first reference to _workingBuffer goes through the private accessor which
            // may initialize it.)
            _z.InputBuffer = workingBuffer;

            do
            {
                // need data in _workingBuffer in order to deflate/inflate.  Here, we check if we have any.
                if ((_z.AvailableBytesIn == 0) && (!nomoreinput))
                {
                    // No data available, so try to Read data from the captive stream.
                    _z.NextIn = 0;
                    _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length);
                    if (_z.AvailableBytesIn == 0)
                        nomoreinput = true;

                }
                // we have data in InputBuffer; now compress or decompress as appropriate
                rc = (_wantCompress)
                    ? _z.Deflate(_flushMode)
                    : _z.Inflate(_flushMode);

                if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR))
                    return 0;

                if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
                    throw new ZlibException(String.Format("{0}flating:  rc={1}  msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message));

                if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count))
                    break; // nothing more to read
            }
            //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK);
            while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK);


            // workitem 8557
            // is there more room in output?
            if (_z.AvailableBytesOut > 0)
            {
                if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0)
                {
                    // deferred
                }

                // are we completely done reading?
                if (nomoreinput)
                {
                    // and in compression?
                    if (_wantCompress)
                    {
                        // no more input data available; therefore we flush to
                        // try to complete the read
                        rc = _z.Deflate(FlushType.Finish);

                        if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
                            throw new ZlibException(String.Format("Deflating:  rc={0}  msg={1}", rc, _z.Message));
                    }
                }
            }


            rc = (count - _z.AvailableBytesOut);

            // calculate CRC after reading
            if (crc != null)
                crc.SlurpBlock(buffer, offset, rc);

            return rc;
        }
Exemplo n.º 30
0
        public void Test()
        {
            int iterations = 20;
            INetworkDataProvider metlinkProvider = new MetlinkDataProvider();

            //http://ptv.vic.gov.au/stop/view/StopID

            var testRoutes2 = new[,]
                {
                    { new MetlinkNode(19965, metlinkProvider), new MetlinkNode(19879, metlinkProvider) },
                    { new MetlinkNode(12018, metlinkProvider), new MetlinkNode(18475, metlinkProvider) },
                    { new MetlinkNode(19965, metlinkProvider), new MetlinkNode(19842, metlinkProvider) }
                };

            var testRoutes = new[,]
                {
                    // Long inter-suburban routes
                    {
                        new MetlinkNode(19965, metlinkProvider),
                        new MetlinkNode(19879, metlinkProvider)
                    }, // Coburg - Ringwood
                    {
                        new MetlinkNode(20005, metlinkProvider),
                        new MetlinkNode(19855, metlinkProvider)
                    }, // Epping - Frankston
                    {
                        new MetlinkNode(19990, metlinkProvider),
                        new MetlinkNode(19921, metlinkProvider)
                    }, // Hurstbridge - Werribee
                    {
                        new MetlinkNode(19844, metlinkProvider),
                        new MetlinkNode(20000, metlinkProvider)
                    }, // Belgrave - Watergardens
                    {
                        new MetlinkNode(19886, metlinkProvider),
                        new MetlinkNode(40221, metlinkProvider)
                    }, // Cranbourne - Craigieburn

                    // Lateral inter-suburban routes.
                    {
                        new MetlinkNode(19965, metlinkProvider),
                        new MetlinkNode(19935, metlinkProvider)
                    }, // Coburg - Heidelberg
                    {
                        new MetlinkNode(19965, metlinkProvider),
                        new MetlinkNode(628, metlinkProvider)
                    }, // Coburg - Kew (Wilsmear/Grandview)
                    {
                        new MetlinkNode(19990, metlinkProvider),
                        new MetlinkNode(19246, metlinkProvider)
                    },
                    // East Kew Terminus - Box Hill (r202)
                    {
                        new MetlinkNode(12018, metlinkProvider),
                        new MetlinkNode(18475, metlinkProvider)
                    }, // Yarravile - Highpoint (r223)
                    {
                        new MetlinkNode(4808, metlinkProvider),
                        new MetlinkNode(19649, metlinkProvider)
                    }, // Greensborough - Boxhill

                    // Inner-city routes.
                    {
                        new MetlinkNode(19843, metlinkProvider),
                        new MetlinkNode(22180, metlinkProvider)
                    }, // Parliament - Southern Cross
                    {
                        new MetlinkNode(17882, metlinkProvider),
                        new MetlinkNode(19841, metlinkProvider)
                    },
                    // 9-Spring St/Bourke St  - Flagstaff
                    {
                        new MetlinkNode(19489, metlinkProvider),
                        new MetlinkNode(19973, metlinkProvider)
                    }, // Melbourne Uni - North Melbourne
                    {
                        new MetlinkNode(18034, metlinkProvider),
                        new MetlinkNode(17901, metlinkProvider)
                    },
                    // 2-King St/La Trobe St - Melbourne Town Hall/Collins St
                    {
                        new MetlinkNode(18450, metlinkProvider),
                        new MetlinkNode(19594, metlinkProvider)
                    },
                    // Casino - Royal Childrens Hospital/Flemington Rd

                    // Commuter Routes
                    {
                        new MetlinkNode(19965, metlinkProvider),
                        new MetlinkNode(19842, metlinkProvider)
                    }, // Coburg - Melbourne Central
                    {
                        new MetlinkNode(19876, metlinkProvider),
                        new MetlinkNode(19841, metlinkProvider)
                    }, // Lilydale  - Flagstaff
                    {
                        new MetlinkNode(19489, metlinkProvider),
                        new MetlinkNode(19921, metlinkProvider)
                    }, // Werribee - North Melbourne
                    {
                        new MetlinkNode(20005, metlinkProvider),
                        new MetlinkNode(19843, metlinkProvider)
                    }, // Epping - Parliament
                    {
                        new MetlinkNode(19855, metlinkProvider),
                        new MetlinkNode(19854, metlinkProvider)
                    } // Frankston - Flinders St

                };
            bool first = true;
            DateTime time = DateTime.Parse("8:00 AM 7/05/2012");

            bool cont = true;

            while (cont)
            {
                foreach (SearchType searchType in Enum.GetValues(typeof(SearchType)))
                {
                    if (searchType == SearchType.DFS_BiDir || searchType == SearchType.DFS_Standard)
                        continue;

                    //foreach (bool bidir in new[] { true, false })
                    {
                        for (int i = 0; i < testRoutes.GetLength(0); i++)
                        {

                            //try
                            {
                                testRoutes[i, 0].RetrieveData();
                                testRoutes[i, 1].RetrieveData();

                                EvolutionaryProperties properties = new EvolutionaryProperties();
                                properties.NetworkDataProviders = new [] {metlinkProvider};
               						 properties.PointDataProviders = new [] {new WalkingDataProvider()};
                                properties.ProbMinDistance = 0.7;
                                properties.ProbMinTransfers = 0.2;
                                properties.MaximumWalkDistance = 1.5;
                                properties.PopulationSize = 100;
                                properties.MaxDistance = 0.5;
                                properties.DepartureTime = time;
                                properties.NumberToKeep = 25;
                                properties.MutationRate = 0.1;
                                properties.CrossoverRate = 0.7;
                                //properties.Bidirectional = bidir;
                                //properties.RouteGenerator = new AlRouteGenerator(properties);
                                properties.SearchType = SearchType.Greedy_BiDir;
                                properties.RouteGenerator = new DFSRoutePlanner(properties);
                                properties.Mutator = new StandardMutator(properties);
                                properties.Breeder = new StandardBreeder(properties);
                                properties.FitnessFunction = new AlFitnessFunction(properties);
                                properties.Database = new MySqlDatabase("20110606fordistributionforrmit");
                                properties.Destination = testRoutes[i, 0];
                                properties.Origin = testRoutes[i, 1];
                                properties.Destination.RetrieveData();

                                properties.Database.Open();
                                //properties.DataStructures = new DataStructures(properties);

                                var planner = new EvolutionaryRoutePlanner(properties);
                                Stopwatch sw = Stopwatch.StartNew();
                                planner.Start();

                                StreamWriter writer =
                                    new StreamWriter(
                                        "results/" + searchType + "-" + testRoutes[i, 0].Id + "-"  + testRoutes[i, 1].Id + ".csv",
                                        true);
                                writer.WriteLine(
                                    "[New iteration {0}-{1} ({2}-{3}) {4} @ {5}]",
                                    testRoutes[i, 0].Id,
                                    testRoutes[i, 1].Id,
                                    testRoutes[i, 0].StopSpecName,
                                    testRoutes[i, 1].StopSpecName,
                                    searchType,
                                    DateTime.Now.ToString(CultureInfo.InvariantCulture));

                                Console.WriteLine(
                                    "[New iteration {0}-{1} ({2}-{3}) {4} @ {5}]",
                                    testRoutes[i, 0].Id,
                                    testRoutes[i, 1].Id,
                                    testRoutes[i, 0].StopSpecName,
                                    testRoutes[i, 1].StopSpecName,
                                    searchType,
                                    DateTime.Now.ToString(CultureInfo.InvariantCulture));

                                writer.WriteLine(
                                    "Average UnifiedFitnessScore, Minimum Fitenss, Diversity Metric, Total Time (Iteration), Total Time (Test),Iteration number");

                                this.writeInfo(writer, planner, sw.Elapsed, 0);

                                for (int j = 0; j < 99; j++)
                                {
                                    planner.SolveStep();
                                    this.writeInfo(writer, planner, sw.Elapsed, j + 1);
                                }
                                writer.WriteLine("Path: " + String.Join(",",planner.Result.BestPath));
                                writer.Close();
                                properties.Database.Close();
                            }
                                /*
                            catch (Exception e)
                            {
                                Console.WriteLine("Exception!: {0} ({1}). Writing to error log...", e, e.Message);
                                StreamWriter writer = new StreamWriter("error.log", true);
                                writer.WriteLine(
                                    "[{0}] Exception!: {1} ({2}).\n{3}",
                                    DateTime.Now.ToString(CultureInfo.InvariantCulture),
                                    e,
                                    e.Message,
                                    e.StackTrace);
                                writer.WriteLine(
                                    "[Last error thrown on: {0}-{1} ({2}-{3}) {4} @ {5}]",
                                    testRoutes[i, 0].Id,
                                    testRoutes[i, 1].Id,
                                    testRoutes[i, 0].StopSpecName,
                                    testRoutes[i, 1].StopSpecName,
                                    searchType,
                                    DateTime.Now.ToString(CultureInfo.InvariantCulture));
                                writer.Close();
                                throw;
                            }
                                 * */

                        }
                    }
                }
                var reader = new StreamReader("cont.txt");
                string result = reader.ReadToEnd().Trim();
                switch (result)
                {
                    case "yes":
                        cont = true;
                        break;
                    case "no":
                        cont = false;
                        break;
                    default:
                        Console.WriteLine("Cant read {0}" , ((FileStream)reader.BaseStream).Name);
                        break;
                }
                reader.Close();

            }
        }