问:
code 128 barcode in c# wrong check digit for one barcode
I have been using the code from here to convert three digit numbers to barcodes for scanning in the company I work for.

I have only found a problem with one barcode.  When it encodes "002" it outputs "Ì002 Î".  I have found that this will not scan with the space.  With much time searching and looking for what should be in that space and what scans.  I found that the barcode generator generator code from here has the Â as the check character.

Now for my question How could I change the code to encode that correctly? Or,Is there another FREE code sample that I could implement to get the code 128 barcode?

I have it implemented like

```<code>MEKBarcodeLBL.Text = HazmatLabels.Classes.BarcodeConverter128.StringToBarcode(MEKScrapLBL.Text).PadLeft(3, '0');
</code>```

Thanks in advance for all your help!!!!

BarcodeConverter128.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HazmatLabels.Classes
{

    /// <summary>
    /// Code 128
    /// Convert an input string to the equivilant string including start and stop characters.
    /// This object compresses the values to the shortest possible code 128 barcode format
    /// </summary>
    public static class BarcodeConverter128
    {
        /// <summary>
        /// Converts an input string to the equivilant string, that need to be produced using the 'Code 128' font.
        /// </summary>
        /// <param name="value">String to be encoded</param>
        /// <returns>Encoded string start/stop and checksum characters included</returns>
        public static string StringToBarcode(string value)
        {
            // Parameters : a string
            // Return     : a string which give the bar code when it is dispayed with CODE128.TTF font
            //           : an empty string if the supplied parameter is no good
            int charPos, minCharPos;
            int currentChar, checksum;
            bool isTableB = true, isValid = true;
            string returnValue = string.Empty;

            if (value.Length > 0)
            {

                // Check for valid characters
                for (int charCount = 0; charCount < value.Length; charCount++)
                {
                    //currentChar = char.GetNumericValue(value, charPos);
                    currentChar = (int)char.Parse(value.Substring(charCount, 1));
                    if (!(currentChar >= 32 && currentChar <= 126))
                    {
                        isValid = false;
                        break;
                    }
                }

                // Barcode is full of ascii characters, we can now process it
                if (isValid)
                {
                    charPos = 0;
                    while (charPos < value.Length)
                    {
                        if (isTableB)
                        {
                            // See if interesting to switch to table C
                            // yes for 4 digits at start or end, else if 6 digits
                            if (charPos == 0 || charPos + 4 == value.Length)
                                minCharPos = 4;
                            else
                                minCharPos = 6;

                            minCharPos = BarcodeConverter128.IsNumber(value, charPos, minCharPos);

                            if (minCharPos < 0)
                            {
                                // Choice table C
                                if (charPos == 0)
                                {
                                    // Starting with table C
                                    returnValue = ((char)205).ToString(); // char.ConvertFromUtf32(205);
                                }
                                else
                                {
                                    // Switch to table C
                                    returnValue = returnValue + ((char)199).ToString();
                                }
                                isTableB = false;
                            }
                            else
                            {
                                if (charPos == 0)
                                {
                                    // Starting with table B
                                    returnValue = ((char)204).ToString(); // char.ConvertFromUtf32(204);
                                }

                            }
                        }

                        if (!isTableB)
                        {
                            // We are on table C, try to process 2 digits
                            minCharPos = 2;
                            minCharPos = BarcodeConverter128.IsNumber(value, charPos, minCharPos);
                            if (minCharPos < 0) // OK for 2 digits, process it
                            {
                                currentChar = int.Parse(value.Substring(charPos, 2));
                                currentChar = currentChar < 95 ? currentChar + 32 : currentChar + 100;
                                returnValue = returnValue + ((char)currentChar).ToString();
                                charPos += 2;
                            }
                            else
                            {
                                // We haven't 2 digits, switch to table B
                                returnValue = returnValue + ((char)200).ToString();
                                isTableB = true;
                            }
                        }
                        if (isTableB)
                        {
                            // Process 1 digit with table B
                            returnValue = returnValue + value.Substring(charPos, 1);
                            charPos++;
                        }
                    }

                    // Calculation of the checksum
                    checksum = 0;
                    for (int loop = 0; loop < returnValue.Length; loop++)
                    {
                        currentChar = (int)char.Parse(returnValue.Substring(loop, 1));
                        currentChar = currentChar < 127 ? currentChar - 32 : currentChar - 100;
                        if (loop == 0)
                            checksum = currentChar;
                        else
                            checksum = (checksum + (loop * currentChar)) % 103;
                    }

                    // Calculation of the checksum ASCII code
                    checksum = checksum < 95 ? checksum + 32 : checksum + 100;
                    // Add the checksum and the STOP
                    returnValue = returnValue +
                        ((char)checksum).ToString() +
                        ((char)206).ToString();
                }
            }

            return returnValue;
        }

        private static int IsNumber(string InputValue, int CharPos, int MinCharPos)
        {
            // if the MinCharPos characters from CharPos are numeric, then MinCharPos = -1
            MinCharPos--;
            if (CharPos + MinCharPos < InputValue.Length)
            {
                while (MinCharPos >= 0)
                {
                    if ((int)char.Parse(InputValue.Substring(CharPos + MinCharPos, 1)) < 48
                        || (int)char.Parse(InputValue.Substring(CharPos + MinCharPos, 1)) > 57)
                    {
                        break;
                    }
                    MinCharPos--;
                }
            }
            return MinCharPos;
        }
    }
}
</code>```

Body:
I have been using the code from here to convert three digit numbers to barcodes for scanning in the company I work for.

I have only found a problem with one barcode.  When it encodes "002" it outputs "Ì002 Î".  I have found that this will not scan with the space.  With much time searching and looking for what should be in that space and what scans.  I found that the barcode generator generator code from here has the Â as the check character.

Now for my question How could I change the code to encode that correctly? Or,Is there another FREE code sample that I could implement to get the code 128 barcode?

I have it implemented like

MEKBarcodeLBL.Text = HazmatLabels.Classes.BarcodeConverter128.StringToBarcode(MEKScrapLBL.Text).PadLeft(3, '0');

Thanks in advance for all your help!!!!

BarcodeConverter128.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HazmatLabels.Classes
{

    ///
    /// Code 128
    /// Convert an input string to the equivilant string including start and stop characters.
    /// This object compresses the values to the shortest possible code 128 barcode format
    ///
    public static class BarcodeConverter128
    {
        ///
        /// Converts an input string to the equivilant string, that need to be produced using the 'Code 128' font.
        ///
        /// <param name="value">String to be encoded</param>
        /// <returns>Encoded string start/stop and checksum characters included</returns>
        public static string StringToBarcode(string value)
        {
            // Parameters : a string
            // Return     : a string which give the bar code when it is dispayed with CODE128.TTF font
            //           : an empty string if the supplied parameter is no good
            int charPos, minCharPos;
            int currentChar, checksum;
            bool isTableB = true, isValid = true;
            string returnValue = string.Empty;

            if (value.Length > 0)
            {

                // Check for valid characters
                for (int charCount = 0; charCount < value.Length; charCount++)
                {
                    //currentChar = char.GetNumericValue(value, charPos);
                    currentChar = (int)char.Parse(value.Substring(charCount, 1));
                    if (!(currentChar >= 32 && currentChar <= 126))
                    {
                        isValid = false;
                        break;
                    }
                }

                // Barcode is full of ascii characters, we can now process it
                if (isValid)
                {
                    charPos = 0;
                    while (charPos < value.Length)
                    {
                        if (isTableB)
                        {
                            // See if interesting to switch to table C
                            // yes for 4 digits at start or end, else if 6 digits
                            if (charPos == 0 || charPos + 4 == value.Length)
                                minCharPos = 4;
                            else
                                minCharPos = 6;

                            minCharPos = BarcodeConverter128.IsNumber(value, charPos, minCharPos);

                            if (minCharPos < 0)
                            {
                                // Choice table C
                                if (charPos == 0)
                                {
                                    // Starting with table C
                                    returnValue = ((char)205).ToString(); // char.ConvertFromUtf32(205);
                                }
                                else
                                {
                                    // Switch to table C
                                    returnValue = returnValue + ((char)199).ToString();
                                }
                                isTableB = false;
                            }
                            else
                            {
                                if (charPos == 0)
                                {
                                    // Starting with table B
                                    returnValue = ((char)204).ToString(); // char.ConvertFromUtf32(204);
                                }

                            }
                        }

                        if (!isTableB)
                        {
                            // We are on table C, try to process 2 digits
                            minCharPos = 2;
                            minCharPos = BarcodeConverter128.IsNumber(value, charPos, minCharPos);
                            if (minCharPos < 0) // OK for 2 digits, process it
                            {
                                currentChar = int.Parse(value.Substring(charPos, 2));
                                currentChar = currentChar < 95 ? currentChar + 32 : currentChar + 100;
                                returnValue = returnValue + ((char)currentChar).ToString();
                                charPos += 2;
                            }
                            else
                            {
                                // We haven't 2 digits, switch to table B
                                returnValue = returnValue + ((char)200).ToString();
                                isTableB = true;
                            }
                        }
                        if (isTableB)
                        {
                            // Process 1 digit with table B
                            returnValue = returnValue + value.Substring(charPos, 1);
                            charPos++;
                        }
                    }

                    // Calculation of the checksum
                    checksum = 0;
                    for (int loop = 0; loop < returnValue.Length; loop++)
                    {
                        currentChar = (int)char.Parse(returnValue.Substring(loop, 1));
                        currentChar = currentChar < 127 ? currentChar - 32 : currentChar - 100;
                        if (loop == 0)
                            checksum = currentChar;
                        else
                            checksum = (checksum + (loop * currentChar)) % 103;
                    }

                    // Calculation of the checksum ASCII code
                    checksum = checksum < 95 ? checksum + 32 : checksum + 100;
                    // Add the checksum and the STOP
                    returnValue = returnValue +
                        ((char)checksum).ToString() +
                        ((char)206).ToString();
                }
            }

            return returnValue;
        }

        private static int IsNumber(string InputValue, int CharPos, int MinCharPos)
        {
            // if the MinCharPos characters from CharPos are numeric, then MinCharPos = -1
            MinCharPos--;
            if (CharPos + MinCharPos < InputValue.Length)
            {
                while (MinCharPos >= 0)
                {
                    if ((int)char.Parse(InputValue.Substring(CharPos + MinCharPos, 1)) < 48
                        || (int)char.Parse(InputValue.Substring(CharPos + MinCharPos, 1)) > 57)
                    {
                        break;
                    }
                    MinCharPos--;
                }
            }
            return MinCharPos;
        }
    }
}

Body:
This is the other code and I am not sure on how to implement it.

Code128Rendering.cs

    using System;
    using System.Drawing;
    using System.Diagnostics;

    namespace GenCode128
    {
        /// <summary>
        /// Summary description for Code128Rendering.
        /// </summary>
        public static class Code128Rendering
        {

            #region Code patterns

            // in principle these rows should each have 6 elements
            // however, the last one -- STOP -- has 7. The cost of the
            // extra integers is trivial, and this lets the code flow
            // much more elegantly
            private static readonly int[,] cPatter

ns =
                       {
                        {2,1,2,2,2,2,0,0},  // 0
                        {2,2,2,1,2,2,0,0},  // 1
                        {2,2,2,2,2,1,0,0},  // 2
                        {1,2,1,2,2,3,0,0},  // 3
                        {1,2,1,3,2,2,0,0},  // 4
                        {1,3,1,2,2,2,0,0},  // 5
                        {1,2,2,2,1,3,0,0},  // 6
                        {1,2,2,3,1,2,0,0},  // 7
                        {1,3,2,2,1,2,0,0},  // 8
                        {2,2,1,2,1,3,0,0},  // 9
                        {2,2,1,3,1,2,0,0},  // 10
                        {2,3,1,2,1,2,0,0},  // 11
                        {1,1,2,2,3,2,0,0},  // 12
                        {1,2,2,1,3,2,0,0},  // 13
                        {1,2,2,2,3,1,0,0},  // 14
                        {1,1,3,2,2,2,0,0},  // 15
                        {1,2,3,1,2,2,0,0},  // 16
                        {1,2,3,2,2,1,0,0},  // 17
                        {2,2,3,2,1,1,0,0},  // 18
                        {2,2,1,1,3,2,0,0},  // 19
                        {2,2,1,2,3,1,0,0},  // 20
                        {2,1,3,2,1,2,0,0},  // 21
                        {2,2,3,1,1,2,0,0},  // 22
                        {3,1,2,1,3,1,0,0},  // 23
                        {3,1,1,2,2,2,0,0},  // 24
                        {3,2,1,1,2,2,0,0},  // 25
                        {3,2,1,2,2,1,0,0},  // 26
                        {3,1,2,2,1,2,0,0},  // 27
                        {3,2,2,1,1,2,0,0},  // 28
                        {3,2,2,2,1,1,0,0},  // 29
                        {2,1,2,1,2,3,0,0},  // 30
                        {2,1,2,3,2,1,0,0},  // 31
                        {2,3,2,1,2,1,0,0},  // 32
                        {1,1,1,3,2,3,0,0},  // 33
                        {1,3,1,1,2,3,0,0},  // 34
                        {1,3,1,3,2,1,0,0},  // 35
                        {1,1,2,3,1,3,0,0},  // 36
                        {1,3,2,1,1,3,0,0},  // 37
                        {1,3,2,3,1,1,0,0},  // 38
                        {2,1,1,3,1,3,0,0},  // 39
                        {2,3,1,1,1,3,0,0},  // 40
                        {2,3,1,3,1,1,0,0},  // 41
                        {1,1,2,1,3,3,0,0},  // 42
                        {1,1,2,3,3,1,0,0},  // 43
                        {1,3,2,1,3,1,0,0},  // 44
                        {1,1,3,1,2,3,0,0},  // 45
                        {1,1,3,3,2,1,0,0},  // 46
                        {1,3,3,1,2,1,0,0},  // 47
                        {3,1,3,1,2,1,0,0},  // 48
                        {2,1,1,3,3,1,0,0},  // 49
                        {2,3,1,1,3,1,0,0},  // 50
                        {2,1,3,1,1,3,0,0},  // 51
                        {2,1,3,3,1,1,0,0},  // 52
                        {2,1,3,1,3,1,0,0},  // 53
                        {3,1,1,1,2,3,0,0},  // 54
                        {3,1,1,3,2,1,0,0},  // 55
                        {3,3,1,1,2,1,0,0},  // 56
                        {3,1,2,1,1,3,0,0},  // 57
                        {3,1,2,3,1,1,0,0},  // 58
                        {3,3,2,1,1,1,0,0},  // 59
                        {3,1,4,1,1,1,0,0},  // 60
                        {2,2,1,4,1,1,0,0},  // 61
                        {4,3,1,1,1,1,0,0},  // 62
                        {1,1,1,2,2,4,0,0},  // 63
                        {1,1,1,4,2,2,0,0},  // 64
                        {1,2,1,1,2,4,0,0},  // 65
                        {1,2,1,4,2,1,0,0},  // 66
                        {1,4,1,1,2,2,0,0},  // 67
                        {1,4,1,2,2,1,0,0},  // 68
                        {1,1,2,2,1,4,0,0},  // 69
                        {1,1,2,4,1,2,0,0},  // 70
                        {1,2,2,1,1,4,0,0},  // 71
                        {1,2,2,4,1,1,0,0},  // 72
                        {1,4,2,1,1,2,0,0},  // 73
                        {1,4,2,2,1,1,0,0},  // 74
                        {2,4,1,2,1,1,0,0},  // 75
                        {2,2,1,1,1,4,0,0},  // 76
                        {4,1,3,1,1,1,0,0},  // 77
                        {2,4,1,1,1,2,0,0},  // 78
                        {1,3,4,1,1,1,0,0},  // 79
                        {1,1,1,2,4,2,0,0},  // 80
                        {1,2,1,1,4,2,0,0},  // 81
                        {1,2,1,2,4,1,0,0},  // 82
                        {1,1,4,2,1,2,0,0},  // 83
                        {1,2,4,1,1,2,0,0},  // 84
                        {1,2,4,2,1,1,0,0},  // 85
                        {4,1,1,2,1,2,0,0},  // 86
                        {4,2,1,1,1,2,0,0},  // 87
                        {4,2,1,2,1,1,0,0},  // 88
                        {2,1,2,1,4,1,0,0},  // 89
                        {2,1,4,1,2,1,0,0},  // 90
                        {4,1,2,1,2,1,0,0},  // 91
                        {1,1,1,1,4,3,0,0},  // 92
                        {1,1,1,3,4,1,0,0},  // 93
                        {1,3,1,1,4,1,0,0},  // 94
                        {1,1,4,1,1,3,0,0},  // 95
                        {1,1,4,3,1,1,0,0},  // 96
                        {4,1,1,1,1,3,0,0},  // 97
                        {4,1,1,3,1,1,0,0},  // 98
                        {1,1,3,1,4,1,0,0},  // 99
                        {1,1,4,1,3,1,0,0},  // 100
                        {3,1,1,1,4,1,0,0},  // 101
                        {4,1,1,1,3,1,0,0},  // 102
                        {2,1,1,4,1,2,0,0},  // 103
                        {2,1,1,2,1,4,0,0},  // 104
                        {2,1,1,2,3,2,0,0},  // 105
                        {2,3,3,1,1,1,2,0}   // 106
                     };

        #endregion Code patterns

        private const int cQuietWidth = 10;

        /// <summary>
        /// Make an image of a Code128 barcode for a given string
        /// </summary>
        /// <param name="InputData">Message to be encoded</param>
        /// <param name="BarWeight">Base thickness for bar width (1 or 2 works well)</param>
        /// <param name="AddQuietZone">Add required horiz margins (use if output is tight)</param>
        /// <returns>An Image of the Code128 barcode representing the message</returns>
        public static Image MakeBarcodeImage(string InputData, int BarWeight, bool AddQuietZone)
        {
            // get the Code128 codes to represent the message
            Code128Content content = new Code128Content(InputData);
            int[] codes = content.Codes;

            int width, height;
            width = ((codes.Length - 3) * 11 + 35) * BarWeight;
            height = Convert.ToInt32(System.Math.Ceiling(Convert.ToSingle(width) * .15F));

            if (AddQuietZone)
            {
                width += 2 * cQuietWidth * BarWeight;  // on both sides
            }

            // get surface to draw on
            Image myimg = new System.Drawing.Bitmap(width, height);
            using (Graphics gr = Graphics.FromImage(myimg))
            {

                // set to white so we don't have to fill the spaces with white
                gr.FillRectangle(System.Drawing.Brushes.White, 0, 0, width, height);

                // skip quiet zone
                int cursor = AddQuietZone ? cQuietWidth * BarWeight : 0;

                for (int codeidx = 0; codeidx < codes.Length; codeidx++)
                {
                    int code = codes[codeidx];

                    // take the bars two at a time: a black and a white
                    for (int bar = 0; bar < 8; bar += 2)
                    {
                        int barwidth = cPatterns[code, bar] * BarWeight;
                        int spcwidth = cPatterns[code, bar + 1] * BarWeight;

                        // if width is zero, don't try to draw it
                        if (barwidth > 0)
                        {
                            gr.FillRectangle(System.Drawing.Brushes.Black, cursor, 0, barwidth, height);
                        }

                        // note that we never need to draw the space, since we
                        // initialized the graphics to all white

                        // advance cursor beyond this pair
                        cursor += (barwidth + spcwidth);
                    }
                }
            }

            return myimg;

        }

    }
}

Code128Content.cs

using System;
using System.Text;

namespace GenCode128
{
    public enum CodeSet
    {
        CodeA
       , CodeB
        // ,CodeC   // not supported
    }

    /// <summary>
    /// Represent the set of code values to be output into barcode form
    /// </summary>
    public class Code128Content
    {
        private int[] mCodeList;

        /// <summary>
        /// Create content based on a string of ASCII data
        /// </summary>
        /// <param name="AsciiData">the string that should be represented</param>
        public Code128Content(string AsciiData)
        {
            mCodeList = StringToCode128(AsciiData);
        }

        /// <summary>
        /// Provides the Code128 code values representing the object's string
        /// </summary>
        public int[] Codes
        {
            get
            {
                return mCodeList;
            }
        }

        /// <summary>
        /// Transform the string into integers representing the Code128 codes
        /// necessary to represent it
        /// </summary>
        /// <param name="AsciiData">String to be encoded</param>
        /// <returns>Code128 representation</returns>
        private int[] StringToCode128(string AsciiData)
        {
            // turn the string into ascii byte data
            byte[] asciiBytes = Encoding.ASCII.GetBytes(AsciiData);

            // decide which codeset to start with
            Code128Code.CodeSetAllowed csa1 = asciiBytes.Length > 0 ? Code128Code.CodesetAllowedForChar(asciiBytes[0]) : Code128Code.CodeSetAllowed.CodeAorB;
            Code128Code.CodeSetAllowed csa2 = asciiBytes.Length > 0 ? Code128Code.CodesetAllowedForChar(asciiBytes[1]) : Code128Code.CodeSetAllowed.CodeAorB;
            CodeSet currcs = GetBestStartSet(csa1, csa2);

            // set up the beginning of the barcode
            System.Collections.ArrayList codes = new System.Collections.ArrayList(asciiBytes.Length + 3); // assume no codeset changes, account for start, checksum, and stop
            codes.Add(Code128Code.StartCodeForCodeSet(currcs));

            // add the codes for each character in the string
            for (int i = 0; i < asciiBytes.Length; i++)
            {
                int thischar = asciiBytes[i];
                int nextchar = asciiBytes.Length > (i + 1) ? asciiBytes[i + 1] : -1;

                codes.AddRange(Code128Code.CodesForChar(thischar, nextchar, ref currcs));
            }

            // calculate the check digit
            int checksum = (int)(codes[0]);
            for (int i = 1; i < codes.Count; i++)
            {
                checksum += i * (int)(codes[i]);
            }
            codes.Add(checksum % 103);

            codes.Add(Code128Code.StopCode());

            int[] result = codes.ToArray(typeof(int)) as int[];
            return result;
        }

        /// <summary>
        /// Determines the best starting code set based on the the first two
        /// characters of the string to be encoded
        /// </summary>
        /// <param name="csa1">First character of input string</param>
        /// <param name="csa2">Second character of input string</param>
        /// <returns>The codeset determined to be best to start with</returns>
        private CodeSet GetBestStartSet(Code128Code.CodeSetAllowed csa1, Code128Code.CodeSetAllowed csa2)
        {
            int vote = 0;

            vote += (csa1 == Code128Code.CodeSetAllowed.CodeA) ? 1 : 0;
            vote += (csa1 == Code128Code.CodeSetAllowed.CodeB) ? -1 : 0;
            vote += (csa2 == Code128Code.CodeSetAllowed.CodeA) ? 1 : 0;
            vote += (csa2 == Code128Code.CodeSetAllowed.CodeB) ? -1 : 0;

            return (vote > 0) ? CodeSet.CodeA : CodeSet.CodeB;   // ties go to codeB due to my own prejudices
        }
    }

    /// <summary>
    /// Static tools for determining codes for individual characters in the content
    /// </summary>
    public static class Code128Code
    {
        #region Constants

        private const int cSHIFT = 98;
        private const int cCODEA = 101;
        private const int cCODEB = 100;

        private const int cSTARTA = 103;
        private const int cSTARTB = 104;
        private const int cSTOP = 106;

        #endregion

        /// <summary>
        /// Get the Code128 code value(s) to represent an ASCII character, with
        /// optional look-ahead for length optimization
        /// </summary>
        /// <param name="CharAscii">The ASCII value of the character to translate</param>
        /// <param name="LookAheadAscii">The next character in sequence (or -1 if none)</param>
        /// <param name="CurrCodeSet">The current codeset, that the returned codes need to follow;
        /// if the returned codes change that, then this value will be changed to reflect it</param>
        /// <returns>An array of integers representing the codes that need to be output to produce the
        /// given character</returns>
        public static int[] CodesForChar(int CharAscii, int LookAheadAscii, ref CodeSet CurrCodeSet)
        {
            int[] result;
            int shifter = -1;

            if (!CharCompatibleWithCodeset(CharAscii, CurrCodeSet))
            {
                // if we have a lookahead character AND if the next character is ALSO not compatible
                if ((LookAheadAscii != -1) && !CharCompatibleWithCodeset(LookAheadAscii, CurrCodeSet))
                {
                    // we need to switch code sets
                    switch (CurrCodeSet)
                    {
                        case CodeSet.CodeA:
                            shifter = cCODEB;
                            CurrCodeSet = CodeSet.CodeB;
                            break;
                        case CodeSet.CodeB:
                            shifter = cCODEA;
                            CurrCodeSet = CodeSet.CodeA;
                            break;
                    }
                }
                else
                {
                    // no need to switch code sets, a temporary SHIFT will suffice
                    shifter = cSHIFT;
                }
            }

            if (shifter != -1)
            {
                result = new int[2];
                result[0] = shifter;
                result[1] = CodeValueForChar(CharAscii);
            }
            else
            {
                result = new int[1];
                result[0] = CodeValueForChar(CharAscii);
            }

            return result;
        }

        /// <summary>
        /// Tells us which codesets a given character value is allowed in
        /// </summary>
        /// <param name="CharAscii">ASCII value of character to look at</param>
        /// <returns>Which codeset(s) can be used to represent this character</returns>
        public static CodeSetAllowed CodesetAllowedForChar(int CharAscii)
        {
            if (CharAscii >= 32 && CharAscii <= 95)
            {
                return CodeSetAllowed.CodeAorB;
            }
            else
            {
                return (CharAscii < 32) ? CodeSetAllowed.CodeA : CodeSetAllowed.CodeB;
            }
        }

        /// <summary>
        /// Determine if a character can be represented in a given codeset
        /// </summary>
        /// <param name="CharAscii">character to check for</param>
        /// <param name="currcs">codeset context to test</param>
        /// <returns>true if the codeset contains a representation for the ASCII character</returns>
        public static bool CharCompatibleWithCodeset(int CharAscii, CodeSet currcs)
        {
            CodeSetAllowed csa = CodesetAllowedForChar(CharAscii);
            return csa == CodeSetAllowed.CodeAorB
                     || (csa == CodeSetAllowed.CodeA && currcs == CodeSet.CodeA)
                     || (csa == CodeSetAllowed.CodeB && currcs == CodeSet.CodeB);
        }

        /// <summary>
        /// Gets the integer code128 code value for a character (assuming the appropriate code set)
        /// </summary>
        /// <param name="CharAscii">character to convert</param>
        /// <returns>code128 symbol value for the character</returns>
        public static int CodeValueForChar(int CharAscii)
        {
            return (CharAscii >= 32) ? CharAscii - 32 : CharAscii + 64;
        }

        /// <summary>
        /// Return the appropriate START code depending on the codeset we want to be in
        /// </summary>
        /// <param name="cs">The codeset you want to start in</param>
        /// <returns>The code128 code to start a barcode in that codeset</returns>
        public static int StartCodeForCodeSet(CodeSet cs)
        {
            return cs == CodeSet.CodeA ? cSTARTA : cSTARTB;
        }

        /// <summary>
        /// Return the Code128 stop code
        /// </summary>
        /// <returns>the stop code</returns>
        public static int StopCode()
        {
            return cSTOP;
        }

        /// <summary>
        /// Indicates which code sets can represent a character -- CodeA, CodeB, or either
        /// </summary>
        public enum CodeSetAllowed
        {
            CodeA,
            CodeB,
            CodeAorB
        }

    }
}


来源: stackexchange

问:
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
How do I convert a string to a byte[] in .NET (C#) without manually specifying a specific encoding?

I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know why encoding comes to play here.

Also, why should encoding even be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?

答:
```<code>byte[] strToByteArray(string str)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetBytes(str);
}
</code>```

OwnerDisplayName: Vulcan Eager

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Dale Ragan

OwnerDisplayName: gkrogers

ContentLicense: CC BY-SA 2.5


问:
iPhone xcode search path for device vs simulator?
I am confused at this setting (Project -> Edit Active Target).
The Search Paths can differ based on the SDK setting (simulator vs device).

But if I provide both simulator and device paths, for lets say the Frameworks path, then i get linker errors. But it seems if I only provide the proper path for whichever SDK i have selected, then it builds fine!

How can I keep both path settings? Currently Im having to cut and paste the appropriate path based on the SDK i have selected to build.

Thanks!

答:
Rob already hinted at this, but to clarify, here's how you'd set it using the build window.

In the build settings window, select the setting you want to modify (like "Framework search paths").  Then click the gear in the lower left, and select "Add Build Setting Condition."  Then you can add a value that applies only to iOS Simulator builds, and a second build setting condition to apply only to device builds.


问:
Extracting centroids using k-means clustering in python?
I have some data in a 1D array with shape [1000,] with 1000 elements in it. I applied k-means clustering on this data with 10 as number of clusters. After applying the k-means, I got cluster labels (id's) with shape [1000,] and centroids of shape [10,] for each cluster. The labels array allots value between 0 and 9 to each of the 1000 elements. However,  I want each element to show its centroid rather than its cluster id's. How can I achieve this?

```<code>from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=10)
kmeans.fit(data)   #data is of shape [1000,]
#learn the labels and the means
labels = kmeans.predict(data)  #labels of shape [1000,] with values 0<= i <= 9
centroids  = kmeans.cluster_centers_  #means of shape [10,]
</code>```

In the code above, I want respective centroids for each element in the [1000,] array instead of its cluster id's.

答:
Seems like a list comprehension would work well.</p>

```<code>centroid_labels = [centroids[i] for i in labels]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some data in a 1D array with shape [1000,] with 1000 elements in it. I applied k-means clustering on this data with 10 as number of clusters. After applying the k-means, I got cluster labels (id's) with shape [1000,] and centroids of shape [10,] for each cluster. The labels array allots value between 0 and 9 to each of the 1000 elements. However,  I want each element to show its centroid rather than its cluster id's. How can I achieve this?

from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=10)
kmeans.fit(data)   #data is of shape [1000,]
#learn the labels and the means
labels = kmeans.predict(data)  #labels of shape [1000,] with values 0<= i <= 9
centroids  = kmeans.cluster_centers_  #means of shape [10,]

