public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetByteCount(Char[],Int32,Int32) with null char[]");

        try
        {
            Char[] chars = new Char[] { };

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 0, 0);

            if (byteCount != 0)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method GetByteCount Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
示例#2
0
    static void Main()
    {
        Console.Write("Enter word: ");
        string word = Console.ReadLine();
        char[] letters = new Char[52];

        for (int i = 0; i < 52; i++)
        {
            if (i < 26)
            {
                letters[i] = (char)(i + 65);
            }
            else
            {
                letters[i] = (char)(i + 71);
            }
        }

        for (int i = 0; i < word.Length; i++)
        {
            for (int j = 0; j < letters.Length; j++)
            {
                if (word[i] == letters[j])
                {
                    Console.WriteLine("{0} -> {1}", letters[j], j);
                }
            }
        }
    }
示例#3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //make call to external url and display results
        WebResponse result = null;
        string output = "";

        WebRequest req = WebRequest.Create(ServletCallUrl);
        result = req.GetResponse();
        Stream ReceiveStream = result.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader sr = new StreamReader(ReceiveStream, encode);
        Char[] read = new Char[256];
        int count = sr.Read(read, 0, read.Length);
        while (count > 0)
        {
            String str = new String(read, 0, count);
            output += str;
            count = sr.Read(read, 0, read.Length);
        }

        if (result != null)
        {
            result.Close();
        }

        Response.Write(output);
    }
示例#4
0
 public void SetCompare(Char c)
 {
     if (c == 'Y')
         _CompareDel = CompareToY;
     else
         _CompareDel = CompareToX;
 }
示例#5
0
 public Tile(int x, int y, TYPE type, Char c)
 {
     _x = x;
     _y = y;
     this.type = type;
     SetCompare(c);
 }
示例#6
0
 public static bool VerifyCharTryParse(string value, Char expectedResult, bool expectedReturn)
 {
     Char result;
     if (verbose)
     {
         TestLibrary.Logging.WriteLine("Test: Char.TryParse, Value = '{0}', Expected Result, {1}, Expected Return = {2}",
             value, expectedResult, expectedReturn);
     }
     try
     {
         bool returnValue = Char.TryParse(value, out result);
         if (returnValue != expectedReturn)
         {
             TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedReturn, returnValue);
             return false;
         }
         if (result != expectedResult)
         {
             TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Result: {1}, Actual Result: {2}", value, expectedResult, result);
             return false;
         }
         return true;
     }
     catch (Exception ex)
     {
         TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex);
         return false;
     }
 }
示例#7
0
	private static Int32 WcsToMbsConverter(int codePage, IntPtr inStr, Int32 inLen, IntPtr outBuffer, Int32 outSize)
	{
		Char[] inBuffer = new Char[inLen];
		Marshal.Copy(inStr, inBuffer, 0, inBuffer.Length);
		Encoding encoder;
		if(codePage==936)
		{
            encoder = Encoding.UTF8;
		}
		else
		{
			 encoder = Encoding.GetEncoding(codePage);
		}

		if (outBuffer == IntPtr.Zero)	//query out length
		{
			return encoder.GetByteCount(inBuffer);
		}
		else
		{
			Byte[] outData = encoder.GetBytes(inBuffer);
			if (outData.Length > outSize)		//out buffer too small
				return -1;

			Marshal.Copy(outData, 0, outBuffer, outData.Length);
			return outData.Length;
		}
	}
示例#8
0
    static void Main()
    {
        Console.Write("Enter an unsigned integer number: ");
        uint number = uint.Parse(Console.ReadLine());
        Console.Write("Enter first bit position: ");
        int p = int.Parse(Console.ReadLine());
        Console.Write("Enter second bit position: ");
        int q = int.Parse(Console.ReadLine());
        Console.Write("Enter number of bits to swap: ");
        int k = int.Parse(Console.ReadLine());

        if (Math.Abs(q - p) < k)
        {
            Console.WriteLine("Bits to swap are overlapping! You stupid w***e!");
            return;
        }

        string bitStr = Convert.ToString(number, 2).PadLeft(32, '0');

        char[] newStr = new Char[32];
        newStr = bitStr.ToCharArray();
        for (int i = 0; i < k; i++)
        {
            newStr[31 - p - i] = bitStr[31 - q - i];
            newStr[31 - q - i] = bitStr[31 - p - i];
        }

        string new_bitStr = new String(newStr);
        uint new_num = Convert.ToUInt32(new_bitStr, 2);
        Console.WriteLine("The old number was: {0}", bitStr);
        Console.WriteLine("The new number is:  {0}", new_bitStr);
    }
示例#9
0
 public static string GetMessageFromWeb(string strURL)
 {
     System.Text.StringBuilder sbuBuilder;
     // Creates an HttpWebRequest with the specified URL. 
     HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
     // Sends the HttpWebRequest and waits for the response.            
     HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
     // Gets the stream associated with the response.
     Stream receiveStream = myHttpWebResponse.GetResponseStream();
     Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
     // Pipes the stream to a higher level stream reader with the required encoding format. 
     StreamReader readStream = new StreamReader(receiveStream, encode);
     sbuBuilder = new System.Text.StringBuilder();
     Char[] read = new Char[READ_CHUNK_SIZE];
     // Reads 256 characters at a time.    
     int count = readStream.Read(read, 0, READ_CHUNK_SIZE);
     while (count > 0)
     {
         sbuBuilder.Append(read);
         if (count < READ_CHUNK_SIZE)
         {
             sbuBuilder.Remove(sbuBuilder.Length - (READ_CHUNK_SIZE - count), READ_CHUNK_SIZE - count);
         }
         count = readStream.Read(read, 0, READ_CHUNK_SIZE);
     }
     myHttpWebResponse.Close();
     readStream.Close();
     return sbuBuilder.ToString();
 }
    public static SqlBoolean ArraysFullyIncluded(String AArray, String ASubArray, Char ASeparator)
    {
        //String
        //  LArray      = (AArray.IsNull ? null : AArray.Value),
        //  LSubArray   = (ASubArray.IsNull ? null : ASubArray.Value);

        if (String.IsNullOrEmpty(ASubArray) || ASubArray.Equals(ASeparator))
          return true;

        if (String.IsNullOrEmpty(AArray) || AArray.Equals(ASeparator))
          return false;

        if (AArray.Equals("*"))
          return new SqlBoolean(true);
        if (ASubArray.Equals("*"))
          return new SqlBoolean(false);

        AArray = ASeparator + AArray + ASeparator;
        foreach(String LItem in ASubArray.Split(new char[]{ASeparator}, StringSplitOptions.RemoveEmptyEntries))
        {
          if(AArray.IndexOf(ASeparator + LItem + ASeparator) == -1)
        return false;
        }

        return true;
    }
示例#11
0
 Int32 ShortestDistance(Char[,] map)
 {
     Int32 i, j, sh, shi, shj, n = map.GetLength(0), m = map.GetLength(1);
     Int32[,] dist = new Int32[n, m];
     for (i = 0; i < n; ++i) {
         for (j = 0; j < m; ++j) {
             dist[i, j] = -1;
         }
     }
     dist[0, 0] = 0;
     Queue<Int32> qu = new Queue<Int32>();
     qu.Enqueue(0);
     qu.Enqueue(0);
     while (qu.Count != 0) {
         i = qu.Dequeue();
         j = qu.Dequeue();
         if (map[i, j] == 'x') {
             return dist[i, j];
         }
         for (sh = 0; sh < 4; ++sh) {
             shi = i + shift[sh, 0];
             shj = j + shift[sh, 1];
             if (shi >= 0 && shj >= 0 && shi < n && shj < m && map[shi, shj] != '#' && dist[shi, shj] < 0) {
                 dist[shi, shj] = dist[i, j] + 1;
                 qu.Enqueue(shi);
                 qu.Enqueue(shj);
             }
         }
     }
     return -1;
 }
示例#12
0
        private bool VerifyInvalidReadValue(int iBufferSize, int iIndex, int iCount, Type exceptionType)
        {
            bool bPassed = false;
            Char[] buffer = new Char[iBufferSize];

            ReloadSource();
            DataReader.PositionOnElement(ST_TEST_NAME);
            DataReader.Read();
            if (!DataReader.CanReadValueChunk)
            {
                try
                {
                    DataReader.ReadValueChunk(buffer, 0, 5);
                    return bPassed;
                }
                catch (NotSupportedException)
                {
                    return true;
                }
            }
            try
            {
                DataReader.ReadValueChunk(buffer, iIndex, iCount);
            }
            catch (Exception e)
            {
                CError.WriteLine("Actual   exception:{0}", e.GetType().ToString());
                CError.WriteLine("Expected exception:{0}", exceptionType.ToString());
                bPassed = (e.GetType().ToString() == exceptionType.ToString());
            }

            return bPassed;
        }
 public virtual bool runTest
   ()
   {
   System.Console.Error.WriteLine( "String.EndsWith: Co1150EW runTest starting..." );
   int nErrorBits = 0; 
   System.String swrString2 = null;
   swrString2 = "nOpqRs";
   if ( swrString2.EndsWith( "qRs" ) != true ) 
     nErrorBits = nErrorBits | 0x1;
   if ( swrString2.EndsWith( "qrs" ) != false )
     nErrorBits = nErrorBits | 0x2;
   if ( swrString2.EndsWith( "nOp" ) != false )
     nErrorBits = nErrorBits | 0x4;
   Char[] swrString3 = new Char[8];
   IntlStrings intl = new IntlStrings();
   swrString2 = intl.GetString(10, true, true);
   swrString2.CopyTo(2, swrString3, 0, swrString2.Length - 2);
   String swrString4 = new String(swrString3);
   if(swrString2.EndsWith(swrString4) != true) {
   nErrorBits = nErrorBits | 0x1;
   }
   System.Console.Error.WriteLine( nErrorBits  );
   if (nErrorBits == 0)
     {
     return true; 
     }
   else
     {
     return false; 
     }
   }
 public void PosTest2()
 {
     Char[] chars = new Char[] { };
     UTF8Encoding utf8 = new UTF8Encoding();
     int byteCount = utf8.GetByteCount(chars, 0, 0);
     Assert.Equal(0, byteCount);
 }
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetByteCount(Char[],Int32,Int32) with non-null char[]");

        try
        {
            Char[] chars = new Char[] {
                            '\u0023', 
                            '\u0025', 
                            '\u03a0', 
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 1, 2);

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;

        Char[] chars = new Char[] { } ;
        UnicodeEncoding uEncoding = new UnicodeEncoding();

        int expectedValue = 0;
        int actualValue;

        TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method with a empty char array.");
        try
        {
            actualValue = uEncoding.GetByteCount(chars,0,0);

            if (expectedValue != actualValue)
            {
                TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
            retVal = false;
        }
        return retVal;
    }
示例#17
0
 public override sealed void ReadChar(Char ch)
 {
     switch (state) {
     case State.END:
     case State.ERROR:
         state = State.ERROR;
         break;
     case State.START:
         switch (ch) {
         case 'L':
             state = State.L;
             break;
         case '\"':
             state = State.Q;
             fsachar.Reset();
             break;
         default:
             state = State.ERROR;
             break;
         }
         break;
     case State.L:
         if (ch == '\"') {
             state = State.Q;
             fsachar.Reset();
         } else {
             state = State.ERROR;
         }
         break;
     case State.Q:
         if (fsachar.GetStatus() == FSAStatus.NONE && ch == '\"') {
             state = State.QQ;
             fsachar.Reset();
         } else {
             fsachar.ReadChar(ch);
             switch (fsachar.GetStatus()) {
             case FSAStatus.END:
                 state = State.Q;
                 val = val + fsachar.RetrieveChar();
                 raw = raw + fsachar.RetrieveRaw();
                 fsachar.Reset();
                 ReadChar(ch);
                 break;
             case FSAStatus.ERROR:
                 state = State.ERROR;
                 break;
             default:
                 break;
             }
         }
         break;
     case State.QQ:
         state = State.END;
         break;
     default:
         state = State.ERROR;
         break;
     }
 }
	public bool runTest()
	{
		Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
		int iCountErrors = 0;
		int iCountTestcases = 0;
		String strValue = String.Empty;
		Char[] chArr = new Char[]{
			Char.MinValue
			,Char.MaxValue
			,'\t'
			,' '
			,'$'
			,'@'
			,'#'
			,'\0'
			,'\v'
			,'\''
			,'\u3190'
			,'\uC3A0'
			,'A'
			,'5'
			,'\uFE70' 
			,'-'
			,';'
			,'\u00E6'
			,'\n'
			,'\v'
		};
		try {
			StringBuilder sb = new StringBuilder(40);
			StringWriter sw = new StringWriter(sb);
			StringReader sr;
			for(int i = 0 ; i < chArr.Length ; i++)
				sb.Append(chArr[i]);
			sw.Write(sb.ToString());
			sr = new StringReader(sw.GetStringBuilder().ToString());
			Int32 tmp = 0;
			for(int i = 0 ; i < chArr.Length ; i++) {
				iCountTestcases++;
				if((tmp = sr.Read()) != (Int32)chArr[i]) {
					iCountErrors++;
					printerr( "Error_298vc_"+i+"! Expected=="+(Int32)chArr[i]+", got=="+tmp);
				}
			}
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_298yg! Unexpected exception thrown, exc=="+exc.ToString());
		}
		if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
			return true;
		}
		else
		{
			Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
			return false;
		}
	}
示例#19
0
        /**
         * <summary>Adds holes in the base PolygonCollider2D to account for stationary characters, so they can be evaded during pathfinding calculations (Polygon Collider-based navigation only).
         * This function will only have an effect if moveAroundChars is True.</summary>
         * <param name = "charToExclude">The character to ignore when creating holes. Typically this is the Player character, or any character already moving.</param>
         * <returns>True if changes were made to the base PolygonCollider2D.</returns>
         */
        public bool AddCharHoles(Char charToExclude)
        {
            if (!moveAroundChars)
            {
                return false;
            }

            bool changesMade = false;

            if (GetComponent <PolygonCollider2D>())
            {
                PolygonCollider2D poly = GetComponent <PolygonCollider2D>();
                AC.Char[] characters = GameObject.FindObjectsOfType (typeof (AC.Char)) as AC.Char[];

                foreach (AC.Char character in characters)
                {
                    CircleCollider2D circleCollider2D = character.GetComponent <CircleCollider2D>();
                    if (circleCollider2D != null && character.charState == CharState.Idle
                        && (charToExclude == null || character != charToExclude)
                        && Physics2D.OverlapPointNonAlloc (character.transform.position, NavigationEngine_PolygonCollider.results, 1 << KickStarter.sceneSettings.navMesh.gameObject.layer) != 0)
                    {
                        circleCollider2D.isTrigger = true;

                        List<Vector2> newPoints3D = new List<Vector2>();

                        #if UNITY_5
                        Vector2 centrePoint =  character.transform.TransformPoint (circleCollider2D.offset);
                        #else
                        Vector2 centrePoint =  character.transform.TransformPoint (circleCollider2D.center);
                        #endif

                        float radius = circleCollider2D.radius * character.transform.localScale.x;

                        newPoints3D.Add (centrePoint + Vector2.up * radius);
                        newPoints3D.Add (centrePoint + Vector2.right * radius);
                        newPoints3D.Add (centrePoint - Vector2.up * radius);
                        newPoints3D.Add (centrePoint - Vector2.right * radius);

                        poly.pathCount ++;

                        List<Vector2> newPoints = new List<Vector2>();
                        foreach (Vector3 holePoint in newPoints3D)
                        {
                            newPoints.Add (holePoint - transform.position);
                        }

                        poly.SetPath (poly.pathCount-1, newPoints.ToArray ());
                        changesMade = true;
                    }
                }

                if (changesMade)
                {
                    RebuildVertexArray (poly);
                }
            }

            return changesMade;
        }
 public void PosTest1()
 {
     Char[] chars = new Char[] { };
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int actualValue;
     actualValue = uEncoding.GetByteCount(chars, 0, 0);
     Assert.Equal(0, actualValue);
 }
