问:
Use SUBSTRING AND CHARINDEX to get last complete word in field
I have a field in my database that I plan to truncate, for reporting purposes, to 50 characters with the statement below.

```<code>SELECT (CASE WHEN (LEN(Notes) > 50) THEN SUBSTRING(Notes, 0, 50) + '...' WHEN (LEN(Notes) < 50) THEN SUBSTRING(Notes, 0, LEN(Notes)) + '...' ELSE 'NO NOTES WERE ENTERED' END) AS Notes FROM MyTable
</code>```

This works great, however, I would like to complete the last word in the notes field so that a word isn't cut off so I would like to use CHARINDEX, SUBSTRING, REVERSE and possibly the RIGHT function to return the last complete word that is part of a string roughly 50 characters long.

I have experimented and I'm not having much luck.

Any help would be appreciated.

答:
In case you don't want to exceed the character limit you could have it like this:</p>

```<code>DECLARE @Table TABLE
(
  String nvarchar(100)
)

DECLARE
  @Size int             = 25

INSERT @Table SELECT 'Lorem ipsum dolor sit ame'
INSERT @Table SELECT 'Lorem ipsum dolor sit ame tas'
INSERT @Table SELECT 'Lorem ipsum dolor sit am asd'
INSERT @Table SELECT 'Lorem ipsum dolor sita am'
INSERT @Table SELECT 'Lorem ipsum dolor sita a amet, consectetur adipiscing elit,'
INSERT @Table SELECT 'Lorem ipsum dolor sita'
INSERT @Table SELECT 'Lorem ipsum dolor sita asamet, consectetur adipiscing elit,'

SELECT
  LEN(R.LimitTruncation) AS LimitTruncationLen,
  R.LimitTruncation,
  LEN(String) AS StringLen,
  R.String
FROM
(
  SELECT
    String,
    --This is the main part
    CASE
      WHEN LEN(String) <= @Size THEN String
      WHEN CHARINDEX(' ', String, @Size) = @Size OR CHARINDEX(' ', String, @Size) = @Size + 1 THEN RTRIM(LEFT(String, @Size))
      ELSE REVERSE(SUBSTRING(REVERSE(LEFT(String, @Size)), CHARINDEX(' ', REVERSE(LEFT(String, @Size))), @Size))
    END AS LimitTruncation
  FROM
    @Table
) R
</code>```

Body:
I have a field in my database that I plan to truncate, for reporting purposes, to 50 characters with the statement below.

SELECT (CASE WHEN (LEN(Notes) > 50) THEN SUBSTRING(Notes, 0, 50) + '...' WHEN (LEN(Notes) < 50) THEN SUBSTRING(Notes, 0, LEN(Notes)) + '...' ELSE 'NO NOTES WERE ENTERED' END) AS Notes FROM MyTable

This works great, however, I would like to complete the last word in the notes field so that a word isn't cut off so I would like to use CHARINDEX, SUBSTRING, REVERSE and possibly the RIGHT function to return the last complete word that is part of a string roughly 50 characters long.

I have experimented and I'm not having much luck.

Any help would be appreciated.

Body:
In case you don't want to exceed the character limit you could have it like this:

DECLARE @Table TABLE
(
  String nvarchar(100)
)

DECLARE
  @Size int             = 25

INSERT @Table SELECT 'Lorem ipsum dolor sit ame'
INSERT @Table SELECT 'Lorem ipsum dolor sit ame tas'
INSERT @Table SELECT 'Lorem ipsum dolor sit am asd'
INSERT @Table SELECT 'Lorem ipsum dolor sita am'
INSERT @Table SELECT 'Lorem ipsum dolor sita a amet, consectetur adipiscing elit,'
INSERT @Table SELECT 'Lorem ipsum dolor sita'
INSERT @Table SELECT 'Lorem ipsum dolor sita asamet, consectetur adipiscing elit,'

SELECT
  LEN(R.LimitTruncation) AS LimitTruncationLen,
  R.LimitTruncation,
  LEN(String) AS StringLen,
  R.String
FROM
(
  SELECT
    String,
    --This is the main part
    CASE
      WHEN LEN(String) <= @Size THEN String
      WHEN CHARINDEX(' ', String, @Size) = @Size OR CHARINDEX(' ', String, @Size) = @Size + 1 THEN RTRIM(LEFT(String, @Size))
      ELSE REVERSE(SUBSTRING(REVERSE(LEFT(String, @Size)), CHARINDEX(' ', REVERSE(LEFT(String, @Size))), @Size))
    END AS LimitTruncation
  FROM
    @Table
) R


来源: stackexchange

问:
Spacing between columns in a table
I have a big problem with the spacing of columns in a table.
Here's what I'd like to get, spacing only between :

Not working with margin, padding  or border:

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td></td>
<td></td>
<td></td>
<td></td></code>```

Not working with border-spacing:

And if use first-child and last-child, same problem as previous image.

Solution I found, but really dirty:

.spacer {
  width: 15px;
  height: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td></td>
<div id="spacer"></div>
<td></td>
<div id="spacer"></div>
<td></td>
<div id="spacer"></div>
<td></td></code>```

答:
Use
 and margin instead.

.table {
  width: 100%;
  height: 500px;
}

.row {
  width: 100%;
  height: 100%;
}

.cell {
  float: left; /* make the divs sit next to each other like cells */
  background: red;
  width: calc(25% - 12px); /* 4 cells so 25% but minus 12 because we have 3 x 15px margins divided by 4 cells which is 11.25 but decimals can cause issues in some browsers */
  height: 100%;
  margin-left: 15px;
}