In the code above, I want respective centroids for each element in the [1000,] array instead of its cluster id's.

Body:
Seems like a list comprehension would work well.

centroid_labels = [centroids[i] for i in labels]


问:
Webpack: extract css to its own bundle
I'm using webpack on a project. I use style-loader so I can import "my.css".

The css gets bundled with the javascript and will be rendered in a

答:
Yes, you need to use extract-text-webpack-plugin. You might want to do it only on your production config. Config looks like this:</p>

```<code>const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          //resolve-url-loader may be chained before sass-loader if necessary
          use: ['css-loader', 'sass-loader']
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('style.css')
    //if you want to pass in options, you can do so:
    //new ExtractTextPlugin({
    //  filename: 'style.css'
    //})
  ]
}
</code>```

Title: Webpack: extract css to its own bundle

Body:
Yes, you need to use extract-text-webpack-plugin. You might want to do it only on your production config. Config looks like this:

const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          //resolve-url-loader may be chained before sass-loader if necessary
          use: ['css-loader', 'sass-loader']
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('style.css')
    //if you want to pass in options, you can do so:
    //new ExtractTextPlugin({
    //  filename: 'style.css'
    //})
  ]
}


问:
jquery click on div in Chrome Console
Maybe one of you can help me.
How do I click on a div, by using the Chrome Console?