示例#21
0
    static void Main(string[] args)
    {
        string param1 = "value1";
        string param2 = "value2";

        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = string.Format("param1={0}&param2={1}", param1, param2);
        byte[] buffer = encoding.GetBytes(postData);

        // Prepare web request...
        HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create("http://");

        // We use POST ( we can also use GET )
        myRequest.Method = "POST";

        // Set the content type to a FORM
        myRequest.ContentType = "application/x-www-form-urlencoded";

        // Get length of content
        myRequest.ContentLength = buffer.Length;

        // Get request stream
        Stream newStream = myRequest.GetRequestStream();

         // Send the data.
         newStream.Write(buffer, 0, buffer.Length);

        // Close stream
        newStream.Close();

        // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse();

        // Display the contents of the page to the console.
        Stream streamResponse = myHttpWebResponse.GetResponseStream();
        // Get stream object
        StreamReader streamRead = new StreamReader(streamResponse);
        Char[] readBuffer = new Char[256];

        // Read from buffer
        int count = streamRead.Read(readBuffer, 0, 256);
        while (count > 0)
        {
            // get string
            String resultData = new String(readBuffer, 0, count);
            // Write the data
            Console.WriteLine(resultData);
            // Read from buffer
            count = streamRead.Read(readBuffer, 0, 256);

         }
        // Release the response object resources.
        streamRead.Close();
        streamResponse.Close();
        // Close response
        myHttpWebResponse.Close();
    }
示例#22
0
 static String GetString(Int32 length)
 {
     Int32 i;
     Char[] result = new Char[length];
     for (i = 0; i < length; ++i) {
         result[i] = GetCharacter();
     }
     return new String(result);
 }
    /// <summary>
    /// Chuyển chuỗi tiếng việt có dấu sang không dấu dạng : chuoi-tieng-viet
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static string Encode(string text)
    {
        if (text == null || text == string.Empty)
            return string.Empty;

        // Fields
        String[] pattern = new String[7];
        Char[] replaceChar = new Char[14];

        // Khởi tạo giá trị thay thế
        replaceChar[0] = 'a';
        replaceChar[1] = 'd';
        replaceChar[2] = 'e';
        replaceChar[3] = 'i';
        replaceChar[4] = 'o';
        replaceChar[5] = 'u';
        replaceChar[6] = 'y';
        replaceChar[7] = 'A';
        replaceChar[8] = 'D';
        replaceChar[9] = 'E';
        replaceChar[10] = 'I';
        replaceChar[11] = 'O';
        replaceChar[12] = 'U';
        replaceChar[13] = 'Y';

        //Mẫu cần thay thế tương ứng
        pattern[0] = "(á|à|ả|ã|ạ|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ)"; //letter a
        pattern[1] = "đ";   //letter d
        pattern[2] = "(é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ)"; //letter e
        pattern[3] = "(í|ì|ỉ|ĩ|ị)"; //letter i
        pattern[4] = "(ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ)"; //letter o
        pattern[5] = "(ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự)"; //letter u
        pattern[6] = "(ý|ỳ|ỷ|ỹ|ỵ)"; //letter y

        //Thay the cac ky tu Tieng Viet co dau thanh khong dau
        char[] arr = replaceChar;
        for (int i = 0; i < pattern.Length; i++)
        {
            MatchCollection matchs = Regex.Matches(text, pattern[i], RegexOptions.IgnoreCase);
            foreach (Match m in matchs)
            {
                char ch = Char.IsLower(m.Value[0]) ? arr[i] : arr[i + 7];
                text = text.Replace(m.Value[0], ch);
            }
        }

        //Loại bỏ các ký tự đặc biệt
        text = text.Trim();
        text = text.Replace(" - ", "-");
        text = Regex.Replace(text, @"[^a-zA-Z0-9\-\s]", string.Empty);
        text = Regex.Replace(text, @"\s+", "-");

        //Chuyển tất cả về dạng chữ thường
        text = text.ToLower();

        return text;
    }
示例#24
0
	public bool runTest()
	{
		int iCountErrors = 0;
		int iCountTestcases = 0;
        String strTemp = String.Empty ;
        Char[] cArr = new Char[10] ;
        StringBuilder sb = new StringBuilder(40);
        StringWriter sw = new StringWriter(sb);
        StringReader sr;
        iCountTestcases++;
        bool[] bArr = new bool[]{  true,true,true,true,true,false,false,false,false,false};
		try {
			for(int i = 0 ; i < bArr.Length ; i++)
				sw.WriteLine(bArr[i]);
			sr = new StringReader(sw.GetStringBuilder().ToString());
			for(int i = 0 ; i < bArr.Length ; i++) {
                sr.Read(cArr, 0, bArr[i].ToString().Length+System.Environment.NewLine.Length);
				if(new String(cArr, 0, bArr[i].ToString().Length) != bArr[i].ToString()) {
					iCountErrors++;
					printerr( "Error_298vc_"+i+"! Expected=="+bArr[i].ToString()+", got=="+new String(cArr));
				}
			}
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_298yg! Unexpected exception thrown, exc=="+exc.ToString());
		}
        iCountTestcases++;
        bArr = new bool[10000];
        for(int i = 0 ; i < bArr.Length ; i++)
            bArr[i] = Convert.ToBoolean(rand.Next(0,2));
		try {
            sb.Length = 0;
			for(int i = 0 ; i < bArr.Length ; i++)
				sw.WriteLine(bArr[i]);
			sr = new StringReader(sw.GetStringBuilder().ToString());
			for(int i = 0 ; i < bArr.Length ; i++) {
                sr.Read(cArr, 0, bArr[i].ToString().Length+System.Environment.NewLine.Length);
                if(new String(cArr, 0, bArr[i].ToString().Length) != bArr[i].ToString()) {
					iCountErrors++;
					printerr( "Error_57485_"+i+"! Expected=="+bArr[i].ToString()+", got=="+new String(cArr));
				}
			}
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_43432! Unexpected exception thrown, exc=="+exc.ToString());
		}
        if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs. iCountTestcases=="+iCountTestcases.ToString());
			return true;
		}
		else
		{
			Console.WriteLine("FAiL! iCountErrors=="+iCountErrors.ToString() );
			return false;
		}
	}
 public void PosTest1()
 {
     Char[] chars = new Char[] {
                     '\u0023',
                     '\u0025',
                     '\u03a0',
                     '\u03a3'  };
     UTF8Encoding utf8 = new UTF8Encoding();
     int byteCount = utf8.GetByteCount(chars, 1, 2);
 }
示例#26
0
 public void PosTest2()
 {
     Char[] chars;
     Byte[] bytes = new Byte[] { };
     UTF7Encoding UTF7 = new UTF7Encoding();
     int charCount = UTF7.GetCharCount(bytes, 0, 0);
     chars = new Char[] { };
     int charsDecodedCount = UTF7.GetChars(bytes, 0, 0, chars, 0);
     Assert.Equal(0, charsDecodedCount);
 }
示例#27
0
 public void PosTest2()
 {
     Byte[] bytes;
     Char[] chars = new Char[] { };
     UTF7Encoding UTF7 = new UTF7Encoding();
     int byteCount = UTF7.GetByteCount(chars, 0, 0);
     bytes = new Byte[byteCount];
     int bytesEncodedCount = UTF7.GetBytes(chars, 0, 0, bytes, 0);
     Assert.Equal(0, bytesEncodedCount);
 }
 public void GaryClicked()
 {
     if (active != Char.Gary) {
         active = Char.Gary;
         marker.transform.localPosition = marker_gary;
     } else {
         active = Char.NoActive;
         marker.transform.position = marker_noactive;
     }
 }
 public void RobertClicked()
 {
     if (active != Char.Robert) {
         active = Char.Robert;
         marker.transform.localPosition = marker_robert;
     } else {
         active = Char.NoActive;
         marker.transform.position = marker_noactive;
     }
 }
    private Vector3 marker_noactive; //start pos, off screen

    #endregion Fields

    #region Methods

    public void BobbyClicked()
    {
        if (active != Char.Bobby) {
            active = Char.Bobby;
            marker.transform.localPosition = marker_bobby;
        } else {
            active = Char.NoActive;
            marker.transform.position = marker_noactive;
        }
    }
示例#31
0
        public void lexemAnalyse(string expression)
        {
            string token = "";
            Token  tok;
            term   currentTerm = term.none;

            this.terms = new List <Token>();

            for (int i = 0; i < expression.Length; i++)
            {
                if (Char.IsNumber(expression[i]))  //IsDigit
                {
                    if ((currentTerm == term.negotive) || (currentTerm == term.number))
                    {
                        token      += expression[i];
                        currentTerm = term.number;
                    }
                    else if ((currentTerm != term.none) && (currentTerm != term.whitespace))
                    {
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        token       = expression[i].ToString();
                        currentTerm = term.number;
                    }
                    else
                    {
                        token       = expression[i].ToString();
                        currentTerm = term.number;
                    }
                }
                else if (Char.IsLetter(expression[i]))
                {
                    if (currentTerm == term.number)
                    {
                        //this.terms.Add("*");
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        tok       = new Token();
                        tok.value = "*";
                        tok.type  = term.operation;
                        this.terms.Add(tok);
                        token       = expression[i].ToString();
                        currentTerm = term.letter;
                    }
                    else if ((currentTerm == term.letter) || (currentTerm == term.multiline))
                    {
                        token      += expression[i].ToString();
                        currentTerm = term.multiline;
                    }
                    else if ((currentTerm == term.leftbracket) || (currentTerm == term.operation))
                    {
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        token       = expression[i].ToString();
                        currentTerm = term.letter;
                    }
                    else if (currentTerm == term.rightbracket)
                    {
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        tok       = new Token();
                        tok.value = "*";
                        tok.type  = term.operation;
                        this.terms.Add(tok);
                        token       = expression[i].ToString();
                        currentTerm = term.letter;
                    }
                    else if ((currentTerm == term.none) || (currentTerm == term.whitespace))
                    {
                        token       = expression[i].ToString();
                        currentTerm = term.letter;
                    }
                    else
                    {
                        token += expression[i];
                    }
                }
                else if (Char.IsWhiteSpace(expression[i]))
                {
                    if ((currentTerm != (int)term.none) && (currentTerm != term.whitespace))
                    {
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        token       = "";
                        currentTerm = term.whitespace;
                    }
                }
                else if (Char.IsSymbol(expression[i]) || (expression[i] == '*') || (expression[i] == '/'))
                {
                    if ((currentTerm == term.number) || (currentTerm == term.letter) || (currentTerm == term.rightbracket) || (currentTerm == term.multiline))
                    {
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        token       = expression[i].ToString();
                        currentTerm = term.operation;
                    }
                    else
                    {
                        token       = expression[i].ToString();
                        currentTerm = term.operation;
                    }
                }
                else if (expression[i] == '-')
                {
                    if ((currentTerm == term.number) || (currentTerm == term.letter) || (currentTerm == term.rightbracket))

                    {
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        token       = expression[i].ToString();
                        currentTerm = term.operation;
                    }
                    else if (currentTerm == term.leftbracket)
                    {
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        token       = expression[i].ToString();
                        currentTerm = term.negotive;
                    }
                    else if (currentTerm != (int)term.none)
                    {
                        token       = expression[i].ToString();
                        currentTerm = term.operation;
                    }
                    else
                    {
                        token       = expression[i].ToString();
                        currentTerm = term.negotive;
                    }
                }
                else if (expression[i] == ',')
                {
                    if (currentTerm == term.number)

                    {
                        token += expression[i].ToString();
                    }
                }
                else if (expression[i] == '(')
                {
                    if ((currentTerm == term.number) || (currentTerm == term.letter))


                    {
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        tok       = new Token();
                        tok.value = "*";
                        tok.type  = term.operation;
                        this.terms.Add(tok);
                        token       = expression[i].ToString();
                        currentTerm = term.leftbracket;
                    }
                    else if ((currentTerm == term.operation) || (currentTerm == term.multiline))
                    {
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        token       = expression[i].ToString();
                        currentTerm = term.leftbracket;
                    }
                    else if ((currentTerm == term.none) || (currentTerm == term.whitespace))
                    {
                        token       = expression[i].ToString();
                        currentTerm = term.leftbracket;
                    }
                }
                else if (expression[i] == ')')
                {
                    if ((currentTerm == term.number) || (currentTerm == term.letter) || (currentTerm == term.rightbracket))

                    {
                        tok       = new Token();
                        tok.value = token;
                        tok.type  = currentTerm;
                        this.terms.Add(tok);
                        token       = expression[i].ToString();
                        currentTerm = term.rightbracket;
                    }
                }
                //else
                //    this.terms.Add(token);
            }
            tok       = new Token();
            tok.value = token;
            tok.type  = currentTerm;
            this.terms.Add(tok);
        }
示例#32
0
 Write(Char c)
 {
     this.Write(new String(c, 1));
 }
示例#33
0
 private void txtDienthoai_KeyPress(object sender, KeyPressEventArgs e)
 {
     if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
         e.Handled = true;
 }
示例#34
0
 static bool hn(string name, string rule)
 {
     return(name.StartsWith(rule) && name.Length > rule.Length && Char.IsUpper(name[rule.Length]));
 }