.cell:first-child {
  margin-left: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table">
  <div class="row">
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Spacing between columns in a table

Body:
I have a big problem with the spacing of columns in a table.
Here's what I'd like to get, spacing only between :

Not working with margin, padding  or border:

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

Not working with border-spacing:

And if use first-child and last-child, same problem as previous image.

Solution I found, but really dirty:

.spacer {
  width: 15px;
  height: 15px;
}

Body:
Use <div> and margin instead.

.table {
  width: 100%;
  height: 500px;
}

.row {
  width: 100%;
  height: 100%;
}

.cell {
  float: left; /* make the divs sit next to each other like cells */
  background: red;
  width: calc(25% - 12px); /* 4 cells so 25% but minus 12 because we have 3 x 15px margins divided by 4 cells which is 11.25 but decimals can cause issues in some browsers */
  height: 100%;
  margin-left: 15px;
}

.cell:first-child {
  margin-left: 0;
}

<div class="table">
  <div class="row">
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
  </div>
</div>


问:
Is it possible to read results of the XmlSerializer being sent by HTTPClient?
I am using an extension method to post xml using the HTTPClient which works great.

My question: Is it possible to read, log, or display the results of the XmlSerializer data that is being sent/posted ?

```<code>    public static class HttpExtensions  {
    public static Task<HttpResponseMessage> PostAsXmlWithSerializerAsync<T>(this HttpClient client, string requestUri, T value)
    {
        return client.PostAsync(requestUri
                                , value
                                , new XmlMediaTypeFormatter { UseXmlSerializer = true }
                                );
    }
}
</code>```

答:
Yes, you can.
Download and install Fiddler , then filter your requestUri , you can monitor all transferring data such you serialized xml.

Body:
I am using an extension method to post xml using the HTTPClient which works great.

My question: Is it possible to read, log, or display the results of the XmlSerializer data that is being sent/posted ?

    public static class HttpExtensions  {
    public static Task<HttpResponseMessage> PostAsXmlWithSerializerAsync<T>(this HttpClient client, string requestUri, T value)
    {
        return client.PostAsync(requestUri
                                , value
                                , new XmlMediaTypeFormatter { UseXmlSerializer = true }
                                );
    }
}


问:
OutOfMemoryException when using SQL Filestream
I'm trying to upload a zip file which is around 600 MB to SQL 2008 FILESTREAM table and I get the OutOfMemoryException. I'm using the SqlFileStream class to upload the file (as described in this tutorial - http://www.aghausman.net/dotnet/saving-and-retrieving-file-using-filestream-sql-server-2008.html). I have a 32-bit Vista machine with 4GB ram if that matters and I'm using VS 2010, Entity Framework 4.

Here's my code snippet -

```<code>public static void AddItem(RepositoryFile repository)
    {
        var contents = repository.Data; // I get the exception at this line.
        repository.Data = System.Text.Encoding.ASCII.GetBytes("0x00");

        using (var scope = new TransactionScope())
        {
            using (var db = new MyEntities())
            {
                db.RepositoryTable.AddObject(repository);
                db.SaveChanges();
            }

            using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            using (var cmd = new SqlCommand("SELECT Data.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM dbo.RepositoryTable", con))
            {
                cmd.Connection.Open();
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var path = reader.GetString(0);
                        var transactionContext = reader.GetSqlBytes(1).Buffer;
                        var fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write);

                        fileStream.Write(contents, 0, contents.Length);
                        fileStream.Close();
                    }
                }
            }

            scope.Complete();
        }
    }
</code>```

How do I upload the file without any errors?

Thanks!

答:
I figured out the issue. Here's my code -</p>

```<code>private void AddFile()
    {
        if (!fupFile.HasFile)
        {
            lblMessage.Text = "Please select a file.";
            return;
        }

        var data = new byte[(int) fupFile.FileContent.Length];
        fupFile.FileContent.Read(data, 0, data.Length);

        if (fupFile.FileContent.Length > 0)
        {
            var repositoryFile = new Repository
                                     {
                                         ID = Guid.NewGuid(),
                                         Name = Path.GetFileName(fupFile.PostedFile.FileName),
                                         Data = System.Text.Encoding.ASCII.GetBytes("0x00")
                                     };

            RepositoryController.AddItem(repositoryFile, data); // Calling DAL class.
        }
    }

// DAL method
public static void AddItem(RepositoryFile repository, byte[] data)
{
    using (var scope = new TransactionScope())
    {
        using (var db = new MyEntities()) // DBContext
        {
            db.RepositoryTable.AddObject(repository);
            db.SaveChanges();
        }

        using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
        using (var cmd = new SqlCommand(string.Format("SELECT Data.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM dbo.RepositoryTable WHERE ID='{0}'", repository.ID), con)) // "Data" is the column name which has the FILESTREAM. Data.PathName() gives me the local path to the file.
        {
            cmd.Connection.Open();
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var path = reader.GetString(0);
                    var transactionContext = reader.GetSqlBytes(1).Buffer;
                    var fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write);

                    fileStream.Write(contents, 0, contents.Length); //Write contents to the file.
                    fileStream.Close();
                }
            }
        }

        scope.Complete();
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to upload a zip file which is around 600 MB to SQL 2008 FILESTREAM table and I get the OutOfMemoryException. I'm using the SqlFileStream class to upload the file (as described in this tutorial - http://www.aghausman.net/dotnet/saving-and-retrieving-file-using-filestream-sql-server-2008.html). I have a 32-bit Vista machine with 4GB ram if that matters and I'm using VS 2010, Entity Framework 4.

Here's my code snippet -

public static void AddItem(RepositoryFile repository)
    {
        var contents = repository.Data; // I get the exception at this line.
        repository.Data = System.Text.Encoding.ASCII.GetBytes("0x00");

        using (var scope = new TransactionScope())
        {
            using (var db = new MyEntities())
            {
                db.RepositoryTable.AddObject(repository);
                db.SaveChanges();
            }

            using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            using (var cmd = new SqlCommand("SELECT Data.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM dbo.RepositoryTable", con))
            {
                cmd.Connection.Open();
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var path = reader.GetString(0);
                        var transactionContext = reader.GetSqlBytes(1).Buffer;
                        var fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write);

                        fileStream.Write(contents, 0, contents.Length);
                        fileStream.Close();
                    }
                }
            }

            scope.Complete();
        }
    }

How do I upload the file without any errors?

Thanks!

Body:
I figured out the issue. Here's my code -

private void AddFile()
    {
        if (!fupFile.HasFile)
        {
            lblMessage.Text = "Please select a file.";
            return;
        }

        var data = new byte[(int) fupFile.FileContent.Length];
        fupFile.FileContent.Read(data, 0, data.Length);

        if (fupFile.FileContent.Length > 0)
        {
            var repositoryFile = new Repository
                                     {
                                         ID = Guid.NewGuid(),
                                         Name = Path.GetFileName(fupFile.PostedFile.FileName),
                                         Data = System.Text.Encoding.ASCII.GetBytes("0x00")
                                     };

            RepositoryController.AddItem(repositoryFile, data); // Calling DAL class.
        }
    }

// DAL method
public static void AddItem(RepositoryFile repository, byte[] data)
{
    using (var scope = new TransactionScope())
    {
        using (var db = new MyEntities()) // DBContext
        {
            db.RepositoryTable.AddObject(repository);
            db.SaveChanges();
        }

        using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
        using (var cmd = new SqlCommand(string.Format("SELECT Data.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM dbo.RepositoryTable WHERE ID='{0}'", repository.ID), con)) // "Data" is the column name which has the FILESTREAM. Data.PathName() gives me the local path to the file.
        {
            cmd.Connection.Open();
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var path = reader.GetString(0);
                    var transactionContext = reader.GetSqlBytes(1).Buffer;
                    var fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write);

                    fileStream.Write(contents, 0, contents.Length); //Write contents to the file.
                    fileStream.Close();
                }
            }
        }

        scope.Complete();
    }
}


问:
On iPhone, Vimeo Javascript API .play() function doesn't work until the video has been played
I'm using SwipeView (http://cubiq.org/swipeview) to create a swipeable slideshow on touchscreen devices. This is simple enough with images, but I want to include a Vimeo video in the slideshow as well. Unfortunately, because the iFrame captures your swipe input for itself (I believe this is what's happening at least), once you've arrived at the video player slide you can no longer swipe away from it unless you tap on the pagination. This isn't acceptable.

My solution was to hide the video somewhere on the page (using display: none; or height: 0; or whatever works) and use an image in the slideshow with a click event that triggers the video to play. Even if the video is hidden, when it plays it should go fullscreen and play (on iPhone, at least).

This technique is working fine when I test it on my desktop browser, but it's behaving strangely on the iPhone. For testing purposes, the video is being displayed underneath the slideshow. If I load the page and tap on the slide, it does nothing. However, if I play the video by tapping the actual video player, once the video has been closed I can play the video again by tapping the slide. Basically, once the video is played via the player I can play the video via the API but not without using the player once first.

Here is my code:

```<code>// Append the "hidden" video player to the page
$('.slider-container').append("<div class='mobile-video-slide'><iframe id='slideshow-player' src='//player.vimeo.com/video/81295681?title=0&byline=0&portrait=0&color=8bd4ee&api=1&player_id=slideshow-player' width='500' height='281' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>");

// Get the player object
var iframe = $('#slideshow-player')[0],
    player = $f(iframe);

// When the video is ready
player.addEvent('ready', function() {
    // Add the click event to the slide
    $('#play-video').on('click', function() {
        // Play the video
        player.api('play');

        // Don't jump the page
        return false;
    });
});
</code>```

I have determined through testing that the player.ready event is working properly, and that the image's click event is working properly. The problem seems to lie entirely in the player.api('play') call. Any help, or an alternate method of accomplishing this would be appreciated.

答:
Some browser forbid to trigger the "play" via js in the beginning. There has to be real user interaction to play the video.

However, if you want to put the vimeo video in a slider what you can do is:

apply a image with "play button" on top of the video

set "opacity: 0" to the iframe and make it exactly the size&position of the "play button" (iframe have to be "allowfullscreen")

once user trigger the video play for the first time. Make the iframe to normal size you want and let vimeo player.js take control.

In this case, user have to click the "play button" to trigger the video

Body:
I'm using SwipeView (http://cubiq.org/swipeview) to create a swipeable slideshow on touchscreen devices. This is simple enough with images, but I want to include a Vimeo video in the slideshow as well. Unfortunately, because the iFrame captures your swipe input for itself (I believe this is what's happening at least), once you've arrived at the video player slide you can no longer swipe away from it unless you tap on the pagination. This isn't acceptable.

My solution was to hide the video somewhere on the page (using display: none; or height: 0; or whatever works) and use an image in the slideshow with a click event that triggers the video to play. Even if the video is hidden, when it plays it should go fullscreen and play (on iPhone, at least).

This technique is working fine when I test it on my desktop browser, but it's behaving strangely on the iPhone. For testing purposes, the video is being displayed underneath the slideshow. If I load the page and tap on the slide, it does nothing. However, if I play the video by tapping the actual video player, once the video has been closed I can play the video again by tapping the slide. Basically, once the video is played via the player I can play the video via the API but not without using the player once first.

Here is my code:

// Append the "hidden" video player to the page
$('.slider-container').append("

");

// Get the player object
var iframe = $('#slideshow-player')[0],
    player = $f(iframe);

// When the video is ready
player.addEvent('ready', function() {
    // Add the click event to the slide
    $('#play-video').on('click', function() {
        // Play the video
        player.api('play');

        // Don't jump the page
        return false;
    });
});

I have determined through testing that the player.ready event is working properly, and that the image's click event is working properly. The problem seems to lie entirely in the player.api('play') call. Any help, or an alternate method of accomplishing this would be appreciated.


问:
How to change UITableViewRowAction title color?
Am using UITableViewRowAction in "editActionsForRowAtIndexPath" method. I can change the backgroundcolor of UITableViewRowAction, but am not able to change the title color. But I would like to change the color of the UITableViewRowAction. Any inputs on this regard will be appreciable.</p>

答:
You can add these two functions in your UITableViewCell subclass and call the setActionButtonsTitleColor function to set action buttons' title color.

```<code>func setActionButtonsTitleColor(color: UIColor) {
  let actionButtons: [UIButton] = self.getActionButtons()

  for actionButton in actionButtons {
    actionButton.setTitleColor(color, for: .normal)
  }
}

func getActionButtons() -> [UIButton] {
  let actionButtons: [UIButton] = self.subviews.map {
    (view: UIView) -> [UIView] in
    return view.subviews
  }
  .joined()
  .filter {
    (view: UIView) -> Bool in
    return String(describing: view).contains("UITableViewCellActionButton")
  }.flatMap {
    (view: UIView) -> UIButton? in
    return view as? UIButton
  }

  return actionButtons
}
</code>```

Body:
You can add these two functions in your UITableViewCell subclass and call the setActionButtonsTitleColor function to set action buttons' title color.

func setActionButtonsTitleColor(color: UIColor) {
  let actionButtons: [UIButton] = self.getActionButtons()

  for actionButton in actionButtons {
    actionButton.setTitleColor(color, for: .normal)
  }
}

func getActionButtons() -> [UIButton] {
  let actionButtons: [UIButton] = self.subviews.map {
    (view: UIView) -> [UIView] in
    return view.subviews
  }
  .joined()
  .filter {
    (view: UIView) -> Bool in
    return String(describing: view).contains("UITableViewCellActionButton")
  }.flatMap {
    (view: UIView) -> UIButton? in
    return view as? UIButton
  }

  return actionButtons
}


问:
How to fix the Conquer step of this iterative quicksort implementation following Khan Academy's example?
For educational purposes I am trying to learn the quick sort algorithm. Instead of checking out an implementation on the web or trying to implement directly from the pseudocode on wikipedia, I am trying a "hard way" approach.

I watched this lecture from CS50 https://www.youtube.com/watch?v=aQiWF4E8flQ&t=305s in order to understand how the numbers move while being "quick sorted". My implementation, which I will show bellow, works perfectly for the example provided on the video. The example on the video of an initial unsorted array is this:

That's my code in Python 3:

```<code>len_seq = int(input())

print("len_seq",len_seq)

seq_in = list(map(int,(input()).split()))

print("seq_in",seq_in)

def my_quick_sort(seq):

    wall_index = 0

    pivot_corect_final_index_list = []

    while wall_index<len_seq:

        pivot = seq[-1]
        print("pivot",pivot)

        print("wall_index",wall_index)

        for i in range(wall_index,len_seq):
            print ("seq[i]",seq[i])
            if seq[i]<pivot:
                print("before inside swap,", seq)
                seq[wall_index],seq[i]=seq[i],seq[wall_index]
                print("after inside swap,", seq)
                wall_index = wall_index + 1
                print ("wall_index",wall_index)

        print("before outside swap,", seq)

        seq[wall_index],seq[-1]=seq[-1],seq[wall_index]
        print("after outside swap,", seq)

        pivot_corect_final_index = wall_index
        print ("pivot correct final index",pivot_corect_final_index)

        pivot_corect_final_index_list.append(pivot_corect_final_index)
        print ("pivot_corect_final_index_list",pivot_corect_final_index_list)

        wall_index = wall_index + 1
        print ("wall_index",wall_index)

    return seq

print(my_quick_sort(seq_in))
</code>```

To use harvard's CS50 example in my code you need to input this:

```<code>9
6 5 1 3 8 4 7 9 2
</code>```

The algorithm works fine and returns the correct output:

```<code>[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

Continuing my study, I tried to implement Khan Academy's example: https://www.khanacademy.org/computing/computer-science/algorithms/quick-sort/a/overview-of-quicksort

The unsorted list in this case is:

```<code>[9, 7, 5, 11, 12, 2, 14, 3, 10, 6]
</code>```

You need to input the following in my code in order to run it:

```<code>10
9 7 5 11 12 2 14 3 10 6
</code>```

Differently from the Harvard example, in this case my implementation does not work perfectly. It returns:

```<code>[5, 2, 3, 6, 7, 9, 10, 11, 12, 14]
</code>```

As you see, all the numbers that I treated as pivots end in the correct position. However, some numbers behind the pivots are not right.

Reading khan academy's article it seems that my implementation is right on the partition step. However, it is not right on the conquer step. I am trying to avoid looking to a final solution. I am trying to improve what I have build so far. Not sure if this is the best method, but that's what I am trying right now.

How can I fix the conquer step? Is it necessary to introduce a recursive approach? How can I do that inside my iterative process going on?
And should that step be introduced after successfully treating each pivot?

Thanks for the patience of reading this long post.

答:
Can't comment, not enough reputation.

In the first pass of your algorithm, you correctly place all elements smaller than the pivot to the left of the pivot. However, since your value of wall_index increases (e.g. from 0 to 1), you ignore the leftmost element with index 0 (it might not be in the correct position, so it should not be ignored).

In the Khan academy test case, the number 5 gets placed at the leftmost index in the first pass, and then gets ignored by subsequent passes, thus it gets stuck on the left. Similarly, trying this modification of the harvard example

```<code>9
6 5 1 3 8 4 7 2 9
</code>```

yields

```<code>[6, 5, 1, 3, 8, 4, 7, 2, 9]
</code>```

After the first partitioning, you have to make sure to apply quicksort to both the arrays to the left and to the right of the pivot. For example, after the first pivot (6) is placed in the correct position for the Khan example (what you labeled as the outside swap),

```<code>[5, 2, 3, 6, 12, 7, 14, 9, 10, 11]
 <--1-->  p  <--------2--------->
</code>```

you have to apply the same quicksort to both subarrays 1 and 2 in the diagram above. I suggest you try out the recursive implementation first, which will give you a good idea of the algorithm, then try to implement it iteratively.

Body:
For educational purposes I am trying to learn the quick sort algorithm. Instead of checking out an implementation on the web or trying to implement directly from the pseudocode on wikipedia, I am trying a "hard way" approach.

I watched this lecture from CS50 https://www.youtube.com/watch?v=aQiWF4E8flQ&t=305s in order to understand how the numbers move while being "quick sorted". My implementation, which I will show bellow, works perfectly for the example provided on the video. The example on the video of an initial unsorted array is this:

That's my code in Python 3:

len_seq = int(input())

print("len_seq",len_seq)

seq_in = list(map(int,(input()).split()))

print("seq_in",seq_in)

def my_quick_sort(seq):

    wall_index = 0

    pivot_corect_final_index_list = []

    while wall_index<len_seq:

        pivot = seq[-1]
        print("pivot",pivot)

        print("wall_index",wall_index)

        for i in range(wall_index,len_seq):
            print ("seq[i]",seq[i])
            if seq[i]<pivot:
                print("before inside swap,", seq)
                seq[wall_index],seq[i]=seq[i],seq[wall_index]
                print("after inside swap,", seq)
                wall_index = wall_index + 1
                print ("wall_index",wall_index)

        print("before outside swap,", seq)

        seq[wall_index],seq[-1]=seq[-1],seq[wall_index]
        print("after outside swap,", seq)

        pivot_corect_final_index = wall_index
        print ("pivot correct final index",pivot_corect_final_index)

        pivot_corect_final_index_list.append(pivot_corect_final_index)
        print ("pivot_corect_final_index_list",pivot_corect_final_index_list)

        wall_index = wall_index + 1
        print ("wall_index",wall_index)

    return seq

print(my_quick_sort(seq_in))

To use harvard's CS50 example in my code you need to input this:

9
6 5 1 3 8 4 7 9 2

The algorithm works fine and returns the correct output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Continuing my study, I tried to implement Khan Academy's example: https://www.khanacademy.org/computing/computer-science/algorithms/quick-sort/a/overview-of-quicksort

The unsorted list in this case is:

[9, 7, 5, 11, 12, 2, 14, 3, 10, 6]

You need to input the following in my code in order to run it:

10
9 7 5 11 12 2 14 3 10 6

Differently from the Harvard example, in this case my implementation does not work perfectly. It returns:

[5, 2, 3, 6, 7, 9, 10, 11, 12, 14]

As you see, all the numbers that I treated as pivots end in the correct position. However, some numbers behind the pivots are not right.

Reading khan academy's article it seems that my implementation is right on the partition step. However, it is not right on the conquer step. I am trying to avoid looking to a final solution. I am trying to improve what I have build so far. Not sure if this is the best method, but that's what I am trying right now.

How can I fix the conquer step? Is it necessary to introduce a recursive approach? How can I do that inside my iterative process going on?
And should that step be introduced after successfully treating each pivot?

Thanks for the patience of reading this long post.

Body:
Can't comment, not enough reputation.

In the first pass of your algorithm, you correctly place all elements smaller than the pivot to the left of the pivot. However, since your value of wall_index increases (e.g. from 0 to 1), you ignore the leftmost element with index 0 (it might not be in the correct position, so it should not be ignored).

In the Khan academy test case, the number 5 gets placed at the leftmost index in the first pass, and then gets ignored by subsequent passes, thus it gets stuck on the left. Similarly, trying this modification of the harvard example

9
6 5 1 3 8 4 7 2 9

yields

[6, 5, 1, 3, 8, 4, 7, 2, 9]

After the first partitioning, you have to make sure to apply quicksort to both the arrays to the left and to the right of the pivot. For example, after the first pivot (6) is placed in the correct position for the Khan example (what you labeled as the outside swap),

[5, 2, 3, 6, 12, 7, 14, 9, 10, 11]
 <--1-->  p  <--------2--------->

you have to apply the same quicksort to both subarrays 1 and 2 in the diagram above. I suggest you try out the recursive implementation first, which will give you a good idea of the algorithm, then try to implement it iteratively.


问:
tizen web app, launch another web application
I was wondering if anyone knows how to launch a web app from another web app at when something like a button press event. I've seen code written in C I think but I would like it in Javascript, unless someone knows a way to run c in html ???</p>

答:
You can do it using App Control API of Tizen Web App. Follow the example

//main.js

```<code>function onSuccess () {
    console.log(“App Launched”);}

function onError () {
    console.log(“Cannot Launch”);}

var appId=" com.samsung.clocksetting"; // app to be launched

tizen.application.launch(appId, onSuccess, onError);
</code>```

// config.xml

```<code><tizen:privilege name="http://tizen.org/privilege/application.launch"/>
</code>```

Body:
You can do it using App Control API of Tizen Web App. Follow the example

//main.js

function onSuccess () {
    console.log(“App Launched”);}

function onError () {
    console.log(“Cannot Launch”);}

var appId=" com.samsung.clocksetting"; // app to be launched

tizen.application.launch(appId, onSuccess, onError);

// config.xml

<tizen:privilege name="http://tizen.org/privilege/application.launch"/>


问:
PushSharp's notification to Apple generate temp RSA files on server
I'm having a problem with my WCF push notification service.
Every time it sends a push notification to apple, a new RSA is generated inside the "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys" folder.
I think that the problem causing this might be related to the Apple p12 Certificate.

Why does that happen? Is there any way to prevent the generating of those RSA?

I'm using PushSharp library and my code looks like this:

```<code>pushBroker = new PushBroker();
pushBroker.RegisterAppleService(
    new PushSharp.Apple.ApplePushChannelSettings(false, appleCert, p12Pass, false)
    , null);
</code>```

答:
I had the same problem and i found the solution
to prevent generate key every time you send new push notification,
the code should be like this. and it work perfect for me</p>

```<code> var cert = X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable;
 var certificate1 = new X509Certificate2(appleCert, p12CerPass,cert);
_broker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(certificate1, false));
</code>```

Body:
I'm having a problem with my WCF push notification service.
Every time it sends a push notification to apple, a new RSA is generated inside the "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys" folder.
I think that the problem causing this might be related to the Apple p12 Certificate.

Why does that happen? Is there any way to prevent the generating of those RSA?

I'm using PushSharp library and my code looks like this:

pushBroker = new PushBroker();
pushBroker.RegisterAppleService(
    new PushSharp.Apple.ApplePushChannelSettings(false, appleCert, p12Pass, false)
    , null);

Body:
I had the same problem and i found the solution
to prevent generate key every time you send new push notification,
the code should be like this. and it work perfect for me

 var cert = X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable;
 var certificate1 = new X509Certificate2(appleCert, p12CerPass,cert);
_broker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(certificate1, false));


问:
how to add Admob Ads in a class that extends ListActivity
i want to add java code of Admob Ads in OnCreateMethod. But my java class extends ListActivity.
Please tell me how to add admob ads in this class.

If i add the code in the class that extends ListActivity it crashes the App.

Please provide me a solution for this.

Thanks in Advance.

my MainActivity java code

```<code>public class MainActivity extends ListActivity
{
    List headlines;
    List links;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        new MyAsyncTask().execute();
    }

    class MyAsyncTask extends AsyncTask<Object,Void,ArrayAdapter>
    {
        @Override
        protected ArrayAdapter doInBackground(Object[] params)
        {
            headlines = new ArrayList();
            links = new ArrayList();
            try
            {
                URL url = new URL("http://feelthesport.blogspot.com/feeds/posts/default?alt=rss");
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                factory.setNamespaceAware(false);
                XmlPullParser xpp = factory.newPullParser();

                // We will get the XML from an input stream
                xpp.setInput(getInputStream(url), "UTF_8");
                boolean insideItem = false;

                // Returns the type of current event: START_TAG, END_TAG, etc..
                int eventType = xpp.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT)
                {
                    if (eventType == XmlPullParser.START_TAG)
                    {
                        if (xpp.getName().equalsIgnoreCase("item"))
                        {
                            insideItem = true;
                        }
                        else if (xpp.getName().equalsIgnoreCase("title"))
                        {
                            if (insideItem)
                                headlines.add(xpp.nextText()); //extract the headline
                        }
                        else if (xpp.getName().equalsIgnoreCase("link"))
                        {
                            if (insideItem)
                                links.add(xpp.nextText()); //extract the link of article
                        }
                    }
                    else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item"))
                    {
                        insideItem=false;
                    }
                    eventType = xpp.next(); //move to next element
                }

            }
            catch (MalformedURLException e)
            {
                e.printStackTrace();
            }
            catch (XmlPullParserException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return null;
        }
        protected void onPostExecute(ArrayAdapter adapter)
        {
            adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, headlines);
            setListAdapter(adapter);
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
        Uri uri = Uri.parse((links.get(position)).toString());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    public InputStream getInputStream(URL url)
    {
        try
        {
            return url.openConnection().getInputStream();
        }
        catch (IOException e)
        {
            return null;
        }
    }
}
</code>```

答:
I think so rather adding to ListActivity.
Add AppCompatActivity & make use of RecyclerView
Add Adapter for AdMob Create custom layout whatever you want this could be helpful even if you you want to add your item along with AdMob.
Once added CustomerAdapterClass, call setAdapter()

Done your view will get poopulated.
Thanks.

Body:
i want to add java code of Admob Ads in OnCreateMethod. But my java class extends ListActivity.
Please tell me how to add admob ads in this class.

If i add the code in the class that extends ListActivity it crashes the App.

Please provide me a solution for this.

Thanks in Advance.

my MainActivity java code

public class MainActivity extends ListActivity
{
    List headlines;
    List links;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        new MyAsyncTask().execute();
    }

    class MyAsyncTask extends AsyncTask<Object,Void,ArrayAdapter>
    {
        @Override
        protected ArrayAdapter doInBackground(Object[] params)
        {
            headlines = new ArrayList();
            links = new ArrayList();
            try
            {
                URL url = new URL("http://feelthesport.blogspot.com/feeds/posts/default?alt=rss");
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                factory.setNamespaceAware(false);
                XmlPullParser xpp = factory.newPullParser();

                // We will get the XML from an input stream
                xpp.setInput(getInputStream(url), "UTF_8");
                boolean insideItem = false;

                // Returns the type of current event: START_TAG, END_TAG, etc..
                int eventType = xpp.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT)
                {
                    if (eventType == XmlPullParser.START_TAG)
                    {
                        if (xpp.getName().equalsIgnoreCase("item"))
                        {
                            insideItem = true;
                        }
                        else if (xpp.getName().equalsIgnoreCase("title"))
                        {
                            if (insideItem)
                                headlines.add(xpp.nextText()); //extract the headline
                        }
                        else if (xpp.getName().equalsIgnoreCase("link"))
                        {
                            if (insideItem)
                                links.add(xpp.nextText()); //extract the link of article
                        }
                    }
                    else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item"))
                    {
                        insideItem=false;
                    }
                    eventType = xpp.next(); //move to next element
                }

            }
            catch (MalformedURLException e)
            {
                e.printStackTrace();
            }
            catch (XmlPullParserException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return null;
        }
        protected void onPostExecute(ArrayAdapter adapter)
        {
            adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, headlines);
            setListAdapter(adapter);
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
        Uri uri = Uri.parse((links.get(position)).toString());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    public InputStream getInputStream(URL url)
    {
        try
        {
            return url.openConnection().getInputStream();
        }
        catch (IOException e)
        {
            return null;
        }
    }
}


问:
Google Cloud Storage inconsistent responses
I have a bucket set up in Google Cloud Storage, with the "object default permissions" set to grant the "User" group "allUsers" with permission "Reader".

In the bucket there are a number of files, and I have a client checking if a particular file is present by trying to access it.  Most of the time we get a 404 response, but fairly often we see a 403 response for the first few tries.

The 403 response body is (with my own formatting and replacement of private info):

```<code><?xml version='1.0' encoding='UTF-8'?>
<Error>
    <Code>AccessDenied</Code>
    <Message>Access denied.</Message>
    <Details>Anonymous users does not have storage.objects.get access to object mybucket/myfile.gz.</Details>
</Error>
</code>```

So my question is why do I sometimes get a 403 and sometimes a 404 response when trying to open a file that doesn't exist?

I know that there will be changes from 29 May 2017, but they are not in effect yet, and so it appears that either something is wrong or Google have been randomly applying the new logic early.

答:
I have a definitive answer on this via an email from Google, so I'm giving the response for completeness.

It has been found out that there was a miscommunication between the Engineers. Originally, the changes were supposed to be scheduled on 5/22 but due to some internal delays, they decided to announce it on a later date which is 5/29. Due to this confusion, the Engineers rolled this feature out on the original date (5/22) instead of 5/29.

TL;DR: Google screwed up and rolled out breaking changes a week early.

Body:
I have a bucket set up in Google Cloud Storage, with the "object default permissions" set to grant the "User" group "allUsers" with permission "Reader".

In the bucket there are a number of files, and I have a client checking if a particular file is present by trying to access it.  Most of the time we get a 404 response, but fairly often we see a 403 response for the first few tries.

The 403 response body is (with my own formatting and replacement of private info):

<?xml version='1.0' encoding='UTF-8'?>
<Error>
    AccessDenied
    <Message>Access denied.</Message>
    Anonymous users does not have storage.objects.get access to object mybucket/myfile.gz.
</Error>

So my question is why do I sometimes get a 403 and sometimes a 404 response when trying to open a file that doesn't exist?

I know that there will be changes from 29 May 2017, but they are not in effect yet, and so it appears that either something is wrong or Google have been randomly applying the new logic early.


问:
Prevent Suggestion for Input Field in HTML in All browser
I have an HTML form Which Contains the Various Field.

Simply We all Know that every browser will show some suggestion for the input field.

Like an Email Input field. When you enter or click on that input it shows the previously entered email or any other values.
I have cleared and done all procedures for stopping that behavior.  But still, I get previously entered data in the input field. (as in shown in image)

So how do I remove that suggestion or previously entered data?
Or How do I prevent that automatic suggestion for the input field?

This is my HTML Sample Code for Input Field.

```<code><div class="form-group ">
    <div class="col-xs-12">
        <input class="form-control" type="email" name="email" id="login_email" required placeholder="User Email" data-parsley-type="email">
    </div>
</div>
</code>```

答:
You can set

```<code><input type="text" name="email" autocomplete="off" />
</code>```

And some browsers like Firefox 3.0.X may still show cached objects so you can set your <form> tag with autocomplete="off".

For more detailed answers, please visit

How do you disable browser Autocomplete on web form field / input tag?

Body:
I have an HTML form Which Contains the Various Field.

Simply We all Know that every browser will show some suggestion for the input field.

Like an Email Input field. When you enter or click on that input it shows the previously entered email or any other values.
I have cleared and done all procedures for stopping that behavior.  But still, I get previously entered data in the input field. (as in shown in image)

So how do I remove that suggestion or previously entered data?
Or How do I prevent that automatic suggestion for the input field?

This is my HTML Sample Code for Input Field.

        <input class="form-control" type="email" name="email" id="login_email" required placeholder="User Email" data-parsley-type="email">

Body:
You can set

<input type="text" name="email" autocomplete="off" />

And some browsers like Firefox 3.0.X may still show cached objects so you can set your <form> tag with autocomplete="off".

For more detailed answers, please visit

How do you disable browser Autocomplete on web form field / input tag?


问:
Spring MVC jackson message converter date format is not working, always return long timestamp
I have found this two:

Jackson Object Mapper in spring MVC not working

why is the Object Mapper date fromat not used by message converters for date transform?

but none are the solution for me.

Spring MVC xml:

```<code><mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
          <property name="objectMapper">
             <bean class="com.xxx.model.MyJacksonObjectMapper">

             </bean>
          </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
</code>```

MyJacksonObjectMapper:

```<code>public class MyJacksonObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = -3282890427623599460L;

    public MyJacksonObjectMapper() {
        super();
        disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    }

}
</code>```

Not matter I change register-defaults to true or false, it is still not working, my controller always serialize the object's date value in timestamp (long) format.

My POJO object is not appended with any annotation, it is plain POJO and I cannot annotate it with any annotation (not my class), I believe there must be config to allow serialize default object's date in desired format, but it is not working, please help.

Dependency:

```<code><dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.3</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.2.5.RELEASE</version>
</dependency>
</code>```

答:
OK this answer https://stackoverflow.com/a/7714503/1542363 indirectly saved me, although I don't know why.

It mentioned this should be removed:

```<code><mvc:annotation-driven/>
</code>```

My issue is similar to this, I have duplicated annotation block in Spring config XML:

so I change my config from:

```<code><mvc:annotation-driven>
  <mvc:argument-resolvers>
    <bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
  </mvc:argument-resolvers>
</mvc:annotation-driven>

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
          <property name="objectMapper">
             <bean class="com.xxx.model.MyJacksonObjectMapper">

             </bean>
          </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
</code>```

to:

```<code><mvc:annotation-driven>
    <mvc:argument-resolvers>
        <bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
    </mvc:argument-resolvers>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
          <property name="objectMapper">
             <bean class="com.xxx.model.MyJacksonObjectMapper"></bean>
          </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
</code>```

then it works, not sure what is the reason.

Body:
I have found this two:

Jackson Object Mapper in spring MVC not working

why is the Object Mapper date fromat not used by message converters for date transform?

but none are the solution for me.

Spring MVC xml:

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
          <property name="objectMapper">
             <bean class="com.xxx.model.MyJacksonObjectMapper">

             </bean>
          </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

MyJacksonObjectMapper:

public class MyJacksonObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = -3282890427623599460L;

    public MyJacksonObjectMapper() {
        super();
        disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    }

}

Not matter I change register-defaults to true or false, it is still not working, my controller always serialize the object's date value in timestamp (long) format.

My POJO object is not appended with any annotation, it is plain POJO and I cannot annotate it with any annotation (not my class), I believe there must be config to allow serialize default object's date in desired format, but it is not working, please help.

Dependency:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.3</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.2.5.RELEASE</version>
</dependency>

Body:
OK this answer https://stackoverflow.com/a/7714503/1542363 indirectly saved me, although I don't know why.

It mentioned this should be removed:

<mvc:annotation-driven/>

My issue is similar to this, I have duplicated annotation block in Spring config XML:

so I change my config from:

<mvc:annotation-driven>
  <mvc:argument-resolvers>
    <bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
  </mvc:argument-resolvers>
</mvc:annotation-driven>

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
          <property name="objectMapper">
             <bean class="com.xxx.model.MyJacksonObjectMapper">

             </bean>
          </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

to:

<mvc:annotation-driven>
    <mvc:argument-resolvers>
        <bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
    </mvc:argument-resolvers>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
          <property name="objectMapper">
             <bean class="com.xxx.model.MyJacksonObjectMapper"></bean>
          </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

then it works, not sure what is the reason.


问:
Save data randomly generated into label
I am fairly new to coding and was wondering if it was possible to save data I have randomly generated into a label. I can randomly generate the data and input it into the label but I am having difficulties saving the previous data from the label to an array. Is it possible to do this? And how would it be done?

Essentially I want the user to be able to go back to the previous text in the label if they press a button

Thank you for any help.

code:

This is how I am generating the random variable from an array which contains quotes

```<code>//right hand button tapped

@IBAction func RHSButton(_ sender: Any) {

// randomises variable to display
    var randomQuote: String {
        let randomNumber = Int(arc4random_uniform(UInt32(myQuotes.count)))
        return myQuotes[randomNumber]}

   quotesLabel.text = randomQuote

}
</code>```

I want to be able to store the data into an array called:

```<code>var randomGeneratedQuotes : [String] = []
</code>```

But I am not quite sure how

答:
hi seems like u want undo feature.

take one more array and add selected randomNumber

on clicking button display last index of array and remove it from array.

Title: Save data randomly generated into label

Body:
I am fairly new to coding and was wondering if it was possible to save data I have randomly generated into a label. I can randomly generate the data and input it into the label but I am having difficulties saving the previous data from the label to an array. Is it possible to do this? And how would it be done?

Essentially I want the user to be able to go back to the previous text in the label if they press a button

Thank you for any help.

code:

This is how I am generating the random variable from an array which contains quotes

//right hand button tapped

@IBAction func RHSButton(_ sender: Any) {

// randomises variable to display
    var randomQuote: String {
        let randomNumber = Int(arc4random_uniform(UInt32(myQuotes.count)))
        return myQuotes[randomNumber]}

   quotesLabel.text = randomQuote

}

I want to be able to store the data into an array called:

var randomGeneratedQuotes : [String] = []

But I am not quite sure how


问:
Calendar Not return correct .weekday swift 3.1
I'm trying to get weekday of given Date Object. But it always returns +1 value.
example : If I gave a date as : 2017-06-01 18:30:00 +0000

it returns weekday 6 -> Friday
It should bee weekday 5 -> Thursday

My code :

```<code>let calendar = Calendar.current
        let day: Int = calendar.component(.weekday, from: self.month!)
        print ("---------")
        print(self.month!)
        print (day)
        switch day {
        case 1:print("Sunday")
        case 2:print("Monday")
        case 3:print("Tuesday")
        case 4:print("Wednesday")
        case 5:print("Thursday")
        case 6:print("Friday")
        case 7:print("Saturday")
        default:
            break
        }
</code>```

Output on the Console : (I have given 2 dates both of them ar wrong)

```<code>---------
2016-01-01 18:30:00 +0000
7
Saturday
---------
2017-06-01 18:30:00 +0000
6
Friday
</code>```

Where I did the mistake...
Thank you.

答:
From my point of view create extension to the Date it is more clear to use:

```<code>extension Date {
    func weekday() -> Int? {
        return Calendar.current.dateComponents([.weekday], from: self).weekday
    }
}

print(Date().weekday()!)
</code>```

Example:

```<code>let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
let date = dateFormatter.date(from: "2017-06-01 18:30:00 +0000")

print(date?.weekday()!) //5 In Ukraine
</code>```

Body:
I'm trying to get weekday of given Date Object. But it always returns +1 value.
example : If I gave a date as : 2017-06-01 18:30:00 +0000

it returns weekday 6 -> Friday
It should bee weekday 5 -> Thursday

My code :

let calendar = Calendar.current
        let day: Int = calendar.component(.weekday, from: self.month!)
        print ("---------")
        print(self.month!)
        print (day)
        switch day {
        case 1:print("Sunday")
        case 2:print("Monday")
        case 3:print("Tuesday")
        case 4:print("Wednesday")
        case 5:print("Thursday")
        case 6:print("Friday")
        case 7:print("Saturday")
        default:
            break
        }

Output on the Console : (I have given 2 dates both of them ar wrong)

---------
2016-01-01 18:30:00 +0000
7
Saturday
---------
2017-06-01 18:30:00 +0000
6
Friday

Where I did the mistake...
Thank you.

Body:
From my point of view create extension to the Date it is more clear to use:

extension Date {
    func weekday() -> Int? {
        return Calendar.current.dateComponents([.weekday], from: self).weekday
    }
}

print(Date().weekday()!)

Example:

let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
let date = dateFormatter.date(from: "2017-06-01 18:30:00 +0000")

print(date?.weekday()!) //5 In Ukraine


问:
How to display image into picture box using image path in database
How can I retrieve image into picture box using image path in database? Before this I retrieve from shared folder but its make my system slow when loading image. Then I changes the method wheres I want to retrieve image into picture box using image path that stored in MSSQL database. Hopefully it not slow down my system. Anyone please help me. Here is my code but not work to retrieve image.</p>

```<code>private void textBoxEmplNo_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            if (textBoxEmplNo.Text != "")
            {

                string selectSql = "select a.name, a.empno, a.workno, a.icnum, a.passport, a.deptno, a.section, a.designation, b.path from m_employee a inner join m_emp_photo b on b.empno=a.empno where a.empno= @empno";

                SqlCommand cmd = new SqlCommand(selectSql, con);

                cmd.Parameters.AddWithValue("@empno", textBoxEmplNo.Text);

                bool isDataFound = false;

                try
                {

                    con.Open();

                    using (SqlDataReader read = cmd.ExecuteReader())
                    {
                        while (read.Read())
                        {
                            isDataFound = true;

                            textBoxWorkNo.Text = (read["workno"].ToString());
                            textBoxName.Text = (read["name"].ToString());
                            textBoxICPass.Text = (read["icnum"].ToString());
                            textBoxPassport.Text = (read["passport"].ToString());
                            textBoxDept.Text = (read["deptno"].ToString());
                            textBoxSection.Text = (read["section"].ToString());
                            textBoxDesignation.Text = (read["designation"].ToString());

                            pictureBox1.Image = Image.FromFile("@path");
                        }
                    }
</code>```

答:
pictureBox1.Image = Image.FromFile("" + read["path"].ToString());</p>

```<code>            pictureBox1.SizeMode=System.Windows.Forms.PictureBoxSizeMode.StretchImage;
</code>```

Body:
How can I retrieve image into picture box using image path in database? Before this I retrieve from shared folder but its make my system slow when loading image. Then I changes the method wheres I want to retrieve image into picture box using image path that stored in MSSQL database. Hopefully it not slow down my system. Anyone please help me. Here is my code but not work to retrieve image.

private void textBoxEmplNo_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            if (textBoxEmplNo.Text != "")
            {

                string selectSql = "select a.name, a.empno, a.workno, a.icnum, a.passport, a.deptno, a.section, a.designation, b.path from m_employee a inner join m_emp_photo b on b.empno=a.empno where a.empno= @empno";

                SqlCommand cmd = new SqlCommand(selectSql, con);

                cmd.Parameters.AddWithValue("@empno", textBoxEmplNo.Text);

                bool isDataFound = false;

                try
                {

                    con.Open();

                    using (SqlDataReader read = cmd.ExecuteReader())
                    {
                        while (read.Read())
                        {
                            isDataFound = true;

                            textBoxWorkNo.Text = (read["workno"].ToString());
                            textBoxName.Text = (read["name"].ToString());
                            textBoxICPass.Text = (read["icnum"].ToString());
                            textBoxPassport.Text = (read["passport"].ToString());
                            textBoxDept.Text = (read["deptno"].ToString());
                            textBoxSection.Text = (read["section"].ToString());
                            textBoxDesignation.Text = (read["designation"].ToString());

                            pictureBox1.Image = Image.FromFile("@path");
                        }
                    }

Body:
pictureBox1.Image = Image.FromFile("" + read["path"].ToString());

            pictureBox1.SizeMode=System.Windows.Forms.PictureBoxSizeMode.StretchImage;


问:
jQuery update input field multiple times
I'm currently using the following to update an input field without reloading the entire page:

```<code><input type="number" name="voorraad" id="5258" class="voorraad 5258" value="129">

<script>
(function($) {
jQuery(document).ready(function(){
jQuery('.voorraad').blur(function(){

var nieuwevoorraad = jQuery(this).val();
var productid = jQuery(this).attr('id');
jQuery( "." + productid ).replaceWith( '<span class="' + productid + '_glyphspan"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Bijwerken...</span>' );
    $.post("<?php echo site_url();?>/updateStock.php",{
        productid : productid,
        nieuwevoorraad : nieuwevoorraad,

     },

  function(result){
  jQuery( "." + productid + "_glyphspan" ).replaceWith( '<input type="number" name="voorraad" id="'+productid+'" class="voorraad '+productid+'" value="'+nieuwevoorraad+'"/>' );
        });
});
});
})(jQuery);
</script>
</code>```

However, after the second replace, the input field no longer works, and I need to refresh the entire page. What I am looking for, is that the script runs on each change I make to the input field. Any ideas?

答:
You have to replace

```<code>jQuery('.voorraad').blur(function(){
</code>```

with

```<code>jQuery(document).on("blur",".voorraad",function(){
</code>```

because you dynamically replace this element.

Body:
I'm currently using the following to update an input field without reloading the entire page:

<input type="number" name="voorraad" id="5258" class="voorraad 5258" value="129">

However, after the second replace, the input field no longer works, and I need to refresh the entire page. What I am looking for, is that the script runs on each change I make to the input field. Any ideas?

Body:
You have to replace

jQuery('.voorraad').blur(function(){

with

jQuery(document).on("blur",".voorraad",function(){

because you dynamically replace this element.


问:
Linq to join tables on XElement.Name = XAttribute("n")
This is driving me bat-guano crazy!
Client data file:

```<code><rows>
    <row>
        <CustomerID>ABC123</CustomerID>
        <PrdcrCd>10</PrdcrCd>
        <StrAdr>123 Main St., NW</StrAdr>
        <City>Anytown</City>
        etc.
    </row>
<rows>
</code>```

Map file for transforming client data into acceptable input:

```<code><SourceEntries>
    <map>
        <Field n='CustomerID' m='201' />
        <Field n='StrAdr' m='315' />
        <Field n='City' m='316' />
        <Field n='PrdrCd' m='442' />
        etc.
    </map>
</SourceEntries>
</code>```

Finally, the template for acceptable input:

```<code><template>
    <Field n='ClientId' id='201' />
    <Field n='Street Address' id='315' />
    <Field n='City' id='316' />
    <Field n='ProducerCode' id='442' />
    etc.
</template>
</code>```

So, from the client file XElement name, match the Source Entries attribute value 'n', and get the Source Entires map reference m. Then, use m to match a template element attribute i, retrieve the template name attribute 'n' and create a new XElement tree using that name.

Since I'm a noob at Linq, and not particularly adept at XML, I thought I'd start out slowly. Like this:

```<code>var results = from t1 in clientXm.Elements("row").Descendants()
      join t2 in sourceEntries.Elements("Field") on t1.Name equals t2.Attributes("n") into xRef
      select new
          {
              (string)xRef.Attributes("n"),
              (string)xRef.Attributes("m")
          };
</code>```

First error, in the join clause at "on t1.Name.LocalName equals" is that Argument type 'string' is not assignable to parameter type 'TKey'. Then, in the select clause, for the two items I'm interested in, I get "Anonymous type projection initializer should be simple name or member access expression." Oh, and of course, the XML file structures are specification requirements, so I can't change any of them.

At this point, I'm so freaking confused I don't know whether the world is upside-down, or I'm standing on my head. Can I please buy a clue... or at least a vowel? Any and all help greatly appreciated.

EDIT

Using LinqPad, I tried this statement:

```<code>XElement _clientXml = XElement.Load(@"client.xml");
XElement _sourceEntries = XElement.Load(@"Client_Map.xml");

foreach (XElement clientData in _clientXml.Descendants("row").Descendants()){
    IEnumerable<XElement> mapRefs =
        from mapData in _sourceEntries.Descendants("Field")
        where clientData.Name.LocalName == (string) mapData.Attribute("n")
        select mapData;
    foreach (XElement item in mapRefs){
        Console.WriteLine(item.Attribute("m"));
    }
}
</code>```

In LinqPad, this produced a list of "m" values -- just what I'm trying to get at this baby step. BUT the exact same code in VS gives me nothing. When I debug, mapRefs is an empty set when I get to the second foreach.

Does this make any sense at all?

Thanks
Randy

答:
Well it's easy to fix the compiler errors:

```<code>var results = from t1 in clientXm.Elements("row").Descendants()
              join t2 in sourceEntries.Elements("Field")
              on t1.Name.LocalName equals (string) t2.Attribute("n") into xRef
              select new
              {
                  N = (string)xRef.Attributes("n"),
                  M = (string)xRef.Attributes("m")
              };
</code>```

However, I'm not sure how you're intending the cast from IEnumerable<XAttribute> to string to work in the projection...

I suspect you don't want a group join (which is what you get with join...into. But I don't understand how your data sample works, so it's hard to give you the correct code. Where should ClientId come from, for example? You've only got it in your sample output... assuming that is your sample output, of course.

Basically, if you could simplify your sample data into two inputs and an output, and explain how the output is derived, that would make life easier... at the moment it's not clear.

Body:
This is driving me bat-guano crazy!
Client data file:

<rows>
    <row>
        <CustomerID>ABC123</CustomerID>
        <PrdcrCd>10</PrdcrCd>
        <StrAdr>123 Main St., NW</StrAdr>
        <City>Anytown</City>
        etc.
    </row>
<rows>

Map file for transforming client data into acceptable input:

<SourceEntries>
    <map>
        <Field n='CustomerID' m='201' />
        <Field n='StrAdr' m='315' />
        <Field n='City' m='316' />
        <Field n='PrdrCd' m='442' />
        etc.
    </map>
</SourceEntries>

Finally, the template for acceptable input:

<template>
    <Field n='ClientId' id='201' />
    <Field n='Street Address' id='315' />
    <Field n='City' id='316' />
    <Field n='ProducerCode' id='442' />
    etc.
</template>

So, from the client file XElement name, match the Source Entries attribute value 'n', and get the Source Entires map reference m. Then, use m to match a template element attribute i, retrieve the template name attribute 'n' and create a new XElement tree using that name.

Since I'm a noob at Linq, and not particularly adept at XML, I thought I'd start out slowly. Like this:

var results = from t1 in clientXm.Elements("row").Descendants()
      join t2 in sourceEntries.Elements("Field") on t1.Name equals t2.Attributes("n") into xRef
      select new
          {
              (string)xRef.Attributes("n"),
              (string)xRef.Attributes("m")
          };

First error, in the join clause at "on t1.Name.LocalName equals" is that Argument type 'string' is not assignable to parameter type 'TKey'. Then, in the select clause, for the two items I'm interested in, I get "Anonymous type projection initializer should be simple name or member access expression." Oh, and of course, the XML file structures are specification requirements, so I can't change any of them.

At this point, I'm so freaking confused I don't know whether the world is upside-down, or I'm standing on my head. Can I please buy a clue... or at least a vowel? Any and all help greatly appreciated.

EDIT

Using LinqPad, I tried this statement:

XElement _clientXml = XElement.Load(@"client.xml");
XElement _sourceEntries = XElement.Load(@"Client_Map.xml");

foreach (XElement clientData in _clientXml.Descendants("row").Descendants()){
    IEnumerable<XElement> mapRefs =
        from mapData in _sourceEntries.Descendants("Field")
        where clientData.Name.LocalName == (string) mapData.Attribute("n")
        select mapData;
    foreach (XElement item in mapRefs){
        Console.WriteLine(item.Attribute("m"));
    }
}

In LinqPad, this produced a list of "m" values -- just what I'm trying to get at this baby step. BUT the exact same code in VS gives me nothing. When I debug, mapRefs is an empty set when I get to the second foreach.

Does this make any sense at all?

Thanks
Randy

Body:
Well it's easy to fix the compiler errors:

var results = from t1 in clientXm.Elements("row").Descendants()
              join t2 in sourceEntries.Elements("Field")
              on t1.Name.LocalName equals (string) t2.Attribute("n") into xRef
              select new
              {
                  N = (string)xRef.Attributes("n"),
                  M = (string)xRef.Attributes("m")
              };

However, I'm not sure how you're intending the cast from IEnumerable<XAttribute> to string to work in the projection...

I suspect you don't want a group join (which is what you get with join...into. But I don't understand how your data sample works, so it's hard to give you the correct code. Where should ClientId come from, for example? You've only got it in your sample output... assuming that is your sample output, of course.

Basically, if you could simplify your sample data into two inputs and an output, and explain how the output is derived, that would make life easier... at the moment it's not clear.


问:
How to centrally align a float: left ul/li navigation menu with css?
So I have the following CSS in place to display a horizontal navigation bar using:

```<code>.navigation ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.navigation li {
  float: left;
  margin: 0 1.15em;
  /*    margin: 0 auto;*/
}

.navigation {
  /*    width: auto;*/
  /*    margin: 0 auto;*/
  text-align: center;
}
</code>```

My question is: how do I align the navigation bar centrally above the title?

答:
```<code>ul {
 display: inline-block;
 text-align: center;
}
</code>```

Body:
So I have the following CSS in place to display a horizontal navigation bar using:

.navigation ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.navigation li {
  float: left;
  margin: 0 1.15em;
  /*    margin: 0 auto;*/
}

.navigation {
  /*    width: auto;*/
  /*    margin: 0 auto;*/
  text-align: center;
}

My question is: how do I align the navigation bar centrally above the title?


问:
Substring a String depending on int
I wanted to substring a String depending on int that I will passed on the method. I used nested loop for this. But everytime it loops I wanted to substring only from last substring to int the I passed in the method and get also the last string. How can I achieve this?

```<code>private static void input(String s, int I)
{
    List list = new ArrayList();

    for(int a = 0; a < s.length(); a++)
    {
        for(int position = 0; position < s.length(); position++)
        {
            if(position + a + I <= s.length())
            {
                list.add(s.substring(position, position + a + I));
            }
        }
    }

}

input("abaca", 2);
</code>```

Expected output: "ab", "ac", "a"

答:
You don't need nested loops. Just iterate over the String once, and add an I character substring in each iteration.

Note that a is the starting index of the current substring, and it therefore incremented by I in each iteration.

The last substring may have a shorter length. If a + I > s.length(), the last index of the last substring will be s.length() - 1 instead of a + I - 1.

```<code>for(int a = 0; a < s.length(); a+=I) {
    list.add(s.substring(a, Math.min(a + I, s.length())));
}
</code>```

This produces

```<code>[ab, ac, a]
</code>```

for input("abaca", 2).

Title: Substring a String depending on int

Body:
I wanted to substring a String depending on int that I will passed on the method. I used nested loop for this. But everytime it loops I wanted to substring only from last substring to int the I passed in the method and get also the last string. How can I achieve this?

private static void input(String s, int I)
{
    List list = new ArrayList();

    for(int a = 0; a < s.length(); a++)
    {
        for(int position = 0; position < s.length(); position++)
        {
            if(position + a + I <= s.length())
            {
                list.add(s.substring(position, position + a + I));
            }
        }
    }

}

input("abaca", 2);

Expected output: "ab", "ac", "a"

Body:
You don't need nested loops. Just iterate over the String once, and add an I character substring in each iteration.

Note that a is the starting index of the current substring, and it therefore incremented by I in each iteration.

The last substring may have a shorter length. If a + I > s.length(), the last index of the last substring will be s.length() - 1 instead of a + I - 1.

for(int a = 0; a < s.length(); a+=I) {
    list.add(s.substring(a, Math.min(a + I, s.length())));
}

This produces

[ab, ac, a]

for input("abaca", 2).


问:
Different menu toolbar in fragment with BottonNavigationView
I have a layout with bottonNavigationView and fragments. How can I have different toolbar menus for each fragment? I've already tried several things.

In a fragment, I hace used.

```<code>((AppCompatActivity) getActivity()).getSupportActionBar()
</code>```

This is the layout of a fragment

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.cspm.ventas6.cspm.v_fragments.f_clientes"
    android:focusable="false">

    <LinearLayout
        android:id="@+id/con_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:descendantFocusability="blocksDescendants"
        android:focusable="false">

  <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

        <!-- Toolbar is the actual app bar with text and the action items -->
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways" />
    </android.support.design.widget.AppBarLayout>

        <ListView
            android:id="@+id/client_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:divider="@null" />
    </LinearLayout>
</FrameLayout>
</code>```

答:
In your fragment, add following two methods.

```<code>@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // tells the fragment that fragment will use toolbar's options menu
    setHasOptionsMenu(true);
}

/**
* this method is called when fragment prepares options menu,
* simply, inflate your menu and call super
*/
@Override
public void onPrepareOptionsMenu(Menu menu) {
    getActivity().getMenuInflater().inflate(R.menu.menu_res_id, menu);
    super.onPrepareOptionsMenu(menu);
}
</code>```

Change menu_res_id with your menu resource.

And, if you only want to remove an item from current menu, then replace line

```<code>getActivity().getMenuInflater().inflate(R.menu.menu_res_id, menu);
</code>```

with

```<code>menu.findItem(R.id.action_search).setVisible(false);
</code>```

Body:
I have a layout with bottonNavigationView and fragments. How can I have different toolbar menus for each fragment? I've already tried several things.

In a fragment, I hace used.

((AppCompatActivity) getActivity()).getSupportActionBar()

This is the layout of a fragment

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.cspm.ventas6.cspm.v_fragments.f_clientes"
    android:focusable="false">

    <LinearLayout
        android:id="@+id/con_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:descendantFocusability="blocksDescendants"
        android:focusable="false">

  <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways" />
    </android.support.design.widget.AppBarLayout>

        <ListView
            android:id="@+id/client_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:divider="@null" />
    </LinearLayout>
</FrameLayout>

Body:
In your fragment, add following two methods.

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // tells the fragment that fragment will use toolbar's options menu
    setHasOptionsMenu(true);
}

/**
* this method is called when fragment prepares options menu,
* simply, inflate your menu and call super
*/
@Override
public void onPrepareOptionsMenu(Menu menu) {
    getActivity().getMenuInflater().inflate(R.menu.menu_res_id, menu);
    super.onPrepareOptionsMenu(menu);
}

Change menu_res_id with your menu resource.

And, if you only want to remove an item from current menu, then replace line

getActivity().getMenuInflater().inflate(R.menu.menu_res_id, menu);

with

menu.findItem(R.id.action_search).setVisible(false);


问:
How to check the text box value that exist in the database after submit the form
I have this HTML Code in a form, I would like to check whether this value that user input is already exist in the database or not.

```<code><tr height="50">
    <td valign="top"><label for="CINumber"><span style="color:red">*</span>CI Name:</label></td>
     <td><input type="text" id="CINumber" name="CINumber"></td>
</tr>
</code>```

I have this ``JavaScript function for sumbmit the form values:

```<code>function submit(){
    var cNumber = document.getElementById("CINumber").value;
     //many form value within this function but I showed this value only cause this value need to check when click submit button.
    $.ajax({
        url: 'PHPMethodCalls_AL.php',
        type: 'post',
        data: {'action':'AddNewCI', 'cNumber' : cNumber },
        success: function(data,status) {
            //alert(data);
            if(status == "success"){
                alert("CI Name can be assigned");
                alert("Successfully Register New CI Record.");
            } else {
                alert("CI Name is already present!");
                return ;
            }
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
}
</code>```

And I call the PHPMethod Call in the 'PHPMethodCalls_AL.php' url..

```<code>if($_POST['action'] == "AddNewCI"){
    $cNumber = $_POST['cNumber'];
    $newCI = AddNewCI($cNumber);
    echo json_encode($newCI );
}
</code>```

After that I call the PHP function that connect with the database.

```<code>function AddNewCI($cNumber){
    global $DB;
    if(!empty($cNumber)){
        $namequery="SELECT Name from Item where Name='$cNumber'";
        $namecheck=mysql_query($namequery);
        $row=mysql_num_rows($namecheck);

        if($row==0){
            echo "success";
            $strSql1 ="INSERT INTO Item (Name)VALUES('$cNumber')";
            $res1 = $DB->Query($strSql1, false, $err_mess.__LINE__);
        }
        else {
            echo "!success";
        }
    }
}
</code>```

After click submit, I only got the (status == "success") then pop up 2 alert box  even the data is already exist in the database. However, the duplicate value don't save in the database cause I made the UNIQUE for this fields. Please suggest me how should I do to get the the right alert box if the data was exist, show "Alredy exist" if not " show the success alert box"...

答:
try this one less code and working well

      here no need to display error message if you use jquery validation you can simply use "render"   and render function displayed error message like required in jquery

         // When the browser is ready...
        $(function() {
        // Setup form validation on the #register-form element
        $("#addfrm").validate({

```<code>   // Specify the validation rules
    rules: {
      CINumber: {
            required: true,
            remote: {
            url: "PHPMethodCalls_AL.php",
            type: "post",
            data: {
              CINumber: function() {
                return $( "#CINumber" ).val();
              }
            }
          }
        }
    },

    // Specify the validation error messages
    messages: {
        CINumber: {
            required: "Please enter your CINumber",
            remote:"Entered CINumber already exists please enter another one"
       }
    },

    submitHandler: function(form) {
        form.submit();
    }
});
});
</script>

 PHPMethodCalls_AL.php
   this file return true when cinumber not exits on database and when it`s return false that means cinumber already exits on database

<?php
   //add database configuration
   $CINumber=$_POST['CINumber'];
   $query="SELECT * FROM `table_name` where `CINumber`=$CINumber";
   $result=mysql_query($query);
   $number_of_rows = mysql_num_rows($result);
   if($number_of_rows){
      echo "false";
   }else{
     echo "true";
   }
   die();
   ?>
</code>```

Body:
I have this HTML Code in a form, I would like to check whether this value that user input is already exist in the database or not.

    *CI Name:
     <input type="text" id="CINumber" name="CINumber">

I have this ``JavaScript function for sumbmit the form values:

function submit(){
    var cNumber = document.getElementById("CINumber").value;
     //many form value within this function but I showed this value only cause this value need to check when click submit button.
    $.ajax({
        url: 'PHPMethodCalls_AL.php',
        type: 'post',
        data: {'action':'AddNewCI', 'cNumber' : cNumber },
        success: function(data,status) {
            //alert(data);
            if(status == "success"){
                alert("CI Name can be assigned");
                alert("Successfully Register New CI Record.");
            } else {
                alert("CI Name is already present!");
                return ;
            }
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
}

And I call the PHPMethod Call in the 'PHPMethodCalls_AL.php' url..

if($_POST['action'] == "AddNewCI"){
    $cNumber = $_POST['cNumber'];
    $newCI = AddNewCI($cNumber);
    echo json_encode($newCI );
}

After that I call the PHP function that connect with the database.

function AddNewCI($cNumber){
    global $DB;
    if(!empty($cNumber)){
        $namequery="SELECT Name from Item where Name='$cNumber'";
        $namecheck=mysql_query($namequery);
        $row=mysql_num_rows($namecheck);

        if($row==0){
            echo "success";
            $strSql1 ="INSERT INTO Item (Name)VALUES('$cNumber')";
            $res1 = $DB->Query($strSql1, false, $err_mess.__LINE__);
        }
        else {
            echo "!success";
        }
    }
}

After click submit, I only got the (status == "success") then pop up 2 alert box  even the data is already exist in the database. However, the duplicate value don't save in the database cause I made the UNIQUE for this fields. Please suggest me how should I do to get the the right alert box if the data was exist, show "Alredy exist" if not " show the success alert box"...

Body:
try this one less code and working well

      here no need to display error message if you use jquery validation you can simply use "render"   and render function displayed error message like required in jquery

         // When the browser is ready...
        $(function() {
        // Setup form validation on the #register-form element
        $("#addfrm").validate({

   // Specify the validation rules
    rules: {
      CINumber: {
            required: true,
            remote: {
            url: "PHPMethodCalls_AL.php",
            type: "post",
            data: {
              CINumber: function() {
                return $( "#CINumber" ).val();
              }
            }
          }
        }
    },

    // Specify the validation error messages
    messages: {
        CINumber: {
            required: "Please enter your CINumber",
            remote:"Entered CINumber already exists please enter another one"
       }
    },

    submitHandler: function(form) {
        form.submit();
    }
});
});
</script>

 PHPMethodCalls_AL.php
   this file return true when cinumber not exits on database and when it`s return false that means cinumber already exits on database

<?php
   //add database configuration
   $CINumber=$_POST['CINumber'];
   $query="SELECT * FROM `table_name` where `CINumber`=$CINumber";
   $result=mysql_query($query);
   $number_of_rows = mysql_num_rows($result);
   if($number_of_rows){
      echo "false";
   }else{
     echo "true";
   }
   die();
   ?>


问:
Attachment Missing python 2.7

Attachment is missing in this script

I am trying to send an attachment using python script, but i don't receive the attachment,its missing,let me know how to get the attachment which is missing now and whats the error in this code

```<code>import smtplib
import base64

filename = "D:\python/Files_List.txt"

fo = open("Files_List.txt", "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)  # base64

sender = 'rom@domain.com'
reciever = 'to@domain.com'

marker = "AUNIQUEMARKe"

body ="""
This is a Attachment Mail
"""
part1 = """From:from<from@domain.com>
To:to<to@domain.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)

part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,marker)

part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, reciever, message)
   print "Successfully sent email"
except Exception:
   print "Error: unable to send email"
</code>```

答: You're reading the file to be attached in binary mode, so that your encodedcontent is of type bytes (that's OK). Then you format it without converting to a string. As a result, your message contains b'....'  (that's not OK).

Title: Attachment Missing python 2.7

Body:
Attachment is missing in this script

I am trying to send an attachment using python script, but i don't receive the attachment,its missing,let me know how to get the attachment which is missing now and whats the error in this code

import smtplib
import base64

filename = "D:\python/Files_List.txt"

fo = open("Files_List.txt", "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)  # base64

sender = 'rom@domain.com'
reciever = 'to@domain.com'

marker = "AUNIQUEMARKe"

body ="""
This is a Attachment Mail
"""
part1 = """From:from<from@domain.com>
To:to<to@domain.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)

part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,marker)

part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, reciever, message)
   print "Successfully sent email"
except Exception:
   print "Error: unable to send email"