I want to be able to click the div on this site any ideas.

example: https://gleam.io/ZyYPU/100-subscriber-giveaway-100-usd

Tried this without any luck.

```<code>$('.entry-method #em2690957').click();
</code>```

答:
you can this:</p>

```<code>$('.entry-method, #em2690957').click();
</code>```

Title: jquery click on div in Chrome Console

Body:
Maybe one of you can help me.
How do I click on a div, by using the Chrome Console?

I want to be able to click the div on this site any ideas.

example: https://gleam.io/ZyYPU/100-subscriber-giveaway-100-usd

Tried this without any luck.

$('.entry-method #em2690957').click();

Body:
you can this:

$('.entry-method, #em2690957').click();


问:
Trying to deserialize and serialize a table in lua using the serpent library
So I am trying to do a simple serialization of a lua table, and deserialize it back into a table. But for some reason it just fails.

```<code>local a = {}
a[0] = {name="presetA"}
local line = serpent.line(a)

local presets, err = loadstring(line)

if (err) then
    log("Error")
    log(err)
else
    log("Success")
    log(serpent.block(presets))
end
</code>```

After running, log(err) shows

```<code>[string "{[0] = {name = "presetA"}}"]:1: unexpected symbol near '{'
</code>```

答:
loadstring loads a Lua chunk from the given string and runs it.