示例#35
0
        //private String converteMapeamento(String entrada)
        //{
        //    String saida = entrada;
        //    if (!String.IsNullOrEmpty(sufixoMapeamento))
        //    {
        //        saida = String.Format("{0}.{1}", sufixoMapeamento, entrada);
        //    }

        //    return saida;
        //}
        protected void converterValor(PropertyInfo pInfo, Type tipoCampo, Object vlObj)
        {
            if (vlObj == DBNull.Value)
            {
                return;
            }

            if (tipoCampo.IsSubclassOf(typeof(AbstractEntidade)))
            {
                Mapear mapear = pInfo.obterAtributo <Mapear>(true);
                if (mapear == null || String.IsNullOrEmpty(mapear.SufixoTabela))
                {
                    return;
                }

                ConstructorInfo constructorInfo = tipoCampo.GetConstructor(Type.EmptyTypes);
                if (constructorInfo == null)
                {
                    throw new Exception(String.Format("Não foi possível instanciar {0}", tipoCampo.FullName));
                }

                AbstractEntidade obj = (AbstractEntidade)constructorInfo.Invoke(null);

                obj.sufixoMapeamento = mapear.SufixoTabela;
                if (vlObj is IDataReader)
                {
                    obj.deReader(vlObj as IDataReader);
                    pInfo.SetValue(obterInstancia(), obj, null);
                    return;
                }
                if (typeof(Hashtable) == vlObj.GetType())
                {
                    obj.deHashtable(vlObj as Hashtable);
                    pInfo.SetValue(obterInstancia(), obj, null);
                    return;
                }
                if (typeof(DataRow) == vlObj.GetType())
                {
                    obj.deTable(vlObj as DataRow);
                    pInfo.SetValue(obterInstancia(), obj, null);
                    return;
                }
                return;
            }

            if (tipoCampo.Name.IndexOf("Nullable") > -1)
            {
                tipoCampo = Nullable.GetUnderlyingType(pInfo.PropertyType);
            }

            if ((tipoCampo == typeof(int)) && (!(vlObj is int)))
            {
                pInfo.SetValue(obterInstancia(), int.Parse(vlObj.ToString()), null);
            }
            else if ((tipoCampo == typeof(Char)) && (!(vlObj is char)))
            {
                pInfo.SetValue(obterInstancia(), Char.Parse(vlObj.ToString()), null);
            }
            else if (tipoCampo.IsEnum)
            {
                if (vlObj is string)
                {
                    pInfo.SetValue(obterInstancia(), Enum.Parse(tipoCampo, vlObj.ToString(), true), null);
                }
                else
                {
                    pInfo.SetValue(obterInstancia(), Enum.ToObject(tipoCampo, vlObj), null);
                }
            }
            else
            {
                pInfo.SetValue(obterInstancia(), vlObj, null);
            }
        }
        /// <summary>
        /// Reports the index number, or character position, of the first occurrence of the specified String object in the current <see cref="StringBuilder" /> object.
        /// The search starts at a specified character position.
        /// </summary>
        /// <param name="sb">The string builder.</param>
        /// <param name="value">The <see cref="string" /> object you want to find.</param>
        /// <param name="startIndex">The starting index number for the search.</param>
        /// <param name="ignoreCase">if set to <c>true</c> the case will be ignored during the comparison.</param>
        /// <returns>The character position of the <paramref name="value" /> parameter if the specified string is found, or -1 if it is not found. If value is empty, the return value is <paramref name="startIndex" />.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">startIndex</exception>
        public static int IndexOf(this StringBuilder sb, string value, int startIndex, bool ignoreCase)
        {
            if (startIndex > sb.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(startIndex));
            }

            if (sb.Length == 0 || value == null)
            {
                return(-1);
            }

            if (value == String.Empty)
            {
                return(startIndex);
            }

            int index;
            var length = value.Length;
            var count  = (sb.Length - length) + 1;

            if (!ignoreCase)
            {
                for (var i = startIndex; i < count; i++)
                {
                    if (sb[i] != value[0])
                    {
                        continue;
                    }

                    index = 1;
                    while ((index < length) && (sb[i + index] == value[index]))
                    {
                        index++;
                    }
                    if (index == length)
                    {
                        return(i);
                    }
                }
            }
            else
            {
                for (var i = startIndex; i < count; i++)
                {
                    if (Char.ToLower(sb[i]) != Char.ToLower(value[0]))
                    {
                        continue;
                    }

                    index = 1;
                    while ((index < length) && (Char.ToLower(sb[i + index]) == Char.ToLower(value[index])))
                    {
                        index++;
                    }
                    if (index == length)
                    {
                        return(i);
                    }
                }
            }
            return(-1);
        }
示例#37
0
文件: parser.cs 项目: ForNeVeR/pnet
        private void ResolveReferences()
        {
            int       gid  = 1;
            Hashtable dict = new Hashtable();

            // number unnamed groups

            foreach (CapturingGroup group in caps)
            {
                if (group.Name == null)
                {
                    dict.Add(gid.ToString(), group);
                    group.Number = gid++;

                    ++num_groups;
                }
            }

            // number named groups

            foreach (CapturingGroup group in caps)
            {
                if (group.Name != null)
                {
                    if (!dict.Contains(group.Name))
                    {
                        dict.Add(group.Name, group);
                        group.Number = gid++;

                        ++num_groups;
                    }
                    else
                    {
                        CapturingGroup prev = (CapturingGroup)dict[group.Name];
                        group.Number = prev.Number;
                    }
                }
            }

            // resolve references

            foreach (Expression expr in refs.Keys)
            {
                string name = (string)refs[expr];
                if (!dict.Contains(name))
                {
                    throw NewParseException("Reference to undefined group " +
                                            (Char.IsDigit(name[0]) ? "number " : "name ") +
                                            name);
                }

                CapturingGroup group = (CapturingGroup)dict[name];
                if (expr is Reference)
                {
                    ((Reference)expr).CapturingGroup = group;
                }
                else if (expr is CaptureAssertion)
                {
                    ((CaptureAssertion)expr).CapturingGroup = group;
                }
                else if (expr is BalancingGroup)
                {
                    ((BalancingGroup)expr).Balance = group;
                }
            }
        }
示例#38
0
    static public int RunTests(Type type, string[] args)
    {
        int    failed = 0, ran = 0;
        int    result, expected, elen;
        int    i, j;
        string name;

        MethodInfo[] methods;
        bool         do_timings = false;
        int          tms = 0;
        DateTime     start, end = DateTime.Now;

        if (args != null && args.Length > 0)
        {
            for (j = 0; j < args.Length; j++)
            {
                if (args [j] == "--time")
                {
                    do_timings = true;
                    string[] new_args = new string [args.Length - 1];
                    for (i = 0; i < j; ++i)
                    {
                        new_args [i] = args [i];
                    }
                    j++;
                    for (; j < args.Length; ++i, ++j)
                    {
                        new_args [i] = args [j];
                    }
                    args = new_args;
                    break;
                }
            }
        }
        methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
        for (i = 0; i < methods.Length; ++i)
        {
            name = methods [i].Name;
            if (!name.StartsWith("test_"))
            {
                continue;
            }
            if (args != null && args.Length > 0)
            {
                bool found = false;
                for (j = 0; j < args.Length; j++)
                {
                    if (name.EndsWith(args [j]))
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    continue;
                }
            }
            for (j = 5; j < name.Length; ++j)
            {
                if (!Char.IsDigit(name [j]))
                {
                    break;
                }
            }
            expected = Int32.Parse(name.Substring(5, j - 5));
            start    = DateTime.Now;
            result   = (int)methods [i].Invoke(null, null);
            if (do_timings)
            {
                end = DateTime.Now;
                long tdiff = end.Ticks - start.Ticks;
                int  mdiff = (int)tdiff / 10000;
                tms += mdiff;
                Console.WriteLine("{0} took {1} ms", name, mdiff);
            }
            ran++;
            if (result != expected)
            {
                failed++;
                Console.WriteLine("{0} failed: got {1}, expected {2}", name, result, expected);
            }
        }

        if (do_timings)
        {
            Console.WriteLine("Total ms: {0}", tms);
        }
        Console.WriteLine("Regression tests: {0} ran, {1} failed in {2}", ran, failed, type);
        //Console.WriteLine ("Regression tests: {0} ran, {1} failed in [{2}]{3}", ran, failed, type.Assembly.GetName().Name, type);
        return(failed);
    }
示例#39
0
        private static void Parse(string key_string)
        {
            bool isBlock  = false;
            bool isVkey   = false;
            bool isRepeat = false;
            bool isShift  = false;
            bool isCtrl   = false;
            bool isAlt    = false;

            StringBuilder repeats      = new StringBuilder();
            StringBuilder group_string = new StringBuilder();

            int key_len = key_string.Length;

            for (int i = 0; i < key_len; i++)
            {
                switch (key_string[i])
                {
                case '{':

                    group_string.Remove(0, group_string.Length);
                    repeats.Remove(0, repeats.Length);
                    int start = i + 1;
                    for (; start < key_len; start++)
                    {
                        if (start > i + 1 && key_string[start] == '}')                                 // allow right parenthesis char "{}}"
                        {
                            break;
                        }

                        if (Char.IsWhiteSpace(key_string[start]))
                        {
                            if (isRepeat)
                            {
                                throw new ArgumentException("SendKeys string {0} is not valid.", key_string);
                            }

                            isRepeat = true;
                            continue;
                        }
                        if (isRepeat)
                        {
                            if (!Char.IsDigit(key_string[start]))
                            {
                                throw new ArgumentException("SendKeys string {0} is not valid.", key_string);
                            }

                            repeats.Append(key_string[start]);
                            continue;
                        }

                        group_string.Append(key_string[start]);
                    }
                    if (start == key_len || start == i + 1)
                    {
                        break;
                        //throw new ArgumentException("SendKeys string {0} is not valid.", key_string);
                    }

                    else if (SendKeys.keywords.Contains(group_string.ToString().ToUpper()))
                    {
                        isVkey = true;
                    }
                    else
                    {
                        //throw new ArgumentException("SendKeys string {0} is not valid.", key_string);
                    }

                    int repeat = 1;
                    if (repeats.Length > 0)
                    {
                        repeat = Int32.Parse(repeats.ToString());
                    }
                    if (isVkey)
                    {
                        AddVKey((int)keywords[group_string.ToString().ToUpper()], repeats.Length == 0 ? 1 : repeat);
                    }
                    else
                    {
                        if (Char.IsUpper(Char.Parse(group_string.ToString())))
                        {
                            if (!isShift)
                            {
                                AddVKey((int)Keys.ShiftKey, true);
                            }
                            AddKey(Char.Parse(group_string.ToString()), 1);
                            if (!isShift)
                            {
                                AddVKey((int)Keys.ShiftKey, false);
                            }
                        }
                        else
                        {
                            AddKey(Char.Parse(group_string.ToString().ToUpper()), repeats.Length == 0 ? 1 : repeat);
                        }
                    }

                    i        = start;
                    isRepeat = isVkey = false;
                    if (isShift)
                    {
                        AddVKey((int)Keys.ShiftKey, false);
                    }
                    if (isCtrl)
                    {
                        AddVKey((int)Keys.ControlKey, false);
                    }
                    if (isAlt)
                    {
                        AddVKey((int)Keys.Menu, false);
                    }
                    isShift = isCtrl = isAlt = false;
                    break;

                case '+': {
                    AddVKey((int)Keys.ShiftKey, true);
                    isShift = true;
                    break;
                }

                case '^': {
                    AddVKey((int)Keys.ControlKey, true);
                    isCtrl = true;
                    break;
                }

                case '%': {
                    AddVKey((int)Keys.Menu, true);
                    isAlt = true;
                    break;
                }

                case '~': {
                    AddVKey((int)Keys.Enter, 1);
                    break;
                }

                case '(':
                    isBlock = true;
                    break;

                case ')': {
                    if (isShift)
                    {
                        AddVKey((int)Keys.ShiftKey, false);
                    }
                    if (isCtrl)
                    {
                        AddVKey((int)Keys.ControlKey, false);
                    }
                    if (isAlt)
                    {
                        AddVKey((int)Keys.Menu, false);
                    }
                    isShift = isCtrl = isAlt = isBlock = false;
                    break;
                }

                default: {
                    if (Char.IsUpper(key_string[i]))
                    {
                        if (!isShift)
                        {
                            AddVKey((int)Keys.ShiftKey, true);
                        }
                        AddKey(key_string[i], 1);
                        if (!isShift)
                        {
                            AddVKey((int)Keys.ShiftKey, false);
                        }
                    }
                    else
                    {
                        AddKey(Char.Parse(key_string[i].ToString().ToUpper()), 1);
                    }

                    if (!isBlock)
                    {
                        if (isShift)
                        {
                            AddVKey((int)Keys.ShiftKey, false);
                        }
                        if (isCtrl)
                        {
                            AddVKey((int)Keys.ControlKey, false);
                        }
                        if (isAlt)
                        {
                            AddVKey((int)Keys.Menu, false);
                        }
                        isShift = isCtrl = isAlt = isBlock = false;
                    }
                    break;
                }
                }
            }

            if (isBlock)
            {
                throw new ArgumentException("SendKeys string {0} is not valid.", key_string);
            }

            if (isShift)
            {
                AddVKey((int)Keys.ShiftKey, false);
            }
            if (isCtrl)
            {
                AddVKey((int)Keys.ControlKey, false);
            }
            if (isAlt)
            {
                AddVKey((int)Keys.Menu, false);
            }
        }
示例#40
0
 public static string FDName(this string normal)
 {
     string n = new string(normal.ToCharArray().Where(c => !Char.IsWhiteSpace(c)).ToArray());
     return n.ToLower();
 }