As your serialized table is not a valid Lua expression the interpreter reports the observed error.

Let's serialze an example:

```<code>serpent.line({key = "value"})
</code>```

returns

"{key = "value"} --[[table: 0D80CF40]]"

A table constructor on it's own is not a valid Lua expression.

Try to run that line and you'll Lua will report:

input:1: unexpected symbol near '{'

The output of serpent.line cannot be used as input to loadstring.

Now see the difference if you use serpent.dump instead

```<code>"do local _={name="hallo"};return _;end"
</code>```

This is a valid, executable Lua chunk that will return the serialized table.

Please note the following section from the serpent documentation:

Note that line and block functions return pretty-printed data
  structures and if you want to deserialize them, you need to add return
  before running them through loadstring. For example:
  loadstring('return '..require('mobdebug').line("foo"))() == "foo".

While you can use loadstring or load functions to load serialized
  fragments, Serpent also provides load function that adds safety checks
  and reports an error if there is any executable code in the fragment...

Please read manuals.

Body:
So I am trying to do a simple serialization of a lua table, and deserialize it back into a table. But for some reason it just fails.

local a = {}
a[0] = {name="presetA"}
local line = serpent.line(a)

local presets, err = loadstring(line)

if (err) then
    log("Error")
    log(err)
else
    log("Success")
    log(serpent.block(presets))
end

After running, log(err) shows

[string "{[0] = {name = "presetA"}}"]:1: unexpected symbol near '{'

Body:
loadstring loads a Lua chunk from the given string and runs it.

As your serialized table is not a valid Lua expression the interpreter reports the observed error.

Let's serialze an example:

serpent.line({key = "value"})

returns

"{key = "value"} --[[table: 0D80CF40]]"

A table constructor on it's own is not a valid Lua expression.

Try to run that line and you'll Lua will report:

input:1: unexpected symbol near '{'

The output of serpent.line cannot be used as input to loadstring.

Now see the difference if you use serpent.dump instead

"do local _={name="hallo"};return _;end"

This is a valid, executable Lua chunk that will return the serialized table.

Please note the following section from the serpent documentation:

Note that line and block functions return pretty-printed data
  structures and if you want to deserialize them, you need to add return
  before running them through loadstring. For example:
  loadstring('return '..require('mobdebug').line("foo"))() == "foo".

While you can use loadstring or load functions to load serialized
  fragments, Serpent also provides load function that adds safety checks
  and reports an error if there is any executable code in the fragment...

Please read manuals.


问:
Checking odd/even numbers and changing outputs on number size
I have a couple of problems to solve for an assignment, and am a bit stuck.
The question is to write a program that gets the user to input an odd number (check it's odd), then print an upside down pyramid of stars based on the size of the input.

For example, if you enter 5, it comes up with

```<code>*****
 ***
  *
</code>```

My problem is therefore two-fold.

1) How do I check if it's even or odd? I tried if number/2 == int in the hope that it might do something, and the internet tells me to do if number%2==0, but that doesn't work.

2) How do I change the asterisks in the middle of each line?

Any help with either problem is greatly appreciated.

答:
Sample Instruction
Given an integer, n, performing the following conditional actions:

If n is odd, print Weird

If n is even and in the inclusive range of 2 to 5, print Not Weird

If n is even and in the inclusive range of 6 to 20, print Weird

If n is even and greater than 20, print Not Weird

import math
n = int(input())

if n % 2 ==1:
    print("Weird")
elif n % 2==0 and n in range(2,6):
    print("Not Weird")
elif n % 2 == 0 and n in range(6,21):
    print("Weird")
elif n % 2==0 and n>20:
    print("Not Weird")
```

Body:
I have a couple of problems to solve for an assignment, and am a bit stuck.
The question is to write a program that gets the user to input an odd number (check it's odd), then print an upside down pyramid of stars based on the size of the input.

For example, if you enter 5, it comes up with

*****
 ***
  *

My problem is therefore two-fold.

1) How do I check if it's even or odd? I tried if number/2 == int in the hope that it might do something, and the internet tells me to do if number%2==0, but that doesn't work.

2) How do I change the asterisks in the middle of each line?

Any help with either problem is greatly appreciated.


问:
How to convert current time to date without time in sql?
I want to select data where the operation_date between '01-Jan-2016' and yesterday. I used code as follows:

```<code>select *
where operation_date between '01-Jan-2016' and sysdate-1
from TABLE
</code>```

But sysdate returns both date and time. Therefore, the above output includes all the data between '01-Jan-2016' and say, 14 Nov-2017 09:50:51. I only want the data before today. How to convert current time to date without time? Thanks.

答:
Seems that you are looking for trunc().

Example

```<code>SELECT sysdate - 1 AS current_Date_Time
    ,trunc(sysdate) - 1 AS CURRENT_DATE1
    ,trunc(sysdate - 1) AS CURRENT_DATE2
FROM dual
</code>```

Result

```<code>CURRENT_DATE_TIME       CURRENT_DATE1         CURRENT_DATE2
----------------------------------------------------------
13.11.2017 18:08:41     13.11.2017 00:00:00   13.11.2017 00:00:00
</code>```

DEMO

So the correct query will be as below.

```<code>SELECT *
WHERE operation_date BETWEEN DATE '2016-01-01' -- ANSI Date Literal
        AND trunc(sysdate - 1)
FROM TABLE
</code>```

OR

```<code>SELECT *
WHERE operation_date BETWEEN DATE '2016-01-01' -- ANSI Date Literal
        AND trunc(sysdate) - 1
FROM TABLE
</code>```

Body:
I want to select data where the operation_date between '01-Jan-2016' and yesterday. I used code as follows:

select *
where operation_date between '01-Jan-2016' and sysdate-1
from TABLE

But sysdate returns both date and time. Therefore, the above output includes all the data between '01-Jan-2016' and say, 14 Nov-2017 09:50:51. I only want the data before today. How to convert current time to date without time? Thanks.

Body:
Seems that you are looking for trunc().

Example

SELECT sysdate - 1 AS current_Date_Time
    ,trunc(sysdate) - 1 AS CURRENT_DATE1
    ,trunc(sysdate - 1) AS CURRENT_DATE2
FROM dual

Result

CURRENT_DATE_TIME       CURRENT_DATE1         CURRENT_DATE2
----------------------------------------------------------
13.11.2017 18:08:41     13.11.2017 00:00:00   13.11.2017 00:00:00

DEMO

So the correct query will be as below.

SELECT *
WHERE operation_date BETWEEN DATE '2016-01-01' -- ANSI Date Literal
        AND trunc(sysdate - 1)
FROM TABLE

OR

SELECT *
WHERE operation_date BETWEEN DATE '2016-01-01' -- ANSI Date Literal
        AND trunc(sysdate) - 1
FROM TABLE


问:
Get the current slide element on change event in OwlCarousel2
I am trying to create an effect similar to this (the demo uses Bootstrap Carousel):

https://codepen.io/SitePoint/pen/BpVrXP/

Bootstrap's 'slide.bs.carousel' returns a relatedTarget that is the slide element going to be displayed as soon as the carousel is moved i.e changed to another slide.

I haven't been able to find an equivalent data being returned in OwlCarousel2's changed.owl.carousel event. What event, if any, returns the element that's going to be in view?

Is there any alternative way or am I missing something?

答: Try the event translated.owl.carousel, translated is fired after the animation


问:
Join Queries in Peewee
Hello Stackoverflow Community,

I have just started working on peewee application and little stuck with join queries. Currently, I have following models setup :

```<code>class Equipment(BaseModel):
    equip_id = CharField(primary_key=True)
    is_fullset = BooleanField(default=False)

class Department(BaseModel):
    dept_id = IntegerField(primary_key=True)
    dept_name = CharField()

class User(BaseModel):
    email = CharField(primary_key=True)
    equip_id_fk = ForeignKeyField(Equipment, related_name="equipments", null=True)
    dept_id_fk = ForeignKeyField(Department, related_name="departments")
    user_name = CharField()
</code>```

I want to display a view/table that will hold combined information of all the table. I tried doing this like this for User and Equipment (for now) :

```<code>  query = (Equipment.select(Equipment, User).join(User, JOIN.LEFT_OUTER))
</code>```

Here I get equipment values first and then User. I tried changing User with Equipment and vice versa, but didn't work out well.
Basically, I want to display all these three tables into one singular table in this order:

```<code>User Name || User Email || Dept_ID || Dept_NAME || EQUIP_ID || Is_Fullset
</code>```

Please let me know if I need to change my models or query. Any help would be really appreciated.

答:
```<code>query = (User
         .select(User, Equipment, Department)
         .join(Equipment, JOIN.INNER)
         .switch(User)
         .join(Department, JOIN.INNER))
for row in query:
    print(row.user_name, row.email, row.dept_id_fk.dept_id,
          row.dept_id_fk.dept_name, row.equip_id_fk.equip_id,
          row.equip_id_fk.is_fullset)
</code>```

Title: Join Queries in Peewee

Body:
Hello Stackoverflow Community,

I have just started working on peewee application and little stuck with join queries. Currently, I have following models setup :

class Equipment(BaseModel):
    equip_id = CharField(primary_key=True)
    is_fullset = BooleanField(default=False)

class Department(BaseModel):
    dept_id = IntegerField(primary_key=True)
    dept_name = CharField()

class User(BaseModel):
    email = CharField(primary_key=True)
    equip_id_fk = ForeignKeyField(Equipment, related_name="equipments", null=True)
    dept_id_fk = ForeignKeyField(Department, related_name="departments")
    user_name = CharField()

I want to display a view/table that will hold combined information of all the table. I tried doing this like this for User and Equipment (for now) :

  query = (Equipment.select(Equipment, User).join(User, JOIN.LEFT_OUTER))

Here I get equipment values first and then User. I tried changing User with Equipment and vice versa, but didn't work out well.
Basically, I want to display all these three tables into one singular table in this order:

User Name || User Email || Dept_ID || Dept_NAME || EQUIP_ID || Is_Fullset

Please let me know if I need to change my models or query. Any help would be really appreciated.


问:
jQuery click events stopping works
I have a problem. jQuery('#FinishTest').click() works, but it stops when you select all the answers. The error does not appear in the console.

my code

```<code>jQuery('#FinishTest').click(function() {

  var names = {};
  jQuery(':radio').each(function() {
    names[jQuery(this).attr('name')] = true;
  });
  var count = 0;
  jQuery.each(names, function() {
    count++;
  });

  if (jQuery(':radio:checked').length > 3) {
    if (jQuery(':radio:checked').length < count) {
      if (confirm("Henüz cevaplanmamış sorularınız var. Testi bitirmek istediğinizden eminmisiniz ?")) {
        finishtest();
      } else {
        jQuery('#FinishTest').bind('click');
        return;
      }
    }
  } else {
    alert('Testi bitirebilmek için en az 2 soru cevaplamalısınız.');
  }
});
</code>```

答:
That happen because of the following condition in your code :

```<code>if( jQuery(':radio:checked').length < count )
</code>```

When you select all the answers you will end up by jQuery(':radio:checked').length equals six 6 and the count variable value will be also 6 so the condition will never evaluates to true.

Try to add equal to you condition = so it will be inferior or equal <= :

```<code>if( jQuery(':radio:checked').length <= count ){
   //Your logic here
}
</code>```

Hope this helps.

Changed and solved problem.

if (jQuery(':radio:checked').length > 3) {
  if (jQuery(':radio:checked').length < count) {
    if (confirm("Henüz cevaplanmamış sorularınız var. Testi bitirmek istediğinizden eminmisiniz ?")) {
      finishtest();
    }
  } else {
    finishtest();
  }
} else {
  alert('Testi bitirebilmek için en az 2 soru cevaplamalısınız.');
}```

Title: jQuery click events stopping works

Body:
I have a problem. jQuery('#FinishTest').click() works, but it stops when you select all the answers. The error does not appear in the console.

my code

jQuery('#FinishTest').click(function() {

  var names = {};
  jQuery(':radio').each(function() {
    names[jQuery(this).attr('name')] = true;
  });
  var count = 0;
  jQuery.each(names, function() {
    count++;
  });

  if (jQuery(':radio:checked').length > 3) {
    if (jQuery(':radio:checked').length < count) {
      if (confirm("Henüz cevaplanmamış sorularınız var. Testi bitirmek istediğinizden eminmisiniz ?")) {
        finishtest();
      } else {
        jQuery('#FinishTest').bind('click');
        return;
      }
    }
  } else {
    alert('Testi bitirebilmek için en az 2 soru cevaplamalısınız.');
  }
});

Body:
That happen because of the following condition in your code :

if( jQuery(':radio:checked').length < count )

When you select all the answers you will end up by jQuery(':radio:checked').length equals six 6 and the count variable value will be also 6 so the condition will never evaluates to true.

Try to add equal to you condition = so it will be inferior or equal <= :

if( jQuery(':radio:checked').length <= count ){
   //Your logic here
}

Hope this helps.

Changed and solved problem.

if (jQuery(':radio:checked').length > 3) {
  if (jQuery(':radio:checked').length < count) {
    if (confirm("Henüz cevaplanmamış sorularınız var. Testi bitirmek istediğinizden eminmisiniz ?")) {
      finishtest();
    }
  } else {
    finishtest();
  }
} else {
  alert('Testi bitirebilmek için en az 2 soru cevaplamalısınız.');
}


问:
Javascript lookup for value between upper and lower limit
I am working on a project in angularjs. I need help with creating a function which maps a single value to an array of json data containing range and return i.e. if value is within the range, then assign corresponding return value for that range. How can I achieve this using lookup function in javascript. An example of a json table I am using is this:

```<code>[{"LI":"05:0","LS":null,"points":0},
 {"LI":"04:00","LS":"05:00","points":3},
 {"LI":"03:00","LS":"4:00","points":4},
 {"LI":null,"LS":"3:00","points":4}
]
</code>```

Basically, if value is >= 5.00 return 0, if value >= 4.00 and value < 5.00,, return 3.

The function receives json table and value to lookup, then returns the points corresponding to that interval.

答:
If anyone finds it useful, my final code is as follows:

var app = angular.module('JsonMapping', []);

app.controller('MainCtrl', function($scope) {

  $scope.Model = {
   Value: 10,
   Result: 0,
   ReferenceTable: [{"LI":85,"LS":null,"points":15},{"LI":84,"LS":85,"points":14},{"LI":83,"LS":84,"points":13},{"LI":82,"LS":83,"points":12},{"LI":81,"LS":82,"points":11},{"LI":80,"LS":81,"points":10},{"LI":78,"LS":80,"points":8},{"LI":76,"LS":78,"points":6},{"LI":74,"LS":76,"points":4},{"LI":72,"LS":74,"points":2},{"LI":70,"LS":72,"points":1},{"LI":null,"LS":70,"points":0}]
  }

 $scope.GetPointsForValue = function() {
       var lowerLimit = 0, upperLimit = 0, points = 0.0;

   for (var i = $scope.Model.ReferenceTable.length - 1; i >= 0; i--) {
      lowerLimit = $scope.Model.ReferenceTable[i].LI;
      upperLimit = $scope.Model.ReferenceTable[i].LS;

      if(lowerLimit === null && parseFloat($scope.Model.Value) < upperLimit) {
          $scope.Model.Result = $scope.Model.ReferenceTable[i].points;
          break;
       }else if (upperLimit === null && parseFloat($scope.Model.Value) >= lowerLimit) {
          $scope.Model.Result = $scope.Model.ReferenceTable[i].points;
          break;
       }else if (upperLimit > parseFloat($scope.Model.Value) && parseFloat($scope.Model.Value) >= lowerLimit){
          $scope.Model.Result = $scope.Model.ReferenceTable[i].points;
          break;
       }
   }
};

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="JsonMapping">

<head>
  <meta charset="utf-8" />
  <title>Map value to Json Array</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <input type="number" ng-model="Model.Value" ng-change="GetPointsForValue()">
  <p>Points for value = {{Model.Result}}
</body>

</html></code>```

Body:
I am working on a project in angularjs. I need help with creating a function which maps a single value to an array of json data containing range and return i.e. if value is within the range, then assign corresponding return value for that range. How can I achieve this using lookup function in javascript. An example of a json table I am using is this:

[{"LI":"05:0","LS":null,"points":0},
 {"LI":"04:00","LS":"05:00","points":3},
 {"LI":"03:00","LS":"4:00","points":4},
 {"LI":null,"LS":"3:00","points":4}
]

Basically, if value is >= 5.00 return 0, if value >= 4.00 and value < 5.00,, return 3.

The function receives json table and value to lookup, then returns the points corresponding to that interval.

Body:
If anyone finds it useful, my final code is as follows:

var app = angular.module('JsonMapping', []);

app.controller('MainCtrl', function($scope) {

  $scope.Model = {
   Value: 10,
   Result: 0,
   ReferenceTable: [{"LI":85,"LS":null,"points":15},{"LI":84,"LS":85,"points":14},{"LI":83,"LS":84,"points":13},{"LI":82,"LS":83,"points":12},{"LI":81,"LS":82,"points":11},{"LI":80,"LS":81,"points":10},{"LI":78,"LS":80,"points":8},{"LI":76,"LS":78,"points":6},{"LI":74,"LS":76,"points":4},{"LI":72,"LS":74,"points":2},{"LI":70,"LS":72,"points":1},{"LI":null,"LS":70,"points":0}]
  }

 $scope.GetPointsForValue = function() {
       var lowerLimit = 0, upperLimit = 0, points = 0.0;

   for (var i = $scope.Model.ReferenceTable.length - 1; i >= 0; i--) {
      lowerLimit = $scope.Model.ReferenceTable[i].LI;
      upperLimit = $scope.Model.ReferenceTable[i].LS;

      if(lowerLimit === null && parseFloat($scope.Model.Value) < upperLimit) {
          $scope.Model.Result = $scope.Model.ReferenceTable[i].points;
          break;
       }else if (upperLimit === null && parseFloat($scope.Model.Value) >= lowerLimit) {
          $scope.Model.Result = $scope.Model.ReferenceTable[i].points;
          break;
       }else if (upperLimit > parseFloat($scope.Model.Value) && parseFloat($scope.Model.Value) >= lowerLimit){
          $scope.Model.Result = $scope.Model.ReferenceTable[i].points;
          break;
       }
   }
};

});

<!DOCTYPE html>
<html ng-app="JsonMapping">

<head>
  <meta charset="utf-8" />
  <title>Map value to Json Array</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <input type="number" ng-model="Model.Value" ng-change="GetPointsForValue()">
  <p>Points for value = {{Model.Result}}
</body>

</html>


问:
How do I read this text file and Insert into MySQL?
sample

```<code>user id  User Name
   U456      Mathew
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane
</code>```

and so on up to 500k.

I need to read this text file and insert to MySQL  in two columns say User ID and User Name. How do I do this in PHP?

答:
Use the fopen function of PHP to access and read the file.. From there on the rest is pretty much simple. Read the file line by line and insert the values into the database.

http://us3.php.net/manual/en/function.fopen.php

The above link gives a very good description of how the fopen function works.. Using a loop will be easy in this task.

Body:
sample

user id  User Name
   U456      Mathew
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane

and so on up to 500k.

I need to read this text file and insert to MySQL  in two columns say User ID and User Name. How do I do this in PHP?


问:
Implementing DES in Python, cannot understand part of the code
I'm learning how to write the code for DES encryption in Python. I came across this code on Github (link: https://github.com/RobinDavid/pydes/blob/master/pydes.py) but I'm not able to understand a part of the code. (See line 123 in the Github code, also given below:)

```<code>def binvalue(val, bitsize): #Return the binary value as a string of the given size
    binval = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:]   # this is line 124 I'm not getting
    if len(binval) > bitsize:
        raise "binary value larger than the expected size"
    while len(binval) < bitsize:
        binval = "0"+binval #Add as many 0 as needed to get the wanted size
return binval
</code>```

I understand what the function does (as written: #Return the binary value as a string of the given size) but I don't understand how it does it, I don't understand line 124. Thanks for answering.

答:
```<code>binval = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:]
</code>```

this line is a ternary expression returning the binary value of val if val is integer, else it does the same but on the ASCII code of val.

This is a way (among others) to be compatible with Python 2 and Python 3.

in Python 3, val is an integer, as a part of a bytes data, when val is a 1-sized string as part of a str data in Python 2, which doesn't make a difference between binary & string.

In a nutshell, this is a portable way of converting a byte/character to its binary representation as string.

Note that the author could learn more about python since

```<code>while len(binval) < bitsize:
        binval = "0"+binval