示例#41
0
        private void RegistrarButton_Click(object sender, EventArgs e)
        {
            if (modificar == false)
            {
                //Registro cliente

                if (camposVacios())
                {
                    MessageBox.Show("Se requiere llenar todos los campos.");
                    fieldList.Clear();
                }
                else
                {
                    Char   tipo = 'V';
                    int    estado = -1;
                    String nombre, huella;
                    if (natural.Checked)
                    {
                        tipo   = 'N';
                        nombre = nombreField.Text;
                    }
                    else
                    {
                        tipo               = 'J';
                        nombre             = razonField.Text;
                        apellidoField.Text = null;
                    }
                    if (activo.Checked)
                    {
                        estado = 1;
                    }
                    else
                    {
                        estado = 0;
                    }
                    if (siRadio.Checked)
                    {
                        //Setear valor a huella
                    }
                    else
                    {
                        //huella = null
                    }
                    //Verificar primero con regex antes de declarar el nuevo objeto cliente. Aquí mando if, invoco función.
                    Cliente client = new Cliente(cedulaRUCField.Text, nombre, apellidoField.Text, telefonoField.Text, direccionField.Text, ciudadField.Text, correoField.Text, "STRING HUELLA5", tipo, estado);
                    int     hecho  = client.agregarCliente(client);
                    if (hecho == 0)
                    {
                        MessageBox.Show("Cliente registrado exitosamente.");
                        inicial.Visible = true;
                        this.Close();
                    }
                    else if (hecho == -1)
                    {
                        MessageBox.Show("El cliente especificado ya se encuentra registrado.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        MessageBox.Show("Se produjo un error al registrar el cliente.");
                    }
                }
            }
            else
            {
                //Guardo cliente modificado


                if (camposVacios())
                {
                    MessageBox.Show("Se requiere llenar todos los campos.");
                }
                else
                {
                    Cliente client = new Cliente(cedulaRUCField.Text, nombreField.Text, apellidoField.Text, telefonoField.Text, direccionField.Text, ciudadField.Text, correoField.Text, "STRING HUELLA5", 'M', 1);
                    if (client.modificarCliente(client) == 0)
                    {
                        MessageBox.Show("Cliente modificado exitosamente.");
                        inicial.Visible = true;
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("Se produjo un error al modificar el cliente.");
                    }
                }
            }
        }
示例#42
0
 private bool IsIdentifierChar(char c)
 {
     return(IsIdentifierStartChar(c) || Char.IsDigit(c));
 }
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            String input = File.ReadAllText(@"TyonTekijaLista.txt");
            int    rivi = 0, sarake = 0;

            string[,] TyoLista = new string[100, 100];
            foreach (var row in input.Split('\n'))
            {
                sarake = 0;
                foreach (var col in row.Trim().Split('.'))
                {
                    TyoLista[rivi, sarake] = col.Trim();
                    sarake++;
                }
                rivi++;
            }
            DateTime AikaNyt = DateTime.Now;
            int      luku    = Convert.ToInt16(TyoLista[0, 2]);

            if (luku < AikaNyt.Month)
            {
                int i;
                for (i = 1; i < TyoLista.GetLength(0); i++)
                {
                    if (TyoLista[i, 2] == null)
                    {
                        i++;
                        break;
                    }
                }
                for (int s = 1; s < i; s++)
                {
                    TyoLista[s, 2] = "0";
                }
                string UusiKuukausi = AikaNyt.Month.ToString();
                TyoLista[0, 2] = UusiKuukausi;
            }

            /*
             * TyoLista[, 0] = Käyttäjänimi
             * TyoLista[, 1] = Salasana
             * TyoLista[, 2] = Työtunnit
             * TyoLista[, 3] = Tuntipalkka(brutto)
             * TyoLista[, 4] = Ikä
             * TyoLista[, 5] = veroprosentti
             * TyoLista[, 6] = Työttömyysvakuutusmaksu
             */

            Console.WriteLine("Tervetuloa tuntilaskuriin!");
            //Käyttäjän valinta
            while (true)
            {
                //kysytään kuka käyttää
                Console.WriteLine("Anna käyttäjänimi");
                string Kayttaja = Console.ReadLine();
                for (int h = 0; h < TyoLista.GetLength(0); h++)
                {
                    int Valinta; //admin sekä työntekijän valikko valinta muuttuja
                    if (Kayttaja == TyoLista[0, 0])
                    {
                        string Salasana = SalasananSuojaus();
                        if (Salasana == TyoLista[0, 1])
                        {
                            Console.WriteLine("Hei " + Kayttaja + "!");
                            while (true)
                            {
                                //Admin valikko
                                Console.WriteLine("Paina 1 Tarkastellaksesi sekä muokataksesi työntekijöiden tietoja");
                                Console.WriteLine("Paina 2 Lisätäksesi työntekijän");
                                Console.WriteLine("Paina 3 Vaihtaaksesi salasanasi");
                                Console.WriteLine("Paina 0 kirjautuaksesi ulos ja tallentaaksesi tiedot");
                                //ottaa stringin adminin valinnasta
                                string valinta = Console.ReadLine();
                                //yrittää muuttaa numeroksi
                                if (int.TryParse(valinta, out Valinta))
                                {
                                    if (Valinta == 1)
                                    {
                                        while (true)
                                        {
                                            int i;
                                            for (i = 1; i < TyoLista.GetLength(0); i++)
                                            {
                                                //Tarkastellaan työntekijöiden tietoja
                                                Console.Clear();
                                                Console.WriteLine("Palkkakauden vaihde: " + DateTime.DaysInMonth(AikaNyt.Year, AikaNyt.Month) + "." + AikaNyt.Month + "." + AikaNyt.Year);
                                                Console.WriteLine("Työntekijät:");
                                                int m;
                                                for (m = 1; m < TyoLista.GetLength(0); m++)
                                                {
                                                    if (TyoLista[m, 0] == null)
                                                    {
                                                        m++;
                                                        break;
                                                    }
                                                }
                                                for (int s = 1; s < m; s++)
                                                {
                                                    Console.WriteLine(TyoLista[s, 0]);
                                                }
                                                Console.WriteLine("Tietoja tarkastellaksesi, syötä valitun henkilön käyttäjätunnus");
                                                Console.WriteLine("Paina 0 poistuaksesi\n");
                                                string TyontekijanTarkastus = Console.ReadLine();
                                                if (TyontekijanTarkastus == TyoLista[i, 0])
                                                {
                                                    var tuntipalkka   = TyoLista[i, 3];
                                                    var veroprosentti = TyoLista[i, 5];
                                                    var tehdytTunnit  = TyoLista[i, 2];
                                                    var ika           = TyoLista[i, 4];
                                                    //var bruttopalkka = TyoLista[i, 6];   ??
                                                    Console.Clear();
                                                    //LASKUT
                                                    double   kauttajaTyoTunnit     = Convert.ToDouble(TyoLista[i, 2]);
                                                    double   kauttajaTuntiPalkka   = Convert.ToDouble(TyoLista[i, 3]);
                                                    double   kauttajaVeroProsentti = (Convert.ToDouble(TyoLista[i, 5]) / 100);
                                                    string   syntymaPaivaString    = TyoLista[i, 4];
                                                    DateTime syntymaPaiva          = Convert.ToDateTime(TyoLista[i, 4]); //YYYY-MM-DD

                                                    DateTime paivaNyt       = DateTime.Now;                              //YYYY-MM-DD
                                                    string   paivaNytString = paivaNyt.ToString("yyyy-MM-dd").Remove(4, 1);
                                                    paivaNytString = paivaNytString.Remove(6, 1);
                                                    int paivaNytInt = Convert.ToInt32(paivaNytString);

                                                    syntymaPaivaString = syntymaPaivaString.Remove(4, 1);
                                                    syntymaPaivaString = syntymaPaivaString.Remove(6, 1);
                                                    int syntymapaivaInt   = Convert.ToInt32(syntymaPaivaString);
                                                    var kauttajaIkaString = Convert.ToString(paivaNytInt - syntymapaivaInt).Remove(2);
                                                    int kauttajaIka       = Convert.ToInt16(kauttajaIkaString);

                                                    double kauttajaTyoElakeProsentti = 0;

                                                    if (kauttajaIka < 53)
                                                    {
                                                        kauttajaTyoElakeProsentti = 0.015;
                                                    }
                                                    else if (kauttajaIka >= 53 && kauttajaIka < 63)
                                                    {
                                                        kauttajaTyoElakeProsentti = 0.017;
                                                    }
                                                    Console.WriteLine("\n---------------------------");
                                                    Console.Write("Nimi: ");
                                                    Console.Write(TyoLista[i, 0]);
                                                    Console.WriteLine();
                                                    Console.Write("Syntymäaika: ");
                                                    Console.Write(TyoLista[i, 4]);
                                                    Console.WriteLine();
                                                    Console.Write("Tuntipalkka: ");
                                                    Console.Write(tuntipalkka + "e");
                                                    Console.WriteLine();
                                                    Console.Write("Veroprosentti: ");
                                                    Console.Write(veroprosentti + "%");
                                                    Console.WriteLine();
                                                    Console.Write("Työeläkekerroin: " + kauttajaTyoElakeProsentti);
                                                    Console.WriteLine();
                                                    Console.Write("Tehdyt tunnit: ");
                                                    Console.WriteLine(tehdytTunnit + "h");
                                                    Console.WriteLine("---------------------------");
                                                    //Console.Write("Bruttopalkka: ");
                                                    //Console.WriteLine(bruttopalkka + "e");
                                                    while (true)
                                                    {
                                                        Console.WriteLine("Paina 1 muokataksesi käyttäjänimeä");
                                                        Console.WriteLine("Paina 2 muokataksesi tehtyjä työtunteja");
                                                        Console.WriteLine("Paina 3 muokataksesi bruttopalkkaa");
                                                        Console.WriteLine("Paina 4 muokataksesi veroprosenttia");
                                                        Console.WriteLine("Paina 5 muokataksesi salasanaa");
                                                        Console.WriteLine("Paina 6 poistaaksesi käyttäjän");
                                                        Console.WriteLine("Paina 0 palataksesi\n");
                                                        string tyonTekijanMuokkaus = Console.ReadLine();
                                                        if (int.TryParse(tyonTekijanMuokkaus, out int TyonTekijanMuokkaus))
                                                        {
                                                            if (TyonTekijanMuokkaus == 1)
                                                            {
                                                                Console.WriteLine("Anna Uusi käyttäjänimi");
                                                                string UusiKayttajaNimi = Console.ReadLine();
                                                                TyoLista[i, 0] = UusiKayttajaNimi;
                                                                Console.Clear();
                                                            }
                                                            else if (TyonTekijanMuokkaus == 2)
                                                            {
                                                                Console.WriteLine("Anna kaikki tehdyt tunnit yhteensä");
                                                                string UusiTehdytTunnit = Console.ReadLine();
                                                                TyoLista[i, 2] = UusiTehdytTunnit;
                                                                Console.Clear();
                                                            }
                                                            else if (TyonTekijanMuokkaus == 3)
                                                            {
                                                                Console.WriteLine("Anna uusi bruttopalkka");
                                                                string UusiBrutto = Console.ReadLine();
                                                                TyoLista[i, 3] = UusiBrutto;
                                                                Console.Clear();
                                                            }
                                                            else if (TyonTekijanMuokkaus == 4)
                                                            {
                                                                Console.WriteLine("Anna uusi veroprosentti");
                                                                string UusiVeroProsentti = Console.ReadLine();
                                                                TyoLista[i, 5] = UusiVeroProsentti;
                                                                Console.Clear();
                                                            }
                                                            else if (TyonTekijanMuokkaus == 5)
                                                            {
                                                                Console.WriteLine("Anna uusi salasana");
                                                                string Uusisalasana = Console.ReadLine();
                                                                TyoLista[i, 1] = Uusisalasana;
                                                                Console.Clear();
                                                            }
                                                            else if (TyonTekijanMuokkaus == 6)
                                                            {
                                                                Console.WriteLine("Oletko varma?\nTätä muutosta ei voi perua tämän jälkeen\nKirjoita \"Kyllä\" poitaaksesi");
                                                                string PoistoValintaKylla = Console.ReadLine();
                                                                if (PoistoValintaKylla == "Kyllä" || PoistoValintaKylla == "kyllä")
                                                                {
                                                                    for (int s = 0; s < 7; s++)
                                                                    {
                                                                        TyoLista[i, s] = null;
                                                                    }
                                                                }
                                                            }
                                                            else if (TyonTekijanMuokkaus == 0)
                                                            {
                                                                Console.Clear();
                                                                break;
                                                            }
                                                            else
                                                            {
                                                                Console.WriteLine("Anna luku väliltä 0-4");
                                                            }
                                                        }
                                                    }
                                                }
                                                else if (TyontekijanTarkastus == "0")
                                                {
                                                    break;
                                                }
                                                else
                                                {
                                                    Console.WriteLine("Käyttäjää ei löydy");
                                                }
                                            }
                                            break;
                                        }
                                    }
                                    else if (Valinta == 2)
                                    {
                                        //Lisätään työntekijä listaan
                                        Console.Write("Syötä uuden työntekijän etunimi: ");
                                        string pieni_etunimi = (Console.ReadLine()).ToLower();
                                        Console.Write("Syötä uuden työntekijän sukunimi: ");
                                        string pieni_sukunimi = (Console.ReadLine()).ToLower();
                                        string etunimi        = Char.ToUpper(pieni_etunimi[0]) + pieni_etunimi.Substring(1);
                                        string sukunimi       = Char.ToUpper(pieni_sukunimi[0]) + pieni_sukunimi.Substring(1);
                                        string kauttajatunnus = sukunimi + etunimi;
                                        Console.WriteLine("Uusi käyttäjänimi: " + kauttajatunnus);
                                        Console.WriteLine("Syötä salasanasi: ");
                                        string KayttajaSalasana = Console.ReadLine();
                                        //Lisää työntekijän syntymäaika
                                        Console.Write("Syötä uuden työntekijän syntymäaika (PP.KK.VVVV): ");
                                        string[] syntymaAika = (Console.ReadLine()).Split('.');
                                        if (syntymaAika[1].Length == 1)
                                        {
                                            syntymaAika[1] = "0" + syntymaAika[1];
                                        }
                                        if (syntymaAika[0].Length == 1)
                                        {
                                            syntymaAika[0] = "0" + syntymaAika[0];
                                        }
                                        Console.Write("Anna uuden työntekijän bruttopalkka tunnilta: ");
                                        string UudenTyöntekijänBrutto = Console.ReadLine();
                                        Console.Write("Anna uuden työntekijän veroprosentti: ");
                                        string UudenyöntekijänVeroProsentti = Console.ReadLine();
                                        int    i;
                                        for (i = 0; i < TyoLista.GetLength(0); i++)
                                        {
                                            if (TyoLista[i, 0] == null)
                                            {
                                                break;
                                            }
                                        }
                                        TyoLista[i, 0] = kauttajatunnus;
                                        TyoLista[i, 1] = KayttajaSalasana;
                                        TyoLista[i, 2] = "0";
                                        TyoLista[i, 3] = UudenTyöntekijänBrutto;
                                        TyoLista[i, 4] = syntymaAika[2] + "-" + syntymaAika[1] + "-" + syntymaAika[0];
                                        TyoLista[i, 5] = UudenyöntekijänVeroProsentti;
                                        Console.Write("Uusi työntekijä on luotu käyttäjänimellä: " + TyoLista[i, 0]);
                                        Console.WriteLine("\nPaina enter jatkaaksesi");
                                        Console.ReadLine();
                                        Console.Clear();
                                    }
                                    else if (Valinta == 3)
                                    {
                                        Salasana = SalasananSuojaus();
                                        if (Salasana == TyoLista[0, 1])
                                        {
                                            string          uusiSalasana;
                                            SalasananVaihto SalasanaTyyppi = new SalasananVaihto();
                                            uusiSalasana = SalasanaTyyppi.SalasanaVaihdetaan();

                                            TyoLista[0, 1] = null;
                                            TyoLista[0, 1] = uusiSalasana;
                                            Salasana       = TyoLista[0, 1];
                                        }
                                        else
                                        {
                                            Console.WriteLine("Väärä salasana.");
                                            Console.WriteLine();
                                        }
                                    }
                                    else if (Valinta == 0)
                                    {
                                        int f;
                                        for (f = 0; f < TyoLista.GetLength(0); f++)
                                        {
                                            if (TyoLista[f, 0] == null)
                                            {
                                                f--;
                                                break;
                                            }
                                        }
                                        int q;
                                        for (q = 0; q < TyoLista.GetLength(1); q++)
                                        {
                                            if (TyoLista[1, q] == null)
                                            {
                                                break;
                                            }
                                        }
                                        int p;
                                        int s = q - 1;
                                        using (var sw = new StreamWriter(@"TyonTekijaLista.txt"))
                                        {
                                            for (p = 0; p < f; p++)
                                            {
                                                for (int k = 0; k < q; k++)
                                                {
                                                    sw.Write(TyoLista[p, k]);
                                                    if (k < s)
                                                    {
                                                        sw.Write(".");
                                                    }
                                                }
                                                sw.Write("\n");
                                            }
                                            sw.Flush();
                                            sw.Close();
                                        }
                                        Salasana = null;
                                        Console.Clear();
                                        break;
                                    }
                                    else
                                    {
                                        Console.WriteLine("Anna luku väliltä 0-2");
                                    }
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("Väärä salasana");
                            Salasana = null;
                        }
                        break;
                    }
                    else if (Kayttaja == TyoLista[h, 0])
                    {
                        string Salasana = SalasananSuojaus();
                        if (Salasana == TyoLista[h, 1])
                        {
                            //LASKUT
                            double   kauttajaTyoTunnit     = Convert.ToDouble(TyoLista[h, 2]);
                            double   kauttajaTuntiPalkka   = Convert.ToDouble(TyoLista[h, 3]);
                            double   kauttajaVeroProsentti = (Convert.ToDouble(TyoLista[h, 5]) / 100);
                            string   syntymaPaivaString    = TyoLista[h, 4];
                            DateTime syntymaPaiva          = Convert.ToDateTime(TyoLista[h, 4]); //YYYY-MM-DD

                            DateTime paivaNyt       = DateTime.Now;                              //YYYY-MM-DD
                            string   paivaNytString = paivaNyt.ToString("yyyy-MM-dd").Remove(4, 1);
                            paivaNytString = paivaNytString.Remove(6, 1);
                            int paivaNytInt = Convert.ToInt32(paivaNytString);

                            syntymaPaivaString = syntymaPaivaString.Remove(4, 1);
                            syntymaPaivaString = syntymaPaivaString.Remove(6, 1);
                            int syntymapaivaInt   = Convert.ToInt32(syntymaPaivaString);
                            var kauttajaIkaString = Convert.ToString(paivaNytInt - syntymapaivaInt).Remove(2);
                            int kauttajaIka       = Convert.ToInt16(kauttajaIkaString);

                            double kauttajaTyoElakeProsentti = 0;

                            if (kauttajaIka < 53)
                            {
                                kauttajaTyoElakeProsentti = 0.015;
                            }
                            else if (kauttajaIka >= 53 && kauttajaIka < 63)
                            {
                                kauttajaTyoElakeProsentti = 0.017;
                            }
                            Console.WriteLine("Hei " + Kayttaja + "!");
                            while (true)
                            {
                                //työntekijän valikko
                                Console.WriteLine("Paina 1 Lisätäksesi tunteja");
                                Console.WriteLine("Paina 2 tarkastellaksesi tietojasi");
                                Console.WriteLine("Paina 3 vaihtaaksesi salasanasi");
                                Console.WriteLine("Paina 0 kirjautuaksesi ulos ja tallentaaksesi tiedot");
                                string valinta = Console.ReadLine();//käyttäjän valinta
                                //Yritetään muuttaa numeroksi
                                if (int.TryParse(valinta, out Valinta))
                                {
                                    if (Valinta == 1)
                                    {
                                        //omien tuntien lisääminen
                                        bool tyotunnitOikein = true;
                                        //Palauttaa luuppiin jos tyotunnitOikein = true
                                        while (tyotunnitOikein == true)
                                        {
                                            Console.WriteLine("Syötä päivän työtuntisi\nSyöttämällä 0, palaat päävalikkoon");
                                            string tyotunnit = Console.ReadLine();
                                            if (tyotunnit == "0")
                                            {
                                                tyotunnitOikein = false;
                                                break;
                                            }
                                            double tyotunnitDouble;

                                            //yrittää muuntaa doubleksi
                                            if (double.TryParse(tyotunnit, out tyotunnitDouble))
                                            {
                                                Console.WriteLine("Vahvista tuntimäärä " + tyotunnit + " kirjoittamalla se uudestaan\nSyöttämällä \"0\", palaat päävalikkoon");
                                                double tyotunnitTarkastus;
                                                //muuntaa syötettävän takistusluvun doubleksi vertailua varten
                                                double.TryParse(Console.ReadLine(), out tyotunnitTarkastus);
                                                if (tyotunnitTarkastus == 0)
                                                {
                                                    tyotunnitOikein = false;
                                                    break;
                                                }
                                                //jos tarkistus on väärin, käyttäjä palaa ylemmän tason while-luuppiin ja kirjaa tunnit uudelleen
                                                if (tyotunnitDouble != tyotunnitTarkastus)
                                                {
                                                    Console.WriteLine("Vahvistus on väärin, syötä työtuntisi uudestaan.");
                                                }
                                                else
                                                {
                                                    //Hakee työlistasta työtunnit, muuttaa ne doubleksi
                                                    double tyotunnitSumma = Convert.ToDouble(TyoLista[h, 2]);
                                                    //Laskee haetut työtunnit ja lisätyt työtunnit summaan
                                                    tyotunnitSumma = tyotunnitDouble + tyotunnitSumma;
                                                    //Muuttaa lasketun summan stringiksi, listaan säilyttämistä varten, Tallentaa listaan.
                                                    TyoLista[h, 2] = Convert.ToString(tyotunnitSumma);
                                                    Console.WriteLine("Työtuntiesi asettaminen onnistui!\nPaina Enter jatkaaksesi");
                                                    Console.ReadKey();
                                                    tyotunnitOikein = false;
                                                }
                                                Console.Clear();
                                            }
                                            else
                                            {
                                                Console.WriteLine("Syötteeksi hyväksytään vain numerot ja pilkut.");
                                            }
                                        }
                                    }
                                    else if (Valinta == 2)
                                    {
                                        //omien tietojen tarkastelu
                                        var tuntipalkka   = TyoLista[h, 3];
                                        var veroprosentti = TyoLista[h, 5];
                                        var tehdytTunnit  = TyoLista[h, 2];
                                        var ika           = TyoLista[h, 4];
                                        //var bruttopalkka = TyoLista[i, 6];   ??
                                        Console.WriteLine("---------------------------");
                                        Console.Write("Käyttäjän nimi: ");
                                        Console.Write(TyoLista[h, 0]);
                                        Console.WriteLine();
                                        Console.Write("Syntymäaikasi: ");
                                        Console.Write(TyoLista[h, 4]);
                                        Console.WriteLine();
                                        Console.Write("Tuntipalkka: ");
                                        Console.Write(tuntipalkka + "e");
                                        Console.WriteLine();
                                        Console.Write("Veroprosentti: ");
                                        Console.Write(veroprosentti + "%");
                                        Console.WriteLine();
                                        Console.Write("Työeläkekerroin: " + kauttajaTyoElakeProsentti);
                                        Console.WriteLine();
                                        Console.Write("Tehdyt tunnit: ");
                                        Console.WriteLine(tehdytTunnit + "h");
                                        Console.WriteLine("Seuraava palkkapäivä: " + DateTime.DaysInMonth(AikaNyt.Year, AikaNyt.Month) + "." + AikaNyt.Month + "." + AikaNyt.Year);
                                        Console.WriteLine("---------------------------");
                                        //Console.Write("Bruttopalkka: ");
                                        //Console.WriteLine(bruttopalkka + "e");
                                    }
                                    else if (Valinta == 3)
                                    {
                                        Console.WriteLine("Syötä nykyinen salasanasi:");
                                        string AnnettuSalasana = Console.ReadLine();

                                        if (Salasana == AnnettuSalasana)
                                        {
                                            string          uusiSalasana;
                                            SalasananVaihto SalasanaTyyppi = new SalasananVaihto();
                                            uusiSalasana = SalasanaTyyppi.SalasanaVaihdetaan();

                                            TyoLista[h, 1] = null;
                                            TyoLista[h, 1] = uusiSalasana;
                                            Salasana       = TyoLista[h, 1];
                                            Console.Clear();
                                        }
                                        else
                                        {
                                            Console.WriteLine("Väärä salasana");
                                        }
                                    }
                                    else if (Valinta == 0)
                                    {
                                        //paluu käyttäjän valintaan
                                        int f;
                                        for (f = 0; f < TyoLista.GetLength(0); f++)
                                        {
                                            if (TyoLista[f, 0] == null)
                                            {
                                                f--;
                                                break;
                                            }
                                        }
                                        int q;
                                        for (q = 0; q < TyoLista.GetLength(1); q++)
                                        {
                                            if (TyoLista[1, q] == null)
                                            {
                                                break;
                                            }
                                        }
                                        int s = q - 1;
                                        using (var sw = new StreamWriter(@"TyonTekijaLista.txt"))
                                        {
                                            for (int p = 0; p < f; p++)
                                            {
                                                for (int k = 0; k < q; k++)
                                                {
                                                    sw.Write(TyoLista[p, k]);
                                                    if (k < s)
                                                    {
                                                        sw.Write(".");
                                                    }
                                                }
                                                sw.Write("\n");
                                            }

                                            sw.Flush();
                                            sw.Close();
                                        }
                                        Salasana = null;
                                        Console.Clear();
                                        break;
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("Anna luku väliltä 0 - 2");
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("Väärä salasana");
                            Salasana = null;
                        }
                        break;
                    }
                }
            }
        }
示例#44
0
        /// <summary>
        /// Convert a Python value to an instance of a primitive managed type.
        /// </summary>
        private static bool ToPrimitive(IntPtr value, Type obType, out object result, bool setError)
        {
            IntPtr   overflow = Exceptions.OverflowError;
            TypeCode tc       = Type.GetTypeCode(obType);

            result = null;
            IntPtr op;
            int    ival;

            switch (tc)
            {
            case TypeCode.String:
                string st = Runtime.GetManagedString(value);
                if (st == null)
                {
                    goto type_error;
                }
                result = st;
                return(true);

            case TypeCode.Int32:
                // Trickery to support 64-bit platforms.
                if (Runtime.IsPython2 && Runtime.Is32Bit)
                {
                    op = Runtime.PyNumber_Int(value);

                    // As of Python 2.3, large ints magically convert :(
                    if (Runtime.PyLong_Check(op))
                    {
                        Runtime.XDecref(op);
                        goto overflow;
                    }

                    if (op == IntPtr.Zero)
                    {
                        if (Exceptions.ExceptionMatches(overflow))
                        {
                            goto overflow;
                        }
                        goto type_error;
                    }
                    ival = (int)Runtime.PyInt_AsLong(op);
                    Runtime.XDecref(op);
                    result = ival;
                    return(true);
                }
                else     // Python3 always use PyLong API
                {
                    op = Runtime.PyNumber_Long(value);
                    if (op == IntPtr.Zero)
                    {
                        Exceptions.Clear();
                        if (Exceptions.ExceptionMatches(overflow))
                        {
                            goto overflow;
                        }
                        goto type_error;
                    }
                    long ll = (long)Runtime.PyLong_AsLongLong(op);
                    Runtime.XDecref(op);
                    if (ll == -1 && Exceptions.ErrorOccurred())
                    {
                        goto overflow;
                    }
                    if (ll > Int32.MaxValue || ll < Int32.MinValue)
                    {
                        goto overflow;
                    }
                    result = (int)ll;
                    return(true);
                }

            case TypeCode.Boolean:
                result = Runtime.PyObject_IsTrue(value) != 0;
                return(true);

            case TypeCode.Byte:
#if PYTHON3
                if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
                {
                    if (Runtime.PyBytes_Size(value) == 1)
                    {
                        op     = Runtime.PyBytes_AS_STRING(value);
                        result = (byte)Marshal.ReadByte(op);
                        return(true);
                    }
                    goto type_error;
                }
#elif PYTHON2
                if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
                {
                    if (Runtime.PyString_Size(value) == 1)
                    {
                        op     = Runtime.PyString_AsString(value);
                        result = (byte)Marshal.ReadByte(op);
                        return(true);
                    }
                    goto type_error;
                }
#endif

                op = Runtime.PyNumber_Int(value);
                if (op == IntPtr.Zero)
                {
                    if (Exceptions.ExceptionMatches(overflow))
                    {
                        goto overflow;
                    }
                    goto type_error;
                }
                ival = (int)Runtime.PyInt_AsLong(op);
                Runtime.XDecref(op);

                if (ival > Byte.MaxValue || ival < Byte.MinValue)
                {
                    goto overflow;
                }
                byte b = (byte)ival;
                result = b;
                return(true);

            case TypeCode.SByte:
#if PYTHON3
                if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
                {
                    if (Runtime.PyBytes_Size(value) == 1)
                    {
                        op     = Runtime.PyBytes_AS_STRING(value);
                        result = (byte)Marshal.ReadByte(op);
                        return(true);
                    }
                    goto type_error;
                }
#elif PYTHON2
                if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
                {
                    if (Runtime.PyString_Size(value) == 1)
                    {
                        op     = Runtime.PyString_AsString(value);
                        result = (sbyte)Marshal.ReadByte(op);
                        return(true);
                    }
                    goto type_error;
                }
#endif

                op = Runtime.PyNumber_Int(value);
                if (op == IntPtr.Zero)
                {
                    if (Exceptions.ExceptionMatches(overflow))
                    {
                        goto overflow;
                    }
                    goto type_error;
                }
                ival = (int)Runtime.PyInt_AsLong(op);
                Runtime.XDecref(op);

                if (ival > SByte.MaxValue || ival < SByte.MinValue)
                {
                    goto overflow;
                }
                sbyte sb = (sbyte)ival;
                result = sb;
                return(true);

            case TypeCode.Char:
#if PYTHON3
                if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
                {
                    if (Runtime.PyBytes_Size(value) == 1)
                    {
                        op     = Runtime.PyBytes_AS_STRING(value);
                        result = (byte)Marshal.ReadByte(op);
                        return(true);
                    }
                    goto type_error;
                }
#elif PYTHON2
                if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
                {
                    if (Runtime.PyString_Size(value) == 1)
                    {
                        op     = Runtime.PyString_AsString(value);
                        result = (char)Marshal.ReadByte(op);
                        return(true);
                    }
                    goto type_error;
                }
#endif
                else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType))
                {
                    if (Runtime.PyUnicode_GetSize(value) == 1)
                    {
                        op = Runtime.PyUnicode_AsUnicode(value);
                        Char[] buff = new Char[1];
                        Marshal.Copy(op, buff, 0, 1);
                        result = buff[0];
                        return(true);
                    }
                    goto type_error;
                }

                op = Runtime.PyNumber_Int(value);
                if (op == IntPtr.Zero)
                {
                    goto type_error;
                }
                ival = Runtime.PyInt_AsLong(op);
                Runtime.XDecref(op);
                if (ival > Char.MaxValue || ival < Char.MinValue)
                {
                    goto overflow;
                }
                result = (char)ival;
                return(true);

            case TypeCode.Int16:
                op = Runtime.PyNumber_Int(value);
                if (op == IntPtr.Zero)
                {
                    if (Exceptions.ExceptionMatches(overflow))
                    {
                        goto overflow;
                    }
                    goto type_error;
                }
                ival = (int)Runtime.PyInt_AsLong(op);
                Runtime.XDecref(op);
                if (ival > Int16.MaxValue || ival < Int16.MinValue)
                {
                    goto overflow;
                }
                short s = (short)ival;
                result = s;
                return(true);

            case TypeCode.Int64:
                op = Runtime.PyNumber_Long(value);
                if (op == IntPtr.Zero)
                {
                    if (Exceptions.ExceptionMatches(overflow))
                    {
                        goto overflow;
                    }
                    goto type_error;
                }
                long l = (long)Runtime.PyLong_AsLongLong(op);
                Runtime.XDecref(op);
                if ((l == -1) && Exceptions.ErrorOccurred())
                {
                    goto overflow;
                }
                result = l;
                return(true);

            case TypeCode.UInt16:
                op = Runtime.PyNumber_Int(value);
                if (op == IntPtr.Zero)
                {
                    if (Exceptions.ExceptionMatches(overflow))
                    {
                        goto overflow;
                    }
                    goto type_error;
                }
                ival = (int)Runtime.PyInt_AsLong(op);
                Runtime.XDecref(op);
                if (ival > UInt16.MaxValue || ival < UInt16.MinValue)
                {
                    goto overflow;
                }
                ushort us = (ushort)ival;
                result = us;
                return(true);

            case TypeCode.UInt32:
                op = Runtime.PyNumber_Long(value);
                if (op == IntPtr.Zero)
                {
                    if (Exceptions.ExceptionMatches(overflow))
                    {
                        goto overflow;
                    }
                    goto type_error;
                }
                uint ui = (uint)Runtime.PyLong_AsUnsignedLong(op);

                if (Exceptions.ErrorOccurred())
                {
                    Runtime.XDecref(op);
                    goto overflow;
                }

                IntPtr check = Runtime.PyLong_FromUnsignedLong(ui);
                int    err   = Runtime.PyObject_Compare(check, op);
                Runtime.XDecref(check);
                Runtime.XDecref(op);
                if (0 != err || Exceptions.ErrorOccurred())
                {
                    goto overflow;
                }

                result = ui;
                return(true);

            case TypeCode.UInt64:
                op = Runtime.PyNumber_Long(value);
                if (op == IntPtr.Zero)
                {
                    if (Exceptions.ExceptionMatches(overflow))
                    {
                        goto overflow;
                    }
                    goto type_error;
                }
                ulong ul = (ulong)Runtime.PyLong_AsUnsignedLongLong(op);
                Runtime.XDecref(op);
                if (Exceptions.ErrorOccurred())
                {
                    goto overflow;
                }
                result = ul;
                return(true);


            case TypeCode.Single:
                op = Runtime.PyNumber_Float(value);
                if (op == IntPtr.Zero)
                {
                    if (Exceptions.ExceptionMatches(overflow))
                    {
                        goto overflow;
                    }
                    goto type_error;
                }
                double dd = Runtime.PyFloat_AsDouble(op);
                Runtime.CheckExceptionOccurred();
                Runtime.XDecref(op);
                if (dd > Single.MaxValue || dd < Single.MinValue)
                {
                    if (!double.IsInfinity(dd))
                    {
                        goto overflow;
                    }
                }
                result = (float)dd;
                return(true);

            case TypeCode.Double:
                op = Runtime.PyNumber_Float(value);
                if (op == IntPtr.Zero)
                {
                    goto type_error;
                }
                double d = Runtime.PyFloat_AsDouble(op);
                Runtime.CheckExceptionOccurred();
                Runtime.XDecref(op);
                result = d;
                return(true);
            }


type_error:

            if (setError)
            {
                string tpName = Runtime.PyObject_GetTypeName(value);
                Exceptions.SetError(Exceptions.TypeError, $"'{tpName}' value cannot be converted to {obType}");
            }

            return(false);

overflow:

            if (setError)
            {
                Exceptions.SetError(Exceptions.OverflowError, "value too large to convert");
            }

            return(false);
        }
示例#45
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            foreach (char slovo in textBox.Text)
            {
                if (!Char.IsLetter(slovo))
                {
                    textBlock10.Visibility = Visibility.Visible;
                    textBlock10.Text       = "Ime nije validno, unesite opet";
                    return;
                }
            }
            foreach (char slovo in textBox1.Text)
            {
                if (!Char.IsLetter(slovo))
                {
                    textBlock10.Visibility = Visibility.Visible;
                    textBlock10.Text       = "Prezime nije validno, unesite opet";
                    return;
                }
            }
            foreach (char broj in textBox2.Text)
            {
                if (!Char.IsDigit(broj))
                {
                    textBlock10.Visibility = Visibility.Visible;
                    textBlock10.Text       = "Broj telefona nije validan, unesite broj u formatu 0038xxxxxxxxx";
                    return;
                }
            }
            if (datumrodj.Date.Year < 1920 || datumrodj.Date.Year > 1997)
            {
                textBlock10.Text = "Niste unijeli dobro datum rođenja."; return;
            }
            if (textBox4.Text.Length != 14)
            {
                textBlock10.Text = "Pogresan format broja licne karte"; return;
            }
            foreach (DezurniRadnik item in KontejnerskaKlasa.dezurniRadnici)
            {
                if (item.Username == textBox5.Text)
                {
                    textBlock10.Text = "Username vec zauzet."; return;
                }
            }
            if (textBox5.Text.Length > 10)
            {
                textBlock10.Text = "Username ne moze biti duzi od 10 znakova"; return;
            }
            if (passwordBox.Password.Length > 16)
            {
                textBlock10.Text = "Password ne moze btii duzi od 16 znakoma"; return;
            }
            foreach (char slovo in textBox3.Text)
            {
                if (!Char.IsLetter(slovo))
                {
                    textBlock10.Visibility = Visibility.Visible;
                    textBlock10.Text       = "Adresa nije validna ukucajte adresu bez broja";
                    return;
                }
            }
            //ako prodju sve validacije
            //dodajemo dez radnika u kontejnersku klasu
            DezurniRadnik radnik = new DezurniRadnik(textBox.Text, textBox1.Text, textBox2.Text,
                                                     textBox3.Text, textBox4.Text, datumrodj.Date.DateTime, textBox5.Text, passwordBox.Password);

            radnik.RFID = textBox7.Text;
            KontejnerskaKlasa.dezurniRadnici.Add(radnik);

            Windows.UI.Xaml.Window window = Windows.UI.Xaml.Window.Current;
            if (window != null)
            {
                Windows.UI.Xaml.Controls.Frame frame = window.Content as Windows.UI.Xaml.Controls.Frame;
                if (frame != null)
                {
                    frame.Navigate((typeof(FormaSupervizor)));
                }
            }
        }
示例#46
0
 public string GetMemberFieldName()
 {
     return("_" + Char.ToLower(Name[0], System.Globalization.CultureInfo.InvariantCulture) + Name.Substring(1));
 }
示例#47
0
        private bool EvalChar(Mode mode, ref int ptr, ref int pc, bool multi)
        {
            bool consumed = false;
            char c        = '\0';
            bool negate;
            bool ignore;

            do
            {
                ushort  word  = program[pc];
                OpCode  op    = (OpCode)(word & 0x00ff);
                OpFlags flags = (OpFlags)(word & 0xff00);

                ++pc;

                ignore = (flags & OpFlags.IgnoreCase) != 0;

                // consume character: the direction of an In construct is
                // determined by the direction of its first op

                if (!consumed)
                {
                    if ((flags & OpFlags.RightToLeft) != 0)
                    {
                        if ((substring_mode && ptr <= (regex_rtl ? text_end : text_start)) || (!substring_mode && ptr <= 0))
                        {
                            return(false);
                        }

                        c = text[--ptr];
                    }
                    else
                    {
                        if ((!regex_rtl && ptr >= text_end) || (regex_rtl && ptr >= text_start))
                        {
                            return(false);
                        }

                        c = text[ptr++];
                    }

                    if (ignore)
                    {
                        c = Char.ToLower(c);
                    }

                    consumed = true;
                }

                // negate flag

                negate = (flags & OpFlags.Negate) != 0;

                // execute op

                switch (op)
                {
                case OpCode.True:
                    return(true);

                case OpCode.False:
                    return(false);

                case OpCode.Character: {
                    if (c == (char)program[pc++])
                    {
                        return(!negate);
                    }
                    break;
                }

                case OpCode.Category: {
                    if (CategoryUtils.IsCategory((Category)program[pc++], c))
                    {
                        return(!negate);
                    }
                    break;
                }

                case OpCode.NotCategory: {
                    if (!CategoryUtils.IsCategory((Category)program[pc++], c))
                    {
                        return(!negate);
                    }
                    break;
                }

                case OpCode.Range: {
                    int lo = (char)program[pc++];
                    int hi = (char)program[pc++];
                    if (lo <= c && c <= hi)
                    {
                        return(!negate);
                    }
                    break;
                }

                case OpCode.Set: {
                    int lo   = (char)program[pc++];
                    int len  = (char)program[pc++];
                    int bits = pc;
                    pc += len;

                    int i = (int)c - lo;
                    if (i < 0 || i >= len << 4)
                    {
                        break;
                    }


                    if ((program[bits + (i >> 4)] & (1 << (i & 0xf))) != 0)
                    {
                        return(!negate);
                    }
                    break;
                }
                }
            } while (multi);

            return(negate);
        }
示例#48
0
        public static object GetIndexedPropertyValue(object container, string expr)
        {
            if (container == null)
                throw new ArgumentNullException("container");
            if ((expr == null) || (expr.Length == 0))
                throw new ArgumentNullException("expr");

            int openIdx = expr.IndexOf('[');
            int closeIdx = expr.IndexOf(']'); // see the test case. MS ignores all after the first ]
            if (openIdx < 0 || closeIdx < 0 || closeIdx - openIdx <= 1)
                throw new ArgumentException(expr + " is not a valid indexed expression.");

            string val = expr.Substring(openIdx + 1, closeIdx - openIdx - 1);
            val = val.Trim();
            if (val.Length == 0)
                throw new ArgumentException(expr + " is not a valid indexed expression.");

            bool is_string = false;
            // a quoted val means we have a string
            if ((val[0] == '\'' && val[val.Length - 1] == '\'') ||
                (val[0] == '\"' && val[val.Length - 1] == '\"'))
            {
                is_string = true;
                val = val.Substring(1, val.Length - 2);
            }
            else
            {
                // if all chars are digits, then we have a int
                for (int i = 0; i < val.Length; i++)
                    if (!Char.IsDigit(val[i]))
                    {
                        is_string = true;
                        break;
                    }
            }

            int intVal = 0;
            if (!is_string)
            {
                try
                {
                    intVal = Int32.Parse(val);
                }
                catch
                {
                    throw new ArgumentException(expr + " is not a valid indexed expression.");
                }
            }

            string property = null;
            if (openIdx > 0)
            {
                property = expr.Substring(0, openIdx);
                if (property != null && property.Length > 0)
                    container = GetPropertyValue(container, property);
            }

            if (container == null)
                return null;

            if (container is System.Collections.IList)
            {
                if (is_string)
                    throw new ArgumentException(expr + " cannot be indexed with a string.");
                IList l = (IList)container;
                return l[intVal];
            }

            Type t = container.GetType();

            // MS does not seem to look for any other than "Item"!!!
            object[] atts = t.AllAttributes<DefaultMemberAttribute>();
            if (atts.Length != 1)
                property = "Item";
            else
                property = ((DefaultMemberAttribute)atts[0]).MemberName;

            Type[] argTypes = new Type[] { (is_string) ? typeof(string) : typeof(int) };
#if !NETSTANDARD2_0
            PropertyInfo prop = t.GetProperty(property, argTypes);
#else
            PropertyInfo prop = t.GetTypeInfo().GetProperty(property, argTypes);
#endif
            if (prop == null)
                throw new ArgumentException(expr + " indexer not found.");

            object[] args = new object[1];
            if (is_string)
                args[0] = val;
            else
                args[0] = intVal;

            return prop.GetValue(container, args);
        }
示例#49
0
        private bool Eval(Mode mode, ref int ref_ptr, int pc)
        {
            int ptr = ref_ptr;

Begin:
            for (;;)
            {
                ushort  word  = program[pc];
                OpCode  op    = (OpCode)(word & 0x00ff);
                OpFlags flags = (OpFlags)(word & 0xff00);

                switch (op)
                {
                case OpCode.Anchor: {
                    int skip = program[pc + 1];

                    int  anch_offset  = program[pc + 2];
                    bool anch_reverse = (flags & OpFlags.RightToLeft) != 0;
                    int  anch_ptr     = anch_reverse ?  ptr - anch_offset  : ptr + anch_offset;
                    int  anch_end     = (regex_rtl ? text_start : text_end) - match_min + anch_offset;                // maximum anchor position


                    int anch_begin = 0;


                    // the general case for an anchoring expression is at the bottom, however we
                    // do some checks for the common cases before to save processing time. the current
                    // optimizer only outputs three types of anchoring expressions: fixed position,
                    // fixed substring, and no anchor.

                    OpCode anch_op = (OpCode)(program[pc + 3] & 0x00ff);
                    if (anch_op == OpCode.Position && skip == 6)                                                // position anchor
                    // Anchor
                    //  Position
                    //	True

                    {
                        switch ((Position)program[pc + 4])
                        {
                        case Position.StartOfString:
                            if (anch_reverse || anch_offset == 0)
                            {
                                if (anch_reverse)
                                {
                                    ptr = anch_offset;
                                }
                                if (TryMatch(ref ptr, pc + skip))
                                {
                                    goto Pass;
                                }
                            }
                            break;

                        case Position.StartOfLine:
                            if (anch_ptr == 0)
                            {
                                ptr = 0;
                                if (TryMatch(ref ptr, pc + skip))
                                {
                                    goto Pass;
                                }

                                ++anch_ptr;
                            }

                            while ((anch_reverse && anch_ptr >= 0) || (!anch_reverse && anch_ptr <= anch_end))
                            {
                                if (anch_ptr == 0 || text[anch_ptr - 1] == '\n')
                                {
                                    if (anch_reverse)
                                    {
                                        ptr = anch_ptr == anch_end ? anch_ptr : anch_ptr + anch_offset;
                                    }
                                    else
                                    {
                                        ptr = anch_ptr == 0 ? anch_ptr : anch_ptr - anch_offset;
                                    }
                                    if (TryMatch(ref ptr, pc + skip))
                                    {
                                        goto Pass;
                                    }
                                }

                                if (anch_reverse)
                                {
                                    --anch_ptr;
                                }
                                else
                                {
                                    ++anch_ptr;
                                }
                            }
                            break;

                        case Position.StartOfScan:
                            if (anch_ptr == scan_ptr)
                            {
                                ptr = anch_reverse ? scan_ptr + anch_offset : scan_ptr - anch_offset;
                                if (TryMatch(ref ptr, pc + skip))
                                {
                                    goto Pass;
                                }
                            }
                            break;

                        default:
                            // FIXME
                            break;
                        }
                    }
                    else if (qs != null ||
                             (anch_op == OpCode.String && skip == 6 + program[pc + 4]))                         // substring anchor
                    // Anchor
                    //	String
                    //	True

                    {
                        bool reverse = ((OpFlags)program[pc + 3] & OpFlags.RightToLeft) != 0;

                        if (qs == null)
                        {
                            bool   ignore    = ((OpFlags)program[pc + 3] & OpFlags.IgnoreCase) != 0;
                            char[] substring = GetChars(pc + 3);
                            qs = new QuickSearch(new string(substring), ignore, reverse);
                        }
                        while ((anch_reverse && anch_ptr >= anch_begin) ||
                               (!anch_reverse && anch_ptr <= anch_end))
                        {
                            if (reverse)
                            {
                                anch_ptr = qs.Search(text, anch_ptr, anch_begin);
                                if (anch_ptr != -1)
                                {
                                    anch_ptr += qs.Length;
                                }
                            }
                            else
                            {
                                anch_ptr = qs.Search(text, anch_ptr, anch_end);
                            }
                            if (anch_ptr < 0)
                            {
                                break;
                            }

                            ptr = reverse ? anch_ptr + anch_offset : anch_ptr - anch_offset;
                            if (TryMatch(ref ptr, pc + skip))
                            {
                                goto Pass;
                            }

                            if (reverse)
                            {
                                anch_ptr -= 2;
                            }
                            else
                            {
                                ++anch_ptr;
                            }
                        }
                    }
                    else if (anch_op == OpCode.True)                                                            // no anchor
                    // Anchor
                    //	True


                    {
                        while ((anch_reverse && anch_ptr >= anch_begin) ||
                               (!anch_reverse && anch_ptr <= anch_end))
                        {
                            ptr = anch_ptr;
                            if (TryMatch(ref ptr, pc + skip))
                            {
                                goto Pass;
                            }
                            if (anch_reverse)
                            {
                                --anch_ptr;
                            }
                            else
                            {
                                ++anch_ptr;
                            }
                        }
                    }
                    else                                                                                        // general case
                    // Anchor
                    //	<expr>
                    //	True

                    {
                        while ((anch_reverse && anch_ptr >= anch_begin) ||
                               (!anch_reverse && anch_ptr <= anch_end))
                        {
                            ptr = anch_ptr;
                            if (Eval(Mode.Match, ref ptr, pc + 3))
                            {
                                // anchor expression passed: try real expression at the correct offset

                                ptr = anch_reverse ? anch_ptr + anch_offset : anch_ptr - anch_offset;
                                if (TryMatch(ref ptr, pc + skip))
                                {
                                    goto Pass;
                                }
                            }

                            if (anch_reverse)
                            {
                                --anch_ptr;
                            }
                            else
                            {
                                ++anch_ptr;
                            }
                        }
                    }

                    goto Fail;
                }

                case OpCode.False: {
                    goto Fail;
                }

                case OpCode.True: {
                    goto Pass;
                }

                case OpCode.Position: {
                    if (!IsPosition((Position)program[pc + 1], ptr))
                    {
                        goto Fail;
                    }
                    pc += 2;
                    break;
                }

                case OpCode.String: {
                    bool reverse = (flags & OpFlags.RightToLeft) != 0;
                    bool ignore  = (flags & OpFlags.IgnoreCase) != 0;
                    int  len     = program[pc + 1];

                    if (reverse)
                    {
                        ptr -= len;
                        if ((!regex_rtl && ptr < 0) || (regex_rtl && ptr < text_end))
                        {
                            goto Fail;
                        }
                    }
                    else
                    if (ptr + len > text_end)
                    {
                        goto Fail;
                    }

                    pc += 2;
                    for (int i = 0; i < len; ++i)
                    {
                        char c = text[ptr + i];
                        if (ignore)
                        {
                            c = Char.ToLower(c);
                        }

                        if (c != (char)program[pc++])
                        {
                            goto Fail;
                        }
                    }

                    if (!reverse)
                    {
                        ptr += len;
                    }
                    break;
                }

                case OpCode.Reference: {
                    bool reverse = (flags & OpFlags.RightToLeft) != 0;
                    bool ignore  = (flags & OpFlags.IgnoreCase) != 0;
                    int  m       = GetLastDefined(program [pc + 1]);
                    if (m < 0)
                    {
                        goto Fail;
                    }

                    int str = marks [m].Index;
                    int len = marks [m].Length;

                    if (reverse)
                    {
                        ptr -= len;
                        if ((!regex_rtl && ptr < 0) || (regex_rtl && ptr < text_end))
                        {
                            goto Fail;
                        }
                    }
                    else if (ptr + len > text_end)
                    {
                        goto Fail;
                    }

                    pc += 2;
                    if (ignore)
                    {
                        for (int i = 0; i < len; ++i)
                        {
                            if (Char.ToLower(text[ptr + i]) != Char.ToLower(text[str + i]))
                            {
                                goto Fail;
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < len; ++i)
                        {
                            if (text[ptr + i] != text[str + i])
                            {
                                goto Fail;
                            }
                        }
                    }

                    if (!reverse)
                    {
                        ptr += len;
                    }
                    break;
                }

                case OpCode.Character:
                case OpCode.Category:
                case OpCode.NotCategory:
                case OpCode.Range:
                case OpCode.Set: {
                    if (!EvalChar(mode, ref ptr, ref pc, false))
                    {
                        goto Fail;
                    }
                    break;
                }

                case OpCode.In: {
                    int target = pc + program[pc + 1];
                    pc += 2;
                    if (!EvalChar(mode, ref ptr, ref pc, true))
                    {
                        goto Fail;
                    }

                    pc = target;
                    break;
                }

                case OpCode.Open: {
                    Open(program[pc + 1], ptr);
                    pc += 2;
                    break;
                }

                case OpCode.Close: {
                    Close(program[pc + 1], ptr);
                    pc += 2;
                    break;
                }

                case OpCode.BalanceStart: {
                    int start = ptr;                     //point before the balancing group

                    if (!Eval(Mode.Match, ref ptr, pc + 5))
                    {
                        goto Fail;
                    }



                    if (!Balance(program[pc + 1], program[pc + 2], (program[pc + 3] == 1 ? true : false), start))
                    {
                        goto Fail;
                    }


                    pc += program[pc + 4];
                    break;
                }

                case OpCode.Balance: {
                    goto Pass;
                }

                case OpCode.IfDefined: {
                    int m = GetLastDefined(program [pc + 2]);
                    if (m < 0)
                    {
                        pc += program[pc + 1];
                    }
                    else
                    {
                        pc += 3;
                    }
                    break;
                }

                case OpCode.Sub: {
                    if (!Eval(Mode.Match, ref ptr, pc + 2))
                    {
                        goto Fail;
                    }

                    pc += program[pc + 1];
                    break;
                }

                case OpCode.Test: {
                    int cp       = Checkpoint();
                    int test_ptr = ptr;
                    if (Eval(Mode.Match, ref test_ptr, pc + 3))
                    {
                        pc += program[pc + 1];
                    }
                    else
                    {
                        Backtrack(cp);
                        pc += program[pc + 2];
                    }
                    break;
                }

                case OpCode.Branch: {
                    OpCode branch_op;
                    do
                    {
                        int cp = Checkpoint();
                        if (Eval(Mode.Match, ref ptr, pc + 2))
                        {
                            goto Pass;
                        }

                        Backtrack(cp);

                        pc       += program[pc + 1];
                        branch_op = (OpCode)(program[pc] & 0xff);
                    } while (branch_op != OpCode.False);

                    goto Fail;
                }

                case OpCode.Jump: {
                    pc += program[pc + 1];
                    break;
                }

                case OpCode.Repeat: {
                    this.repeat = new RepeatContext(
                        this.repeat,                                            // previous context
                        ReadProgramCount(pc + 2),                               // minimum
                        ReadProgramCount(pc + 4),                               // maximum
                        (flags & OpFlags.Lazy) != 0,                            // lazy
                        pc + 6                                                  // subexpression
                        );

                    if (Eval(Mode.Match, ref ptr, pc + program[pc + 1]))
                    {
                        goto Pass;
                    }
                    else
                    {
                        this.repeat = this.repeat.Previous;
                        goto Fail;
                    }
                }

                case OpCode.Until: {
                    RepeatContext current = this.repeat;

                    //
                    // Can we avoid recursion?
                    //
                    // Backtracking can be forced in nested quantifiers from the tail of this quantifier.
                    // Thus, we cannot, in general, use a simple loop on repeat.Expression to handle
                    // quantifiers.
                    //
                    // If 'deep' was unmolested, that implies that there was no nested quantifiers.
                    // Thus, we can safely avoid recursion.
                    //
                    if (deep == current)
                    {
                        goto Pass;
                    }

                    int start       = current.Start;
                    int start_count = current.Count;

                    while (!current.IsMinimum)
                    {
                        ++current.Count;
                        current.Start = ptr;
                        deep          = current;
                        if (!Eval(Mode.Match, ref ptr, current.Expression))
                        {
                            current.Start = start;
                            current.Count = start_count;
                            goto Fail;
                        }
                        if (deep != current)                            // recursive mode
                        {
                            goto Pass;
                        }
                    }

                    if (ptr == current.Start)
                    {
                        // degenerate match ... match tail or fail
                        this.repeat = current.Previous;
                        deep        = null;
                        if (Eval(Mode.Match, ref ptr, pc + 1))
                        {
                            goto Pass;
                        }

                        this.repeat = current;
                        goto Fail;
                    }

                    if (current.IsLazy)
                    {
                        for (;;)
                        {
                            // match tail first ...
                            this.repeat = current.Previous;
                            deep        = null;
                            int cp = Checkpoint();
                            if (Eval(Mode.Match, ref ptr, pc + 1))
                            {
                                goto Pass;
                            }

                            Backtrack(cp);

                            // ... then match more
                            this.repeat = current;
                            if (current.IsMaximum)
                            {
                                goto Fail;
                            }
                            ++current.Count;
                            current.Start = ptr;
                            deep          = current;
                            if (!Eval(Mode.Match, ref ptr, current.Expression))
                            {
                                current.Start = start;
                                current.Count = start_count;
                                goto Fail;
                            }
                            if (deep != current)                                // recursive mode
                            {
                                goto Pass;
                            }
                            // Degenerate match: ptr has not moved since the last (failed) tail match.
                            // So, next and subsequent tail matches will fail.
                            if (ptr == current.Start)
                            {
                                goto Fail;
                            }
                        }
                    }
                    else
                    {
                        int stack_size = stack.Count;

                        // match greedily as much as possible
                        while (!current.IsMaximum)
                        {
                            int cp        = Checkpoint();
                            int old_ptr   = ptr;
                            int old_start = current.Start;

                            ++current.Count;
                            current.Start = ptr;
                            deep          = current;
                            if (!Eval(Mode.Match, ref ptr, current.Expression))
                            {
                                --current.Count;
                                current.Start = old_start;
                                Backtrack(cp);
                                break;
                            }
                            if (deep != current)
                            {
                                // recursive mode: no more backtracking, truncate the stack
                                stack.Count = stack_size;
                                goto Pass;
                            }
                            stack.Push(cp);
                            stack.Push(old_ptr);

                            // Degenerate match: no point going on
                            if (ptr == current.Start)
                            {
                                break;
                            }
                        }

                        // then, match the tail, backtracking as necessary.
                        this.repeat = current.Previous;
                        for (;;)
                        {
                            deep = null;
                            if (Eval(Mode.Match, ref ptr, pc + 1))
                            {
                                stack.Count = stack_size;
                                goto Pass;
                            }
                            if (stack.Count == stack_size)
                            {
                                this.repeat = current;
                                goto Fail;
                            }

                            --current.Count;
                            ptr = stack.Pop();
                            Backtrack(stack.Pop());
                        }
                    }
                }

                case OpCode.FastRepeat: {
                    this.fast = new RepeatContext(
                        fast,
                        ReadProgramCount(pc + 2),                               // minimum
                        ReadProgramCount(pc + 4),                               // maximum
                        (flags & OpFlags.Lazy) != 0,                            // lazy
                        pc + 6                                                  // subexpression
                        );

                    fast.Start = ptr;

                    int cp = Checkpoint();

                    pc += program[pc + 1];                              // tail expression
                    ushort tail_word = program[pc];

                    int c1   = -1;                              // first character of tail operator
                    int c2   = -1;                              // ... and the same character, in upper case if ignoring case
                    int coff = 0;                               // 0 or -1 depending on direction

                    OpCode tail_op = (OpCode)(tail_word & 0xff);
                    if (tail_op == OpCode.Character || tail_op == OpCode.String)
                    {
                        OpFlags tail_flags = (OpFlags)(tail_word & 0xff00);

                        if ((tail_flags & OpFlags.Negate) != 0)
                        {
                            goto skip;
                        }

                        if (tail_op == OpCode.String)
                        {
                            int offset = 0;

                            if ((tail_flags & OpFlags.RightToLeft) != 0)
                            {
                                offset = program[pc + 1] - 1;
                            }

                            c1 = program[pc + 2 + offset];                                                      // first char of string
                        }
                        else
                        {
                            c1 = program[pc + 1];                                                       // character
                        }
                        if ((tail_flags & OpFlags.IgnoreCase) != 0)
                        {
                            c2 = Char.ToUpper((char)c1);                                                // ignore case
                        }
                        else
                        {
                            c2 = c1;
                        }

                        if ((tail_flags & OpFlags.RightToLeft) != 0)
                        {
                            coff = -1;                                                                  // reverse
                        }
                        else
                        {
                            coff = 0;
                        }
                    }

skip:
                    if (fast.IsLazy)
                    {
                        if (!fast.IsMinimum && !Eval(Mode.Count, ref ptr, fast.Expression))
                        {
                            //Console.WriteLine ("lazy fast: failed mininum.");
                            fast = fast.Previous;
                            goto Fail;
                        }

                        while (true)
                        {
                            int p = ptr + coff;
                            if (c1 < 0 || (p >= 0 && ((regex_rtl && p >= text_end) || (!regex_rtl && p < text_end)) && (c1 == text[p] || c2 == text[p])))
                            {
                                deep = null;
                                if (Eval(Mode.Match, ref ptr, pc))
                                {
                                    break;
                                }
                            }

                            if (fast.IsMaximum)
                            {
                                //Console.WriteLine ("lazy fast: failed with maximum.");
                                fast = fast.Previous;
                                goto Fail;
                            }

                            Backtrack(cp);
                            if (!Eval(Mode.Count, ref ptr, fast.Expression))
                            {
                                //Console.WriteLine ("lazy fast: no more.");
                                fast = fast.Previous;
                                goto Fail;
                            }
                        }
                        fast = fast.Previous;
                        goto Pass;
                    }
                    else
                    {
                        if (!Eval(Mode.Count, ref ptr, fast.Expression))
                        {
                            fast = fast.Previous;
                            goto Fail;
                        }

                        int width;
                        if (fast.Count > 0)
                        {
                            width = (ptr - fast.Start) / fast.Count;
                        }
                        else
                        {
                            width = 0;
                        }

                        while (true)
                        {
                            int p = ptr + coff;
                            if (c1 < 0 || (p >= 0 && ((regex_rtl && p >= text_end) || (!regex_rtl && p < text_end)) && (c1 == text[p] || c2 == text[p])))
                            {
                                deep = null;
                                if (Eval(Mode.Match, ref ptr, pc))
                                {
                                    break;
                                }
                            }

                            --fast.Count;
                            if (!fast.IsMinimum)
                            {
                                fast = fast.Previous;
                                goto Fail;
                            }

                            ptr -= width;
                            Backtrack(cp);
                        }
                        fast = fast.Previous;
                        goto Pass;
                    }
                }

                case OpCode.Info: {
                    Debug.Assert(false, "Regex", "Info block found in pattern");
                    goto Fail;
                }
                }
            }
Pass:
            ref_ptr = ptr;

            switch (mode)
            {
            case Mode.Match:
                return(true);

            case Mode.Count: {
                ++fast.Count;
                if (fast.IsMaximum || (fast.IsLazy && fast.IsMinimum))
                {
                    return(true);
                }

                pc = fast.Expression;
                goto Begin;
            }
            }

Fail:
            switch (mode)
            {
            case Mode.Match:
                return(false);

            case Mode.Count: {
                if (!fast.IsLazy && fast.IsMinimum)
                {
                    return(true);
                }

                ref_ptr = fast.Start;
                return(false);
            }
            }

            return(false);
        }
示例#50
0
 private void Obs_KeyPress(object sender, KeyPressEventArgs e)
 {
     e.KeyChar = Char.ToUpper(e.KeyChar);
 }
示例#51
0
        static void Main(string[] args)
        {
            // Преметивные типы в C#
            SByte   bte  = 8;
            Int32   i32  = 5;
            Int64   i64  = 5;
            Int16   i16  = 5;
            Byte    ubt  = 192;
            UInt16  ui16 = 16;
            UInt32  ui32 = 1651513;
            UInt64  ui64 = 1657856875;
            Char    ch   = 'a';
            Boolean bol  = true;
            Single  sng  = 12.4f;
            Double  db   = 12.55;
            Decimal dcm  = 111.1m;
            String  str  = "gaga";
            Object  obj  = new Object();


            // Явное присваивание
            i32 = 5;
            bte = (SByte)ubt;
            Int32 ii32 = (Int32)i64;
            Byte  btta = (Byte)ch;
            Char  ch1  = (Char)ui16;

            // Не явное присваивание
            dcm = ui16;
            i32 = i16;
            i64 = i32;
            Single s  = i32;
            Single s2 = ch;
            Double B  = ubt;

            // Упаковка и распаковка значимых типов
            Object l   = i16;
            UInt32 z   = (UInt32)(Int16)l;
            Object lol = ubt;
            Char   c1  = (Char)(Byte)lol;

            // Неявное типизированная переменая
            var aa  = new[] { 2, 3, 4, 5 };
            var aa1 = 1;
            var aa2 = new List <int>(new int[] { 1, 2, 4 });

            Console.WriteLine(aa.GetType());
            Console.WriteLine(aa1.GetType());
            Console.WriteLine(aa2.GetType());

            // Nullabe
            int?n1 = null;
            int?n2 = 2;
            // если левый операнд не нуль, то он его выводит
            int y = n1 ?? 1;
            int x = n2 ?? 3;

            Console.WriteLine(y + "\t" + x);

            Nullable <Int64> z1 = 50000;

            if (z1.HasValue) // проверет если данный операнд индифецирован то выводит значение
            {
                Console.WriteLine(z1.Value);
            }

            string st  = "hello";
            string st2 = "hello";
            string st3 = "Bob";
            int    stn = String.Compare(st, st2);
            int    cmp = st.CompareTo(st2); // второй способ


            // сравнить строки
            if (stn == 0 || cmp == 0)
            {
                Console.WriteLine("Строки равны");
            }
            else
            {
                Console.WriteLine("Строки не равны");
            }

            /* выполнить сцепление(конкатенацию), копирование, выделение подстроки, разделение строки на слова,
             * вставка подстроки в заданную позицию, удаление заданной подстроки
             */
            Console.WriteLine();
            Console.WriteLine(st + st2 + st3);

            st = String.Copy(st3);
            Console.WriteLine(st);

            st = "privet mir. hah aaaa . agasdg";
            Console.WriteLine(st.Substring(6, 5));

            Console.WriteLine(String.Join(" ", st.Split('.')));

            char[] delims = ".:".ToCharArray();
            string stdel  = "privet.mir:hah:aaaa.agasdg";

            string[] words = stdel.Split(delims);
            foreach (string name in words)
            {
                Console.WriteLine(name);
            }

            Console.WriteLine(st.Insert(6, " LIKE A BOSS"));

            Console.WriteLine(st.Remove(6, 4));

            // создайте пустую строку и null строку и что нибудь выполнить
            String empty  = "";
            String nullst = null;

            empty = empty.Insert(0, "BOB");
            Console.WriteLine(empty);
            try
            {
                nullst = nullst.Insert(0, "BOB");
                Console.WriteLine(nullst);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.GetType());
            }
            // задание d
            StringBuilder stb = new StringBuilder("kjasdgjaipjg;oiaaksdjg");

            stb.Remove(3, 4);
            stb.Append("KEKS");
            stb.Insert(0, "LOL");
            Console.WriteLine(stb);

            // Массивы

            const int sz = 3;

            int[,] mass = new int[sz, sz] {
                { 3, 7, 6 }, { 4, 2, 3 }, { 7, 2, 1 }
            };
            for (int i = 0; i < sz; i++)
            {
                for (int j = 0; j < sz; j++)
                {
                    Console.Write(mass[i, j] + " ");
                }
                Console.WriteLine();
            }

            ///////

            String[] strArr = { "lol", "kek", "zzz" };

            foreach (String g in strArr)
            {
                Console.WriteLine(g);
            }

            Console.WriteLine($"\tДлинна массива = {strArr.Length}");


            int num = int.Parse(Console.ReadLine());

            Console.WriteLine("наше значение: ");
            strArr[num - 1] = Console.ReadLine();

            Console.WriteLine();
            foreach (String g in strArr)
            {
                Console.WriteLine(g);
            }
            ///////

            double[][] mas2 = new double[3][];
            mas2[0] = new double[1];
            mas2[1] = new double[2];
            mas2[2] = new double[3];
            Console.WriteLine("Введите массив: ");
            for (int i = 0; i < mas2.Length; i++)
            {
                Console.WriteLine($"Введите {mas2[i].Length} числа: ");
                int j = 0;
                foreach (String g in Console.ReadLine().Split(' '))
                {
                    mas2[i][j] = Convert.ToDouble(g);
                    j++;
                }
            }

            Console.WriteLine("\nВведенный массив: ");
            foreach (double[] arr in mas2)
            {
                foreach (double value in arr)
                {
                    Console.Write(value + " ");
                }
                Console.WriteLine();
            }
            ////////////
            var varIntg = new int[5];
            var varStrr = "строка";


            ////////////////////////////////////



            var MyTuple = (ammount : 10, st : "Hi", chr : 'z', st2 : "eeee", ulng : (ulong)1337);

            Console.WriteLine(MyTuple);
            Console.WriteLine(MyTuple.ammount + " " + MyTuple.chr + " " + MyTuple.st2);

            (int count, string stroka1, char chr, string stroka2, ulong ulngint) = MyTuple;
            Console.WriteLine(count + " " + stroka1 + " " + chr + " " + stroka2 + " " + ulngint);


            (int first, string second, char third, string four, ulong five)tuple2 = (123, "sdfsg", 'x', "four", 123);
            int cmpTuple = MyTuple.CompareTo(tuple2);



            if (cmpTuple == 0)
            {
                Console.WriteLine("Картежи одинаковые");
            }
            else
            {
                Console.WriteLine("Картежи разные");
            }

            //////////////////////

            int[] array = { 1, 2, 3, 4, 5, 6, 7 };

            (int, int, int, char) CortageF(int[] arr, string strin)
            {
                int  min = arr[0];
                int  max = arr[0];
                int  sum = arr[0];
                char c   = strin[0];

                for (int i = 1; i < arr.Length; i++)
                {
                    if (arr[i] < min)
                    {
                        min = arr[i];
                    }
                    if (arr[i] > max)
                    {
                        max = arr[i];
                    }
                    sum += arr[i];
                }

                return(max, min, sum, c);
            }

            Console.WriteLine(CortageF(array, "Slim Shady"));
        }
示例#52
0
 public FilteredSignature(String sSignature, Char cParametersSplitChar)
 {
     this.sSignature           = sSignature;
     this.cParametersSplitChar = cParametersSplitChar;
     sParseSignature();
 }
示例#53
0
 private static bool charEqual(char a, char b, bool senseCase)
 {
     return(senseCase ? a == b : Char.ToUpperInvariant(a) == Char.ToUpperInvariant(b));
 }
示例#54
0
        private bool TryGetParametersForFunction(string expression, string targetFunctionName, out List <string> exprParams)
        {
            int functionKeyworkIndex = expression.IndexOf($"{targetFunctionName}(");

            if (functionKeyworkIndex == -1)
            {
                exprParams = null;
                return(false);
            }

            if ((functionKeyworkIndex != 0 &&
                 functionKeyworkIndex == 1 && expression[0] != '!') ||
                functionKeyworkIndex > 1 ||
                !expression.EndsWith(')'))
            {
                throw new InvalidDataException($"Condition {expression} malformed. Currently only single-function conditions are supported.");
            }

            exprParams = new List <string>();
            bool          isWithinString  = false;
            bool          expectDelimiter = false;
            int           curParsingIndex = functionKeyworkIndex + targetFunctionName.Length + 1;
            StringBuilder resolvedValue   = new StringBuilder();

            // Account for the trailing parenthesis.
            while (curParsingIndex + 1 < expression.Length)
            {
                char currentChar = expression[curParsingIndex];
                // toggle string nesting on ', except if scaped
                if (currentChar == '\'' && !(curParsingIndex > 0 && expression[curParsingIndex - 1] == '\\'))
                {
                    if (isWithinString)
                    {
                        exprParams.Add(resolvedValue.ToString());
                        resolvedValue.Clear();
                        expectDelimiter = true;
                    }

                    isWithinString = !isWithinString;
                }
                else if (isWithinString)
                {
                    resolvedValue.Append(currentChar);
                }
                else if (currentChar == ',')
                {
                    if (!expectDelimiter)
                    {
                        throw new InvalidDataException($"Unexpected comma found within {expression}");
                    }
                    expectDelimiter = false;
                }
                else if (!Char.IsWhiteSpace(currentChar))
                {
                    throw new InvalidDataException($"Non whitespace, non comma value found outside of string within: {expression}");
                }
                curParsingIndex++;
            }

            if (isWithinString)
            {
                throw new InvalidDataException($"Non-terminated string detected within {expression}");
            }
            return(true);
        }
示例#55
0
 /// <summary>
 /// Create a <see cref="Pattern"/> from the given <paramref name="char"/>.
 /// </summary>
 /// <param name="char">The <see cref="Char"/> literal.</param>
 /// <returns>A <see cref="Pattern"/> representing literally the <paramref name="char"/>.</returns>
 public static Pattern Literal(Char @char) => new Pattern(new CharLiteral(@char));
示例#56
0
        private Token ParseNumeric()
        {
            bool floating = false;
            char c;

            for (_current++; _current < _source.Length; _current++)
            {
                c = _source[_current];

                if (c == '.')
                {
                    if (floating)
                    {
                        break;
                    }

                    floating = true;
                }
                else if (!Char.IsDigit(c))
                {
                    break;
                }
            }

            bool haveExponent = false;

            if (_current < _source.Length)
            {
                c = _source[_current];

                if (c == 'E' || c == 'e')
                {
                    _current++;

                    if (_source[_current] == '-')
                    {
                        _current++;
                    }

                    int?exponentEnd = _current == _source.Length ? null : SkipDigits(_current);

                    if (!exponentEnd.HasValue)
                    {
                        throw new ODataException(String.Format(
                                                     ErrorMessages.Lexer_ExpectedDigitsAfterExponent, _offset
                                                     ));
                    }

                    _current = exponentEnd.Value;

                    haveExponent = true;

                    if (_current < _source.Length)
                    {
                        c = _source[_current];

                        if (c == 'm' || c == 'M')
                        {
                            throw new ODataException(String.Format(
                                                         ErrorMessages.Lexer_DecimalCannotHaveExponent, _offset
                                                         ));
                        }
                        else if (c == 'l' || c == 'L')
                        {
                            throw new ODataException(String.Format(
                                                         ErrorMessages.Lexer_LongCannotHaveExponent, _offset
                                                         ));
                        }
                    }
                }
            }

            string      text = _source.Substring(_offset, _current - _offset);
            object      value;
            LiteralType type;

            if (_current < _source.Length)
            {
                c = _source[_current];

                switch (c)
                {
                case 'F':
                case 'f':
                    value = float.Parse(text, ParseCulture);
                    type  = LiteralType.Single;
                    _current++;
                    break;

                case 'D':
                case 'd':
                    value = double.Parse(text, ParseCulture);
                    type  = LiteralType.Double;
                    _current++;
                    break;

                case 'M':
                case 'm':
                    value = decimal.Parse(text, ParseCulture);
                    type  = LiteralType.Decimal;
                    _current++;
                    break;

                case 'L':
                case 'l':
                    value = long.Parse(text, ParseCulture);
                    type  = LiteralType.Long;
                    _current++;
                    break;

                default:
                    if (floating || haveExponent)
                    {
                        value = double.Parse(text, ParseCulture);
                        type  = LiteralType.Double;
                    }
                    else
                    {
                        value = int.Parse(text, ParseCulture);
                        type  = LiteralType.Int;
                    }
                    break;
                }
            }
            else
            {
                if (floating || haveExponent)
                {
                    value = double.Parse(text, ParseCulture);
                    type  = LiteralType.Double;
                }
                else
                {
                    value = int.Parse(text, ParseCulture);
                    type  = LiteralType.Int;
                }
            }

            _offset = _current;

            return(new LiteralToken(value, type));
        }
示例#57
0
 /// <summary>
 /// Searches the receiver for the specified value using
 /// the binary search algorithmd  The receiver must <strong>must</strong> be
 /// sorted (as by the sort method) prior to making this calld  If
 /// it is not sorted, the results are undefined: in particular, the call
 /// may enter an infinite loopd  If the receiver contains multiple elements
 /// equal to the specified object, there is no guarantee which instance
 /// will be found.
 ///
 /// <summary>
 /// <param name="key">the value to be searched for.</param>
 /// <param name="from">the leftmost search position, inclusive.</param>
 /// <param name="to">the rightmost search position, inclusive.</param>
 /// <returns>index of the search key, if it is contained in the receiver;</returns>
 ///	       otherwise, <i>(-(<i>insertion point</i>) - 1)</i>d  The <i>insertion
 ///	       point</i> is defined as the the point at which the value would
 ///            be inserted into the receiver: the index of the first
 ///	       element greater than the key, or <i>receiver.Count</i>, if all
 ///	       elements in the receiver are less than the specified keyd  Note
 ///	       that this guarantees that the return value will be &gt;= 0 if
 ///	       and only if the key is found.
 /// <see cref="Cern.Colt.Sorting"></see>
 /// <see cref="java.util.Arrays"></see>
 public override int BinarySearchFromTo(Char key, int from, int to)
 {
     return(Cern.Colt.Sorting.BinarySearchFromTo(_elements, key, from, to));
 }
示例#58
0
    public bool runTest()
    {
        int    iCountErrors    = 0;
        int    iCountTestcases = 0;
        String strTemp         = String.Empty;

        Char[]        cArr = new Char[10];
        StringBuilder sb   = new StringBuilder(40);
        StringWriter  sw   = new StringWriter(sb);
        StringReader  sr;

        iCountTestcases++;
        bool[] bArr = new bool[] { true, true, true, true, true, false, false, false, false, false };
        try {
            for (int i = 0; i < bArr.Length; i++)
            {
                sw.WriteLine(bArr[i]);
            }
            sr = new StringReader(sw.GetStringBuilder().ToString());
            for (int i = 0; i < bArr.Length; i++)
            {
                sr.Read(cArr, 0, bArr[i].ToString().Length + System.Environment.NewLine.Length);
                if (new String(cArr, 0, bArr[i].ToString().Length) != bArr[i].ToString())
                {
                    iCountErrors++;
                    printerr("Error_298vc_" + i + "! Expected==" + bArr[i].ToString() + ", got==" + new String(cArr));
                }
            }
        } catch (Exception exc) {
            iCountErrors++;
            printerr("Error_298yg! Unexpected exception thrown, exc==" + exc.ToString());
        }
        iCountTestcases++;
        bArr = new bool[10000];
        for (int i = 0; i < bArr.Length; i++)
        {
            bArr[i] = Convert.ToBoolean(rand.Next(0, 2));
        }
        try {
            sb.Length = 0;
            for (int i = 0; i < bArr.Length; i++)
            {
                sw.WriteLine(bArr[i]);
            }
            sr = new StringReader(sw.GetStringBuilder().ToString());
            for (int i = 0; i < bArr.Length; i++)
            {
                sr.Read(cArr, 0, bArr[i].ToString().Length + System.Environment.NewLine.Length);
                if (new String(cArr, 0, bArr[i].ToString().Length) != bArr[i].ToString())
                {
                    iCountErrors++;
                    printerr("Error_57485_" + i + "! Expected==" + bArr[i].ToString() + ", got==" + new String(cArr));
                }
            }
        } catch (Exception exc) {
            iCountErrors++;
            printerr("Error_43432! Unexpected exception thrown, exc==" + exc.ToString());
        }
        if (iCountErrors == 0)
        {
            Console.WriteLine("paSs. iCountTestcases==" + iCountTestcases.ToString());
            return(true);
        }
        else
        {
            Console.WriteLine("FAiL! iCountErrors==" + iCountErrors.ToString());
            return(false);
        }
    }
示例#59
0
 public static long Append(this long?x, char c)
 {
     return(checked ((x * 10 ?? 0) + (long)Char.GetNumericValue(c)));
 }
示例#60
0
 private static bool isResourceNameElement(XName elementName)
 {
     return Char.IsUpper(elementName.LocalName, 0) && elementName.Namespace == XmlNs.XFHIR;
 }