</code>```

could be replaced by binval = binval.zfill(bitsize).

Body:
I'm learning how to write the code for DES encryption in Python. I came across this code on Github (link: https://github.com/RobinDavid/pydes/blob/master/pydes.py) but I'm not able to understand a part of the code. (See line 123 in the Github code, also given below:)

def binvalue(val, bitsize): #Return the binary value as a string of the given size
    binval = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:]   # this is line 124 I'm not getting
    if len(binval) > bitsize:
        raise "binary value larger than the expected size"
    while len(binval) < bitsize:
        binval = "0"+binval #Add as many 0 as needed to get the wanted size
return binval

I understand what the function does (as written: #Return the binary value as a string of the given size) but I don't understand how it does it, I don't understand line 124. Thanks for answering.

Body:
binval = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:]

this line is a ternary expression returning the binary value of val if val is integer, else it does the same but on the ASCII code of val.

This is a way (among others) to be compatible with Python 2 and Python 3.

in Python 3, val is an integer, as a part of a bytes data, when val is a 1-sized string as part of a str data in Python 2, which doesn't make a difference between binary & string.

In a nutshell, this is a portable way of converting a byte/character to its binary representation as string.

Note that the author could learn more about python since

while len(binval) < bitsize:
        binval = "0"+binval

could be replaced by binval = binval.zfill(bitsize).


问:
Automatically log user into existing ASP.NET MVC 4 web app based on whether user has an Active Directory account
I hope someone can help me with the following scenario, as I've been trolling the web for without success for a couple of days now.

The scenario I'm facing is how do I automatically bypass the login screen and go directly to the dashboard if the user exists in Active Directory (AD)?  If the user does not exist i.e. user does not have an Active Directory (AD) account redirect the user to a login page.

Attached is a picture to explain the process better.

If I run the ASP.NET MVC 4 web app using "IIS Express" the username and domain are correct, and I automatically get logged in because my credentials are correct for e.g:

```<code>username   => "username"
domain     => "domain"
</code>```

But If I run the solution on my "Local IIS" the credentials are incorrect because IIS logs in using the following credentials:

```<code>web.config setting (identity impersonate="false")
username   => "NT AUTHORITY\\IUSR"
domain     => "IIS APPPOOL"

web.config setting (identity impersonate="true")
username   => "NT AUTHORITY\\IUSR"
domain => "NT AUTHORITY"
</code>```

[15/11/2017] Update

It seems like it's failing on UserPrincipal.FindByIdentity as I built in basic logging so I can get a better understanding of where it's failing on the server.

The error I'm getting is "An operations error occurred.".

The settings in IIS of interest are as follows:

"Application Pools" Advanced Settings...

```<code>Enable 32-Bit Applications  = True
Identity                    = NetworkService
</code>```

And the Websites Authentication setting are as follows:

```<code>Anonymous Authentication    = Disabled
ASP.NET Impersonation       = Enabled
Basic Authentication        = Disabled
Forms Authentication        = Disabled
Windows Authentication      = Enabled
</code>```

[16/11/2017] Update

Turned off Impersonation in IIS and set the Identity to ApplicationPoolIdentity

Here are my values from the log file I created:

```<code>[2017-11-16 07:17:52 AM]    Windows username    => username (e.g. jdoe)
[2017-11-16 07:17:52 AM]    Domain              => IIS APPPOOL
[2017-11-16 07:21:18 AM]    Windows username    => username (e.g. jdoe)
[2017-11-16 07:21:18 AM]    Domain              => IIS APPPOOL
[2017-11-16 07:23:38 AM]    Windows username    => username (e.g. jdoe)
[2017-11-16 07:23:38 AM]    Domain              => IIS APPPOOL
</code>```

[16/11/2017] Solution

"Application Pools" Advanced Settings...

```<code>Enable 32-Bit Applications  = True
Identity                    = NetworkService
</code>```

And the Websites Authentication setting are as follows:

```<code>Anonymous Authentication    = Disabled
ASP.NET Impersonation       = Disabled
Basic Authentication        = Disabled
Forms Authentication        = Disabled
Windows Authentication      = Enabled
</code>```

Cheers,

Tim

答:
Enable Windows Authentication in your Local ISS.
ISS screenshot

This should solve the issue you are having with your local ISS.

Body:
I hope someone can help me with the following scenario, as I've been trolling the web for without success for a couple of days now.

The scenario I'm facing is how do I automatically bypass the login screen and go directly to the dashboard if the user exists in Active Directory (AD)?  If the user does not exist i.e. user does not have an Active Directory (AD) account redirect the user to a login page.

Attached is a picture to explain the process better.

If I run the ASP.NET MVC 4 web app using "IIS Express" the username and domain are correct, and I automatically get logged in because my credentials are correct for e.g:

username   => "username"
domain     => "domain"

But If I run the solution on my "Local IIS" the credentials are incorrect because IIS logs in using the following credentials:

web.config setting (identity impersonate="false")
username   => "NT AUTHORITY\\IUSR"
domain     => "IIS APPPOOL"

web.config setting (identity impersonate="true")
username   => "NT AUTHORITY\\IUSR"
domain => "NT AUTHORITY"

[15/11/2017] Update

It seems like it's failing on UserPrincipal.FindByIdentity as I built in basic logging so I can get a better understanding of where it's failing on the server.

The error I'm getting is "An operations error occurred.".

The settings in IIS of interest are as follows:

"Application Pools" Advanced Settings...

Enable 32-Bit Applications  = True
Identity                    = NetworkService

And the Websites Authentication setting are as follows:

Anonymous Authentication    = Disabled
ASP.NET Impersonation       = Enabled
Basic Authentication        = Disabled
Forms Authentication        = Disabled
Windows Authentication      = Enabled

[16/11/2017] Update

Turned off Impersonation in IIS and set the Identity to ApplicationPoolIdentity

Here are my values from the log file I created:

[2017-11-16 07:17:52 AM]    Windows username    => username (e.g. jdoe)
[2017-11-16 07:17:52 AM]    Domain              => IIS APPPOOL
[2017-11-16 07:21:18 AM]    Windows username    => username (e.g. jdoe)
[2017-11-16 07:21:18 AM]    Domain              => IIS APPPOOL
[2017-11-16 07:23:38 AM]    Windows username    => username (e.g. jdoe)
[2017-11-16 07:23:38 AM]    Domain              => IIS APPPOOL

[16/11/2017] Solution

"Application Pools" Advanced Settings...

Enable 32-Bit Applications  = True
Identity                    = NetworkService

And the Websites Authentication setting are as follows:

Anonymous Authentication    = Disabled
ASP.NET Impersonation       = Disabled
Basic Authentication        = Disabled
Forms Authentication        = Disabled
Windows Authentication      = Enabled

Cheers,

Tim


问:
In Android 7.0 appium launches the app but wont perform further actions
I am automating android native apps using appium. Appium is working fine across all devices which has versions less than 7.0, but when I run appium on version 7.0 or more, appium launches the app but wont perfom further actions(appium wont stop execution, it will freeze at that point after launching app).

Please refer below appium logs.

```<code>        disc='loginScreen_createAccountSelectorButton']","4e69a744-5030-426e-a666-539ec0dc6ef7"]
        [debug] [BaseDriver] Valid locator strategies for this request: xpath, id, class name, accessibility id, -android uiautomator
        [debug] [BaseDriver] Valid locator strategies for this request: xpath, id, class name, accessibility id, -android uiautomator
        [debug] [BaseDriver] Waiting up to 0 ms for condition
        [debug] [AndroidBootstrap] Sending command to android: {"cmd":"action","action":"find","params":{"strategy":"xpath","selector":"//android.widget.TextViewp[@conent-disc='loginScreen_createAccountSelectorButton']","context":"","multiple":false}}
        [debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"action","action":"find","params":{"strategy":"xpath","selector":"//android.widget.TextViewp[@conent-disc='loginScreen_createAccountSelectorButton']","context":"","multiple":false}}
        [debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type ACTION
        [debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command action: find
        [debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Finding '//android.widget.TextViewp[@conent-disc='loginScreen_createAccountSelectorButton']' using 'XPATH' with the contextId: '' multiple: false
</code>```

If you see last line of the log, appium trie's to find the element but and the appium server will not stop, it will be running for ever. Please help to make it run on the android devices which has version more than 7.0.

答:
In order to solve your issue, you need to update your Android 7.0 SDK. You can do it by navigating in Android Studio to Help => Check for Updates.

You can also install required version of SDK by navigating to SDK Manager and select the SDK from the list and install it.

Note:

I am able to execute tests on my Android 7.0 device effortlessly as I keep my Appium and Android up-to-date.

Body:
I am automating android native apps using appium. Appium is working fine across all devices which has versions less than 7.0, but when I run appium on version 7.0 or more, appium launches the app but wont perfom further actions(appium wont stop execution, it will freeze at that point after launching app).

Please refer below appium logs.

        disc='loginScreen_createAccountSelectorButton']","4e69a744-5030-426e-a666-539ec0dc6ef7"]
        [debug] [BaseDriver] Valid locator strategies for this request: xpath, id, class name, accessibility id, -android uiautomator
        [debug] [BaseDriver] Valid locator strategies for this request: xpath, id, class name, accessibility id, -android uiautomator
        [debug] [BaseDriver] Waiting up to 0 ms for condition
        [debug] [AndroidBootstrap] Sending command to android: {"cmd":"action","action":"find","params":{"strategy":"xpath","selector":"//android.widget.TextViewp[@conent-disc='loginScreen_createAccountSelectorButton']","context":"","multiple":false}}
        [debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"action","action":"find","params":{"strategy":"xpath","selector":"//android.widget.TextViewp[@conent-disc='loginScreen_createAccountSelectorButton']","context":"","multiple":false}}
        [debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type ACTION
        [debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command action: find
        [debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Finding '//android.widget.TextViewp[@conent-disc='loginScreen_createAccountSelectorButton']' using 'XPATH' with the contextId: '' multiple: false

If you see last line of the log, appium trie's to find the element but and the appium server will not stop, it will be running for ever. Please help to make it run on the android devices which has version more than 7.0.


问:
WordPress pages outside install directory
I have WordPress installed in a subdirectory and I'd like one WordPress page to appear as if it's on the root.

Eg.

/wordpress/mypage

To appear as:

/mypage

答:
Assuming you're on Apache, and you've got permalinks already working, you can use an .htaccess file in your document root to rewrite yoursite.com/wordpress/mypage to yoursite.com/mypage.

If you don't already have a .htaccess file in your document root, create one and put this in:

RewriteEngine on

RewriteRule ^mypage$ wordpress/mypage

I'm no .htaccess expert, but that should do the trick.


问:
NSIS - Compile with opcode re arranged to prevent access to source code
I am trying to reduce and make as difficult as possible the ability to access my source code after being compiled by NSIS. I have read that the only way to reduce the chance of unzipping is to modify the order of the opcodes in the Source\fileform.h from the source code and then Compile the new version.

This is a bit over my head. I was wondering if anyone has done this before and willing to post one they have done. (Or create one for me?)

Main reason for this is I have info that I encrypt using blow-fish within NSIS and do not want the chance oFf someone finding out what the encryption keys are. (Used for licencing the software) I understand noting is fool proof, but just want it as difficult as possible.

I know its asking a lot, but could really this.

Thanks!

答:
I don't believe there are any publicly available modified builds like that. And if there were and it got popular, the decompilers would just add support for it.

I have a complete step-by-step guide to building NSIS here.

If you know C/C++, Delphi or C# you could build your own private NSIS plug-in that handles the encryption details.

No matter what you do, somebody who knows how to use a debugger can easily set a breakpoint on the blow-fish plug-in and view your key. The only way around that is a custom plug-in or an external application that handles the cryptography internally...


问:
Angular 4 *ngFor current element value to increase and decrease
I'm making a little application in Angular 4, I'm displaying a table with some data, I wanna increase and decrease the current value by clicking DecreaseVal() and IncreaseVal() function, but it change all the value in the loop.

```<code><tr class="rem1" *ngFor="let hero of heroes">
   <td class="invert">
    <div class="quantity">
        <div class="quantity-select">
            <div class="entry minus" (click)="DecreaseVal()">&nbsp</div>
            <div class="entry value"><span>{{count}}</span></div>
            <div class="entry plus" (click)="IncreaseVal()"> </div>
        </div>
    </div>
  </td>
</tr>
</code>```

This is my component

```<code> count=1;
    DecreaseVal()
    {
    this.count=this.count>1?this.count-1:this.count;
    }
    IncreaseVal()
    {
     this.count=this.count<5?this.count+1:this.count;
    }
</code>```

答:
It happens because your count variable is global and doesn't belong to the Hero class. You need to tweak you code in the following way:

Declare new field in
hero.class.ts

count: number = 0;

Tweak your template component.html

```<code><tr class="rem1" *ngFor="let hero of heroes">
   <td class="invert">
    <div class="quantity">
        <div class="quantity-select">
            <div class="entry minus" (click)="DecreaseVal(hero)">&nbsp</div>
            <div class="entry value"><span>{{hero.count}}</span></div>
            <div class="entry plus" (click)="IncreaseVal(hero)"> </div>
        </div>
    </div>
  </td>
</tr>
</code>```

And now in component.ts

```<code>DecreaseVal(hero: Hero)
{
    if (hero.count > 1) {
       hero.count--;
    }
}

IncreaseVal(hero: Hero)
{
    if (hero.count < 5) {
       hero.count++;
    }
}
</code>```

UPD: Updated with suggestions and notes from Andrien Brunelat.

Body:
I'm making a little application in Angular 4, I'm displaying a table with some data, I wanna increase and decrease the current value by clicking DecreaseVal() and IncreaseVal() function, but it change all the value in the loop.

&nbsp

{{count}}

This is my component

 count=1;
    DecreaseVal()
    {
    this.count=this.count>1?this.count-1:this.count;
    }
    IncreaseVal()
    {
     this.count=this.count<5?this.count+1:this.count;
    }

Body:
It happens because your count variable is global and doesn't belong to the Hero class. You need to tweak you code in the following way:

Declare new field in
hero.class.ts

count: number = 0;

Tweak your template component.html

<tr class="rem1" *ngFor="let hero of heroes">
   <td class="invert">
    <div class="quantity">
        <div class="quantity-select">
            <div class="entry minus" (click)="DecreaseVal(hero)">&nbsp</div>
            <div class="entry value"><span>{{hero.count}}</span></div>
            <div class="entry plus" (click)="IncreaseVal(hero)">&nbsp;</div>
        </div>
    </div>
  </td>
</tr>

And now in component.ts

DecreaseVal(hero: Hero)
{
    if (hero.count > 1) {
       hero.count--;
    }
}

IncreaseVal(hero: Hero)
{
    if (hero.count < 5) {
       hero.count++;
    }
}

UPD: Updated with suggestions and notes from Andrien Brunelat.


问:
Multiple http pages on electron
I am using electron to convert my web app to desktop. I have two HTML pages that I would like the user to be able to access. Is there an elegant way to switch between pages via electron? Im thinking like a side panel or something similar. I have tried electron tabs and it was no good. </p>

答: Electron only provides a headless chrome environment to run your app in. There should be no difference between your web app and your electron app functionality wise.</p>

Title: Multiple http pages on electron


问:
How do I save Json output to a SQLite database in c#?
I'm trying to make an app in xamarin forms that gets information from bittrex then puts it into a model and then saves it to the local SQLite database.

Here is my code for saving things to the database:

```<code>    public class CoinsDatabase
{
    readonly SQLiteAsyncConnection database;

    public CoinsDatabase(string dbPath)
    {
        database = new SQLiteAsyncConnection(dbPath);
        database.CreateTableAsync<Coins>().Wait();
    }

    public Task<List<Coins>> GetCoinsAsync()
    {
        return database.Table<Coins>().ToListAsync();
    }

    public Task<Coins> GetCoinsAsync(int id)
    {
        return database.Table<Coins>().Where(i => i.CoinID == id).FirstOrDefaultAsync();
    }

    public Task<int> SaveCoinAsync(Coins coin)
    {
        if(coin.CoinID == 0){
            return database.InsertAsync(coin);
        } else {
            return database.UpdateAsync(coin);
        }
    }

    public Task<int> DeleteCoinAsync(Coins coin)
    {
        return database.DeleteAsync(coin);
    }
</code>```

Here is my code for getting the Json information and processing it:

```<code>async void Save_Clicked(object sender, System.EventArgs e)
    {
        if (CoinNameEntry.Text != null){
            var uri = new Uri("https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-" + CoinNameEntry.Text.ToLower());

            HttpClient httpClient = new HttpClient();

            var response = await httpClient.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                Coins coins = JsonConvert.DeserializeObject<Coin>(content);
                var coinItem = (Coins)coins["result"].ToObject<Coins>();
                await App.Database.SaveCoinAsync(coinItem);
                await Navigation.PopAsync();
            } else {
                await DisplayAlert("Alert", "An error occured getting the coininformation of " + CoinNameEntry.Text.ToUpper(), "OK");
            }

        } else {
            await DisplayAlert("Alert", "Please select a Coin first", "OK");
        }
    }
</code>```

And this is my Coins model:

```<code>    public class Coins
{
    public List<Coin> coins { get; set; }
}
public class Coin
{
    [PrimaryKey, AutoIncrement]
    public int CoinID { get; set; }
    public string CoinName { get; set; }
    public bool Notification { get; set; }
    public string MarketName { get; set; }
    public double High { get; set; }
    public double Low { get; set; }
    public double Volume { get; set; }
    public double Last { get; set; }
    public double BaseVolume { get; set; }
    public bool TimeStamp { get; set; }
    public double Bid { get; set; }
    public double Ask { get; set; }
    public int OpenBuyOrders { get; set; }
    public int OpenSellOrders { get; set; }
    public double PrevDay { get; set; }
    public string Created { get; set; }

}
</code>```

I have been trying to get this working for a week now and I was wondering if someone knows what i do wrong or if someone has tips on how to fix this problem.

Please keep in mind that im a beginner with xamarin and C# :)

答:
OK, try this: First, add a JsonProperty to your coins class to map the result to the correct property:

```<code>public class Coins
{
    [JsonProperty("result")]
    public List<Coin> coins { get; set; }
}
</code>```

Then replace the following two lines in your code:

```<code>Coins coins = JsonConvert.DeserializeObject<Coin>(content);
var coinItem = (Coins)coins["result"].ToObject<Coins>();
</code>```

with

```<code>Coins coins = JsonConvert.DeserializeObject<Coins>(content);
var coinItem = coins.coins[0];
</code>```

Please note that this will give you the first of the coins in the list - change the index or use LINQ if you want to retrieve a coin from somewhere else in the list.

I also very much suspect that your SQLite code won't do what you want. Currently all your methods act on a Coins object rather than a Coin object. Try changing the methods to

```<code>readonly SQLiteAsyncConnection database;

public CoinsDatabase(string dbPath)
{
    database = new SQLiteAsyncConnection(dbPath);
    database.CreateTableAsync<Coin>().Wait();
}

public Task<List<Coin>> GetCoinsAsync()
{
    return database.Table<Coin>().ToListAsync();
}

public Task<Coin> GetCoinsAsync(int id)
{
    return database.Table<Coin>().Where(i => i.CoinID == id).FirstOrDefaultAsync();
}

public Task<int> SaveCoinAsync(Coin coin)
{
    if(coin.CoinID == 0){
        return database.InsertAsync(coin);
    } else {
        return database.UpdateAsync(coin);
    }
}

public Task<int> DeleteCoinAsync(Coin coin)
{
    return database.DeleteAsync(coin);
}
</code>```

Body:
I'm trying to make an app in xamarin forms that gets information from bittrex then puts it into a model and then saves it to the local SQLite database.

Here is my code for saving things to the database:

    public class CoinsDatabase
{
    readonly SQLiteAsyncConnection database;

    public CoinsDatabase(string dbPath)
    {
        database = new SQLiteAsyncConnection(dbPath);
        database.CreateTableAsync<Coins>().Wait();
    }

    public Task<List<Coins>> GetCoinsAsync()
    {
        return database.Table<Coins>().ToListAsync();
    }

    public Task<Coins> GetCoinsAsync(int id)
    {
        return database.Table<Coins>().Where(i => i.CoinID == id).FirstOrDefaultAsync();
    }

    public Task<int> SaveCoinAsync(Coins coin)
    {
        if(coin.CoinID == 0){
            return database.InsertAsync(coin);
        } else {
            return database.UpdateAsync(coin);
        }
    }

    public Task<int> DeleteCoinAsync(Coins coin)
    {
        return database.DeleteAsync(coin);
    }

Here is my code for getting the Json information and processing it:

async void Save_Clicked(object sender, System.EventArgs e)
    {
        if (CoinNameEntry.Text != null){
            var uri = new Uri("https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-" + CoinNameEntry.Text.ToLower());

            HttpClient httpClient = new HttpClient();

            var response = await httpClient.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                Coins coins = JsonConvert.DeserializeObject<Coin>(content);
                var coinItem = (Coins)coins["result"].ToObject<Coins>();
                await App.Database.SaveCoinAsync(coinItem);
                await Navigation.PopAsync();
            } else {
                await DisplayAlert("Alert", "An error occured getting the coininformation of " + CoinNameEntry.Text.ToUpper(), "OK");
            }

        } else {
            await DisplayAlert("Alert", "Please select a Coin first", "OK");
        }
    }

And this is my Coins model:

    public class Coins
{
    public List<Coin> coins { get; set; }
}
public class Coin
{
    [PrimaryKey, AutoIncrement]
    public int CoinID { get; set; }
    public string CoinName { get; set; }
    public bool Notification { get; set; }
    public string MarketName { get; set; }
    public double High { get; set; }
    public double Low { get; set; }
    public double Volume { get; set; }
    public double Last { get; set; }
    public double BaseVolume { get; set; }
    public bool TimeStamp { get; set; }
    public double Bid { get; set; }
    public double Ask { get; set; }
    public int OpenBuyOrders { get; set; }
    public int OpenSellOrders { get; set; }
    public double PrevDay { get; set; }
    public string Created { get; set; }

}

I have been trying to get this working for a week now and I was wondering if someone knows what i do wrong or if someone has tips on how to fix this problem.

Please keep in mind that im a beginner with xamarin and C# :)

Body:
OK, try this: First, add a JsonProperty to your coins class to map the result to the correct property:

public class Coins
{
    [JsonProperty("result")]
    public List<Coin> coins { get; set; }
}

Then replace the following two lines in your code:

Coins coins = JsonConvert.DeserializeObject<Coin>(content);
var coinItem = (Coins)coins["result"].ToObject<Coins>();

with

Coins coins = JsonConvert.DeserializeObject<Coins>(content);
var coinItem = coins.coins[0];

Please note that this will give you the first of the coins in the list - change the index or use LINQ if you want to retrieve a coin from somewhere else in the list.

I also very much suspect that your SQLite code won't do what you want. Currently all your methods act on a Coins object rather than a Coin object. Try changing the methods to

readonly SQLiteAsyncConnection database;

public CoinsDatabase(string dbPath)
{
    database = new SQLiteAsyncConnection(dbPath);
    database.CreateTableAsync<Coin>().Wait();
}

public Task<List<Coin>> GetCoinsAsync()
{
    return database.Table<Coin>().ToListAsync();
}

public Task<Coin> GetCoinsAsync(int id)
{
    return database.Table<Coin>().Where(i => i.CoinID == id).FirstOrDefaultAsync();
}

public Task<int> SaveCoinAsync(Coin coin)
{
    if(coin.CoinID == 0){
        return database.InsertAsync(coin);
    } else {
        return database.UpdateAsync(coin);
    }
}

public Task<int> DeleteCoinAsync(Coin coin)
{
    return database.DeleteAsync(coin);
}


问:
"Paste" string variable in excel VBA instead of the contents of clipboard?
I have a string variable that contains an HTML table in excel VBA. I know that when this table is stored in the clipboard and I invoke .PasteSpecial, Excel does some nifty preprocessing and fills the cells out in the current sheet the same way as they appear in the table.

However, if I simply set the .Value of a cell/range to the string variable, no such preprocessing takes place and the entire string, HTML tags and all, are dumped into the cell. I want the former result, but I cannot use the clipboard because it is being used by this application elsewhere and there is no guarantee I would not overwrite critical data. It is also being used asynchronously so I cannot simply save the current contents of the clipboard, use the clipboard, and then restore the previous contents of the clipboard.

So, is there any way to get the "pasting preprocessing" to occur when setting the value for a range with a formatted string?

答:
I can't think of anyway to invoke Excel's preprocessor without the clipboard.  For parsing, you may want to check out the Split function.  Here's an example.</p>

```<code>Sub ParseTable()

    Dim sHtmlTable As String
    Dim vaTable As Variant
    Dim i As Long

    Const STDSTART = "<td"
    Const STDEND = "</td"

    sHtmlTable = "<table border=""1""><tr><td>row 1, cell 1</td><td>row 1, cell 2</td></tr><tr><td>row 2, cell 1</td><td>row 2, cell 2</td></tr></table>"

    vaTable = Split(sHtmlTable, ">")

    For i = LBound(vaTable) To UBound(vaTable)
        If vaTable(i) = STDSTART Then
            Debug.Print Replace(vaTable(i + 1), STDEND, "")
        End If
    Next i

End Sub
</code>```

Body:
I can't think of anyway to invoke Excel's preprocessor without the clipboard.  For parsing, you may want to check out the Split function.  Here's an example.

Sub ParseTable()

    Dim sHtmlTable As String
    Dim vaTable As Variant
    Dim i As Long

    Const STDSTART = "<td"
    Const STDEND = "</td"

    sHtmlTable = "<table border=""1""><tr><td>row 1, cell 1</td><td>row 1, cell 2</td></tr><tr><td>row 2, cell 1</td><td>row 2, cell 2</td></tr></table>"

    vaTable = Split(sHtmlTable, ">")

    For i = LBound(vaTable) To UBound(vaTable)
        If vaTable(i) = STDSTART Then
            Debug.Print Replace(vaTable(i + 1), STDEND, "")
        End If
    Next i

End Sub


问:
How to select list in pandas dataframe
I have a dataframe which contains list item in a single cell.

For example, data frame 'home'

```<code>a       b                  c
'book'  ['living room']   ['cat','foo']
'shoes' ['door']          ['man','woman']
'cook'  []                ['knife']
</code>```

The question is how do I select the 'cook' based on b == [] (empty list).

like

```<code>home.loc[home.b==[]]
</code>```

BTW, I created the list using lambda x : [] function.

答:
Try this:

```<code>home.loc[home['b'].str.len()==0]
</code>```

UPDATE:

```<code>In [313]: d
Out[313]:
       a              b             c
0   book  [living room]    [cat, foo]
1  shoes         [door]  [man, woman]
2   cook             []       [knife]

In [314]: lst = ['cat','foo']

In [315]: d.loc[d['c'].astype(str) == str(lst)]
Out[315]:
      a              b           c
0  book  [living room]  [cat, foo]
</code>```

Title: How to select list in pandas dataframe

Body:
I have a dataframe which contains list item in a single cell.

For example, data frame 'home'

a       b                  c
'book'  ['living room']   ['cat','foo']
'shoes' ['door']          ['man','woman']
'cook'  []                ['knife']

The question is how do I select the 'cook' based on b == [] (empty list).

like

home.loc[home.b==[]]

BTW, I created the list using lambda x : [] function.

Body:
Try this:

home.loc[home['b'].str.len()==0]

UPDATE:

In [313]: d
Out[313]:
       a              b             c
0   book  [living room]    [cat, foo]
1  shoes         [door]  [man, woman]
2   cook             []       [knife]

In [314]: lst = ['cat','foo']

In [315]: d.loc[d['c'].astype(str) == str(lst)]
Out[315]:
      a              b           c
0  book  [living room]  [cat, foo]


答:
The left hand of the list comprehension accepts any Haskell expression, so we can write the if-then-else in the left hand of the list comprehension and omit the i < 10 condition on the right hand:

```<code>concat [(""++show i)++<b>if i < 10 then "   " else "  "</b> | i &lt- [1..n]]++"\n"</code>```

For n = 15, this then produces:

```<code>Prelude> concat [(""++show i)++if i < 10 then "   " else "  " | i <- [1..n]]++"\n"
"1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  \n"
</code>```

We can also remove the ""++ part on the left side of the list comprehension, since this is bascially a no operation:

```<code>concat [show i ++ if i < 10 then "   " else "  " | i &lt- [1..n]] ++ "\n"</code>```

The above is however not very elegant: if i = 123, then we still will run into trouble. We can calculate the length of the show, calculate 4-l (with l the length), and add this as extra spacing. For instance:

```<code>concat [<b>s</b> ++ <b>replicate (4-length s) ' '</b> | i &lt- [1..n], <b>let s = show i</b>] ++ "\n"</code>```

There are also some more dedicated formatting and joining functions, but since the exercise is probably to get familier with lists, I think this is out of scope here.

Like @4castle says, we can use for instance printf:

```<code>import Text.Printf(printf)

concatMap (printf "%-4d") [1..n] ++ "\n"
</code>```

Title: Haskell if else list comprehension

Body:
I'm trying to print out a board in the right way, like this:

  1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18
 1.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
 2.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
 3.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
 4.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
 5.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
 6.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
 7.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
 8.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
 9.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
10.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
11.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
12.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
13.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
14.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
15.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
16.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
17.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .
18.   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .

I have the list comprehension here

 ((concat [(""++show i)++"   " | i <- [1..n], i<10])++"\n")

I can get the 9 first numbers correctly, but the problem comes when i would like to put an else statement in my comprehension. I can't seem to know how to do that. So to make my self extra clear, i would like to do the same thing with the double digits but the only difference will be that i want two spaces instead of three between each double digit.

Body:
The left hand of the list comprehension accepts any Haskell expression, so we can write the if-then-else in the left hand of the list comprehension and omit the i < 10 condition on the right hand:

concat [(""++show i)++if i < 10 then "   " else "  " | i &lt- [1..n]]++"\n"

For n = 15, this then produces:

Prelude> concat [(""++show i)++if i < 10 then "   " else "  " | i <- [1..n]]++"\n"
"1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  \n"

We can also remove the ""++ part on the left side of the list comprehension, since this is bascially a no operation:

concat [show i ++ if i < 10 then "   " else "  " | i &lt- [1..n]] ++ "\n"

The above is however not very elegant: if i = 123, then we still will run into trouble. We can calculate the length of the show, calculate 4-l (with l the length), and add this as extra spacing. For instance:

concat [s ++ replicate (4-length s) ' ' | i &lt- [1..n], let s = show i] ++ "\n"

There are also some more dedicated formatting and joining functions, but since the exercise is probably to get familier with lists, I think this is out of scope here.

Like @4castle says, we can use for instance printf:

import Text.Printf(printf)

concatMap (printf "%-4d") [1..n] ++ "\n"